The first book‑length catalog of prompt architecture as design patterns.


Why a Pattern Catalog?

Agent building used to feel like a hobbyist craft. People cobbled prompts together, copied snippets, and hoped for the best. The result was fragile code that broke with a model update. A pattern catalog changes that. It gives us reusable building blocks. It lets us reason about agents the way software engineers reason about classes and modules.

The repo at <https://github.com/lorenzouriel/21-ai-agentic-design-patterns> gathers 21 patterns in one place. It supplies runnable examples for CrewAI and LangChain. It treats prompts as code. That shift is the core of this article.


The Landscape of Patterns

The patterns fall into five families.

  • Prompt Chaining – Connect multiple prompts into a logical flow.
  • Routing – Dispatch work to the right sub‑agent.
  • Parallelization – Run independent branches at the same time.
  • Orchestrator‑Worker – A master coordinates specialized workers.
  • Evaluator‑Optimizer – One agent judges another and suggests improvements.

Within those families sit 21 concrete patterns. Below we walk through each one, give a short description, and show tiny code snippets for CrewAI and LangChain.


1. ReAct (Reason + Act)

ReAct blends internal reasoning with external tool calls. The prompt asks the model to think step‑by‑step, then act when a tool is needed.

CrewAI

from crewai import Agent, Task, Crew

react_agent = Agent(
    role="Researcher",
    goal="Answer questions using web search",
    backstory="You love digging for facts.",
    llm=llm,
    tools=[web_search]
)

react_task = Task(
    description="Use ReAct to answer: {{question}}",
    expected_output="A concise answer with citations"
)

crew = Crew(agents=[react_agent], tasks=[react_task])
crew.kickoff()

LangChain

from langchain.agents import ReActAgent
from langchain.tools import DuckDuckGoSearchRun

agent = ReActAgent.from_llm_and_tools(
    llm, tools=[DuckDuckGoSearchRun()]
)
answer = agent.run("Why does the sky appear blue?")

Why it matters: ReAct is the foundation for any agent that needs to fetch data.


2. Plan‑and‑Execute

First the model writes a plan. Then it runs each step in order. The pattern separates thinking from acting, making debugging easier.

CrewAI

plan_agent = Agent(
    role="Planner",
    goal="Create a step‑by‑step plan for {{task}}",
    llm=llm
)
execute_agent = Agent(
    role="Executor",
    goal="Carry out steps from the plan",
    llm=llm,
    tools=[python_tool]
)

LangChain

from langchain.agents import create_openai_functions_agent

planner = create_openai_functions_agent(llm, functions=[plan_function])
executor = create_openai_functions_agent(llm, functions=[execute_function])
plan = planner.invoke({"input": "Summarize the 2024 US election"})
result = executor.invoke({"plan": plan})

Why it matters: Clear separation helps teams audit each phase.


3. LLM‑as‑Judge

One model evaluates the output of another. The judge returns a score and optional feedback.

CrewAI

judge = Agent(
    role="Critic",
    goal="Score the draft and suggest improvements",
    llm=llm
)

review = judge.run(draft_text)

LangChain

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

template = "Score the following answer from 1‑10 and give a brief critique:\n\n{answer}"
judge_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(template))
score = judge_chain.run({"answer": answer})

Why it matters: Automated quality control scales without human bottlenecks.


4. Self‑Correction

The agent checks its own output, spots errors, and patches them. It loops until the answer passes a sanity check.

CrewAI

self_corrector = Agent(
    role="Editor",
    goal="Detect and fix mistakes in the response",
    llm=llm
)

fixed = self_corrector.run(initial_answer)

LangChain

from langchain.output_parsers import JsonOutputParser

prompt = "Check the answer for factual errors. Return a JSON with corrected text."
chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(prompt))
fixed = chain.run({"answer": answer})

Why it matters: Reduces hallucinations in a single pass.


5. Human‑in‑the‑Loop (HITL)

The agent pauses for user input before proceeding. It formats a clear request and resumes when the human replies.

CrewAI

human_agent = Agent(
    role="Mediator",
    goal="Ask the user for clarification before continuing",
    llm=llm,
    tools=[human_input]
)

LangChain

from langchain.agents import AgentExecutor, Tool

ask_tool = Tool(name="AskHuman", func=lambda x: input(x), description="Ask user a question")
agent = AgentExecutor.from_agent_and_tools(agent=llm, tools=[ask_tool])

Why it matters: Guarantees safety when stakes are high.


6. Prompt Chaining – Simple

Chain two prompts: one generates a schema, the next fills it.

CrewAI

schema_agent = Agent(...)
fill_agent = Agent(...)

def chain(data):
    schema = schema_agent.run(data)
    return fill_agent.run({"schema": schema, "data": data})

LangChain

from langchain.prompts import PromptTemplate

template1 = PromptTemplate.from_template("Give a JSON schema for {topic}")
template2 = PromptTemplate.from_template("Populate the schema with details about {topic}")

7. Prompt Chaining – Conditional

Branch based on the first prompt’s answer.

CrewAI

if "yes" in first_answer.lower():
    result = yes_agent.run()
else:
    result = no_agent.run()

LangChain

from langchain.chains import SequentialChain

chain = SequentialChain(chains=[first, second], input_variables=["x"], output_variables=["y"])

8. Routing – Keyword

Send a request to the agent whose expertise matches a keyword.

CrewAI

router = Agent(
    role="Router",
    goal="Match requests to the right specialist",
    llm=llm,
    tools=[finance_agent, legal_agent, tech_agent]
)

LangChain

from langchain.routing import MultiPromptRouter
router = MultiPromptRouter(prompts={"finance": finance_prompt, "legal": legal_prompt})

9. Routing – Function

Map a function name in the user request to a tool.

CrewAI

if "summarize" in query:
    summarizer.run(query)

LangChain

from langchain.agents import initialize_agent, Tool
agent = initialize_agent([summarize_tool, translate_tool], llm, agent="zero-shot-react-description")

10. Parallelization – Map‑Reduce

Run many workers in parallel, then combine results.

CrewAI

workers = [Agent(...), Agent(...), Agent(...)]
results = crew.run_parallel(tasks)
final = reducer.run(results)

LangChain

from langchain.utilities import ParallelChain
parallel = ParallelChain(chains=[chain1, chain2, chain3])
combined = parallel.run(inputs)

11. Parallelization – Fan‑Out/Fan‑In

Broadcast a request to several agents, then pick the best answer.

CrewAI

candidates = [agent_a.run(q), agent_b.run(q), agent_c.run(q)]
best = selector.run(candidates)

LangChain

from langchain.agents import AgentExecutor
# Use an aggregator tool that scores each response

12. Orchestrator‑Worker – Master/Slave

A master agent creates subtasks, workers execute, and the master merges.

CrewAI

master = Agent(...)
worker = Agent(...)
plan = master.run(task)
outputs = [worker.run(step) for step in plan]
final = master.combine(outputs)

LangChain

from langchain.experimental.plan_and_execute import PlanAndExecute
executor = PlanAndExecute(llm=llm, planner=planner, executor=worker)

13. Orchestrator‑Worker – Supervisor

Supervisor monitors worker health and retries on failure.

CrewAI

try:
    result = worker.run(step)
except Exception:
    supervisor.run(step)

LangChain

from langchain.callbacks import CallbackManager
manager = CallbackManager([RetryCallback()])

14. Evaluator‑Optimizer – Gradient

Evaluator scores a draft, optimizer rewrites to improve the score.

CrewAI

score = evaluator.run(draft)
optimized = optimizer.run({"draft": draft, "target": score+1})

LangChain

from langchain.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are an optimizer."),
    ("human", "Improve this: {text}")
])

15. Evaluator‑Optimizer – Reinforcement Loop

Loop until a threshold is reached.

CrewAI

while True:
    feedback = evaluator.run(current)
    if feedback["score"] >= 9:
        break
    current = optimizer.run({"text": current})

LangChain

from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=opt_prompt)

16. Prompt Templates – Fixed

Store a reusable prompt in a file and load it at runtime.

CrewAI

with open("templates/research.txt") as f:
    prompt = f.read()
agent.run(prompt)

LangChain

from langchain.prompts import PromptTemplate
prompt = PromptTemplate.from_filepath("templates/research.txt")

17. Prompt Templates – Dynamic

Insert variables into a template using Jinja‑style placeholders.

CrewAI

prompt = "Answer the question: {{question}}"
agent.run(prompt, variables={"question": q})

LangChain

prompt = PromptTemplate.from_template("Answer: {question}")

18. Tool Wrappers – Simple

Expose a function as a LangChain tool.

CrewAI

agent.add_tool(name="calc", func=lambda x: eval(x))

LangChain

from langchain.tools import tool
@tool
def calc(expr: str) -> str:
    return str(eval(expr))

19. Tool Wrappers – Composite

Combine several APIs behind a single abstraction.

CrewAI

class ResearchTool:
    def __call__(self, query):
        return web_search.run(query) + wikipedia.run(query)
agent.add_tool(name="research", func=ResearchTool())

LangChain

class ResearchTool(BaseTool):
    name = "research"
    def _run(self, query):
        return f"{search(query)}\n{wiki(query)}"

20. Memory – Short‑Term

Keep a short‑term context store that the agent can read/write.

CrewAI

agent.memory.add("last_topic", topic)
previous = agent.memory.get("last_topic")

LangChain

from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()

21. Memory – Long‑Term Vector Store

Persist embeddings and retrieve similar past tasks.

CrewAI

vector_store = FAISS.from_texts(past_tasks, embedding)
agent.add_memory(vector_store)

LangChain

from langchain.vectorstores import FAISS
store = FAISS.from_texts(docs, embedding)

Putting It All Together

A production system seldom uses a single pattern. Most real agents layer several. A typical workflow might look like this:

  1. Router decides whether the request is finance, law, or code.
  2. Planner writes a plan using Plan‑and‑Execute.
  3. Parallel workers fetch data with ReAct.
  4. Evaluator‑optimizer scores the draft.
  5. Human‑in‑the‑Loop asks the user to approve the final answer.

The repo ships a full end‑to‑end example that stitches these pieces. Clone it, run python demo.py, and you’ll see the patterns in action.


Final Thoughts

Design patterns give us a shared language. They reduce duplication and make agents easier to audit. The 21 patterns in this catalog are the first step toward a mature engineering discipline for LLM agents. Start using them today and watch your agents become more reliable, maintainable, and fun to build.


Citations


Suggested Title

“21 Agentic Design Patterns: A Blueprint for Building Reusable LLM Agents”


Word Count

1157


Fact‑Check Notes

  • Verify that the repo URL is correct and public.
  • Confirm the ReAct implementation matches the latest CrewAI and LangChain versions.
  • Ensure the code snippets run without import errors (may need minor version tweaks).
  • Double‑check the citation for the original ReAct paper.