SPB Git

Repository Public

functions.md 6.3 KB 196 lines markdown

1# Functions23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45Function tools let an agent call your application code. You define the function and its arguments. The agent requests a call, your code returns a result, and the harness continues the turn.67Your handler can run in an application server, a worker, or an environment you control. Attaching an environment to a session does not automatically run function tools there.89101112If you use [function calling in the Responses API](https://developers.openai.com/api/docs/guides/function-calling), you can reuse your function implementation with the session flow described here.1314151617## Define a function1819Add a function definition to `agent.tools` when you [configure the agent](https://developers.openai.com/api/docs/guides/agents-api/configuration). Give it a name, a description, and a JSON Schema for its arguments:2021```json22{23  "type": "function",24  "name": "get_customer",25  "description": "Look up a customer by ID.",26  "parameters": {27    "type": "object",28    "properties": { "customer_id": { "type": "string" } },29    "required": ["customer_id"],30    "additionalProperties": false31  }32}33```3435363738## Handle required actions3940When the agent needs a function result, the session emits `agent.session.requires_action`. Read the pending calls from `event.session.required_actions`. You can also [retrieve the session](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/methods/retrieve) and read `session.required_actions` without streaming.4142A function entry in `required_actions` looks like this:4344```json45{46  "type": "function_call",47  "turn_id": "turn_123",48  "call_id": "call_123",49  "name": "get_customer",50  "arguments": { "customer_id": "123" }51}52```5354Run the named function with the supplied arguments. Use `required_actions` to decide which calls need results; a `function_call` item in session history alone does not establish that a result is pending.5556## Return the result5758Send `agent.session.input.tool_result` to the [session events endpoint](https://developers.openai.com/api/reference/resources/beta/subresources/agents/subresources/sessions/subresources/events/methods/create). Copy `turn_id` and `call_id` from the pending action:5960- For success, set `success: true` and supply `output` as a string or a supported content array. Serialize JSON objects to strings.61- For an error, set `success: false` and supply an `error` message that the agent can use.6263646566For each pending `get_customer` call, run your lookup and return its result. Here, `action` is the entry from `required_actions`:6768Return a function result6970```javascript71const result = {72  turn_id: action.turn_id,73  call_id: action.call_id,74};75let outcome;7677outcome = {78  success: true,79  output: JSON.stringify(getCustomer(action.arguments)),80};8182await client.beta.agents.sessions.events.create(sessionId, {83  events: [84    { type: "agent.session.input.tool_result", ...result, ...outcome },85  ],86});87```8889```python90import json9192action = action.to_dict()9394result = {95    "type": "agent.session.input.tool_result",96    "turn_id": action["turn_id"],97    "call_id": action["call_id"],98}99100output = get_customer(action["arguments"])101result.update(success=True, output=json.dumps(output))102103client.beta.agents.sessions.events.create(session_id, events=[result])104```105106```go107result := openai.AgentSessionInputParamAgentSessionInputToolResult{108	TurnID: action.TurnID,109	CallID: action.CallID,110}111112arguments := action.Arguments.(map[string]any)113customerID := arguments["customer_id"].(string)114var customer any115if customerID == "123" {116	customer = map[string]any{"name": "Example Customer", "plan": "pro"}117}118output, err := json.Marshal(map[string]any{"found": customer != nil, "customer": customer})119if err != nil {120	panic(err)121}122result.Success = true123result.Output = openai.AgentFunctionCallOutputParamUnion{OfString: openai.String(string(output))}124125err = client.Beta.Agents.Sessions.Events.New(ctx, session.ID, openai.BetaAgentSessionEventNewParams{126	Events: []openai.AgentSessionInputParamUnion{{OfParamAgentSessionInputToolResult: &result}},127})128if err != nil {129	panic(err)130}131```132133```java134var json = new JsonMapper();135136var result =137    AgentSessionInputParam.AgentSessionInputToolResult.builder()138        .turnId(action.turnId())139        .callId(action.callId());140var arguments = json.valueToTree(action._arguments());141142boolean found = arguments.path("customer_id").asText().equals("123");143var output = json.createObjectNode().put("found", found);144if (found)145  output.putObject("customer").put("name", "Example Customer").put("plan", "pro");146else output.putNull("customer");147result.success(true).output(json.writeValueAsString(output));148149client150    .beta()151    .agents()152    .sessions()153    .events()154    .create(155        EventCreateParams.builder()156            .sessionId(sessionId)157            .addEvent(result.build())158            .build());159```160161```ruby162require "json"163164result = {165  type: "agent.session.input.tool_result",166  turn_id: action.turn_id,167  call_id: action.call_id168}169arguments = action.arguments170171customer_id = arguments[:customer_id] || arguments["customer_id"]172customer = (customer_id == "123") ? {173  name: "Example Customer",174  plan: "pro"175} : nil176result[:success] = true177result[:output] = JSON.generate(found: !customer.nil?, customer: customer)178179client.beta.agents.sessions.events.create(session.id, events: [result])180```181182183The harness continues the turn after it receives the required results. Follow [session events and items](https://developers.openai.com/api/docs/guides/agents-api/sessions/events) to check the turn's outcome and retrieve its output.184185## Recover after a disconnect186187Retrieve the session to find pending actions. If you already ran a function, submit its saved result with the same `turn_id` and `call_id`.188189For functions with side effects, store results durably by session, turn, and call ID. If execution might have succeeded but no result was saved, check the outcome before running the function again.190191192193194## Load functions on demand195196Functions load eagerly by default. To defer a function, set `defer_loading: true` on its definition and include `{ "type": "tool_search" }` in `agent.tools`. See [Tool search](https://developers.openai.com/api/docs/guides/tools-tool-search#agents-api) for a complete example.
Files main
Menu

Theme