工具让 Agent 能够采取行动,例如获取数据、运行代码、调用外部 API,甚至使用计算机。SDK 支持五类工具:
Tools let agents take actions: things like fetching data, running code, calling external APIs, and even using a computer. The SDK supports five categories:
- OpenAI 托管工具:在 OpenAI 服务器上为模型执行操作。
- 本地/运行时执行工具:
ComputerTool和ApplyPatchTool始终在你的环境中运行,而ShellTool既可以在本地运行,也可以在托管容器中运行。 FunctionTool实例:将任意 Python 函数封装为工具。- 将 Agent 用作工具:将一个 Agent 暴露为可调用的工具,而不进行完整的控制权移交。
- 实验性功能:Codex 工具,通过工具调用执行限定在工作区范围内的 Codex 任务。
- Hosted OpenAI tools: execute for the model on OpenAI servers.
- Local/runtime execution tools:
ComputerToolandApplyPatchToolalways run in your environment, whileShellToolcan run locally or in a hosted container. FunctionToolinstances: wrap any Python function as a tool.- Agents as tools: expose an agent as a callable tool without a full handoff.
- Experimental: Codex tool: run workspace-scoped Codex tasks from a tool call.
选择工具类型
Choosing a tool type
可以把本页当作工具目录,再跳转到与你所控制的运行时相对应的章节。
Use this page as a catalog, then jump to the section that matches the runtime you control.
托管工具
Hosted tools
使用 OpenAIResponsesModel 时,OpenAI 提供以下内置工具:
OpenAI offers a few built-in tools when using the OpenAIResponsesModel:
WebSearchTool让 Agent 搜索网页。FileSearchTool支持从你的 OpenAI 向量存储中检索信息。CodeInterpreterTool让大语言模型在沙箱环境中执行代码。HostedMCPTool将远程 MCP 服务器的工具暴露给模型。ImageGenerationTool根据提示词生成图像。ToolSearchTool让模型按需加载延迟加载的工具、命名空间或托管 MCP 服务器。ProgrammaticToolCallingTool让模型通过生成的 JavaScript 协调符合条件的工具。
- The
WebSearchToollets an agent search the web. - The
FileSearchToolallows retrieving information from your OpenAI Vector Stores. - The
CodeInterpreterToollets the LLM execute code in a sandboxed environment. - The
HostedMCPToolexposes a remote MCP server's tools to the model. - The
ImageGenerationToolgenerates images from a prompt. - The
ToolSearchToollets the model load deferred tools, namespaces, or hosted MCP servers on demand. - The
ProgrammaticToolCallingToollets the model coordinate eligible tools from generated JavaScript.
托管搜索的高级选项:
Advanced hosted search options:
- 除
vector_store_ids和max_num_results外,FileSearchTool还支持filters、ranking_options和include_search_results。将max_num_results设为 1 至 50 的整数;None或零表示使用服务提供方的默认值。 WebSearchTool支持filters、user_location、search_context_size、external_web_access、search_content_types和image_settings。
FileSearchToolsupportsfilters,ranking_options, andinclude_search_resultsin addition tovector_store_idsandmax_num_results. Setmax_num_resultsto an integer from 1 through 50;Noneor zero uses the provider default.WebSearchToolsupportsfilters,user_location,search_context_size,external_web_access,search_content_types, andimage_settings.
如果网页搜索应返回图像,请在 search_content_types 中包含 "image";如果模型还需要辅助的文本结果,请同时包含 "text"。image_settings.max_results 用正数指定要获取的图像数量,image_settings.caption 则请求在有相应信息时返回简短描述。包含 "image" 时,SDK 会自动请求 web_search_call.results。这些原始结果保存在 RunResult.raw_responses 的 web_search_call 项中,与助手消息分开存放,可能包含 image_url、source_website_url、thumbnail_url 和 caption。参见 OpenAI 的图像搜索结果指南。
Set search_content_types to include "image" when the web search should return images, and also include "text" when the model needs supporting text results. image_settings.max_results requests a positive number of image results, while image_settings.caption requests short descriptions when available. When "image" is present, the SDK automatically requests web_search_call.results. Those raw results are stored on the web_search_call item in RunResult.raw_responses, separately from the assistant message, and can include image_url, source_website_url, thumbnail_url, and caption. See the OpenAI image search results guide.
托管工具搜索
Hosted tool search
工具搜索允许 OpenAI Responses 模型将大量工具的加载推迟到运行时,使模型只加载当前轮次需要的那部分工具。如果你有很多函数工具、命名空间分组或托管 MCP 服务器,希望减少工具 schema 占用的 token,又不想一开始就暴露所有工具,这项功能很有用。
Tool search lets OpenAI Responses models defer large tool surfaces until runtime, so the model loads only the subset it needs for the current turn. This is useful when you have many function tools, namespace groups, or hosted MCP servers and want to reduce tool-schema tokens without exposing every tool up front.
如果构建 Agent 时就已经知道候选工具有哪些,可以先采用托管工具搜索。如果应用需要动态决定加载什么,Responses API 也支持由客户端执行的工具搜索,但标准 Runner 不会自动执行这种模式。
Start with hosted tool search when the candidate tools are already known when you build the agent. If your application needs to decide what to load dynamically, the Responses API also supports client-executed tool search, but the standard Runner does not auto-execute that mode.
需要了解的事项:
What to know:
- 托管工具搜索仅适用于 OpenAI Responses 模型。
- 为 Agent 配置延迟加载的工具集合时,必须且只能添加一个
ToolSearchTool()。 - 可搜索的工具集合包括
@function_tool(defer_loading=True)、tool_namespace(name=..., description=..., tools=[...])和HostedMCPTool(tool_config={..., "defer_loading": True})。 - 延迟加载的函数工具必须与
ToolSearchTool()配合使用。仅使用命名空间的配置也可以添加ToolSearchTool(),让模型按需加载合适的分组。 tool_namespace()将多个FunctionTool实例归入一个共享名称和描述的命名空间。当你有许多相互关联的工具时,例如crm、billing或shipping,这通常是最合适的做法。- OpenAI 的官方最佳实践是尽可能使用命名空间。
- 条件允许时,应优先使用命名空间或托管 MCP 服务器,而不是大量单独延迟加载的函数。它们通常能为模型提供更好的高层搜索入口,并节省更多 token。
- 命名空间可以混合即时可用和延迟加载的工具。未设置
defer_loading=True的工具仍然可以立即调用,同一命名空间中的延迟工具则通过工具搜索加载。 - 经验上应让每个命名空间保持较小规模,最好少于 10 个函数。
- 按名称指定的
tool_choice不能指向单纯的命名空间名称,也不能指向仅能延迟加载的工具。应优先使用auto、required,或真实的顶层可调用工具名称。 ToolSearchTool(execution="client")用于手动编排 Responses。如果模型发出由客户端执行的tool_search_call,标准Runner会抛出异常,而不会替你执行。- 工具搜索活动会以专用的条目和事件类型,出现在
RunResult.new_items和RunItemStreamEvent中。 examples/tools/tool_search.py提供了完整可运行示例,涵盖命名空间加载和顶层延迟工具。- 官方平台指南:工具搜索。
- Hosted tool search is available only with OpenAI Responses models.
- Add exactly one
ToolSearchTool()when you configure deferred-loading surfaces on an agent. - Searchable surfaces include
@function_tool(defer_loading=True),tool_namespace(name=..., description=..., tools=[...]), andHostedMCPTool(tool_config={..., "defer_loading": True}). - Deferred-loading function tools must be paired with
ToolSearchTool(). Namespace-only setups may also useToolSearchTool()to let the model load the right group on demand. tool_namespace()groupsFunctionToolinstances under a shared namespace name and description. This is usually the best fit when you have many related tools, such ascrm,billing, orshipping.- OpenAI's official best-practice guidance is Use namespaces where possible.
- Prefer namespaces or hosted MCP servers over many individually deferred functions when possible. They usually give the model a better high-level search surface and better token savings.
- Namespaces can mix immediate and deferred tools. Tools without
defer_loading=Trueremain callable immediately, while deferred tools in the same namespace are loaded through tool search. - As a rule of thumb, keep each namespace fairly small, ideally fewer than 10 functions.
- Named
tool_choicecannot target bare namespace names or deferred-only tools. Preferauto,required, or a real top-level callable tool name. ToolSearchTool(execution="client")is for manual Responses orchestration. If the model emits a client-executedtool_search_call, the standardRunnerraises instead of executing it for you.- Tool search activity appears in
RunResult.new_itemsand inRunItemStreamEventwith dedicated item and event types. - See
examples/tools/tool_search.pyfor complete runnable examples covering both namespaced loading and top-level deferred tools. - Official platform guide: Tool search.
程序化工具调用
Programmatic Tool Calling
程序化工具调用(Programmatic Tool Calling)让支持该功能的 OpenAI Responses 模型生成 JavaScript,调用符合条件的工具、组合其输出,并向模型返回一个结果。它适合边界明确、能从循环、分支、并行调用或中间计算中获益的工作流,无须在每次工具调用后都与模型往返交互。
Programmatic Tool Calling lets a supported OpenAI Responses model generate JavaScript that calls eligible tools, combines their outputs, and returns one result to the model. It is useful for bounded workflows that benefit from loops, branching, parallel calls, or intermediate calculations without a model round trip after every tool call.
生成的程序在一个全新的托管 V8 环境中运行。它没有 Node.js API、文件系统或网络访问能力,也没有持久进程。程序只能与明确获准使用的工具交互。
The generated program runs in a fresh hosted V8 environment. It does not have Node.js APIs, filesystem or network access, or a persistent process. The program can interact only with tools that you explicitly allow.
需要了解的事项:
What to know:
- 程序化工具调用仅适用于支持该功能的 OpenAI Responses 模型。Chat Completions 模型和非 Responses 后端会拒绝
ProgrammaticToolCallingTool()和tool_choice="programmatic_tool_calling"。 - 每个 Agent 最多添加一个
ProgrammaticToolCallingTool()。Agent 还必须暴露以下至少一种能力:至少一个可由程序调用的工具;一个由命名空间、延迟函数或延迟托管 MCP 服务器提供可搜索内容的ToolSearchTool();或者由提示词管理、对 SDK 不透明的工具集合。没有可搜索工具集合的单独ToolSearchTool()会被拒绝。 allowed_callers控制工具的调用方式。省略它时只允许模型直接调用。使用["programmatic"]只允许程序调用,使用["direct", "programmatic"]则允许两种方式。- 可以选择加入的 SDK 工具类型包括
FunctionTool、CustomTool、ShellTool、ApplyPatchTool、HostedMCPTool和CodeInterpreterTool。函数、自定义、shell 和 apply-patch 工具直接提供allowed_callers参数;托管 MCP 和代码解释器则需要在tool_config内设置allowed_callers。 - 对于
@function_tool(allowed_callers=[...]),Pydantic 模型、TypedDict 或 dataclass 等结构化返回类型注解会自动转为严格的对象输出 schema;在结果返回给程序前,会先按该 schema 验证返回值。函数没有可用的注解时,使用output_type=...;如果已有严格的对象 schema,可以使用更底层的output_json_schema={...}作为替代入口。output_type与output_json_schema互斥。返回类型注解为str、Any或None时,不会创建输出 schema。对于受 schema 约束、由程序发起的调用,默认的失败格式化函数会被禁用,因为它返回的自由格式文本不满足输出 schema。因此,处理函数抛出的异常会继续向上传播,除非你提供了能返回符合 schema 的 JSON 的自定义failure_error_function。 - 由程序发起的 SDK 工具调用仍然遵循正常的 Runner 生命周期。工具输入和输出护栏、钩子、超时、并发限制、审批、会话以及
RunState的暂停/恢复行为仍然适用,SDK 也会保留每个子调用与发起它的程序之间的关系。 - 只要存在
ProgrammaticToolCallingTool(),即便程序尚未执行,模型请求重试也会采用更严格的重放安全边界。SDK 会禁用这类请求由服务提供方管理的重试,以及 WebSocket 在收到事件前的重试。Runner 的重试策略只有在服务提供方的建议明确标记重放安全时才会重试;单独使用retry_policies.network_error()不会覆盖这一边界。 - 对审批敏感或影响较大的工具,通常更适合保留为直接调用,让人可以在每项操作成为更大程序的一部分之前逐项审查。如果程序发起的调用因审批而暂停,请照常通过
RunState处理这一中断,然后恢复原来的运行。 - 程序化工具调用可以与托管工具搜索结合使用。在生成的程序调用延迟工具前,模型必须先加载这些工具。
program项及其普通的、由程序发起的子工具调用会显示为ToolCallItem条目。对应的program_output会显示为ToolCallOutputItem。托管 MCP 的审批请求和工具目录则使用专用的 MCP 条目和流式事件。如何检查这些内容,参见结果和流式输出文档。examples/tools/programmatic_tool_calling.py提供了完整的并发库存规划示例。- 官方平台指南:程序化工具调用。
- Programmatic Tool Calling is available only with supported OpenAI Responses models.
ProgrammaticToolCallingTool()andtool_choice="programmatic_tool_calling"are rejected by Chat Completions models and non-Responses backends. - Add at most one
ProgrammaticToolCallingTool()to an agent. The agent must also expose at least one programmatically callable tool, aToolSearchTool()backed by a namespace, deferred function, or deferred hosted MCP server, or an opaque prompt-managed tool surface. A bareToolSearchTool()without a searchable surface is rejected. allowed_callerscontrols how a tool may be invoked. Omitting it allows direct model calls only. Use["programmatic"]for program-only access or["direct", "programmatic"]to allow both.- SDK tool types that can opt in are
FunctionTool,CustomTool,ShellTool,ApplyPatchTool,HostedMCPTool, andCodeInterpreterTool. Function, custom, shell, and apply-patch tools exposeallowed_callersdirectly. For hosted MCP and code interpreter, setallowed_callersinsidetool_config. - For
@function_tool(allowed_callers=[...]), a structured return annotation such as a Pydantic model, TypedDict, or dataclass automatically becomes a strict object output schema, and the returned value is validated against that schema before it is returned to the program. Useoutput_type=...when the function has no usable annotation, or the lower-leveloutput_json_schema={...}escape hatch when you already have a strict object schema.output_typeandoutput_json_schemaare mutually exclusive. Return annotations ofstr,Any, orNonedo not create an output schema. For a schema-backed program-owned call, the default failure formatter is disabled because its free-form text does not satisfy the output schema. A handler exception therefore propagates unless you provide a customfailure_error_functionthat returns schema-conforming JSON. - Program-owned SDK tools still use the normal Runner lifecycle. Tool input and output guardrails, hooks, timeouts, concurrency limits, approvals, sessions, and
RunStatepause/resume behavior continue to apply, and the SDK preserves each child call's program caller relationship. - Model-request retries use a stricter replay-safety boundary whenever
ProgrammaticToolCallingTool()is present, even before a program executes. The SDK disables provider-managed retries and WebSocket pre-event retries for these requests. A Runner retry policy retries only when provider advice explicitly marks the replay safe;retry_policies.network_error()by itself does not override this boundary. - Approval-sensitive or high-impact tools are usually better kept as direct calls so a person can review each action before it becomes part of a larger program. If a program-owned call pauses for approval, resolve the interruption through
RunStateand resume the original run as usual. - Programmatic Tool Calling can be combined with hosted tool search. The model must load deferred tools before a generated program can call them.
- A
programitem and its ordinary program-owned child tool calls appear asToolCallItementries. The matchingprogram_outputappears as aToolCallOutputItem. Hosted MCP approval requests and tool catalogs use specialized MCP items and stream events instead. See Results and Streaming for inspection details. - See
examples/tools/programmatic_tool_calling.pyfor a complete concurrent inventory-planning example. - Official platform guide: Programmatic Tool Calling.
托管容器 shell 与技能
Hosted container shell + skills
ShellTool 也支持在 OpenAI 托管容器中执行。如果你希望模型在托管容器而非本地运行时中执行 shell 命令,可以使用这种模式。
ShellTool also supports OpenAI-hosted container execution. Use this mode when you want the model to run shell commands in a managed container instead of your local runtime.
要在后续运行中复用已有容器,请设置 environment={"type": "container_reference", "container_id": "cntr_..."}。
To reuse an existing container in later runs, set environment={"type": "container_reference", "container_id": "cntr_..."}.
需要了解的事项:
What to know:
- 托管 shell 通过 Responses API 的 shell 工具提供。
container_auto为请求创建容器;container_reference复用已有容器。container_auto还可以包含file_ids和memory_limit。environment.skills接受技能引用和内联技能包。- 使用托管环境时,不要在
ShellTool上设置executor、needs_approval或on_approval。 network_policy支持disabled和allowlist两种模式。- 在允许列表模式下,
network_policy.domain_secrets可以按名称注入限定于特定域名的密钥。 examples/tools/container_shell_skill_reference.py和examples/tools/container_shell_inline_skill.py提供了完整示例。- OpenAI 平台指南:Shell 和 Skills。
- Hosted shell is available through the Responses API shell tool.
container_autoprovisions a container for the request;container_referencereuses an existing one.container_autocan also includefile_idsandmemory_limit.environment.skillsaccepts skill references and inline skill bundles.- With hosted environments, do not set
executor,needs_approval, oron_approvalonShellTool. network_policysupportsdisabledandallowlistmodes.- In allowlist mode,
network_policy.domain_secretscan inject domain-scoped secrets by name. - See
examples/tools/container_shell_skill_reference.pyandexamples/tools/container_shell_inline_skill.pyfor complete examples. - OpenAI platform guides: Shell and Skills.
本地运行时工具
Local runtime tools
本地运行时工具在模型响应之外执行。模型仍然决定何时调用它们,但实际工作由你的应用或配置好的执行环境完成。
Local runtime tools execute outside the model response itself. The model still decides when to call them, but your application or configured execution environment performs the actual work.
ComputerTool 和 ApplyPatchTool 始终需要你提供本地实现。ShellTool 横跨两种模式:需要托管执行时,使用上面的托管容器配置;希望命令在自己的进程中运行时,使用下面的本地运行时配置。
ComputerTool and ApplyPatchTool always require local implementations that you provide. ShellTool spans both modes: use the hosted-container configuration above when you want managed execution, or the local runtime configuration below when you want commands to run in your own process.
本地运行时工具需要你提供实现:
Local runtime tools require you to supply implementations:
ComputerTool:实现Computer或AsyncComputer接口,以启用图形界面/浏览器自动化。ShellTool:最新的 shell 工具,同时支持本地执行和托管容器执行。LocalShellTool:旧版的本地 shell 集成。ApplyPatchTool:实现ApplyPatchEditor,以在本地应用差异补丁。- 使用
ShellTool(environment={"type": "local", "skills": [...]})可以启用本地 shell 技能。
ComputerTool: implement theComputerorAsyncComputerinterface to enable GUI/browser automation.ShellTool: the latest shell tool for both local execution and hosted container execution.LocalShellTool: legacy local-shell integration.ApplyPatchTool: implementApplyPatchEditorto apply diffs locally.- Local shell skills are available with
ShellTool(environment={"type": "local", "skills": [...]}).
Shell 操作的有限超时值使用正整数毫秒。调用本地 ShellTool 执行器前,SDK 会把 0 和 None 都视为未明确设置超时,因为零在不同执行器实现中的含义并不一致;其他值会在执行器调用前被拒绝。这一规则只针对超时字段:max_output_length=0 仍然是有效设置,表示捕获的输出为空。
Shell action timeouts use positive integer milliseconds for a finite timeout. The SDK treats both 0 and None as no explicit timeout before calling a local ShellTool executor because zero does not have a portable meaning across executor implementations; other values are rejected before executor invocation. This is specific to the timeout field: max_output_length=0 remains a supported request for empty captured output.
本地 shell 与文件编辑的审批
Approval for local shell and file edits
本地 ShellTool 和 ApplyPatchTool 默认设置为 needs_approval=False。采用这个设置时,SDK 可以不请求审批就调用你的执行器或编辑器。命令在哪里运行、文件在哪里更改,由你的实现决定;预期的资源权限和隔离也必须由你的实现落实。SDK 的审批并不提供沙箱。
Local ShellTool and ApplyPatchTool default to needs_approval=False. With this setting, the SDK can invoke your executor or editor without requesting approval. Your implementation determines where commands run or files change and must enforce the intended resource permissions and isolation; SDK approval does not provide a sandbox.
如果命令或文件编辑需要审查,请在工具上设置 needs_approval=True,或提供一个可调用的策略,让它对需要审批的调用返回 True。没有 on_approval 回调时,运行会在调用执行器或编辑器之前暂停,并在 result.interruptions 中返回待处理请求。通过 RunState 批准或拒绝这些请求,再按照人在回路指南中的说明恢复运行。
For commands or file edits that require review, set needs_approval=True on the tool, or provide a callable policy that returns True for calls that require approval. Without an on_approval callback, the run pauses before invoking the executor or editor and returns pending requests in result.interruptions. Approve or reject those requests through RunState, then resume the run as described in the human-in-the-loop guide.
如果要在应用代码中立即作出决定,请同时设置 needs_approval 和 on_approval。只有调用需要审批且尚无审批决定时,SDK 才会调用 on_approval;单独设置这个回调不会启用审批。命令行提示示例见 examples/tools/shell.py,手动处理中断的示例见 examples/tools/shell_human_in_the_loop.py。相比之下,examples/tools/apply_patch.py 示例在编辑器内部、更改文件之前发出提示。
To decide immediately in application code, set both needs_approval and on_approval. The SDK invokes on_approval only when the call requires approval and has no existing approval decision; setting the callback alone does not enable approval. See examples/tools/shell.py for a CLI prompt and examples/tools/shell_human_in_the_loop.py for manual interruption handling. The examples/tools/apply_patch.py example instead prompts inside its editor before changing files.
如果应用有意授权自动执行,例如通过执行器落实沙箱策略,那么应保留 needs_approval=False。托管 shell 环境不支持 SDK 的本地 needs_approval 或 on_approval 设置。
Keep needs_approval=False when your application intentionally authorizes automatic execution, for example through an executor that enforces your sandbox policy. Hosted shell environments do not support the SDK's local needs_approval or on_approval settings.
ComputerTool 与 Responses 的计算机工具
ComputerTool and the Responses computer tool
ComputerTool 仍然是一个本地运行框架:你提供 Computer 或 AsyncComputer 实现,SDK 再将这套运行框架映射到 OpenAI Responses API 的计算机工具接口。
ComputerTool is still a local harness: you provide a Computer or AsyncComputer implementation, and the SDK maps that harness onto the OpenAI Responses API computer surface.
当 Agent 未设置 model 时,SDK 会按正常的模型选择优先级处理。SDK 内置的默认模型目前是 gpt-5.6-luna,支持计算机使用。如果 OPENAI_DEFAULT_MODEL 或 RunConfig.model 覆盖了这个默认值,请选择支持计算机使用的模型。如果希望针对计算机使用任务选择不同的能力和成本组合,可以在 Agent 上设置 model。下面的示例使用 gpt-5.6 别名,OpenAI 会将其路由到 GPT-5.6 Sol;你也可以选择其他支持计算机使用的模型,例如 GPT-5.6 Terra 或 GPT-5.6 Luna。
When an Agent does not set model, normal SDK model-selection precedence applies. The built-in SDK default, currently gpt-5.6-luna, supports computer use. If OPENAI_DEFAULT_MODEL or RunConfig.model overrides that default, select a model that supports computer use. Set model on the agent when you want to choose a different capability and cost profile for the computer-use workload. The example below uses the gpt-5.6 alias, which OpenAI routes to GPT-5.6 Sol; you can instead select another model that supports computer use, such as GPT-5.6 Terra or GPT-5.6 Luna.
对于明确指定支持正式版内置计算机工具的模型(如 gpt-5.6)的请求,SDK 发送 {"type": "computer"} 载荷。对于旧版 computer-use-preview 模型,SDK 仍然发送预览版载荷 {"type": "computer_use_preview", "environment": ..., "display_width": ..., "display_height": ...}。这与平台的从 computer-use-preview 迁移方案一致:
For explicit requests to a model that supports the GA built-in computer tool, such as gpt-5.6, the SDK sends the payload {"type": "computer"}. For requests to the older computer-use-preview model, the SDK continues to send the preview payload {"type": "computer_use_preview", "environment": ..., "display_width": ..., "display_height": ...}. This mirrors the platform's migration from computer-use-preview:
- 模型:
computer-use-preview→gpt-5.6-sol - 工具选择器:
computer_use_preview→computer - 计算机调用结构:每个
computer_call中包含单个action→computer_call中包含批量actions[] - 截断:预览版路径要求
ModelSettings(truncation="auto")→ 正式版路径不再要求
- Model:
computer-use-preview->gpt-5.6-sol - Tool selector:
computer_use_preview->computer - Computer call shape: one
actionpercomputer_call-> batchedactions[]oncomputer_call - Truncation:
ModelSettings(truncation="auto")required on the preview path -> not required on the GA path
SDK 根据实际 Responses 请求最终采用的模型,选择这种传输格式。如果你使用提示词模板,并因为模型由提示词指定而在请求中省略 model,SDK 会保留兼容预览版的计算机工具载荷;除非你明确指定受支持的正式版模型,例如 model="gpt-5.6",或者通过 ModelSettings(tool_choice="computer") 或 ModelSettings(tool_choice="computer_use") 强制使用正式版选择器。
The SDK chooses that wire shape from the effective model on the actual Responses request. If you use a prompt template and the request omits model because the prompt owns it, the SDK keeps the preview-compatible computer payload unless you either make a supported GA model such as model="gpt-5.6" explicit or force the GA selector with ModelSettings(tool_choice="computer") or ModelSettings(tool_choice="computer_use").
存在 ComputerTool 时,tool_choice="computer"、"computer_use" 和 "computer_use_preview" 都会被接受,并被归一化为与请求实际采用的模型匹配的内置选择器。没有 ComputerTool 时,这些字符串仍然被当作普通函数名称。
When a ComputerTool is present, tool_choice="computer", "computer_use", and "computer_use_preview" are all accepted and normalized to the built-in selector that matches the effective request model. Without a ComputerTool, those strings still behave like ordinary function names.
当 ComputerTool 由 ComputerProvider 工厂提供实例时,这个区别很重要。正式版 computer 载荷在序列化时不需要 environment 或屏幕尺寸,因此可以在工厂创建 Computer 或 AsyncComputer 实例之前完成序列化。兼容预览版的序列化仍然需要一个已经解析得到的 Computer 或 AsyncComputer 实例,以便 SDK 发送 environment、display_width 和 display_height。
This distinction matters when ComputerTool is backed by a ComputerProvider factory. The GA computer payload does not need environment or dimensions at serialization time, so serialization can occur before a factory has produced a Computer or AsyncComputer instance. Preview-compatible serialization still needs a resolved Computer or AsyncComputer instance so the SDK can send environment, display_width, and display_height.
运行时,两条路径仍然使用同一套本地运行框架。预览版响应会发出包含单个 action 的 computer_call 项;正式版响应可以发出批量 actions[],SDK 会依次执行这些操作,然后生成 computer_call_output 截图项。examples/tools/computer_use.py 提供了基于 Playwright 的可运行框架。
At runtime, both paths still use the same local harness. Preview responses emit computer_call items with a single action; GA responses can emit batched actions[], and the SDK executes them in order before producing a computer_call_output screenshot item. See examples/tools/computer_use.py for a runnable Playwright-based harness.
待处理的计算机安全检查
Pending computer safety checks
Responses API 可以在 computer_call 中包含 pending_safety_checks,标记需要应用审查的问题。每项检查都有一个 id,以及可选的 code 和 message 字段,用于描述问题类型并提供详细信息。这些检查来自 API,Agents SDK 会把它们传给你的回调。关于 pending_safety_checks 和 acknowledged_safety_checks,参见 Responses API 参考文档;应用层面的预防措施,参见计算机使用安全指南。
The Responses API can include pending_safety_checks in a computer_call to flag concerns for your application to review. Each check has an id and optional code and message fields that describe the type of concern and provide details. These checks come from the API; the Agents SDK passes them to your callback. See the Responses API reference for pending_safety_checks and acknowledged_safety_checks, and the computer-use safety guidance for application-level precautions.
配置 ComputerTool.on_safety_check,以决定是否继续执行被标记的计算机调用。只有调用包含待处理检查时,SDK 才会在执行其操作之前调用这个回调。
Configure ComputerTool.on_safety_check to decide whether to proceed with a flagged computer call. The SDK invokes this callback only when the call includes pending checks, before executing the call's actions.
回调每次接收一个 ComputerToolSafetyCheckData。返回 True 表示确认该项检查;返回 False 则会在执行该调用的操作或截图之前抛出 UserError。配置了回调时,SDK 要求所有报告的检查都得到确认。回调可以是同步或异步的。
The callback receives one ComputerToolSafetyCheckData at a time. Return True to acknowledge that check. Return False to raise UserError before the call's actions or screenshot execute. The SDK requires all reported checks to be acknowledged when a callback is configured. The callback can be synchronous or asynchronous.
如果省略 on_safety_check,SDK 会继续执行,并让这些检查保持未确认状态。SDK 不会自动提示人工处理。如果应用要求审查被标记的调用,请明确配置回调。例如,下面这项保守策略会拒绝所有被标记的调用:
If on_safety_check is omitted, the SDK proceeds with execution and leaves the checks unacknowledged. The SDK does not prompt a person automatically. Configure the callback explicitly when your application requires review of flagged calls. For example, this conservative policy rejects every flagged call:
要允许经过审查的调用,请将 reject_flagged_call 替换为这样的回调:把 data.safety_check 和拟执行的 data.tool_call 展示给应用的审查人员,等待决定,再返回该决定。未知的检查代码也应被视为需要审查。
To allow reviewed calls, replace reject_flagged_call with a callback that presents data.safety_check and the proposed data.tool_call to your application's reviewer, waits for a decision, and returns that decision. Treat unknown check codes as requiring review as well.
不含待处理检查的计算机调用不会触发这个回调。如果某项策略必须适用于每一个计算机操作,请在计算机运行框架中落实。要收集人工决定,回调必须自行安排交互并返回决定;SDK 不会填充 RunResult.interruptions,也不会使用人在回路文档描述的暂停和恢复流程。
Computer calls without pending checks do not invoke this callback. Enforce any policy that must apply to every computer action in your computer harness. To collect a person's decision, your callback must arrange that interaction and return the decision; the SDK does not populate RunResult.interruptions or use the pause-and-resume flow described in Human-in-the-loop.
函数工具
Function tools
任意 Python 函数都可以用作工具。Agents SDK 会自动完成工具配置:
You can use any Python function as a tool. The Agents SDK will set up the tool automatically:
- 工具名称取自 Python 函数名称,也可以由你自行指定。
- 工具描述取自函数的文档字符串,也可以由你自行提供。
- 函数输入的 schema 会根据函数参数自动创建。
- 除非禁用,各个输入的描述会取自函数的文档字符串。
- The name of the tool will be the name of the Python function (or you can provide a name)
- Tool description will be taken from the docstring of the function (or you can provide a description)
- The schema for the function inputs is automatically created from the function's arguments
- Descriptions for each input are taken from the docstring of the function, unless disabled
通过 @tool 创建的工具,会通过只读的 __wrapped__ 属性暴露原始 Python 可调用对象。这有助于检查和测试,但直接调用它会绕过工具运行时的处理流程,包括 schema 验证、上下文注入、护栏、超时、失败处理和执行轨迹记录。手动构建的 FunctionTool 实例不会暴露 __wrapped__。
Tools created by @tool expose the original Python callable through the read-only __wrapped__ attribute. This is useful for inspection and testing, but calling it directly bypasses the tool runtime pipeline, including schema validation, context injection, guardrails, timeouts, failure handling, and tracing. Hand-built FunctionTool instances do not expose __wrapped__.
我们使用 Python 的 inspect 模块提取函数签名,使用 griffe 解析文档字符串,并使用 pydantic 创建 schema。
We use Python's inspect module to extract the function signature, along with griffe to parse docstrings and pydantic for schema creation.
使用 OpenAI Responses 模型时,@function_tool(defer_loading=True) 会隐藏函数工具,直到 ToolSearchTool() 将它加载。你也可以通过 tool_namespace() 对相关函数工具分组。完整配置及约束见托管工具搜索。
When you are using OpenAI Responses models, @function_tool(defer_loading=True) hides a function tool until ToolSearchTool() loads it. You can also group related function tools with tool_namespace(). See Hosted tool search for the full setup and constraints.
- 函数参数可以使用任意 Python 类型,函数也可以是同步或异步的。
- 如果存在文档字符串,就会从中提取函数描述和参数描述。
- 函数可以选择将运行上下文作为第一个参数。你还可以覆盖工具名称、描述、采用的文档字符串风格等设置。
- 可以把装饰后的函数传入工具列表。
- You can use any Python types as arguments to your functions, and the function can be sync or async.
- Docstrings, if present, are used to capture descriptions and argument descriptions
- Functions can optionally take the run context as their first argument. You can also set overrides, like the name of the tool, description, which docstring style to use, etc.
- You can pass the decorated functions to the list of tools.
展开查看输出
Expand to see output
从函数工具返回图像或文件
Returning images or files from function tools
除了返回文本,还可以把一张或多张图像、一个或多个文件作为函数工具的输出。为此,你可以返回以下任意类型:
In addition to returning text outputs, you can return one or many images or files as the output of a function tool. To do so, you can return any of:
- 图像:
ToolOutputImage,或其 TypedDict 版本ToolOutputImageDict。 - 文件:
ToolOutputFileContent,或其 TypedDict 版本ToolOutputFileContentDict。 - 文本:字符串、可转为字符串的对象,或
ToolOutputText(也可以使用其 TypedDict 版本ToolOutputTextDict)。
- Images:
ToolOutputImage(or the TypedDict version,ToolOutputImageDict) - Files:
ToolOutputFileContent(or the TypedDict version,ToolOutputFileContentDict) - Text: either a string or stringable objects, or
ToolOutputText(or the TypedDict version,ToolOutputTextDict)
自定义函数工具
Custom function tools
有时,你并不想使用 Python 函数作为工具。如果愿意,可以直接创建 FunctionTool。你需要提供:
Sometimes, you don't want to use a Python function as a tool. You can directly create a FunctionTool if you prefer. You'll need to provide:
namedescriptionparams_json_schema,即参数的 JSON schema。on_invoke_tool,这是一个异步函数,接收ToolContext和 JSON 字符串形式的参数,并返回工具输出,例如文本、结构化工具输出对象或输出列表。
namedescriptionparams_json_schema, which is the JSON schema for the argumentson_invoke_tool, which is an async function that receives aToolContextand the arguments as a JSON string, and returns tool output (for example, text, structured tool output objects, or a list of outputs).
自动解析参数和文档字符串
Automatic argument and docstring parsing
如前所述,我们会自动解析函数签名来提取工具的 schema,并解析文档字符串,提取工具本身及各个参数的描述。需要说明的是:
As mentioned before, we automatically parse the function signature to extract the schema for the tool, and we parse the docstring to extract descriptions for the tool and for individual arguments. Some notes on that:
- 签名解析通过
inspect模块完成。我们利用类型注解理解参数类型,并动态构建 Pydantic 模型来表示整体 schema。它支持大多数类型,包括 Python 基本类型、Pydantic 模型、TypedDict 等。 - 我们使用
griffe解析文档字符串,支持google、sphinx和numpy格式。我们会尽力自动检测格式,但并不保证总能识别;调用function_tool时也可以明确设置格式。将use_docstring_info设为False可以禁用文档字符串解析。对于 Google 风格的文档字符串,解析器也接受紧接在摘要文本后、两者之间没有空行的Args:、Arguments:、Params:或Parameters:小节。
- The signature parsing is done via the
inspectmodule. We use type annotations to understand the types for the arguments, and dynamically build a Pydantic model to represent the overall schema. It supports most types, including Python primitives, Pydantic models, TypedDicts, and more. - We use
griffeto parse docstrings. Supported docstring formats aregoogle,sphinxandnumpy. We attempt to automatically detect the docstring format, but this is best-effort and you can explicitly set it when callingfunction_tool. You can also disable docstring parsing by settinguse_docstring_infotoFalse. For Google-style docstrings, the parser also accepts anArgs:,Arguments:,Params:, orParameters:section immediately after summary text without an intervening blank line.
schema 提取代码位于 agents.function_schema。
The code for the schema extraction lives in agents.function_schema.
使用 Pydantic Field 约束和描述参数
Constraining and describing arguments with Pydantic Field
可以使用 Pydantic 的 Field 为工具参数添加约束,例如数字的最小值/最大值、字符串长度或匹配模式,也可以添加描述。与 Pydantic 一样,两种写法都受支持:基于默认值的写法(arg: int = Field(..., ge=1))和 Annotated 写法(arg: Annotated[int, Field(..., ge=1)])。生成的 JSON schema 和验证过程都会包含这些约束。
You can use Pydantic's Field to add constraints (e.g. min/max for numbers, length or pattern for strings) and descriptions to tool arguments. As in Pydantic, both forms are supported: default-based (arg: int = Field(..., ge=1)) and Annotated (arg: Annotated[int, Field(..., ge=1)]). The generated JSON schema and validation include these constraints.
对于可变参数,注解描述的是收集到的每一个值。因此,SDK 会将 Annotated[..., Field(...)] 约束应用于通过 *args 或 **kwargs 传入的每个值;没有传入可变参数时,空集合仍然有效。
For variadic parameters, an annotation describes each collected value. The SDK therefore applies Annotated[..., Field(...)] constraints to each value supplied through *args or **kwargs, while omitted variadic parameters remain valid empty collections.
SDK 会忽略可变参数(*args 或 **kwargs)注解中的 Field(description=...)。要描述这个收集参数,请在函数文档字符串中添加对应参数条目,或在 Annotated 中使用字符串,例如 *scores: Annotated[int, "Exam scores", Field(ge=0, le=100)]。如果启用了文档字符串解析,且两个来源都提供描述,则优先使用文档字符串中的描述。
The SDK ignores Field(description=...) in the annotation of a variadic parameter (*args or **kwargs). To describe the collected parameter, use a parameter entry in the function docstring or a string in Annotated, for example *scores: Annotated[int, "Exam scores", Field(ge=0, le=100)]. When docstring parsing is enabled and both sources provide a description, the docstring description takes precedence.
对于 **kwargs,使用 @tool(strict_mode=False),并把关键字值放入以该参数命名的嵌套对象中。例如,带有 **scores: int 的工具接收 {"scores": {"exam": 90}}。
For **kwargs, use @tool(strict_mode=False) and supply the keyword values in the nested object named after the parameter. For example, a tool with **scores: int receives {"scores": {"exam": 90}}.
标量位置参数应注解为 *args: T。如果每个位置参数本身都是同质元组,使用 *args: tuple[T, ...];SDK 会拒绝 *args: tuple[int, str] 这类定长元组注解,因为一种固定的元组结构无法描述长度可变的位置参数序列。
Annotate scalar positional values as *args: T. If each positional value is itself a homogeneous tuple, use *args: tuple[T, ...]; the SDK rejects fixed-length tuple annotations such as *args: tuple[int, str] because one fixed tuple shape cannot describe a variadic sequence of positional values.
函数工具超时
Function tool timeouts
可以通过 @function_tool(timeout=...) 为异步函数工具设置每次调用的超时时间。
You can set per-call timeouts for async function tools with @function_tool(timeout=...).
达到超时时间后,默认行为是 timeout_behavior="error_as_result",即向模型发送一条可见的超时消息,例如 Tool 'slow_lookup' timed out after 2 seconds.。
When a timeout is reached, the default behavior is timeout_behavior="error_as_result", which sends a model-visible timeout message (for example, Tool 'slow_lookup' timed out after 2 seconds.).
你可以控制超时的处理方式:
You can control timeout handling:
timeout_behavior="error_as_result"(默认):向模型返回超时消息,让模型有机会恢复。timeout_behavior="raise_exception":抛出ToolTimeoutError,并使运行失败。timeout_error_function=...:在使用error_as_result时自定义超时消息。
timeout_behavior="error_as_result"(default): return a timeout message to the model so it can recover.timeout_behavior="raise_exception": raiseToolTimeoutErrorand fail the run.timeout_error_function=...: customize the timeout message when usingerror_as_result.
注意
Note
超时配置仅支持异步的 @function_tool 处理函数。
Timeout configuration is supported only for async @function_tool handlers.
处理函数工具中的错误
Handling errors in function tools
通过 @function_tool 创建函数工具时,可以传入 failure_error_function。当工具调用崩溃时,这个函数负责向大语言模型提供错误响应。
When you create a function tool via @function_tool, you can pass a failure_error_function. This is a function that provides an error response to the LLM in case the tool call crashes.
- 默认情况下,也就是不传入任何值时,会运行
default_tool_error_function,告知大语言模型发生了错误。 - 如果传入自己的错误函数,就会改为运行该函数,并将响应发送给大语言模型。
- 如果明确传入
None,所有工具调用错误都会被重新抛出,交由你处理。例如,模型生成无效 JSON 时可能出现ModelBehaviorError,你的代码崩溃时可能出现UserError,等等。
- By default (i.e. if you don't pass anything), it runs a
default_tool_error_functionwhich tells the LLM an error occurred. - If you pass your own error function, it runs that instead, and sends the response to the LLM.
- If you explicitly pass
None, then any tool call errors will be re-raised for you to handle. This could be aModelBehaviorErrorif the model produced invalid JSON, or aUserErrorif your code crashed, etc.
如果手动创建 FunctionTool 对象,就必须在 on_invoke_tool 函数内部处理错误。
If you are manually creating a FunctionTool object, then you must handle errors inside the on_invoke_tool function.
将 Agent 用作工具
Agents as tools
在某些工作流中,你可能希望由一个中央 Agent 编排一组专门化 Agent,而不是移交控制权。可以通过将 Agent 建模为工具来实现。
In some workflows, you may want a central agent to orchestrate a network of specialized agents, instead of handing off control. You can do this by modeling agents as tools.
定制作为工具的 Agent
Customizing tool-agents
agent.as_tool 是将 Agent 转为工具的便捷方法。它支持常用运行时选项,包括 max_turns、run_config、hooks、previous_response_id、conversation_id、session 和 needs_approval。它也通过 parameters、input_builder 和 include_input_schema 支持结构化输入。
agent.as_tool is a convenience method for turning an agent into a tool. It supports common runtime options such as max_turns, run_config, hooks, previous_response_id, conversation_id, session, and needs_approval. It also supports structured input with parameters, input_builder, and include_input_schema.
这些状态选项配置的是工具调用所启动的嵌套 Agent 运行;父级运行的对话状态不会自动继承。要在父级和嵌套运行之间共享由客户端管理的历史记录,请明确向两者传入同一个 session。与 Runner.run 一样,应为嵌套运行选择一种状态策略:由客户端管理的 session,或通过 previous_response_id 或 conversation_id 实现的服务端续接。
The state options configure the nested agent run started by the tool call; the parent run's conversation state is not inherited automatically. To share client-managed history between the parent and nested runs, explicitly pass the same session to both. As with Runner.run, choose one state strategy for the nested run: a client-managed session, or server-managed continuation through previous_response_id or conversation_id.
作为工具的 Agent 的结构化输入
Structured input for tool-agents
默认情况下,Agent.as_tool() 期望接收只含一个字符串字段 input 的对象({"input": "..."});但你可以传入 parameters(Pydantic 模型类型或 dataclass 类型),暴露一个结构化 schema。
By default, Agent.as_tool() expects an object with one string field, input ({"input": "..."}), but you can expose a structured schema by passing parameters (a Pydantic model type or a dataclass type).
其他选项:
Additional options:
include_input_schema=True会在生成的嵌套输入中包含完整的 JSON Schema。input_builder=...让你完全定制结构化工具参数如何转换为嵌套 Agent 的输入。- 嵌套运行上下文中的
RunContextWrapper.tool_input包含已解析的结构化载荷。
include_input_schema=Trueincludes the full JSON Schema in the generated nested input.input_builder=...lets you fully customize how structured tool arguments become nested agent input.RunContextWrapper.tool_inputcontains the parsed structured payload inside the nested run context.
完整可运行示例见 examples/agent_patterns/agents_as_tools_structured.py。
See examples/agent_patterns/agents_as_tools_structured.py for a complete runnable example.
作为工具的 Agent 的审批关卡
Approval gates for tool-agents
Agent.as_tool(..., needs_approval=...) 使用与 function_tool 相同的审批流程。如果需要审批,运行会暂停,待处理项出现在 result.interruptions 中;随后使用 result.to_state(),并在调用 state.approve(...) 或 state.reject(...) 后恢复运行。完整的暂停/恢复模式见人在回路指南。
Agent.as_tool(..., needs_approval=...) uses the same approval flow as function_tool. If approval is required, the run pauses and pending items appear in result.interruptions; then use result.to_state() and resume after calling state.approve(...) or state.reject(...). See the Human-in-the-loop guide for the full pause/resume pattern.
自定义输出提取
Custom output extraction
在某些情况下,你可能希望在将作为工具的 Agent 的输出返回给中央 Agent 之前对其进行修改。如果希望完成以下操作,这样做会很有用:
In certain cases, you might want to modify the output of the tool-agents before returning it to the central agent. This may be useful if you want to:
- 从子 Agent 的聊天历史中提取某条特定信息,例如 JSON 载荷。
- 转换或重新格式化 Agent 的最终回答,例如把 Markdown 转成纯文本或 CSV。
- 验证输出,或在 Agent 响应缺失或格式有误时提供兜底值。
- Extract a specific piece of information (e.g., a JSON payload) from the sub-agent's chat history.
- Convert or reformat the agent’s final answer (e.g., transform Markdown into plain text or CSV).
- Validate the output or provide a fallback value when the agent’s response is missing or malformed.
可以通过向 as_tool 方法提供 custom_output_extractor 参数来实现:
You can do this by supplying the custom_output_extractor argument to the as_tool method:
在自定义提取器中,嵌套的 RunResult 还会暴露 agent_tool_invocation。如果你在后处理嵌套结果时需要外层工具名称、调用 ID 或原始参数,这个属性会很有用。参见结果指南。
Inside a custom extractor, the nested RunResult also exposes agent_tool_invocation, which is useful when you need the outer tool name, call ID, or raw arguments while post-processing the nested result. See the Results guide.
嵌套 Agent 运行的流式输出
Streaming nested agent runs
向 as_tool 传入 on_stream 回调,可以监听嵌套 Agent 发出的流式事件,同时仍在流结束后返回其最终输出。
Pass an on_stream callback to as_tool to listen to streaming events emitted by the nested agent while still returning its final output once the stream completes.
预期行为:
What to expect:
- 事件类型与
StreamEvent["type"]一致:raw_response_event、run_item_stream_event、agent_updated_stream_event。 - 提供
on_stream会自动以流式模式运行嵌套 Agent,并在返回最终输出前消费完流。 - 处理函数可以同步或异步;每个事件在到达时按顺序传递。
- 通过模型工具调用来调用工具时,会提供
tool_call;直接调用时它可能为None。 - 完整可运行示例见
examples/agent_patterns/agents_as_tools_streaming.py。
- Event types mirror
StreamEvent["type"]:raw_response_event,run_item_stream_event,agent_updated_stream_event. - Providing
on_streamautomatically runs the nested agent in streaming mode and drains the stream before returning the final output. - The handler may be synchronous or asynchronous; each event is delivered in order as it arrives.
tool_callis present when the tool is invoked via a model tool call; direct calls may leave itNone.- See
examples/agent_patterns/agents_as_tools_streaming.pyfor a complete runnable sample.
有条件地启用工具
Conditional tool enabling
可以使用 is_enabled 参数,在运行时有条件地启用或禁用 Agent 工具。这样就能根据上下文、用户偏好或运行时条件,动态筛选大语言模型可用的工具。
You can conditionally enable or disable agent tools at runtime using the is_enabled parameter. This allows you to dynamically filter which tools are available to the LLM based on context, user preferences, or runtime conditions.
is_enabled 参数接受:
The is_enabled parameter accepts:
- 布尔值:
True(始终启用)或False(始终禁用)。 - 可调用函数:接收
(context, agent)并返回布尔值的函数。 - 异步函数:用于复杂条件逻辑的异步函数。
- Boolean values:
True(always enabled) orFalse(always disabled) - Callable functions: Functions that take
(context, agent)and return a boolean - Async functions: Async functions for complex conditional logic
被禁用的工具会在运行时对大语言模型完全隐藏,因此适合用于:
Disabled tools are completely hidden from the LLM at runtime, making this useful for:
- 限定在单个请求范围内的能力可见性。
- 按环境控制工具可用性,例如开发环境与生产环境。
- 对不同工具配置进行 A/B 测试。
- 根据运行时状态动态筛选工具。
- Request-scoped capability visibility
- Environment-specific tool availability (dev vs prod)
- A/B testing different tool configurations
- Dynamic tool filtering based on runtime state
对于在本地配置的函数工具,runner 还会在调用前重新评估 is_enabled。不过,is_enabled 控制的是可见性和调用分发,不能代替依赖工具参数或所访问资源的授权检查。应在工具实现内部落实这些检查,或在适当时使用工具输入护栏和审批。MCP 服务器必须自行对受保护的操作进行授权。
For locally configured function tools, the runner also reevaluates is_enabled before invocation. However, is_enabled controls visibility and dispatch; it does not replace authorization that depends on the tool arguments or the resource being accessed. Enforce those checks inside the tool implementation, or use tool input guardrails and approvals when appropriate. MCP servers must authorize their own protected operations.
参见上下文管理,其中介绍了如何将同一项应用策略统一应用于函数工具、MCP 工具和控制权移交。
See context management for a pattern that applies one application policy across function tools, MCP tools, and handoffs.
实验性功能:Codex 工具
Experimental: Codex tool
codex_tool 封装了 Codex CLI,让 Agent 能在一次工具调用中执行限定于工作区范围的任务,包括 shell、文件编辑和 MCP 工具操作。这个接口仍处于实验阶段,可能发生变化。
The codex_tool wraps the Codex CLI so an agent can run workspace-scoped tasks (shell, file edits, MCP tools) during a tool call. This surface is experimental and may change.
如果希望主 Agent 在不离开当前运行的情况下,把一个边界明确的工作区任务委派给 Codex,可以使用它。默认工具名称是 codex。如果设置自定义名称,必须是 codex 或以 codex_ 开头。当 Agent 包含多个 Codex 工具时,各工具必须使用唯一的名称。
Use it when you want the main agent to delegate a bounded workspace task to Codex without leaving the current run. By default, the tool name is codex. If you set a custom name, it must be codex or start with codex_. When an agent includes multiple Codex tools, each must use a unique name.
可以从以下几组选项开始:
Start with these option groups:
- 执行范围:
sandbox_mode与working_directory定义 Codex 可以在哪里操作,应配合设置;如果工作目录不在 Git 仓库中,请设置skip_git_repo_check=True。 - 会话线程默认值:
default_thread_options=ThreadOptions(...)配置模型、推理强度、审批策略、额外目录、网络访问和网页搜索模式。应优先使用web_search_mode,而不是旧版的web_search_enabled。 - 轮次默认值:
default_turn_options=TurnOptions(...)配置每个轮次的行为,例如idle_timeout_seconds和可选的取消signal。 - 工具输入/输出:工具调用必须至少包含一个
inputs条目,其形式为{ "type": "text", "text": ... }或{ "type": "local_image", "path": ... }。output_schema可以要求 Codex 返回结构化响应。
- Execution surface:
sandbox_modeandworking_directorydefine where Codex can operate. Pair them together, and setskip_git_repo_check=Truewhen the working directory is not inside a Git repository. - Thread defaults:
default_thread_options=ThreadOptions(...)configures the model, reasoning effort, approval policy, additional directories, network access, and web search mode. Preferweb_search_modeover the legacyweb_search_enabled. - Turn defaults:
default_turn_options=TurnOptions(...)configures per-turn behavior such asidle_timeout_secondsand the optional cancellationsignal. - Tool I/O: tool calls must include at least one
inputsitem with{ "type": "text", "text": ... }or{ "type": "local_image", "path": ... }.output_schemalets you require structured Codex responses.
会话线程复用与持久化由不同的选项控制:
Thread reuse and persistence are separate controls:
persist_session=True让同一工具实例的多次调用复用一个 Codex 会话线程。use_run_context_thread_id=True将线程 ID 存入运行上下文,并让共享同一个可变上下文对象的多次运行复用它。- 线程 ID 的优先级为:每次调用的
thread_id,其次是运行上下文中的线程 ID(如果启用),最后是配置的thread_id选项。 - 对于
name="codex",默认运行上下文键名是codex_thread_id;对于name="codex_<suffix>",键名是codex_thread_id_<suffix>。可以通过run_context_thread_id_key覆盖它。
persist_session=Truereuses one Codex thread for repeated calls to the same tool instance.use_run_context_thread_id=Truestores and reuses the thread ID in run context across runs that share the same mutable context object.- Thread ID precedence is: per-call
thread_id, then run-context thread ID (if enabled), then the configuredthread_idoption. - The default run-context key is
codex_thread_idforname="codex"andcodex_thread_id_<suffix>forname="codex_<suffix>". Override it withrun_context_thread_id_key.
运行时配置:
Runtime configuration:
- 认证:设置
CODEX_API_KEY(推荐)或OPENAI_API_KEY,也可以传入codex_options={"api_key": "..."}。 - 运行时:
codex_options.base_url覆盖 CLI 的基础 URL。 - 二进制文件解析:设置
codex_options.codex_path_override(或CODEX_PATH)以固定 CLI 路径。否则,SDK 先从PATH中解析codex,再回退到随包附带的供应商二进制文件。 - 环境:
codex_options.env完全控制子进程环境。提供该选项后,子进程不会继承os.environ。 - 流限制:
codex_options.codex_subprocess_stream_limit_bytes(或OPENAI_AGENTS_CODEX_SUBPROCESS_STREAM_LIMIT_BYTES)控制 stdout/stderr 读取器的限制。有效范围为65536至67108864,默认值为8388608。 - 流式输出:
on_stream接收线程/轮次生命周期事件,以及条目事件,也就是reasoning、command_execution、mcp_tool_call、file_change、web_search、todo_list和error条目的更新。 - 输出:结果包含
response、usage和thread_id;用量会累加到RunContextWrapper.usage。
- Auth: set
CODEX_API_KEY(preferred) orOPENAI_API_KEY, or passcodex_options={"api_key": "..."}. - Runtime:
codex_options.base_urloverrides the CLI base URL. - Binary resolution: set
codex_options.codex_path_override(orCODEX_PATH) to pin the CLI path. Otherwise the SDK resolvescodexfromPATH, then falls back to the bundled vendor binary. - Environment:
codex_options.envfully controls the subprocess environment. When it is provided, the subprocess does not inheritos.environ. - Stream limits:
codex_options.codex_subprocess_stream_limit_bytes(orOPENAI_AGENTS_CODEX_SUBPROCESS_STREAM_LIMIT_BYTES) controls stdout/stderr reader limits. Valid range is65536to67108864; default is8388608. - Streaming:
on_streamreceives thread/turn lifecycle events and item events (reasoning,command_execution,mcp_tool_call,file_change,web_search,todo_list, anderroritem updates). - Outputs: results include
response,usage, andthread_id; usage is added toRunContextWrapper.usage.
参考:
Reference:
- Codex 工具 API 参考文档
- ThreadOptions 参考文档
- TurnOptions 参考文档
- 完整可运行示例见
examples/tools/codex.py和examples/tools/codex_same_thread.py。
- Codex tool API reference
- ThreadOptions reference
- TurnOptions reference
- See
examples/tools/codex.pyandexamples/tools/codex_same_thread.pyfor complete runnable samples.
— 全文完 —
原文来自 OpenAI,中文为非官方学习译文。
查看原始出处 ↗