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工作原理
- Every SDK has a tool loop with a round limit. That replaces the planner and tool nodes.每个 SDK 都有带轮次上限的工具循环。它替代的是规划节点和工具节点。
- Graph frameworks make state explicit with reducers. That is merge_state.图框架用 reducer 把状态显式化。那就是 merge_state。
- Tools are Python functions with type hints and a docstring, or an MCP server.工具是带类型注解和 docstring 的 Python 函数,或者一个 MCP 服务。
- Tracing replaces JSON-lines logs. Check where traces are sent.追踪(tracing)替代 JSON Lines 日志。要确认 trace 被发送到了哪里。
- Your tools, skills, evals, and answer checks stay outside the framework.你的工具、技能、评估和回答检查都留在框架之外。
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.md | How to add capabilities without breaking the contract.如何在不破坏契约的前提下增加能力。 |
Process map流程图
The same parts, under three names同样的部件,三套名称
- 1Endpoint端点Hand-built: chat(). LangGraph: ChatOpenAI(base_url). Agents SDK: OpenAIChatCompletionsModel.手写:chat()。LangGraph:ChatOpenAI(base_url)。Agents SDK:OpenAIChatCompletionsModel。
- 2Tools工具Hand-built: Registry. LangGraph: functions passed in a list. Agents SDK: @function_tool.手写:Registry。LangGraph:以列表传入的函数。Agents SDK:@function_tool。
- 3Loop循环Hand-built: Agent.run(). LangGraph: create_react_agent. Agents SDK: Runner.手写:Agent.run()。LangGraph:create_react_agent。Agents SDK:Runner。
- 4Round budget轮次预算Hand-built: max_rounds. LangGraph: recursion_limit. Agents SDK: max_turns.手写:max_rounds。LangGraph:recursion_limit。Agents SDK:max_turns。
- 5Record记录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 实际运行时打印的内容。
- 1Map SDK features to parts you built把 SDK 的功能对应到你搭建过的部件
- 2Give every SDK the same endpoint给每个 SDK 同一个端点
- 3Port the agent to LangGraph把智能体移植到 LangGraph
- 4Port the agent to the OpenAI Agents SDK把智能体移植到 OpenAI Agents SDK
- 5Run all three and compare三个都跑一遍并比较
- 6Port to the Claude Agent SDK through MCP通过 MCP 移植到 Claude Agent SDK
- 7Decide what stays outside any SDK决定哪些东西留在任何 SDK 之外
01Map SDK features to parts you built把 SDK 的功能对应到你搭建过的部件
- the list of parts to map要对应的部件清单 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
Do this操作
- 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,找出它对下列概念的叫法:循环、轮次上限、工具定义、状态合并、护栏或钩子接入点、追踪。
- For each, write what it does at the limit. Does it raise, return, or answer from evidence?对每一项,写下它在达到上限时的行为:抛异常、直接返回,还是根据已有证据作答?
- Find where traces go by default.查明 trace 默认发送到哪里。
- SDKs and frameworksSDK 与框架 3: Port the agent to LangGraph把智能体移植到 LangGraph (which settings to look for需要关注哪些设置)
02Give every SDK the same endpoint给每个 SDK 同一个端点
- serve()serve() ← API and gatewayAPI 与网关 3: Write the gateway handler编写网关处理函数
- a key with the tools scope带 tools 权限的密钥 ← API and gatewayAPI 与网关 2: Build the key store建立密钥库
Do this操作
- Start the gateway on a local port and issue a key with chat and tools scopes.在本地端口启动网关,并签发一个带 chat 和 tools 权限的密钥。
- 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 代码就会连到你的真实模型。
"""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- SDKs and frameworksSDK 与框架 3: Port the agent to LangGraph把智能体移植到 LangGraph (base URL and keybase URL 和密钥)
- SDKs and frameworksSDK 与框架 4: Port the agent to the OpenAI Agents SDK把智能体移植到 OpenAI Agents SDK (base URL and keybase URL 和密钥)
03Port the agent to LangGraph把智能体移植到 LangGraph
- base URL and keybase URL 和密钥 ← SDKs and frameworksSDK 与框架 2: Give every SDK the same endpoint给每个 SDK 同一个端点
- build_registry()build_registry() ← Tools and MCP工具与 MCP 3: Write the tools, with diagnostics for empty results编写工具,并为空结果提供诊断
- which settings to look for需要关注哪些设置 ← SDKs and frameworksSDK 与框架 1: Map SDK features to parts you built把 SDK 的功能对应到你搭建过的部件
Do this操作
- `pip install langgraph langchain-openai`.`pip install langgraph langchain-openai`。
- Wrap each registry tool in a plain function with a docstring.把注册表里的每个工具包装成带 docstring 的普通函数。
- Create the model with your base URL and key. Create the agent with the tools and the same base prompt.用你的 base URL 和密钥创建模型。用这些工具和同样的基础提示词创建智能体。
- Set `recursion_limit`. That is the round budget.设置 `recursion_limit`。它就是轮次预算。
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}- SDKs and frameworksSDK 与框架 5: Run all three and compare三个都跑一遍并比较 (the LangGraph portLangGraph 移植版)
04Port the agent to the OpenAI Agents SDK把智能体移植到 OpenAI Agents SDK
- base URL and keybase URL 和密钥 ← SDKs and frameworksSDK 与框架 2: Give every SDK the same endpoint给每个 SDK 同一个端点
- build_registry()build_registry() ← Tools and MCP工具与 MCP 3: Write the tools, with diagnostics for empty results编写工具,并为空结果提供诊断
Do this操作
- `pip install openai-agents`.`pip install openai-agents`。
- Decorate each tool with `@function_tool`.用 `@function_tool` 装饰每个工具。
- Create a chat-completions model with a client that points at your base URL.创建一个 chat-completions 模型,其客户端指向你的 base URL。
- Disable tracing, or decide knowingly to send traces to the vendor. It is on by default.关闭 tracing,或者在知情的前提下决定把 trace 发给厂商。它默认是开启的。
- Pass `max_turns` when running.运行时传入 `max_turns`。
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]}- SDKs and frameworksSDK 与框架 5: Run all three and compare三个都跑一遍并比较 (the Agents SDK portAgents SDK 移植版)
05Run all three and compare三个都跑一遍并比较
- the LangGraph portLangGraph 移植版 ← SDKs and frameworksSDK 与框架 3: Port the agent to LangGraph把智能体移植到 LangGraph
- the Agents SDK portAgents SDK 移植版 ← SDKs and frameworksSDK 与框架 4: Port the agent to the OpenAI Agents SDK把智能体移植到 OpenAI Agents SDK
- the hand-built loop as reference作为参照的手写循环 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
Do this操作
- Run the demo. It asks one question through each loop.运行 demo。它把同一个问题分别交给每个循环。
- Compare the sequence each reports.比较各自报告的执行序列。
- Then run each through your agent eval. The eval scores answers and does not care which loop produced them.然后让每个都通过你的智能体评估。评估只给回答打分,不关心是哪个循环产生的。
python3 -m labs.m14_sdk.demohand-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.- SDKs and frameworksSDK 与框架 7: Decide what stays outside any SDK决定哪些东西留在任何 SDK 之外 (the three versions side by side并排的三个版本)
06Port to the Claude Agent SDK through MCP通过 MCP 移植到 Claude Agent SDKNot executed in the labslab 中未执行
- the MCP server moduleMCP 服务模块 ← Tools and MCP工具与 MCP 5: Serve the same tools over MCP通过 MCP 提供同一批工具
Do this操作
- `pip install claude-agent-sdk` and set an API key.`pip install claude-agent-sdk` 并设置 API 密钥。
- In the options, list the MCP server by command and arguments.在选项里用命令和参数列出 MCP 服务。
- Allow the two tools by their MCP names, and set `max_turns`.按 MCP 名称允许这两个工具,并设置 `max_turns`。
- Iterate the messages from `query()` and collect the text.遍历 `query()` 返回的消息并收集文本。
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.这一步需要人工检查。
07Decide what stays outside any SDK决定哪些东西留在任何 SDK 之外
- the three versions side by side并排的三个版本 ← SDKs and frameworksSDK 与框架 5: Run all three and compare三个都跑一遍并比较
Do this操作
- List what the three versions share unchanged: the registry and tools, the base prompt, the eval sets, the guard.列出三个版本原样共用的东西:注册表和工具、基础提示词、评估集、护栏。
- Keep those in their own modules with no SDK import.把它们放在各自的模块里,不导入任何 SDK。
- Treat the loop file as the adapter you would rewrite when switching.把循环文件当作切换时需要重写的适配层。
How it works with the other parts它如何与其他部分协作
- Harness engineeringHarness 工程An SDK replaces the loop. The plug points you built map to its hooks and guardrails.SDK 替代的是循环。你搭建的各个接入点对应它的钩子和护栏。
- Tools and MCP工具与 MCPThe registry functions and the MCP server are the two ways tools enter an SDK.注册表函数和 MCP 服务是工具进入 SDK 的两种途径。
- Evaluation评估The agent eval scores any loop. Use it to compare SDKs on your questions.智能体评估可以给任何循环打分。用它在你自己的问题上比较各个 SDK。
- API and gatewayAPI 与网关One base URL keeps the model constant across SDKs.同一个 base URL 让各 SDK 之间的模型保持一致。
What went wrong in the real build真实搭建中踩过的坑
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 里的名称变得比概念快。学的是概念,名称要去核实。
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本模块如何对应 |
|---|---|
| Databricks | MLflow 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 watsonx | The Orchestrate ADK defines agents and tools in files and a CLI. It also imports agents built with LangGraph and similar frameworks.Orchestrate ADK 用文件和命令行来定义智能体和工具。它也可以导入用 LangGraph 等框架构建的智能体。 |
| Codex | The OpenAI Agents SDK provides the loop, handoffs, guardrails, sessions, and tracing. Codex itself can be run headless and scripted.OpenAI Agents SDK 提供循环、交接、护栏、会话和追踪。Codex 本身可以无界面运行并通过脚本调用。 |
| Cursor | Cursor provides a command-line agent and background agents. For your own service use a general SDK.Cursor 提供命令行智能体和后台智能体。要构建自己的服务,请使用通用 SDK。 |
| Claude Code / Agent SDK | The 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 machine | Any 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。在手写版本里那是什么?
What should stay outside any SDK?哪些东西应该留在任何 SDK 之外?
Why give every SDK the same base URL when comparing them?比较各个 SDK 时,为什么要给它们同一个 base URL?
Name three settings to check in any SDK before using it.说出使用任何 SDK 之前都要检查的三项设置。
Terms术语
| ReducerReducer | A function that merges a node's update into shared state.把某个节点的更新合并进共享状态的函数。 |
| Handoff交接(Handoff) | One agent passing the conversation to another.一个智能体把对话转交给另一个智能体。 |
| TraceTrace | A 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.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Claude Code → your own models
- Double-click button: gives Claude Code access to the knowledge bank. Built 2026-08-23, after a Claude Code session on local-qwen38 was asked about the agency a commodity spending and answered "I don't have that in my knowledge" — while brain.db held 144,781 atoms and the spending tables ...
- LocalAPI-Claude.command rev 2026-08-22b The one command for the Claude Code local API. Start, restart, or re-run after pulling a model. Idempotent.
- LocalAPI-Claude.command rev 2026-08-22b The one command for the Claude Code local API. Start, restart, or re-run after pulling a model. Idempotent.
- Disaster Emergency Fund Codes: the shared vocabulary. DEFC is how a federal dollar says which emergency, disaster or supplemental law it came from.
- Restart-Claude-Code-Gateway.command The one to double-click after editing config.yaml.