The golden rule
Use the simplest pattern that solves the problem. Patterns stack in layers of increasing complexity and cost. Each step up adds capability, and also latency, cost and new ways to fail.
- 1Prompting
- 2RAG
- 3Workflows
- 4Agents
- 5Multi-agent
| Situation | Reach for |
|---|---|
| The model already knows it | Prompting |
| The model lacks the knowledge | RAG |
| You know the steps | Workflow |
| You don't know the steps | Agent |
| One agent's context or focus breaks down | Multi-agent |
| It touches money, email or production | Human in the loop and guardrails |
1. Prompting patterns
The cheapest layer. Exhaust these before you add infrastructure.
| Pattern | When to use |
|---|---|
| Zero-shot | The task is common and well defined ("summarize this") |
| Few-shot | Output format or style matters: show 2 to 5 examples |
| Chain of thought | Reasoning tasks: math, logic, multi-step analysis |
| Structured output | Code consumes the result: force JSON with tool use or JSON mode |
| Role or system prompt | A consistent persona, tone or set of constraints across a session |
2. RAG patterns
Use RAG when the model needs knowledge it doesn't have: private documents, fresh data, large corpora.
| Pattern | When to use |
|---|---|
| Naive RAG | Embed → retrieve top k → put into the prompt. Fine for small, clean corpora |
| Hybrid search | Vector and keyword (BM25) together. When exact terms matter: IDs, names, code |
| Reranking | Retrieve 50, rerank to 5 with a cross-encoder. Fixes poor precision |
| Query rewriting, HyDE | Rewrite the question before retrieval. For vague or conversational queries |
| Semantic chunking | Structural or semantic chunks beat fixed-size chunks almost always |
| Agentic RAG | The model decides whether and what to retrieve, possibly in rounds. For complex questions across sources |
RAG in two halves
Use it when: the model needs knowledge it does not have: your documents, fresh data, a large corpus.
- Once: split the documents into chunks, embed each chunk, store the vectors.
- Per question: embed it, fetch the nearest chunks, rerank and keep the best few.
- Put those chunks and the question in the prompt, and ask for sources.
The catch: retrieval decides the answer. If the right chunk is not in the top few, the model cannot use it, so measure retrieval before tuning prompts.
3. Workflow patterns
Fixed control flow with an LLM inside each step. Predictable and debuggable, so prefer these over agents whenever the steps are known.
| Pattern | Shape | When to use |
|---|---|---|
| Prompt chaining | Step 1 output feeds step 2 | A known sequence: outline → draft → edit |
| Routing | A classifier sends input to a specialized prompt or model | Support triage; cheap versus expensive model routing |
| Parallelization (fan-out) | Split → N parallel calls → aggregate | Independent subtasks, voting, per-document processing |
| Evaluator-optimizer | Generator and critic loop until accepted | Quality-critical output: code review, translation |
| Orchestrator-workers | A lead LLM decomposes and delegates | Subtasks you can't predict upfront, with one point of control |
4. Agentic patterns
The LLM controls the loop. Use them only when the path can't be decided in advance.
| Pattern | When to use |
|---|---|
| Tool use, function calling | The foundation: the model picks tools and arguments |
| ReAct loop | Reason → act → observe → repeat. The default agent loop |
| Reflection | The agent reviews its own output and retries. Better quality at a latency cost |
| Planning | Write a plan first, then execute. For long multi-step tasks |
| Memory | Short term (the conversation) and long term (facts, preferences). When sessions must build on each other |
| Human in the loop | Approval gates before irreversible actions such as payments, emails and deletes. Required for high-stakes tools |
Workflow or agent
Use it when: you have to choose who decides the next step: your code or the model.
- Workflow: write the steps in code, with one LLM call inside each.
- Agent: give the model tools and let it loop: reason, act, observe.
- Stop the loop on "done", a step limit or a budget.
The catch: every step the model chooses is a step you cannot predict or test in advance. Prefer the workflow whenever you can write the steps down.
5. Agent collaboration patterns
"Multi-agent" is the umbrella term; the patterns below are specific shapes under it. Start with orchestrator-workers, the sensible default.
| Pattern | Structure | When to use | Main cost |
|---|---|---|---|
| Orchestrator-workers (supervisor) | A lead agent delegates; workers never talk to each other | Unpredictable subtasks, one point of control | The supervisor's context grows with every result |
| Sequential pipeline | A → B → C, each owns a stage | Known ordered stages, each with its own tools or context | Errors compound downstream |
| Evaluator-optimizer | Generator and critic loop | Quality over latency, when "good" can be written down | 2 to 5× cost; the critic needs a rubric, not "is this good?" |
| Debate, ensemble voting | N independent answers, then a judge or consensus | High stakes with no ground truth | Most expensive per answer; returns fall off after 3 to 5 agents |
| Hierarchical | Supervisors managing supervisors | Genuinely large scopes, which are rare | Failure modes multiply; hard to trace |
| Swarm | Peers; any agent hands off to any other, no boss | Conversations that shift domain (sales ↔ billing ↔ tech) | Lowest determinism and debuggability |
| Fan-out (map-reduce) | Parallel independent calls → aggregate | Independent chunks where latency matters | Almost none; use it freely, even inside other patterns |
Fan-out, supervisor and swarm compared
Fan-out is a concurrency pattern rather than collaboration: workers never interact and can be plain prompt calls. Swarm is decentralized: routing logic lives inside each agent, and a handoff transfers the whole conversation.
| Fan-out | Supervisor | Swarm | |
|---|---|---|---|
| Who decides routing | You, in code | A central agent | Each agent, locally |
| Workers run | In parallel | Parallel or sequential | One at a time |
| Workers talk to each other | Never | Never (only via the supervisor) | Directly, via handoff |
| Control returns to a center | Yes (reduce step) | Yes (supervisor) | No, control wanders |
| Determinism | High | Medium | Low |
| Debuggability | Easy | Medium | Hard |
Who routes the work
Use it when: one agent is not enough, and you have to decide who sends work where.
- Fan-out: your code splits the work, workers run in parallel, a reduce step joins them.
- Supervisor: a lead agent delegates, and every result comes back to it.
- Swarm: each agent decides whom to hand the conversation to.
The catch: control moves further from your code at each step to the right, and determinism and debuggability drop with it.
How agents communicate
This is a separate choice from the topology above.
- Handoff: full control transfer; the receiving agent gets the conversation (OpenAI Agents SDK style).
- Tool call: a sub-agent is invoked as a function and returns a result, which keeps the parent context clean (Claude and LangGraph subagent style).
- Shared state: a graph state object or scratchpad that all agents read and write (LangGraph's core model).
- Message passing: async messages or events between agents (AutoGen style).
The deciding factor is often isolation versus continuity. Supervisor sub-agents keep contexts isolated: the worker returns a conclusion and the parent stays clean. Swarm handoffs share the conversation history.
6. Case study: a ticket to PR coding pipeline
The shape that works is a sequential pipeline with fan-out inside the read-only stages and an evaluator loop at the end. Not a swarm, and not a free-form supervisor.
- Ticket
- Investigate fan-out, read-only
- Plan
- Human approves the plan
- Implement a single agent
- Verify fresh evaluator agents
- PR description
- Human merges
Investigate with fan-out, read-only sub-agents. This stage is search-heavy and fills context quickly. One agent traces the bug area, one maps the affected tests, one checks conventions and related PRs. Each returns a conclusion instead of file dumps, which keeps the parent context clean. The output is a written investigation doc with the root cause, relevant files, approach options and risks.
Plan behind a human approval gate. This is the highest-leverage place for a human: reviewing a plan is cheap, reviewing a wrong diff is expensive.
Implement with one agent. Code changes are deeply interdependent, and two agents editing related files produce conflicts and inconsistent assumptions. Fan out implementation only when the ticket really splits (backend, frontend, docs), and then with strict file ownership that never overlaps.
Verify with a fresh evaluator, never the implementer. An agent grading its own work is systematically lenient. Spawn fresh agents that get the ticket and the diff: one runs the tests, one reviews against conventions, one checks the acceptance criteria. Findings go back to the implementer for at most 2 or 3 rounds, then escalate to a human.
By ticket size: a small ticket gets a single agent plus a verify step, a medium ticket gets the full pipeline, and only truly parallel workstreams get fan-out implementation with strict file ownership.
The ticket to PR pipeline
Use it when: an agent writes code that people will merge.
- Investigate with read-only agents in parallel; each returns a conclusion, not file dumps.
- A human approves the plan, then one agent implements it.
- Fresh agents verify; findings go back for at most 2 or 3 rounds, then a human merges.
The catch: an agent grading its own work is lenient, so the verifier must never be the implementer.
7. Concerns that apply to every pattern
- Guardrails: input and output validation, prompt injection defense, PII filtering.
- Caching: prompt caching for repeated context, semantic caching for repeated queries.
- Evals: automated test sets plus LLM as judge. Without evals, everything else is guesswork.
- Fallbacks and retries: model or provider fallback chains for reliability.
Hard-won warnings for multi-agent systems
- A single agent with good tools beats multi-agent most of the time. Add agents only when one agent's context or focus clearly breaks down.
- Context isolation is the real reason for sub-agents. If you're not getting that benefit, skip the pattern.
- Every agent boundary loses information, so write explicit contracts for what goes in and what must come back.
- Cost scales linearly with agents; reliability doesn't. Two agents that are each right 90% of the time, chained, are right about 81% of the time.
Framework notes
How the patterns map to LangGraph in Python and Spring AI in Java.
| Concept | LangGraph | Spring AI (Java) |
|---|---|---|
| Fan-out, map-reduce | Send API | Hand-rolled with CompletableFuture or structured concurrency |
| Orchestrator-workers | Subgraphs and Send | A hand-rolled supervisor loop, or a call out to a LangGraph service |
| Evaluator-optimizer | A conditional edge looping back | Advisor chain and a custom loop |
| Swarm | langgraph-swarm | Not native |
| Shared state | The State object | Managed by the application |
| RAG | Retriever nodes | RAG Advisors |
| Tool calling | Native | Native (@Tool, function callbacks) |