OpenAI 函数调用
函数调用也称工具调用,让模型连接外部系统,访问训练数据之外的信息,以及应用提供的操作。这里介绍由JSON Schema定义的函数工具,以及使用自由文本输入输出的自定义工具。
Agents API会话应通过Functions注册并处理会话操作请求;本文示例展示Responses和Chat Completions。函数众多或模式很大时,可结合工具搜索延迟加载不常用工具;只有 gpt-5.4 及后续模型支持 tool_search。
GPT-6 Astra和GPT-6.1 Sol的工具调用要求使用Responses API。来源的Chat Completions示例使用关闭推理的GPT-5.6 Terra;现有应用升级参见迁移指南。
工作原理
工具:提供给模型的功能
函数或工具是向模型声明可访问的一项能力。生成回答时,模型可能判断需要它提供的数据或操作。例如查询某地天气、按用户ID读取账户资料、为丢失订单退款。API请求可列出供模型考虑的工具;天气例子提供接收 location 的 get_weather。
工具调用:模型请求使用工具
模型阅读提示后,若判断需要使用某工具,会返回特殊的工具调用响应。例如用户问“巴黎天气如何?”,模型可能请求 get_weather,将 location 设为 Paris。
工具输出:应用为模型生成的结果
工具输出是应用执行工具后生成的响应,可以是JSON或普通文本,并应关联具体调用,以下使用 call_id。天气工具可能返回 {"temperature": "25", "unit": "C"},也可返回图片内容或文件内容。
把工具定义、原始问题、模型调用及执行结果送回模型,才得到“巴黎今天25摄氏度”之类最终回答。
来源示例1(text)
巴黎今天的气温是25摄氏度。
函数与工具的区别
- 函数是由JSON Schema定义的一类工具,让模型向应用传递数据,再由应用访问资料或执行操作。
- 自定义工具使用自由文本输入输出。
- 平台也提供内置工具,包括网页搜索、代码执行和远程MCP。
工具调用流程
- 请求模型,提供可用工具。
- 接收模型的工具调用。
- 在应用端使用调用参数执行代码。
- 再次请求模型并携带工具输出。
- 接收最终回答,或更多工具调用。

Responses允许按任务需要重复循环。若希望框架封装常见编排,可比较Responses与Agents SDK。
函数工具示例
以下以 get_horoscope 查询某星座今日运势,展示完整调用流程。
来源示例2(javascript)
程序中的自然语言译释9:
获取某星座今天的运势。
程序中的自然语言译释10:
下周二你会和一只小水獭成为朋友。
程序中的自然语言译释11:
我的运势如何?我是水瓶座。
程序中的自然语言译释12:
仅使用工具生成的运势作答。
程序中的自然语言译释13:
星座,例如金牛座或水瓶座。
// [中文] 定义get_horoscope工具、发出请求,再处理调用并回传结果;推理项和调用项需随输入保留。
import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
const openai = new OpenAI();
// [中文] 步骤1:定义供模型调用的工具列表。
// 1. Define a list of callable tools for the model
const tools = [
{
type: "function",
name: "get_horoscope",
description: "Get today's horoscope for an astrological sign.",
parameters: {
type: "object",
properties: {
sign: {
type: "string",
description: "An astrological sign like Taurus or Aquarius",
},
},
required: ["sign"],
additionalProperties: false,
},
strict: true,
},
];
function getHoroscope(sign) {
return `${sign}: Next Tuesday you will befriend a baby otter.`;
}
// [中文] 创建持续追加内容的输入列表。
// 创建输入列表,后续逐步追加内容。
let input = [
{ role: "user", content: "What is my horoscope? I am an Aquarius." },
];
// [中文] 步骤2:把工具定义连同提示发送给模型。
// 2. Prompt the model with tools defined
let response = await openai.responses.create({
model: "gpt-6-astra",
tools,
input,
});
// [中文] 保留模型输出,以便下一轮续接。
// 保留模型输出,供下一轮使用。
input.push(...toResponseInputItems(response.output));
for (const item of response.output) {
if (item.type !== "function_call") continue;
if (item.name === "get_horoscope") {
// [中文] 步骤3:执行get_horoscope的函数逻辑。
// 3. Execute the function logic for get_horoscope
const { sign } = JSON.parse(item.arguments);
const horoscope = getHoroscope(sign);
// [中文] 步骤4:把函数结果提供给模型。
// 4. Provide function call results to the model
input.push({
type: "function_call_output",
call_id: item.call_id,
output: horoscope,
});
}
}
console.log("Final input:");
console.log(JSON.stringify(input, null, 2));
response = await openai.responses.create({
model: "gpt-6-astra",
instructions: "Respond only with a horoscope generated by a tool.",
tools,
input,
});
// [中文] 步骤5:模型可以根据工具结果给出回答。
// 5. The model should be able to give a response!
console.log("Final output:");
console.log(response.output_text);
来源示例3(python)
本段复用的中文释义:译释9、译释10、译释11、译释12、译释13。
## [中文] 定义get_horoscope工具、发出请求,再处理调用并回传结果;推理项和调用项需随输入保留。
from openai import OpenAI
import json
client = OpenAI()
## [中文] 步骤1:定义供模型调用的工具列表。
## 1. Define a list of callable tools for the model
tools = [
{
"type": "function",
"name": "get_horoscope",
"description": "Get today's horoscope for an astrological sign.",
"parameters": {
"type": "object",
"properties": {
"sign": {
"type": "string",
"description": "An astrological sign like Taurus or Aquarius",
},
},
"required": ["sign"],
},
},
]
def get_horoscope(sign):
return f"{sign}: Next Tuesday you will befriend a baby otter."
## [中文] 创建持续追加内容的输入列表。
## 创建输入列表,后续逐步追加内容。
input_list = [{"role": "user", "content": "What is my horoscope? I am an Aquarius."}]
## [中文] 步骤2:把工具定义连同提示发送给模型。
## 2. Prompt the model with tools defined
response = client.responses.create(
model="gpt-6-astra",
tools=tools,
input=input_list,
)
## [中文] 保存函数调用输出,用于后续请求。
## 保存函数调用的输出,供后续请求使用。
input_list += response.output
for item in response.output:
if item.type == "function_call":
if item.name == "get_horoscope":
# [中文] 步骤3:执行get_horoscope的函数逻辑。
# 3. Execute the function logic for get_horoscope
sign = json.loads(item.arguments)["sign"]
horoscope = get_horoscope(sign)
# [中文] 步骤4:把函数结果提供给模型。
# 4. Provide function call results to the model
input_list.append(
{
"type": "function_call_output",
"call_id": item.call_id,
"output": horoscope,
}
)
print("Final input:")
print(input_list)
response = client.responses.create(
model="gpt-6-astra",
instructions="Respond only with a horoscope generated by a tool.",
tools=tools,
input=input_list,
)
## [中文] 步骤5:模型可以根据工具结果给出回答。
## 5. The model should be able to give a response!
print("Final output:")
print(response.model_dump_json(indent=2))
print("\n" + response.output_text)
来源示例4(go)
本段复用的中文释义:译释9、译释10、译释11、译释12、译释13。
// [中文] 定义get_horoscope工具、发出请求,再处理调用并回传结果;推理项和调用项需随输入保留。
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := horoscopeResponseTool()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is my horoscope? I am an Aquarius.")},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
var functionOutput responses.ResponseInputItemUnionParam
for _, output := range response.Output {
if output.Type != "function_call" {
continue
}
call := output.AsFunctionCall()
if call.Name != "get_horoscope" {
continue
}
var arguments struct {
Sign string `json:"sign"`
}
if err := json.Unmarshal([]byte(call.Arguments), &arguments); err != nil {
panic(err)
}
functionOutput = responses.ResponseInputItemParamOfFunctionCallOutput(getHoroscope(arguments.Sign))
functionOutput.OfFunctionCallOutput.CallID = openai.String(call.CallID)
}
if functionOutput.OfFunctionCallOutput == nil {
panic("the model did not call get_horoscope")
}
response, err = client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
PreviousResponseID: openai.String(response.ID),
Instructions: openai.String("Respond only with a horoscope generated by a tool."),
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{functionOutput}},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
func horoscopeResponseTool() responses.ToolUnionParam {
parameters := map[string]any{
"type": "object",
"properties": map[string]any{
"sign": map[string]any{"type": "string", "description": "An astrological sign like Taurus or Aquarius"},
},
"required": []string{"sign"},
"additionalProperties": false,
}
tool := responses.ToolParamOfFunction("get_horoscope", parameters, true)
tool.OfFunction.Description = openai.String("Get today's horoscope for an astrological sign.")
return tool
}
func getHoroscope(sign string) string {
return fmt.Sprintf("%s: Next Tuesday you will befriend a baby otter.", sign)
}
来源示例5(java)
本段复用的中文释义:译释9、译释11、译释12、译释13。
// [中文] 定义get_horoscope工具、发出请求,再处理调用并回传结果;推理项和调用项需随输入保留。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
import java.util.Map;
FunctionTool horoscope =
FunctionTool.builder()
.name("get_horoscope")
.description("Get today's horoscope for an astrological sign.")
.parameters(
FunctionTool.Parameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties",
JsonValue.from(
Map.of(
"sign",
Map.of(
"type", "string",
"description",
"An astrological sign like Taurus or Aquarius"))))
.putAdditionalProperty("required", JsonValue.from(List.of("sign")))
.putAdditionalProperty("additionalProperties", JsonValue.from(false))
.build())
.strict(true)
.build();
var firstResponse =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What is my horoscope? I am an Aquarius.")
.addTool(horoscope)
.build());
var functionCall =
firstResponse.output().stream()
.flatMap(item -> item.functionCall().stream())
.filter(call -> call.name().equals("get_horoscope"))
.findFirst()
.orElseThrow(() -> new IllegalStateException("The model did not call get_horoscope"));
record HoroscopeArguments(String sign) {}
String sign = functionCall.arguments(HoroscopeArguments.class).sign();
ResponseCreateParams followUp =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.instructions("Respond only with a horoscope generated by a tool.")
.previousResponseId(firstResponse.id())
.inputOfResponse(
List.of(
ResponseInputItem.ofFunctionCallOutput(
ResponseInputItem.FunctionCallOutput.builder()
.callId(functionCall.callId())
.output(sign + ": Embrace an unexpected opportunity today.")
.build())))
.addTool(horoscope)
.build();
client.responses().create(followUp).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
来源示例6(ruby)
本段复用的中文释义:译释9、译释11。
## [中文] 定义get_horoscope工具、发出请求,再处理调用并回传结果;推理项和调用项需随输入保留。
require "json"
require "openai"
client = OpenAI::Client.new
tools = [
{
type: :function,
name: "get_horoscope",
description: "Get today's horoscope for an astrological sign.",
parameters: {
type: :object,
properties: { sign: { type: :string } },
required: ["sign"],
additionalProperties: false
},
strict: true
}
]
first_response = client.responses.create(
model: "gpt-6-astra",
input: "What is my horoscope? I am an Aquarius.",
tools: tools
)
function_call = first_response.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseFunctionToolCall) &&
item.name == "get_horoscope"
end
unless function_call.is_a?(OpenAI::Models::Responses::ResponseFunctionToolCall)
raise "The model did not call get_horoscope"
end
arguments = JSON.parse(function_call.arguments, symbolize_names: true)
sign = arguments.fetch(:sign)
response = client.responses.create(
model: "gpt-6-astra",
previous_response_id: first_response.id,
input: [
{
type: :function_call_output,
call_id: function_call.call_id,
output: "#{sign}: Embrace an unexpected opportunity today."
}
],
tools: tools
)
puts(response.output_text)
GPT-5、o4-mini等推理模型在工具调用响应中返回的推理项,也必须连同工具结果一起传回。
定义函数
通常在每次API请求的 tools 中声明,也可通过工具搜索后续加载。两种方式的函数模式相同。
| 字段 | 含义 |
|---|---|
type |
固定为 function |
name |
函数名,例如 get_weather |
description |
何时、如何使用 |
parameters |
定义输入参数的JSON Schema |
strict |
是否强制严格符合模式 |
天气函数定义:
来源示例7(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
程序中的自然语言译释16:
城市和国家,例如哥伦比亚的波哥大。
{
"type": "function",
"name": "get_weather",
"description": "Retrieves current weather for the given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Units the temperature will be returned in."
}
},
"required": ["location", "units"],
"additionalProperties": false
},
"strict": true
}
parameters 可利用属性类型、枚举、描述、嵌套对象和递归对象等JSON Schema能力。
定义命名空间
按领域分组,例如 crm、billing、shipping。它能组织相近工具,尤其适合模型要在不同系统用途的工具之间选择,例如CRM搜索与工单系统搜索。
来源示例8(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
程序中的自然语言译释24:
用于查找客户与管理订单的CRM工具。
程序中的自然语言译释26:
按客户ID获取客户资料。
程序中的自然语言译释27:
按客户ID列出尚未关闭的订单。
{
"type": "namespace",
"name": "crm",
"description": "CRM tools for customer lookup and order management.",
"tools": [
{
"type": "function",
"name": "get_customer_profile",
"description": "Fetch a customer profile by customer ID.",
"parameters": {
"type": "object",
"properties": {
"customer_id": { "type": "string" }
},
"required": ["customer_id"],
"additionalProperties": false
}
},
{
"type": "function",
"name": "list_open_orders",
"description": "List open orders for a customer ID.",
"defer_loading": true,
"parameters": {
"type": "object",
"properties": {
"customer_id": { "type": "string" }
},
"required": ["customer_id"],
"additionalProperties": false
}
}
]
}
工具搜索
工具生态较大时,可以延迟全部或部分定义;模型先搜索相关工具,加入上下文后使用。支持范围及配置参见工具搜索。
函数定义最佳实践
- 名称、参数描述和指令清晰具体。 明确函数及各参数的用途、格式和返回含义;通过系统提示说明何时用、何时不用。针对反复失败加入例子与边界情况,但增加示例也可能损害推理模型表现。延迟工具的细节放在函数描述,命名空间描述保持简洁。
- 遵循软件工程规范。 行为可预测、直观,符合最小惊讶原则。用枚举和对象结构防止无效状态,例如
toggle_light(on: bool, off: bool)容易产生矛盾。以“新人能否仅凭这些说明正确使用”为检验,补足其会追问的信息。 - 能用代码承担的工作交给代码。 已知订单ID时,不再让模型填写;可定义无参数的
submit_refund(),由代码传入ID。总是依次调用的功能可合并,例如将mark_location()逻辑并入query_location()。 - 初始函数数量尽量少。 评估不同数量下表现,每轮起始尽量少于20个只是软建议。大型或不常用部分通过工具搜索延迟加载。
- 使用OpenAI资源。 在Playground迭代模式;大量函数或困难任务可评估微调及函数调用示例。
词元使用
函数定义会按模型受训的语法注入系统消息,占用上下文并作为输入词元计费。接近限制时,减少预加载函数、缩短描述或使用工具搜索。工具定义很多时,也可评估微调减少所需词元。
处理函数调用
响应可能有零个、一个或多个调用,应用应能处理多个。Responses的 output 中 type: function_call 项包含 call_id、name 和JSON编码的 arguments。
来源示例9(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
[
{
"id": "fc_12345xyz",
"call_id": "call_12345xyz",
"type": "function_call",
"name": "get_weather",
"arguments": "{\"location\":\"Paris, France\"}"
},
{
"id": "fc_67890abc",
"call_id": "call_67890abc",
"type": "function_call",
"name": "get_weather",
"arguments": "{\"location\":\"Bogotá, Colombia\"}"
},
{
"id": "fc_99999def",
"call_id": "call_99999def",
"type": "function_call",
"name": "send_email",
"arguments": "{\"to\":\"bob@email.com\",\"body\":\"Hi bob\"}"
}
]
使用工具搜索时,调用前可能先出现搜索调用和搜索输出;加载后的函数仍按同样方式处理。
执行调用并追加结果:
来源示例10(javascript)
// [中文] 遍历模型返回的函数调用,解析参数并通过call_id关联回传结果。
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
input.push(...toResponseInputItems(response.output));
for (const toolCall of response.output) {
if (toolCall.type !== "function_call") {
continue;
}
const name = toolCall.name;
const args = JSON.parse(toolCall.arguments);
const result = await callFunction(name, args);
input.push({
type: "function_call_output",
call_id: toolCall.call_id,
output: result.toString(),
});
}
来源示例11(python)
## [中文] 遍历模型返回的函数调用,解析参数并通过call_id关联回传结果。
input_messages += response.output
for tool_call in response.output:
if tool_call.type != "function_call":
continue
name = tool_call.name
args = json.loads(tool_call.arguments)
result = call_function(name, args)
input_messages.append(
{
"type": "function_call_output",
"call_id": tool_call.call_id,
"output": json.dumps(result),
}
)
来源示例12(go)
// [中文] 遍历模型返回的函数调用,解析参数并通过call_id关联回传结果。
input = append(input, responseOutputAsInput(response.Output)...)
for _, output := range response.Output {
if output.Type != "function_call" {
continue
}
toolCall := output.AsFunctionCall()
var arguments functionArguments
if err := json.Unmarshal([]byte(toolCall.Arguments), &arguments); err != nil {
panic(err)
}
result, err := callFunction(toolCall.Name, arguments)
if err != nil {
panic(err)
}
toolOutput := responses.ResponseInputItemParamOfFunctionCallOutput(result)
toolOutput.OfFunctionCallOutput.CallID = openai.String(toolCall.CallID)
input = append(input, toolOutput)
}
来源示例13(java)
// [中文] 遍历模型返回的函数调用,解析参数并通过call_id关联回传结果。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
response.output().stream()
.map(item -> JsonValue.from(item).convert(ResponseInputItem.class))
.forEach(input::add);
response.output().stream()
.flatMap(item -> item.functionCall().stream())
.forEach(
call -> {
String result;
if (call.name().equals("get_weather")) {
record Coordinates(double latitude, double longitude) {}
Coordinates coordinates = call.arguments(Coordinates.class);
result =
JsonValue.from(
Map.of(
"latitude", coordinates.latitude(),
"longitude", coordinates.longitude(),
"temperature_c", 18))
.toString();
} else if (call.name().equals("send_email")) {
record Email(String to, String body) {}
Email message = call.arguments(Email.class);
result = JsonValue.from(Map.of("to", message.to(), "status", "sent")).toString();
} else {
throw new IllegalArgumentException("Unknown function: " + call.name());
}
var output =
ResponseInputItem.ofFunctionCallOutput(
ResponseInputItem.FunctionCallOutput.builder()
.callId(call.callId())
.output(result)
.build());
input.add(output);
System.out.println(call.callId() + " " + result);
});
来源示例14(ruby)
## [中文] 遍历模型返回的函数调用,解析参数并通过call_id关联回传结果。
input.concat(response.output)
response.output.each do |tool_call|
next unless tool_call.is_a?(OpenAI::Models::Responses::ResponseFunctionToolCall)
arguments = JSON.parse(tool_call.arguments)
result = call_function(tool_call.name, arguments)
input << {
type: :function_call_output,
call_id: tool_call.call_id,
output: JSON.generate(result)
}
end
上例使用假设的 call_function 路由各调用。以下是一种可能的实现:
来源示例15(javascript)
// [中文] 按函数名分派本地实现;夹具仅用于演示,真实服务由应用接入。
const callFunction = async (name, args) => {
if (name === "get_weather") {
return getWeather(args.latitude, args.longitude);
}
if (name === "send_email") {
return sendEmail(args.to, args.body);
}
throw new Error(`Unknown function: ${name}`);
};
来源示例16(python)
## [中文] 按函数名分派本地实现;夹具仅用于演示,真实服务由应用接入。
def call_function(name, args):
if name == "get_weather":
return get_weather(**args)
if name == "send_email":
return send_email(**args)
raise ValueError(f"Unknown function: {name}")
来源示例17(go)
// [中文] 按函数名分派本地实现;夹具仅用于演示,真实服务由应用接入。
func callFunction(name string, arguments functionArguments) (string, error) {
switch name {
case "get_weather":
return getWeather(arguments.Location), nil
case "send_email":
return sendEmail(arguments.To, arguments.Body), nil
default:
return "", fmt.Errorf("unknown function: %s", name)
}
}
来源示例18(java)
// [中文] 按函数名分派本地实现;夹具仅用于演示,真实服务由应用接入。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
var argsJson = new ObjectMapper().readTree("{\"location\":\"Paris, France\"}");
System.out.println(callFunction("get_weather", argsJson));
// [中文] 这些本地夹具只演示调用分派,应替换成应用服务。
// 这些本地测试数据用于演示分发,请换成应用中的实际服务。
// [中文] 邮件夹具只打印输入,不会实际发送邮件。
// 此邮件示例只打印输入,不会发送邮件。
static Map<String, Object> callFunction(String name, JsonNode arguments) {
return switch (name) {
case "get_weather" -> getWeather(arguments.get("location").asText());
case "send_email" -> sendEmail(arguments.get("to").asText(), arguments.get("body").asText());
default -> throw new IllegalArgumentException("Unknown function: " + name);
};
}
private static Map<String, Object> getWeather(String location) {
int temperature =
switch (location) {
case "Bogotá, Colombia" -> 18;
case "Paris, France" -> 15;
default -> 20;
};
return Map.of("location", location, "temperature_celsius", temperature);
}
private static Map<String, Object> sendEmail(String to, String body) {
System.out.println("Sending email to " + to + ": " + body);
return Map.of("status", "sent");
}
来源示例19(csharp)
// [中文] 按函数名分派本地实现;夹具仅用于演示,真实服务由应用接入。
using System.Text.Json;
using JsonDocument arguments = JsonDocument.Parse("{\"location\":\"Paris, France\"}");
Console.WriteLine(FunctionDispatcher.CallFunction("get_weather", arguments.RootElement));
internal static class FunctionDispatcher
{
// [中文] 这些本地夹具只演示调用分派,应替换成应用服务。
// 这些本地测试数据用于演示分发,请换成应用中的实际服务。
// [中文] 邮件夹具只打印输入,不会实际发送邮件。
// 此邮件示例只打印输入,不会发送邮件。
internal static string CallFunction(string name, JsonElement arguments) => name switch
{
"get_weather" => GetWeather(arguments.GetProperty("location").GetString()!),
"send_email" => SendEmail(arguments.GetProperty("to").GetString()!, arguments.GetProperty("body").GetString()!),
_ => throw new ArgumentException($"Unknown function: {name}", nameof(name))
};
private static string GetWeather(string location) => JsonSerializer.Serialize(new { location, temperature_celsius = location switch { "Bogotá, Colombia" => 18, "Paris, France" => 15, _ => 20 } });
private static string SendEmail(string to, string body)
{
Console.WriteLine($"Sending email to {to}: {body}");
return "{\"status\":\"sent\"}";
}
}
来源示例20(ruby)
## [中文] 按函数名分派本地实现;夹具仅用于演示,真实服务由应用接入。
def call_function(name, arguments)
case name
when "get_weather"
FunctionCallingExample.get_weather(
arguments.fetch("latitude"),
arguments.fetch("longitude")
)
when "send_email"
FunctionCallingExample.send_email(
arguments.fetch("to"),
arguments.fetch("body")
)
else
raise ArgumentError, "Unknown function: #{name}"
end
end
结果格式
function_call_output 通常提交字符串,内容可为JSON、错误码或普通文本,由模型解释。返回图像或文件时也可以提交相应对象数组。没有返回值的函数,例如 send_email,也应返回 "success" 等成功或失败标记。
将结果纳入响应
将结果追加至 input 后再次发送给模型:
来源示例21(javascript)
// [中文] 把此前函数结果作为输入再次请求模型,读取各语言示例实际展示的输出。
const response = await openai.responses.create({
model: "gpt-6-astra",
input,
tools,
});
来源示例22(python)
## [中文] 把此前函数结果作为输入再次请求模型,读取各语言示例实际展示的输出。
response = client.responses.create(
model="gpt-6-astra",
input=input_messages,
tools=responses_tools,
)
print(response.output_text)
来源示例23(go)
// [中文] 把此前函数结果作为输入再次请求模型,读取各语言示例实际展示的输出。
response, err = client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},
Tools: tools,
})
if err != nil {
panic(err)
}
来源示例24(java)
程序中的自然语言译释117:
获取某城市的天气。
// [中文] 把此前函数结果作为输入再次请求模型,读取各语言示例实际展示的输出。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseFunctionToolCall;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
import java.util.Map;
FunctionTool weather =
FunctionTool.builder()
.name("get_weather")
.description("Get the weather for a city.")
.parameters(
FunctionTool.Parameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties", JsonValue.from(Map.of("city", Map.of("type", "string"))))
.putAdditionalProperty("required", JsonValue.from(List.of("city")))
.putAdditionalProperty("additionalProperties", JsonValue.from(false))
.build())
.strict(true)
.build();
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("What is the weather like in Paris?")
.build()),
ResponseInputItem.ofFunctionCall(
ResponseFunctionToolCall.builder()
.callId("call_weather")
.name("get_weather")
.arguments("{\"city\":\"Paris\"}")
.build()),
ResponseInputItem.ofFunctionCallOutput(
ResponseInputItem.FunctionCallOutput.builder()
.callId("call_weather")
.output("{\"city\":\"Paris\",\"temperature_c\":18}")
.build())))
.addTool(weather)
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
来源示例25(ruby)
本段复用的中文释义:译释117。
## [中文] 把此前函数结果作为输入再次请求模型,读取各语言示例实际展示的输出。
require "openai"
client = OpenAI::Client.new
input = [
{
role: :user,
content: "What is the weather like in Paris?"
},
{
type: :function_call,
call_id: "call_weather",
name: "get_weather",
arguments: '{"city":"Paris"}'
},
{
type: :function_call_output,
call_id: "call_weather",
output: '{"city":"Paris","temperature_c":18}'
}
]
tools = [
{
type: :function,
name: "get_weather",
description: "Get the weather for a city",
parameters: {
type: :object,
properties: { city: { type: :string } },
required: ["city"],
additionalProperties: false
},
strict: true
}
]
response = client.responses.create(
model: "gpt-6-astra",
input: input,
tools: tools
)
puts(response.output_text)
最终回答示例:
来源示例26(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
"It's about 15°C in Paris, 18°C in Bogotá, and I've sent that email to Bob."
其他配置
工具选择
默认由模型决定何时调用及调用多少。tool_choice 可控制行为:
| 配置 | 行为 |
|---|---|
"auto" |
默认,零个、一个或多个函数 |
"required" |
一个或多个函数 |
{"type": "function", "name": "get_weather"} |
恰好调用指定函数 |
allowed_tools |
仅允许可用工具中的指定子集 |
"none" |
模拟未传入函数的行为 |
当只想开放子集、又不想改动完整工具清单而破坏提示缓存时,可用 allowed_tools。
来源示例27(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
"tool_choice": {
"type": "allowed_tools",
"mode": "auto",
"tools": [
{ "type": "function", "name": "get_weather" },
{ "type": "function", "name": "search_docs" }
]
}
}
结合搜索时,tool_choice 约束当前轮已经可调用的工具;加载子集后特别适用。
并行函数调用
从GPT-5开始的受支持模型,在同时开放内置工具时也能并行调用函数;但内置工具不能加入并行函数调用批次。parallel_tool_calls: false 将一轮限制为零个或一个工具调用。
来源说明:微调模型同轮调用多个函数时,这些调用会关闭严格模式。gpt-4.1-nano-2025-04-14 在启用并行时可能对同一工具多次调用,建议为该快照禁用并行。
严格模式
strict: true 让调用可靠符合模式,而不是尽力匹配,官方建议开启。它使用结构化输出,因此 parameters 的每个对象都必须 additionalProperties: false,且 properties 中所有字段都列入 required。可选值通过类型中允许 null 表达。
显式严格模式但模式不满足条件时,请求会被拒绝,并说明缺少的约束。省略时,Responses会尽量规范化为严格模式,无法兼容则回退为非严格尽力调用,响应工具显示 strict: false;Chat Completions默认非严格。Responses要明确退出严格模式,应设置 strict: false。
开启与关闭示例:
来源示例28(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
本段复用的中文释义:译释16。
{
"type": "function",
"name": "get_weather",
"description": "Retrieves current weather for the given location.",
//highlight-start
"strict": true,
//highlight-end
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
},
"units": {
//highlight-start
"type": ["string", "null"],
//highlight-end
"enum": ["celsius", "fahrenheit"],
"description": "Units the temperature will be returned in."
}
},
//highlight-start
"required": ["location", "units"],
"additionalProperties": false
//highlight-end
}
}
来源示例29(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
本段复用的中文释义:译释16。
{
"type": "function",
"name": "get_weather",
"description": "Retrieves current weather for the given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
},
"units": {
//highlight-start
"type": "string",
//highlight-end
"enum": ["celsius", "fahrenheit"],
"description": "Units the temperature will be returned in."
}
},
//highlight-start
"required": ["location"],
//highlight-end
}
}
Playground生成的模式开启严格模式。严格模式不支持全部JSON Schema特性,参见受支持模式。来源针对微调模型另说明:首次请求要处理模式,之后缓存;频繁变动模式可能增加延迟;模式为性能而缓存,不符合ZDR条件。
流式输出
设置 stream: true 接收事件,可以在模型填写参数时展示函数名和参数进度。
来源示例30(javascript)
程序中的自然语言译释15:
巴黎今天天气怎么样?
程序中的自然语言译释118:
根据提供的坐标获取当前摄氏温度。
// [中文] 启用stream接收函数调用事件;此段展示事件,不代表已执行业务函数。
import { OpenAI } from "openai";
const openai = new OpenAI();
const tools = [
{
type: "function",
name: "get_weather",
description: "Get current temperature for provided coordinates in celsius.",
parameters: {
type: "object",
properties: {
latitude: { type: "number" },
longitude: { type: "number" },
},
required: ["latitude", "longitude"],
additionalProperties: false,
},
strict: true,
},
];
const stream = await openai.responses.create({
model: "gpt-6-astra",
input: [{ role: "user", content: "What's the weather like in Paris today?" }],
tools,
stream: true,
store: true,
});
for await (const event of stream) {
console.log(event);
}
来源示例31(python)
程序中的自然语言译释14:
获取指定地点的当前温度。
本段复用的中文释义:译释15、译释16。
## [中文] 启用stream接收函数调用事件;此段展示事件,不代表已执行业务函数。
from openai import OpenAI
client = OpenAI()
tools = [
{
"type": "function",
"name": "get_weather",
"description": "Get current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia",
}
},
"required": ["location"],
"additionalProperties": False,
},
}
]
stream = client.responses.create(
model="gpt-6-astra",
input=[{"role": "user", "content": "What's the weather like in Paris today?"}],
tools=tools,
stream=True,
)
for event in stream:
print(event)
来源示例32(go)
本段复用的中文释义:译释15、译释16。
// [中文] 启用stream接收函数调用事件;此段展示事件,不代表已执行业务函数。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
parameters := map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]any{"type": "string", "description": "City and country e.g. Bogotá, Colombia"},
},
"required": []string{"location"},
"additionalProperties": false,
}
tool := responses.ToolParamOfFunction("get_weather", parameters, true)
stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What's the weather like in Paris today?")},
Tools: []responses.ToolUnionParam{tool},
})
for stream.Next() {
fmt.Println(stream.Current().Type)
}
if err := stream.Err(); err != nil {
panic(err)
}
}
来源示例33(java)
程序中的自然语言译释119:
巴黎天气如何?
本段复用的中文释义:译释117。
// [中文] 启用stream接收函数调用事件;此段展示事件,不代表已执行业务函数。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
import java.util.List;
import java.util.Map;
FunctionTool weather =
FunctionTool.builder()
.name("get_weather")
.description("Get the weather for a city.")
.parameters(
FunctionTool.Parameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties", JsonValue.from(Map.of("city", Map.of("type", "string"))))
.putAdditionalProperty("required", JsonValue.from(List.of("city")))
.putAdditionalProperty("additionalProperties", JsonValue.from(false))
.build())
.strict(true)
.build();
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What is the weather in Paris?")
.addTool(weather)
.build();
try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
stream.stream()
.forEach(
event -> {
System.out.println(event);
event
.outputItemAdded()
.ifPresent(added -> System.out.println("response.output_item.added: " + added));
event
.functionCallArgumentsDelta()
.ifPresent(
delta ->
System.out.println("response.function_call_arguments.delta: " + delta));
});
}
来源示例34(ruby)
本段复用的中文释义:译释117、译释119。
## [中文] 启用stream接收函数调用事件;此段展示事件,不代表已执行业务函数。
require "openai"
client = OpenAI::Client.new
stream = client.responses.stream(
model: "gpt-6-astra",
input: "What is the weather in Paris?",
tools: [
{
type: :function,
name: "get_weather",
description: "Get the weather for a city",
parameters: {
type: :object,
properties: { city: { type: :string } },
required: ["city"],
additionalProperties: false
},
strict: true
}
]
)
stream.each { |event| puts(event.type) }
事件示例:
来源示例35(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
{"type":"response.output_item.added","response_id":"resp_1234xyz","output_index":0,"item":{"type":"function_call","id":"fc_1234xyz","call_id":"call_1234xyz","name":"get_weather","arguments":""}}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"{\""}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"location"}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"\":\""}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"Paris"}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":","}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":" France"}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"\"}"}
{"type":"response.function_call_arguments.done","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"arguments":"{\"location\":\"Paris, France\"}"}
{"type":"response.output_item.done","response_id":"resp_1234xyz","output_index":0,"item":{"type":"function_call","id":"fc_1234xyz","call_id":"call_1234xyz","name":"get_weather","arguments":"{\"location\":\"Paris, France\"}"}}
此时累积的不是普通文本 content,而是JSON编码的 arguments。每个函数调用先产生 response.output_item.added:
| 字段 | 含义 |
|---|---|
type |
固定为response.output_item.added |
sequence_number |
事件序列号 |
output_index |
响应输出项索引,区分各调用 |
item |
进行中的调用,含 name、arguments、id |
随后产生多次 response.function_call_arguments.delta:
| 字段 | 含义 |
|---|---|
type |
固定为response.function_call_arguments.delta |
sequence_number |
事件序列号 |
item_id |
增量所属函数调用项ID |
output_index |
对应输出项索引 |
delta |
参数字符串增量 |
累积增量示例:
来源示例36(javascript)
// [中文] 按output_index保存调用项,并把后续arguments增量拼接到同一项。
const finalToolCalls = {};
for await (const event of stream) {
if (
event.type === "response.output_item.added" &&
event.item.type === "function_call"
) {
finalToolCalls[event.output_index] = event.item;
} else if (event.type === "response.function_call_arguments.delta") {
const index = event.output_index;
if (finalToolCalls[index]) {
finalToolCalls[index].arguments += event.delta;
}
}
}
来源示例37(python)
## [中文] 按output_index保存调用项,并把后续arguments增量拼接到同一项。
final_tool_calls = {}
for event in stream:
if event.type == "response.output_item.added":
final_tool_calls[event.output_index] = event.item
elif event.type == "response.function_call_arguments.delta":
index = event.output_index
if final_tool_calls[index]:
final_tool_calls[index].arguments += event.delta
来源示例38(go)
本段复用的中文释义:译释15。
// [中文] 按output_index保存调用项,并把后续arguments增量拼接到同一项。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
parameters := map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]any{"type": "string"},
},
"required": []string{"location"},
"additionalProperties": false,
}
tool := responses.ToolParamOfFunction("get_weather", parameters, true)
stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("What's the weather like in Paris today?"),
},
Tools: []responses.ToolUnionParam{tool},
})
finalToolCalls := map[int64]responses.ResponseFunctionToolCall{}
for stream.Next() {
event := stream.Current()
if event.Type == "response.output_item.added" && event.Item.Type == "function_call" {
finalToolCalls[event.OutputIndex] = event.Item.AsFunctionCall()
}
if event.Type == "response.function_call_arguments.delta" {
finalToolCall, ok := finalToolCalls[event.OutputIndex]
if !ok {
continue
}
finalToolCall.Arguments += event.Delta
finalToolCalls[event.OutputIndex] = finalToolCall
}
}
if err := stream.Err(); err != nil {
panic(err)
}
fmt.Println(finalToolCalls)
}
来源示例39(java)
本段复用的中文释义:译释117、译释119。
// [中文] 按output_index保存调用项,并把后续arguments增量拼接到同一项。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseFunctionToolCall;
import com.openai.models.responses.ResponseStreamEvent;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
FunctionTool weather =
FunctionTool.builder()
.name("get_weather")
.description("Get the weather for a city.")
.parameters(
FunctionTool.Parameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties", JsonValue.from(Map.of("location", Map.of("type", "string"))))
.putAdditionalProperty("required", JsonValue.from(List.of("location")))
.putAdditionalProperty("additionalProperties", JsonValue.from(false))
.build())
.strict(true)
.build();
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What is the weather in Paris?")
.addTool(weather)
.build();
Map<Long, ResponseFunctionToolCall> toolCalls = new LinkedHashMap<>();
try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
stream.stream()
.forEach(
event -> {
event
.outputItemAdded()
.ifPresent(
added ->
added
.item()
.functionCall()
.ifPresent(call -> toolCalls.put(added.outputIndex(), call)));
event
.functionCallArgumentsDelta()
.ifPresent(
delta ->
toolCalls.computeIfPresent(
delta.outputIndex(),
(ignored, call) ->
call.toBuilder()
.arguments(call.arguments() + delta.delta())
.build()));
});
}
toolCalls.values().forEach(System.out::println);
来源示例40(ruby)
本段复用的中文释义:译释119。
## [中文] 按output_index保存调用项,并把后续arguments增量拼接到同一项。
require "openai"
client = OpenAI::Client.new
stream = client.responses.stream(
model: "gpt-6-astra",
input: "What is the weather in Paris?",
tools: [
{
type: :function,
name: "get_weather",
parameters: {
type: :object,
properties: { location: { type: :string } },
required: ["location"],
additionalProperties: false
},
strict: true
}
]
)
final_tool_calls = {}
stream.each do |event|
case event
when OpenAI::Models::Responses::ResponseOutputItemAddedEvent
item = event.item
next unless item.is_a?(OpenAI::Models::Responses::ResponseFunctionToolCall)
final_tool_calls[event.output_index] = {
id: item.id,
call_id: item.call_id,
name: item.name,
type: item.type,
arguments: item.arguments.dup
}
when OpenAI::Models::Responses::ResponseFunctionCallArgumentsDeltaEvent
tool_call = final_tool_calls[event.output_index]
tool_call[:arguments] << event.delta if tool_call
end
end
puts(final_tool_calls.sort.to_h.values)
最终累积对象示例:
来源示例41(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
{
"type": "function_call",
"id": "fc_1234xyz",
"call_id": "call_2345abc",
"name": "get_weather",
"arguments": "{\"location\":\"Paris, France\"}"
}
参数完成后产生 response.function_call_arguments.done,其 arguments 是最终参数字符串,使用 item_id 和 output_index 关联此前调用;正式事件还含 type 与 sequence_number。该事件不包含完整 item。完整函数调用项由 response.output_item.done 的 item 提供,其中包含 name、arguments、id、call_id 等信息。
原指南的字段表与同页事件示例不一致:它把完整调用项放进参数完成事件的说明。本译稿依据正式Responses流式事件参考区分二者,来源程序保留。不要将Realtime同名事件的字段直接套用到Responses。
自定义工具
自定义工具与模式驱动函数类似,但输入是任意字符串,无需包装JSON,适合自由文本或自定义语法。以下定义接收Python代码文本的工具:
来源示例42(javascript)
程序中的自然语言译释17:
使用code_exec工具,在控制台打印hello world。
程序中的自然语言译释120:
执行任意Python代码。这是工具描述,实际执行器由应用实现。
// [中文] 声明接收自由文本的code_exec自定义工具;此请求只让模型生成调用,未提供Python执行器。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
input: "Use the code_exec tool to print hello world to the console.",
tools: [
{
type: "custom",
name: "code_exec",
description: "Executes arbitrary Python code.",
},
],
});
console.log(response.output);
来源示例43(python)
本段复用的中文释义:译释17、译释120。
## [中文] 声明接收自由文本的code_exec自定义工具;此请求只让模型生成调用,未提供Python执行器。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Use the code_exec tool to print hello world to the console.",
tools=[
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary Python code.",
}
],
)
print(response.output)
来源示例44(go)
本段复用的中文释义:译释17、译释120。
// [中文] 声明接收自由文本的code_exec自定义工具;此请求只让模型生成调用,未提供Python执行器。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfCustom("code_exec")
tool.OfCustom.Description = openai.String("Executes arbitrary Python code.")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the code_exec tool to print hello world to the console.")},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
}
来源示例45(java)
程序中的自然语言译释121:
使用code_exec打印hello world。
本段复用的中文释义:译释120。
// [中文] 声明接收自由文本的code_exec自定义工具;此请求只让模型生成调用,未提供Python执行器。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.CustomTool;
import com.openai.models.responses.ResponseCreateParams;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Use code_exec to print hello world.")
.addTool(
CustomTool.builder()
.name("code_exec")
.description("Executes arbitrary Python code.")
.build())
.build();
client.responses().create(params).output().forEach(System.out::println);
来源示例46(ruby)
本段复用的中文释义:译释120、译释121。
## [中文] 声明接收自由文本的code_exec自定义工具;此请求只让模型生成调用,未提供Python执行器。
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "Use code_exec to print hello world.",
tools: [
{
type: :custom,
name: "code_exec",
description: "Executes arbitrary Python code."
}
]
)
puts(response.output)
输出数组仍有模型产生的调用,但输入为普通文本:
来源示例47(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
[
{
"id": "rs_6890e972fa7c819ca8bc561526b989170694874912ae0ea6",
"type": "reasoning",
"content": [],
"summary": []
},
{
"id": "ctc_6890e975e86c819c9338825b3e1994810694874912ae0ea6",
"type": "custom_tool_call",
"status": "completed",
"call_id": "call_aGiFQkRWSWAIsMQ19fKqxUgb",
"input": "print(\"hello world\")",
"name": "code_exec"
}
]
上下文无关文法
上下文无关文法(CFG)用一组规则定义合法文本。配置自定义工具的 grammar 可约束模型输入,支持 lark 和 regex 两种语法。
Lark文法
来源示例48(javascript)
程序中的自然语言译释19:
使用math_exp工具,计算4加4。
程序中的自然语言译释122:
生成符合要求的数学表达式。
// [中文] 以Lark文法限制math_exp的输入表达式;规则描述加法、乘法和整数,不执行数学业务代码。
import OpenAI from "openai";
const client = new OpenAI();
const grammar = `
start: expr
expr: term (SP ADD SP term)* -> add
| term
term: factor (SP MUL SP factor)* -> mul
| factor
factor: INT
SP: " "
ADD: "+"
MUL: "*"
%import common.INT
`;
const response = await client.responses.create({
model: "gpt-6-astra",
input: "Use the math_exp tool to add four plus four.",
tools: [
{
type: "custom",
name: "math_exp",
description: "Creates valid mathematical expressions",
format: {
type: "grammar",
syntax: "lark",
definition: grammar,
},
},
],
});
console.log(response.output);
来源示例49(python)
本段复用的中文释义:译释19、译释122。
## [中文] 以Lark文法限制math_exp的输入表达式;规则描述加法、乘法和整数,不执行数学业务代码。
from openai import OpenAI
client = OpenAI()
grammar = """
start: expr
expr: term (SP ADD SP term)* -> add
| term
term: factor (SP MUL SP factor)* -> mul
| factor
factor: INT
SP: " "
ADD: "+"
MUL: "*"
%import common.INT
"""
response = client.responses.create(
model="gpt-6-astra",
input="Use the math_exp tool to add four plus four.",
tools=[
{
"type": "custom",
"name": "math_exp",
"description": "Creates valid mathematical expressions",
"format": {
"type": "grammar",
"syntax": "lark",
"definition": grammar,
},
}
],
)
print(response.output)
来源示例50(go)
本段复用的中文释义:译释19、译释122。
// [中文] 以Lark文法限制math_exp的输入表达式;规则描述加法、乘法和整数,不执行数学业务代码。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
grammar := `start: expr
expr: term (SP ADD SP term)* -> add
| term
term: factor (SP MUL SP factor)* -> mul
| factor
factor: INT
SP: " "
ADD: "+"
MUL: "*"
%import common.INT`
tool := responses.ToolParamOfCustom("math_exp")
tool.OfCustom.Description = openai.String("Creates valid mathematical expressions")
tool.OfCustom.Format = shared.CustomToolInputFormatParamOfGrammar(grammar, "lark")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the math_exp tool to add four plus four.")},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
}
来源示例51(java)
程序中的自然语言译释123:
使用math_exp计算4加4。
本段复用的中文释义:译释122。
// [中文] 以Lark文法限制math_exp的输入表达式;规则描述加法、乘法和整数,不执行数学业务代码。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.CustomToolInputFormat;
import com.openai.models.responses.CustomTool;
import com.openai.models.responses.ResponseCreateParams;
String grammar =
"""
start: expr
expr: term (SP ADD SP term)*
term: INT
SP: " "
ADD: "+"
%import common.INT
""";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Use math_exp to add four plus four.")
.addTool(
CustomTool.builder()
.name("math_exp")
.description("Creates valid mathematical expressions.")
.format(
CustomToolInputFormat.Grammar.builder()
.syntax(CustomToolInputFormat.Grammar.Syntax.LARK)
.definition(grammar)
.build())
.build())
.build();
client.responses().create(params).output().forEach(System.out::println);
来源示例52(ruby)
本段复用的中文释义:译释122、译释123。
## [中文] 以Lark文法限制math_exp的输入表达式;规则描述加法、乘法和整数,不执行数学业务代码。
require "openai"
client = OpenAI::Client.new
grammar = <<~LARK
start: expr
expr: term (SP ADD SP term)*
term: INT
SP: " "
ADD: "+"
%import common.INT
LARK
response = client.responses.create(
model: "gpt-6-astra",
input: "Use math_exp to add four plus four.",
tools: [
{
type: :custom,
name: "math_exp",
description: "Creates valid mathematical expressions.",
format: {
type: :grammar,
syntax: :lark,
definition: grammar
}
}
]
)
puts(response.output)
输出应符合定义:
来源示例53(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
[
{
"id": "rs_6890ed2b6374819dbbff5353e6664ef103f4db9848be4829",
"type": "reasoning",
"content": [],
"summary": []
},
{
"id": "ctc_6890ed2f32e8819daa62bef772b8c15503f4db9848be4829",
"type": "custom_tool_call",
"status": "completed",
"call_id": "call_pmlLjmvG33KJdyVdC4MVdk5N",
"input": "4 + 4",
"name": "math_exp"
}
]
使用Lark的变体,采样由LLGuidance约束。不支持词法正则中的环视、惰性量词 *?、+?、??,以及终结符优先级、模板、除内置 %import common 外的导入和 %declare。可用Lark IDE试验。
限制文法复杂度
只保留工具需要的规则与模式。过于复杂可能导致API报错,应先确认兼容性。简单文法通常更可靠;复杂文法可能需要同时迭代文法、提示词和工具描述,防止模型生成偏离预期分布的内容。
正确与错误的模式
正确:单个有界终结符。
来源示例54(text):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
start: SENTENCE
SENTENCE: /[A-Za-z, ]*(the hero|a dragon|an old man|the princess)[A-Za-z, ]*(fought|saved|found|lost)[A-Za-z, ]*(a treasure|the kingdom|a secret|his way)[A-Za-z, ]*\./
错误:把自由文本分散到多个规则与终结符,试图让规则决定切分位置。词法分析会贪婪匹配,导致失去边界控制。
来源示例55(text):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
start: sentence
sentence: /[A-Za-z, ]+/ subject /[A-Za-z, ]+/ verb /[A-Za-z, ]+/ object /[A-Za-z, ]+/
小写规则不决定终结符如何从输入切分,只有终结符定义负责。需要匹配锚点间自由文本时,用一个完整正则终结符一次性匹配目标结构。
终结符与规则
Lark终结符用于词法标记,惯例为大写;规则用于语法产生式,惯例为小写。保持文法明确、避免无谓复杂,并清晰区分职责。终结符正则采用Rust regex语法,不是Python的 re。
关键概念与最佳实践
先词法、后语法。 终结符在语法规则应用之前按贪婪、最长匹配识别。拆分规则不能约束正则内部如何匹配。
自由文本片段尽量用一个终结符。 在任意文本中识别锚点之间内容时,用一个终结符表达,不要交织自由文本终结符和语法规则,否则词法分析可能忽略预期边界。
用规则组合离散标记。 数字、关键字、标点等有明确分隔的标记适合由规则组成更大结构,两个终结符之间的任意文本不适合这样限制。
终结符应聚焦、有界、自包含。 使用明确字符类和有界量词,如 {0,10},避免到处使用无界 *。来源以 /[^.\n]{0,10}*\./ 对比 /.+\./ 说明其限制增长的意图;具体文法仍须先验证。
规则组合标记,不控制正则内部。 正确的规则组合示例:
来源示例56(text):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
start: expr
NUMBER: /[0-9]+/
PLUS: "+"
MINUS: "-"
expr: term (("+"|"-") term)*
term: NUMBER
显式处理空白。 不依赖开放式 %ignore;无界忽略可能让文法过于复杂或生成偏离。应在允许空白处显式安排终结符。
排错
- API拒绝复杂文法时,简化规则与终结符,去掉无界
%ignore。 - 出现非预期标记时,检查终结符重叠和贪婪词法匹配。
- 输出极长、重复或语法合法但语义错误时,收紧文法;迭代提示并加入少量示例,完善工具描述;可尝试把推理强度从medium提高到high。
正则文法
来源示例57(javascript)
程序中的自然语言译释20:
使用timestamp工具,保存2025年8月7日上午10点的时间戳。各语言提示词略有措辞差异,日期输入语法以各段grammar为准。
程序中的自然语言译释21:
按日期加时间的格式保存时间戳;该Python描述称为24小时格式,实际正则仍含AM/PM分支,不应只凭description判断格式。
// [中文] 以正则限制timestamp工具的日期时间输入;各语言description措辞不同,实际格式由grammar定义。
import OpenAI from "openai";
const client = new OpenAI();
const grammar =
"^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\\s+(?P<day>\\d{1,2})(?:st|nd|rd|th)?\\s+(?P<year>\\d{4})\\s+at\\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$";
const response = await client.responses.create({
model: "gpt-6-astra",
input:
"Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",
tools: [
{
type: "custom",
name: "timestamp",
description: "Saves a timestamp in date + time in 24-hr format.",
format: {
type: "grammar",
syntax: "regex",
definition: grammar,
},
},
],
});
console.log(response.output);
来源示例58(python)
本段复用的中文释义:译释20、译释21。
## [中文] 以正则限制timestamp工具的日期时间输入;各语言description措辞不同,实际格式由grammar定义。
from openai import OpenAI
client = OpenAI()
grammar = r"^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?\s+(?P<year>\d{4})\s+at\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$"
response = client.responses.create(
model="gpt-6-astra",
input="Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",
tools=[
{
"type": "custom",
"name": "timestamp",
"description": "Saves a timestamp in date + time in 24-hr format.",
"format": {
"type": "grammar",
"syntax": "regex",
"definition": grammar,
},
}
],
)
print(response.output)
来源示例59(go)
程序中的自然语言译释125:
按日期与时间格式保存时间戳。
本段复用的中文释义:译释20。
// [中文] 以正则限制timestamp工具的日期时间输入;各语言description措辞不同,实际格式由grammar定义。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
grammar := `^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?\s+(?P<year>\d{4})\s+at\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$`
tool := responses.ToolParamOfCustom("timestamp")
tool.OfCustom.Description = openai.String("Saves a timestamp in date and time format.")
tool.OfCustom.Format = shared.CustomToolInputFormatParamOfGrammar(grammar, "regex")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.")},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
}
来源示例60(java)
程序中的自然语言译释124:
使用timestamp保存2025年8月7日上午10点。
本段复用的中文释义:译释20、译释125。
// [中文] 以正则限制timestamp工具的日期时间输入;各语言description措辞不同,实际格式由grammar定义。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.CustomToolInputFormat;
import com.openai.models.responses.CustomTool;
import com.openai.models.responses.ResponseCreateParams;
String grammar =
"^(January|February|March|April|May|June|July|August|September|October|November|December) "
+ "\\d{1,2}(st|nd|rd|th)? \\d{4} at (0?[1-9]|1[0-2])(AM|PM)$";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Use timestamp to save August 7th 2025 at 10AM.")
.addTool(
CustomTool.builder()
.name("timestamp")
.description("Saves a timestamp in date and time format.")
.format(
CustomToolInputFormat.Grammar.builder()
.syntax(CustomToolInputFormat.Grammar.Syntax.REGEX)
.definition(grammar)
.build())
.build())
.build();
client.responses().create(params).output().forEach(System.out::println);
来源示例61(ruby)
本段复用的中文释义:译释20、译释124、译释125。
## [中文] 以正则限制timestamp工具的日期时间输入;各语言description措辞不同,实际格式由grammar定义。
require "openai"
client = OpenAI::Client.new
grammar = "^(January|February|March|April|May|June|July|August|September|October|November|December) \\d{1,2}(st|nd|rd|th)? \\d{4} at (0?[1-9]|1[0-2])(AM|PM)$"
response = client.responses.create(
model: "gpt-6-astra",
input: "Use timestamp to save August 7th 2025 at 10AM.",
tools: [
{
type: :custom,
name: "timestamp",
description: "Saves a timestamp in date and time format.",
format: {
type: :grammar,
syntax: :regex,
definition: grammar
}
}
]
)
puts(response.output)
输出应符合定义的正则:
来源示例62(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
本段复用的中文释义:译释20。
[
{
"id": "rs_6894f7a3dd4c81a1823a723a00bfa8710d7962f622d1c260",
"type": "reasoning",
"content": [],
"summary": []
},
{
"id": "ctc_6894f7ad7fb881a1bffa1f377393b1a40d7962f622d1c260",
"type": "custom_tool_call",
"status": "completed",
"call_id": "call_8m4XCnYvEmFlzHgDHbaOCFlK",
"input": "August 7th 2025 at 10AM",
"name": "timestamp"
}
]
同样使用Rust regex语法,不支持环视和惰性量词。
关键概念与最佳实践
模式必须放在一行;匹配输入换行时使用转义 \n,不要使用允许跨行模式的verbose或extended模式。将正则作为普通模式字符串提供,不要用 // 包裹。