Capstone: an enterprise multi-agent AI assistant
Overview
Throughout this course, you have progressed from constructing simple state graphs to implementing agents, tool execution, persistent memory, retrieval workflows, human-in-the-loop interactions, and production monitoring.
The capstone brings these capabilities together into a single application: an Enterprise Multi-Agent AI Assistant.
Unlike a conventional chatbot that generates responses from conversation history, this assistant must interact with organizational knowledge, structured databases, enterprise applications, and human decision-makers. It must understand requests, determine which capabilities are needed, delegate work, collect evidence, execute authorized actions, and maintain continuity across interruptions.
Imagine an employee submitting the following request:
Find our travel reimbursement policy, calculate my approved expenses for this month, and create a finance review ticket containing the results.
Completing this request requires several distinct capabilities:
- Retrieving current company policies.
- Querying authorized financial records.
- Combining information from multiple sources.
- Preparing an external action.
- Obtaining human approval.
- Executing the approved operation.
- Returning a grounded, auditable response.
A single language model without tools cannot reliably perform these operations. Even a tool-enabled agent may become difficult to maintain when its responsibilities, permissions, and tool inventory grow.
The capstone addresses this complexity through specialized agents coordinated by a supervisor and governed by an explicit LangGraph workflow.
Project scope
You will build an internal enterprise assistant for a fictional organization. The reference implementation will use employee policies, expense records, and support tickets as its primary business domains.
The final application should support conversational requests, multi-step execution, secure enterprise integrations, persistent conversations, real-time progress updates, and human approval.
This lesson establishes the engineering blueprint. The following lessons implement the supervisor, specialist agents, and production capabilities.
The previous lesson on graph versioning, performance, cost, and monitoring remains directly relevant: those considerations now become project requirements rather than optional improvements.
Requirements
Requirements describe what the application must accomplish and the conditions under which it must operate successfully.
Without explicit requirements, a multi-agent system can appear impressive during demonstrations while remaining unreliable in realistic business situations.
Functional requirements
The assistant must provide the following capabilities.
| Capability | Expected behavior |
|---|---|
| Request understanding | Identify user intent and required capabilities |
| Multi-agent orchestration | Delegate tasks to appropriate specialist agents |
| Agentic RAG | Retrieve and assess relevant enterprise documents |
| SQL analytics | Answer authorized questions using structured records |
| Enterprise API tools | Read records and perform approved operations |
| MCP integration | Discover and invoke authorized external tools |
| Conversation memory | Maintain continuity across interactions |
| Human approval | Suspend sensitive operations until approved |
| Streaming | Deliver meaningful progress and response updates |
| Recovery | Handle recoverable execution failures |
Agentic retrieval-augmented generation, or agentic RAG, differs from fixed retrieval pipelines because the agent can determine whether retrieval is necessary, refine its search, assess evidence, and request additional information.
However, every such loop must have a defined termination condition. The assistant must acknowledge insufficient evidence rather than repeatedly searching or inventing answers.
Non-functional requirements
Non-functional requirements specify how well the system must operate.
For this project, use the following illustrative engineering targets. These are proposed capstone targets, not universal enterprise service-level agreements.
| Quality attribute | Proposed target |
|---|---|
| Routing accuracy | At least 90% on a labeled evaluation dataset |
| Read authorization | No unauthorized disclosures in security tests |
| Write authorization | No unapproved external mutations |
| Grounded answers | At least 90% on a defined evidence-based evaluation |
| Availability | 99.9% monthly production service objective |
| Read-only latency | P95 below 15 seconds on the reference workload |
| Recovery | Resume supported workflows without duplicate writes |
| Observability | Trace every orchestration run and external tool operation |
P95 latency means that 95% of measured requests complete within the specified duration. Measure approval waiting time separately from active execution latency.
Availability requires extended operational measurement; a successful local demonstration does not establish compliance with a monthly availability objective.
Security and governance requirements
The assistant will operate across multiple enterprise trust boundaries. Access to a tool does not imply authorization to use it for every employee or organization.
The application must enforce authenticated identity, tenant isolation, least-privilege tool access, read-only database credentials where appropriate, validated external actions, and auditable approval decisions.
Retrieved documents, tool responses, and MCP content must be treated as untrusted data. Instructions embedded in retrieved content must never override application authorization rules.
For example, a document stating that all financial transactions should be automatically approved has no authority to modify the application’s approval policy.
Security controls belong in deterministic application logic, database permissions, and service-level authorization, not exclusively in model prompts.
Acceptance scenarios
Convert requirements into observable scenarios before writing implementation code.
| User request | Expected behavior |
|---|---|
| What is the travel policy? | Retrieve and cite an authorized policy |
| Calculate my monthly expenses | Query permitted financial records |
| Compare expenses against policy | Coordinate knowledge and analytics agents |
| Create a finance ticket | Prepare an action and request approval |
| Show another employee’s salary | Deny access unless explicitly authorized |
| Continue my pending request | Restore the appropriate workflow |
| Create a ticket during an API outage | Recover safely or report an unresolved failure |
These scenarios become the foundation of your automated acceptance tests.
Proposed architecture
Choosing an orchestration pattern
Multi-agent applications can be organized in several ways.
| Pattern | Characteristics | Trade-off |
|---|---|---|
| Single agent | One model with many tools | Simple but difficult to scale across domains |
| Router | Classifies and delegates requests | Efficient but limited iterative coordination |
| Supervisor | Coordinates specialists and synthesizes results | Greater control with additional orchestration overhead |
| Handoffs | Agents transfer control between themselves | Flexible but harder to govern centrally |
| Parallel workers | Multiple tasks execute concurrently | Lower latency for independent work |
For this capstone, use a centralized supervisor with specialized agents and deterministic control boundaries.
The supervisor handles planning, delegation, and result aggregation. Each specialist receives only the information and capabilities needed for its task.
Centralized supervision makes it easier to trace decisions, enforce execution budgets, and prevent uncontrolled communication between agents.
High-level system architecture
The following diagram shows how the client, orchestration layer, specialist agents, enterprise resources, and approval boundary interact.
The gateway authenticates users and supplies trusted runtime context. The supervisor identifies required work and delegates to specialists.
The knowledge agent accesses approved document collections. The analytics agent accesses permitted structured records. The operations agent prepares proposed actions, while a separate approval boundary governs sensitive execution.
Persistent state supports workflow continuity, and the response stream communicates progress and final results.
Production observability, authorization, and resource limits apply across all components.
How LangGraph executes the architecture
The outer application is a StateGraph. Its state contains the information needed to coordinate execution.
Each node reads state and returns updates. Edges determine which nodes execute next. Conditional edges or Command objects support dynamic routing.
Internally, LangGraph organizes execution into supersteps. Nodes scheduled within the same superstep can execute concurrently, and their state updates are combined according to the relevant reducers.
This matters when several agents return results simultaneously. Concurrent writes to the same state field require a suitable reducer or separate output channels.
For the initial implementation, sequential delegation is easier to validate. Parallel execution can be introduced later for independent tasks using graph branching or Send.
The official Graph API documentation provides additional details about state, reducers, and execution semantics.
Execution lifecycle
The following diagram represents the lifecycle of a typical enterprise request.
Notice that retrieving information and authorizing external mutations are separate responsibilities.
The supervisor may propose an operation, but it cannot grant itself permission to execute it.
Components
1. Supervisor and specialist orchestration
Begin with a deterministic prototype before introducing model-driven decisions.
This approach isolates graph construction, state transitions, context handling, and delegation from the probabilistic behavior of language models.
Install the core dependencies in a Python virtual environment.
pip install -U "langgraph>=1,<2" "langchain>=1,<2" langchain-openaiThe following complete example demonstrates sequential delegation to multiple simulated specialists. It also separates trusted runtime context from workflow state.
from dataclasses import dataclass
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
@dataclass
class Context:
user_id: str
tenant_id: str
class State(TypedDict, total=False):
request: str
pending_tasks: list[str]
findings: dict[str, str]
response: str
def supervisor(state: State) -> dict:
request = state["request"].lower()
tasks = []
if "policy" in request:
tasks.append("knowledge")
if "expense" in request:
tasks.append("analytics")
return {
"pending_tasks": tasks,
"findings": {},
}
def dispatch(state: State) -> str:
tasks = state["pending_tasks"]
return tasks[0] if tasks else "respond"
def knowledge(state: State) -> dict:
return {
"pending_tasks": state["pending_tasks"][1:],
"findings": {
**state["findings"],
"policy": "Limit: USD 500 per travel expense.",
},
}
def analytics(
state: State,
runtime: Runtime[Context],
) -> dict:
user_id = runtime.context.user_id
return {
"pending_tasks": state["pending_tasks"][1:],
"findings": {
**state["findings"],
"analytics": f"{user_id}: USD 1,250 approved this month.",
},
}
def respond(state: State) -> dict:
findings = state["findings"]
return {
"response": "\n".join(findings.values())
if findings
else "No supported capability matched the request."
}
builder = StateGraph(State, context_schema=Context)
builder.add_node("supervisor", supervisor)
builder.add_node("knowledge", knowledge)
builder.add_node("analytics", analytics)
builder.add_node("respond", respond)
destinations = {
"knowledge": "knowledge",
"analytics": "analytics",
"respond": "respond",
}
builder.add_edge(START, "supervisor")
for source in ("supervisor", "knowledge", "analytics"):
builder.add_conditional_edges(source, dispatch, destinations)
builder.add_edge("respond", END)
graph = builder.compile()
result = graph.invoke(
{"request": "Show the travel policy and my expenses."},
config={"recursion_limit": 15},
context=Context(
user_id="employee-101",
tenant_id="company-a",
),
)
print(result["response"])Expected output:
Limit: USD 500 per travel expense.
employee-101: USD 1,250 approved this month.The supervisor creates a task queue, and the dispatch function selects the next specialist. Each specialist consumes one task and records its findings.
The queue shrinks after every execution, establishing a termination condition.
These specialists are deterministic workflow nodes rather than autonomous agents. The next lesson replaces simulated decisions and results with model-driven planning and specialized agent graphs.
Note: The keyword router, hardcoded business data, and simulated identity handling are deliberate prototype simplifications. They do not implement production authentication, authorization, or natural-language understanding.
2. Knowledge agent and agentic RAG
The knowledge agent answers questions using enterprise documents such as employee handbooks, operational procedures, product documentation, and compliance policies.
Its responsibilities include query formulation, retrieval, relevance assessment, bounded search refinement, and evidence-based answer generation.
Every retrieved document should carry metadata identifying its source, tenant, access restrictions, version, and effective date.
Consider a user asking about international travel reimbursement. Retrieving an outdated domestic travel policy could produce an apparently plausible but incorrect answer.
The knowledge agent must therefore distinguish semantic relevance from applicability and document freshness.
The following example demonstrates a minimal tool-enabled knowledge agent using the LangChain 1.x create_agent API.
Configure a valid OPENAI_API_KEY before running it, and ensure your account has access to the course model.
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool
@tool
def search_policy(query: str) -> str:
"""Retrieve relevant policies from a demonstration collection."""
if "travel" in query.lower():
return (
"Source: TRAVEL-2026-v1. "
"Travel reimbursement is limited to USD 500 "
"per expense."
)
return "No matching policy found."
model = init_chat_model("openai:gpt-5.4-mini")
knowledge_agent = create_agent(
model=model,
tools=[search_policy],
system_prompt=(
"You are an enterprise knowledge specialist. "
"Search the policy collection before answering. "
"Include source identifiers and acknowledge "
"missing evidence."
),
)
result = knowledge_agent.invoke(
{
"messages": [
{
"role": "user",
"content": "What is the travel reimbursement limit?",
}
]
},
config={"recursion_limit": 12},
)
print(result["messages"][-1].content)An expected response would identify the USD 500 limit and reference TRAVEL-2026-v1. Exact wording and tool-selection behavior may vary between model executions.
This example establishes the specialist’s agent interface. The production version replaces the demonstration collection with permission-aware retrieval over indexed documents.
3. Analytics agent and SQL tools
The analytics agent translates business questions into controlled data-access operations.
Avoid allowing unrestricted model-generated SQL against production databases. Begin with narrowly defined business tools, parameterized queries, and read-only credentials.
The following standalone example demonstrates tenant-scoped and employee-scoped analytics using SQLite.
import sqlite3
from langchain.tools import tool
connection = sqlite3.connect(":memory:")
connection.execute("""
CREATE TABLE expenses (
tenant_id TEXT,
employee_id TEXT,
amount_cents INTEGER,
status TEXT
)
""")
connection.executemany(
"INSERT INTO expenses VALUES (?, ?, ?, ?)",
[
("company-a", "employee-101", 50000, "approved"),
("company-a", "employee-101", 75000, "approved"),
("company-a", "employee-101", 20000, "pending"),
("company-b", "employee-101", 900000, "approved"),
],
)
tenant_id = "company-a"
employee_id = "employee-101"
@tool
def approved_expenses() -> int:
"""Return the current employee's approved expenses in cents."""
row = connection.execute(
"""
SELECT COALESCE(SUM(amount_cents), 0)
FROM expenses
WHERE tenant_id = ?
AND employee_id = ?
AND status = 'approved'
""",
(tenant_id, employee_id),
).fetchone()
return row[0]
total = approved_expenses.invoke({})
assert total == 125000
print(f"Approved expenses: USD {total / 100:,.2f}")
connection.close()Expected output:
Approved expenses: USD 1,250.00The model cannot choose a different tenant or employee because identity is not exposed as a tool argument.
In the full application, use ToolRuntime or Runtime[Context] to obtain trusted request-specific identity. Replace the demonstration globals with authenticated context and use appropriate database-level access controls.
Also define date ranges, currencies, and business aggregation rules explicitly. The example aggregates all seeded approved expenses rather than implementing a monthly reporting period.
4. Enterprise operations and MCP integration
The operations agent handles business processes such as creating support tickets, initiating expense reviews, and updating authorized records.
Enterprise tools may be implemented as Python functions wrapping REST APIs or exposed through the Model Context Protocol (MCP).
MCP provides a standardized interface for discovering and invoking external capabilities. It does not automatically establish that every discovered tool is safe or permitted.
The integration layer must restrict available servers, validate tool schemas, manage credentials securely, enforce tenant permissions, and classify tools according to their side effects.
Read operations may execute automatically when authorized. Sensitive write operations must produce structured action proposals containing the operation, target resource, arguments, expected effects, and approval requirements.
Only the execution component should possess the credentials required to perform protected writes.
5. Human approval and guardrails
LangGraph supports resumable human approval through interrupt() and checkpointing.
The following example demonstrates the smallest approval workflow. No external operation is performed; the execution node returns a simulated result.
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt
class State(TypedDict, total=False):
action: str
status: str
def approval(
state: State,
) -> Command[Literal["execute", "__end__"]]:
decision = interrupt({
"action": state["action"],
"question": "Approve this operation?",
})
if isinstance(decision, dict) and decision.get("approved") is True:
return Command(
update={"status": "approved"},
goto="execute",
)
return Command(
update={"status": "rejected"},
goto=END,
)
def execute(state: State) -> dict:
return {"status": "executed"}
builder = StateGraph(State)
builder.add_node("approval", approval)
builder.add_node("execute", execute)
builder.add_edge(START, "approval")
builder.add_edge("execute", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "review-001"}}
pending = graph.invoke(
{"action": "Create finance review ticket"},
config,
)
print("Approval pending:", bool(pending["__interrupt__"]))
completed = graph.invoke(
Command(resume={"approved": True}),
config,
)
print("Final status:", completed["status"])Expected output:
Approval pending: True
Final status: executedOn resume, the interrupted node starts again from its beginning. Consequently, external mutations must not occur before approval inside that node.
In production, approvals must be authenticated, tied to an immutable action proposal, checked for expiration, and revalidated before execution.
See the LangGraph interrupts documentation for additional execution constraints.
6. Persistent state and memory
The assistant requires several distinct persistence mechanisms.
| Storage component | Responsibility |
|---|---|
| Graph checkpointer | Workflow state, conversation continuity, pending execution |
| Long-term store | Permitted preferences and reusable information across threads |
| Vector index | Searchable enterprise documents |
| Business database | Authoritative organizational records |
| Audit storage | Security decisions and operation history |
Start local development with InMemorySaver and InMemoryStore. Introduce durable storage during production integration.
A production checkpointer, such as PostgresSaver for a self-managed graph, must survive application restarts. An independently hosted Agent Server can manage persistence infrastructure for the deployed application.
A thread ID identifies workflow continuity; it is not proof that the requesting user owns the thread.
7. Streaming, resilience, and deployment
The user interface must communicate meaningful execution progress rather than remain silent throughout a long-running request.
LangGraph supports streaming state updates, model message chunks, and custom progress events through its v2 streaming interface. Publish sanitized application events such as policy retrieval completed or approval required rather than exposing unrestricted internal state.
Resilience requires bounded retries, appropriate timeouts, explicit recursion limits, and recoverable failure paths.
External write operations require particular care. A remote service may complete an operation even when the assistant receives a timeout. Use stable idempotency keys and reconciliation before attempting another write.
Observability should capture agent selection, tool calls, latency, token consumption, failures, and approval outcomes using LangSmith traces and application metrics.
Package the completed graph using langgraph.json and deploy it through LangGraph CLI and LangSmith Agent Server. Keep environment secrets outside the repository and verify deployment through authenticated client requests.
Milestones
Implement the capstone incrementally. Each milestone should produce an independently testable capability.
| Milestone | Deliverable | Completion condition |
|---|---|---|
| M1: Project foundation | State schema and deterministic graph | Basic routing tests pass |
| M2: Agent orchestration | Supervisor and specialist agents | Multi-domain delegation works |
| M3: Enterprise knowledge | Agentic RAG pipeline | Answers include valid evidence |
| M4: Business integrations | SQL, REST, and MCP tools | Authorized operations succeed |
| M5: Memory and approval | Durable state and approval workflow | Interrupted execution resumes safely |
| M6: Production hardening | Streaming, guardrails, and recovery | Failure and security tests pass |
| M7: Evaluation | Evaluation dataset and traces | Measurable quality targets are assessed |
| M8: Deployment | Running application and documentation | End-to-end acceptance tests pass |
Recommended project structure
Organize the repository by architectural responsibility rather than placing every capability inside a single Python file.
enterprise-assistant/
├── app/
│ ├── graph.py
│ ├── state.py
│ ├── context.py
│ ├── agents/
│ │ ├── supervisor.py
│ │ ├── knowledge.py
│ │ ├── analytics.py
│ │ └── operations.py
│ ├── tools/
│ │ ├── retrieval.py
│ │ ├── sql.py
│ │ ├── enterprise_api.py
│ │ └── mcp.py
│ └── guardrails/
│ ├── authorization.py
│ └── approval.py
├── tests/
├── evaluations/
├── data/
├── langgraph.json
├── pyproject.toml
├── .env.example
└── README.mdThis structure allows specialists, tools, and security policies to be tested independently.
Commit dependency lockfiles, sanitized test fixtures, architecture decisions, and deployment instructions. Never commit real credentials or confidential enterprise data.
The next lesson concentrates on M1 and M2: implementing the supervisor, constructing specialist agents, defining delegation contracts, and coordinating multi-step execution.
Subsequent lessons complete the remaining production capabilities.
Assessment criteria
The capstone is assessed as an engineering system, not merely as a demonstration of conversational intelligence.
Weighted assessment rubric
| Assessment area | Weight | Evidence required |
|---|---|---|
| Architecture and state design | 15% | Clear boundaries and maintainable graph |
| Multi-agent orchestration | 20% | Correct routing and result aggregation |
| RAG and enterprise tools | 15% | Grounded retrieval and accurate operations |
| Persistence and recovery | 10% | Checkpoint restoration and safe recovery |
| Security and human approval | 15% | Authorization and approval enforcement |
| Streaming and observability | 10% | Useful events, traces, and metrics |
| Evaluation and testing | 10% | Automated tests and documented results |
| Deployment and documentation | 5% | Reproducible application deployment |
| Total | 100% |
A proposed passing score is 75%, subject to mandatory security and correctness gates.
Mandatory acceptance gates
Regardless of the numerical score, the application must not pass assessment if it permits unauthorized data access, executes protected writes without approval, duplicates mutations during recovery, or exposes enterprise credentials.
It must also avoid presenting failed operations as successful.
Evaluate these conditions using deterministic assertions wherever possible.
Use model-based evaluators for semantic qualities such as relevance and groundedness. LangSmith evaluation datasets can measure output quality, while AgentEvals can assess whether an execution trajectory follows an acceptable sequence of operations.
Do not use an LLM judge as the sole evidence that an authorization or approval control works.
Common architectural mistakes
Avoid these recurring problems during implementation:
- Unbounded delegation: agents repeatedly transfer tasks without termination conditions.
- Oversized shared state: every agent receives irrelevant documents and conversation history.
- Excessive permissions: all agents can invoke all enterprise tools.
- Prompt-only security: authorization depends entirely on model compliance.
- Unsafe retries: external mutations execute more than once.
- Premature optimization: parallel execution and caching are introduced before correctness is established.
- Happy-path testing: demonstrations omit outages, rejected approvals, and malicious inputs.
Tip: Build the deterministic orchestration prototype first, establish acceptance tests, and introduce model-driven behavior behind well-defined interfaces. This makes failures easier to isolate and reproduce.
Required final demonstration
Your final submission must demonstrate a complete business workflow beginning with an employee request that requires multiple specialists.
Show the supervisor’s delegation decisions, policy retrieval with source references, authorized SQL analytics, preparation of an external action, human approval, successful execution, and the final response.
Demonstrate a second run in which approval is rejected, and prove that no protected external action occurs. Include a recovery scenario and a security test involving an unauthorized resource.
The accompanying repository must contain reproducible setup instructions, an architecture description, automated tests, evaluation results, known limitations, and deployment configuration.
The examples in this lesson are intentionally small reference implementations. Their APIs follow the LangGraph 1.x and LangChain 1.x interfaces, but they have not been execution-tested in the authoring environment. Run their assertions in your course environment before progressing to the full capstone implementation.
Build the capstone orchestration prototype
Build a deterministic LangGraph supervisor that delegates employee requests to a knowledge agent, an analytics agent, or an operations agent. Ensure that operations requiring external changes pause for human approval before execution. Verify successful routing, approval, rejection, and graceful handling of unsupported requests.
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt
class State(TypedDict, total=False):
request: str
route: str
proposed_action: dict
response: str
def supervisor(state: State) -> Command:
# TODO: Classify the request and delegate.
raise NotImplementedError
def knowledge_agent(state: State) -> dict:
# TODO: Return simulated policy information.
raise NotImplementedError
def analytics_agent(state: State) -> dict:
# TODO: Return simulated enterprise analytics.
raise NotImplementedError
def operations_agent(state: State) -> dict:
# TODO: Prepare a proposed action without executing it.
raise NotImplementedError
def approval(state: State) -> Command:
# TODO: Pause execution and route based on approval.
raise NotImplementedError
def execute(state: State) -> dict:
# TODO: Simulate the approved action.
raise NotImplementedError
# TODO: Register nodes and edges.
# TODO: Compile with InMemorySaver.
# TODO: Test routing, approval, and rejection.from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt
class State(TypedDict, total=False):
request: str
route: str
proposed_action: dict
response: str
executed_actions = []
def supervisor(
state: State,
) -> Command[
Literal["knowledge", "analytics", "operations", "__end__"]
]:
request = state["request"].lower()
if "ticket" in request:
destination = "operations"
elif "expense" in request:
destination = "analytics"
elif "policy" in request:
destination = "knowledge"
else:
return Command(
update={
"route": "unsupported",
"response": "This request is outside my supported capabilities.",
},
goto=END,
)
return Command(
update={"route": destination},
goto=destination,
)
def knowledge_agent(state: State) -> dict:
return {
"response": "Travel reimbursement limit: USD 500 per expense."
}
def analytics_agent(state: State) -> dict:
return {
"response": "Approved expenses this month: USD 1,250."
}
def operations_agent(state: State) -> dict:
return {
"proposed_action": {
"type": "create_ticket",
"title": "Employee support request",
}
}
def approval(
state: State,
) -> Command[Literal["execute", "__end__"]]:
decision = interrupt({
"question": "Approve the proposed action?",
"action": state["proposed_action"],
})
if isinstance(decision, dict) and decision.get("approved") is True:
return Command(goto="execute")
return Command(
update={"response": "Action rejected. Nothing was executed."},
goto=END,
)
def execute(state: State) -> dict:
# Simulated external write.
executed_actions.append(state["proposed_action"].copy())
return {
"response": "Support ticket created successfully (simulated)."
}
builder = StateGraph(State)
builder.add_node("supervisor", supervisor)
builder.add_node("knowledge", knowledge_agent)
builder.add_node("analytics", analytics_agent)
builder.add_node("operations", operations_agent)
builder.add_node("approval", approval)
builder.add_node("execute", execute)
builder.add_edge(START, "supervisor")
builder.add_edge("knowledge", END)
builder.add_edge("analytics", END)
builder.add_edge("operations", "approval")
builder.add_edge("execute", END)
graph = builder.compile(checkpointer=InMemorySaver())
def config(thread_id: str) -> dict:
return {
"configurable": {"thread_id": thread_id},
"recursion_limit": 15,
}
knowledge = graph.invoke(
{"request": "What is the travel policy?"},
config("knowledge-test"),
)
assert knowledge["route"] == "knowledge"
analytics = graph.invoke(
{"request": "Show my approved expenses"},
config("analytics-test"),
)
assert analytics["route"] == "analytics"
pending = graph.invoke(
{"request": "Create a support ticket"},
config("approval-test"),
)
assert pending.get("__interrupt__")
assert len(executed_actions) == 0
approved = graph.invoke(
Command(resume={"approved": True}),
config("approval-test"),
)
assert len(executed_actions) == 1
print(approved["response"])
graph.invoke(
{"request": "Create another support ticket"},
config("rejection-test"),
)
rejected = graph.invoke(
Command(resume={"approved": False}),
config("rejection-test"),
)
assert len(executed_actions) == 1
print(rejected["response"])
unsupported = graph.invoke(
{"request": "Generate a movie"},
config("unsupported-test"),
)
assert unsupported["route"] == "unsupported"
print("All acceptance tests passed.")Summary
- An enterprise multi-agent assistant combines specialized agents with centralized orchestration and deterministic security controls.
- Functional and non-functional requirements establish measurable expectations before implementation begins.
- A supervisor coordinates delegation while specialist agents operate within narrowly defined responsibilities and permissions.
- Checkpointing, long-term memory, and enterprise data storage serve distinct architectural purposes.
- External write operations must pass authorization, validation, and human approval boundaries before execution.
- Incremental milestones reduce integration risk by validating individual capabilities before introducing production infrastructure.
- Production readiness requires measurable evidence of correctness, security, reliability, observability, and operational maintainability.