Agent handoffs and delegation

Topic 3 of 4 in Multi-agent systems24 min readAdvancedFree course

Overview

In the previous lesson, you built a supervisor architecture in which a central agent coordinated specialized workers. The supervisor decided which worker should execute a task, received its result, and determined what should happen next.

That architecture is effective when one agent should remain responsible for the entire interaction. However, not every application benefits from centralized coordination.

Consider a customer support system with two specialized agents:

  • A billing agent that handles invoices, subscriptions, and payment questions.
  • A technical agent that handles application errors, connectivity, and troubleshooting.

A customer initially asks about an invoice but subsequently reports that they cannot log in. Rather than repeatedly routing through a supervisor, the billing agent can transfer the conversation directly to the technical agent.

The technical agent becomes responsible for the interaction and can ask follow-up questions, use specialized tools, or transfer responsibility again when appropriate.

This transfer is called an agent handoff.

A related pattern, delegation, allows an agent to assign work to another agent without surrendering overall control.

Understanding the distinction is essential when designing autonomous systems, hierarchical teams, conversational assistants, and collaborative agent workflows.

By the end of this lesson, you will understand how to implement cross-graph handoffs using Command.PARENT, design agent communication contracts, persist conversational ownership, and prevent infinite collaboration loops.

How a handoff works

Transferring control and responsibility

A handoff consists of three logical operations:

  1. Select the destination agent.
  2. Transfer the information required by that agent.
  3. Schedule the destination agent to execute.

The receiving agent does not necessarily need to return control to the original agent. It can complete the interaction itself.

This diagram illustrates a conversational system in which specialists transfer responsibility directly.

This diagram illustrates a conversational system in which specialists transfer responsibility directly.

The important distinction is that a handoff changes which agent owns the next stage of execution.

This ownership can be represented explicitly in shared state through an active_agent field.

Understanding Command.PARENT

You previously learned that a LangGraph node can return a Command containing both a state update and a destination.

For example:

Python
Command(
    goto="technical",
    update={"active_agent": "technical"},
)

By default, the destination belongs to the graph in which the command is returned.

However, production agents are frequently implemented as separate compiled subgraphs. Each subgraph may contain its own model calls, tools, validation steps, and internal routing.

If a node inside the billing subgraph wants to transfer execution to the technical agent registered in the parent graph, it must cross the graph boundary.

This is what Command.PARENT enables.

Python
Command(
    graph=Command.PARENT,
    goto="technical",
    update={"active_agent": "technical"},
)

The command’s fields have distinct responsibilities:

Field Responsibility
graph Identifies the graph in which the destination should execute.
goto Names the destination node.
update Specifies state changes to apply.
resume Supplies a value when resuming an interrupted execution.

Command.PARENT targets the immediate enclosing graph, not an arbitrary ancestor or remote agent service.

LangGraph handles this cross-graph control transfer through its execution runtime. It applies the appropriate state updates and schedules the destination according to the parent graph’s topology.

This is graph orchestration, not a direct Python function call between agents.

A deterministic cross-graph handoff

Before introducing language models, build a small deterministic example. Separating routing mechanics from model behavior makes debugging much easier.

Install the dependencies:

Terminal
pip install -U "langgraph>=1.0,<2" "langchain>=1.0,<2" langchain-openai

The following program creates an intake subgraph that transfers execution to a billing node in its parent graph.

Python
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Command

def latest(old: str, new: str) -> str:
    return new

class State(TypedDict):
    request: str
    active_agent: Annotated[str, latest]
    answer: str

def intake_node(state: State) -> Command:
    return Command(
        graph=Command.PARENT,
        goto="billing",
        update={"active_agent": "billing"},
    )

intake_builder = StateGraph(State)
intake_builder.add_node("classify", intake_node)
intake_builder.add_edge(START, "classify")

intake_graph = intake_builder.compile()

def billing_node(state: State):
    return {
        "answer": f"Billing specialist received: {state['request']}"
    }

builder = StateGraph(State)
builder.add_node(
    "intake",
    intake_graph,
    destinations=("billing",),
)
builder.add_node("billing", billing_node)

builder.add_edge(START, "intake")
builder.add_edge("billing", END)

graph = builder.compile()

result = graph.invoke(
    {
        "request": "Explain my invoice",
        "active_agent": "intake",
        "answer": "",
    }
)

print(result)

Expected output:

Text
{
    'request': 'Explain my invoice',
    'active_agent': 'billing',
    'answer': 'Billing specialist received: Explain my invoice'
}

The intake node executes inside its own subgraph, yet its command targets the billing node outside that subgraph.

The destinations argument provides graph visualization metadata. It does not create an executable edge or enforce an authorization policy.

The custom latest reducer implements replacement semantics. When a parent state key is shared with a subgraph and updated through Command.PARENT, define a suitable reducer for that key in the parent.

For conversation history, MessagesState already supplies the add_messages reducer.

Note: A Command adds dynamic routing rather than automatically overriding existing static edges. Avoid attaching unconditional execution edges to nodes that also choose their destinations through commands.

For additional details about graph boundaries and state updates, consult the LangGraph Graph API documentation.

Building the system

Designing a conversational handoff architecture

We will now build a customer support application with two model-driven agents that can transfer conversations to each other.

Each specialist will have:

  • A role-specific system prompt.
  • A dedicated handoff tool.
  • A local graph for model and tool execution.
  • Access to shared conversational state.
  • A bounded number of transfers per user turn.

The parent graph maintains ownership and handles conversation completion.

We will use StateGraph and ToolNode directly because this gives us explicit control over routing, message propagation, and termination.

Implementing handoff tools

A handoff tool differs from an ordinary information-retrieval tool.

An ordinary tool might return an invoice amount or database record. A handoff tool returns a Command that changes execution ownership.

The model chooses whether to call the tool. Python code decides whether the requested transition is permitted and performs the actual state update.

When a tool triggers a handoff, the receiving agent should receive a valid conversation history.

Consider this message sequence:

Text
HumanMessage: I cannot access my account.

AIMessage:
    tool_call: transfer_to_technical
    id: call_123

ToolMessage:
    tool_call_id: call_123
    content: Transferred to technical support.

The tool response must correspond to the original tool call identifier.

Forwarding only the AIMessage leaves an unanswered tool call. Forwarding only the ToolMessage creates an orphaned tool response.

Both situations can produce provider validation errors or inconsistent model behavior.

A parent-directed command can technically omit tool messages when discarding the entire tool exchange. However, if you preserve the triggering tool call in the shared conversation, preserve its matching response as well.

Complete multi-agent implementation

Configure your OpenAI credentials before running the application.

Terminal
export OPENAI_API_KEY="your-api-key"

This example uses one handoff tool per specialist and disables parallel tool calls to simplify ownership transitions.

Python
from typing import Annotated

from langchain.chat_models import init_chat_model
from langchain.messages import (
    AIMessage,
    HumanMessage,
    SystemMessage,
    ToolMessage,
)
from langchain.tools import tool, ToolRuntime
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode
from langgraph.types import Command

model = init_chat_model("openai:gpt-5.4-mini")

MAX_HANDOFFS = 3

def latest(old, new):
    return new

class SupportState(MessagesState):
    active_agent: Annotated[str, latest]
    remaining_handoffs: Annotated[int, latest]
    turn_complete: bool

def transfer(
    destination: str,
    reason: str,
    runtime: ToolRuntime,
) -> Command:
    state = runtime.state
    remaining = state["remaining_handoffs"]

    if remaining <= 0:
        return Command(
            goto="budget_reply",
            update={
                "messages": [
                    ToolMessage(
                        content="Transfer budget exhausted.",
                        tool_call_id=runtime.tool_call_id,
                    )
                ]
            },
        )

    last_ai = state["messages"][-1]

    acknowledgement = ToolMessage(
        content=f"Transferred to {destination}. Reason: {reason[:500]}",
        tool_call_id=runtime.tool_call_id,
    )

    return Command(
        graph=Command.PARENT,
        goto=destination,
        update={
            "active_agent": destination,
            "remaining_handoffs": remaining - 1,
            "messages": [last_ai, acknowledgement],
        },
    )

@tool
def transfer_to_technical(
    reason: str,
    runtime: ToolRuntime,
) -> Command:
    """Transfer login, connectivity, or application issues to technical support."""
    return transfer("technical", reason, runtime)

@tool
def transfer_to_billing(
    reason: str,
    runtime: ToolRuntime,
) -> Command:
    """Transfer invoice, payment, or subscription issues to billing support."""
    return transfer("billing", reason, runtime)

def build_specialist(role_prompt: str, handoff_tool):
    specialist_model = model.bind_tools(
        [handoff_tool],
        parallel_tool_calls=False,
    )

    def model_step(state: SupportState) -> Command:
        response = specialist_model.invoke(
            [
                SystemMessage(content=role_prompt),
                *state["messages"],
            ]
        )

        if not response.tool_calls:
            return Command(
                graph=Command.PARENT,
                goto="finish",
                update={"messages": [response]},
            )

        # Reject unexpected multiple ownership transitions.
        if len(response.tool_calls) != 1:
            return Command(
                graph=Command.PARENT,
                goto="finish",
                update={
                    "messages": [
                        AIMessage(
                            content="Please clarify your primary support issue."
                        )
                    ]
                },
            )

        return Command(
            goto="tools",
            update={"messages": [response]},
        )

    def budget_reply(state: SupportState) -> Command:
        response = AIMessage(
            content=(
                "I could not identify the correct specialist. "
                "Please clarify your main issue or contact human support."
            )
        )

        return Command(
            graph=Command.PARENT,
            goto="finish",
            update={
                "messages": [
                    *state["messages"][-2:],
                    response,
                ]
            },
        )

    child = StateGraph(SupportState)

    child.add_node(
        "model",
        model_step,
        destinations=("tools",),
    )
    child.add_node(
        "tools",
        ToolNode([handoff_tool]),
        destinations=("budget_reply",),
    )
    child.add_node("budget_reply", budget_reply)

    child.add_edge(START, "model")

    return child.compile()

billing = build_specialist(
    "You are the billing specialist. Help with subscriptions, "
    "payments, and invoices. Transfer technical issues using your "
    "handoff tool. Otherwise answer directly. Never invent account data.",
    transfer_to_technical,
)

technical = build_specialist(
    "You are the technical specialist. Help with login problems "
    "and application errors. Transfer billing questions using your "
    "handoff tool. Otherwise answer directly. Never claim to have "
    "performed actions you cannot perform.",
    transfer_to_billing,
)

def prepare(state: SupportState) -> Command:
    active = state.get("active_agent")

    if active not in {"billing", "technical"}:
        active = "billing"

    return Command(
        goto=active,
        update={
            "active_agent": active,
            "remaining_handoffs": MAX_HANDOFFS,
            "turn_complete": False,
        },
    )

def finish(state: SupportState):
    last = state["messages"][-1]

    if not isinstance(last, AIMessage) or last.tool_calls:
        raise ValueError("Invalid terminal conversation state")

    return {"turn_complete": True}

builder = StateGraph(SupportState)

builder.add_node(
    "prepare",
    prepare,
    destinations=("billing", "technical"),
)
builder.add_node(
    "billing",
    billing,
    destinations=("technical", "finish"),
)
builder.add_node(
    "technical",
    technical,
    destinations=("billing", "finish"),
)
builder.add_node("finish", finish)

builder.add_edge(START, "prepare")
builder.add_edge("finish", END)

graph = builder.compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {"thread_id": "support-001"},
    "recursion_limit": 40,
}

result = graph.invoke(
    {
        "messages": [
            HumanMessage(
                content="I cannot log in. The password reset page is broken."
            )
        ]
    },
    config=config,
)

print("Active agent:", result["active_agent"])
print("Complete:", result["turn_complete"])
print("Answer:", result["messages"][-1].content)

follow_up = graph.invoke(
    {
        "messages": [
            HumanMessage(
                content="The reset page displays a server error."
            )
        ]
    },
    config=config,
)

print("Active agent:", follow_up["active_agent"])
print("Answer:", follow_up["messages"][-1].content)

An illustrative execution produces:

Text
Active agent: technical
Complete: True
Answer: Try opening the password reset page in a private browser
window. If the server error persists, contact technical support.

Active agent: technical
Answer: A persistent server error may indicate a service-side issue...

The precise model responses and routing decisions can vary.

The examples use current LangGraph and LangChain 1.x interfaces. Live execution against the configured model provider has not been verified here; it requires the installed dependencies, valid credentials, and access to the specified model.

Understanding the execution sequence

The implementation contains several important architectural decisions.

First, prepare initializes the transfer budget and selects the persisted active agent. On a new thread, billing becomes the default entry point.

Second, the selected specialist invokes its model with a dedicated system prompt and the shared conversation.

If the model generates a normal response, the specialist transfers execution to the parent’s finish node.

If the model requests a handoff, ToolNode executes the requested tool. The tool constructs an acknowledgement, updates ownership, decrements the transfer budget, and targets another parent node.

The receiving specialist starts with the updated conversation and its own system prompt.

If the budget is exhausted, execution remains inside the current subgraph long enough to generate a controlled fallback response.

Finally, the parent validates the terminal message and reaches END.

Maintaining ownership across turns

Reaching END completes the current graph invocation. It does not automatically erase the conversation.

Because the parent graph uses a checkpointer, messages and active_agent remain available for subsequent invocations using the same thread identifier.

The second invocation begins at START, executes prepare, and continues with the technical agent.

Notice that the transfer budget is reset for each new user turn, while conversational ownership is preserved.

In a deployed system, replace InMemorySaver with a durable checkpointer such as PostgresSaver. Generate thread identifiers on the application side and enforce authorization before allowing users to access existing threads.

The thread identifier is a persistence mechanism, not an authentication credential.

Delegation vs handoff

Choosing the appropriate interaction model

Delegation and handoffs solve different coordination problems.

Imagine a research assistant that needs a specialist to extract facts from a document. The research assistant should receive the extracted facts and continue its original task.

That is delegation.

Now imagine a support agent that encounters a specialized billing dispute and transfers the entire conversation to a billing specialist.

That is a handoff.

Dimension Delegation Handoff
Overall ownership Calling agent Receiving agent
Execution pattern Call and return Transfer and continue
User-facing response Usually calling agent Usually receiving agent
Context Focused task input Relevant conversation state
Parallel execution Often useful Usually undesirable
Common architecture Supervisor or hierarchy Decentralized agent network
Main risk Incorrect worker output Uncontrolled transfers
Typical implementation Agent exposed as a tool Tool returning Command

A delegated agent is effectively a callable specialist. Its completion returns a result rather than transferring conversational authority.

The following diagram illustrates delegation within a hierarchical research team.

Delegation vs handoff diagram: START to Lead Agent; Lead Agent to Research Agent (Delegate); Research Agent to Lead Agent (Findings); Lead Agent to Review Agent (Delegate); Review Agent to Lead Agent (Feedback); Lead Agent to Final Response; Final Response to END.

The lead agent remains accountable for integrating the specialists’ work.

Implementing delegation with create_agent

LangChain’s create_agent provides a convenient way to create specialists that can be invoked from ordinary tools.

The following example delegates database architecture analysis to a specialist while retaining control in the lead agent.

Python
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langchain.tools import tool

model = init_chat_model("openai:gpt-5.4-mini")

database_agent = create_agent(
    model=model,
    tools=[],
    system_prompt=(
        "You are a database architecture specialist. "
        "Return concise, technically accurate recommendations."
    ),
)

@tool
def consult_database_specialist(question: str) -> str:
    """Delegate a database design question to a specialist."""
    result = database_agent.invoke(
        {"messages": [HumanMessage(content=question)]},
        config={"recursion_limit": 10},
    )

    return result["messages"][-1].text

lead_agent = create_agent(
    model=model,
    tools=[consult_database_specialist],
    system_prompt=(
        "You are a software architecture lead. "
        "Consult the database specialist for database questions. "
        "Integrate its findings into your own final answer."
    ),
)

result = lead_agent.invoke(
    {
        "messages": [
            HumanMessage(
                content=(
                    "Design a persistence strategy for a "
                    "multi-agent customer support application."
                )
            )
        ]
    },
    config={"recursion_limit": 20},
)

print(result["messages"][-1].text)

The expected behavior is that the lead agent consults the database specialist and incorporates its recommendations into an overall architecture response.

The specialist receives only the delegated question, not the lead agent’s complete conversation.

Unlike a handoff, the tool returns text. It does not return a parent-directed command.

This architecture is particularly useful for research, document analysis, code review, and specialized calculations.

Combining both patterns

Production systems frequently combine delegation and handoffs.

A technical support agent might delegate log analysis to a diagnostic specialist. After receiving the findings, it may discover that the underlying issue is an expired subscription and hand off the conversation to billing.

The diagnostic specialist does not need conversational ownership. The billing specialist does.

Hierarchical teams can apply the same distinction at multiple levels, provided their graph boundaries and ownership rules remain explicit.

For more implementation patterns, see the official handoffs documentation and subagents documentation.

Managing termination

Why multi-agent systems can loop indefinitely

A decentralized agent network can exhibit behavior that does not occur in straightforward sequential workflows.

Consider this interaction:

Text
Billing: This appears to be a technical issue.
Technical: This appears to be a billing issue.
Billing: This appears to be a technical issue.
Technical: This appears to be a billing issue.
...

Both agents make locally plausible decisions, yet the overall system fails to make progress.

This is an orchestration failure.

Better prompting can reduce these loops, but prompts alone cannot guarantee termination.

Separate business termination from runtime termination

A robust system defines multiple reasons to stop.

Condition Appropriate outcome
Task completed Return a final answer.
Clarification required Ask the user and end the current turn.
Transfer budget exhausted Return a controlled fallback.
Human approval required Pause using an interrupt.
Repeated failures Escalate or return a failure status.
Execution limit exceeded Handle the runtime exception.

An interrupt differs from END. An interrupt suspends execution for later resumption, whereas END completes the current run once no other work remains scheduled.

Similarly, an ordinary clarification question can end a run successfully without resolving the underlying business task.

For production applications, consider separate state fields such as turn_complete, task_resolved, and status.

Enforcing recursion limits

LangGraph’s recursion limit constrains graph execution super-steps.

In current LangGraph 1.x releases, the default can be as high as 10,007. That is far too permissive for many conversational workflows.

Always configure a deliberate limit appropriate to the workload.

The following standalone example demonstrates the runtime protection against an intentionally non-terminating agent network.

Python
from typing import TypedDict

from langgraph.errors import GraphRecursionError
from langgraph.graph import StateGraph, START
from langgraph.types import Command

class State(TypedDict):
    transfers: int

def agent_a(state: State) -> Command:
    return Command(
        goto="agent_b",
        update={"transfers": state["transfers"] + 1},
    )

def agent_b(state: State) -> Command:
    return Command(
        goto="agent_a",
        update={"transfers": state["transfers"] + 1},
    )

builder = StateGraph(State)
builder.add_node("agent_a", agent_a, destinations=("agent_b",))
builder.add_node("agent_b", agent_b, destinations=("agent_a",))
builder.add_edge(START, "agent_a")

graph = builder.compile()

try:
    graph.invoke(
        {"transfers": 0},
        config={"recursion_limit": 6},
    )
except GraphRecursionError:
    print("Execution stopped: recursion limit reached.")

Expected output:

Text
Execution stopped: recursion limit reached.

The recursion limit is a runtime safeguard, not a business-level completion strategy. It counts super-steps rather than handoffs, model calls, tokens, or monetary expenditure.

Tip: Use a small business-level handoff budget together with a larger recursion limit. The former enables graceful termination, while the latter protects against unexpected graph behavior.

Detecting lack of progress

Transfer counters prevent unlimited cycling but cannot determine whether collaboration is productive.

More sophisticated systems maintain progress indicators such as:

  • Requirements completed.
  • Artifacts created or updated.
  • Unresolved issues.
  • Previously visited agents.
  • Review failures.
  • Repeated error signatures.

A writing agent returning a substantially improved draft to a reviewer represents useful progress. Two specialists exchanging the same unresolved request repeatedly do not.

Combine bounded retries with application-specific progress checks. Also enforce independent request deadlines, model-call budgets, and token expenditure limits where appropriate.

Context engineering

Context as an agent communication contract

Context engineering determines what information an agent receives, retains, and exposes to other agents.

In multi-agent systems, this is an architectural concern rather than merely a prompting technique.

An agent receiving a handoff needs sufficient information to continue without unnecessarily repeating work. However, transferring every internal message can introduce irrelevant instructions, conflicting assumptions, sensitive information, and excessive token consumption.

Treat every handoff as a communication contract between components.

A useful handoff payload may contain:

  • The original user objective.
  • Verified facts and their provenance.
  • Work already completed.
  • Outstanding questions.
  • Relevant constraints.
  • The reason for transferring responsibility.
  • References to generated artifacts.

Where possible, represent operationally important facts in typed state fields instead of relying on natural-language conversation history.

Shared state vs isolated state

LangGraph supports subgraphs that share state channels with their parent and subgraphs that maintain separate schemas.

Strategy Advantages Limitations
Fully shared history Straightforward continuity Context growth and interference
Isolated agent state Strong separation of responsibilities Explicit context mapping required
Selective shared state Controlled communication and continuity More schema design effort
External artifact storage Suitable for large documents and results Requires retrieval and access control

Selective shared state is often a practical choice for production systems.

For example, a research agent may maintain private retrieval messages while exposing verified findings and document identifiers to a writer.

The writer does not need every intermediate search result.

Designing structured context

The following example demonstrates a compact, typed handoff payload for a document production workflow.

Python
from typing import TypedDict
import json

class HandoffContext(TypedDict):
    objective: str
    verified_facts: list[str]
    unresolved_questions: list[str]
    artifact_ids: list[str]
    constraints: list[str]

context: HandoffContext = {
    "objective": "Write a guide to multi-agent systems",
    "verified_facts": [
        "Command.PARENT targets an enclosing graph.",
        "Delegated workers return results to their caller.",
    ],
    "unresolved_questions": [
        "Which deployment environment will be used?"
    ],
    "artifact_ids": ["research-report-001"],
    "constraints": [
        "Use Python examples.",
        "Do not invent deployment details.",
    ],
}

print(json.dumps(context, indent=2))

The resulting JSON provides a compact communication envelope that can be validated, persisted, inspected, or incorporated into a receiving agent’s prompt.

In larger applications, persist substantial research artifacts externally and transfer authorized identifiers rather than embedding entire documents in every model request.

Preserving valid message history

The add_messages reducer merges messages using their identifiers. Existing messages with matching identifiers can be replaced, while new messages are appended.

Consequently, returning the entire inherited message list is generally unnecessary. Return only the messages that should be added or modified.

When reducing conversation history, preserve complete tool-call exchanges.

If an assistant message contains multiple tool calls, every forwarded call needs its corresponding tool response. Do not arbitrarily retain one response while leaving other calls unanswered.

Also avoid propagating one specialist’s system prompt into another specialist’s shared conversation. Each agent should construct its own model input using its own instructions.

Security and production considerations

Handoffs change execution ownership, but they must not automatically grant new permissions.

A model-generated transfer reason is untrusted application data. It should not override system instructions, authorize refunds, grant database access, or determine tenant boundaries.

Define permitted destinations in application code, validate structured payloads, and independently authorize sensitive operations.

Keep authenticated identity and request-scoped dependencies in runtime context through context_schema and Runtime[Context]. Do not treat model-generated state or the checkpoint configuration as trusted user identity.

For observability, record the source agent, destination agent, transfer reason, remaining budget, execution outcome, and relevant trace identifiers. Avoid logging secrets or unnecessary personal information.

Test direct responses, successful transfers, malformed tool exchanges, denied transfers, repeated agent visits, checkpoint recovery, and budget exhaustion independently.

Preparing for the next lesson

The next lesson, Project: a research, writing and review team, will bring these coordination patterns together into a collaborative agent application.

The research agent will produce structured findings, the writing agent will transform those findings into a draft, and the review agent will evaluate the draft against explicit requirements.

A review failure can transfer execution back to the writer, while a successful review can terminate the workflow. Specialized subtasks can also be delegated without changing ownership.

The central engineering challenge will be ensuring that each agent contributes useful work, communicates through well-defined state contracts, and operates within a bounded execution process that produces a predictable final result.

Exercise

Build a bounded agent handoff workflow

Build a writing and review workflow in which a writer subgraph transfers control to a reviewer using Command.PARENT. The reviewer must approve a sufficiently complete draft or return control to the writer for revision. Allow at most one revision and ensure the workflow terminates whether the draft is approved or rejected. Verify the final approval status and revision count using assertions.

Python
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Command


def latest(old: str, new: str) -> str:
    return new


class State(TypedDict):
    topic: str
    draft: Annotated[str, latest]
    revisions: int
    approved: bool


def write_draft(state: State) -> Command:
    # TODO: Generate a draft.
    # Include a source reference when revising.
    # Transfer control to the parent review node.
    raise NotImplementedError


def review_draft(state: State) -> Command:
    # TODO: Approve drafts containing a source reference.
    # Otherwise, request at most one revision.
    # Terminate if the revision budget is exhausted.
    raise NotImplementedError


# TODO: Build and compile the writer subgraph.

# TODO: Build the parent graph with writer and reviewer nodes.

initial_state = {
    "topic": "Agentic AI",
    "draft": "",
    "revisions": 0,
    "approved": False,
}

# TODO: Invoke the graph with a recursion limit.
# TODO: Assert approval and exactly one revision.

Summary

  • A handoff transfers conversational or workflow ownership from one agent to another.
  • Delegation assigns a task to a specialist while the calling agent retains responsibility for the overall interaction.
  • Command.PARENT allows a nested agent graph to transfer execution to a node in its immediate parent graph.
  • Handoff tools must preserve valid message history by pairing forwarded tool calls with matching tool responses.
  • Persistent active-agent state allows conversations to continue with the appropriate specialist across user turns.
  • Explicit completion conditions and bounded handoff budgets prevent uncontrolled agent-to-agent loops.
  • Context engineering improves reliability by transferring relevant facts and artifacts rather than unnecessary internal messages.