🚀 One API for every frontier model on FastInfra

Browse models

Transparent per-token pricing → compare providers on FastInfra

View pricing

OpenAI-compatible chat completions → start in minutes

Read the docs

⚡ Server Auction → Enterprise bare metal from $78.15/mo (173 in stock)

Browse deals

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.
The 10 cheapest paid chat models on FastInfra by combined input and output price (USD per 1M tokens)
ModelInput $/1MOutput $/1MRoutes
Solar Mini 4.5
upstage/solar-mini-4-5
$0.0108$0.04321
Mistral Nemo
mistralai/mistral-nemo
$0.0313$0.03241
L3 Lunaris 8B
sao10k/l3-lunaris-8b
$0.04$0.051
Ling 3.0 Flash
inclusionai/ling-3.0-flash
$0.0227$0.0681
Llama 3.2 3B Instruct
meta-llama/llama-3.2-3b-instruct
$0.0648$0.06482
Mistral Small 24B Instruct 2501
mistralai/mistral-small-24b-instruct-2501
$0.054$0.08642
Command R7B 12.2024
cohere/command-r7b-12-2024
$0.0375$0.151
Nova Micro V1
amazon/nova-micro-v1
$0.0378$0.15121
Schematron V2 Turbo
inference-net/schematron-v2-turbo
$0.0324$0.1621
Trinity Mini
arcee-ai/trinity-mini
$0.0486$0.1621
Implement history compression to control costs. Remove redundant context, summarize long tool outputs, and keep only the essential state variables for the next step. This reduces the input payload for subsequent API calls. # Route intermediate steps to cost-optimized models response = client.chat.completions.create( model="auto", # FastInfra selects cheapest available messages=compressed_history, tools=tools ) Compare model capabilities against step complexity. Use small, fast models for simple data extraction or formatting tasks. Use larger models only when semantic understanding is required. See the full model list at /models. Monitor token usage per step. Identify which tools generate the most verbose outputs. Refine tool definitions to return structured, concise data (e.g., JSON) instead of natural language descriptions. This reduces output token count significantly. Review your pricing structure at /pricing to understand per-token rates. Automatic routing ensures you never pay for more capability than needed for a specific step in the chain.

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.