Understanding the max_turns Parameter for Automatic Tool Execution in aisuite
The max_turns parameter activates an automatic tool-execution loop in aisuite that repeatedly invokes the LLM, executes requested tools, and feeds results back into the conversation until the specified iteration limit is reached.
aisuite is Andrew Ng's Python library that provides a unified interface to multiple LLM providers. When building agents that require iterative tool use, the max_turns parameter eliminates boilerplate code by automatically managing the conversation loop between the model and your tool implementations.
How max_turns Triggers the Tool Runner
When you pass max_turns to a chat completion request, aisuite switches from a single-turn response to an iterative execution mode.
In aisuite/client.py, the Completions.create() method inspects the keyword arguments for max_turns at lines 92–96. If the parameter is present, the method immediately delegates execution to the private _tool_runner method instead of proceeding with a standard single completion call (lines 49–55).
This delegation triggers a while-loop that continues interacting with the provider until either the model stops requesting tool calls or the turn limit is reached.
Inside the _tool_runner Implementation
The _tool_runner method in aisuite/client.py implements the automatic execution logic through the following sequence:
-
Tool Validation and Wrapping (lines 64–73): The method accepts tools as either a
Toolsinstance or a raw list of callable functions. It validates and normalizes these into a consistent internal format before execution begins. -
State Initialization: The runner initializes counters including
turns,intermediate_responses, andintermediate_messagesto track the conversation state across iterations. -
Execution Loop: While
turns < max_turns, the runner:- Sends the current message list to the provider via
provider.chat_completions_create - Extracts any tool calls from the LLM's response
- Executes the requested tools locally
- Appends the tool results to the conversation history
- Increments the turn counter
- Sends the current message list to the provider via
-
Termination: The loop exits when the model returns a response without tool calls or when the iteration count reaches the configured
max_turnslimit.
Practical Usage Example
The following example demonstrates configuring a chat completion with automatic tool execution limited to five turns:
import aisuite as ai
client = ai.Client()
def get_weather(location):
"""Tool function to fetch weather data."""
return f"Sunny and 75°F in {location}"
tools = [get_weather]
messages = [
{"role": "user", "content": "What's the weather in San Francisco and New York?"}
]
# Enable automatic tool execution with max 5 turns
response = client.chat.completions.create(
model="openai:gpt-4o",
messages=messages,
tools=tools,
max_turns=5
)
print(response.choices[0].message.content)
In this example, aisuite automatically handles the entire conversation loop. If the model decides to call get_weather for both cities in separate turns, the framework manages the tool execution and result injection without requiring manual intervention.
Summary
max_turnsis a keyword argument accepted byaisuite.client.Completions.create()that enables automatic multi-turn tool execution.- The parameter is extracted at lines 92–96 in
aisuite/client.pyand triggers delegation to the_tool_runnermethod. - The tool runner validates tools (lines 64–73), initializes state counters, and executes a while-loop that continues until the turn limit is reached or no more tool calls are requested.
- This feature eliminates manual loop management when building agents that require multiple tool invocations to complete a user request.
Frequently Asked Questions
What happens when the max_turns limit is reached?
When the iteration counter equals the max_turns value, the _tool_runner exits the while-loop and returns the current conversation state to the caller. According to the implementation in aisuite/client.py, this occurs even if the model still has pending tool calls, effectively capping the execution depth to prevent infinite loops or excessive API costs.
Can I use max_turns with any provider supported by aisuite?
Yes. The max_turns parameter is handled entirely within the aisuite client layer before delegation to specific providers. The loop invokes the provider's chat_completions_create method generically, meaning you can use max_turns with any provider configured in your aisuite environment, including OpenAI, Anthropic, Google, or local models.
How does aisuite validate the tools parameter when max_turns is active?
At lines 64–73 of aisuite/client.py, the _tool_runner validates whether the tools argument is an instance of the Tools class or a list of callable functions. If you pass raw functions, aisuite wraps them appropriately before entering the execution loop, ensuring consistent schema generation and error handling across different provider formats.
Does max_turns affect token usage or pricing?
Yes. Each iteration of the tool execution loop generates a separate API call to the underlying provider. Setting a high max_turns value increases the total number of requests and tokens consumed, as the full conversation history (including all previous tool results) is sent with each subsequent turn. Monitor your usage carefully when enabling automatic tool execution for complex multi-step tasks.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →