Implementing Multi-Step Tool Calling with LLMs
Multi-step tool calling requires the model to iterate between generating tool calls and executing them until a final answer is reached. This pattern demands robust looping logic and precise state management to prevent infinite loops. By using an OpenAI-compatible API with automatic routing, you can access models, ensuring you select the right capability for each step while controlling token usage across the entire chain.
Define Function Definitions for Tools
LLMs interpret tool definitions through JSON Schema. Vague or loosely typed schemas lead to hallucinated arguments, failed function calls, and increased latency as the model retries. Strict typing forces the model to adhere to specific data structures, reducing parsing errors and downstream validation logic. Structure your function definitions with explicit types, required fields, and clear descriptions. Avoid optional fields unless the tool explicitly supports defaults. Use `enum` for categorical inputs to restrict the model’s choice set. Provide concise `description` fields for both the function and each parameter; the model uses these descriptions to decide when to invoke the tool and what values to populate. { "name": "get_weather", "description": "Retrieve current weather for a city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "City name, e.g., 'New York'" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["city", "unit"] } } This structure ensures the LLM returns valid JSON that your backend can deserialize without additional cleaning. When defining complex tools, break them into smaller, single-purpose functions. A monolithic tool with twenty optional parameters is harder for the model to navigate than three focused tools. Test your schemas against the model before integrating them into your application loop. Use the FastInfra API to send these definitions alongside your prompt and inspect the raw function call output. The platform supports hundreds of models, including 723 options, allowing you to test schema compatibility across different architectures. Refer to the [documentation](/docs) for specific endpoint parameters for tool calling.Build the Looping Logic
The core of multi-step tool calling is a deterministic loop that continues until the model returns a standard text response without any `tool_calls`. This pattern prevents infinite recursion and ensures the application state remains consistent across iterations.
Start by initializing a message history array containing the system prompt and the user’s original query. In each iteration, send this history to the inference endpoint. Inspect the response object specifically for the `tool_calls` field. If the field is empty or null, the conversation is complete. If it contains entries, extract the function name and arguments, execute the corresponding local or remote function, and append the result as a new message with the role `tool`.
Use a strict maximum iteration limit to safeguard against logic errors or model hallucinations that trigger endless tool requests. A limit of 10–15 steps covers most complex workflows while preventing runaway scenarios without impacting user experience.
while len(tool_calls) > max_steps:
response = client.chat.completions.create(
model="fastinfra/auto",
messages=history,
tools=tools
)
if not response.choices[0].message.tool_calls:
break
for call in response.choices[0].message.tool_calls:
result = execute_tool(call.function.name, call.function.arguments)
history.append({"role": "tool", "content": result})
When using an API that supports automatic lowest-cost routing, such as FastInfra, the loop benefits from consistent latency profiles across steps. The platform routes each request to the most cost-effective model available among the 723 options, ensuring that intermediate tool-calling steps do not incur unnecessary overhead. This is critical because multi-step chains often involve many small inference calls.
Ensure that the `history` array includes the `tool_call_id` in the tool response message. This links the output back to the specific request, allowing the model to correctly associate results with the invoked functions. Without this linkage, the model may lose context regarding which tool produced which data, leading to incorrect subsequent steps. Review the implementation details in the FastInfra documentation for precise JSON structure requirements.
Manage State Across Steps
State management determines whether a multi-step chain succeeds or collapses. The model requires the full conversation history, including previous tool calls and their outputs, to reason about the next step. Truncating this history arbitrarily breaks the logical flow and causes the model to hallucinate or repeat previous errors.
Store messages in a structured list that preserves the role, content, and tool-specific metadata for every turn. When the model requests a tool, append the function call object to the history. After executing the tool, append the result as a tool response with the matching call ID. This creates a linear, auditable trail that the LLM can parse deterministically.
Monitor the token count of the accumulated history against the model’s context window. If the history approaches the limit, apply a summarization strategy or remove the oldest non-critical turns. Do not discard tool outputs that are prerequisites for the current step. Keeping only the final state of intermediate calculations reduces noise while preserving necessary context.
history.append({"role": "tool", "tool_call_id": call_id, "content": str(result)})
response = client.chat.completions.create(
model="gpt-4o",
messages=history
)
FastInfra simplifies state handling by providing a standard OpenAI-compatible interface for all 723 available models. You can switch models based on context window size or cost efficiency without changing your state management logic. Use the API to route long-context tasks to models with larger windows, while using smaller, faster models for intermediate steps that require minimal history.
Review your state persistence layer for serialization errors. Ensure that complex tool outputs, such as JSON objects or large strings, are properly formatted before being added to the message list. Improper formatting can cause parsing errors in the next inference step, breaking the chain. For detailed implementation examples, see the FastInfra documentation.
Implement Error Recovery Strategies
Tool failures in multi-step chains usually stem from invalid arguments, network timeouts, or rate limits. A robust system must distinguish between transient errors, which are recoverable, and semantic errors, which require model intervention. Implement a retry mechanism with exponential backoff for network-related issues. This prevents overwhelming the upstream service during temporary outages. For semantic errors, such as a tool rejecting malformed JSON, the system should feed the error message back into the LLM. The model then generates corrected arguments. This loop continues until the tool succeeds or a maximum retry count is reached. Avoid infinite loops by setting a hard cap on retries, typically between three and five attempts. Use this pattern to handle tool execution errors:if error.is_transient():
retry_with_backoff()
elif error.is_semantic():
context.append(f"Error: {error.message}")
response = client.chat.completions.create(
model="auto",
messages=context
)
extract_and_retry_tools(response)
else:
raise error
When retries fail, implement a fallback strategy. Switch to a simpler, faster model for the remaining steps if the primary model is hallucinating or stuck. This reduces latency and cost while maintaining progress. You can access hundreds of models via a single API endpoint, allowing dynamic switching based on performance metrics.
Monitor token usage during error recovery. Each retry consumes input and output tokens. Track the cost of failed attempts to identify problematic tools or prompts. Adjust your routing logic to avoid expensive models for simple, high-failure tasks. Review the pricing structure at /pricing to understand how per-token billing affects your error-handling budget.
Finally, log all error states and recovery actions. This data is essential for debugging complex chains. Identify which tools fail most often and refine their function definitions. Clear, specific error messages improve the LLM's ability to self-correct.
Control Token Usage Costs
Multi-step tool calling multiplies token consumption. Each iteration requires sending the full conversation history, including previous tool calls and outputs, back to the model. Without optimization, costs scale linearly with the number of steps. Route intermediate reasoning steps to cheaper models. Reserve high-cost, high-capability models only for the final answer generation or complex logic that smaller models cannot handle. FastInfra automatically routes requests to the lowest-cost provider that meets your performance requirements, reducing spend without manual vendor management. At median pricing, input tokens cost 0.2794 and output tokens cost 0.918. The 3.3 determines the effective cost per step. Minimizing verbose tool outputs and pruning history before the next call directly reduces this ratio.| Model | Input $/1M | Output $/1M | Routes |
|---|---|---|---|
Solar Mini 4.5upstage/solar-mini-4-5 | $0.0108 | $0.0432 | 1 |
Mistral Nemomistralai/mistral-nemo | $0.0313 | $0.0324 | 1 |
L3 Lunaris 8Bsao10k/l3-lunaris-8b | $0.04 | $0.05 | 1 |
Ling 3.0 Flashinclusionai/ling-3.0-flash | $0.0227 | $0.068 | 1 |
Llama 3.2 3B Instructmeta-llama/llama-3.2-3b-instruct | $0.0648 | $0.0648 | 2 |
Mistral Small 24B Instruct 2501mistralai/mistral-small-24b-instruct-2501 | $0.054 | $0.0864 | 2 |
Command R7B 12.2024cohere/command-r7b-12-2024 | $0.0375 | $0.15 | 1 |
Nova Micro V1amazon/nova-micro-v1 | $0.0378 | $0.1512 | 1 |
Schematron V2 Turboinference-net/schematron-v2-turbo | $0.0324 | $0.162 | 1 |
Trinity Miniarcee-ai/trinity-mini | $0.0486 | $0.162 | 1 |
Select Models for Routing
Routing decisions in multi-step tool calling directly impact latency and cost. Simple extraction tasks or single-step function calls do not require large language models with extensive reasoning capabilities. Routing these requests to smaller, faster models reduces inference time and lowers per-token expenses. Complex chains involving multiple dependencies, conditional logic, or multi-hop reasoning benefit from larger models that maintain context accuracy across steps.
FastInfra provides access to 723 models, including 0 free options, allowing you to match model capacity to task complexity. Instead of using a single heavy model for the entire pipeline, implement dynamic routing based on the predicted difficulty of the current step. This strategy ensures that simple validation or formatting steps execute quickly, while complex planning steps utilize models with higher reasoning capabilities.
Define routing rules in your application logic or configuration. You can inspect the tool call structure or use a lightweight classifier to determine the required model tier. For example, if a step requires only JSON schema validation, route to a small parameter model. If the step involves synthesizing information from previous tool outputs to plan the next action, route to a larger model.
response = client.chat.completions.create(
model="fastinfra/router:best-effort",
messages=history,
tools=tools,
extra_body={"routing_strategy": "complexity_based"}
)
Monitor the performance of each model in your specific tool-calling workload. Latency thresholds and success rates vary by model architecture and provider. Use the API documentation to understand model-specific constraints and capabilities. Adjust your routing thresholds based on observed error rates and token consumption. This iterative tuning process ensures that your application remains cost-efficient while maintaining the reliability required for multi-step automation. Review your pricing structure to understand how different model tiers affect your overall inference budget.
Debugging Multi-Step Chains
Multi-step tool calling chains are difficult to debug because errors to trace because the failure point is often hidden in the middle of a long conversation history. A single malformed JSON response or a silent timeout can cause the entire loop to terminate without a clear error message. Effective debugging requires capturing the full state at every iteration, not just the final result.
Log the complete request and response payload for every API call. Include the system prompt, user message, and any previous tool outputs. This creates an audit trail that reveals exactly what the model saw when it decided to call a tool or finish. Without this context, you cannot distinguish between a model logic error and a tool execution failure.
{
"messages": [...],
"tools": [...],
"request_id": "req_123",
"step": 3,
"tool_call_id": "call_456"
}
Inspect intermediate tool outputs immediately after execution. If a tool returns an error or unexpected data, log that specific output before sending it back to the model. This prevents the model from hallucinating corrections based on bad data. Use a structured log format that separates tool execution logs from model inference logs.
- Capture the exact JSON schema sent to the model to verify it matches your tool definitions.
- Record the latency of each step to identify bottlenecks in tool execution versus model inference.
- Flag any step where the model ignores a tool output and attempts to finish prematurely.
Use FastInfra's per-token pricing model to monitor cost anomalies during debugging. If a chain enters an infinite loop, costs will spike rapidly. Set up alerts for high token usage per request to catch runaway loops early. Review the pricing details to understand how input and output tokens accumulate across multiple turns. This financial visibility helps you identify inefficient chains that require architectural fixes rather than just code patches.
Related FastInfra resources
Frequently asked questions
How do I prevent infinite loops in tool calling?
Set a maximum iteration limit in your loop logic. If the model requests tools beyond this limit, force a final response or trigger an error handler to break the cycle.
Should I use streaming for multi-step tool calls?
Streaming is useful for real-time feedback but complicates state management. For multi-step logic, it is often easier to wait for the full response to parse tool calls before proceeding.
Can I use different models for different steps?
Yes. You can route simple tool calls to cheaper, faster models and reserve complex reasoning steps for more capable models, optimizing both cost and performance.
How do I handle JSON parsing errors in tool arguments?
Wrap tool execution in try-catch blocks. If JSON parsing fails, return the error message to the model in the next turn, instructing it to correct the format.
What is the best way to store tool outputs?
Store tool outputs as messages in the conversation history with a specific role (e.g., 'tool' or 'function'). This keeps the context linear and easy for the model to reference.
Last reviewed November 16, 2026 by FastInfra. Prices and counts on this page are refreshed from the live catalog on every load.