Skip to content

Expose max_turns Parameter When Running an Agent as a Tool #551

@dspencej

Description

@dspencej

Description:

Currently, when converting an agent to a tool via the as_tool method, the underlying call to Runner.run does not allow specifying a custom max_turns value. The call defaults to the library’s DEFAULT_MAX_TURNS (currently set to 10), which may be insufficient for certain workflows where an agent should be allowed to run for more iterations.

Current Behavior:

In the current implementation of the Agent.as_tool method, the tool is defined as follows:

@function_tool(
    name_override=tool_name or _transforms.transform_string_function_style(self.name),
    description_override=tool_description or "",
)
async def run_agent(context: RunContextWrapper, input: str) -> str:
    from .run import Runner
    output = await Runner.run(
        starting_agent=self,
        input=input,
        context=context.context,
    )
    if custom_output_extractor:
        return await custom_output_extractor(output)
    return ItemHelpers.text_message_outputs(output.new_items)

Notice that no max_turns parameter is passed to Runner.run(), so the default value is always used. This limits the flexibility of running agents as tools because some scenarios might require a higher turn limit.

Proposed Enhancement:

It would be beneficial if the library provided a mechanism to override the max_turns limit when an agent is run as a tool. Possible approaches include:

Updating as_tool to Accept a max_turns Parameter:
Allow an optional parameter (e.g., max_turns: int = DEFAULT_MAX_TURNS) in the as_tool method signature, and then pass that value to the call to Runner.run(). For example:

def as_tool(
    self,
    tool_name: str | None,
    tool_description: str | None,
    custom_output_extractor: Callable[[RunResult], Awaitable[str]] | None = None,
    max_turns: int = DEFAULT_MAX_TURNS,  # New parameter to override default
) -> Tool:
    @function_tool(
        name_override=tool_name or _transforms.transform_string_function_style(self.name),
        description_override=tool_description or "",
    )
    async def run_agent(context: RunContextWrapper, input: str) -> str:
        from .run import Runner
        output = await Runner.run(
            starting_agent=self,
            input=input,
            context=context.context,
            max_turns=max_turns,  # Pass the custom value here
        )
        if custom_output_extractor:
            return await custom_output_extractor(output)
        return ItemHelpers.text_message_outputs(output.new_items)
    return run_agent

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions