产品介绍

Call an Agent with the Python SDK

Use DataAgent from a Python process. Configure a usable model with the configuration quick reference. The SDK reads config.yaml and .env from DataAgent Home by default. Use LaunchOptions(config=..., env_file=...) to choose them separately. See environment precedence.

See the Python SDK reference for common methods, session parameters, and return values.

Call an agent

Start with a product configuration that has a model and no MCP connections. Save the example as example.py. Run uv run python example.py in a source checkout or python example.py in an environment with DataAgent installed.

import asyncio

from dataagent import LaunchOptions, create_agent, prepare_runtime


async def main():
    runtime = prepare_runtime(LaunchOptions())
    async with create_agent(runtime) as agent:
        result = await agent.ainvoke(
            {"messages": [("user", "Explain what you can do in three sentences.")]},
            config={"configurable": {"thread_id": "sdk-demo"}},
        )
        print(result["messages"][-1].content)


asyncio.run(main())

The script should print one model reply and exit. For synchronous calls, use with create_agent(runtime) and agent.invoke(...) in a regular function. prepare_runtime loads configuration. Use LaunchOptions(init_home=True) to initialize missing Home templates. If your selected configuration enables MCP, import load_mcp_tools from dataagent, call mcp_tools = await load_mcp_tools(runtime) and pass mcp_tools=mcp_tools to create_agent. See MCP integration.

Exiting async with closes any semantic client created by the Agent.

To see a root agent delegate to nl2sql, enable and configure that plugin, leave dataagent.entry unset, and ask a question about the configured database.

Continue a conversation

thread_id selects the session. The SQLite checkpointer saves its history. The server uses AsyncSqliteSaver at <Home>/runtime/checkpoints.sqlite. An embedded application can use the same saver and file layout and manages the connection itself.

Save the script as conversation.py. Before running it, point DATAAGENT_HOME to an SDK-only Home with a configured model.

import argparse
import asyncio

from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver

from dataagent import create_agent, prepare_runtime


async def main(message: str) -> None:
    runtime = prepare_runtime()
    state_dir = runtime.paths.state_dir
    state_dir.mkdir(parents=True, exist_ok=True)
    database = state_dir / "checkpoints.sqlite"
    config = {"configurable": {"thread_id": "project-chat"}}

    async with AsyncSqliteSaver.from_conn_string(str(database)) as saver:
        await saver.setup()
        async with create_agent(runtime, checkpointer=saver) as agent:
            result = await agent.ainvoke(
                {"messages": [("user", message)]},
                config=config,
            )
            print(result["messages"][-1].content)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("message")
    asyncio.run(main(parser.parse_args().message))

Run the script twice in an environment with DataAgent installed. In a source checkout, use uv run python for the same commands.

python conversation.py "The project codename for this conversation is Maple. Please confirm."
python conversation.py "What was the project codename?"

The second invocation should answer Maple. Each invocation starts a separate Python process, sends only the new message, and reads history using the same database file and thread_id. To continue a session managed by a running server, call that server through the HTTP integration.

Async and streaming calls

Use the ainvoke() example above if you only need the final reply. Use astream() to show progress as the Agent runs. This example uses stream_mode="updates" to read incremental run updates.

import asyncio
from contextlib import aclosing

from dataagent import create_agent, prepare_runtime


async def main():
    runtime = prepare_runtime()
    config = {"configurable": {"thread_id": "stream-demo"}}
    inputs = {"messages": [("user", "List three examples")]}

    async with create_agent(runtime) as agent:
        async with aclosing(agent.astream(inputs, config, stream_mode="updates")) as updates:
            async for update in updates:
                print(update)


asyncio.run(main())

The terminal prints run updates as they arrive. Each describes an execution step and may contain a tool result. Use ainvoke() for only the final reply.

Find session outputs

Files produced by a task belong to its session. See sessions and outputs for how to find them.

Write to backend.log

The SDK uses the host's Python logging configuration. To use DataAgent's JSON logging, import configure_logging from dataagent.host and call configure_logging(runtime) immediately after prepare_runtime(...).

This replaces the root handlers and writes INFO and higher to <Home>/runtime/logs/backend.log by default. DATAAGENT_CONSOLE_LOG_LEVEL controls the console level and defaults to INFO. When set to DEBUG, the root logger also receives DEBUG records. The host controls initialization and may log an exception at the call boundary with logger.exception(..., extra={"threadId": "sdk-demo"}) before re-raising. The caller handles configuration and execution failures. See observability and the host API for trace and output locations.

dataagent serve and serve-a2a initialize logging at startup. SDK logging follows the selected Home. The launcher manages DATAAGENT_LOG_CAPTURE.

Close a stream early

Use closing or aclosing. Break when you have what you need. Leaving the context closes the stream and releases the session.

from contextlib import closing

with closing(agent.stream(inputs, config)) as stream:
    for chunk in stream:
        print(chunk)
        break

For async streams, use async with aclosing(agent.astream(inputs, config)) and async for. See Agent API for concurrency rules.

Access models from tools

To select a model or call the semantic client inside a tool, see the tool guide.