PTENES
MODULE 3.3 · Track 3 · Model, cost, and orchestration

Chaining subagents

The orchestrator doesn’t just launch subagents — it chains: the output of A feeds B, which feeds C. This module teaches you how to design, debug, and scale sequential pipelines without having agents talk to each other.

⏱ ~25 min 🔗 7 topics 💡 Intermediate level
🎼 MAESTRO coordinates the chain Agent A research Agent B draft Agent C review ✓ output ⛔ An agent cannot call another agent always through the maestro Maestro → subagent A → subagent B → subagent C → Result

The conductor coordinates the entire chain. Agents don’t communicate directly — each one responds only to the conductor.

Detailed content

What it is

Chaining subagents means that the A's output becomes the B's input, which in turn feeds C — and the orchestrator coordinates each handoff. There is no direct conversation between agents: the chain exists entirely in the orchestrator’s context.

Why learn

✦ Separates responsibilities into clear stages
✦ Each agent operates in a clean, focused context
✦ Makes debugging easier: it failed in B, not A or C
✦ Lets you reuse steps in other chains

Key concepts

→
Input bridge

The conductor extracts A’s result and injects it as context into B’s prompt.

→
Deterministic chain

A→B→C always in that order; the conductor doesn't skip steps without checking the previous output.

→
Checkpoint

Between each stage, the orchestrator can validate, transform, or abort before continuing.

What it is

Skills are instructions loaded into the maestro's context — they guide the behavior. Agents are subprocesses with their own window — they run isolated work. In a chain, the skill defines the workflow; the agents handle the steps.

Key concepts

✓ Skill: good for

  • ✓ Define the chain's steps
  • ✓ Reuse logic across projects
  • ✓ Trigger multiple subagents
  • ✓ Keep the orchestrator’s context short

◎ Agent: good for

  • ◎ Intensive file reading
  • ◎ In-depth web research
  • ◎ Generating a standalone artifact
  • ◎ Task with its own tools

💡 Practical tip

Use the skill as the chain orchestrator — it contains the prompt that launches each agent in sequence and instructs the orchestrator to hand off outputs between them.

Why learn

Confusing a skill with an agent is the most common mistake when designing chains. Understanding the distinction prevents bloating the orchestrator's context with work that should live in a separate window.

What it is

In Claude Code, a subagent isn't allowed to launch another subagent directly. All delegation goes through the orchestrator. This isn't a limitation — it's intentional design to ensure traceability, cost control, and visibility into the workflow.

⛔ Prohibited pattern

# ❌ NÃO funciona assim
Agent A → lança Agent B internamente
Agent B → lança Agent C internamente

# ✓ Como funciona de fato
Maestro → Agent A → retorna resultado
Maestro → Agent B (com output de A) → retorna resultado
Maestro → Agent C (com output de B) → retorna resultado

Why learn

✗ Risk of ignoring

  • • Infinite delegation loops
  • • API costs with no cap
  • • Zero traceability
  • • Difficult to debug

✓ Model benefit

  • • Maestro sees everything
  • • Predictable cost per stage
  • • Can abort at any point
  • • Clear logs for each agent

Key concepts

The architecture is star (orchestrator at the center), not mesh (all connected). Each subagent is a leaf of the tree — never an intermediate node with its own children.

What it is

Each subagent has exactly one relationship: with the conductor that created it. It doesn’t know other subagents, has no access to their context, and cannot influence them. It’s a specialist hired for a single mission — it delivers the report and wraps up.

Key concepts — lifecycle

Maestro builds the prompt

Includes the necessary context + the previous step’s output

Subagent opens its own window

Zero context — it only sees what the orchestrator sent

Executes the task

Can use tools, read files, call APIs

Returns the result to the orchestrator

Clean text — single report, no conversation

Window closes — context released

There's no "later" for the subagent

Why learn

Understanding the 1-to-1 relationship prevents attempts to "make agents collaborate directly" — which fail silently, without an explicit error.

What it is

The conductor decides whether to sequence, not the agents. The conductor evaluates: "Does B depend on A's output ?" If so, it's a chain. If not, it can be parallel. This decision determines latency vs. cost.

Key concepts

🔗 Chain them when:

  • → B uses A's output
  • → Order matters for quality
  • → Accuracy > speed
  • → Incremental review of the result

⚡ Parallelize when:

  • → Tasks are independent
  • → Speed > accuracy
  • → Fan-out for data collection
  • → N versions to compare later

💡 Rule of thumb

If you can describe the task as “research and then draft and then review", is a chain. If it's "research and at the same time collect examples", is parallel.

Why learn

Chaining when you could parallelize wastes latency. Parallelizing when there’s a dependency produces incorrect results. Knowing the difference is the core orchestration skill.

What it is

A skill can contain instructions that guide the orchestrator to launch subagents in sequence. The skill doesn’t execute anything — it’s loaded into the orchestrator’s context and guides each call to the Agent tool.

Key concepts

1
Skill defines the workflow

Lists the steps, what each agent receives, and what it should return.

2
Maestro runs the workflow

Launch Agent A, capture its output, build a prompt for Agent B, and so on.

3
Skill is reusable

The same workflow can be invoked in any project without rewriting it.

Why learn

Putting the chain logic in a skill makes the project auditable, version-controlled, and portable. Without this pattern, orchestration is scattered across ad hoc prompts that are impossible to maintain.

What it is

A chain of 3-5 agents works well with a human orchestrator. Beyond that, accumulated outputs inflate the context and increase the cost of each step. The natural next step is to migrate to a workflow: tools like n8n, LangGraph, or Python scripts that coordinate agent calls outside the LLM’s context.

Key concepts — signs it’s time to scale

⚠ Warning signs

  • ! Chain with >6 steps
  • ! A’s output barely fits in B’s prompt
  • ! Needs a retry for each step
  • ! Unpredictable total cost

✓ Solution: workflow

  • → n8n coordinates via JSON/HTTP
  • → State persists across steps
  • → Retry without rerunning everything
  • → Logs by node, not by token

Why learn

Know when to stop using the conversational conductor and migrating to a workflow is the difference between a pipeline that works in production and one that collapses in the third week.

Real example

Skill that orchestrates subagents in a chain: research → draft → review

.claude/skills/pipeline-pesquisa.md
# pipeline-pesquisa

Orquestra 3 subagentes em cadeia para produzir um artigo pesquisado e revisado.

## Quando usar
Quando o usuário pedir "pesquise X e escreva um artigo" com qualidade alta.

## Etapas

### ETAPA 1 — Pesquisa (web-research-assistant)
Lançar um subagente `web-research-assistant` com o prompt:

```
Pesquise profundamente sobre: {TEMA}
Retorne:
- 5 fatos verificados com fonte
- 3 perspectivas contraditórias
- 1 dado quantitativo recente
Formato: markdown estruturado, máx. 400 palavras.
```

Capture o output como `PESQUISA`.

### ETAPA 2 — Rascunho (general-purpose)
Com `PESQUISA` em mãos, lançar `general-purpose`:

```
Com base nas pesquisas abaixo, escreva um artigo de 600 palavras sobre {TEMA}.
Tom: educativo, direto, sem jargão.
Use os fatos como base; cite as perspectivas contraditórias.

--- PESQUISA ---
{PESQUISA}
```

Capture como `RASCUNHO`.

### ETAPA 3 — Revisão (general-purpose)
Lançar `general-purpose` com o rascunho:

```
Revise o artigo abaixo para:
1. Precisão factual (corrija erros vs. pesquisa fornecida)
2. Clareza e fluidez
3. Tamanho: mantenha 500-650 palavras
Retorne APENAS o artigo final, sem comentários.

--- RASCUNHO ---
{RASCUNHO}
--- PESQUISA ORIGINAL ---
{PESQUISA}
```

## Output
Retorne ao usuário o artigo revisado com o cabeçalho:
`## Artigo: {TEMA} (pesquisado + revisado)`

## Regras
- Maestro NÃO encurta as etapas
- Se ETAPA 1 falhar, abortar com mensagem clara
- Agentes não se comunicam diretamente

Stage 1

web-research-assistant gathers facts with sources

Stage 2

general-purpose turns research into a draft

Stage 3

general-purpose reviews and delivers the final article

Ready-made prompts

Copy and adapt — each prompt triggers a chain of subagents

Research → draft → review chain
Use a skill pipeline-pesquisa. Tema: "impacto dos LLMs no mercado de trabalho".
Encadeie: [1] web-research-assistant para coletar 5 fatos recentes com fonte,
[2] general-purpose para rascunhar artigo de 600 palavras,
[3] general-purpose para revisar precisão e fluência.
Retorne apenas o artigo final.
Code analysis → refactor → test chain
Encadeie 3 subagentes:
1. Explore para mapear todos os arquivos em src/ e listar funções com mais de 50 linhas
2. general-purpose para refatorar as 3 maiores funções encontradas (recebe output do 1)
3. general-purpose para escrever testes unitários das funções refatoradas (recebe output do 2)
Cada agente recebe apenas o output do anterior — não o contexto todo.
Collection → synthesis → publication chain
Monte uma cadeia de 3 subagentes para processar o relatório em /docs/relatorio.pdf:
[A] web-research-assistant: pesquise o contexto de mercado do tema do relatório
[B] general-purpose: sintetize relatório + pesquisa num resumo executivo de 1 página
[C] general-purpose: formate o resumo em HTML compatível com o design system INEMA
Passe o output de cada etapa como contexto para a próxima.

Simulated screen

Maestro orchestrating a chain of 3 subagents in the terminal

claude — pipeline-pesquisa $ /pipeline-pesquisa "impact of LLMs on the market" ▶ Step 1 — web-research-assistant prompt: "Research in depth: impact of LLMs..." subagent_type: web-research-assistant | context: isolated ✓ complete → 412 tokens output └─ output captured → injected into Step 2 ▶ Step 2 — general-purpose (draft) prompt: "Based on the research below, write..." context: Step 1 output included | own window ✓ complete → 638 words └─ draft captured → injected into Step 3 ▶ Step 3 — general-purpose (review) prompt: "Review for factual accuracy and clarity..." context: draft + original research | own window ✓ complete → 601 words ✓ Pipeline complete: 3 steps | ~2.8k tokens total ## Article: impact of LLMs on the job market (researched + reviewed) Large language models are redefining...
🎯

Exercise

Model a 3-step chain for a real problem of yours

Task

  1. 1. Choose a real problem from your work that involves 3 distinct stages (e.g., collect data → analyze → write a report).
  2. 2. For each step, define: subagent name, input (what it receives from the orchestrator) and output (what it hands back).
  3. 3. Write the maestro's "checkpoint" between each step: what does it validate before moving on?
  4. 4. Explain: why does each step need to be sequential rather than parallel?

Verification criterion

✓ Well-modeled chain

  • ✓ Each agent receives only what it needs
  • ✓ No agent calls another directly
  • ✓ Maestro has an explicit checkpoint
  • ✓ Clear sequence rationale

✗ Warning signs

  • ✗ "Agent A asks Agent B"
  • ✗ B’s input does not use A’s output
  • ✗ Maestro doesn’t validate between steps
  • ✗ Stages could run in parallel

💡 Self-assessment tip

Put your model through the “what if A fails?” test: if the conductor can detect the failure and abort before launching B, the chain is well designed. If not, it needs a checkpoint.

Previous: Module 3.2 Next: Module 3.4