API / limit-agentic-turns-with-max-turns

API

Limit agentic tool turns with max_turns

Limit agentic tool turns with max_turns

On agentic Grok API requests (web search, X search, collections search, code execution, and friends), the model can loop: think → call tools → read results → call more tools. max_turns caps how many of those assistant / tool-call turns run in one request.

Turn vs tool call

One turn is one iteration of the agent loop. Inside a single turn the model may invoke several tools in parallel. So max_turns=3 means up to three iterations, not “only three tool calls.”

When the cap is hit, the server stops further tool calls and returns a final answer from what it already gathered. If you omit max_turns, the server applies a global default cap.

xAI SDK

import os
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search, x_search

client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
    model="grok-4.6",
    tools=[web_search(), x_search()],
    max_turns=3,
)
chat.append(user("What is the latest news from xAI?"))
response = chat.sample()
print(response.content)

Suggested ranges

Goal max_turns
Quick lookup 1–2
Balanced research 3–5
Deep research 10+ or unset (server default)

Lower caps cut latency and tool spend; higher caps dig deeper. Pair with the Sep 21 X Search return-volume pricing when searches can return large post sets — Prepare for the X Search tool pricing change.

Pitfalls

  • Treating max_turns as a hard ceiling on individual tool invocations — parallel tools in one turn still count as one turn.
  • Setting 1 on questions that need multi-hop retrieval, then blaming the model for a shallow answer.