函数工具让智能体能够调用您的应用程序代码。您定义函数及其参数,智能体发起调用请求,您的代码返回结果,然后执行框架继续执行当前轮次。
您的处理程序可以在应用服务器、工作进程或您控制的环境中运行。将环境关联到会话并不会自动在该环境中运行函数工具。
如果您使用 Responses API 中的函数调用,就可以在此处介绍的会话流程中复用您的函数实现。
在配置智能体时,将函数定义添加到 agent.tools。为函数指定名称、描述以及定义其参数的 JSON Schema:
1234567891011{
"type": "function",
"name": "get_customer",
"description": "Look up a customer by ID.",
"parameters": {
"type": "object",
"properties": { "customer_id": { "type": "string" } },
"required": ["customer_id"],
"additionalProperties": false
}
}
当智能体需要函数结果时,会话会发出 agent.session.requires_action 事件。从 event.session.required_actions 中读取待处理的调用。您也可以不使用流式传输,而是获取会话并读取 session.required_actions。
required_actions 中的函数条目如下所示:
1234567{
"type": "function_call",
"turn_id": "turn_123",
"call_id": "call_123",
"name": "get_customer",
"arguments": { "customer_id": "123" }
}
使用提供的参数运行指定名称的函数。根据 required_actions 判断哪些调用需要返回结果;仅凭会话历史中的 function_call 条目,无法确定某个调用是否仍在等待结果。
向会话事件端点发送 agent.session.input.tool_result。从待处理操作中复制 turn_id 和 call_id:
- 成功时,设置
success: true,并以字符串或受支持的内容数组形式提供 output。请将 JSON 对象序列化为字符串。
- 出错时,设置
success: false,并在 error 中提供智能体可以使用的错误消息。
对于每个待处理的 get_customer 调用,执行查询并返回结果。这里的 action 是 required_actions 中的条目:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16const result = {
turn_id: action.turn_id,
call_id: action.call_id,
};
let outcome;
outcome = {
success: true,
output: JSON.stringify(getCustomer(action.arguments)),
};
await client.beta.agents.sessions.events.create(sessionId, {
events: [
{ type: "agent.session.input.tool_result", ...result, ...outcome },
],
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14import json
action = action.to_dict()
result = {
"type": "agent.session.input.tool_result",
"turn_id": action["turn_id"],
"call_id": action["call_id"],
}
output = get_customer(action["arguments"])
result.update(success=True, output=json.dumps(output))
client.beta.agents.sessions.events.create(session_id, events=[result])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24result := openai.AgentSessionInputParamAgentSessionInputToolResult{
TurnID: action.TurnID,
CallID: action.CallID,
}
arguments := action.Arguments.(map[string]any)
customerID := arguments["customer_id"].(string)
var customer any
if customerID == "123" {
customer = map[string]any{"name": "Example Customer", "plan": "pro"}
}
output, err := json.Marshal(map[string]any{"found": customer != nil, "customer": customer})
if err != nil {
panic(err)
}
result.Success = true
result.Output = openai.AgentFunctionCallOutputParamUnion{OfString: openai.String(string(output))}
err = client.Beta.Agents.Sessions.Events.New(ctx, session.ID, openai.BetaAgentSessionEventNewParams{
Events: []openai.AgentSessionInputParamUnion{{OfParamAgentSessionInputToolResult: &result}},
})
if err != nil {
panic(err)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25var json = new JsonMapper();
var result =
AgentSessionInputParam.AgentSessionInputToolResult.builder()
.turnId(action.turnId())
.callId(action.callId());
var arguments = json.valueToTree(action._arguments());
boolean found = arguments.path("customer_id").asText().equals("123");
var output = json.createObjectNode().put("found", found);
if (found)
output.putObject("customer").put("name", "Example Customer").put("plan", "pro");
else output.putNull("customer");
result.success(true).output(json.writeValueAsString(output));
client
.beta()
.agents()
.sessions()
.events()
.create(
EventCreateParams.builder()
.sessionId(sessionId)
.addEvent(result.build())
.build());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18require "json"
result = {
type: "agent.session.input.tool_result",
turn_id: action.turn_id,
call_id: action.call_id
}
arguments = action.arguments
customer_id = arguments[:customer_id] || arguments["customer_id"]
customer = (customer_id == "123") ? {
name: "Example Customer",
plan: "pro"
} : nil
result[:success] = true
result[:output] = JSON.generate(found: !customer.nil?, customer: customer)
client.beta.agents.sessions.events.create(session.id, events: [result])
执行框架收到所需结果后,会继续执行当前轮次。跟踪会话事件和条目,以检查该轮次的执行结果并获取其输出。
获取会话以查找待处理操作。如果您已经运行过某个函数,请使用相同的 turn_id 和 call_id 提交已保存的结果。
对于有副作用的函数,请按会话、轮次和调用 ID 持久化存储结果。如果函数可能已执行成功,但未保存结果,请先核实执行结果,再重新运行函数。
函数默认会预先加载。要延迟加载某个函数,请在其定义中设置 defer_loading: true,并在 agent.tools 中添加 { "type": "tool_search" }。完整示例请参阅工具搜索。