AI Agents by HandAll problemsAbout

All problems › Agent problem · medium · ~20 min

Delegate to a sub-agent

sub-agents context isolation

Solve it in your browser →

Delegate to a sub-agent (~20 min)

subagent.py is the planner again, with two tools (search_flights, search_hotels) and a working loop. The planner should also know what a destination is like on the travel date (weather, what's worth doing in that weather), but that research takes several lookups, and you don't want all of it in the planner's context.

The module already has a researcher: its own tools (SUB_TOOLS: get_weather, search_attractions), handlers (SUB_HANDLERS), system prompt (SUB_SYSTEM), model (SUB_MODEL) and turn budget (SUB_MAX_TURNS). run_subagent is a stub.

Goal: give the planner a research_destination tool that hands a question to the researcher and gets back only its answer.

  1. Add a tool named research_destination to the planner's tools. Its input: city and question (both strings, both required).
  2. Running it starts a fresh researcher conversation whose first user message contains the city and the question. Researcher calls use model=SUB_MODEL, system=SUB_SYSTEM, tools=SUB_TOOLS, and run the usual tool loop (every tool_use gets a tool_result, failures come back as is_error).
  3. The researcher's final text is the research_destination tool result. None of the researcher's own messages, tool calls or tool results appear in the planner's history.
  4. The researcher gets at most SUB_MAX_TURNS model calls. If it runs out, or anything inside it raises (including an API error), the planner gets an is_error result for that research_destination call and carries on. The planner never crashes because of the researcher.
  5. The researcher can't call research_destination itself, and every model call (planner and researcher) goes through the same client that run_agent was given.
  6. search_flights, search_hotels, max_turns and the is_error handling keep working, and run_agent(prompt, client=None, max_turns=10) -> str keeps its signature.

Be ready to explain what you gain from a sub-agent here (context size, cost, a cheaper model, focused instructions) and what you lose (latency, the planner can't see the raw data, errors are summarized), and when you'd just give the planner the tools directly.

Try it: python -m subagent Check it: pytest tests/test_subagent.py

Starter code and hidden tests open in the editor. Nothing to install.