Tool calling
Declare tools, validate arguments, run a local function, and return its result.
Workflow
The selected model and line must support tools. The model proposes a call; your application validates and executes it, then returns the result. The API does not execute arbitrary local functions for you.
Complete example
Install dependencies and set environment variables using the OpenAI SDK guide. This tool only formats a string and accesses no external system. It demonstrates one tool round trip; applications should bound the number of rounds.
import json
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["IROUTER_API_KEY"],
base_url="https://gateway.irouter.io/v1", max_retries=0)
model = os.environ["IROUTER_MODEL"]
messages = [{"role": "user", "content": "Use format_label to trim: ' iRouter '."}]
tools = [{"type": "function", "function": {
"name": "format_label", "description": "Trim surrounding whitespace.",
"parameters": {"type": "object", "properties": {
"label": {"type": "string"}}, "required": ["label"],
"additionalProperties": False}
}}]
reply = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = reply.choices[0].message
if message.tool_calls:
messages.append(message.model_dump(exclude_none=True))
for call in message.tool_calls:
if call.function.name != "format_label":
raise ValueError("Unsupported tool")
args = json.loads(call.function.arguments)
if not isinstance(args, dict) or set(args) != {"label"} or not isinstance(args["label"], str):
raise ValueError("Invalid arguments")
result = {"label": args["label"].strip()}
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result)})
reply = client.chat.completions.create(model=model, messages=messages)
print(reply.choices[0].message.content)
else:
print(message.content)Validate before execution
Allowlist functions and validate argument types and business permissions. Side effects such as payments, deletion, or email require application authorization and business idempotency controls. Never send model-generated strings directly to a shell or SQL engine.
A response may request multiple tools. Return a result for each tool_call_id. For streaming, assemble complete arguments before parsing JSON or executing the tool.
Other protocols
Messages uses tool_use and tool_result blocks; Responses uses function-call and function-output items. Their formats differ from this message sequence. See OpenAI tool calling for protocol fields and verify iRouter line compatibility.