Lompat ke konten

Pelajaran 10 ยท Tool Calling and Agents

Function Calling with the Responses API

Define function tools, handle function_call items, return function_call_output results, control tool_choice and run a safe, bounded tool-calling loop.

A model knows nothing about your order database and cannot send an email. Function calling lets it ask your program to do such things. You describe your functions. The model replies with a request to call one, with arguments. Your code decides whether to run it, runs it, and sends back the result. The model then continues.

If the general idea is new, what are tools explains it without any one vendor. This lesson shows the shapes used by the Responses API.

Describe a tool

A function tool has a name, a description and a JSON Schema for its parameters.

Python
# Read-only
tools = [{
    "type": "function",
    "name": "get_order_status",
    "description": "Look up the shipping status of one order of the current customer.",
    "parameters": {
        "type": "object",
        "properties": {
            "order_id": {"type": "string", "description": "Order ID such as A-1042"}
        },
        "required": ["order_id"],
        "additionalProperties": False,
    },
    "strict": True,
}]

strict: True asks for arguments that follow the schema. The same strict rules as for Structured Outputs apply: closed objects and every property required. The description is instruction text for the model. Say what the tool does, when to use it and what the arguments mean.

The round trip

sequenceDiagram
  participant A as Your app
  participant M as Model
  A->>M: input + tools
  M-->>A: function_call (name, arguments, call_id)
  A->>A: check and run the function
  A->>M: function_call_output (call_id, output)
  M-->>A: final message

The model proposes; your application disposes.

The model's request is an output item with the type function_call. It has a name, a call_id and arguments. The arguments are a JSON string, so you must parse them. You answer with an input item of type function_call_output that has the same call_id and your result in output.

Python
# Read-only
import json

history = [{"role": "user", "content": "Where is order A-1042?"}]
response = client.responses.create(model="gpt-6.2-sol", input=history, tools=tools)

history += response.output      # includes reasoning and function_call items

for item in response.output:
    if item.type == "function_call":
        args = json.loads(item.arguments)
        result = run_tool(item.name, args)          # your function
        history.append({
            "type": "function_call_output",
            "call_id": item.call_id,
            "output": json.dumps(result),
        })

final = client.responses.create(model="gpt-6.2-sol", input=history, tools=tools)
print(final.output_text)

With reasoning models, send the reasoning items back along with the tool results. Appending all of response.output does that. If you use previous_response_id instead, send only the new function outputs.

A safe loop

One round is not always enough. A model may look up an order and then ask for tracking details. Write a loop with a maximum number of rounds. In this stand-in, fake_model is scripted. The dispatch code is the part to study.

Python Stand-in: dispatch tool calls safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the second call. The user mia does not own order A-2000, so the tool returns "order not found". The user value comes from your login session, never from the model's arguments.

Parallel calls and tool_choice

A single reply can contain several function calls. Handle every one and return one output for each call_id. Set parallel_tool_calls=False if you want at most one call per turn.

tool_choice controls whether tools are used.

Value Effect
"auto" Default: the model decides
"required" The model must call at least one tool
"none" No tool calls
{"type": "function", "name": "..."} Call this particular function

There is also an allowed_tools form that limits which listed tools may be called. When streaming, function arguments arrive in pieces through response.function_call_arguments.delta events. Wait for the matching done event before you parse them.

Design good tools

  • Offer a few clear tools, not dozens of overlapping ones.
  • Make them narrow: get_order_status is safer than run_sql.
  • Return short, useful results with helpful error messages.
  • Remove data the model does not need.

Protect actions

Schema-valid arguments can still be wrong or dangerous. For each tool, check identity and permission in code, validate values, and limit rates. For actions that spend money, send messages or delete data, show the exact action to a person and wait for approval. Use an idempotency key or a recorded action ID so that a retry does not run the action twice.

Tool results can contain text written by strangers, such as a web page or a ticket. That text may try to steer the model. Never let a tool result alone grant new permissions. See executing tool calls safely.

Return helpful tool errors

A tool result is also text the model reads, so an error message can guide its next step. Compare "error" with "order not found: ask the user to check the order ID, which looks like A-1042." The second helps the model respond well. Do not put stack traces, internal host names or database messages into tool output. They help attackers and use tokens.

Distinguish kinds of failure. "Not found" is a normal answer. "The service is temporarily unavailable" suggests trying later. "Not permitted" should end the attempt. Your code should still enforce each limit even if the model keeps asking.

Test tool use

Write test questions and note the tool call you expect for each, including questions where no tool should be called. Check the chosen tool, the arguments and what happens after an error. Test your dispatcher without a model too: send unknown tool names, broken JSON, missing and extra fields and other users' IDs, as the stand-in above begins to do. When the model often picks the wrong tool, improve the names and descriptions first, and reduce overlap between tools. Add a rule to the developer message only if clearer tool definitions are not enough.

Log the tool name, a safe summary of the arguments, the outcome and the duration for each call.

Common mistakes

  • Treating the arguments string as a dictionary without parsing it.
  • Returning a result for only one of several calls in the same reply.
  • Trusting a user ID or role that appears in the arguments instead of using your session.
  • Dropping the original function call items from history, so the result no longer has a matching request.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What form do function call arguments arrive in?

    Parse the string and validate the values before using them.
  2. 2. How is a result matched to its request?

    The function_call_output item repeats the call_id of the function_call.
  3. 3. Where should the current user's identity come from?

    Authorization must rely on data your server controls.
  4. 4. Why set a maximum number of rounds?

    A bounded loop limits cost and damage when something goes wrong.

Summary

  • Tools are described with a name, description and parameter schema.
  • The model emits function_call items; you return function_call_output items with the same call_id.
  • Send reasoning and call items back when you manage history yourself.
  • Handle several calls, bound the loop and report errors as results.
  • Enforce permissions in code and require approval for risky actions.

Next: Built-In Tools and MCP

Progres Anda disimpan di browser ini. Tidak perlu akun.