Skip to content

How to set max_turn for agents set as tools. #497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yongkangzhao opened this issue Apr 14, 2025 · 9 comments
Closed

How to set max_turn for agents set as tools. #497

yongkangzhao opened this issue Apr 14, 2025 · 9 comments
Labels
question Question about using the SDK

Comments

@yongkangzhao
Copy link

yongkangzhao commented Apr 14, 2025

Please read this first

  • Have you read the docs?Agents SDK docs
    YES, seems max_turn is only available to be set at Runner. but with the implementation of agents as tools, I don't get access to the Runner of the tool agents.
  • Have you searched for related issues? Others may have had similar requests
    YES couldn't find any

Question

Describe your question. Provide details if available.
How to set max_turn when agents are being used as tools.
I have serveral agents as tool use case. and the main agent can set Runner.run(max_turn), but I couldn't figure out where so inject max_turn limits for agents created as tools.

exactly like this example here: https://github.com/openai/openai-agents-python/blob/main/examples/agent_patterns/agents_as_tools.py

if it is not already implemented, I would suggest having a parameters for Agent, so that each agent can have a different max_turn limits, while Runner.run max_turn can override it.

thanks!

@yongkangzhao yongkangzhao added the question Question about using the SDK label Apr 14, 2025
@rm-openai
Copy link
Collaborator

Just added some docs for this here: #504

@yongkangzhao
Copy link
Author

I see, but does this also applies for MCP tools? Since I'm also using tools obtained from MCP servers, I don't get to modify the tool implementations.

@rm-openai
Copy link
Collaborator

Well MCP tools don't have a max_turns param - what are you trying to achieve with MCP tools?

@yongkangzhao
Copy link
Author

yongkangzhao commented Apr 14, 2025

For example,

Browser control MCP tool/agents often runs more than 10 turns.

Each time the main agent gives another agent as tool a small task to finish on its own, and just report back the results. That way my main agent only sees the result and so my total context is reduced a bit, and so the agent can focus on accomplishing the big task without derailing its attention during the process.

DEFAULT_MAX_TURNS = 10

I see that the default max turn is hard coded here, can we modify it so that this can be override with some kind, environment variables perhaps?

@rm-openai
Copy link
Collaborator

@yongkangzhao I think I'm not totally following.

  • If the agent is being used in code you wrote, then you can pass max_turns=99999 (or whatever else you like)
  • If the agent is being used in an MCP server you wrote, same as the first point, you can pass max_turns=whatever
  • If the agent is written by someone else inside their MCP server, then you'll need to ask the person who wrote that MCP server to set max_turns.

I see that the default max turn is hard coded here, can we modify it so that this can be override with some kind, environment variables perhaps?

You can just pass the max_turns to Runner.run() instead?

@yongkangzhao
Copy link
Author

yongkangzhao commented Apr 14, 2025

@rm-openai

import asyncio
import os
from typing import List, Dict, Any, Optional

# Assuming imports succeed
from agents import Agent, Runner, trace, gen_trace_id, ModelSettings
from agents.mcp import MCPServerSse

PLAYWRIGHT_MCP_URL = "http://localhost:8931/sse"

async def run_simple_web_task():
    print(f"INFO: Attempting to connect to Playwright MCP Server at {PLAYWRIGHT_MCP_URL}")

    async with MCPServerSse(
        name="PlaywrightMCPExampleServer",
        params={"url": PLAYWRIGHT_MCP_URL}
    ) as server:
        print("INFO: MCP Server connection established.")

        browser_agent = Agent(
            name="BrowserToolAgent",
            instructions=(
                "You are a browser interaction specialist. Execute the specific browser commands "
                "given to you (e.g., navigate, get_text, click). Use only the provided tools. "
                "Be precise with URLs and selectors."
                "When asked to play tictactoe, you are expected to make the move."
                "When you finish, tell the user the result of the task, what you did, and what the final is. Especially detail the key information on the page."
            ),
            mcp_servers=[server],
            model_settings=ModelSettings(tool_choice="required"),
            handoff_description="Controls a web browser via Playwright MCP (navigate, get text, click)."
        )

        orchestrator_agent = Agent(
            name="WebTaskOrchestrator",
            instructions=(
                "Your goal is to accomplish the user's web-based task. Analyze the request. "
                "Do not attempt to perform the task directly. Instead, "
                "use the 'browser_tool' to perform those specific actions. "
                "Provide clear instructions to the tool, including URLs and what specific text/element is needed. "
                "Iterate until the task is complete. "

                "for example, if the task is to play a game, "
                "ask the browser tool to navigate to the game page, "
                "then ask the browser tool to click on the game board, "
                "ask the browser tool to give you the current game state so you can decide your next move, "
                "and finally, ask the browser tool to click on the game board again to make your move. "
                "if you are not sure what to do next, ask the browser tool to give you the current game state. "
                "Report the final result to the user after the task is complete."
            ),
            tools=[
                browser_agent.as_tool(
                    tool_name="browser_tool",
                    tool_description="Use to interact with web pages: navigate to a URL, get text from elements."
                )
            ]
        )
        print("INFO: Orchestrator agent created.")

        task_message = "Go to https://www.wikidata.org/wiki/Q28865 and traverse the page to the page concept of Math(Q395). Do not use the search bar. Do not ask the browser agent to directly navigate to the Math page either. This is meant to be a challenge for you, collaborate with the browser agent to solve this problem iteratively."

        print(f"\nINFO: Executing task: '{task_message}'")
        trace_id = gen_trace_id()
        trace_url = f"https://platform.openai.com/traces/trace?trace_id={trace_id}"
        print(f"INFO: Trace URL: {trace_url}")

        with trace(f"Minimal Example - {trace_id}", trace_id=trace_id):
            #here I can adjust the number of max_turn for the orchestrator agent, but I don't see how to adjust the max_turn for the agents as tools.
            result = await Runner.run(
                starting_agent=orchestrator_agent,
                input=task_message
            )

        print("\n--- Orchestration Result ---")
        final_output = result.final_output if result.final_output else "No final output generated."
        print(f"Final Output: {final_output}")
        print("--------------------------")

if __name__ == "__main__":
    print("INFO: Starting Minimal Playwright MCP Agent Example (No Error Handling)...")
    # Set API keys if needed
    # import openai
    # openai.api_key = "YOUR_API_KEY"
    asyncio.run(run_simple_web_task())
    print("INFO: Script finished.")

This is a quick example, don't actually run it, it wouldn't take 10 turns.
but incase you do here is the command to start the mcp_server:

npx @playwright/mcp@latest --port 8931

I don't see a way for me to adjust the max_turn of browser_agent Agent here.

@rm-openai
Copy link
Collaborator

rm-openai commented Apr 15, 2025

@yongkangzhao do this instead:

@function_tool
def browser_tool(input:str):
  """Use to interact with web pages: navigate to a URL, get text from elements."""
  browser_agent = Agent(...)
  result = await Runner.run(browser_agent, input, max_turns=50)
  return ItemHelpers.text_message_outputs(result.new_items)

then do orchestrator_agent=Agent(..., tools=[browser_tool])

That should do what you need.

@yongkangzhao
Copy link
Author

oh! 😳

Literally agent as tool 🤦‍♂️.

Thank you!

I also had to add async in front of def.

Works for me now, thank you!

@rm-openai
Copy link
Collaborator

Awesome, closing this out then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question about using the SDK
Projects
None yet
Development

No branches or pull requests

2 participants