Based on the real implementation in langchainrust v0.32.0
(crates/lc-agents/src/orchestrator/, crates/lc-langgraph/src/presets.rs).
This is not a "how to call the API" tutorial. For every pattern it answers
three questions: what problem it solves, what it costs, and when you should
not use it.
Intended for backend and LLM application engineers building Agents, RAG, and
multi-agent systems.
All diagrams are plain-text line drawings. No Mermaid required; they render
directly in Markdown and on CSDN.
Repository: https://github.com/atliliw/langchainrust
If you do not want to read the whole article, match your problem first:
| Your problem | Start with |
|---|---|
| One objective, one tool set, decide as you go | ReAct (with the FunctionCalling variant) |
| Multi-step task, plan first and then execute | PlanExecute |
| Fixed steps with a clear order | SequentialPipeline |
| Decide at runtime which specialist goes next | Supervisor |
| Multiple roles need to read each other and debate/review | GroupChat |
| No center; specialists hand control to each other | Swarm |
| Same task needs parallel perspectives, voting, or best-of | FanOutFanIn |
| Plan first, execute later, avoid repeated observations | ReWOO |
| The answer can be judged, and self-correction helps | Reflexion |
| One sample is unreliable; compare several lines of thought | Tree of Thoughts |
| Actions have side effects and you need rollback | LATS |
| Task types vary and you need a custom reasoning structure | Self-Discover |
These are the 12 patterns used throughout this article. FunctionCalling is a
native tool-calling variant of ReAct and is not counted separately.
LangGraph presets are not a 13th pattern; they are a graph-based way to carry
the patterns above, useful when you need persistence, approvals, or recovery.
A simple decision order:
Are the steps fixed?
ββ Yes β Sequential / FanOutFanIn
ββ No β Do you need multiple roles?
ββ No β single-agent loop / PlanExecute / search
ββ Yes β Do the roles need to see each other's messages?
ββ Yes β GroupChat
ββ No β Supervisor / Swarm
The one-line principle: get the simplest single-agent loop working first, then add structure based on measurements. Do not start with multi-agent.
A single model call has a capability ceiling set by the model. Real tasks are
rarely one question and one answer:
The root cause is usually not that "the model is not smart enough." It is that
the model has not been given a suitable organization. The same model can
behave very differently when placed in different loops, routers, or search
structures.
langchainrust unifies these organizations behind the Orchestrator trait
(crates/lc-agents/src/orchestrator/mod.rs):
#[async_trait]
pub trait Orchestrator: Send + Sync {
type Input;
type Output;
async fn run_with_context(
&self,
input: Self::Input,
ctx: &RunContext,
) -> Result<Self::Output, AgentError>;
fn last_usage(&self) -> Option<RunUsage> { None }
}
RunContext carries the trace_id, a shared workspace, and an optional governor
(timeout/cancellation). Every orchestrator can enter LCEL and can also be wrapped
as a tool for a parent agent.
The rest of this article classifies patterns by collaboration structure, not
by feature name.
Assume the task is: look up three sources (product docs, competitor pricing,
user reviews) and write a comparison brief with citations.
Shared assumptions: 200 tokens per tool observation, 300 tokens per generation,
system prompts excluded. These are order-of-magnitude estimates, not benchmarks.
| Pattern | Model calls | Tool calls | Context behavior | Rough tokens | What it feels like |
|---|---|---|---|---|---|
| ReAct | 6β8 turns | 3 | every observation is re-injected | 4kβ6k | simple, but gets more expensive as it searches |
| ReWOO | 2 (planner + solver) | 3 | observations are read once by the solver | 2kβ3k | cheap if the plan is right |
| Supervisor | 1 routing call + 2β3 workers | 3 | scratchpad summaries | 3kβ5k | dynamic, but routing can wobble |
| GroupChat | 4 roles Γ 2 rounds = 8 calls | 3 | full transcript | 12kβ15k | thorough discussion, most expensive |
The same task: ReAct "searches and thinks as it goes," ReWOO "draws a DAG first
and then executes," Supervisor "finds someone to do it," and GroupChat "holds a
meeting." Picking the wrong structure often does not produce a wrong answer; it
produces an answer that is an order of magnitude more expensive or slower.
Do not go by feel. First record six metrics on the same batch of tasks:
| Metric | What it tells you |
|---|---|
| task success rate | whether the end-to-end task is completed |
| tool-call accuracy | share of correct tools and correct arguments |
| retries per task | average number of retries |
| tokens per success | tokens consumed per successful task |
| P95 latency | tail latency |
| human intervention rate | share of tasks that need a human takeover |
Then choose by failure mode:
| Failure mode | Prefer |
|---|---|
| Missing lookups, wrong lookups, wrong order | PlanExecute / ReWOO |
| The answer can be judged, but the first attempt is wrong | Reflexion / ToT |
| Subtasks are independent | FanOutFanIn |
| Roles need to challenge and review each other | GroupChat |
| Input decides the specialist; routing is not fixed | Supervisor |
| Actions have side effects and need rollback | LATS |
Decision rule: the success-rate gain from the new structure must exceed the increase in tokens and latency. Otherwise you are over-orchestrating. Run an
The most basic class: the model repeatedly "thinks β calls a tool β observes the
result β thinks again" until it produces the final answer.
User input
β
βΌ
[LLM thinks] ββneeds toolββ> [Run tool]
β² β
βββββββ observation back ββ
β
βββ no tool needed ββ> [Final answer]
ReActAgent: the model emits Thought / Action / Action Input, a parser runs
the tool, and the Observation is appended back to the context. Good for text
protocols and models without native tool calling.FunctionCallingAgent: not a separate orchestration pattern, but the native
tool-calling variant of the ReAct loop. Arguments are structured JSON, so no
free-text parsing is needed. Good for OpenAI/Anthropic-style function calling.PlanExecuteAgent: produces a plan first, executes it step by step, and
replans when necessary. Good for tasks with many steps that need an explicit
plan.
Minimal call (ReAct):
let agent = ReActAgent::new(llm, prompt_template);
let executor = AgentExecutor::new(Arc::new(agent), tools)
.with_max_iterations(10);
let answer = executor.invoke("look up ...".to_string()).await?;
Cost: every turn re-injects the history of observations, so tokens grow
linearly with the number of turns. The more tools you have, the longer the prompt
and the more likely the model is to pick the wrong tool.
When not to use it: if the tool-call graph can be determined up front (for
example, "look up A, then use A's result to look up B"), ReAct's turn-by-turn
decision-making is wasted. Use ReWOO instead.
A router model decides each round "who gets the next subtask, or are we done?"
Workers are leaf agents. Their output is fed back into a scratchpad and handed to
the router again.
[objective]
β
βΌ
[Supervisor router]
βββ> [Researcher] ββresultβββ
βββ> [Writer] ββresultβββΌββ> scratchpad
βββ> [Critic] ββresultβββ β
βΌ
next round / FINISH
crates/lc-agents/src/orchestrator/supervisor.rs
max_rounds is bounded; router output supports JSON plus a
<<<NEXT>>> fallback; workers cannot recursively delegate (one-level
recursion guard).
Minimal call:
let researcher = Arc::new(TaskAdapter::from_executor(research_executor));
let writer = Arc::new(TaskAdapter::from_executor(writer_executor));
let supervisor = Supervisor::new(
router_llm,
vec![("Researcher".into(), researcher), ("Writer".into(), writer)],
8,
);
let answer = supervisor
.run_with_context(AgentTask::new("..."), &RunContext::new_random())
.await?;
Every participant can see the full history of messages, and one participant
speaks per round. There are three speaker selectors: round-robin, keyword, and
LLM. There are three termination modes: max rounds, a moderator FINISH, and a
consensus threshold (whichever fires first).
[objective]
β
βΌ
ββββββββββββββββββββββββββββββββ
β Shared transcript β
β [Planner][Researcher][Critic]β
ββββββββββββββββ¬ββββββββββββββββ
β read full history each round
βΌ
[Speaker Selector]
round-robin / keyword / LLM
β
βΌ
[Current speaker]
β
βΌ
append speech to transcript
β
βΌ
termination met?
β β
no yes
β β
ββnext round ββ> [answer]
crates/lc-agents/src/orchestrator/group_chat.rs
A minimal example:
use std::sync::Arc;
use langchainrust::{
AgentTask, GroupChat, GroupChatConfig, GroupParticipant, Orchestrator,
RunContext, SpeakerSelector, Termination,
};
// planner / researcher / critic / writer are all
// Arc<dyn Orchestrator<Input = AgentTask, Output = String>>
let chat = GroupChat::new(
vec![
GroupParticipant::new("Planner", planner).with_role("break down the task"),
GroupParticipant::new("Researcher", researcher).with_role("add facts"),
GroupParticipant::new("Critic", critic).with_role("find problems"),
GroupParticipant::new("Writer", writer).with_role("write the final answer"),
],
GroupChatConfig::new(6, SpeakerSelector::RoundRobin, Termination::MaxRounds),
)?;
let answer = chat
.run_with_context(
AgentTask::new("Write a technical brief on reranking"),
&RunContext::new_random(),
)
.await?;
If you already have an AgentExecutor, wrap it with TaskAdapter first and it
can be used as a participant.
There is no central router. The current agent either answers directly or hands
control to an allowed peer, carrying its context variables with it.
[entry A] ββhandoff(B)ββ> [B] ββhandoff(C)ββ> [C]
β β β
ββ answer directly ββ answer directly ββ answer directly
Constraints: the target must be in the allowlist; max_handoffs prevents ping-pong.
crates/lc-agents/src/orchestrator/swarm.rs
{"handoff":"B","reason":"...","context":{...}}; weaker models can
use <<<HANDOFF>>>B<<<END_HANDOFF>>>. max_handoffs prevents ping-pong.
Send the same input to multiple agents in parallel, then aggregate the results.
βββ> [Worker A] βββ
β β
[objective] ββΌββ> [Worker B] βββΌββ> [Aggregator] ββ> answer
β β
βββ> [Worker C] βββ
crates/lc-agents/src/orchestrator/fan_out_fan_in.rs
Chain stages in a fixed order; each stage's output becomes the next stage's input.
[input] ββ> [Stage 1] ββ> [Stage 2] ββ> [Stage 3] ββ> [output]
crates/lc-agents/src/orchestrator/sequential.rs
| Structure | Where decisions happen | Good for | Not good for |
|---|---|---|---|
| Supervisor | central router | dynamic specialist selection | specialists must see each other's full messages |
| GroupChat | speaker selector | debate/review/role play | low latency, high QPS |
| Swarm | each agent locally | decentralized collaboration | globally optimal scheduling |
| FanOutFanIn | fixed | multiple perspectives/voting | multi-round discussion |
| Sequential | fixed | stable pipelines | runtime decisions |
Where the boundary blurs: if the Supervisor scratchpad turns into "several
specialists interrupting each other," or a worker needs another worker's full
argument to continue, you probably want GroupChat. Conversely, if only one person
keeps working in a GroupChat while everyone else watches, fall back to Supervisor;
it is cheaper.
A three-role loop: the actor produces an answer β the evaluator judges it β on
failure, the reflector compresses the feedback into a reusable lesson β the next
round's actor retries with all lessons.
[actor] ββ> answer ββ> [evaluator] ββpassββ> [final]
β² β
β fail
β βΌ
βββββ [reflector] <ββ feedback
distills a lesson into the next round
crates/lc-agents/src/orchestrator/reflexion.rs
max_attempts is at least 1; when the budget is exhausted, it returns the last
answer with success=false.
Why not just retry? Retrying is repeated sampling; the failure reason is not
retained. Reflexion compresses the failure into a "do not do this next time"
lesson and feeds it into the next round.
In practice: tasks that converge within 2β3 attempts (code repair, format
validation, fact checking) benefit most. After the 4th attempt you are often just
burning tokens.
Cost: attempts Γ (actor + evaluator + reflector), usually 3β5Γ a normal
answer.
Each expansion has the generator produce breadth candidate thoughts, the
evaluator scores each one, and each level keeps only the top beam_width states
to expand further, with max_nodes as a hard cap.
[root]
/ | \
[c1] [c2] [c3] β generator: breadth
\ | /
[evaluator scores]
β
keep top beam_width
β
expand next level
crates/lc-agents/src/orchestrator/tree_of_thoughts.rs
breadth Γ expanded nodes, clearly
higher than a single chain.
Why not just sample more? Sampling is "parallel luck." ToT narrows level by
level using scores, spending budget on more promising branches.
In practice: breadth=2β3, beam_width=2, max_nodes=10β20 are common
starting points. Go higher and evaluator cost runs away first.
Boundary: if the evaluator is more expensive than the generator, or the task
has no comparable intermediate states, ToT is not worth it. Fall back to a single
chain plus multiple samples.
ToT searches "thoughts"; LATS searches "actions" with environment feedback. Four
stages: UCT selection β expand candidate actions β greedy rollout β value
backpropagation.
[UCT select] ββ> [expand actions] ββ> [rollout] ββ> [backpropagate]
β² β
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
crates/lc-agents/src/orchestrator/lats.rs
LatsEnvironment::step(path, action) must be derived from the The key difference from ToT: ToT evaluates "is this thought good?" LATS
evaluates "what does the environment look like after this action?" The former
needs no environment; the latter requires a replayable/snapshot-able environment.
In practice: tasks with tests, simulators, or sandboxes fit best. Do not point
LATS directly at irreversible real-world actions (placing orders, sending
messages, transferring money).
Cost: every expansion needs a rollout, usually tens of times a single chain.
It is only worth it when "a wrong move is expensive and rollback is possible."
ReAct injects one observation per turn. ReWOO separates "planning" from
"execution": the planner emits the entire tool-call graph at once (#E1
references earlier results), the executor runs it in dependency waves, and the
solver sees all observations once and answers.
[planner]
β emits the whole tool DAG
βΌ
#E1 ββ> #E2
β β
βββ> #E3
β
[executor] runs by dependency wave
β
βΌ
[solver] <ββ all observations
crates/lc-agents/src/orchestrator/rewoo.rs
max_retries; errors carry step/tool/attempts.
let rewoo = ReWooAgent::new(
planner,
solver,
tool_executor, // Arc<dyn ReWooToolExecutor>
ReWooConfig::default().with_tools(["search", "summarize"]),
);
let result = rewoo.run_detailed("...", &RunContext::new_random()).await?;
The composer combines a set of atomic reasoning modules (decompose, critique,
verify, analogize, ...) into a task-specific reasoning structure, and the solver
executes it step by step.
[atomic reasoning modules]
decompose / critique / verify / analogize ...
β
βΌ
[composer] ββ> [reasoning structure] ββ> [solver] ββ> answer
crates/lc-agents/src/orchestrator/self_discover.rs
Why not fixed CoT? Fixed CoT assumes the task type is consistent.
Self-Discover selects reasoning modules first and then assembles a structure,
which suits mixed analysis tasks.
In practice: one extra composer call, but it avoids "using the wrong recipe."
A structure parse failure is a direct error; it does not silently fall back to
CoT.
Boundary: simple Q&A and low-latency tasks do not need it. It fits
"analysis/planning" tasks, not "look up one number" tasks.
The patterns above are orchestrators in lc-agents. In lc-langgraph you can
also build them directly as graphs:
create_react_agent / create_supervisor / create_swarm
(crates/lc-langgraph/src/presets.rs) are assembled with a normal StateGraph,
so checkpointing, streaming, and interrupts come naturally.GraphTool (crates/lc-agents/src/graph_tool.rs) wraps a compiled graph as a
BaseTool, so a parent agent can call the whole graph like an ordinary
function.Send primitive supports runtime-determined map-reduce branching; Command
supports resume and fork (time travel).
When to use a graph instead of an orchestrator:
| Pattern | Where decisions happen | Context cost | Determinism | Best for | Typical failure mode |
|---|---|---|---|---|---|
| ReAct | model, every turn | high (observations re-injected) | low | exploratory tool tasks | wrong tool / loop |
| PlanExecute | plan first, then execute | medium | medium | multi-step tasks | stale plan |
| Supervisor | central router | medium | medium | dynamic specialist selection | routing wobble |
| GroupChat | speaker selector + shared record | high (full transcript) | low | debate / review | off-topic, cost explosion |
| Swarm | each agent locally | low (context only) | low | decentralized collaboration | ping-pong, detours |
| FanOutFanIn | fixed | medium | high | multiple perspectives / voting | aggregation conflicts |
| Sequential | fixed | low | high | stable pipelines | inflexible |
| Reflexion | actor/evaluator/reflector | medium | medium | judgeable correction | unreliable evaluator |
| ToT | search + value model | high (many branches) | medium | planning / reasoning | branch explosion |
| LATS | MCTS + environment | high | medium | action tasks with rollback | non-replayable environment |
| ReWOO | one-shot plan | low | high | tool DAGs | unexecutable plan |
| Self-Discover | composer designs first | medium | medium | varying task types | structure parse failure |
FunctionCalling is folded into the ReAct row: it reuses the same
"observation back into context" loop, with native JSON tool arguments.
LangGraph presets are not in the table: they are a graph-based delivery
mechanism, not a 13th orchestration pattern.
max_nodes, and
depth are hard limits. An orchestrator must never "keep running because the
model did not say stop."<<<HANDOFF>>>, <<<THOUGHT>>>, <<<ACTION>>>), and then
errors outβthere is no silent fallback to round-robin.speaker / round / step,
instead of a generic "agent failed."ExecutorOrchestrator (the adapter that wraps an
AgentExecutor as an Orchestrator) gets exact token counts from
AgentMetrics (per-run executor metrics); TaskAdapter prefers real usage
and only falls back to chars/4 estimation when unavailable.
If a single agent can complete the task, multi-agent often just splits the
failure into more pieces. Get the single agent's prompt, tools, and error
handling stable first, then consider collaboration.
Every additional agent adds tokens, latency, failure surface, and debugging cost.
The value of multi-agent comes from role separation and mutual checking, not
from the number of agents.
GroupChat without max_rounds, Swarm without max_handoffs, or Reflexion
without max_attempts all turn into "keep running because the model did not say
stop."
Reflexion / ToT / LATS all depend on an evaluator. When the evaluator itself is
unreliable, more search just makes the model wrong more consistently.
GroupChat is multi-round and serial, with high token and latency costs. For a
low-latency, high-QPS main path, a single agent or Supervisor fits better.
GroupChat is better for offline review, complex decisions, and multi-role
creative work.
Orchestration is not "the more, the better." Every extra layer adds tokens,
latency, and failure surface. The valuable approach is:
With the same model, the right organization improves quality while reducing
cost; the wrong one only packages the failure in more complexity.