Repository Public
1<!-- source: https://docs.x.ai/developers/tools/tool-usage-details (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Tools34# Tool Usage Details56This page covers the technical details of how tool calls are tracked, billed, and how to understand token usage in agentic requests.78## Real-time Server-side Tool Calls910When streaming agentic requests, you can observe **every tool call decision** the model makes in real-time via the `tool_calls` attribute on the `chunk` object:1112```pythonWithoutSDK13for tool_call in chunk.tool_calls:14 print(f"\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")15```1617**Note**: Only the tool call invocations are shown — **server-side tool call outputs are not returned** in the API response. The agent uses these outputs internally to formulate its final response.1819## Server-side Tool Calls vs Tool Usage2021The API provides two related but distinct metrics for server-side tool executions:2223### `tool_calls` - All Attempted Calls2425```pythonWithoutSDK26response.tool_calls27```2829Returns a list of all **attempted** tool calls made during the agentic process. Each entry contains:3031* `id`: Unique identifier for the tool call32* `function.name`: The name of the specific server-side tool called33* `function.arguments`: The parameters passed to the server-side tool3435This includes **every tool call attempt**, even if some fail.3637### `server_side_tool_usage` - Successful Calls (Billable)3839```pythonWithoutSDK40response.server_side_tool_usage41```4243Returns a map of successfully executed tools and their invocation counts. This represents only the tool calls that returned meaningful responses and **determines your billing**.4445```output46{'SERVER_SIDE_TOOL_X_SEARCH': 3, 'SERVER_SIDE_TOOL_WEB_SEARCH': 2}47```4849## Tool Call Function Names vs Usage Categories5051In xAI SDK chat responses, the function names in `tool_calls` represent the precise name of the tool invoked, while the entries in `server_side_tool_usage` provide a high-level categorization that aligns with the original tool passed in the `tools` array. In the Responses API, Web Search activity is represented as `web_search_call` output items instead.5253| Usage Category | Function Name(s) |54|----------------|------------------|55| `SERVER_SIDE_TOOL_WEB_SEARCH` | `web_search`, `web_search_with_snippets`, `browse_page`, `open_page`, `open_page_with_find` |56| `SERVER_SIDE_TOOL_IMAGE_SEARCH` | `search_images` |57| `SERVER_SIDE_TOOL_X_SEARCH` | `x_user_search`, `x_keyword_search`, `x_semantic_search`, `x_thread_fetch` |58| `SERVER_SIDE_TOOL_CODE_EXECUTION` | `code_execution` |59| `SERVER_SIDE_TOOL_VIEW_X_VIDEO` | `view_x_video` |60| `SERVER_SIDE_TOOL_VIEW_IMAGE` | `view_image` |61| `SERVER_SIDE_TOOL_COLLECTIONS_SEARCH` | `collections_search` |62| `SERVER_SIDE_TOOL_MCP` | `{server_label}.{tool_name}` if `server_label` provided, otherwise `{tool_name}` |6364## When Tool Calls and Usage Differ6566In most cases, `tool_calls` and `server_side_tool_usage` will show the same tools. However, they can differ when:6768* **Failed tool executions**: The model attempts to browse a non-existent webpage, fetch a deleted X post, or encounters other execution errors69* **Invalid parameters**: Tool calls with malformed arguments that can't be processed70* **Network or service issues**: Temporary failures in the tool execution pipeline7172The agentic system handles these failures gracefully, updating its trajectory and continuing with alternative approaches when needed.7374**Billing Note**: Only successful tool executions (`server_side_tool_usage`) are billed. Failed attempts are not charged.7576## Understanding Token Usage7778Agentic requests have unique token usage patterns compared to standard chat completions:7980### `completion_tokens`8182Represents **only the final text output** of the model. This is typically much smaller than you might expect, as the agent performs all its intermediate reasoning and tool orchestration internally.8384### `prompt_tokens`8586Represents the **cumulative input tokens** across all inference requests made during the agentic process. Each request includes the full conversation history up to that point, which grows as the agent progresses.8788While this can result in higher `prompt_tokens` counts, agentic requests benefit significantly from **prompt caching**. The majority of the prompt remains unchanged between steps, allowing for efficient caching.8990### `reasoning_tokens`9192Represents the tokens used for the model's internal reasoning process. This includes planning tool calls, analyzing results, and formulating responses, but excludes the final output tokens.9394### `cached_prompt_text_tokens`9596Indicates how many prompt tokens were served from cache rather than recomputed. Higher values indicate better cache utilization and lower costs.9798### `prompt_image_tokens`99100Represents tokens from visual content that the agent processes. These are counted separately from text tokens. If no images or videos are processed, this value will be zero.101102## Limiting Tool Call Turns103104The `max_turns` parameter allows you to control the maximum number of assistant/tool-call turns the agent can perform during a single request.105106### Understanding Turns vs Tool Calls107108**Important**: `max_turns` does **not** directly limit the number of individual tool calls. Instead, it limits the number of assistant turns in the agentic loop. During a single turn, the model may invoke multiple tools in parallel.109110A "turn" represents one iteration of the agentic reasoning loop:1111121. The model analyzes the current context1132. The model decides to call one or more tools (potentially in parallel)1143. Tools execute and return results1154. The model processes the results116117```pythonXAI118import os119120from xai_sdk import Client121from xai_sdk.chat import user122from xai_sdk.tools import web_search, x_search123124client = Client(api_key=os.getenv("XAI_API_KEY"))125chat = client.chat.create(126 model="grok-4.6",127 tools=[128 web_search(),129 x_search(),130 ],131 max_turns=3, # Limit to 3 assistant/tool-call turns132)133134chat.append(user("What is the latest news from xAI?"))135response = chat.sample()136print(response.content)137```138139### When to Use `max_turns`140141| Use Case | Recommended `max_turns` | Tradeoff |142|----------|------------------------|----------|143| **Quick lookups** | 1-2 | Fastest response, may miss deeper insights |144| **Balanced research** | 3-5 | Good balance of speed and thoroughness |145| **Deep research** | 10+ or unset | Most comprehensive, longer latency and higher cost |146147### Default Behavior148149If `max_turns` is not specified, the server applies a global default cap. When the agent reaches the limit, it will stop making additional tool calls and generate a final response based on information gathered so far.150151## Identifying Tool Call Types152153To determine whether a returned tool call is a client-side tool that needs local execution:154155### Using xAI SDK156157Use the `get_tool_call_type` function:158159```pythonXAI160from xai_sdk.tools import get_tool_call_type161162for tool_call in response.tool_calls:163 print(get_tool_call_type(tool_call))164```165166| Tool call types | Description |167|---------------|-------------|168| `"client_side_tool"` | Client-side tool call - requires local execution |169| `"web_search_tool"` | Web-search tool - handled by xAI server |170| `"x_search_tool"` | X-search tool - handled by xAI server |171| `"code_execution_tool"` | Code-execution tool - handled by xAI server |172| `"collections_search_tool"` | Collections-search tool - handled by xAI server |173| `"mcp_tool"` | MCP tool - handled by xAI server |174175### Using Responses API176177Check the `type` field of output entries (`response.output[].type`):178179| Types | Description |180|-------|-------------|181| `"function_call"` | Client-side tool - requires local execution |182| `"web_search_call"` | Web-search tool - handled by xAI server |183| `"x_search_call"` | X-search tool - handled by xAI server |184| `"code_interpreter_call"` | Code-execution tool - handled by xAI server |185| `"file_search_call"` | Collections-search tool - handled by xAI server |186| `"mcp_call"` | MCP tool - handled by xAI server |187