OpenAI 程序化工具调用
程序化工具调用让模型编写并运行JavaScript来协调工具。程序可并行调用、使用循环与条件,并把中间结果保留在托管运行时中。适合连续的关联调用,或先处理大量工具输出、再返回精简结果的任务。
Responses API中,应用决定是否启用,以及哪些工具可直接调用、从程序调用或两者均可。客户端拥有的工具仍由应用执行。Agents API默认启用并管理智能体循环。启用前应检查模型页面。
了解运行环境
OpenAI在全新、隔离的V8运行时中执行每个生成的程序。支持顶层 await,但不提供Node.js、包安装、直接网络访问、通用文件系统、子进程、控制台,也不在程序执行之间持久保留JavaScript状态。程序只能通过请求中启用的工具与外部交互,通过 text(...) 或 image(...) 输出。
Responses中的程序化工具调用无需持久代码执行容器即可支持ZDR工作流。但组织或项目必须启用ZDR;store: false 只实现无状态续接,不能单独启用ZDR。资格和保留行为取决于完整请求,包括模型、工具及第三方服务,参见数据控制。
何时使用程序化工具调用
控制流程可预测、代码能返回更小的结构化结果时采用程序化调用。一次调用足够、每次结果都需模型重新判断、需要审批或保留引用及原生制品时采用直接调用。
| 任务形态 | 建议方式 |
|---|---|
| 单次查询或操作 | 直接调用 |
| 可由代码筛选、连接、排序、去重、聚合或验证的一组结果 | 程序可返回更小结构化结果时采用程序化调用 |
| 数据流可预测的依赖调用 | 代码能推导后续参数,且限制和失败行为明确时采用程序化调用 |
| 自适应搜索或语义评估 | 每次结果影响下一决策时直接调用 |
| 写入或审批敏感操作 | 默认直接调用,保留清晰授权边界 |
| 最终引用或原生制品校验 | 默认直接调用,除非程序保留原生输出并验证每个必需项 |
配置程序化工具调用
在Responses请求中加入托管工具 programmatic_tool_calling,并为允许程序调用的工具配置 allowed_callers。
来源示例1(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
程序中的自然语言译释76:
返回包含sku字符串和available_units数值的对象。
[
{
"type": "function",
"name": "get_inventory",
"description": "Return an object with sku (string) and available_units (number).",
"parameters": {
"type": "object",
"properties": {
"sku": { "type": "string" }
},
"required": ["sku"],
"additionalProperties": false
},
"output_schema": {
"type": "object",
"properties": {
"sku": { "type": "string" },
"available_units": { "type": "number" }
},
"required": ["sku", "available_units"],
"additionalProperties": false
},
"allowed_callers": ["programmatic"]
},
{
"type": "programmatic_tool_calling"
}
]
allowed_callers |
行为 |
|---|---|
省略或 ["direct"] |
模型直接调用 |
["programmatic"] |
只能由 program 项中的代码调用 |
["direct", "programmatic"] |
两种方式均可 |
parameters 描述函数参数。函数返回可预测的结构化数据时,output_schema 描述 function_call_output.output 字符串编码的JSON对象。两者都应定义,让JavaScript可靠使用返回字段。
支持的工具
function、custom、mcp、apply_patch、本地与托管 shell、code_interpreter 支持 allowed_callers: ["programmatic"]。MCP的 require_approval 可以暂停程序等待批准。启用OpenAI托管工具前,应核对其数据保留与安全要求。
与工具搜索组合
工具搜索在Responses顶层运行,不在生成的JavaScript内运行。设置 defer_loading: true 的函数、自定义和MCP工具最初不向程序开放。模型加载匹配工具后,后续程序可通过 tools.* 调用,但其 allowed_callers 必须含 "programmatic"。运行中的程序不能调用工具搜索,因此应先加载,再启动依赖它的程序。
两种调用模式同时开放时如何分流
将每种方式分配给具体工作流阶段。笼统地说“高效使用程序化调用”无法划清边界。可使用以下指令模板及示例:
来源示例2(text)
<tool_orchestration>
在[有界阶段]使用程序化工具调用,仅调用[允许的工具]。
安全时并发运行独立调用,只使用文档说明的输入输出字段。
处理中间结果并精简,严格输出[程序结果结构],包含最终答案所需证据。
满足[条件]时停止。临时失败最多重试[R]次。
不重复已完成调用,不执行有副作用操作。必需结果仍缺失时,返回明确的结构化失败。
[语义判断、审批或最终验证]使用直接工具调用。
</tool_orchestration>
来源示例3(text)
程序中的自然语言译释78:
比较sku_123的库存与需求。
<tool_orchestration>
使用程序化工具调用比较sku_123的库存与需求,仅调用get_inventory和get_demand,并发执行二者。只使用文档说明的输入输出字段。
处理中间结果并精简,恰好输出一个JSON对象,含sku、available_units、requested_units、shortage_units,其中shortage_units为max(requested_units - available_units, 0)。包含available_units和requested_units作为计算证据。
两个结果包含必需字段时停止。临时失败最多重试1次。不重复已完成调用,不执行有副作用动作。必需结果仍缺失时,返回明确的结构化失败。
只有改变库存前的审批使用直接工具调用。
</tool_orchestration>
需要两种方式时,明确一次交接,避免反复切换或重复工作。如存在安全的后备方案,统一定义并限制重试次数。
理解程序响应项
每次请求仍返回标准Responses对象,没有另一套响应外壳。output 可包含:
program:生成的JavaScript、call_id、用于恢复或重放的不透明fingerprint。function_call:程序发出的调用,拥有自己的call_id,应用用它返回结果;caller.caller_id等于程序的call_id。program_output:程序最终结果及状态,call_id与程序相同,status为completed或incomplete。
它们均为 response.output 中独立的顶层项,caller 记录执行关系。以下程序在应用执行 get_inventory 和 get_demand 时暂停。
来源示例4(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
[
{
"type": "program",
"id": "prog_123",
"call_id": "call_prog_123",
"code": "const [stock, demand] = await Promise.all([tools.get_inventory({ sku: 'sku_123' }), tools.get_demand({ sku: 'sku_123' })]); text(JSON.stringify({ sku: stock.sku, available_units: stock.available_units, requested_units: demand.requested_units, shortage_units: Math.max(demand.requested_units - stock.available_units, 0) }));",
"fingerprint": "opaque_replay_state"
},
{
"type": "function_call",
"id": "fc_123",
"call_id": "call_inventory_123",
"name": "get_inventory",
"arguments": "{\\"sku\\":\\"sku_123\\"}",
"caller": {
"type": "program",
"caller_id": "call_prog_123"
}
},
{
"type": "function_call",
"id": "fc_456",
"call_id": "call_demand_123",
"name": "get_demand",
"arguments": "{\\"sku\\":\\"sku_123\\"}",
"caller": {
"type": "program",
"caller_id": "call_prog_123"
}
}
]
示例只展示相关输出项,省略外围Responses对象。应用返回嵌套函数结果后,后续响应可以包含完整程序输出:
来源示例5(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
{
"type": "program_output",
"id": "prog_out_123",
"call_id": "call_prog_123",
"result": "{\\"sku\\":\\"sku_123\\",\\"available_units\\":42,\\"requested_units\\":31,\\"shortage_units\\":0}",
"status": "completed"
}
program_output.result 中JSON字符串遵循指令要求的结果结构;外层 program_output 遵循API协议,两者不同。最终 message 可能与程序输出一起到达,也可能后续才到,应继续直到收到最终消息。
模型生成的JavaScript由OpenAI运行,应用只执行返回的客户端函数调用。用 function_call_output 返回结果,原样复制调用中的 caller,服务据此恢复正确的程序。
客户端函数调用后继续执行
程序可能多次暂停。应持续到最终助手消息:
- 提交托管工具及允许程序化调用的函数。
- 执行所有返回的客户端函数调用。
- 使用原始
call_id、caller返回每个结果。 - 续接前先处理不完整响应。
- 若没有待处理
function_call,也没有最终message,继续该响应:store: false时重放输出项;存储响应使用previous_response_id。 - 收到最终
message后停止,读取response.output_text或消息中的拒绝内容。
以下示例用 store: false,保留每个响应项,将函数结果返回程序。
来源示例6(javascript)
程序中的自然语言译释77:
返回包含sku字符串和requested_units数值的对象。
本段复用的中文释义:译释76、译释78。
// [中文] 无状态循环保留全部输出,执行客户端函数,原样回传caller;没有最终message时继续,有最终消息才结束。
import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
const client = new OpenAI();
const implementations = {
get_inventory: async ({ sku }) => ({ sku, available_units: 42 }),
get_demand: async ({ sku }) => ({ sku, requested_units: 31 }),
};
const tools = [
{
type: "function",
name: "get_inventory",
description:
"Return an object with sku (string) and available_units (number).",
parameters: {
type: "object",
properties: { sku: { type: "string" } },
required: ["sku"],
additionalProperties: false,
},
output_schema: {
type: "object",
properties: {
sku: { type: "string" },
available_units: { type: "number" },
},
required: ["sku", "available_units"],
additionalProperties: false,
},
allowed_callers: ["programmatic"],
strict: true,
},
{
type: "function",
name: "get_demand",
description:
"Return an object with sku (string) and requested_units (number).",
parameters: {
type: "object",
properties: { sku: { type: "string" } },
required: ["sku"],
additionalProperties: false,
},
output_schema: {
type: "object",
properties: {
sku: { type: "string" },
requested_units: { type: "number" },
},
required: ["sku", "requested_units"],
additionalProperties: false,
},
allowed_callers: ["programmatic"],
strict: true,
},
{ type: "programmatic_tool_calling" },
];
const input = [
{
role: "user",
content: "Compare inventory with demand for sku_123.",
},
];
while (true) {
const response = await client.responses.create({
model: "YOUR_MODEL_ID",
store: false,
input,
tools,
});
// [中文] 响应未完整完成时停止,避免执行部分生成的请求。
if (response.status !== "completed") {
throw new Error(`Response ended with status ${response.status}`);
}
// [中文] 保留可重放输出,包括program和推理项。
// 保留可重放的输出,包括程序项和推理项。
input.push(...toResponseInputItems(response.output));
const calls = response.output.filter((item) => item.type === "function_call");
if (calls.length === 0) {
const message = response.output.find((item) => item.type === "message");
if (message) {
const refusal = message.content.find((part) => part.type === "refusal");
console.log(response.output_text || refusal?.refusal || "");
break;
}
continue;
}
const outputs = await Promise.all(
calls.map(async (call) => {
const run = implementations[call.name];
if (!run) throw new Error(`Unknown tool: ${call.name}`);
const result = await run(JSON.parse(call.arguments));
return {
type: "function_call_output",
call_id: call.call_id,
output: JSON.stringify(result),
// [中文] 原样保留caller,使运行时恢复正确的程序。
// 保留 caller,以便运行时恢复正确的程序。
caller: call.caller,
};
})
);
input.push(...outputs);
}
来源示例7(python)
本段复用的中文释义:译释76、译释77、译释78。
## [中文] 无状态循环保留全部输出,执行客户端函数,原样回传caller;没有最终message时继续,有最终消息才结束。
import json
from openai import OpenAI
client = OpenAI()
model = "gpt-6-astra"
def get_inventory(sku):
return {"sku": sku, "available_units": 42}
def get_demand(sku):
return {"sku": sku, "requested_units": 31}
implementations = {
"get_inventory": get_inventory,
"get_demand": get_demand,
}
tools = [
{
"type": "function",
"name": "get_inventory",
"description": "Return an object with sku (string) and available_units (number).",
"parameters": {
"type": "object",
"properties": {"sku": {"type": "string"}},
"required": ["sku"],
"additionalProperties": False,
},
"output_schema": {
"type": "object",
"properties": {
"sku": {"type": "string"},
"available_units": {"type": "number"},
},
"required": ["sku", "available_units"],
"additionalProperties": False,
},
"allowed_callers": ["programmatic"],
},
{
"type": "function",
"name": "get_demand",
"description": "Return an object with sku (string) and requested_units (number).",
"parameters": {
"type": "object",
"properties": {"sku": {"type": "string"}},
"required": ["sku"],
"additionalProperties": False,
},
"output_schema": {
"type": "object",
"properties": {
"sku": {"type": "string"},
"requested_units": {"type": "number"},
},
"required": ["sku", "requested_units"],
"additionalProperties": False,
},
"allowed_callers": ["programmatic"],
},
{"type": "programmatic_tool_calling"},
]
input_items = [
{
"role": "user",
"content": "Compare inventory with demand for sku_123.",
}
]
while True:
response = client.responses.create(
model=model,
store=False,
input=input_items,
tools=tools,
)
if response.status != "completed":
raise RuntimeError(f"Response ended with status {response.status}")
# [中文] 保留每个输出项,包括program和推理项。
# 保留所有输出项,包括程序项和推理项。
input_items.extend(item.model_dump(exclude_none=True) for item in response.output)
calls = [item for item in response.output if item.type == "function_call"]
if not calls:
message = next(
(item for item in response.output if item.type == "message"), None
)
if message:
refusal = next(
(part.refusal for part in message.content if part.type == "refusal"),
"",
)
print(response.output_text or refusal)
break
continue
for call in calls:
run = implementations.get(call.name)
if run is None:
raise ValueError(f"Unknown tool: {call.name}")
result = run(**json.loads(call.arguments))
input_items.append(
{
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(result),
# [中文] 原样保留caller,使运行时恢复正确的程序。
# 保留 caller,以便运行时恢复正确的程序。
"caller": call.caller.model_dump() if call.caller else None,
}
)
来源示例8(go)
本段复用的中文释义:译释76、译释77、译释78。
// [中文] 无状态循环保留全部输出,执行客户端函数,原样回传caller;没有最终message时继续,有最终消息才结束。
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
type toolArguments struct {
SKU string `json:"sku"`
}
func main() {
client := openai.NewClient()
input := responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(
"Compare inventory with demand for sku_123.",
responses.EasyInputMessageRoleUser,
),
}
tools := []responses.ToolUnionParam{
functionTool(
"get_inventory",
"Return an object with sku (string) and available_units (number).",
"available_units",
),
functionTool(
"get_demand",
"Return an object with sku (string) and requested_units (number).",
"requested_units",
),
programmaticTool(),
}
for {
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Store: openai.Bool(false),
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},
Tools: tools,
})
if err != nil {
panic(err)
}
if response.Status != "completed" {
panic(fmt.Errorf("response ended with status %s", response.Status))
}
// [中文] 保留每个输出项,包括program和推理项。
// 保留所有输出项,包括程序项和推理项。
input = append(input, outputAsInput(response.Output)...)
calls := functionCalls(response.Output)
if len(calls) == 0 {
if text, ok := finalMessageText(response); ok {
fmt.Println(text)
break
}
continue
}
for _, call := range calls {
result, err := runTool(call.Name, call.Arguments)
if err != nil {
panic(err)
}
output, err := json.Marshal(result)
if err != nil {
panic(err)
}
toolOutput := responses.ResponseInputItemParamOfFunctionCallOutput(string(output))
toolOutput.OfFunctionCallOutput.CallID = openai.String(call.CallID)
caller := call.Caller.AsProgram()
if caller.CallerID == "" {
panic("function call is missing its program caller")
}
// [中文] 原样保留caller,使运行时恢复正确的程序。
// 保留 caller,以便运行时恢复正确的程序。
toolOutput.OfFunctionCallOutput.Caller.OfProgram =
&responses.ResponseInputItemFunctionCallOutputCallerProgramParam{
CallerID: caller.CallerID,
}
input = append(input, toolOutput)
}
}
}
func functionTool(name, description, resultField string) responses.ToolUnionParam {
parameters := map[string]any{
"type": "object",
"properties": map[string]any{
"sku": map[string]any{"type": "string"},
},
"required": []string{"sku"},
"additionalProperties": false,
}
outputSchema := map[string]any{
"type": "object",
"properties": map[string]any{
"sku": map[string]any{"type": "string"},
resultField: map[string]any{"type": "number"},
},
"required": []string{"sku", resultField},
"additionalProperties": false,
}
tool := responses.ToolParamOfFunction(name, parameters, true)
tool.OfFunction.Description = openai.String(description)
tool.OfFunction.AllowedCallers = []string{"programmatic"}
tool.OfFunction.OutputSchema = outputSchema
return tool
}
func programmaticTool() responses.ToolUnionParam {
tool := responses.NewToolProgrammaticToolCallingParam()
return responses.ToolUnionParam{OfProgrammaticToolCalling: &tool}
}
func outputAsInput(
output []responses.ResponseOutputItemUnion,
) []responses.ResponseInputItemUnionParam {
input := make([]responses.ResponseInputItemUnionParam, 0, len(output))
for _, item := range output {
var converted responses.ResponseInputItemUnion
if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {
panic(err)
}
input = append(input, converted.ToParam())
}
return input
}
func functionCalls(
output []responses.ResponseOutputItemUnion,
) []responses.ResponseFunctionToolCall {
calls := make([]responses.ResponseFunctionToolCall, 0)
for _, item := range output {
if item.Type == "function_call" {
calls = append(calls, item.AsFunctionCall())
}
}
return calls
}
func finalMessageText(response *responses.Response) (string, bool) {
for _, item := range response.Output {
if item.Type != "message" {
continue
}
text := response.OutputText()
if text != "" {
return text, true
}
for _, content := range item.AsMessage().Content {
if content.Type == "refusal" {
return content.AsRefusal().Refusal, true
}
}
return "", true
}
return "", false
}
func runTool(name, argumentsJSON string) (map[string]any, error) {
var arguments toolArguments
if err := json.Unmarshal([]byte(argumentsJSON), &arguments); err != nil {
return nil, fmt.Errorf("parse %s arguments: %w", name, err)
}
switch name {
case "get_inventory":
return map[string]any{"sku": arguments.SKU, "available_units": 42}, nil
case "get_demand":
return map[string]any{"sku": arguments.SKU, "requested_units": 31}, nil
default:
return nil, fmt.Errorf("unknown tool: %s", name)
}
}
来源示例9(java)
本段复用的中文释义:译释78。
// [中文] 无状态循环保留全部输出,执行客户端函数,原样回传caller;没有最终message时继续,有最终消息才结束。
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
var json = new ObjectMapper();
var tools =
List.of(
Tool.ofFunction(function("get_inventory", "available_units")),
Tool.ofFunction(function("get_demand", "requested_units")),
Tool.ofProgrammaticToolCalling());
var input = new ArrayList<ResponseInputItem>();
input.add(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Compare inventory with demand for sku_123.")
.build()));
while (true) {
var response =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.store(false)
.inputOfResponse(input)
.tools(tools)
.build());
if (!response.status().orElseThrow().equals(ResponseStatus.COMPLETED)) {
throw new IllegalStateException("Response ended with status " + response.status());
}
// [中文] 保留所有可重放输出项,包括program和推理项。
// 保留每个可重放的输出项,包括程序项和推理项。
response.output().stream()
.map(item -> JsonValue.from(item).convert(ResponseInputItem.class))
.forEach(input::add);
var calls = response.output().stream().flatMap(item -> item.functionCall().stream()).toList();
if (calls.isEmpty()) {
var messages = response.output().stream().flatMap(item -> item.message().stream()).toList();
if (!messages.isEmpty()) {
messages.forEach(
message ->
message
.content()
.forEach(
content -> {
content.outputText().ifPresent(text -> System.out.println(text.text()));
content
.refusal()
.ifPresent(refusal -> System.out.println(refusal.refusal()));
}));
break;
}
continue;
}
for (var call : calls) {
String sku = json.readTree(call.arguments()).get("sku").asText();
var result =
switch (call.name()) {
case "get_inventory" -> Map.of("sku", sku, "available_units", 42);
case "get_demand" -> Map.of("sku", sku, "requested_units", 31);
default -> throw new IllegalArgumentException("Unknown tool: " + call.name());
};
var output =
ResponseInputItem.FunctionCallOutput.builder()
.callId(call.callId())
.output(json.writeValueAsString(result));
// [中文] 原样保留caller,使运行时恢复正确的程序。
// 保留 caller,以便运行时恢复正确的程序。
call.caller()
.ifPresent(
caller ->
output.caller(
JsonValue.from(caller)
.convert(ResponseInputItem.FunctionCallOutput.Caller.class)));
input.add(ResponseInputItem.ofFunctionCallOutput(output.build()));
}
}
private static FunctionTool function(String name, String outputField) {
var parameters =
Map.of(
"type",
"object",
"properties",
Map.of("sku", Map.of("type", "string")),
"required",
List.of("sku"),
"additionalProperties",
false);
var outputSchema =
Map.of(
"type",
"object",
"properties",
Map.of("sku", Map.of("type", "string"), outputField, Map.of("type", "number")),
"required",
List.of("sku", outputField),
"additionalProperties",
false);
return FunctionTool.builder()
.name(name)
.description("Return an object with sku (string) and " + outputField + " (number).")
.parameters(JsonValue.from(parameters).convert(FunctionTool.Parameters.class))
.outputSchema(JsonValue.from(outputSchema).convert(FunctionTool.OutputSchema.class))
.allowedCallers(List.of(FunctionTool.AllowedCaller.PROGRAMMATIC))
.strict(true)
.build();
}
来源示例10(ruby)
本段复用的中文释义:译释76、译释77、译释78。
## [中文] 无状态循环保留全部输出,执行客户端函数,原样回传caller;没有最终message时继续,有最终消息才结束。
require "json"
require "openai"
client = OpenAI::Client.new
def get_inventory(sku:)
{
sku: sku,
available_units: 42
}
end
def get_demand(sku:)
{
sku: sku,
requested_units: 31
}
end
implementations = {
"get_inventory" => method(:get_inventory),
"get_demand" => method(:get_demand)
}
tools = [
{
type: :function,
name: "get_inventory",
description: "Return an object with sku (string) and available_units (number).",
parameters: {
type: :object,
properties: { sku: { type: :string } },
required: ["sku"],
additionalProperties: false
},
output_schema: {
type: :object,
properties: {
sku: { type: :string },
available_units: { type: :number }
},
required: %w[sku available_units],
additionalProperties: false
},
allowed_callers: [:programmatic],
strict: true
},
{
type: :function,
name: "get_demand",
description: "Return an object with sku (string) and requested_units (number).",
parameters: {
type: :object,
properties: { sku: { type: :string } },
required: ["sku"],
additionalProperties: false
},
output_schema: {
type: :object,
properties: {
sku: { type: :string },
requested_units: { type: :number }
},
required: %w[sku requested_units],
additionalProperties: false
},
allowed_callers: [:programmatic],
strict: true
},
{ type: :programmatic_tool_calling }
]
input = [
{
role: :user,
content: "Compare inventory with demand for sku_123."
}
]
loop do
response = client.responses.create(
model: "gpt-6-astra",
store: false,
input: input,
tools: tools
)
unless response.status == OpenAI::Responses::ResponseStatus::COMPLETED
raise "Response ended with status #{response.status}"
end
# [中文] 保留每个输出项,包括program和推理项。
# 保留所有输出项,包括程序项和推理项。
input.concat(response.output)
calls = response.output.grep(OpenAI::Models::Responses::ResponseFunctionToolCall)
if calls.empty?
message = response.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputMessage)
end
next unless message.is_a?(OpenAI::Models::Responses::ResponseOutputMessage)
refusal = message.content.find do |content|
content.is_a?(OpenAI::Models::Responses::ResponseOutputRefusal)
end
text = response.output_text
if text.empty? &&
refusal.is_a?(OpenAI::Models::Responses::ResponseOutputRefusal)
text = refusal.refusal
end
puts(text)
break
end
calls.each do |call|
implementation = implementations.fetch(call.name) do
raise ArgumentError, "Unknown tool: #{call.name}"
end
result = implementation.call(**JSON.parse(call.arguments, symbolize_names: true))
output = {
type: :function_call_output,
call_id: call.call_id,
output: JSON.generate(result)
}
# [中文] 原样保留caller,使运行时恢复正确的程序。
# 保留 caller,以便运行时恢复正确的程序。
output[:caller] = call.caller_.to_h if call.caller_
input << output
end
end
存储响应时不必重发全部历史,使用 previous_response_id 并提交新结果即可。无状态请求必须按顺序重放完整序列,包括所有 program、推理、函数调用、函数结果和 program_output。
无状态推理模型请求还须重放每个推理项,它们默认包含 encrypted_content。通用方式参见手动管理会话状态。
为程序设计工具
- 返回紧凑结构化数据,让JavaScript无需解析自然语言。
- 用
output_schema定义字段和类型,并说明错误行为。无法预知返回形态时保持直接调用,让模型检查结果。 - 定义精确的程序结果结构和必需证据;无法产生有效结果时返回明确的结构化失败。
- 尽量保持函数幂等,重试或重放不应重复不安全的副作用。
- 即使来自托管程序,应用仍需逐次检查参数和权限。
- 给工具具体名称与描述,便于模型正确组合。
- 无论调用者是谁,高影响操作都须应用层批准。
评估程序化工具调用
它可能减少进入模型上下文的中间输出,但效果依赖任务和工具结果。先以直接调用为基线,再用代表性任务比较。先规定最终答案质量和证据要求,再衡量效率;任何接受的质量取舍都应明确记录。
评估正确性、完整性、证据覆盖;输入与总词元、端到端延迟和成本;模型轮次、工具调用、重试与恢复;副作用及审批等安全结果;实际使用的调用方式是否符合阶段设计。
Agents API
在Agents API中,该能力在OpenAI管理的执行框架内运行且默认开启。智能体获得 exec 工具,现有工具可在生成的JavaScript中访问,无需包装成命令行程序或安装到沙箱。
要禁用,在 agent.tools 中加入:
来源示例11(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
{
"type": "programmatic_tool_calling",
"enabled": false
}
省略该项或省略 enabled 均保持开启;只有类型的 { "type": "programmatic_tool_calling" } 也保持开启。前文 allowed_callers 和续接循环针对Responses集成。
environment.type: none 的纯会话会话也能用程序化调用。但Bash、executor MCP等沙箱工具仍需执行环境。
JavaScript编排不改变工具执行地点:Shell命令仍在沙箱执行,JavaScript自身不启动系统进程;executor MCP仍使用沙箱,函数工具仍调用应用服务器。智能体处理结果后决定哪些进入上下文。
按前文明确哪些阶段使用代码。Agents配置与调用处理参见函数和MCP连接。