108. Hands-on ~ Tool Calling Agent

This passage explains how to build a simple tool-calling agent with LangGraph using the ReAct loop:

  • Define tools with @tool, such as:

    • calculate(expression)

    • get_weather(city)

    • search_web(query)

  • Define graph state so messages are appended, not overwritten, using:

    • messages: Annotated[list, add_messages]

  • Bind tools to the LLM:

    • llm_with_tools = llm.bind_tools(tools)

  • Create an agent node that sends the message history to the LLM and returns its response.

  • Route execution based on whether the LLM produced tool calls:

    • If yes, go to the ToolNode

    • If no, end the graph

  • Use ToolNode(tools) to automatically execute requested tools.

  • Build the graph:

    • Start at the agent

    • Agent decides whether to call tools

    • Tools run if needed

    • Return to agent for the final response

  • Debugging note:

    • If messages always stay at length 1, the state is probably not using add_messages.

Overall, it shows the standard reason → act → reason workflow:

  1. The model reasons about what tool to use,

  2. the tool is executed,

  3. the model reasons again to produce the final answer.

109. Custom Tool with Error Handling

The passage explains how to build a LangGraph agent with a custom divide tool that handles errors gracefully.

Key points:

  • A divide tool is created that returns the division result for two floats.

  • If the second number is 0, the tool returns an error string like: “Division by zero is undefined.”

  • The tool is added to a tools list and bound to the LLM with llm_with_tools.

  • An agent node processes messages and returns responses.

  • A should_continue function checks the last message to decide whether to continue to the tools node or end.

  • A ToolNode is created with the tool, and the graph is wired:

    • agent → tools if tool use is needed

    • agent → end otherwise

    • tools → agent to complete the loop

Behavior:

  • Query like “What is 100 divided by 5?” returns 20.

  • Query like “What is 100 divided by 0?” does not crash; the tool returns an error message, and the LLM explains the problem naturally.

Main lesson:

  • In production, tools should return errors instead of raising exceptions.

  • The LLM can interpret those error messages and respond appropriately.

  • This keeps the agent robust without needing try/except logic in the graph itself.

110. Hands-on ~ The Supervisor Agent

The passage explains the supervisor pattern in multi-agent systems, where a central supervisor agent coordinates specialized agents.

Main idea

  • A user query is received.

  • The supervisor decides which specialist agent should handle each step.

  • The specialist performs the task and returns the result.

  • The supervisor reviews the output, decides the next step, and keeps routing until the job is finished.

Supervisor responsibilities

The supervisor:

  • understands the user’s intent,

  • breaks complex work into subtasks,

  • routes tasks to the right agent,

  • collects and combines results,

  • decides when the workflow is complete.

Implementation overview

A graph-based workflow is built with:

  • shared state for messages and routing info,

  • a structured routing schema like RouteDecision,

  • a supervisor node that makes routing decisions,

  • specialist agents such as:

    • researcher

    • writer

    • critic

  • a finalizer node to end the workflow.

Workflow behavior

  • Specialists do not call each other directly.

  • All routing goes back through the supervisor, creating a hub-and-spoke architecture.

  • The system loops until the supervisor sends the task to finish.

Example

For a request like “Write a short blog about the benefits of AI in healthcare,” the workflow may be:

  1. supervisor → researcher

  2. supervisor → writer

  3. supervisor → critic

  4. supervisor → writer again if revisions are needed

  5. supervisor → finish

Why it matters

This pattern is useful because it provides:

  • separation of concerns

  • dynamic, adaptive workflows

  • a common architecture used in real-world systems like CrewAI, AutoGen, and enterprise agent platforms.

Key takeaway

The supervisor pattern uses a central controller to manage specialized agents through structured routing until the task is complete.

111. Hands-on ~ Agent Handoffs in LangGraph

The passage explains agent handoffs in LangGraph and why they’re important in real-world customer service systems.

Core idea

A single chatbot agent can’t handle every kind of request well, so the system uses triage to route the message to the right specialist agent, such as:

  • sales

  • support

  • billing

  • or end if no escalation is needed

Why handoffs matter

Handoffs improve:

  • response quality

  • speed of resolution

  • customer satisfaction

  • system efficiency

This mirrors how real enterprise support systems work.

Shared state

All agents share state fields like:

  • messages — conversation history

  • current_agent — who is handling the request

  • handoff_reason — why it was transferred

  • context_summary — key info for the next agent

These fields help preserve context so the next agent doesn’t start from scratch.

Structured routing

Instead of trusting free-form text, the triage agent returns structured output with:

  • handoff_to

  • reason

  • context

Using fixed options like sales, support, billing, stay, or end makes routing reliable.

How the system works

  1. Triage agent reads the message and decides where it should go.

  2. If the decision is end, the system responds directly.

  3. If the decision is a specialist, the conversation is handed off with full context.

  4. The specialist handles the request and finishes the workflow.

Specialist agents

Each specialist has a specific role:

  • Sales: upgrades, pricing, purchases

  • Support: bugs, crashes, technical issues

  • Billing: charges, invoices, duplicate payments

Graph structure

The LangGraph has nodes for:

  • triage

  • sales

  • support

  • billing

The flow starts at triage, routes conditionally, and then ends after the specialist responds.

Supervisor vs handoff

  • Supervisor pattern: agents often report back to a manager agent

  • Handoff pattern: triage sends the request directly to the right specialist, and the workflow usually ends there

Why this is valuable

The system avoids unnecessary escalation, which saves:

  • latency

  • compute

  • cost

At scale, even routing a portion of requests directly can significantly reduce LLM usage and expenses.

Big picture

The passage argues that handoffs are a practical production pattern, not just a demo. LangGraph lets you combine routing, context transfer, and specialist agents into a flexible architecture.

112. Hands-on ~ Map-Reduce Strategy

The passage explains two multi-agent workflow patterns:

Parallel agent execution

  • A shared state is defined with fields for the query, three agent outputs, and a final synthesis.

  • Three agents run in parallel:

    • Research agent for factual/academic output

    • Creative agent for imaginative output

    • Technical agent for technical depth

  • A synthesizer then combines the three results into one coherent final response.

  • The graph fans out from START to all three agents, then fans back in to the synthesizer, which outputs final_synthesis.

MapReduce summarization

  • This pattern is used for document summarization with a map and reduce phase.

  • State includes:

    • documents

    • summaries

    • final_summary

  • In the map step, each document is summarized independently.

  • In the reduce step, all summaries are combined into one final overview.

  • The graph is simple: START -> map -> reduce -> END.

  • It scales to many documents, but large inputs may exceed context limits.

  • A common production fix is hierarchical reduction, where summaries are reduced in batches repeatedly until one final summary remains.

113. How Agents Communicate ~ Reducers Deep Dive

The passage explains how communication works in multi-agent systems and why shared state is usually better than direct agent-to-agent calls.

Main points

  • In single-agent systems, communication is not an issue.

  • In multi-agent systems, agents need a way to share information.

1. Direct agent-to-agent calls

  • Agent A calls Agent B directly.

  • This is tightly coupled:

    • A must know B exists

    • A must know B’s format and interface

  • It scales poorly because connections grow rapidly as more agents are added.

  • Similar to everyone in an office having to call each other directly.

2. Shared state / blackboard pattern

  • Agents communicate through a shared workspace instead of directly.

  • One agent writes to the state, another reads from it.

  • This is:

    • decoupled

    • easier to extend

    • easier to inspect, debug, log, replay, and audit

  • Similar to people writing on a whiteboard for others to read later.

3. Real-world relevance

  • This pattern is common in:

    • message queues like Kafka or RabbitMQ

    • Redux-like state systems

    • enterprise source-of-truth architectures

4. Three communication patterns

  • Message passing: agents share one conversation thread.

    • Best for chat and Q&A

  • Shared state: each agent writes to structured fields.

    • Best for pipelines and parallel workflows

  • Blackboard pattern: combines both messages and typed fields.

    • Often the most practical approach

5. Reducers

  • Reducers determine what happens when multiple agents write to the same state.

  • Common behaviors:

    • Overwrite: last write wins

    • Append: keep all values in a list

    • Add messages: special handling for chat/tool messages

    • Custom merge: domain-specific logic like voting or conflict resolution

6. Choosing a reducer

  • Use overwrite for latest-only values

  • Use operator.add for accumulating items

  • Use add_messages for chat/tool message workflows

  • Use a custom reducer for special merging logic

Final takeaway

Multi-agent communication is usually best handled through shared state or a blackboard, with reducers defining how conflicting writes are merged.

114. Hands-on ~ Message Passing Pattern

This example shows agent communication via message passing in a simple workflow:

  • A shared state is passed through the pipeline, containing:

    • messages: an annotated list of BaseMessage objects

    • current_phase: a string indicating which agent acts next

Workflow agents

  1. Researcher

    • Reads the shared state

    • Researches the topic

    • Adds its findings as a message

    • Sets current_phase to "fact_checker"

  2. Fact Checker

    • Reviews the researcher’s output

    • Verifies accuracy

    • Adds a fact-checker message

    • Sets current_phase to "summarizer"

  3. Summarizer

    • Uses all accumulated messages

    • Produces a final summary

    • Sets current_phase to "done"

Graph setup

The state graph is built with these nodes and edges:

  • START -> researcher

  • researcher -> fact_checker

  • fact_checker -> summarizer

  • summarizer -> END

Demo

The pipeline is run with an input like:

  • “What are the main benefits of renewable energy?”

Execution proceeds in order:

  1. Researcher

  2. Fact checker

  3. Summarizer

Main point

This demonstrates message passing where each agent reads from and writes to a shared message state, while control moves through defined workflow phases.

115. Hands-on ~ Shared Field State

This passage explains the shared state pattern for multi-agent systems, also called a typed field approach.

Core idea

Agents communicate by writing to and reading from shared structured fields in a common state object. Each field has a clear purpose, such as raw_data, analysis, confidence, or recommendation.

Example workflow

  1. Data collector agent

    • Reads the user query

    • Generates data points with the LLM

    • Stores them in raw_data

  2. Analyst agent

    • Reads raw_data and query

    • Summarizes the information

    • Writes to analysis and confidence

  3. Advisor agent

    • Reads analysis, confidence, and query

    • Produces a final recommendation

    • Writes to recommendation

Graph flow

The pipeline goes:

Data Collector → Analyst → Advisor → End

Why it’s useful

Shared state makes the system:

  • easier to understand

  • easier to debug

  • easier to extend

  • more organized, since each agent has a defined role

Summary

In this pattern, agents collaborate through shared fields: one agent collects data, the next analyzes it, and the final one makes a recommendation.

117. Hands-on ~ The Blackboard Iterative Refinement

The blackboard pattern uses a shared state where agents iteratively refine the same artifact until it passes a quality check.

  • Drafter reads critiques and writes a better draft.

  • Critic reviews the latest draft, returns structured feedback, and either approves it or asks for more changes.

  • They communicate only through the shared blackboard, not directly.

Shared state includes

  • message history

  • topic

  • all drafts

  • all critiques

  • iteration count

  • approval flag

Key reducer behavior

  • messages: merged by ID to preserve history

  • drafts/critiques: appended so all versions are kept

  • iteration/is_approved: overwritten because only the latest value matters

Flow

  1. Drafter creates a draft

  2. Critic evaluates it

  3. If approved, stop

  4. If not, send control back to the drafter

  5. Repeat up to a max number of iterations

Why it’s useful

It’s best for tasks that benefit from repeated refinement, such as:

  • writing

  • editing

  • code review

  • planning

  • collaborative analysis

In short, it’s a writer–editor loop built on a shared workspace.

119. Hands-on ~ Single Department in Isolation

The passage explains how to build and test a single subgraph module in a hierarchical agent system, specifically the research department.

Main points:

  • A shared state schema is defined with:

    • team_state

    • messages

    • final_answer

  • add_messages is used so new messages are appended to the state’s message list.

Research team subgraph

A function called build_research_team creates a StateGraph for the research department, consisting of:

  1. Web Researcher

    • Searches the web using a query passed as a human message.

    • Returns structured output.

  2. Paper Reviewer

    • Reviews gathered technical sources.

    • Uses a system message and returns the full result payload.

  3. Research Lead

    • Combines the outputs from both researchers.

    • Appends messages and produces the final synthesized response.

Graph structure

  • The web researcher and paper reviewer run in parallel from the start node.

  • Their outputs then converge into the research lead.

  • The research lead then connects to the end node.

This demonstrates a fan-out / fan-in pattern:

  • Start → Web Researcher

  • Start → Paper Reviewer

  • Both → Research Lead → End

Purpose: single-department isolation

The key idea is that the research team can be run independently of the rest of the system:

  • No CEO

  • No other departments

This lets you test the department in isolation before integrating it into a larger hierarchical architecture.

Demo

A demo_single_department function:

  • builds the research team,

  • compiles the graph,

  • provides the initial state with messages,

  • and runs it to produce:

    • a research brief

    • a final answer

Conclusion

The example shows that each department can function as a standalone module, making it easier to test, validate, and later compose into a larger multi-department system.

120. Hands-on ~ Hierarchical Routing and Full Tracing

The passage explains how to build a hierarchical, modular multi-agent system by composing independent department subgraphs under a top-level router.

Main points

  • Research department already exists as an independent subgraph, with specialized agents like a web searcher and paper reviewer.

  • The same pattern is used to build:

    • a Content team subgraph with:

      • Content Writer

      • Content Editor

    • an Analysis team subgraph with:

      • Data Analyst

      • Strategy Advisor

Top-level routing

  • A CEO supervisor acts as the top-level router.

  • It uses an LLM with structured output to choose the correct department.

  • A routing schema like DepartmentRoute includes:

    • department (research, content, or analysis)

    • description

    • reasoning

Full graph flow

  • The CEO receives the user query.

  • It routes the request to the appropriate department subgraph.

  • That department processes the request.

  • The result is returned to the end.

Demos

  • One demo shows the full routed system on sample queries.

  • Another demo shows the full internal trace, making each step visible.

Why this matters

  • Each department has a focused responsibility.

  • The design is testable, composable, scalable, and maintainable.

  • New departments can be added later without changing existing ones.

Final takeaway

This architecture is a production-ready hierarchical multi-agent system:

  • independent subgraphs for each department

  • top-level routing via a supervisor

  • isolated responsibilities

  • easy expansion and maintenance