Capstone: memory, guardrails, streaming, resilience and deployment
Overview
In the previous lesson, you implemented the supervisor and specialist agents for an enterprise multi-agent AI assistant. Your supervisor could interpret requests, delegate work to appropriate agents, retrieve organizational knowledge, query databases, and interact with enterprise tools.
However, functional orchestration is only one part of a production system.
Consider an employee submitting the following request:
Retrieve our procurement policy, check the available departmental budget, and create a purchase request for five laptops.
The assistant must coordinate document retrieval, SQL queries, and an enterprise purchasing API. It must also remember the conversation, prevent unauthorized purchases, survive temporary service failures, obtain approval, and communicate progress.
If the purchasing API succeeds but the application crashes before recording the result, restarting the workflow must not create another purchase request.
These requirements distinguish an experimental agent from a dependable enterprise application.
In this lesson, you will add six production layers to the existing capstone:
- Persistent execution and long-term memory.
- Human approval and security guardrails.
- Real-time workflow streaming.
- Fault tolerance and recovery.
- Observability and systematic evaluation.
- Application deployment and operational readiness.
The following diagram illustrates the resulting architecture.
The essential architectural decision is to keep probabilistic reasoning separate from deterministic enforcement. Models can recommend actions, but application code determines whether those actions are permitted.
The examples use LangGraph 1.x, with LangGraph 1.2 or later required for node timeouts and error handlers. Install the core dependencies in your capstone environment:
pip install "langgraph>=1.2,<2" "langchain>=1,<2" langchain-openaiThe examples use simulated enterprise services to make their behavior reproducible without accessing real organizational systems.
Persistence and memory
Separate execution state from organizational memory
An enterprise assistant needs two fundamentally different forms of persistence.
Short-term memory preserves the current conversation and workflow. Long-term memory preserves selected information that remains useful across conversations.
LangGraph provides checkpointers and stores for these responsibilities.
| Characteristic | Checkpointer | Store |
|---|---|---|
| Scope | Individual thread | Multiple threads |
| Data | Graph state and execution metadata | Application-defined records |
| Primary identifier | Thread ID | Namespace and key |
| Typical contents | Messages, pending actions, routing state | Preferences, confirmed facts |
| Recovery support | Resumes graph execution | Retrieves remembered information |
| Local implementation | InMemorySaver |
InMemoryStore |
| Production implementation | PostgresSaver |
PostgresStore |
A checkpoint is produced at a graph execution boundary called a superstep. A superstep can contain multiple concurrently executing nodes. LangGraph persists state and scheduling information so the runtime knows which work remains.
The checkpointer is therefore more than a conversation database. It supports recovery, human approval, execution inspection, and historical replay.
See the LangGraph persistence documentation.
Implement thread memory and cross-thread memory
The following example stores an employee’s preferred response format and retrieves it from a different conversation thread.
Save it as memory_demo.py.
from dataclasses import dataclass
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.runtime import Runtime
@dataclass
class Context:
tenant_id: str
user_id: str
def respond(state: MessagesState, runtime: Runtime[Context]):
context = runtime.context
namespace = (
context.tenant_id,
context.user_id,
"preferences",
)
text = state["messages"][-1].content
if text == "Remember that I prefer bullet points":
runtime.store.put(
namespace,
"response_format",
{"format": "bullet points"},
)
reply = "Preference saved."
else:
item = runtime.store.get(namespace, "response_format")
preference = item.value["format"] if item else "paragraphs"
reply = f"Preferred format: {preference}"
return {"messages": [AIMessage(content=reply)]}
builder = StateGraph(MessagesState, context_schema=Context)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
graph = builder.compile(
checkpointer=InMemorySaver(),
store=InMemoryStore(),
)
context = Context("acme", "employee-101")
first = {"configurable": {"thread_id": "conversation-1"}}
second = {"configurable": {"thread_id": "conversation-2"}}
graph.invoke(
{"messages": [HumanMessage(
content="Remember that I prefer bullet points"
)]},
first,
context=context,
)
result = graph.invoke(
{"messages": [HumanMessage(
content="How should you format my answers?"
)]},
second,
context=context,
)
print(result["messages"][-1].content)
print(len(graph.get_state(first).values["messages"]))Expected output:
Preferred format: bullet points
2Although the conversations have different thread IDs, they share the same tenant-specific user namespace. The preference is therefore available in both conversations.
MessagesState uses the add_messages reducer, which manages message additions and replacements rather than overwriting the entire conversation whenever a node returns a message.
In your capstone, use namespaces such as:
(tenant_id, user_id, "preferences")(tenant_id, user_id, "confirmed_facts")(tenant_id, department_id, "knowledge")
Never allow the model to select arbitrary tenant or user identifiers. Derive them from authenticated application context.
Introduce semantic memory retrieval
Exact-key retrieval works well for structured preferences. Semantic retrieval is useful when an employee describes something using different wording.
The following standalone example configures an embedding-enabled store. It requires a valid OPENAI_API_KEY.
from langchain.embeddings import init_embeddings
from langgraph.store.memory import InMemoryStore
store = InMemoryStore(
index={
"embed": init_embeddings(
"openai:text-embedding-3-small"
),
"dims": 1536,
}
)
namespace = ("acme", "employee-101", "facts")
store.put(
namespace,
"fact-1",
{"text": "The employee manages procurement approvals."},
)
store.put(
namespace,
"fact-2",
{"text": "The employee prefers concise responses."},
)
results = store.search(
namespace,
query="Who handles purchasing authorization?",
limit=2,
)
for item in results:
print(item.key, item.value, item.score)The procurement-related record should generally receive the stronger semantic match. Exact scores and ranking depend on the embedding model.
Remember that semantic similarity is not authorization. A retrieved memory must never independently establish an employee’s approval privileges.
Implement memory retention, correction, deletion, provenance, and sensitive-data filtering. A user’s explicit preference is a better memory candidate than an unverified inference produced by an agent.
Replace local persistence with durable storage
InMemorySaver and InMemoryStore are useful for development and automated testing, but their contents disappear when the process terminates.
SQLite is suitable for lightweight, single-instance applications. PostgreSQL is generally more appropriate for enterprise workloads involving multiple workers.
Install the PostgreSQL integration:
pip install langgraph-checkpoint-postgres "psycopg[binary,pool]"The following example reuses the builder and context from memory_demo.py with PostgreSQL persistence. Configure DATABASE_URL before running it.
import os
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.store.postgres import PostgresStore
from langchain.messages import HumanMessage
from memory_demo import builder, Context
uri = os.environ["DATABASE_URL"]
with (
PostgresSaver.from_conn_string(uri) as checkpointer,
PostgresStore.from_conn_string(uri) as store,
):
checkpointer.setup()
store.setup()
graph = builder.compile(
checkpointer=checkpointer,
store=store,
)
result = graph.invoke(
{"messages": [HumanMessage(
content="Remember that I prefer bullet points"
)]},
{"configurable": {"thread_id": "persistent-thread"}},
context=Context("acme", "employee-101"),
durability="sync",
)
print(result["messages"][-1].content)Expected output from the final invocation is Preference saved.
For asynchronous applications, use AsyncPostgresSaver from langgraph.checkpoint.postgres.aio and its asynchronous setup and lifecycle methods.
Choose checkpoint durability deliberately:
| Mode | Persistence behavior | Suitable use |
|---|---|---|
exit |
Persists when execution exits | Low-risk, recomputable work |
async |
Persists while subsequent work proceeds | General interactive workloads |
sync |
Waits for persistence before continuing | Sensitive business workflows |
Synchronous durability reduces the checkpoint-loss window, but it does not make external API operations transactional with graph state.
Human approval and guardrails
Establish trust boundaries
Guardrails are enforceable constraints governing what an assistant may read, generate, remember, and execute.
Apply them throughout your architecture:
- Input: Validate schemas, request sizes, authenticated identities, and supported operations.
- Retrieval: Enforce document-level access controls before returning search results.
- SQL: Use restricted database accounts, parameterized queries, row limits, and execution timeouts.
- Enterprise APIs: Validate tool arguments, resource ownership, operation scope, and permissions.
- MCP tools: Allowlist trusted servers and operations, and treat tool descriptions and results as potentially untrusted input.
- Output: Prevent unauthorized disclosure of confidential information, credentials, and sensitive personal data.
Retrieved documents and tool responses can contain prompt injection attempts. A document instructing the assistant to ignore company policy must remain data, not become an instruction with elevated authority.
Implement a durable human approval gate
LangGraph’s interrupt() function suspends execution and surfaces a review payload. The application later resumes the same thread using Command(resume=...).
The following diagram illustrates the approval lifecycle.
The following runnable example implements a simplified purchase approval workflow. Save it as approval_demo.py.
from typing import TypedDict
from dataclasses import dataclass
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.runtime import Runtime
class State(TypedDict, total=False):
request_id: str
amount: int
approved: bool
status: str
@dataclass
class Context:
can_approve: bool
purchases = {}
def validate(state: State):
allowed = 0 < state["amount"] <= 100000
return {"status": "valid" if allowed else "blocked"}
def route_validation(state: State):
return "review" if state["status"] == "valid" else END
def review(state: State, runtime: Runtime[Context]):
decision = interrupt({
"operation": "create_purchase",
"request_id": state["request_id"],
"amount": state["amount"],
"currency": "INR",
})
approved = (
runtime.context.can_approve
and isinstance(decision, dict)
and decision.get("approved") is True
and decision.get("request_id") == state["request_id"]
)
return {
"approved": approved,
"status": "approved" if approved else "rejected",
}
def route_review(state: State):
return "execute" if state["approved"] else END
def execute(state: State, runtime: Runtime[Context]):
if not state["approved"] or not runtime.context.can_approve:
return {"status": "rejected"}
existing = purchases.setdefault(
state["request_id"],
state["amount"],
)
if existing != state["amount"]:
return {"status": "idempotency_conflict"}
return {"status": "created"}
builder = StateGraph(State, context_schema=Context)
builder.add_node("validate", validate)
builder.add_node("review", review)
builder.add_node("execute", execute)
builder.add_edge(START, "validate")
builder.add_conditional_edges(
"validate", route_validation, ["review", END]
)
builder.add_conditional_edges(
"review", route_review, ["execute", END]
)
builder.add_edge("execute", END)
if __name__ == "__main__":
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "purchase-001"},
"recursion_limit": 20,
}
pending = graph.invoke(
{"request_id": "PR-001", "amount": 75000},
config,
context=Context(False),
durability="sync",
)
print(pending["__interrupt__"][0].value)
assert not purchases
result = graph.invoke(
Command(resume={
"approved": True,
"request_id": "PR-001",
}),
config,
context=Context(True),
durability="sync",
)
print(result["status"])
print(purchases)Expected output:
{'operation': 'create_purchase', 'request_id': 'PR-001', 'amount': 75000, 'currency': 'INR'}
created
{'PR-001': 75000}The initial invocation stops before creating a purchase. The second invocation supplies the review decision and an authorized runtime context.
The approval node restarts from its beginning during resumption. The saved resume value becomes the return value of interrupt().
Note: Never perform irreversible operations before an interrupt. Replay can execute preceding statements again. Also avoid wrapping
interrupt()in a broad exception handler.
Harden approval for enterprise use
The demonstration uses a Boolean permission and an in-memory dictionary. A real application must replace these with authenticated authorization and durable operation tracking.
Bind every approval to an immutable operation ID, tenant, resource, normalized arguments, approver identity, and expiration time. If the proposed action changes, invalidate its approval.
The server must independently authenticate the reviewer and verify access to the interrupted thread. Client-submitted values such as can_approve=True are not trustworthy.
Before execution, recheck relevant business conditions, including current budget and approval validity. An approval obtained yesterday may no longer be sufficient today.
Record approval decisions in an auditable system separate from model-generated conversation text.
See the LangGraph interrupt documentation for replay behavior and interruption constraints.
Real-time streaming
Stream workflow progress
Enterprise workflows may involve several agents and slow external services. Returning nothing until all work finishes creates an unnecessarily opaque experience.
LangGraph exposes multiple streaming modes:
| Mode | Purpose |
|---|---|
updates |
Incremental node state changes |
messages |
Model message chunks and metadata |
custom |
Application-defined progress events |
values |
Complete state snapshots |
debug |
Detailed development diagnostics |
The version 2 streaming interface gives events a consistent structure containing type and data.
Use get_stream_writer() inside nodes to emit application-level events such as policy retrieval progress.
Stream model output and agent progress
The following example simulates document retrieval and streams the model’s final answer. Set OPENAI_API_KEY before running it.
from typing import TypedDict
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, START, END
from langgraph.config import get_stream_writer
class State(TypedDict, total=False):
question: str
evidence: str
answer: str
model = init_chat_model("openai:gpt-5.4-mini")
def retrieve(state: State):
writer = get_stream_writer()
writer({"stage": "knowledge", "status": "started"})
evidence = "Purchases above INR 50,000 require approval."
writer({"stage": "knowledge", "status": "completed"})
return {"evidence": evidence}
def respond(state: State):
response = model.invoke([
SystemMessage(content=(
"Answer using the supplied policy evidence. "
"Do not invent additional policy requirements."
)),
HumanMessage(content=(
f"Question: {state['question']}\n"
f"Evidence: {state['evidence']}"
)),
])
return {"answer": response.text}
graph = (
StateGraph(State)
.add_node("retrieve", retrieve)
.add_node("respond", respond)
.add_edge(START, "retrieve")
.add_edge("retrieve", "respond")
.add_edge("respond", END)
.compile()
)
for chunk in graph.stream(
{"question": "Does a purchase of INR 75,000 need approval?"},
{"recursion_limit": 15},
stream_mode=["updates", "messages", "custom"],
version="v2",
):
kind = chunk["type"]
data = chunk["data"]
if kind == "custom":
print("\nProgress:", data)
elif kind == "messages":
message, metadata = data
if metadata.get("langgraph_node") == "respond":
print(message.text, end="", flush=True)
elif kind == "updates":
print("\nCompleted nodes:", list(data))Expected behavior:
Progress: {'stage': 'knowledge', 'status': 'started'}
Progress: {'stage': 'knowledge', 'status': 'completed'}
Completed nodes: ['retrieve']
Yes, a purchase of INR 75,000 requires approval.
Completed nodes: ['respond']Exact model wording and message chunk boundaries will vary.
LangGraph can expose model message chunks even when a node calls model.invoke(). The runtime integrates with model streaming events.
The newer event-streaming interface, graph.stream_events(inputs, version="v3"), provides projections such as stream.messages, stream.values, stream.interrupts, and stream.output. Use it when building clients that benefit from higher-level event consumption.
For browser applications, forward sanitized events through Server-Sent Events or WebSockets. Never expose raw internal state indiscriminately. Filter internal agent messages, confidential retrieval results, tool arguments, and reasoning-related content.
Progress events are not proof that an external operation committed successfully. Confirm completion from durable application state.
See the LangGraph streaming documentation.
Fault tolerance and recovery
Classify failures before handling them
Not every error should trigger another attempt.
| Failure | Appropriate response |
|---|---|
| Temporary network outage | Bounded retry |
| Rate limiting | Backoff and jitter |
| Invalid tool arguments | Validate and correct |
| Permission denied | Reject without retrying |
| Slow external service | Timeout and fallback |
| Unknown write outcome | Reconcile before retrying |
| Unexpected application defect | Alert and investigate |
Retries increase availability for temporary failures, but retrying permanent failures wastes resources.
Configure retries, timeouts, and error handlers
LangGraph supports node-level resilience policies. A failed attempt is evaluated against the retry policy before the runtime invokes an error handler.
The following asynchronous example simulates an unavailable enterprise API and returns a controlled failure after exhausting retries.
import asyncio
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import RetryPolicy, Command
from langgraph.errors import NodeError
class State(TypedDict, total=False):
customer_id: str
status: str
message: str
attempts = 0
async def fetch_customer(state: State):
global attempts
attempts += 1
await asyncio.sleep(0.1)
raise ConnectionError("Customer service unavailable")
def recover(state: State, error: NodeError) -> Command:
print("Failed node:", error.node)
print("Error type:", type(error.error).__name__)
return Command(
update={
"status": "degraded",
"message": "Customer information is temporarily unavailable.",
},
goto=END,
)
builder = StateGraph(State)
builder.add_node(
"fetch_customer",
fetch_customer,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
backoff_factor=2.0,
retry_on=ConnectionError,
),
timeout=5,
error_handler=recover,
)
builder.add_edge(START, "fetch_customer")
builder.add_edge("fetch_customer", END)
graph = builder.compile()
async def main():
result = await graph.ainvoke(
{"customer_id": "C-101"},
{"recursion_limit": 10},
)
print("Attempts:", attempts)
print("Status:", result["status"])
print(result["message"])
asyncio.run(main())Expected output:
Failed node: fetch_customer
Error type: ConnectionError
Attempts: 3
Status: degraded
Customer information is temporarily unavailable.max_attempts=3 includes the original attempt. The timeout applies separately to each attempt, and the error handler executes when no further retries are permitted.
Node timeouts require asynchronous nodes. Use TimeoutPolicy for more advanced runtime and idle-timeout configuration. Apply shared settings using builder.set_node_defaults(...), but override them where operation-specific behavior is necessary.
These capabilities are documented in the LangGraph fault tolerance guide.
Prevent duplicate side effects
Retries and checkpoint recovery can execute a node multiple times. LangGraph cannot guarantee exactly-once execution of an external enterprise API.
Use a stable idempotency key representing the business operation, for example:
acme:procurement:PR-001
The receiving service should atomically deduplicate requests using that key and return the existing result when appropriate.
Persist the key before performing the operation. If an acknowledgement is lost, query the service using the key before issuing another write.
For multi-service operations, consider compensating transactions or a saga. If inventory reservation succeeds but purchase creation fails permanently, a compensation workflow can release the reservation.
Recover and inspect execution
With checkpointing enabled, graph.get_state(config) returns the latest state snapshot, including pending nodes. graph.get_state_history(config) exposes historical snapshots.
After resolving an infrastructure failure, graph.invoke(None, config, context=...) can continue unfinished execution. A pending human interrupt instead requires a resume command.
For controlled repairs, graph.update_state(config, values, as_node=...) creates an updated checkpoint and influences subsequent scheduling. It is not a rollback of external side effects.
Use CachePolicy(ttl=...) with InMemoryCache for suitable read-only nodes. Include tenant and authorization-relevant inputs in cache keys; runtime context should not be assumed to participate automatically.
Set an explicit recursion_limit because the default graph limit is unsuitable as a practical cost-control mechanism. Also enforce tool-call, token, monetary, and elapsed-time budgets.
Observability and evaluation
Trace the complete execution path
Observability answers what happened, why it happened, and where the application failed.
Enable LangSmith tracing before running your capstone:
pip install langsmith openevals agentevals
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="your-api-key"
export LANGSMITH_PROJECT="enterprise-assistant-capstone"Inspect traces for supervisor decisions, specialist-agent execution, retrieval calls, model latency, tool failures, token consumption, and retry attempts.
Correlate application logs with thread IDs, run IDs, request IDs, and operation IDs. Redact secrets and confidential content before exporting traces.
Do not confuse tracing with an immutable business audit log. Approval records and financial operations may require separate retention and access controls.
Evaluate outcomes and trajectories
A correct final answer does not prove that the agent behaved correctly.
An assistant might provide the correct purchasing policy while unnecessarily querying confidential employee records. Outcome evaluation could pass even though the execution trajectory violated policy.
Evaluate both dimensions:
- Outcome quality: Correctness, completeness, grounding, relevance, and citations.
- Trajectory quality: Agent selection, permitted tools, valid arguments, approval ordering, and unnecessary actions.
Use deterministic assertions for safety-critical properties. Use openevals.create_llm_as_judge for qualitative scoring and agentevals.create_trajectory_match_evaluator for expected tool-call trajectories.
LLM judges are imperfect measurements, so calibrate them against human-reviewed examples.
Run an evaluation experiment
The following example evaluates the validation and rejection behavior of approval_demo.py using LangSmith. It uses isolated in-memory checkpoints and never performs purchases.
from uuid import uuid4
from langsmith import Client
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
from approval_demo import builder, Context
client = Client()
dataset = client.create_dataset(
dataset_name=f"capstone-safety-{uuid4().hex[:8]}"
)
client.create_examples(
dataset_id=dataset.id,
inputs=[
{"amount": 150000},
{"amount": -500},
{"amount": 75000},
],
outputs=[
{"status": "blocked"},
{"status": "blocked"},
{"status": "rejected"},
],
)
def target(inputs):
graph = builder.compile(checkpointer=InMemorySaver())
request_id = uuid4().hex
config = {"configurable": {"thread_id": request_id}}
result = graph.invoke(
{"request_id": request_id, "amount": inputs["amount"]},
config,
context=Context(False),
)
if result.get("__interrupt__"):
result = graph.invoke(
Command(resume={
"approved": True,
"request_id": request_id,
}),
config,
context=Context(False),
)
return {"status": result["status"]}
def safety_correctness(outputs, reference_outputs):
return {
"key": "safety_correctness",
"score": int(
outputs["status"] == reference_outputs["status"]
),
}
client.evaluate(
target,
data=dataset.name,
evaluators=[safety_correctness],
experiment_prefix="approval-safety",
)The expected result is three passing evaluations, each scoring 1.
Expand this dataset to include prompt injection, unauthorized retrieval, approval rejection, duplicated operations, service failures, ambiguous requests, and multi-turn conversations.
Deployment
Package the application
LangSmith Agent Server exposes your graph through managed execution APIs and supports threads, runs, persistence, streaming, and asynchronous workflows.
Organize your capstone repository as follows:
enterprise-assistant/
├── app/
│ ├── __init__.py
│ ├── graph.py
│ ├── supervisor.py
│ ├── agents.py
│ ├── tools.py
│ ├── policies.py
│ └── state.py
├── tests/
├── evaluations/
├── requirements.txt
├── langgraph.json
├── .env
└── .gitignoreExport the compiled graph from app/graph.py. When targeting Agent Server, compile without manually installing a local checkpointer or store because the server manages those persistence services.
For a minimal local deployment demonstration using the approval example, place approval_demo.py in the project root and use:
from approval_demo import builder
graph = builder.compile()Create requirements.txt:
langgraph>=1.2,<2
langchain>=1,<2
langchain-openai
langsmithCreate langgraph.json:
{
"dependencies": ["."],
"graphs": {
"enterprise_assistant": "./app/graph.py:graph"
},
"env": ".env"
}Lock tested dependency versions for actual releases, and keep .env outside version control.
Run and deploy the server
Install the CLI and SDK:
pip install "langgraph-cli[inmem]" langgraph-sdkStart the development server:
langgraph devUse LangSmith Studio to inspect graph execution, threads, state, and interruptions.
For production-like local validation with Docker:
langgraph upBuild a deployment image:
langgraph build -t enterprise-assistant:1.0.0For supported cloud deployments, use langgraph deploy or the LangSmith deployment interface with the required account permissions and deployment configuration.
See the application structure guide and local development documentation.
Call the deployed graph
The following SDK example communicates with the local development server. It deliberately submits a blocked operation, avoiding the need to configure an approval identity.
import asyncio
from langgraph_sdk import get_client
async def main():
client = get_client(url="http://127.0.0.1:2024")
thread = await client.threads.create()
result = await client.runs.wait(
thread["thread_id"],
"enterprise_assistant",
input={
"request_id": "deployment-test",
"amount": 150000,
},
)
print(result["status"])
asyncio.run(main())Expected output:
blockedIn production, configure authentication, tenant-level resource authorization, secrets management, network restrictions, database backups, worker limits, health checks, and monitoring alerts.
Keep graph versions compatible with interrupted threads. Renaming nodes or rearranging interrupt calls can break pending workflows. Drain or migrate incompatible runs before releasing such changes.
Readiness checklist
Treat production readiness as a release gate rather than a subjective assessment.
Functional and security readiness
- Supervisor routes representative requests to appropriate agents.
- RAG responses include verified supporting evidence.
- SQL, enterprise API, and MCP tools enforce least privilege.
- Tenant isolation is enforced for threads, memory, retrieval, and caches.
- Sensitive actions require authenticated approval.
- Rejection and unauthorized approval cannot produce side effects.
- Prompt injection and sensitive-data leakage tests pass.
Reliability and operational readiness
- Checkpoints and long-term memory survive process restarts.
- External writes have durable idempotency protection.
- Retries, timeouts, fallbacks, and recursion limits are configured.
- Streaming clients handle interruptions and connection failures.
- Traces, metrics, alerts, and audit records are available.
- Deployment, rollback, backup, and recovery procedures are documented.
- Evaluation thresholds and load-test requirements are satisfied.
Your evaluation report
Your final capstone deliverable should include an engineering evaluation report demonstrating that the assistant is dependable, not merely impressive during a successful demonstration.
Define measurable acceptance criteria
Use a representative dataset of at least 50 scenarios as an initial benchmark, with separate safety and failure-injection tests.
The following thresholds are illustrative project targets, not universal production standards or measured results.
| Metric | Example target |
|---|---|
| Task completion rate | At least 90% |
| Correct agent routing | At least 95% |
| Grounded response rate | At least 95% |
| Unauthorized writes | 0 observed |
| Duplicate business operations | 0 observed |
| Approval enforcement | 100% of tested cases |
| Transient failure recovery | At least 95% |
| P95 read-only latency | Under 10 seconds |
| Average cost per request | Within agreed budget |
Calculate completion rate as successful tasks divided by attempted tasks. Measure P95 latency as the 95th percentile of observed execution durations.
Report human approval waiting time separately from machine execution time. A purchase waiting several hours for a manager should not distort model-processing latency measurements.
Structure the report
Include the application architecture, supported use cases, model and dependency versions, dataset composition, evaluation methodology, acceptance criteria, actual measured results, representative traces, failure analysis, security findings, deployment configuration, and remaining limitations.
For every failed scenario, identify the likely root cause and proposed remediation. Include evidence that fixes did not introduce regressions.
Zero observed security failures is evidence about the tested dataset, not proof that all possible attacks are prevented.
Prepare your capstone demonstration
Your demonstration should show a realistic end-to-end enterprise workflow:
- Submit a procurement request.
- Observe supervisor delegation to knowledge and SQL agents.
- Stream retrieval and validation progress.
- Display supporting procurement policy evidence.
- Pause before creating the purchase.
- Restart the application and resume the persisted thread.
- Authenticate an approver and authorize the operation.
- Demonstrate recovery from a simulated API failure.
- Verify that only one purchase request exists.
- Open a different conversation and retrieve a saved preference.
- Demonstrate rejection of an unauthorized operation.
- Present evaluation results and corresponding LangSmith traces.
Tip: Use a sandbox enterprise API and synthetic organizational data during the demonstration. Inject failures deliberately rather than depending on unpredictable external outages.
The examples in this lesson are designed for local execution using simulated services; they have not been executed against a live enterprise deployment here. Replace the demonstration authorization flags and in-memory business records with authenticated controls and durable enterprise integrations before claiming production readiness.
In the next lesson, More projects and where to go next, you will explore additional agentic AI projects, advanced architectural patterns, and opportunities to extend your LangGraph engineering skills beyond this enterprise assistant.
Build a production-ready approval workflow
Extend an enterprise assistant with checkpointing, cross-thread memory, human approval, progress streaming, and automatic retries. Ensure that rejected or unauthorized actions never modify enterprise data. Demonstrate successful execution, rejection, transient failure recovery, and memory retrieval across separate conversation threads.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.types import Command, interrupt, RetryPolicy
from langgraph.config import get_stream_writer
class State(TypedDict, total=False):
user_id: str
request_id: str
request: str
approved: bool
status: str
records = {}
store = InMemoryStore()
def prepare(state: State):
# TODO: Emit a progress event.
# TODO: Prepare the requested operation.
pass
def review(state: State):
# TODO: Interrupt execution and collect approval.
pass
def execute(state: State):
# TODO: Reject unapproved operations.
# TODO: Use an idempotency key.
# TODO: Persist a successful operation in memory.
pass
builder = StateGraph(State)
# TODO: Register nodes and configure retries.
# TODO: Add edges and conditional routing.
# TODO: Compile with a checkpointer and store.
# TODO: Test interruption, approval, and rejection.from typing import TypedDict
from dataclasses import dataclass
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.runtime import Runtime
from langgraph.types import Command, interrupt, RetryPolicy
from langgraph.config import get_stream_writer
class State(TypedDict, total=False):
tenant_id: str
user_id: str
request_id: str
request: str
approved: bool
previous_request: str
status: str
@dataclass
class Context:
tenant_id: str
user_id: str
can_approve: bool = False
records = {}
attempts = {}
store = InMemoryStore()
def namespace(context: Context):
return (context.tenant_id, context.user_id, "activity")
def prepare(state: State, runtime: Runtime[Context]):
context = runtime.context
get_stream_writer()({"stage": "preparing"})
item = runtime.store.get(namespace(context), "last_request")
return {
"tenant_id": context.tenant_id,
"user_id": context.user_id,
"approved": False,
"previous_request": item.value["request"] if item else "",
"status": "awaiting_approval",
}
def review(state: State, runtime: Runtime[Context]):
decision = interrupt({
"request_id": state["request_id"],
"request": state["request"],
"question": "Approve this operation?",
})
context = runtime.context
approved = (
context.can_approve
and context.tenant_id == state["tenant_id"]
and context.user_id == state["user_id"]
and isinstance(decision, dict)
and decision.get("approved") is True
and decision.get("request_id") == state["request_id"]
)
return {
"approved": approved,
"status": "approved" if approved else "rejected",
}
def route_review(state: State):
return "execute" if state["approved"] else END
def execute(state: State, runtime: Runtime[Context]):
context = runtime.context
if (
not state["approved"]
or not context.can_approve
or context.tenant_id != state["tenant_id"]
or context.user_id != state["user_id"]
):
return {"status": "rejected"}
key = (
context.tenant_id,
context.user_id,
state["request_id"],
)
attempts[key] = attempts.get(key, 0) + 1
if attempts[key] == 1:
raise ConnectionError("Simulated temporary outage")
existing = records.setdefault(key, state["request"])
if existing != state["request"]:
return {"status": "idempotency_conflict"}
runtime.store.put(
namespace(context),
"last_request",
{"request": state["request"]},
)
get_stream_writer()({"stage": "completed"})
return {"status": "completed"}
builder = StateGraph(State, context_schema=Context)
builder.add_node("prepare", prepare)
builder.add_node("review", review)
builder.add_node(
"execute",
execute,
retry_policy=RetryPolicy(
max_attempts=3,
retry_on=ConnectionError,
initial_interval=0.1,
),
)
builder.add_edge(START, "prepare")
builder.add_edge("prepare", "review")
builder.add_conditional_edges(
"review",
route_review,
["execute", END],
)
builder.add_edge("execute", END)
graph = builder.compile(
checkpointer=InMemorySaver(),
store=store,
)
context = Context("acme", "employee-101", True)
def config(thread_id):
return {
"configurable": {"thread_id": thread_id},
"recursion_limit": 20,
}
first = config("thread-1")
for chunk in graph.stream(
{"request_id": "req-1", "request": "Create support ticket"},
first,
context=context,
stream_mode=["updates", "custom"],
version="v2",
durability="sync",
):
print(chunk["type"], chunk["data"])
assert graph.get_state(first).next == ("review",)
assert not records
result = graph.invoke(
Command(resume={"approved": True, "request_id": "req-1"}),
first,
context=context,
durability="sync",
)
assert result["status"] == "completed"
assert len(records) == 1
assert attempts[("acme", "employee-101", "req-1")] == 2
second = config("thread-2")
pending = graph.invoke(
{"request_id": "req-2", "request": "Update support ticket"},
second,
context=context,
)
assert pending["previous_request"] == "Create support ticket"
assert pending["__interrupt__"]
rejected = graph.invoke(
Command(resume={"approved": False, "request_id": "req-2"}),
second,
context=context,
)
assert rejected["status"] == "rejected"
assert len(records) == 1
third = config("thread-3")
unauthorized = Context("acme", "employee-101", False)
graph.invoke(
{"request_id": "req-3", "request": "Delete support ticket"},
third,
context=unauthorized,
)
denied = graph.invoke(
Command(resume={"approved": True, "request_id": "req-3"}),
third,
context=unauthorized,
)
assert denied["status"] == "rejected"
assert len(records) == 1
print("All production-layer tests passed.")Summary
- Checkpointers preserve thread-specific execution state, while stores provide application-managed memory across conversation threads.
- Human approval must be enforced by deterministic authorization logic before sensitive enterprise operations execute.
- Streaming communicates model output and workflow progress without waiting for the entire graph to finish.
- Retries, timeouts, error handlers, and idempotency work together to make distributed agent workflows resilient.
- Observability and evaluation must measure both final responses and the intermediate actions taken by agents.
- LangSmith Agent Server provides deployment infrastructure for persistent, stateful LangGraph applications.
- Production readiness requires measurable quality, security, recovery, performance, and operational acceptance criteria.