Combining Reasoning and Tool Calling: Building Multi-Turn Thinking Agents

    Large language models excel at semantic understanding, language generation, and multi-step reasoning, but they cannot fetch real-time information or execute operations such as queries, calculations, or writes on their own. This article explains why reasoning and tool calling should be combined, walks through the core think–act–observe loop with a practical pseudocode example, and covers key engineering considerations including context management, tool design, error handling, security, and evaluation metrics for building reliable AI agents.

    Combining Reasoning and Tool Calling: Building Multi-Turn Thinking Agents

    Background: Why Reasoning and Tool Calling Need to Be Combined

    Large language models are good at understanding semantics, organizing language, and performing multi-step reasoning. However, their knowledge comes from training data—they cannot retrieve information in real time, nor can they directly execute queries, computations, or write operations. In the past, developers often had to choose between two modes.

    The first is pure reasoning. The model completes its analysis internally and gives an answer directly. This approach works well for logical derivation tasks, but when a question requires up-to-date data, precise values, or the state of external systems, the answer can easily drift. The model fills in gaps from memory, and the errors are often hard to detect.

    The second is pure tool calling. The model selects a tool based on the user’s question, gets the result, and composes an answer. This works well for lookup tasks, but without intermediate reasoning, the model struggles to decide which tool to call and with what parameters, and it has difficulty synthesizing multiple results. For complex problems that need to be decomposed into multiple steps, answers often stay superficial.

    When the two are combined, the model can first analyze the problem and list the facts that need to be verified, then call tools to gather evidence, and revise its judgment based on the returned results—until it has enough information. This closed loop of thinking, acting, and observing is the core structure of today’s agent applications.

    Core Mechanism: The Think–Act–Observe Loop

    A typical reasoning-plus-tool-calling workflow consists of three steps:

    1. Think: The model analyzes the user’s goal, identifies what is known and what is missing, and decides whether to answer directly or call a tool.
    2. Act: The model emits a structured tool call request, including the tool name and parameters. The host program validates the parameters and performs the actual operation.
    3. Observe: The tool’s result is appended to the context, and the model continues reasoning based on the new information.

    This loop repeats until the model produces a final answer or a system-defined termination condition is triggered.

    Below is a platform-agnostic pseudocode example showing the basic structure of the loop:

    1. def run_agent(user_query, tools, model, max_rounds=8):
    2. messages = [{"role": "user", "content": user_query}]
    3. for round_idx in range(max_rounds):
    4. response = model.generate(messages, tools=tools)
    5. messages.append(response.to_message())
    6. if not response.tool_calls:
    7. return response.text # No tool requested; treat as the final answer
    8. for call in response.tool_calls:
    9. result = execute_tool_safely(call.name, call.arguments)
    10. messages.append({
    11. "role": "tool",
    12. "tool_call_id": call.id,
    13. "content": result,
    14. })
    15. return "Max rounds reached without a reliable conclusion. Please narrow the question and try again."

    Three points in this example are worth noting. First, the loop must have an upper bound; otherwise the model may call the same tool over and over. Second, tool results should be returned as separate messages, each mapped to its call ID, so the model can identify which output corresponds to which call. Third, before returning the final text, check that there are no unhandled tool requests.

    Engineering Considerations

    Context Management

    Multi-turn tool calling can quickly inflate the context length. Each round appends the model’s intermediate reasoning, call requests, and tool results, so long tasks can easily exceed the context window, and costs rise accordingly. In practice, you can adopt the following strategies:

    • Summarize or truncate tool results, keeping only the fields relevant to the current question.
    • For large datasets, write the data to external storage and put only a reference identifier in the context instead of the full content.
    • After a task completes, clear intermediate reasoning and keep only the final conclusion for use in subsequent conversations.
    • If the API supports a specific way of passing reasoning content back during tool-calling rounds, configure it according to the official documentation rather than guessing.

    Tool Design

    Tool descriptions are the model’s primary basis for decision-making. A description should cover the tool’s purpose, applicable scenarios, parameter meanings, value ranges, and return format. Parameter names should be self-explanatory—avoid vague abbreviations. Tool granularity also requires trade-offs: overly fine-grained tools increase the number of calls, while overly coarse tools are hard for the model to select accurately.

    It is recommended to define a parameter schema for each tool and validate types and ranges before execution. Here is an example:

    1. TOOL_SCHEMA = {
    2. "name": "query_order_status",
    3. "description": "Query the current status of an order by order ID. Returns only the status field and its last update time.",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "order_id": {
    8. "type": "string",
    9. "pattern": "^[A-Z0-9]{8,20}$",
    10. "description": "Order ID, consisting of uppercase letters and digits.",
    11. }
    12. },
    13. "required": ["order_id"],
    14. },
    15. }

    Error Handling and Degradation

    Tool call failures are the norm, not the exception. Network timeouts, insufficient permissions, and invalid parameters can all occur. The right approach is to return error information to the model in a structured form, letting the model decide whether to retry, switch to another tool, or tell the user the task cannot be completed. Silently swallowing exceptions forces the model to answer based on incomplete information, making conclusions even less reliable.

    Repeated failures with the same parameters should trigger a circuit breaker. For example, stop retrying after two consecutive failures of the same tool and return an error explanation. This avoids wasting resources on ineffective calls and surfaces problems sooner.

    Security and Permissions

    An agent that can call tools can also perform incorrect actions. From an engineering standpoint, follow the principle of least privilege: expose only the tools needed to complete the task, and manage read-only tools separately from write tools. High-risk operations—such as deleting data, making payments, sending messages, or changing permissions—must require user confirmation or human review, and must never be decided by the model alone.

    Tool outputs are external data and may contain text attempting to alter the model’s behavior. Systems should treat tool output as data, never as instructions to execute.

    Evaluation and Observability

    Evaluating an agent is more complex than evaluating a single question-and-answer exchange. Beyond the final answer, you also need to assess whether the process was sound. Consider tracking the following metrics:

    • Task success rate: whether the final result meets the user’s goal.
    • Tool selection accuracy: whether the right tool was called at the right time.
    • Parameter correctness: whether tool parameters are valid and consistent with the task.
    • Average rounds and latency: the number of loop iterations and end-to-end time to complete a task.
    • Cost per task: resource consumption calculated from input and output lengths.

    Your evaluation set should cover three types of tasks: pure knowledge Q&A, lookup tasks that require external data, and composite tasks that require multi-step decomposition. Business teams should build their evaluation sets from their own data.