Skip to main content
Tool calling lets a model ask your application to run a function. The model chooses a tool and supplies arguments; your code validates and executes the request, then sends the result back for the model to turn into a final answer.
The model never executes your function. Treat its arguments as untrusted input, validate them, and keep authorization checks inside your application.

Complete tool loop

This example defines a weather tool, executes every requested call, and sends the results back to the model.
TypeScript
The assistant message containing 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 its index, concatenate its argument fragments in order, and parse the JSON after the stream finishes.
TypeScript
Example argument deltas
Never call JSON.parse on each fragment. A fragment is not required to be valid JSON by itself.

Control tool selection

Force one function
Support is model- and provider-specific. Check 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.