Server-Side Tool Calling in LLM APIs: Web Search and Preserving Context Across Turns

    This article explains how to use server-side tool calling in LLM APIs for web search. It covers the tool-calling loop and its key parameters, the difference between direct answer and deep reasoning modes, and why thinking blocks, tool call blocks, and tool result blocks must be passed back unchanged in each turn. It also covers sampling parameter overrides, security and cost controls, and an integration checklist.

    Background: From Client-Side Orchestration to Server-Side Hosting

    Building web-enabled Q&A in an application usually means assembling a full pipeline yourself. Typical steps include generating search queries from the user’s question, calling a search API to get a list of results, fetching candidate web pages, extracting the main text, truncating it and inserting it into the prompt, and then matching the model’s output to its sources. Each step adds engineering cost. Poor query quality, page timeouts, failed text extraction, and oversized context can each degrade the final answer.

    Server-side hosting moves these decisions to the model and the server. The client submits only the question and a declaration of available tools. The server then decides whether to search, how many search rounds to run, and which pages to read. The benefits are direct: less client code, search strategies that can be upgraded centrally, and no need to maintain a separate pipeline for each model.

    The trade-off is equally clear. Reasoning state and tool call records live in the multi-turn message history. If the client does not store this content in full, the next turn loses the information the model already retrieved. Integration effort should therefore focus on maintaining the history correctly, not on assembling search requests.

    How the Tool-Calling Loop Works

    Server-side hosting is built on a loop. The model first decides whether the current question needs external information. If it does, the model issues a tool call. The tool results are appended to the context. The model then continues reasoning on the updated context, possibly calling tools again, until it judges the information sufficient and produces a final answer.

    Three parameters in this loop deserve attention:

    • Turn limit: The maximum number of tool calls allowed in a single request. It determines the worst-case latency and cost.
    • Per-call timeout: The wait time for a single tool call. Page-reading tools are especially prone to timeouts.
    • Result trimming: The length limit on tool output. It directly affects how much context is used.

    The following example shows everything the client needs to do:

    1. history = []
    2. def ask(question: str) -> str:
    3. history.append({"role": "user", "content": question})
    4. resp = client.chat(
    5. model=MODEL,
    6. messages=history,
    7. tools=BUILTIN_TOOLS, # Declare server-side built-in tools
    8. )
    9. # Append all output blocks as-is, including thinking blocks,
    10. # tool call blocks, and tool result blocks
    11. history.extend(resp.output_blocks)
    12. return resp.text

    The key point is the last line. The client only needs the final text, but it must keep the complete output blocks, because later turns depend on these blocks to restore the model’s reasoning process.

    Two Typical Working Modes

    Direct Answer Mode

    With thinking disabled, the model decides from the question whether to search the web or run an image search. After retrieving information, it answers directly and attaches source citations. This mode has lower latency and suits fact lookups, news summaries, and product specification checks.

    Display source citations to users. Citations show that the answer is grounded, and they let users check the original text quickly. The frontend can map citation numbers to the superscript markers in the answer, so that clicking a marker opens the original link.

    Deep Reasoning Mode

    With thinking enabled, the model interleaves searches with its reasoning and keeps searching when it finds gaps in its information. Take a comparison of the heights of two landmark buildings as an example. A reasonable execution path usually looks like this: first search for basic information on both buildings, then visit a trusted official page to find the specific figures. If the page does not contain the required numbers, the model searches for keywords within the page or rephrases the query and searches again. Once all the information is in hand, it compares the two and answers.

    This mode costs more. A single question can trigger more than a dozen tool calls, and latency and token consumption rise noticeably. Choose the mode based on question complexity: use direct answers for simple lookups, and enable deep reasoning for complex questions that require cross-checking multiple sources. Use the turn limit to control cost.

    API Protocols and Tool Declarations

    Common chat interfaces fall into three categories: message-block-based interfaces, response-object-based interfaces, and choice-list-based chat completion interfaces. Protocols differ in field naming and structure, but the core concept of tool calling is the same. The client declares the tools it makes available, the server calls them when needed, and the results return to the context.

    Before integrating, confirm the following:

    1. The protocol version you use supports built-in tools and multi-turn tool results.
    2. The tool declaration format matches the protocol you chose.
    3. Built-in tool names and parameter structures follow the service provider’s current documentation. Do not guess fields from experience.

    Key Constraint in Multi-Turn Conversations: Pass Everything Back Unchanged

    This is the step most prone to errors. Thinking content, search records, and fetched page results returned by the server must be sent back unchanged in the next turn.

    If a middleware layer cleans up messages, for example by keeping only text and discarding structured blocks, the request still succeeds, so the error does not surface right away. The model, however, can no longer see the pages it read in the previous turn. This shows up as answers that contradict earlier ones, or as repeated searches for the same content. These failures are silent and costly to debug.

    To troubleshoot:

    • Log the type of every message block in the request body at the gateway or middleware layer, and confirm that tool result blocks are present.
    • Write a regression test. In the first turn, have the model read a specific page. In the second turn, ask about a detail from that page, and verify that the model answers correctly.
    • Avoid summarizing or truncating history unless you have confirmed that the truncation will not remove tool result blocks.

    Sampling Parameters and Server-Side Overrides

    When features such as tool calling, automatic session title generation, or higher safety levels are enabled, the server may take over the sampling process. Some generation parameters set by the client may then be ignored or overridden.

    Do not rely on exact parameter control. First, treat the parameters or metadata returned in the response as the source of truth, and log the actual configuration of every request. Second, if your application has strict requirements for output randomness, read the provider’s documentation to confirm which features override parameters, and verify this in a test environment. Third, do not rely on a single parameter for output stability. Use prompt constraints and result validation together to ensure quality.

    Security and Cost Control

    Search results and web content are external data, and they may contain malicious instructions. The application should:

    • Treat retrieved content as untrusted data. Do not allow text in it to change system instructions or trigger sensitive operations.
    • Check links in the output against an allowlist or run security checks, so users are not lured to dangerous sites.
    • Limit tool-call turns and timeouts, and set per-user call quotas.
    • Store API keys in environment variables or a key management service. Redact keys and user private information from logs.

    For cost, record the number of tool calls, input and output token counts, and latency for each request, and set alert thresholds. These metrics help teams decide which scenarios suit deep reasoning and which should fall back to direct answers.

    Integration Checklist

    • Declared the required built-in tools, with names and parameters that match the current documentation.
    • Stored thinking blocks, tool call blocks, and tool result blocks in full in the message history.
    • The gateway or middleware does not filter structured content.
    • Set turn limits and per-call timeouts.
    • Source citations are displayed in the interface and can be clicked for verification.
    • External content is protected against prompt injection, and output links have been checked for safety.
    • Recorded the effective generation parameters and verified override behavior in a test environment.
    • Monitor tool call counts, token consumption, and latency, with alerts configured.

    Checking each item against this list will surface most integration problems before launch.