# Agentic patterns: ReAct, plan and execute, reflection, multi-agent, routing

Beyond the basic loop, agent systems reuse a handful of patterns. Run each one and watch the messages move between planner, workers, critics, routers and people.

<div data-sim="patterns"><p>Interactive simulation. It needs JavaScript; the text below explains what it shows.</p></div>

## What you are looking at

Each pattern is drawn as its parts and the messages between them; Run plays a typical exchange and the log lists every message. The runs are illustrative scripts, chosen to show where each pattern spends its model calls.

## Things to try

- ReAct: count the tool calls before the answer.
- Plan and execute: watch the planner re-plan after a failed step.
- Orchestrator and workers: three workers run in parallel and report back.
- Human in the loop: nothing irreversible happens before approval.

## How it works in real systems

Real agent frameworks (LangGraph, the OpenAI Agents SDK, CrewAI, the Claude Agent SDK) implement these patterns as graphs, handoffs or sub-agents. Choosing the pattern is mostly a trade between cost, latency and how much control a person keeps.

This simulation replays a scripted run so that every step is the same each time; the structure is real, the timings and scores are typical values.

## Code lab

The same idea in real code, step by step. Copy each block into a notebook or a file and run it in order.

<div class="cl-start"></div>

### Step 1 · Prompt chaining and routing

A small helper to call a chat model (any OpenAI-compatible endpoint works, including a local server):

```python
from openai import OpenAI
client = OpenAI()                                              # reads OPENAI_API_KEY
def ask(prompt, model="gpt-4o-mini"):
    r = client.chat.completions.create(model=model, messages=[{"role": "user", "content": prompt}], temperature=0)
    return r.choices[0].message.content
```

```python
def chain(topic):
    outline = ask(f"Write a 3-point outline about {topic}.")
    return ask(f"Write a short paragraph for each point:\n{outline}")
def route(msg):
    kind = ask(f"Classify as one word, billing, technical or other: {msg}").strip().lower()
    return {"billing": lambda m: ask("You are a billing specialist. " + m), "technical": lambda m: ask("You are a support engineer. " + m)}.get(kind, ask)(msg)
```

### Step 2 · Parallelisation and orchestrator–workers

```python
from concurrent.futures import ThreadPoolExecutor
def vote(question, n=3):                       # sectioning or voting: the same call several times in parallel
    with ThreadPoolExecutor() as ex: answers = list(ex.map(lambda _: ask(question), range(n)))
    return ask(f"Pick the answer most of these agree on:\n{answers}")
def orchestrate(task):
    plan = ask(f"Split this task into at most 4 independent subtasks, one per line:\n{task}").splitlines()
    with ThreadPoolExecutor() as ex: parts = list(ex.map(ask, [p for p in plan if p.strip()]))
    return ask(f"Combine these results into one answer to '{task}':\n" + "\n---\n".join(parts))
```

### Step 3 · Evaluator–optimiser

```python
def refine(task, rounds=3):
    draft = ask(task)
    for _ in range(rounds):
        verdict = ask(f"Critique this answer to '{task}'. If it is good, reply only PASS.\n\n{draft}")
        if verdict.strip().startswith("PASS"): break
        draft = ask(f"Improve the answer using this critique.\nTask: {task}\nAnswer: {draft}\nCritique: {verdict}")
    return draft
```

Use the simplest pattern that works; add autonomy only when fixed steps cannot do the job.

<div class="cl-end"></div>

## More simulations

[← Agent run](/ai-simulations/agent-run) · [All AI Simulations](/ai-simulations) · [Naive RAG →](/ai-simulations/rag-naive)
