Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 14 / labs/m14_*

SDKs and frameworksSDK 与框架

What agent SDKs give you, mapped onto parts you have already built by hand.智能体 SDK 提供了什么,对照你已经亲手搭建过的各个部件来理解。

What it is and why it exists它是什么,为什么需要它

What是什么

An agent SDK packages the harness: the tool loop, state handling, streaming, tracing, and often handoffs and guardrails. This module runs the same agent on three loops: the hand-built one, LangGraph, and the OpenAI Agents SDK, with a Claude Agent SDK port alongside.智能体 SDK 把 Harness 打包好了:工具循环、状态处理、流式输出、追踪,通常还有交接和护栏。本模块让同一个智能体在三种循环上运行:手写的循环、LangGraph 和 OpenAI Agents SDK,另附一个 Claude Agent SDK 的移植版本。

Why为什么

If you can name the part an SDK feature replaces, you can adopt or leave any framework without rewriting your system. Having built each part once makes every SDK's documentation readable.如果你能说出某个 SDK 功能替代的是哪个部件,你就可以采用或放弃任何框架,而不用重写系统。每个部件都亲手做过一遍之后,任何 SDK 的文档都读得懂。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

  • Harness engineeringHarness 工程You evaluate an SDK by comparing it with a loop you understand. Without that, every framework's defaults look like requirements.评估一个 SDK,靠的是把它和你理解的循环做比较。没有这个基础,任何框架的默认值看起来都像是必须如此。Build out of order不按顺序搭建 Stand in with:可用以下替代: Follow one framework's quickstart first, then return to the harness module to see what it hid.先照着某个框架的快速入门做一遍,再回到 Harness 模块看它隐藏了什么。
  • Tools and MCP工具与 MCPTools are what you carry between SDKs. Having them behind one registry and one MCP server makes the comparison a few lines per SDK.工具是你在各个 SDK 之间带着走的东西。把它们放在一个注册表和一个 MCP 服务后面,每个 SDK 的对比就只需要几行代码。Build out of order不按顺序搭建 Stand in with:可用以下替代: One inline function tool.一个内联的函数工具。
  • API and gatewayAPI 与网关SDKs need an endpoint. The gateway gives every SDK the same OpenAI-compatible base URL, so the model is held constant while the loop changes.SDK 需要一个端点。网关为每个 SDK 提供同一个 OpenAI 兼容的 base URL,这样在更换循环时模型保持不变。Build out of order不按顺序搭建 Stand in with:可用以下替代: Point the SDK at a hosted provider.让 SDK 直接连托管的供应商。

Unlocks解锁

Nothing depends on this. It is an end point of the map.没有模块依赖它。它是地图上的一个终点。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/The hand-built reference for every part an SDK provides.SDK 所提供的每个部件的手写参照实现。
apps/claude-code-gateway/Lets a coding agent's loop run against local models.让编程智能体的循环可以对接本地模型。
study-notes/08_Extending_The_Harness_Agent.mdHow to add capabilities without breaking the contract.如何在不破坏契约的前提下增加能力。

Process map流程图

The same parts, under three names同样的部件,三套名称

  1. 1
    Endpoint端点Hand-built: chat(). LangGraph: ChatOpenAI(base_url). Agents SDK: OpenAIChatCompletionsModel.手写:chat()。LangGraph:ChatOpenAI(base_url)。Agents SDK:OpenAIChatCompletionsModel。
  2. 2
    Tools工具Hand-built: Registry. LangGraph: functions passed in a list. Agents SDK: @function_tool.手写:Registry。LangGraph:以列表传入的函数。Agents SDK:@function_tool。
  3. 3
    Loop循环Hand-built: Agent.run(). LangGraph: create_react_agent. Agents SDK: Runner.手写:Agent.run()。LangGraph:create_react_agent。Agents SDK:Runner。
  4. 4
    Round budget轮次预算Hand-built: max_rounds. LangGraph: recursion_limit. Agents SDK: max_turns.手写:max_rounds。LangGraph:recursion_limit。Agents SDK:max_turns。
  5. 5
    Record记录Hand-built: JSON lines. SDKs: traces.手写:JSON Lines。SDK:trace。

Build steps搭建步骤

Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。

  1. 1Map SDK features to parts you built把 SDK 的功能对应到你搭建过的部件
  2. 2Give every SDK the same endpoint给每个 SDK 同一个端点
  3. 3Port the agent to LangGraph把智能体移植到 LangGraph
  4. 4Port the agent to the OpenAI Agents SDK把智能体移植到 OpenAI Agents SDK
  5. 5Run all three and compare三个都跑一遍并比较
  6. 6Port to the Claude Agent SDK through MCP通过 MCP 移植到 Claude Agent SDK
  7. 7Decide what stays outside any SDK决定哪些东西留在任何 SDK 之外
01Map SDK features to parts you built把 SDK 的功能对应到你搭建过的部件
Why this step is here为什么这一步排在这里Read before you install. The map tells you which defaults to check and what to keep outside.先读再装。这张对照表告诉你该检查哪些默认值,以及哪些东西要留在框架之外。

Do this操作

  1. For the SDK you are considering, find its name for: the loop, the round limit, tool definition, state merging, guard or hook points, tracing.针对你考虑使用的 SDK,找出它对下列概念的叫法:循环、轮次上限、工具定义、状态合并、护栏或钩子接入点、追踪。
  2. For each, write what it does at the limit. Does it raise, return, or answer from evidence?对每一项,写下它在达到上限时的行为:抛异常、直接返回,还是根据已有证据作答?
  3. Find where traces go by default.查明 trace 默认发送到哪里。
You are done when完成标志You have a table with one row per harness part and the SDK's name for it.你有了一张表:每个 Harness 部件一行,旁边是 SDK 对它的叫法。
Produces产出A mapping table for one SDK.一张针对某个 SDK 的对照表。
Feeds供给
02Give every SDK the same endpoint给每个 SDK 同一个端点
Why this step is here为什么这一步排在这里Hold the model constant so differences come from the loop. The gateway from module 2 serves that purpose unchanged.让模型保持不变,这样差异就只来自循环。第 2 模块的网关无需改动就能承担这个角色。

Do this操作

  1. Start the gateway on a local port and issue a key with chat and tools scopes.在本地端口启动网关,并签发一个带 chat 和 tools 权限的密钥。
  2. With `LAB_BASE_URL` unset it answers with the fake model. Set it and the same SDK code reaches your real model.不设置 `LAB_BASE_URL` 时它用假模型回答。设置之后,同样的 SDK 代码就会连到你的真实模型。
labs/m14_sdk/serve_fake.py
"""Start the lab gateway on a port so SDKs have an OpenAI-compatible endpoint to call.

With LAB_BASE_URL unset the gateway answers with the fake model. Set it and the
same SDK code talks to your real model through the same gateway.
"""
from __future__ import annotations

from labs.common.paths import work
from labs.m02_gateway.gateway import serve
from labs.m02_gateway.keys import KeyStore


def start():
    keys = KeyStore(work("m14", fresh=True) / "keys.db")
    key = keys.issue("sdk-lab", scopes="chat,tools", rate_per_min=600)
    server, base = serve(keys)
    return server, base + "/v1", key
You are done when完成标志`start()` returns a base URL ending in /v1 and a key.`start()` 返回一个以 /v1 结尾的 base URL 和一个密钥。
Produces产出A base URL and key that any OpenAI-compatible SDK accepts.任何 OpenAI 兼容 SDK 都能接受的 base URL 和密钥。
03Port the agent to LangGraph把智能体移植到 LangGraph
Why this step is here为什么这一步排在这里First port, because a graph framework is closest to the wave executor you wrote.第一个移植对象选它,因为图框架和你写的波次执行器最接近。

Do this操作

  1. `pip install langgraph langchain-openai`.`pip install langgraph langchain-openai`。
  2. Wrap each registry tool in a plain function with a docstring.把注册表里的每个工具包装成带 docstring 的普通函数。
  3. Create the model with your base URL and key. Create the agent with the tools and the same base prompt.用你的 base URL 和密钥创建模型。用这些工具和同样的基础提示词创建智能体。
  4. Set `recursion_limit`. That is the round budget.设置 `recursion_limit`。它就是轮次预算。
labs/m14_sdk/langgraph_agent.py · langgraph
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

from labs.m05_rag.demo import build
from labs.m06_tools.tools import build_registry
from labs.m07_harness.loop import BASE_PROMPT


def make(base_url: str, api_key: str, model: str = "fake"):
    db, _ = build(fresh=False)
    reg = build_registry(db)

    def search_policy(query: str) -> dict:
        """Search policy documents. Use for rules, limits, definitions and deadlines."""
        return reg.call("search_policy", {"query": query})

    def query_expenses(category: str = "", city: str = "", cost_center: str = "", month: str = "") -> dict:
        """Total and list expense records. Filters are optional: category, city, cost_center, month (YYYY-MM)."""
        return reg.call("query_expenses", {"category": category, "city": city, "cost_center": cost_center, "month": month})

    llm = ChatOpenAI(base_url=base_url, api_key=api_key, model=model, temperature=0)
    return create_react_agent(llm, [search_policy, query_expenses], prompt=BASE_PROMPT)


def ask(agent, question: str) -> dict:
    out = agent.invoke({"messages": [{"role": "user", "content": question}]}, {"recursion_limit": 12})
    kinds = [m.type for m in out["messages"]]
    return {"answer": out["messages"][-1].content, "message_types": kinds}
You are done when完成标志The message types read human, ai, tool, ai: the same shape as planner, tool, planner.消息类型依次是 human、ai、tool、ai:与“规划、工具、规划”的结构相同。
Produces产出`langgraph_agent.make()` and `ask()`.`langgraph_agent.make()` 和 `ask()`。
04Port the agent to the OpenAI Agents SDK把智能体移植到 OpenAI Agents SDK
Why this step is here为什么这一步排在这里Second port, to see the same parts under different names. Two ports show what is common to SDKs and what is one vendor's choice.第二个移植对象,用来看同样的部件换了名字是什么样子。做两次移植,才能看出哪些是各 SDK 的共性,哪些是某家厂商自己的选择。

Do this操作

  1. `pip install openai-agents`.`pip install openai-agents`。
  2. Decorate each tool with `@function_tool`.用 `@function_tool` 装饰每个工具。
  3. Create a chat-completions model with a client that points at your base URL.创建一个 chat-completions 模型,其客户端指向你的 base URL。
  4. Disable tracing, or decide knowingly to send traces to the vendor. It is on by default.关闭 tracing,或者在知情的前提下决定把 trace 发给厂商。它默认是开启的。
  5. Pass `max_turns` when running.运行时传入 `max_turns`。
labs/m14_sdk/openai_agents_agent.py · agents-sdk
from agents import Agent, OpenAIChatCompletionsModel, Runner, function_tool, set_tracing_disabled
from openai import AsyncOpenAI

from labs.m05_rag.demo import build
from labs.m06_tools.tools import build_registry
from labs.m07_harness.loop import BASE_PROMPT


def make(base_url: str, api_key: str, model: str = "fake") -> Agent:
    set_tracing_disabled(True)                 # tracing uploads to the vendor by default
    db, _ = build(fresh=False)
    reg = build_registry(db)

    @function_tool
    def search_policy(query: str) -> str:
        """Search policy documents. Use for rules, limits, definitions and deadlines."""
        return reg.call_as_text("search_policy", {"query": query})

    @function_tool
    def query_expenses(category: str = "", city: str = "", cost_center: str = "", month: str = "") -> str:
        """Total and list expense records. Filters are optional: category, city, cost_center, month (YYYY-MM)."""
        return reg.call_as_text("query_expenses", {"category": category, "city": city, "cost_center": cost_center, "month": month})

    client = AsyncOpenAI(base_url=base_url, api_key=api_key)
    return Agent(name="policy-desk", instructions=BASE_PROMPT, tools=[search_policy, query_expenses],
                 model=OpenAIChatCompletionsModel(model=model, openai_client=client))


def ask(agent: Agent, question: str) -> dict:
    result = Runner.run_sync(agent, question, max_turns=6)
    return {"answer": result.final_output, "items": [type(i).__name__ for i in result.new_items]}
You are done when完成标志The run items read tool call, tool output, message.运行条目依次是:工具调用、工具输出、消息。
Produces产出`openai_agents_agent.make()` and `ask()`.`openai_agents_agent.make()` 和 `ask()`。
05Run all three and compare三个都跑一遍并比较
Why this step is here为什么这一步排在这里Now there are three loops over the same tools and endpoint. Compare what each did.现在同样的工具和端点上有了三个循环。比较它们各自做了什么。

Do this操作

  1. Run the demo. It asks one question through each loop.运行 demo。它把同一个问题分别交给每个循环。
  2. Compare the sequence each reports.比较各自报告的执行序列。
  3. Then run each through your agent eval. The eval scores answers and does not care which loop produced them.然后让每个都通过你的智能体评估。评估只给回答打分,不关心是哪个循环产生的。
run
python3 -m labs.m14_sdk.demo
Recorded output / 记录的输出 · m14.demo
hand-built loop : 2 model calls, tools ['search_policy']
langgraph       : ['human', 'ai', 'tool', 'ai'] -> From the tool results: {"results": [{"source": "memos/2026-lodging-mem ...
openai-agents   : ['ToolCallItem', 'ToolCallOutputItem', 'MessageOutputItem'] -> From the tool results: {"results": [{"source": "memos/2026-lodging-mem ...
same tools, same endpoint, three loops. Only the loop changed.
You are done when完成标志All three call `search_policy` once and then answer.三者都调用了一次 `search_policy`,然后作答。
Produces产出Evidence that the loop is the replaceable part.证明循环是可以替换的那部分。
06Port to the Claude Agent SDK through MCP通过 MCP 移植到 Claude Agent SDKNot executed in the labslab 中未执行
Why this step is here为什么这一步排在这里This port reuses the MCP server from module 6 with no wrapper functions, which shows the second way tools travel. It was not executed in the lab run.这个移植直接复用第 6 模块的 MCP 服务,不需要包装函数,展示了工具迁移的第二种方式。它没有在 lab 运行中实际执行。

Do this操作

  1. `pip install claude-agent-sdk` and set an API key.`pip install claude-agent-sdk` 并设置 API 密钥。
  2. In the options, list the MCP server by command and arguments.在选项里用命令和参数列出 MCP 服务。
  3. Allow the two tools by their MCP names, and set `max_turns`.按 MCP 名称允许这两个工具,并设置 `max_turns`。
  4. Iterate the messages from `query()` and collect the text.遍历 `query()` 返回的消息并收集文本。
labs/m14_sdk/claude_agent_sdk_agent.py · claude-sdk
import asyncio
import sys

from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query

from labs.m07_harness.loop import BASE_PROMPT


def options() -> ClaudeAgentOptions:
    return ClaudeAgentOptions(
        system_prompt=BASE_PROMPT,
        mcp_servers={"policy-desk": {"command": sys.executable, "args": ["-m", "labs.m06_tools.mcp_server"]}},
        allowed_tools=["mcp__policy-desk__search_policy", "mcp__policy-desk__query_expenses"],
        max_turns=6,                        # the round budget
    )


async def ask(question: str) -> str:
    text = []
    async for message in query(prompt=question, options=options()):
        if isinstance(message, AssistantMessage):
            text += [b.text for b in message.content if isinstance(b, TextBlock)]
        elif isinstance(message, ResultMessage):
            break
    return "\n".join(text)

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

This step is checked by hand.这一步需要人工检查。

You are done when完成标志Run it yourself with a key. Imports and option names were checked against the installed package. Behavior was not.请带上密钥自己运行。导入语句和选项名已对照安装的包核对过,但运行行为没有验证。
Produces产出A port that shares tools through the protocol.一个通过协议共享工具的移植版本。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
07Decide what stays outside any SDK决定哪些东西留在任何 SDK 之外
Why this step is here为什么这一步排在这里Last, because the ports show it. What you did not have to rewrite is what you own.放在最后,因为移植过程已经说明了答案。那些不需要重写的东西,就是真正属于你的。
Uses用到

Do this操作

  1. List what the three versions share unchanged: the registry and tools, the base prompt, the eval sets, the guard.列出三个版本原样共用的东西:注册表和工具、基础提示词、评估集、护栏。
  2. Keep those in their own modules with no SDK import.把它们放在各自的模块里,不导入任何 SDK。
  3. Treat the loop file as the adapter you would rewrite when switching.把循环文件当作切换时需要重写的适配层。
You are done when完成标志None of your tool, skill, eval, or guard files imports an agent SDK.你的工具、技能、评估和护栏文件都没有导入任何智能体 SDK。
Produces产出A boundary: your assets on one side, the loop on the other.一条边界:一边是你的资产,另一边是循环。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

found while building the labs搭建 lab 时发现

Library APIs had moved库的 API 已经变了

What happened发生了什么
The MCP SDK installed for the lab was a major version newer than the one the code was written for, and the import failed.为 lab 安装的 MCP SDK 比代码所针对的版本高了一个大版本,导入失败。
Fix修复
Run every port in the test suite, and import by what exists.把每个移植版本都纳入测试,并按实际存在的名称导入。
Lesson教训
SDK names change faster than concepts. Learn the concept, verify the name.SDK 里的名称变得比概念快。学的是概念,名称要去核实。
found while building the labs搭建 lab 时发现

Tracing that uploads by default默认会上传的追踪数据

What happened发生了什么
One SDK sends traces to its vendor unless told otherwise.有一个 SDK 除非另行设置,否则会把 trace 发送给它的厂商。
Fix修复
Disable it, or configure an exporter you control.关闭它,或配置一个你自己掌控的导出目标。
Lesson教训
Check where every framework sends data before you give it yours.把数据交给任何框架之前,先查清它会把数据发到哪里。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksMLflow ResponsesAgent wraps an agent written with any framework. The app templates use the OpenAI Agents SDK, and deployment, tracing, and evaluation are added around it.MLflow ResponsesAgent 可以封装用任意框架编写的智能体。官方应用模板使用 OpenAI Agents SDK,平台在其外围提供部署、追踪和评估。
IBM watsonxThe Orchestrate ADK defines agents and tools in files and a CLI. It also imports agents built with LangGraph and similar frameworks.Orchestrate ADK 用文件和命令行来定义智能体和工具。它也可以导入用 LangGraph 等框架构建的智能体。
CodexThe OpenAI Agents SDK provides the loop, handoffs, guardrails, sessions, and tracing. Codex itself can be run headless and scripted.OpenAI Agents SDK 提供循环、交接、护栏、会话和追踪。Codex 本身可以无界面运行并通过脚本调用。
CursorCursor provides a command-line agent and background agents. For your own service use a general SDK.Cursor 提供命令行智能体和后台智能体。要构建自己的服务,请使用通用 SDK。
Claude Code / Agent SDKThe Claude Agent SDK exposes the coding agent's loop, tools, hooks, subagents, and MCP support as a library in Python and TypeScript.Claude Agent SDK 把编程智能体的循环、工具、钩子、子智能体和 MCP 支持,以 Python 和 TypeScript 库的形式提供出来。
Another machineAny SDK that speaks the OpenAI-compatible API can target a local engine by base URL.任何支持 OpenAI 兼容 API 的 SDK,都可以通过 base URL 指向本地引擎。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

A framework advertises reducers for state channels. What is that in the hand-built version?某个框架宣传它为状态通道提供 reducer。在手写版本里那是什么?
A strong answer参考答案merge_state. Keys that extend or sum are reducers. Keys that overwrite are plain channels.merge_state。做追加或求和的键就是 reducer。直接覆盖的键就是普通通道。
What should stay outside any SDK?哪些东西应该留在任何 SDK 之外?
A strong answer参考答案Tools behind a registry and MCP, skill files, eval sets and scripts, and answer checks. Those hold your domain knowledge and should not be rewritten when the loop changes.注册表和 MCP 后面的工具、技能文件、评估集和脚本、回答检查。它们承载的是你的领域知识,循环换了也不应该重写。
Why give every SDK the same base URL when comparing them?比较各个 SDK 时,为什么要给它们同一个 base URL?
A strong answer参考答案It holds the model constant. Any difference in behavior then comes from the loop: its prompts, its limits, its handling of tool results.这样模型保持不变。行为上的任何差异就都来自循环本身:它的提示词、它的上限、它对工具结果的处理方式。
Name three settings to check in any SDK before using it.说出使用任何 SDK 之前都要检查的三项设置。
A strong answer参考答案The round limit and what happens when it is hit, where traces are sent, and how tool errors are returned to the model.轮次上限及其触发后的行为、trace 发送到哪里、工具错误如何返回给模型。

Terms术语

ReducerReducerA function that merges a node's update into shared state.把某个节点的更新合并进共享状态的函数。
Handoff交接(Handoff)One agent passing the conversation to another.一个智能体把对话转交给另一个智能体。
TraceTraceA structured record of the model calls and tool calls in one run.对一次运行中模型调用和工具调用的结构化记录。

From the live build来自实时构建

Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问