Skip to main content
Tool calls (also known as function calls) give an LLM access to external tools. The LLM does not call the tools directly. Instead, it suggests the tool to call. The user then calls the tool separately and provides the results back to the LLM. Finally, the LLM formats the response into an answer to the user’s original question.
See API Best Practices for how to correctly structure tool call IDs, pair every tool call with a tool result, preserve reasoning signatures, and avoid thinking + forced tool_choice conflicts.

Request Body Examples

Tool calling with BLACKBOX AI involves three key steps. Here are the essential request body formats for each step:
Step 1: Inference Request with Tools
Step 2: Tool Execution (Client-Side)
After receiving the model’s response with tool_calls, execute the requested tool locally and prepare the result:
Step 3: Inference Request with Tool Results
Note: The tools parameter must be included in every request (Steps 1 and 3) to validate the tool schema on each call.
Tool Calling Example
Here is typescript code that gives LLMs the ability to call an external API — in this case Project Gutenberg, to search for books. First, let’s do some basic setup:
Define the Tool
Next, we define the tool that we want to call. Remember, the tool is going to get requested by the LLM, but the code we are writing here is ultimately responsible for executing the call and returning the results to the LLM.
Note that the “tool” is just a normal function. We then write a JSON “spec” compatible with the OpenAI function calling parameter. We’ll pass that spec to the LLM so that it knows this tool is available and how to use it. It will request the tool when needed, along with any arguments. We’ll then marshal the tool call locally, make the function call, and return the results to the LLM.
Tool use and tool results
Let’s make the first BLACKBOX AI API call to the model:
The LLM responds with a finish reason of tool_calls, and a tool_calls array. In a generic LLM response-handler, you would want to check the finish_reason before processing tool calls, but here we will assume it’s the case. Let’s keep going, by processing the tool call:
The messages array now has:
  1. Our original request
  2. The LLM’s response (containing a tool call request)
  3. The result of the tool call (a json object returned from the Project Gutenberg API)
Now, we can make a second BLACKBOX AI API call, and hopefully get our result!
The output will be something like:
We did it! We’ve successfully used a tool in a prompt.

Interleaved Thinking

Interleaved thinking allows models to reason between tool calls, enabling more sophisticated decision-making after receiving tool results. This feature helps models chain multiple tool calls with reasoning steps in between and make nuanced decisions based on intermediate results.
Important: Interleaved thinking increases token usage and response latency. Consider your budget and performance requirements when enabling this feature.
For comprehensive information about reasoning tokens and configuration, see the Reasoning and Interleaved Thinking documentation.

How Interleaved Thinking Works

With interleaved thinking, the model can:
  • Reason about the results of a tool call before deciding what to do next
  • Chain multiple tool calls with reasoning steps in between
  • Make more nuanced decisions based on intermediate results
  • Provide transparent reasoning for its tool selection process

Enabling Reasoning with Tool Calls

To enable reasoning with tool calls, include the reasoning parameter in your request:

Example: Multi-Step Research with Reasoning

Here’s an example showing how a model might use interleaved thinking to research a topic across multiple sources:
Model’s Reasoning and Tool Calls:
  1. Initial Thinking: “I need to research electric vehicle environmental impact. Let me start with academic papers to get peer-reviewed research.”
  2. First Tool Call: search_academic_papers({"query": "electric vehicle lifecycle environmental impact", "field": "environmental science"})
  3. After First Tool Result: “The papers show mixed results on manufacturing impact. I need current statistics to complement this academic research.”
  4. Second Tool Call: get_latest_statistics({"topic": "electric vehicle carbon footprint", "year": 2024})
  5. After Second Tool Result: “Now I have both academic research and current data. Let me search for manufacturing-specific studies to address the gaps I found.”
  6. Third Tool Call: search_academic_papers({"query": "electric vehicle battery manufacturing environmental cost", "field": "materials science"})
  7. Final Analysis: Synthesizes all gathered information into a comprehensive response.

Preserving Reasoning Context

When using tools with reasoning models, you can preserve reasoning context across multiple API calls. This is particularly useful for complex workflows where the model needs to maintain its reasoning chain.

Best Practices for Interleaved Thinking

  • Clear Tool Descriptions: Provide detailed descriptions so the model can reason about when to use each tool
  • Structured Parameters: Use well-defined parameter schemas to help the model make precise tool calls
  • Context Preservation: Maintain conversation context across multiple tool interactions using reasoning_details
  • Error Handling: Design tools to provide meaningful error messages that help the model adjust its approach
  • Reasoning Budget: Consider setting appropriate max_tokens or effort levels based on task complexity

Implementation Considerations

When implementing interleaved thinking:
  • Models may take longer to respond due to additional reasoning steps
  • Token usage will be higher due to the reasoning process
  • The quality of reasoning depends on the model’s capabilities
  • Some models may be better suited for this approach than others
  • Reasoning tokens are charged as output tokens
For more detailed examples and provider-specific implementations, see the Reasoning and Interleaved Thinking documentation.

A Simple Agentic Loop

In the example above, the calls are made explicitly and sequentially. To handle a wide variety of user inputs and tool calls, you can use an agentic loop. Here’s an example of a simple agentic loop (using the same tools and initial messages as above):

Best Practices and Advanced Patterns

Function Definition Guidelines
When defining tools for LLMs, follow these best practices: Clear and Descriptive Names: Use descriptive function names that clearly indicate the tool’s purpose.
Comprehensive Descriptions: Provide detailed descriptions that help the model understand when and how to use the tool.
Streaming with Tool Calls
When using streaming responses with tool calls, handle the different content types appropriately:
Tool Choice Configuration
Control tool usage with the tool_choice parameter:
Parallel Tool Calls
Control whether multiple tools can be called simultaneously with the parallel_tool_calls parameter (default is true for most models):
When parallel_tool_calls is false, the model will only request one tool call at a time instead of potentially multiple calls in parallel.
Multi-Tool Workflows
Design tools that work well together:
This allows the model to naturally chain operations: search → get details → check inventory.

Example UseCase: Tool Calling with gpt-5.3-codex

GPT-5.3-Codex is OpenAI’s most capable agentic coding model, designed specifically for multi-turn tool calling workflows. This section covers how to use it correctly with both the Chat Completions API and the Responses API to avoid common pitfalls.
Important: gpt-5.3-codex uses a different tool format depending on the API endpoint. Using the wrong format will cause the model to ignore tools and respond with plain text instead.
  • Chat Completions (/chat/completions): Tools are nested under function
  • Responses API (/v1/responses): Tools use a flat structure
See the Format Comparison below and the Responses API documentation for Responses API-specific examples.

Chat Completions: Complete Multi-Turn Example

Here is a complete, working example of a multi-turn tool calling loop with gpt-5.3-codex using the Chat Completions API. This pattern is what coding agents (like Codex CLI) use internally.

Step-by-Step Turn Walkthrough

The agentic loop above handles everything automatically. This section breaks down what happens at each turn so you can see exactly how messages flow.

Turn 1 — Initial request

Send the user’s message and tool definitions:
The model responds with finish_reason: "tool_calls" and a tool_calls array containing the function name, arguments (as a JSON string), and a unique id.

Turn 1 — Execute the tool and send the result

Append the assistant message (with tool_calls) to the messages array, execute the tool locally, then append the tool result and send the next request:
Three critical rules:
  1. The assistant message with tool_calls must be appended before the tool result
  2. tool_call_id in the tool result must exactly match the id from the tool call
  3. Tool result content must be a string — use JSON.stringify() for objects

Conversation History Shape

After two tool calls (e.g., read → edit), the messages array looks like this:
Every message pair follows this pattern: assistant (with tool_calls) → tool (with matching tool_call_id). Dropping any message in the chain will cause the model to fall back to text responses.

Multi-Turn with User Follow-up Messages

After the model completes a task and responds with text, you can continue the conversation by appending a new user message. This lets users ask follow-up questions based on tool results without starting over.
The conversation history after the follow-up looks like this:
The follow-up user message goes after the assistant’s text response, not in the middle of a tool call sequence. The model sees the full conversation context including previous tool results.

Tool Choice Options

Control how the model uses tools with the tool_choice parameter:
ValueBehavior
"auto"The model decides whether to call a tool (recommended)
"required"The model must call at least one tool
"none"The model cannot call any tools

Use Case: Coding Agent

A coding agent gives the model a set of file system and terminal tools and runs an agentic loop — calling the API, executing whatever tools the model requests, and feeding the results back — until the model returns a plain text response with no further tool calls. Define seven SWE tools using the Chat Completions nested format:
Python
Then run the agentic loop:
Python
The agent loop continues until the model returns a response with no tool_calls. Always set a max_turns guard to prevent runaway loops.
Example tasks this agent handles:
  • "Read main.py and tell me what the entry point function does."
  • "Write a file /tmp/utils.py with a helper function for parsing JSON, then read it back to confirm."
  • "Search app.py for all lines containing 'TODO' and list their line numbers."
  • "Edit config.py: replace DEBUG = False with DEBUG = True, then verify the change."
  • "Run python3 tests/test_api.py and report any failures."
  • "List the project root and find all TypeScript files under src/."

Key Requirements for gpt-5.3-codex Tool Calling

Follow these requirements to ensure reliable tool calling:
Common mistake: If the model responds with text instead of calling tools, check these items first:
  1. Tools array is present in every request (not just the first one)
  2. tool_call_id in tool result messages matches the id from the tool call
  3. Assistant messages with tool_calls are appended to the messages array before the tool results
  4. Tool result content is a string (use JSON.stringify() for objects)
1. Always include tools in every request The tools array must be sent with every API call in the loop, not just the first one. The model needs to see the available tools on each turn. 2. Preserve the full message chain Every assistant message (including those with tool_calls) and every tool result must be appended to the messages array. Dropping any message breaks the conversation chain and causes the model to fall back to text.
3. Match tool_call_id exactly Each tool result must reference the exact id from the corresponding tool call. A mismatch causes the model to ignore the result. 4. Tool result content must be a string The content field in tool result messages must be a string. If your tool returns an object, serialize it with JSON.stringify(). 5. Use tool_choice: "auto" (recommended) For most use cases, tool_choice: "auto" gives the best results. The model will call tools when appropriate and respond with text when the task is complete. Use tool_choice: "required" only when you want to force a tool call on every turn.

Using Reasoning with Tool Calling

For complex multi-step tasks, enabling reasoning improves tool calling reliability. The model will think through its approach before deciding which tool to call.
Reasoning EffortBest For
"low"Simple, single-tool tasks
"medium"General coding tasks (recommended default)
"high"Complex multi-file refactors, debugging
See Reasoning and Interleaved Thinking for details on preserving reasoning context across tool call turns.

Format Comparison

Using the wrong tool format for your API endpoint is the most common cause of “model responds with text instead of calling tools.” Make sure you use the correct format.
AspectChat Completions (/chat/completions)Responses API (/v1/responses)
Tool definitionNested: tools[].function.nameFlat: tools[].name
Tool result role"role": "tool""type": "function_call_output"
Tool result ID field"tool_call_id""call_id"
Message format{"role": "user", "content": "..."}{"type": "message", "role": "user", "content": [...]}
System prompt{"role": "system", "content": "..."}"instructions": "..."

Chat Completions Tool Format

Responses API Tool Format

For complete Responses API tool calling examples, see the Responses API documentation.

Troubleshooting: Model Returns Text Instead of Tool Calls

If gpt-5.3-codex responds with plain text instead of calling tools:
IssueSolution
Wrong tool format for endpointUse nested format for /chat/completions, flat format for /v1/responses
tools array missing from requestInclude tools in every request, not just the first one
Missing tool_call_id in tool resultsEnsure each tool result has tool_call_id matching the call’s id
Tool result content is not a stringUse JSON.stringify() to convert objects to strings
Broken message chainAppend every assistant message (including tool_calls) before tool results
Vague user messageBe specific: “Read src/auth.py” instead of “Look at the code”
No system promptInclude a system prompt like “You are a coding agent. Use tools to complete tasks.”