> ## Documentation Index
> Fetch the complete documentation index at: https://openrouter.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool Calling Best Practices

> Interleaved thinking, streaming tool calls, tool choice, parallel calls, and multi-tool workflows

This page continues [Client Tools](https://openrouter.ai/docs/guides/features/tool-calling.md). The examples reuse the `search_gutenberg_books` tool, `tools`, `instructions`, and `input` defined there.

## 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.

### 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

### 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:

**Initial Request:**

```json expandable lines theme={null}
{
  "model": "anthropic/claude-sonnet-4.5",
  "input": [
    {
      "role": "user",
      "content": "Research the environmental impact of electric vehicles and provide a comprehensive analysis."
    }
  ],
  "tools": [
    {
      "type": "function",
      "name": "search_academic_papers",
      "description": "Search for academic papers on a given topic",
      "parameters": {
        "type": "object",
        "properties": {
          "query": {"type": "string"},
          "field": {"type": "string"}
        },
        "required": ["query"]
      }
    },
    {
      "type": "function",
      "name": "get_latest_statistics",
      "description": "Get latest statistics on a topic",
      "parameters": {
        "type": "object",
        "properties": {
          "topic": {"type": "string"},
          "year": {"type": "integer"}
        },
        "required": ["topic"]
      }
    }
  ]
}
```

**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.

### 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
* **Error Handling**: Design tools to provide meaningful error messages that help the model adjust its approach

### 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

## 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.

```json lines theme={null}
// Good: Clear and specific
{ "name": "get_weather_forecast" }
```

```json lines theme={null}
// Avoid: Too vague
{ "name": "weather" }
```

**Comprehensive Descriptions**: Provide detailed descriptions that help the model understand when and how to use the tool.

```json lines theme={null}
{
  "description": "Get current weather conditions and 5-day forecast for a specific location. Supports cities, zip codes, and coordinates.",
  "parameters": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "City name, zip code, or coordinates (lat,lng). Examples: 'New York', '10001', '40.7128,-74.0060'"
      },
      "units": {
        "type": "string",
        "enum": ["celsius", "fahrenheit"],
        "description": "Temperature unit preference",
        "default": "celsius"
      }
    },
    "required": ["location"]
  }
}
```

## Streaming with Tool Calls

When using streaming responses with tool calls, handle the different content types appropriately. The Python, Go, and cURL tabs define the tool-call handler they use; `handleToolCalls` in the TypeScript tab is your own function with the same job. The Python, Go, and cURL follow-up requests follow [A Simple Agentic Loop](https://openrouter.ai/docs/guides/features/tool-calling.md#a-simple-agentic-loop) on Client Tools. The TypeScript tab receives raw Responses API events, so take `tools` from the TypeScript (fetch) tab in [Define the Tool](https://openrouter.ai/docs/guides/features/tool-calling.md#define-the-tool), not the SDK setup, and build its follow-up like the TypeScript (fetch) tabs in [Tool use and tool results](https://openrouter.ai/docs/guides/features/tool-calling.md#tool-use-and-tool-results): match the raw `search_gutenberg_books` name and send each result with the raw `call_id`, not the SDK loop's `searchGutenbergBooks` and `callId`. Reuse this tab's `MODEL` in that follow-up so the conversation stays on the same model, and start the follow-up's input from `streamInput`, not `input`, so the tool results stay paired with the streamed prompt. In Go, build on the Go tabs in [Define the Tool](https://openrouter.ai/docs/guides/features/tool-calling.md#define-the-tool) and [Tool use and tool results](https://openrouter.ai/docs/guides/features/tool-calling.md#tool-use-and-tool-results), which use the flat Responses API tool format, not the nested Chat Completions `tools` in the first Go program on Client Tools. Add `bufio` to your imports, and use this request in place of that walkthrough's first request and every step after it (the `response1` handling and the second request), not after them, since it declares `body` and `req` again and runs its own follow-up:

```typescript expandable lines theme={null}
const MODEL = 'anthropic/claude-sonnet-4.5';

// Start from the user-only input under a new name, so it can sit beside the Client Tools `input`.
const streamInput = [
  { role: 'user', content: 'What are the titles of some James Joyce books?' },
];

const stream = await fetch('https://openrouter.ai/api/v1/responses', {
  method: 'POST',
  headers: {
    Authorization: `Bearer <OPENROUTER_API_KEY>`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: MODEL,
    input: streamInput,
    tools: tools,
    stream: true
  })
});

if (!stream.body) {
  throw new Error('Expected a streaming response body');
}

const reader = stream.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const toolCalls = [];
const outputItems = [];

while (true) {
  const { done, value } = await reader.read();
  if (done) {
    break;
  }

  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split('\n');
  buffer = lines.pop() ?? '';

  for (const line of lines) {
    if (!line.startsWith('data: ')) continue;
    const data = line.slice(6).trim();
    if (data === '[DONE]') continue;

    const event = JSON.parse(data);

    if (event.type === 'response.failed') {
      throw new Error(event.response.error?.message ?? 'Response failed');
    }
    if (event.type === 'response.incomplete') {
      throw new Error(
        `Response incomplete: ${event.response.incomplete_details?.reason ?? 'unknown reason'}`,
      );
    }
    if (event.type === 'response.output_text.delta') {
      console.log(event.delta);
    }

    if (event.type === 'response.output_item.done') {
      // Preserve every completed item in order. Reasoning and assistant items are
      // required context for some providers when sending tool results.
      outputItems.push(event.item);
      if (event.item.type === 'function_call') {
        // A completed function_call item carries the full arguments string.
        toolCalls.push(event.item);
      }
    }

    if (event.type === 'response.completed') {
      if (toolCalls.length > 0) {
        // Run each function_call locally, then send a follow-up request whose input
        // includes the original input, every output item, and a function_call_output
        // for each call (see A Simple Agentic Loop on Client Tools).
        await handleToolCalls(toolCalls, outputItems);
      }
      // Otherwise the regular response was printed from its output_text deltas above
    }
  }
}
```

```python title="Python" expandable lines theme={null}
# Start from the user-only input, not the input_items left over from the Client Tools walkthrough.
input_items = [{"role": "user", "content": task}]

HEADERS = {
    "Authorization": f"Bearer {OPENROUTER_API_KEY}",
    "Content-Type": "application/json",
}


# Runs each function_call, then sends one non-streaming follow-up request with the results
def handle_tool_calls(tool_calls, output_items):
    results = []
    for call in tool_calls:
        tool_result = TOOL_MAPPING[call["name"]](**json.loads(call["arguments"]))
        results.append({
            "type": "function_call_output",
            "call_id": call["call_id"],
            "output": json.dumps(tool_result),
        })

    follow_up = requests.post(
        "https://openrouter.ai/api/v1/responses",
        headers=HEADERS,
        json={
            "model": "anthropic/claude-sonnet-4.5",
            "input": input_items + output_items + results,
            "tools": tools,
        },
    )
    follow_up.raise_for_status()
    for item in follow_up.json()["output"]:
        if item["type"] != "message":
            continue
        for part in item["content"]:
            if part["type"] == "output_text":
                print(part["text"])


response = requests.post(
    "https://openrouter.ai/api/v1/responses",
    headers=HEADERS,
    json={
        "model": "anthropic/claude-sonnet-4.5",
        "input": input_items,
        "tools": tools,
        "stream": True,
    },
    stream=True,
)
response.raise_for_status()

tool_calls = []
output_items = []

for raw_line in response.iter_lines():
    line = raw_line.decode("utf-8")
    if not line.startswith("data: "):
        continue
    data = line[6:].strip()
    if data == "[DONE]":
        continue

    event = json.loads(data)

    if event["type"] == "response.failed":
        error = event["response"].get("error") or {}
        raise RuntimeError(error.get("message", "Response failed"))
    if event["type"] == "response.incomplete":
        details = event["response"].get("incomplete_details") or {}
        raise RuntimeError(f"Response incomplete: {details.get('reason', 'unknown reason')}")
    if event["type"] == "response.output_text.delta":
        print(event["delta"], end="", flush=True)

    if event["type"] == "response.output_item.done":
        # Preserve every completed item in order. Reasoning and assistant items are
        # required context for some providers when sending tool results.
        output_items.append(event["item"])
        if event["item"]["type"] == "function_call":
            # A completed function_call item carries the full arguments string.
            tool_calls.append(event["item"])

    if event["type"] == "response.completed":
        print()
        if tool_calls:
            # Run each function_call locally, then send a follow-up request whose input
            # includes the original input, every output item, and a function_call_output
            # for each call (see A Simple Agentic Loop on Client Tools).
            handle_tool_calls(tool_calls, output_items)
        # Otherwise the regular response was printed from its output_text deltas above

```

```go title="Go" expandable lines theme={null}
// Start from the user-only input, not the input left over from the Client Tools walkthrough.
input = []any{
	map[string]any{
		"role":    "user",
		"content": "What are the titles of some James Joyce books?",
	},
}

// Runs each function_call, then sends one non-streaming follow-up request with the results
handleToolCalls := func(toolCalls []map[string]any, outputItems []any) {
	followUp := append(append([]any{}, input...), outputItems...)
	for _, call := range toolCalls {
		followUp = append(followUp, map[string]any{
			"type":    "function_call_output",
			"call_id": call["call_id"],
			"output":  runSearch(call["arguments"].(string)),
		})
	}

	body, _ := json.Marshal(map[string]any{
		"model": "anthropic/claude-sonnet-4.5",
		"input": followUp,
		"tools": tools,
	})
	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var result struct {
		Output []struct {
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	for _, item := range result.Output {
		for _, part := range item.Content {
			if part.Type == "output_text" {
				fmt.Println(part.Text)
			}
		}
	}
}

body, _ := json.Marshal(map[string]any{
	"model":  "anthropic/claude-sonnet-4.5",
	"input":  input,
	"tools":  tools,
	"stream": true,
})
req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
req.Header.Set("Content-Type", "application/json")
stream, err := http.DefaultClient.Do(req)
if err != nil {
	log.Fatal(err)
}
defer stream.Body.Close()
if stream.StatusCode != http.StatusOK {
	log.Fatalf("Expected a streaming response, got %s", stream.Status)
}

var toolCalls []map[string]any
var outputItems []any

scanner := bufio.NewScanner(stream.Body)
scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
for scanner.Scan() {
	line := scanner.Text()
	if !strings.HasPrefix(line, "data: ") {
		continue
	}
	data := strings.TrimSpace(line[6:])
	if data == "[DONE]" {
		continue
	}

	var event map[string]any
	if err := json.Unmarshal([]byte(data), &event); err != nil {
		log.Fatal(err)
	}

	switch event["type"] {
	case "response.failed":
		log.Fatalf("Response failed: %v", event["response"].(map[string]any)["error"])
	case "response.incomplete":
		log.Fatalf("Response incomplete: %v", event["response"].(map[string]any)["incomplete_details"])
	case "response.output_text.delta":
		fmt.Print(event["delta"])
	case "response.output_item.done":
		// Preserve every completed item in order. Reasoning and assistant items are
		// required context for some providers when sending tool results.
		item := event["item"].(map[string]any)
		outputItems = append(outputItems, item)
		if item["type"] == "function_call" {
			// A completed function_call item carries the full arguments string.
			toolCalls = append(toolCalls, item)
		}
	case "response.completed":
		fmt.Println()
		if len(toolCalls) > 0 {
			// Run each function_call locally, then send a follow-up request whose input
			// includes the original input, every output item, and a function_call_output
			// for each call (see A Simple Agentic Loop on Client Tools).
			handleToolCalls(toolCalls, outputItems)
		}
		// Otherwise the regular response was printed from its output_text deltas above
	}
}
if err := scanner.Err(); err != nil {
	log.Fatal(err)
}
```

```bash title="cURL" expandable lines theme={null}
# Start from the user-only input, not the INPUT left over from the Client Tools walkthrough.
INPUT='[{"role": "user", "content": "What are the titles of some James Joyce books?"}]'
# Runs each function_call, then sends one non-streaming follow-up request with the results
handle_tool_calls() {
  local tool_calls=$1 output_items=$2 follow_up call terms result
  follow_up=$(jq -c --argjson items "$output_items" '. + $items' <<<"$INPUT")
  while IFS= read -r call; do
    terms=$(jq -er '.arguments | fromjson | .search_terms | join(" ")' <<<"$call") || return 1
    result=$(search_gutenberg_books "$terms") || return 1
    follow_up=$(jq -c --arg call_id "$(jq -r '.call_id' <<<"$call")" --arg output "$result" \
      '. + [{type: "function_call_output", call_id: $call_id, output: $output}]' <<<"$follow_up")
  done < <(jq -c '.[]' <<<"$tool_calls")

  curl -sS https://openrouter.ai/api/v1/responses \
    -H "Authorization: Bearer $OPENROUTER_API_KEY" \
    -H "Content-Type: application/json" \
    -d "$(jq -n --argjson input "$follow_up" --argjson tools "$TOOLS" \
      '{model: "anthropic/claude-sonnet-4.5", input: $input, tools: $tools}')" |
    jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'
}

output_items='[]'

curl -sSN https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --argjson input "$INPUT" --argjson tools "$TOOLS" \
    '{model: "anthropic/claude-sonnet-4.5", input: $input, tools: $tools, stream: true}')" |
while IFS= read -r line; do
  line=${line%$'\r'}
  [[ $line == "data: "* ]] || continue
  data=${line#data: }
  [[ $data == "[DONE]" ]] && continue

  case $(jq -r '.type' <<<"$data") in
    response.failed)
      jq -r '.response.error.message // "Response failed"' <<<"$data" >&2; exit 1 ;;
    response.incomplete)
      jq -r '"Response incomplete: " + (.response.incomplete_details.reason // "unknown reason")' <<<"$data" >&2; exit 1 ;;
    response.output_text.delta)
      jq -rj '.delta' <<<"$data" ;;
    response.output_item.done)
      # Preserve every completed item in order. Reasoning and assistant items are
      # required context for some providers when sending tool results.
      output_items=$(jq -c --argjson item "$(jq -c '.item' <<<"$data")" '. + [$item]' <<<"$output_items") ;;
    response.completed)
      echo
      # A completed function_call item carries the full arguments string.
      tool_calls=$(jq -c 'map(select(.type == "function_call"))' <<<"$output_items")
      if [[ $tool_calls != "[]" ]]; then
        # Run each function_call locally, then send a follow-up request whose input
        # includes the original input, every output item, and a function_call_output
        # for each call (see A Simple Agentic Loop on Client Tools).
        handle_tool_calls "$tool_calls" "$output_items"
      fi
      # Otherwise the regular response was printed from its output_text deltas above
      ;;
  esac
done
```

## Tool Choice Configuration

Control tool usage with the `tool_choice` parameter:

```json lines theme={null}
// Let model decide (default)
{ "tool_choice": "auto" }
```

```json lines theme={null}
// Disable tool usage
{ "tool_choice": "none" }
```

```json lines theme={null}
// Force specific tool (Responses API)
{
  "tool_choice": {
    "type": "function",
    "name": "search_database"
  }
}
```

```json lines theme={null}
// Force specific tool (Chat Completions: the name is nested under `function`)
{
  "tool_choice": {
    "type": "function",
    "function": { "name": "search_database" }
  }
}
```

## Parallel Tool Calls

Control whether multiple tools can be called simultaneously with the `parallel_tool_calls` parameter (default is true for most models):

```json lines theme={null}
// Disable parallel tool calls - tools will be called sequentially
{ "parallel_tool_calls": false }
```

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:

```json expandable lines theme={null}
{
  "tools": [
    {
      "type": "function",
      "name": "search_products",
      "description": "Search for products in the catalog",
      "parameters": {
        "type": "object",
        "properties": {
          "query": { "type": "string", "description": "Product name or search terms" }
        },
        "required": ["query"],
        "additionalProperties": false
      }
    },
    {
      "type": "function",
      "name": "get_product_details",
      "description": "Get detailed information about a specific product",
      "parameters": {
        "type": "object",
        "properties": {
          "product_id": { "type": "string", "description": "Catalog product identifier" }
        },
        "required": ["product_id"],
        "additionalProperties": false
      }
    },
    {
      "type": "function",
      "name": "check_inventory",
      "description": "Check current inventory levels for a product",
      "parameters": {
        "type": "object",
        "properties": {
          "product_id": { "type": "string", "description": "Catalog product identifier" }
        },
        "required": ["product_id"],
        "additionalProperties": false
      }
    }
  ]
}
```

This allows the model to naturally chain operations: search → get details → check inventory.

## Reliability Tracking

OpenRouter tracks how reliably each provider completes tool calls and surfaces this as the **Tool Call Error Rate** on the Performance tab of every model page. The same signal drives [Auto Exacto](https://openrouter.ai/docs/guides/routing/auto-exacto.md) provider ordering on tool-calling requests. For the exact validator, JSON Schema draft, regex semantics, and per-tool-call classification, see [How Tool-Calling Success Rate Is Measured](https://openrouter.ai/docs/guides/routing/auto-exacto.md#how-tool-calling-success-rate-is-measured).

For more details on the Responses API input format and tool parameters, see the [Responses API reference](https://openrouter.ai/docs/api_reference/responses/overview.md).
