Agentic Architectures

Catalogue / Multi-agent Coordination

Dynamic Agent Generation

A drafting stage writes the team for this task, then the team works

Shape
orchestrator
Model calls
1 + 3 per drafting round + per step: 1 + agent turns (often 20 to 50)
Latency
high
Complexity
high

Also known as AutoAgents, Automatic agent generation, Expert recruitment

1

What if no fixed roster of specialists fits the task in front of you?

A planner reads the task and writes the team for it: each agent's role prompt, description and tools, plus a plan that assigns steps to them. Two observers review the team and the plan before any work starts. Then a leader runs the plan with the generated agents, step by step.

You may need it if

  • Requests vary so much that any roster you fix lacks the expert the next task needs.
  • A supervisor keeps giving work to the closest specialist it has, which is not the right one.
  • You add a role to the team by hand each time a new kind of request arrives.
2

When is a team written on the spot worse than one you tested?

Use it when

  • Tasks are too varied to staff in advance, and each one needs its own mix of expertise.
  • The roles a task needs can be worked out from its text, before any work is done.
  • Every tool a generated agent may need already exists in a pool you trust.
  • You run a strong model. Writing a sound team and plan is itself a hard task.

Avoid it when

  • The same kind of request comes back all day. A fixed team that has been tested costs less and behaves the same from run to run.
    Use Supervisor & Specialists instead
  • The roster is fine but the plan keeps failing during the work. The problem is replanning, not staffing.
    Use Magentic Orchestration instead
  • One agent with the right tools could do the whole task. Writing and reviewing a team for it is overhead.
    Use ReAct instead
  • The task needs deep specialist knowledge or special access. Generated roles differ only by their prompt and their tools.

What it costs

Model calls
1 + 3 per drafting round + per step: 1 + agent turns (often 20 to 50)
Latency
high
Complexity
high
3

How does a task become a team, and the team a result?

Two stages. Drafting: the planner writes a team and a plan, two observers return feedback, and the planner revises until they have none or three rounds have passed. Execution: a leader hands each step to the generated agents with the context it needs, checks the result and moves on.

feedback toapplyno feedback, or3 roundsnext step, withits contextstepresultlast step doneTask: The goal, described fully enough that the kinds of expertise it needs can be read from it.TaskPlanner: Writes the team (per agent: role prompt, description, tools, advice) and a plan that assigns each step to its agents. Revises both on feedback.PlannerTeam and plan: The current roster of generated agents and the step list. Rewritten during drafting, adjusted by the leader during execution.Team and planAgent observer: Checks each generated agent against the task: is it needed, is it complete, does another one do the same job, is a role missing.AgentobserverPlan observer: Checks the plan: every step has an agent, the steps are clear and in order, and together they cover the task.Plan observerDraft accepted?: Plain code. Passes when neither observer has feedback, or after three review rounds.Draftaccepted?Action observer: The team leader. For each step it selects the earlier results that matter, hands the step to its agents and checks the outcome.ActionobserverGenerated agents: The roles written during drafting. One works alone and refines its own output, or several take turns on a step until they agree.GeneratedagentsResult: The output of the plan's last step, with the team that was generated and the steps that ran.Result
  1. Step 1 of 7

    The planner writes a team for this task

    A library wants to lend tools as well as books and asks for a proposal: rules, costs, risks. The planner writes five agents, each with a role prompt and tools: lending operations, insurance, budget analyst, cost expert and writer. It also writes a five-step plan that names who does each step.

  2. Step 2 of 7

    Two observers review the draft

    The agent observer finds that the budget analyst and the cost expert would do the same job, and that nobody covers the safety of the tools. The plan observer finds a step with no agent assigned. Neither observer does any of the work.

  3. Step 3 of 7

    The planner revises until nothing is left

    The gate sends the feedback back. The planner merges the two cost roles, adds a tool safety agent and assigns the orphan step. On the second round both observers return nothing and the draft is accepted. Three rounds is the limit.

  4. Step 4 of 7

    The leader hands out the first step

    The action observer reads the accepted plan. Step one, the lending rules, goes to the lending operations agent. It receives the task and its role prompt only, since no earlier result exists yet.

  5. Step 5 of 7

    Agents work alone or together

    The lending operations agent drafts the rules and improves them over a few passes of its own. Step three, the risks, was assigned to two agents. Insurance and safety take turns on one text until both agree, within five turns.

  6. Step 6 of 7

    The leader checks and adjusts

    After each step the leader keeps the result and checks it against the plan. The risk step shows that deposits are needed, so the leader adds deposits to the budget step's instruction. Each new step receives only the earlier results it needs.

  7. Step 7 of 7

    The last step is the answer

    The final step belongs to the writer: turn the step results into the proposal the library asked for. Its output is the result of the run. It is delivered with the list of generated agents, so the reader knows who was invented for the job.

What each part does
Task
The goal, described fully enough that the kinds of expertise it needs can be read from it.
Planner
Writes the team (per agent: role prompt, description, tools, advice) and a plan that assigns each step to its agents. Revises both on feedback.
Team and plan
The current roster of generated agents and the step list. Rewritten during drafting, adjusted by the leader during execution.
Agent observer
Checks each generated agent against the task: is it needed, is it complete, does another one do the same job, is a role missing.
Plan observer
Checks the plan: every step has an agent, the steps are clear and in order, and together they cover the task.
Draft accepted?
Plain code. Passes when neither observer has feedback, or after three review rounds.
Action observer
The team leader. For each step it selects the earlier results that matter, hands the step to its agents and checks the outcome.
Generated agents
The roles written during drafting. One works alone and refines its own output, or several take turns on a step until they agree.
Result
The output of the plan's last step, with the team that was generated and the steps that ran.
  • Draft accepted? → Planner: feedback to apply
  • Draft accepted? → Action observer: no feedback, or 3 rounds
  • Action observer → Generated agents: next step, with its context
  • Generated agents → Action observer: step result
  • Action observer → Result: last step done

Where it connects

Entry
task
Task

A goal described fully enough to tell which kinds of expertise it needs. No roster is supplied. The pool of tools that generated agents may receive is already configured.

Exit
result
AnswerDocument

When: Every step of the plan has run and the last one has produced the deliverable.

The output of the plan's last step, which answers the task. Then the generated team with each role and its tools, and the steps with the agents that ran them.

Working memory for one run
team-plan
Plan

The generated agents (role prompt, description, tools, advice) and the step list with the agents assigned to each step. Discarded when the run ends.

4

What do I ask my assistant to set up?

The agents to launch

Planner

Read the task and write the team it needs. For each agent give a name, a role prompt (profile, goal, constraints), a one-line description, tools chosen from the given pool, and advice. Then write a plan whose every step names its agents and its expected output. The last step writes the final answer. When you receive feedback, revise the team and the plan.

Sees: The task, the pool of available tools and the observers' feedback on its previous draft. No work results.

Agent observer

Review the generated team against the task. For each agent, say whether it is needed, whether its prompt and tools are complete, and whether another agent does the same job. Name any missing role. Reply with a list of concrete changes, or an empty list when the team fits.

Sees: The task and the current team. Not the plan and no work results.

Plan observer

Review the plan against the task and the team. Check that every step has at least one agent from the team, that the steps are clear and in a workable order, and that together they cover the task. Reply with a list of concrete changes, or an empty list.

Sees: The task, the current team and the current plan. No work results.

Action observer

You lead the generated team and do none of its work. Before each step, check the previous result against the plan, select from the earlier results only what this step needs, and rewrite the step's instruction if an earlier result changes what it must do. Do not add agents.

Sees: The task, the team, the plan and every step result so far.

Generated agent, one per role in the accepted team, at most six

Your role prompt was written by the planner for this task. Carry out the step you are given with your own tools. Improve the text over your turns. When the step is shared, take turns with the other assigned agents on one text. Say when you would change nothing more.

Sees: Its role prompt, the step, the earlier results the leader selected and the current text of the step. Not the whole history.

A prompt you can paste

Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.

Framework-agnostic prompt
You are the orchestrator of a multi-agent workflow that follows the "Dynamic Agent Generation" architecture.
Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it.

# Task
[Describe your task here]

# Dynamic Agent Generation
A drafting stage writes the team for this task, then the team works.
Input: the task above. It must provide: A goal described fully enough to tell which kinds of expertise it needs. No roster is supplied. The pool of tools that generated agents may receive is already configured. If something essential is missing, ask for it before starting.

Agents to launch:
- Planner: Read the task and write the team it needs. For each agent give a name, a role prompt (profile, goal, constraints), a one-line description, tools chosen from the given pool, and advice. Then write a plan whose every step names its agents and its expected output. The last step writes the final answer. When you receive feedback, revise the team and the plan.
  Context for this agent: The task, the pool of available tools and the observers' feedback on its previous draft. No work results.
- Agent observer: Review the generated team against the task. For each agent, say whether it is needed, whether its prompt and tools are complete, and whether another agent does the same job. Name any missing role. Reply with a list of concrete changes, or an empty list when the team fits.
  Context for this agent: The task and the current team. Not the plan and no work results.
- Plan observer: Review the plan against the task and the team. Check that every step has at least one agent from the team, that the steps are clear and in a workable order, and that together they cover the task. Reply with a list of concrete changes, or an empty list.
  Context for this agent: The task, the current team and the current plan. No work results.
- Action observer: You lead the generated team and do none of its work. Before each step, check the previous result against the plan, select from the earlier results only what this step needs, and rewrite the step's instruction if an earlier result changes what it must do. Do not add agents.
  Context for this agent: The task, the team, the plan and every step result so far.
- Generated agent (one per role in the accepted team, at most six): Your role prompt was written by the planner for this task. Carry out the step you are given with your own tools. Improve the text over your turns. When the step is shared, take turns with the other assigned agents on one text. Say when you would change nothing more.
  Context for this agent: Its role prompt, the step, the earlier results the leader selected and the current text of the step. Not the whole history.

Procedure:
1. List the pool of tools that generated agents may receive. The planner can only choose from this pool.
2. Launch the planner on the task. Ask for a team of at most six agents and a plan of at most eight steps.
3. Launch both observers on the draft. If either returns feedback, give it to the planner and review the new draft. Accept the draft when both return nothing, or after 3 rounds.
4. Create one agent per generated role, with its role prompt and only the tools the planner gave it.
5. For each step, ask the action observer for the context and the final instruction. Then run the assigned agents. One agent refines its own output, and several take turns on one text. Allow 5 turns per step.
6. Keep each step's result. The action observer reads it before preparing the next step.
7. Return the output of the last step as the result, with the team and the steps.

Stop rule: Drafting ends when both observers have no feedback, or after 3 rounds. A step ends when its agents would change nothing more, or after 5 turns. The run ends when the last step has produced its output.

Exit:
- `result`, when: Every step of the plan has run and the last one has produced the deliverable. Deliver: The output of the plan's last step, which answers the task. Then the generated team with each role and its tools, and the steps with the agents that ran them.

# Final deliverable
The last step's output. Then the generated team with each role and its tools, the number of drafting rounds, and the steps with the agents that ran them and any step cut off at 5 turns.

The same thing in code

LangGraph, python, package langgraph
import asyncio
from typing import TypedDict, TypeVar

from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel, Field

MAX_DRAFT_ROUNDS, MAX_TURNS, MAX_AGENTS, MAX_STEPS = 3, 5, 6, 8
TOOL_POOL = ["web_search", "read_file", "run_code"]  # the planner may only choose from this pool
PLANNER = ("Write the team this task needs. For each agent: a name, a role prompt (profile, goal, constraints), "
           f"a one-line description, tools from {TOOL_POOL} and advice. Then write a plan whose every step names "
           "its agents. The last step writes the final answer. When you receive feedback, revise both.")
AGENT_OBSERVER = ("Review the team against the task: is each agent needed and complete, do two agents do the "
                  "same job, is a role missing? List concrete changes, or nothing when the team fits.")
PLAN_OBSERVER = ("Review the plan: every step has an agent from the team, steps are clear and ordered, and "
                 "together they cover the task. List concrete changes, or nothing.")
LEADER = ("You lead the team and do none of its work. Check the previous result against the plan. For the next "
          "step, select only the earlier results it needs, and adjust its instruction if they change it.")


class AgentSpec(BaseModel):
    name: str
    prompt: str
    description: str
    tools: list[str]
    advice: str


class Step(BaseModel):
    instruction: str
    agents: list[str]  # names from the team; several agents take turns


class Draft(BaseModel):
    team: list[AgentSpec] = Field(max_length=MAX_AGENTS)
    plan: list[Step] = Field(max_length=MAX_STEPS)


class Feedback(BaseModel):
    changes: list[str]


class Brief(BaseModel):
    context: str  # the earlier results this step needs, nothing else
    instruction: str


class Turn(BaseModel):
    output: str  # the full current text of the step
    done: bool  # true when this agent would change nothing more


class State(TypedDict):
    task: str
    draft: Draft | None
    feedback: list[str]
    rounds: int
    results: list[str]
    brief: Brief | None


model = init_chat_model("anthropic:claude-sonnet-5-5")
M = TypeVar("M", bound=BaseModel)


async def ask(schema: type[M], system: str, prompt: str) -> M:
    return schema.model_validate(await model.with_structured_output(schema).ainvoke([SystemMessage(system), HumanMessage(prompt)]))


async def planner(state: State) -> dict:
    prompt = f"Task: {state['task']}"
    if state["draft"]:
        prompt += f"\n\nYour draft:\n{state['draft'].model_dump_json()}\n\nFeedback:\n" + "\n".join(state["feedback"])
    return {"draft": await ask(Draft, PLANNER, prompt)}


async def observers(state: State) -> dict:
    draft = state["draft"]
    assert draft is not None
    team = f"Task: {state['task']}\n\nTeam:\n" + "\n".join(a.model_dump_json() for a in draft.team)
    plan = team + "\n\nPlan:\n" + "\n".join(s.model_dump_json() for s in draft.plan)
    a, p = await asyncio.gather(ask(Feedback, AGENT_OBSERVER, team), ask(Feedback, PLAN_OBSERVER, plan))
    return {"feedback": a.changes + p.changes, "rounds": state["rounds"] + 1}


def accepted(state: State) -> str:  # the gate: no feedback, or three review rounds
    return "leader" if not state["feedback"] or state["rounds"] >= MAX_DRAFT_ROUNDS else "planner"


async def leader(state: State) -> dict:
    draft = state["draft"]
    assert draft is not None
    step = draft.plan[len(state["results"])]
    done = "\n".join(f"Step {i + 1}: {r}" for i, r in enumerate(state["results"]))
    return {"brief": await ask(Brief, LEADER, f"Task: {state['task']}\n\nResults so far:\n{done}\n\nNext step: {step.instruction}")}


async def agents(state: State) -> dict:
    draft, brief = state["draft"], state["brief"]
    assert draft is not None and brief is not None
    names = draft.plan[len(state["results"])].agents
    team = [a for a in draft.team if a.name in names] or draft.team[:1]
    text, agreed = "", 0
    for turn in range(MAX_TURNS):  # one agent refines alone; several take turns until all agree
        spec = team[turn % len(team)]
        prompt = f"Step: {brief.instruction}\n\nContext:\n{brief.context}\n\nCurrent text:\n{text or '(none yet)'}"
        reply = await ask(Turn, f"{spec.prompt}\nAdvice: {spec.advice}", prompt)
        text, agreed = reply.output, agreed + 1 if reply.done else 0
        if agreed >= len(team):
            break
    return {"results": state["results"] + [text]}


def steps_left(state: State) -> str:
    draft = state["draft"]
    return "leader" if draft and len(state["results"]) < len(draft.plan) else END


builder = StateGraph(State)
for name, node in (("planner", planner), ("observers", observers), ("leader", leader), ("agents", agents)):
    builder.add_node(name, node)
builder.add_edge(START, "planner")
builder.add_edge("planner", "observers")
builder.add_conditional_edges("observers", accepted, ["planner", "leader"])
builder.add_edge("leader", "agents")
builder.add_conditional_edges("agents", steps_left, ["leader", END])
graph = builder.compile()


async def run(task: str) -> dict:
    start: State = {"task": task, "draft": None, "feedback": [], "rounds": 0, "results": [], "brief": None}
    s = await graph.ainvoke(start, {"recursion_limit": 60})
    team = [{"name": a.name, "description": a.description, "tools": a.tools} for a in s["draft"].team]
    return {"result": s["results"][-1], "team": team, "draft_rounds": s["rounds"], "steps": len(s["results"])}

Generated agents rely on their role prompt here. Map each name in TOOL_POOL to a real tool and bind only the listed ones to each agent.

Claude Agent SDK, python, package claude-agent-sdk
import asyncio
from typing import TypeVar

from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel, Field

MAX_DRAFT_ROUNDS, MAX_TURNS, MAX_AGENTS, MAX_STEPS = 3, 5, 6, 8
TOOL_POOL = ["WebSearch", "WebFetch", "Read", "Grep", "Glob"]  # the planner may only choose from this pool
PLANNER = ("Write the team this task needs. For each agent: a name, a role prompt (profile, goal, constraints), "
           f"a one-line description, tools from {TOOL_POOL} and advice. Then write a plan whose every step names "
           "its agents. The last step writes the final answer. When you receive feedback, revise both.")
AGENT_OBSERVER = ("Review the team against the task: is each agent needed and complete, do two agents do the "
                  "same job, is a role missing? List concrete changes, or nothing when the team fits.")
PLAN_OBSERVER = ("Review the plan: every step has an agent from the team, steps are clear and ordered, and "
                 "together they cover the task. List concrete changes, or nothing.")
LEADER = ("You lead the team and do none of its work. Check the previous result against the plan. For the next "
          "step, select only the earlier results it needs, and adjust its instruction if they change it.")


class AgentSpec(BaseModel):
    name: str
    prompt: str
    description: str
    tools: list[str]
    advice: str


class Step(BaseModel):
    instruction: str
    agents: list[str]  # names from the team; several agents take turns


class Draft(BaseModel):
    team: list[AgentSpec] = Field(max_length=MAX_AGENTS)
    plan: list[Step] = Field(max_length=MAX_STEPS)


class Feedback(BaseModel):
    changes: list[str]


class Brief(BaseModel):
    context: str  # the earlier results this step needs, nothing else
    instruction: str


class Turn(BaseModel):
    output: str  # the full current text of the step
    done: bool  # true when this agent would change nothing more


M = TypeVar("M", bound=BaseModel)


async def ask(schema: type[M], system: str, prompt: str, tools: list[str] | None = None) -> M:
    # one fresh session per call; a generated agent gets its own role prompt and its own tools
    options = ClaudeAgentOptions(
        system_prompt=system,
        allowed_tools=tools or [],
        output_format={"type": "json_schema", "schema": schema.model_json_schema()},
    )
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, ResultMessage) and msg.structured_output:
            return schema.model_validate(msg.structured_output)
    raise RuntimeError("no result")


async def run(task: str) -> dict:
    # drafting: the planner writes the team and the plan, two observers review, three rounds at most
    draft = await ask(Draft, PLANNER, f"Task: {task}")
    rounds = 0
    while rounds < MAX_DRAFT_ROUNDS:
        rounds += 1
        team = f"Task: {task}\n\nTeam:\n" + "\n".join(a.model_dump_json() for a in draft.team)
        plan = team + "\n\nPlan:\n" + "\n".join(s.model_dump_json() for s in draft.plan)
        a, p = await asyncio.gather(ask(Feedback, AGENT_OBSERVER, team), ask(Feedback, PLAN_OBSERVER, plan))
        feedback = a.changes + p.changes
        if not feedback:
            break
        if rounds < MAX_DRAFT_ROUNDS:
            draft = await ask(Draft, PLANNER, f"Task: {task}\n\nYour draft:\n{draft.model_dump_json()}\n\nFeedback:\n" + "\n".join(feedback))

    # execution: the action observer prepares each step, the generated agents carry it out
    results: list[str] = []
    for step in draft.plan[:MAX_STEPS]:
        done = "\n".join(f"Step {i + 1}: {r}" for i, r in enumerate(results))
        brief = await ask(Brief, LEADER, f"Task: {task}\n\nResults so far:\n{done}\n\nNext step: {step.instruction}")
        assigned = [a for a in draft.team if a.name in step.agents] or draft.team[:1]
        text, agreed = "", 0
        for turn in range(MAX_TURNS):  # one agent refines alone; several take turns until all agree
            spec = assigned[turn % len(assigned)]
            prompt = f"Step: {brief.instruction}\n\nContext:\n{brief.context}\n\nCurrent text:\n{text or '(none yet)'}"
            tools = [t for t in spec.tools if t in TOOL_POOL]  # never a tool outside the pool
            reply = await ask(Turn, f"{spec.prompt}\nAdvice: {spec.advice}", prompt, tools)
            text, agreed = reply.output, agreed + 1 if reply.done else 0
            if agreed >= len(assigned):
                break
        results.append(text)
    team_out = [{"name": a.name, "description": a.description, "tools": a.tools} for a in draft.team]
    return {"result": results[-1], "team": team_out, "draft_rounds": rounds, "steps": len(results)}

Each generated agent is a session with the role prompt and the tools the planner chose, filtered against the pool. The pool here is read-only on purpose.

OpenAI Agents SDK, python, package openai-agents
import asyncio

from agents import Agent, Runner
from pydantic import BaseModel, Field

MAX_DRAFT_ROUNDS, MAX_TURNS, MAX_AGENTS, MAX_STEPS = 3, 5, 6, 8
TOOL_POOL = ["web_search", "read_file", "run_code"]  # the planner may only choose from this pool


class AgentSpec(BaseModel):
    name: str
    prompt: str
    description: str
    tools: list[str]
    advice: str


class Step(BaseModel):
    instruction: str
    agents: list[str]  # names from the team; several agents take turns


class Draft(BaseModel):
    team: list[AgentSpec] = Field(max_length=MAX_AGENTS)
    plan: list[Step] = Field(max_length=MAX_STEPS)


class Feedback(BaseModel):
    changes: list[str]


class Brief(BaseModel):
    context: str  # the earlier results this step needs, nothing else
    instruction: str


class Turn(BaseModel):
    output: str  # the full current text of the step
    done: bool  # true when this agent would change nothing more


planner = Agent(
    name="Planner",
    instructions="Write the team this task needs. For each agent: a name, a role prompt (profile, goal, constraints), "
                 f"a one-line description, tools from {TOOL_POOL} and advice. Then write a plan whose every step "
                 "names its agents. The last step writes the final answer. When you receive feedback, revise both.",
    output_type=Draft,
)
agent_observer = Agent(
    name="Agent observer",
    instructions="Review the team against the task: is each agent needed and complete, do two agents do the "
                 "same job, is a role missing? List concrete changes, or nothing when the team fits.",
    output_type=Feedback,
)
plan_observer = Agent(
    name="Plan observer",
    instructions="Review the plan: every step has an agent from the team, steps are clear and ordered, and "
                 "together they cover the task. List concrete changes, or nothing.",
    output_type=Feedback,
)
leader = Agent(
    name="Action observer",
    instructions="You lead the team and do none of its work. Check the previous result against the plan. For the next "
                 "step, select only the earlier results it needs, and adjust its instruction if they change it.",
    output_type=Brief,
)


def generate(spec: AgentSpec) -> Agent:
    # a generated agent is a role prompt and a tool list; map spec.tools to real tools from the pool
    return Agent(name=spec.name, instructions=f"{spec.prompt}\nAdvice: {spec.advice}", tools=[], output_type=Turn)


async def run(task: str) -> dict:
    # drafting: the planner writes the team and the plan, two observers review, three rounds at most
    draft = (await Runner.run(planner, f"Task: {task}")).final_output_as(Draft)
    rounds = 0
    while rounds < MAX_DRAFT_ROUNDS:
        rounds += 1
        team = f"Task: {task}\n\nTeam:\n" + "\n".join(a.model_dump_json() for a in draft.team)
        plan = team + "\n\nPlan:\n" + "\n".join(s.model_dump_json() for s in draft.plan)
        a, p = await asyncio.gather(Runner.run(agent_observer, team), Runner.run(plan_observer, plan))
        feedback = a.final_output_as(Feedback).changes + p.final_output_as(Feedback).changes
        if not feedback:
            break
        if rounds < MAX_DRAFT_ROUNDS:
            revise = f"Task: {task}\n\nYour draft:\n{draft.model_dump_json()}\n\nFeedback:\n" + "\n".join(feedback)
            draft = (await Runner.run(planner, revise)).final_output_as(Draft)

    # execution: the action observer prepares each step, the generated agents carry it out
    members = {spec.name: generate(spec) for spec in draft.team}
    results: list[str] = []
    for step in draft.plan[:MAX_STEPS]:
        done = "\n".join(f"Step {i + 1}: {r}" for i, r in enumerate(results))
        prepare = f"Task: {task}\n\nResults so far:\n{done}\n\nNext step: {step.instruction}"
        brief = (await Runner.run(leader, prepare)).final_output_as(Brief)
        assigned = [members[n] for n in step.agents if n in members] or list(members.values())[:1]
        text, agreed = "", 0
        for turn in range(MAX_TURNS):  # one agent refines alone; several take turns until all agree
            prompt = f"Step: {brief.instruction}\n\nContext:\n{brief.context}\n\nCurrent text:\n{text or '(none yet)'}"
            reply = (await Runner.run(assigned[turn % len(assigned)], prompt)).final_output_as(Turn)
            text, agreed = reply.output, agreed + 1 if reply.done else 0
            if agreed >= len(assigned):
                break
        results.append(text)
    team_out = [{"name": a.name, "description": a.description, "tools": a.tools} for a in draft.team]
    return {"result": results[-1], "team": team_out, "draft_rounds": rounds, "steps": len(results)}

Agents are built at run time from the planner's specifications. Map each name in TOOL_POOL to a real tool and pass only the listed ones to each agent.

Vercel AI SDK, typescript, package ai
import { anthropic } from '@ai-sdk/anthropic';
import { Output, ToolLoopAgent } from 'ai';
import { z } from 'zod';

const MAX_DRAFT_ROUNDS = 3;
const MAX_TURNS = 5;
const MAX_AGENTS = 6;
const MAX_STEPS = 8;
const TOOL_POOL = ['webSearch', 'readFile', 'runCode']; // the planner may only choose from this pool
const model = anthropic('claude-sonnet-5-5');

const specSchema = z.object({
  name: z.string(),
  prompt: z.string().describe('profile, goal and constraints'),
  description: z.string(),
  tools: z.array(z.string()),
  advice: z.string(),
});
type Spec = z.infer<typeof specSchema>;
const draftSchema = z.object({
  team: z.array(specSchema).max(MAX_AGENTS),
  plan: z.array(z.object({ instruction: z.string(), agents: z.array(z.string()) })).max(MAX_STEPS),
});
const feedbackSchema = z.object({ changes: z.array(z.string()) });

const planner = new ToolLoopAgent({
  model,
  instructions:
    'Write the team this task needs. For each agent: a name, a role prompt (profile, goal, constraints), ' +
    `a one-line description, tools from ${TOOL_POOL.join(', ')} and advice. Then write a plan whose every step ` +
    'names its agents. The last step writes the final answer. When you receive feedback, revise both.',
  output: Output.object({ schema: draftSchema }),
});
const agentObserver = new ToolLoopAgent({
  model,
  instructions:
    'Review the team against the task: is each agent needed and complete, do two agents do the ' +
    'same job, is a role missing? List concrete changes, or nothing when the team fits.',
  output: Output.object({ schema: feedbackSchema }),
});
const planObserver = new ToolLoopAgent({
  model,
  instructions:
    'Review the plan: every step has an agent from the team, steps are clear and ordered, and ' +
    'together they cover the task. List concrete changes, or nothing.',
  output: Output.object({ schema: feedbackSchema }),
});
const leader = new ToolLoopAgent({
  model,
  instructions:
    'You lead the team and do none of its work. Check the previous result against the plan. For the next ' +
    'step, select only the earlier results it needs, and adjust its instruction if they change it.',
  output: Output.object({ schema: z.object({ context: z.string(), instruction: z.string() }) }),
});

// a generated agent is a role prompt and a tool list; map spec.tools to real tools from the pool
const generate = (spec: Spec) =>
  new ToolLoopAgent({
    model,
    instructions: `${spec.prompt}\nAdvice: ${spec.advice}`,
    tools: {},
    output: Output.object({ schema: z.object({ output: z.string(), done: z.boolean() }) }),
  });

export async function run(task: string) {
  // drafting: the planner writes the team and the plan, two observers review, three rounds at most
  let draft = (await planner.generate({ prompt: `Task: ${task}` })).output;
  let rounds = 0;
  while (rounds < MAX_DRAFT_ROUNDS) {
    rounds++;
    const team = `Task: ${task}\n\nTeam:\n${JSON.stringify(draft.team)}`;
    const [a, p] = await Promise.all([
      agentObserver.generate({ prompt: team }),
      planObserver.generate({ prompt: `${team}\n\nPlan:\n${JSON.stringify(draft.plan)}` }),
    ]);
    const feedback = [...a.output.changes, ...p.output.changes];
    if (feedback.length === 0) break;
    if (rounds < MAX_DRAFT_ROUNDS) {
      const revise = `Task: ${task}\n\nYour draft:\n${JSON.stringify(draft)}\n\nFeedback:\n${feedback.join('\n')}`;
      draft = (await planner.generate({ prompt: revise })).output;
    }
  }

  // execution: the action observer prepares each step, the generated agents carry it out
  const members = new Map(draft.team.map((spec) => [spec.name, generate(spec)]));
  const results: string[] = [];
  for (const step of draft.plan.slice(0, MAX_STEPS)) {
    const done = results.map((r, i) => `Step ${i + 1}: ${r}`).join('\n');
    const { output: brief } = await leader.generate({
      prompt: `Task: ${task}\n\nResults so far:\n${done}\n\nNext step: ${step.instruction}`,
    });
    const named = step.agents.flatMap((n) => members.get(n) ?? []);
    const assigned = named.length > 0 ? named : [...members.values()].slice(0, 1);
    let text = '';
    let agreed = 0;
    for (let turn = 0; turn < MAX_TURNS; turn++) { // one agent refines alone; several take turns until all agree
      const { output: reply } = await assigned[turn % assigned.length].generate({
        prompt: `Step: ${brief.instruction}\n\nContext:\n${brief.context}\n\nCurrent text:\n${text || '(none yet)'}`,
      });
      text = reply.output;
      agreed = reply.done ? agreed + 1 : 0;
      if (agreed >= assigned.length) break;
    }
    results.push(text);
  }
  const team = draft.team.map(({ name, description, tools }) => ({ name, description, tools }));
  return { result: results[results.length - 1], team, draftRounds: rounds, steps: results.length };
}

Agents are built at run time from the planner's specifications. Map each name in TOOL_POOL to a real tool and pass only the listed ones to each agent.

Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.

What goes wrong

  • Two generated roles that differ only in name make the team larger, not more capable. Have the agent observer compare what each one would actually do.
  • A planner free to invent tools writes agents that cannot act. Let it choose only from a fixed pool, and give each agent few tools.
  • A generated team is untested and changes from run to run. Log the team with every result, or you cannot explain a bad run.
  • Giving every agent the full history recreates one crowded context. Let the leader select what each step needs.
  • A role prompt does not create knowledge. A generated tax lawyer knows what the model knows, in a different tone.

Chain it

Its result can feed

Source