Skip to navigation
DocsTool calling

Build

Tool calling

In short: Tool calling lets a model ask your code to run a function and use the result, in OpenAI or Anthropic format, with forced tools and parallel calls.

Updated View .md
On this page

Tool calling (function calling) lets the model ask your code to run a function, for example a database lookup or an API call, and then use the result in its answer. The model never runs anything itself: it returns the function name and JSON arguments, your code runs it, and you send the result back.

Every model with tool support in the models table accepts tools in the OpenAI format. Claude models also accept them in the Anthropic format.

How does the tool-calling loop work?

The tool-calling loop is four steps that repeat until the model answers without tool calls.

  1. Send the conversation plus a list of tools, each with a name, a description and a JSON Schema for its arguments.
  2. If the reply has finish_reason: "tool_calls", run each entry in message.tool_calls.
  3. Append the assistant message, then one tool message per call with the matching tool_call_id and the result as a string.
  4. Send the request again. Repeat until the model answers without tool calls.
import json, os
from openai import OpenAI

client = OpenAI(base_url="https://api.oneaiapikey.com/v1", api_key=os.environ["ONEAIAPIKEY_API_KEY"])

def get_order_status(order_id: str) -> dict:
    return {"order_id": order_id, "status": "shipped", "eta": "2 days"}  # your real lookup

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Look up the shipping status of an order by its id.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "Order id, e.g. A-1042"}},
            "required": ["order_id"],
        },
    },
}]
messages = [{"role": "user", "content": "Where is my order A-1042?"}]

while True:
    reply = client.chat.completions.create(model="gpt-6-luna:free", messages=messages, tools=tools)
    msg = reply.choices[0].message
    messages.append(msg)                      # keep the assistant turn, tool_calls included
    if not msg.tool_calls:
        break
    for call in msg.tool_calls:               # may be several in one turn
        args = json.loads(call.function.arguments)
        result = get_order_status(**args)
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

print(msg.content)
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.oneaiapikey.com/v1", apiKey: process.env.ONEAIAPIKEY_API_KEY });

const getOrderStatus = ({ order_id }) => ({ order_id, status: "shipped", eta: "2 days" }); // your real lookup

const tools = [{
  type: "function",
  function: {
    name: "get_order_status",
    description: "Look up the shipping status of an order by its id.",
    parameters: {
      type: "object",
      properties: { order_id: { type: "string", description: "Order id, e.g. A-1042" } },
      required: ["order_id"],
    },
  },
}];
const messages = [{ role: "user", content: "Where is my order A-1042?" }];

let msg;
while (true) {
  const reply = await client.chat.completions.create({ model: "gpt-6-luna:free", messages, tools });
  msg = reply.choices[0].message;
  messages.push(msg); // keep the assistant turn, tool_calls included
  if (!msg.tool_calls?.length) break;
  for (const call of msg.tool_calls) {
    const result = getOrderStatus(JSON.parse(call.function.arguments));
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
  }
}
console.log(msg.content);

Every round trip is a separate, separately billed request, and each one re-sends the tool definitions and the growing history. Keep tool descriptions short and cap the number of rounds in production code.

How do I force or block a tool?

Set tool_choice to force one named tool, require some tool, or allow none.

tool_choice
# Always call this one tool
tool_choice={"type": "function", "function": {"name": "get_order_status"}}

# Must call some tool / may call one (default) / must not call any
tool_choice="required"   # or "auto", "none"

A forced call is also the most portable way to get structured output: define one tool whose parameters are the shape you want, and force it.

Can a model call several tools at once?

Yes. Models may return several tool calls in one turn (for example, two order lookups). Run them all, in any order, and send one tool message per call before the next request. To get at most one call per turn, set parallel_tool_calls: false.

How do tools work in the Anthropic format?

In the Anthropic format, on /v1/messages, the shapes are Anthropic’s: tools have an input_schema, the model replies with tool_use content blocks and stop_reason: "tool_use", and you answer with tool_result blocks inside a user message.

Anthropic tool use
import os, json
import anthropic

client = anthropic.Anthropic(base_url="https://api.oneaiapikey.com", api_key=os.environ["ONEAIAPIKEY_API_KEY"])

tools = [{
    "name": "get_order_status",
    "description": "Look up the shipping status of an order by its id.",
    "input_schema": {
        "type": "object",
        "properties": {"order_id": {"type": "string"}},
        "required": ["order_id"],
    },
}]
messages = [{"role": "user", "content": "Where is my order A-1042?"}]

first = client.messages.create(model="qwen-qwen3.8-27b:free", max_tokens=1024, tools=tools, messages=messages)
if first.stop_reason == "tool_use":
    call = next(b for b in first.content if b.type == "tool_use")
    result = {"order_id": call.input["order_id"], "status": "shipped"}
    messages += [
        {"role": "assistant", "content": first.content},
        {"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": call.id, "content": json.dumps(result)},
        ]},
    ]
    final = client.messages.create(model="qwen-qwen3.8-27b:free", max_tokens=1024, tools=tools, messages=messages)
    print(final.content[0].text)

When you call a Claude model in the OpenAI format, the gateway converts tools, tool_choice, parallel_tool_calls and the tool messages in both directions, so the OpenAI loop above works unchanged.

How do web search and fetch server tools work?

Web search and fetch are server tools that the gateway runs for you. On POST /v1/chat/completions you can declare {"type": "web_search"} and {"type": "web_fetch"} in tools (web_search_preview and a web_search_options object also turn on search). The gateway then runs the tool loop for you: the model gets two functions, web_search(query) and web_fetch(url), the gateway runs each call and sends the results back, and you get the model’s final answer.

Server tools
reply = client.chat.completions.create(
    model="gpt-6-luna:free",
    messages=[{"role": "user", "content": "What changed in the latest Python release?"}],
    tools=[{"type": "web_search"}, {"type": "web_fetch"}],
)
print(reply.choices[0].message.content)
print(reply.usage.server_tool_use)   # web_search_requests, web_fetch_requests
  • Price: $0.0055 per search and $0.001 per page fetched, plus each model round, billed as a normal request. usage in the reply adds up all rounds and counts the calls in usage.server_tool_use.
  • Limits: 8 tool rounds, then one last round in which the model must answer; up to 5 tool calls per round; each result is cut at 16,000 characters.
  • Your own tools work alongside: when the model calls one of your functions, you get that round’s reply with only your calls, as in the loop above. A function of yours named web_search or web_fetch is refused (400, server_tools_name), and so is n above 1 (server_tools_n).
  • Streaming: stream: true works, but the reply arrives in one burst once the last round is done.
  • Usage page: each round is its own request in your usage, with the headers you sent (X-Session-Id, X-Title, X-Tag), so the rounds of one call land in the same session. See Headers.

How does tool search work with large toolsets?

Tool search keeps most tool definitions out of each request. With hundreds of tools, sending every definition on each request costs input tokens. Add {"type": "tool_search"} to tools and mark the rarely used functions "defer_loading": true (if you mark none, all your functions are deferred). The gateway keeps the deferred definitions back and gives the model one function, tool_search(query). It answers each search itself with a keyword match over tool names, descriptions and parameter names (up to 5 tools per search), and the tools found are offered to the model from the next round on.

Deferred tools
tools = [{"type": "tool_search"}] + [
    {"type": "function", "defer_loading": True, "function": f}
    for f in my_400_functions          # name, description, parameters
]
reply = client.chat.completions.create(model="gpt-6-luna:free", messages=messages, tools=tools)
  • Price: searches are free; each model round is billed as a normal request, and usage adds up all rounds plus usage.server_tool_use.tool_search_requests.
  • Limits: 3 searches per round, 6 search rounds, at most 1,000 deferred tools, and 300 seconds for all rounds together (504, tool_search_timeout).
  • Multi-turn: a deferred tool that your earlier assistant turns already called, or that tool_choice names, is offered from the start.
  • Reply: only your own tool calls or the answer; the search rounds are not in it. With stream: true the reply arrives in one burst at the end; during a long search the connection is kept open with SSE comments every 15 seconds, and an error after that arrives as one data: {"error": …} event instead of an HTTP error status.
  • Refused with 400: n above 1 (tool_search_n), a function of yours named tool_search (tool_search_name), tool_choice naming it (tool_search_choice), two tools with the same name (tool_search_duplicate), more than 1,000 deferred tools (tool_search_too_many).

Both features work on /v1/chat/completions only, not on /v1/messages or /v1/responses.

What tips make tool calls more reliable?

These habits make tool calls more reliable.

  • Write descriptions for the model, not for people: say when to use the tool and what each argument means.
  • Validate arguments before you act on them. The JSON is usually well-formed, but the values can be wrong.
  • Return errors as tool results ({"error": "order not found"}) instead of failing the request, so the model can recover.
  • When streaming, the arguments arrive in pieces. See Streaming.
  • Some reasoning models restrict tools in chat completions depending on the reasoning setting. If a model rejects your tools, the error message says why; try a lower reasoning_effort or the Responses API.

↑ ↓ moveEnter openEsc close
New accounts$10 credit on sign-up
Claim $10 credit →