Complete tool loop
This example defines a weather tool, executes every requested call, and sends the results back to the model.TypeScript
tool_calls must be included before the corresponding tool messages. Each tool result must use the exact tool_call_id supplied by the model.
Request and response
Request
Response requesting a tool
function.arguments is a JSON string, not an object. Parse it only after the call is complete, then validate the parsed value against your own schema.
Stream tool calls
In a stream, a tool call can arrive across several deltas. Accumulate each call by itsindex, concatenate its argument fragments in order, and parse the JSON after the stream finishes.
TypeScript
Example argument deltas
JSON.parse on each fragment. A fragment is not required to be valid JSON by itself.
Control tool selection
Force one function
supportsTools, supportsToolChoice, and each endpoint’s supportedParameters in Model capabilities before relying on a feature.
Production checklist
- Keep an explicit allowlist of function names.
- Validate every argument and enforce length, enum, and range limits.
- Apply the current user’s authorization inside each tool implementation.
- Set timeouts for network, database, and filesystem operations.
- Limit the number of tool rounds to prevent accidental loops.
- Return compact structured results; do not send secrets or internal errors back to the model.
- Use idempotency keys for tools with side effects such as purchases or messages.
- Require confirmation before destructive or high-impact actions.
Streaming
Handle text, usage, errors, and cancellation in a chat stream.
Model capabilities
Find models and provider endpoints that support tools.