以编程方式使用文档

使用 Python、TypeScript 和 React 构建、运行和流式传输托管深度代理。SDK 封装了 /v1/deepagents 用于创建代理、管理线程、流式传输运行、注册 MCP 服务器和构建 React UI 的 API。

有关概念,请参阅 托管深度代理概述。有关端到端演练,请按照 快速入门.

安装

uv add managed-deepagents

# or with pip
pip install managed-deepagents
npm install @langchain/managed-deepagents
npm install @langchain/managed-deepagents @langchain/react

Requirements:

  • - Python 3.10 或更高版本,适用于 managed-deepagents.
  • - Node.js 22 或更高版本,适用于 @langchain/managed-deepagents.
  • - 托管深度代理 私人测试阶段访问权限.
  • - A LangSmith API 密钥 用于具有私人测试阶段访问权限的工作区。

配置客户端

设置您的 API 密钥:

两个 SDK 默认使用 https://api.smith.langchain.com/v1/deepagents。要使用兼容的端点,请设置 LANGSMITH_ENDPOINT 或直接传递 API URL:

from managed_deepagents import Client

client = Client(
    api_key="",
    api_url="https://api.smith.langchain.com/v1/deepagents",
)
const client = new Client({
  apiKey: process.env.LANGSMITH_API_KEY,
  apiUrl: "https://api.smith.langchain.com/v1/deepagents",
});

Client()new Client() 读取 LANGSMITH_API_KEYLANGSMITH_ENDPOINT 从环境变量中读取,因此本页中的其余示例在构造客户端时不传递参数。

创建代理

创建代理的请求可以使用相同的顶级 modelbackend 字段,如同 托管深度代理 CLI。传递 model 作为包含 id of {provider}:{model_id}的对象。请参阅 支持的提供商和模型.

from managed_deepagents import Client

with Client() as client:
    agent = client.agents.create(
        name="research-assistant",
        description="Research assistant that can search the web and summarize sources.",
        model="openai:gpt-5.5",
        backend={"type": "state"},
        instructions=(
            "You are a careful research assistant. Search for sources, "
            "keep notes, and return concise answers with citations."
        ),
    )

agent_id = agent["id"]
print(f"Agent ID: {agent_id}")
const client = new Client();

const agent = await client.agents.create({
  name: "research-assistant",
  description: "Research assistant that can search the web and summarize sources.",
  model: "openai:gpt-5.5",
  backend: { type: "state" },
  instructions:
    "You are a careful research assistant. Search for sources, keep notes, and return concise answers with citations.",
});

const agentId = agent.id;
console.log(`Agent ID: ${agentId}`);

Python 方法返回类似字典的响应,因此使用 agent["id"]。TypeScript 方法返回类型化对象,因此使用 agent.id.

运行和流式传输

在运行代理之前创建线程。 线程 保留对话和执行状态,以便您以后可以恢复或检查运行。使用 id 创建代理时返回的

from managed_deepagents import Client

agent_id = "<agent_id>"

with Client() as client:
    thread = client.threads.create(
        agent_id=agent_id,
        options={
            "test_run": False,
            "skip_memory_write_protection": False,
        },
    )

    for event in client.threads.stream(
        thread["id"],
        agent_id=agent_id,
        messages=[
            {
                "role": "user",
                "content": "Research recent approaches to agent memory and summarize the main trade-offs.",
            }
        ],
        stream_mode=["values", "updates", "messages-tuple"],
        stream_subgraphs=True,
    ):
        print(event.event, event.data)
const agentId = "<agent_id>";
const client = new Client();

const thread = await client.threads.create({
  agent_id: agentId,
  options: {
    test_run: false,
    skip_memory_write_protection: false,
  },
});

const langGraphClient = client.getLangGraphClient({ agentId });
const stream = langGraphClient.runs.stream(thread.id, agentId, {
  input: {
    messages: [
      {
        role: "user",
        content:
          "Research recent approaches to agent memory and summarize the main trade-offs.",
      },
    ],
  },
  streamMode: ["values", "updates", "messages-tuple"],
  streamSubgraphs: true,
});

for await (const event of stream) {
  console.log(event.event, event.data);
}

options 对象是可选的,两个字段都默认为 false。设置 test_run to true 将线程标记为在用量和分析中被过滤掉的测试运行。默认情况下, skip_memory_write_protection 让运行时在代理写入长期记忆前引发人工干预中断,以便您可以批准或拒绝写入。将其设置为 true 以允许记忆写入立即进行,这在无人可批准写入的无头运行中很有用。

在 Python 中,直接使用 client.threads.stream(...)。在 TypeScript 中,使用 client.getLangGraphClient(...) 获取 LangGraph 客户端并使用 runs.stream(...)进行流式传输,它接受消息列表作为 input参数。每个事件都暴露一个 event 类型和一个 data 负载。您收到的类型取决于 stream_mode。有关流式传输模式和事件类型,请参阅 从线程流式传输运行.

使用 React useStream

TypeScript SDK 包含一个用于 @langchain/react的 LangGraph 客户端适配器。使用 getLangGraphClient() so useStream 管理线程生命周期、运行提交和状态更新,而 Managed Deep Agents SDK 提供正确的路由、认证标头和负载格式。

const agentId = "<agent_id>";

const managedDeepAgents = new Client();

const client = managedDeepAgents.getLangGraphClient({ agentId });

  const stream = useStream({
    client,
    assistantId: agentId
  });

  return (
    <section>
      <button
        type="button"
        disabled={stream.isLoading}
        onClick={() => {
          void stream.submit({
            messages: [
              { role: "user", content: "Write a short status update." },
            ],
          });
        }}
      >
        Run agent
      </button>

      {stream.messages.map((message, index) => (
        <p key={message.id ?? index}>{String(message.content)}</p>
      ))}

      <p>State keys: {Object.keys(stream.values).join(", ")}</p>
    </section>
  );
}

将请求路由到您的后端

SDK 客户端暴露这些资源组:

资源PythonTypeScript
代理client.agentsclient.agents
线程和运行client.threadsclient.threads
MCP 服务器client.mcp_serversclient.mcpServers
认证会话client.auth_sessionsclient.authSessions

Python 方法使用 snake_case,例如 create_and_runresolve_interrupt。TypeScript 方法使用 camelCase,例如 createAndRunresolveInterrupt.

SDK 可以使用 client.mcp_servers.list_tools(...) 在 Python 中或 client.mcpServers.listTools(...) 在 TypeScript 中注册 MCP 服务器、完成认证会话并发现已注册服务器的工具架构。将所选的工具条目传递给 client.agents.create(...) or client.agents.update(...).

处理错误

请求会引发包含 HTTP 状态和 API 返回时的错误代码及详情的类型化错误。

from managed_deepagents import Client, ManagedDeepAgentsAPIError

with Client() as client:
    try:
        client.agents.get("missing-agent")
    except ManagedDeepAgentsAPIError as error:
        # `code` and `detail` can be empty, for example on a 403 permission error.
        # The raw message is on `error.body`.
        print(error.status_code, error.code, error.detail, error.body)
const client = new Client();

try {
  await client.agents.get("missing-agent");
} catch (error) {
  if (error instanceof ManagedDeepAgentsAPIError) {
    // `code` and `detail` can be undefined, for example on a 403 permission error.
    // The raw message is on `error.body`.
    console.log(error.status, error.code, error.detail, error.body);
  }
}

当请求因缺少权限而被拒绝时,响应是一个 403 ,其 codedetail 为空,其原因以纯文本形式返回。从 error.body 在两个 SDK 中读取,例如 missing permission mcp-servers:create.

有关端点级别的请求和响应架构,请参阅 Managed Deep Agents API 参考.