Complete the loop
- Send
toolsusing a model that supports functions and the requested options. - Inspect the assistant’s
tool_calls; handle an ordinary reply if there are none. - Validate names and arguments, then execute an allowed application function.
- Append the original assistant message and a matching
role: toolresult for each call, then request another reply. - Bound rounds, execution time, and total work because the model can request more tools.
Runnable example: local multiplication
Prepare the TypeScript SDK environment, save astool-calling.mts, and run node tool-calling.mts. This example exposes only a pure calculation, multiply, and makes at most three model requests. Its strict: true requires strict tool-argument support in the model and channel.
tool_call_id. A model can also answer directly; final text depends on the model. Unknown functions, invalid arguments, unfinished output, or the round limit cause a nonzero exit.
function.arguments is a JSON string, not trusted code. Validate application constraints even with strict mode. Tools that access or change real data must enforce the current user’s permissions independently; generated arguments do not grant access. Do not implement this example with eval, arbitrary shell execution, or unrestricted dynamic function dispatch.
Chat Completions versus Responses
A Responses
call_id differs from the output item’s own id. Do not send the Chat messages above unchanged to Responses. Preserve any other output items and context required by the model.
Validate the non-streaming loop first. In a stream, arguments can arrive in fragments: collect them by call index/ID and parse only when complete. Do not execute a function once per fragment.
Chat Completions reference · Streaming
Python: a Responses function-calling loop
Save asresponses-tools.py, configure the Python SDK, and run python responses-tools.py. Choose a model and channel supporting Responses, strict function arguments, and stateless history replay. Requests also use store: false and include: ["reasoning.encrypted_content"]; see conversations for compatibility requirements.
call_id, and rejects repeated call IDs, unknown tools, booleans masquerading as numbers, non-finite values, and overflow. Multiplication has no external side effects; business tools need authorization, idempotency, and execution timeouts. The 60-second request timeout is not a deadline for the entire workflow.
Reference: OpenAI function calling.