More projects and where to go next
Overview
Congratulations on reaching the final lesson of LangGraph – Beginner to Advanced (Agentic AI Engineering with Python).
Throughout this course, you have progressed from basic language model interactions to designing, implementing, evaluating, and deploying sophisticated agentic AI applications.
In the previous lesson, you completed the production-oriented components of an enterprise multi-agent assistant, including persistent memory, guardrails, streaming, resilience, observability, and deployment.
That capstone provides a reusable architectural foundation for many real-world applications.
However, mastering LangGraph is not simply about remembering how to use StateGraph, Command, ToolNode, or interrupt(). It is about understanding how to transform an uncertain, model-driven process into a controlled and dependable software system.
A professional agentic AI engineer must answer questions such as:
- Which decisions genuinely require a language model?
- Which operations must remain deterministic?
- What happens when a tool fails halfway through execution?
- How can an interrupted process recover safely?
- How do we measure whether the application is improving?
- How do we prevent unauthorized actions?
This final lesson explores ten practical projects, a recommended technology stack, essential engineering habits, and a roadmap for continuing your development beyond this course.
From learning a framework to engineering systems
An agentic application is more than a model connected to tools.
It combines reasoning, state management, business rules, external integrations, execution policies, and operational infrastructure.
The following architecture illustrates how these responsibilities can work together.
This is a conceptual architecture rather than a requirement to implement every component in every project.
A simple document assistant might need only three nodes. A regulated enterprise workflow might require multiple agents, authorization checks, durable checkpoints, approval queues, and comprehensive audit records.
The objective is to achieve the required reliability with the simplest suitable architecture.
Real-world project ideas
The following ten projects address problems that organizations encounter across different industries. Each project introduces a different combination of orchestration, retrieval, decision-making, security, and operational challenges.
1. Intelligent customer support assistant
Build an assistant that understands customer complaints, retrieves product information, checks order status, and resolves common support requests.
The application should distinguish between informational questions and requests requiring external actions, such as cancellations or refunds.
Architecture:
- A supervisor identifies customer intent.
- A knowledge agent retrieves relevant support documentation.
- An order agent queries the order management API.
- A resolution workflow proposes an appropriate action.
- A human approves sensitive transactions.
Use checkpointing to preserve conversations and long-term memory to retain authorized customer preferences.
Start with simulated customer records before integrating a real CRM system.
Advanced challenge: Detect repeated unsuccessful resolution attempts and escalate the conversation to a human.
Success metrics: Resolution rate, escalation accuracy, response latency, and unauthorized action rate.
2. Enterprise knowledge and research assistant
Build an assistant that answers questions using internal documents, technical specifications, meeting notes, and organizational policies.
Unlike basic RAG, an agentic RAG system can decide whether to retrieve additional information, reformulate a query, or consult another knowledge source.
Implement document retrieval, evidence grading, bounded retrieval loops, citation generation, and insufficient-evidence responses.
Document-level access control must be applied during retrieval, not merely during answer generation.
Advanced challenge: Combine information from multiple repositories while identifying conflicting or outdated documents.
Success metrics: Retrieval recall, citation correctness, answer groundedness, and access-control compliance.
3. Natural language business intelligence assistant
Create an application that converts business questions into analytical database queries.
A manager might ask:
Which product categories experienced declining revenue during the previous quarter?
The assistant should inspect relevant database schemas, generate SQL, validate the query, execute it, and explain the results.
Separate SQL generation from execution. Use read-only database credentials, restricted views, query timeouts, and row limits.
A deterministic validation layer should enforce database policies rather than relying exclusively on an LLM to identify unsafe queries.
Advanced challenge: Generate follow-up analysis and chart-ready JSON from validated query results.
Success metrics: SQL execution accuracy, numerical correctness, query latency, and policy violations.
4. Automated market research assistant
Build a research application that investigates companies, products, industries, or competitors and produces evidence-based reports.
Use a planning node to decompose research objectives into smaller questions. Dispatch independent research tasks using Send, collect their findings through state reducers, and synthesize a final report.
Each finding should retain its source, publication date, and retrieval date.
Introduce a verification stage that identifies unsupported claims and conflicting evidence. Limit the number of additional research rounds.
Advanced challenge: Generate recurring market intelligence reports and identify meaningful changes between research runs.
Success metrics: Source quality, factual accuracy, topic coverage, freshness, and research cost.
5. IT operations and incident response assistant
Develop an assistant that helps engineering teams investigate operational incidents.
The assistant could retrieve application logs, inspect monitoring alerts, search incident histories, and recommend remediation steps.
Use separate capabilities for diagnostics, infrastructure inspection, and remediation. MCP servers can expose approved observability and infrastructure tools.
Keep diagnostic operations read-only. Require explicit authorization before restarting services, changing configurations, or modifying infrastructure.
Advanced challenge: Simulate an unavailable monitoring service and verify that the graph reports incomplete evidence rather than inventing a diagnosis.
Success metrics: Diagnostic accuracy, investigation duration, remediation safety, and recovery success.
6. Financial document processing assistant
Create a workflow that processes invoices, purchase orders, and expense documents.
The application should extract structured fields, validate totals, detect duplicate documents, compare invoices with purchase orders, and route discrepancies for review.
Use structured model outputs for ambiguous document extraction and ordinary Python functions for arithmetic and business-rule validation.
Checkpointing allows the workflow to remain suspended while a finance employee investigates a discrepancy.
Advanced challenge: Process batches of invoices concurrently while preventing duplicate processing through stable document identifiers.
Success metrics: Extraction accuracy, reconciliation accuracy, duplicate detection rate, and manual processing time saved.
7. Software engineering and code review assistant
Build an assistant that examines repository changes, identifies potential defects, proposes tests, and produces code review feedback.
A supervisor can delegate work to testing, documentation, security, and code-quality agents.
Run generated code only inside an isolated environment with restricted filesystem access, network permissions, and execution resources.
The assistant should produce proposed changes rather than automatically merging or deploying them.
Advanced challenge: Connect a repository MCP server, analyze pull requests, and require maintainer approval before publishing review comments.
Success metrics: Valid issue detection, false-positive rate, test effectiveness, and review time saved.
8. Supply chain and procurement assistant
Develop an application that monitors inventory, evaluates supplier information, and recommends purchasing decisions.
A typical workflow retrieves stock levels, estimates replenishment requirements, compares suppliers, checks spending policies, and prepares purchase requests.
Keep numerical forecasting and spending-limit enforcement deterministic. Use language models to interpret supplier documents and explain recommendations.
Persist pending approvals so procurement employees can review requests independently of the original session.
Advanced challenge: Implement idempotent purchase submission and recover safely when the supplier API times out after receiving an order.
Success metrics: Stockout reduction, recommendation accuracy, duplicate order prevention, and procurement processing time.
9. Personalized learning and assessment assistant
Create an educational assistant that generates explanations, assesses learner understanding, and adapts subsequent lessons.
Use short-term conversation state for the current session and long-term memory for authorized learning preferences, completed topics, and assessment results.
A routing node can choose between explanation, demonstration, assessment, and remediation.
Use deterministic grading for objective questions and rubric-based evaluation for open-ended responses.
Advanced challenge: Generate a personalized learning plan based on demonstrated weaknesses rather than merely asking learners which topics they find difficult.
Success metrics: Learning improvement, grading consistency, recommendation relevance, and learner satisfaction.
10. Enterprise workflow automation assistant
Extend the course capstone into an assistant capable of coordinating activities across departments.
The application might retrieve employee policies, create support tickets, prepare procurement requests, inspect operational reports, and draft communications.
Use a supervisor, specialized agents, enterprise REST APIs, SQL tools, MCP integrations, persistent checkpoints, and human approval.
Stream progress events so users can distinguish ongoing work from completed operations.
Introduce authenticated runtime context, tenant isolation, audit records, and recovery policies.
Advanced challenge: Deploy the application to a staging environment and validate it against realistic workloads, concurrent requests, simulated outages, and unauthorized action attempts.
Success metrics: End-to-end task completion, policy compliance, operational reliability, latency, and cost per successful request.
Choosing your next project
Choose projects according to the engineering skills you need to strengthen.
| Project | Primary engineering skill | Relative complexity |
|---|---|---|
| Customer support | Tool calling and approval | Intermediate |
| Enterprise knowledge | Agentic RAG | Intermediate |
| Business intelligence | SQL safety | Intermediate |
| Market research | Parallel orchestration | Advanced |
| IT operations | Resilience and MCP | Advanced |
| Financial processing | Structured data validation | Intermediate |
| Code review | Sandboxed execution | Advanced |
| Procurement | Durable business workflows | Advanced |
| Learning assistant | Persistent memory | Intermediate |
| Enterprise automation | Complete system integration | Expert |
Rather than building ten unfinished prototypes, complete two or three applications with progressively stronger production capabilities.
Recommended technology stack
Selecting the right components
A technology stack should be selected according to application requirements, team expertise, security obligations, and operational constraints.
The following is a practical reference stack for Python-based agentic AI engineering.
| Application layer | Recommended technologies | Purpose |
|---|---|---|
| Programming language | Python 3.12+ | Application development |
| Model integration | LangChain 1.x | Models, messages, tools, and agents |
| Orchestration | LangGraph 1.x | Stateful execution and workflow control |
| Language models | OpenAI or other supported providers | Reasoning and generation |
| Validation | Pydantic, TypedDict | Data contracts and validation |
| Relational database | PostgreSQL | Business and application data |
| Vector retrieval | pgvector, Qdrant | Semantic document search |
| Checkpointing | PostgreSQL checkpointer | Durable execution |
| Long-term memory | LangGraph Store with persistent backend | Cross-thread information |
| Enterprise integration | HTTPX, SQLAlchemy, MCP | External services and databases |
| Application API | LangSmith Agent Server or FastAPI | Application serving |
| Frontend | Streamlit, React | Interactive interfaces |
| Observability | LangSmith, OpenTelemetry | Tracing and monitoring |
| Evaluation | Pytest, LangSmith, OpenEvals, AgentEvals | Quality measurement |
| Deployment | Docker, managed containers | Application hosting |
| CI/CD | GitHub Actions or equivalent | Automated testing and releases |
Not every project requires every component. PostgreSQL with pgvector, for example, can simplify infrastructure when relational and vector workloads have compatible requirements.
Establishing the development environment
Create an isolated environment for each project.
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install "langgraph>=1,<2" "langchain>=1.4,<2"
pip install langchain-openai
pip install pytestInstall additional integrations only when needed.
pip install "langchain[mcp]>=1.4,<2"
pip install langgraph-checkpoint-postgres "psycopg[binary,pool]"
pip install langsmith openevals agentevals
pip install httpx sqlalchemy
pip install "langgraph-cli[inmem]" langgraph-sdkAfter validating compatibility, commit a dependency lockfile so development, testing, and deployment use reproducible package versions.
Note: The examples use LangGraph 1.x and LangChain 1.x APIs. Local examples use simulated data; model-backed examples require provider credentials and model access. Expected outputs are illustrative rather than results from an executed integration test.
Choosing between LangChain agents and LangGraph workflows
A common mistake is constructing a complex custom graph when a standard tool-calling agent is sufficient.
| Approach | Best suited for |
|---|---|
create_agent() |
Standard model-driven tool calling |
StateGraph |
Explicit routing, policies, and complex workflows |
| Subgraphs | Reusable, independently structured workflows |
| Functional API | Stateful orchestration using function-oriented code |
| Multi-agent architecture | Specialized capabilities and context isolation |
Start with the highest-level abstraction that satisfies your requirements. Introduce lower-level orchestration when you need additional control.
The following example demonstrates a small customer support agent with a read-only order lookup tool.
Configure OPENAI_API_KEY in your environment before running it.
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langchain.tools import tool
ORDERS = {
"ORD-101": "Shipped",
"ORD-102": "Processing",
"ORD-103": "Delivered",
}
@tool
def get_order_status(order_id: str) -> str:
"""Retrieve the current status of an order by its ID."""
return ORDERS.get(order_id, "Order not found")
model = init_chat_model("openai:gpt-5.4-mini")
agent = create_agent(
model=model,
tools=[get_order_status],
system_prompt=(
"You are a customer support assistant. "
"Use the order lookup tool to verify order status. "
"Never invent order information."
),
)
result = agent.invoke(
{
"messages": [
HumanMessage(
content="What is the status of ORD-101?"
)
]
},
config={"recursion_limit": 10},
)
print(result["messages"][-1].content)Expected response:
Your order ORD-101 has been shipped.The wording may vary between model executions.
Internally, the agent invokes the model, executes requested tools, adds their results to the message history, and invokes the model again until it produces a final response.
If the application subsequently requires refund approvals, explicit escalation routes, or coordination with other agents, introduce a custom StateGraph.
Adding production infrastructure
As applications mature, replace temporary infrastructure with durable services.
Use InMemorySaver during local development, SqliteSaver for suitable local persistence requirements, and PostgresSaver or AsyncPostgresSaver for shared production checkpointing.
Remember that checkpoints preserve execution state, whereas stores preserve information intended for reuse across threads.
For enterprise integrations, use ordinary Python tools for tightly controlled business operations and MCP where standardized tool discovery and integration provide value.
The current LangChain MCP integration uses MCPAdapter from langchain.mcp. Review its beta API status and compatibility requirements in the official MCP documentation.
For deployment, maintain a langgraph.json configuration, dependency definitions, and an exported compiled graph. Use langgraph dev for local development and evaluate langgraph up, langgraph build, or langgraph deploy according to your hosting environment.
LangSmith Agent Server provides graph-serving infrastructure and APIs for managing threads, runs, and streaming. A custom FastAPI service is another option, but its surrounding execution and operational infrastructure becomes your responsibility.
Habits that matter more than any framework
Frameworks evolve. Engineering principles remain valuable across frameworks, model providers, and deployment environments.
1. Start with explicit requirements and measurable outcomes
Before writing an agent, define its inputs, outputs, permitted operations, failure behavior, and acceptance criteria.
Avoid vague objectives such as making an assistant intelligent.
Instead, establish measurable requirements:
- Correctly resolve at least 95% of representative order-status requests.
- Prevent all unauthorized refund operations in the security test suite.
- Maintain a defined response latency target.
- Remain within an agreed cost budget per successful task.
These are illustrative targets; choose actual thresholds according to business requirements and risk.
2. Design deterministic boundaries around probabilistic components
Language models are useful when interpreting ambiguous information. They should not be the final authority over permissions, financial calculations, or mandatory business policies.
The following standalone example demonstrates deterministic authorization using runtime context, along with real-time progress events.
from dataclasses import dataclass
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.config import get_stream_writer
@dataclass
class Context:
role: str
class State(TypedDict, total=False):
action: str
allowed: bool
def authorize(
state: State,
runtime: Runtime[Context],
):
writer = get_stream_writer()
permissions = {
"employee": {"read_report"},
"manager": {"read_report", "approve_report"},
}
allowed = state["action"] in permissions.get(
runtime.context.role, set()
)
writer({
"event": "authorization_checked",
"allowed": allowed,
})
return {"allowed": allowed}
builder = StateGraph(State, context_schema=Context)
builder.add_node("authorize", authorize)
builder.add_edge(START, "authorize")
builder.add_edge("authorize", END)
graph = builder.compile()
for chunk in graph.stream(
{"action": "approve_report"},
context=Context(role="employee"),
stream_mode=["updates", "custom"],
version="v2",
):
print(chunk["type"], chunk["data"])Expected output:
custom {'event': 'authorization_checked', 'allowed': False}
updates {'authorize': {'allowed': False}}In production, runtime context must be populated from a trusted authentication layer, not an unverified client-supplied role.
The execution tool must also enforce authorization before performing the operation. A graph-level permission decision alone is not a sufficient security boundary.
3. Build evaluation datasets early
Agent development without systematic evaluation quickly becomes guesswork.
Create datasets containing ordinary requests, ambiguous inputs, missing information, malicious instructions, unauthorized actions, and external-service failures.
Measure both the final answer and the actions taken to produce it.
For example, a refund assistant that generates a polite response but issues an unauthorized refund has failed, regardless of its language quality.
The following example evaluates deterministic routing behavior without requiring a language model.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict, total=False):
intent: str
route: str
def classify(state: State):
routes = {
"policy": "knowledge_agent",
"sales": "sql_agent",
"refund": "human_review",
}
return {
"route": routes.get(
state["intent"], "clarification"
)
}
builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_edge(START, "classify")
builder.add_edge("classify", END)
graph = builder.compile()
dataset = [
("policy", "knowledge_agent"),
("sales", "sql_agent"),
("refund", "human_review"),
("unknown", "clarification"),
("delete_database", "clarification"),
]
passed = 0
for intent, expected in dataset:
result = graph.invoke({"intent": intent})
correct = result["route"] == expected
passed += int(correct)
print(intent, "PASS" if correct else "FAIL")
print(f"Accuracy: {passed / len(dataset):.0%}")
assert passed == len(dataset)Expected output:
policy PASS
sales PASS
refund PASS
unknown PASS
delete_database PASS
Accuracy: 100%This evaluates the routing policy, not natural language understanding. A production classifier requires additional tests against realistic user requests.
Use Client().evaluate() from LangSmith for dataset-based experiments, create_llm_as_judge from OpenEvals for rubric-based judgments, and create_trajectory_match_evaluator from AgentEvals for comparing agent execution paths.
4. Design for failure and recovery
External APIs become unavailable, models produce invalid responses, databases time out, and users abandon sessions.
Design explicitly for these conditions using:
RetryPolicyfor transient failures.- Timeouts for long-running asynchronous operations.
- Persistent checkpoints for recoverable execution.
- Human escalation for unresolved errors.
- Explicit recursion limits for iterative workflows.
- Idempotency keys for external write operations.
Checkpointing does not automatically guarantee exactly-once execution of external side effects.
Tip: An interrupted node restarts from its beginning when resumed. Keep operations before
interrupt()safe to repeat, and protect external writes against duplicate execution.
When an external write times out, reconcile its outcome before attempting it again.
5. Treat observability as part of development
Enable LangSmith tracing with the appropriate credentials and project configuration.
export LANGSMITH_TRACING=true
export LANGSMITH_PROJECT=enterprise-agentSupply LANGSMITH_API_KEY through a secure environment configuration or secret manager.
Monitor model calls, tool failures, execution paths, token consumption, latency percentiles, approval outcomes, and costs.
Avoid recording sensitive customer data or secrets in traces.
The following diagram illustrates how production observations should influence future development.
Convert significant production failures into regression tests so the same defects are less likely to reappear.
6. Prefer simplicity, security, and maintainability
Avoid creating additional agents merely because multi-agent systems appear more sophisticated.
Every agent introduces additional context management, latency, cost, testing obligations, and possible failure modes.
Use version-controlled prompts, explicit state schemas, least-privilege credentials, documented tool contracts, and bounded execution.
Treat retrieved documents and tool responses as untrusted data. They must never be allowed to override application security policies.
A maintainable application is one that another engineer can understand, test, operate, and modify without reconstructing its original design decisions.
Learning resources
Official documentation and technical references
Use primary documentation when learning new APIs or upgrading existing applications.
| Resource | What to study |
|---|---|
| LangGraph documentation | Orchestration, persistence, interrupts, and execution |
| LangChain documentation | Models, tools, middleware, and agents |
| LangChain Academy | Structured courses and practical learning |
| LangSmith Evaluation | Datasets, experiments, and evaluators |
| Agent Server application structure | Deployment configuration |
| LangGraph GitHub | Source code, releases, and implementation details |
| Model Context Protocol | Standardized tool and context integrations |
| OpenEvals | Model-based evaluation |
| AgentEvals | Agent trajectory evaluation |
| OWASP GenAI Security Project | Security risks and defensive practices |
Pay particular attention to migration guides, release notes, deprecations, and API stability notices.
Avoid copying older tutorials without checking whether their imports and execution patterns remain supported.
A recommended 12-week learning roadmap
| Period | Focus | Deliverable |
|---|---|---|
| Weeks 1–2 | Agentic RAG | Document assistant with citations |
| Weeks 3–4 | SQL and enterprise tools | Read-only business intelligence assistant |
| Weeks 5–6 | Persistence and human approval | Resumable business workflow |
| Weeks 7–8 | MCP and multi-agent systems | Specialized integrated assistant |
| Weeks 9–10 | Evaluation, security, and resilience | Automated regression and failure tests |
| Weeks 11–12 | Deployment and monitoring | Production-oriented portfolio application |
For each application, maintain an architecture diagram, a README, installation instructions, representative evaluation results, security considerations, known limitations, and deployment configuration.
Explore distributed systems, database transactions, asynchronous Python, identity management, retrieval optimization, and infrastructure monitoring alongside agent frameworks.
These disciplines become increasingly important as applications move from demonstrations to enterprise environments.
Learning outcomes
Having completed this course, you should be able to:
- Design stateful applications using the LangGraph Graph API and Functional API.
- Build model-driven agents using LangChain’s current agent architecture.
- Implement conditional routing, parallel execution, subgraphs, and specialized multi-agent workflows.
- Combine agentic RAG, SQL databases, REST APIs, and MCP integrations.
- Manage persistent execution, conversation state, and cross-thread memory.
- Implement human approval, authorization, guardrails, and fault recovery.
- Stream application progress and model-generated responses.
- Evaluate agent quality, execution trajectories, operational performance, and security.
- Package, deploy, monitor, and continuously improve production-oriented applications.
- Select appropriate architectures and technologies for unfamiliar business requirements.
This is the final lesson of the course, but your development as an agentic AI engineer continues through practical implementation.
Your next milestone should be an application that real users can rely on, that other engineers can maintain, and whose reliability you can demonstrate through repeatable evidence.
The measure of an advanced agentic AI engineer is not how many agents they can create, but how effectively they can build intelligent systems that remain useful, controlled, secure, and dependable under real-world conditions.
Build an Approval-Gated Procurement Assistant
Build a procurement workflow that validates purchase requests, automatically accepts requests within an authorized spending limit, and pauses expensive requests for human approval. Use runtime context for the spending policy, conditional routing for decision-making, and checkpointing for interrupted execution. Test automatic acceptance, human approval, human rejection, and invalid purchase requests.
from dataclasses import dataclass
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt
@dataclass
class Context:
spending_limit: int
class PurchaseState(TypedDict, total=False):
item: str
amount: int
status: str
reason: str
def validate(state: PurchaseState):
# TODO: Reject invalid items and non-positive amounts.
raise NotImplementedError
def route(
state: PurchaseState,
runtime: Runtime[Context],
) -> Literal["accept", "review", "finish"]:
# TODO: Route according to validation and spending policy.
raise NotImplementedError
def accept(state: PurchaseState):
# TODO: Mark the request as accepted.
raise NotImplementedError
def review(
state: PurchaseState,
) -> Command[Literal["accept", "reject"]]:
# TODO: Interrupt execution and process the review decision.
raise NotImplementedError
def reject(state: PurchaseState):
# TODO: Mark the request as rejected.
raise NotImplementedError
# TODO: Register nodes and configure edges.
builder = StateGraph(
PurchaseState,
context_schema=Context,
)
# TODO: Compile using InMemorySaver.
# TODO: Invoke with unique thread IDs.
# TODO: Resume interrupted requests using Command.
# TODO: Verify all four required scenarios.from dataclasses import dataclass
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt
@dataclass
class Context:
spending_limit: int
class PurchaseState(TypedDict, total=False):
item: str
amount: int
status: str
reason: str
def validate(state: PurchaseState):
item = state.get("item", "")
amount = state.get("amount", 0)
if (
not isinstance(item, str)
or not item.strip()
or type(amount) is not int
or amount <= 0
):
return {
"status": "invalid",
"reason": "Item and positive integer amount required.",
}
return {"status": "validated", "reason": ""}
def route(
state: PurchaseState,
runtime: Runtime[Context],
) -> Literal["accept", "review", "finish"]:
if state["status"] == "invalid":
return "finish"
if state["amount"] <= runtime.context.spending_limit:
return "accept"
return "review"
def accept(state: PurchaseState):
return {
"status": "accepted",
"reason": "Purchase authorized.",
}
def review(
state: PurchaseState,
) -> Command[Literal["accept", "reject"]]:
decision = interrupt({
"type": "purchase_approval",
"item": state["item"],
"amount": state["amount"],
})
# Fail closed unless the response is explicitly True.
if decision is True:
return Command(goto="accept")
return Command(goto="reject")
def reject(state: PurchaseState):
return {
"status": "rejected",
"reason": "Purchase not authorized.",
}
builder = StateGraph(
PurchaseState,
context_schema=Context,
)
builder.add_node("validate", validate)
builder.add_node("accept", accept)
builder.add_node("review", review)
builder.add_node("reject", reject)
builder.add_edge(START, "validate")
builder.add_conditional_edges(
"validate",
route,
{
"accept": "accept",
"review": "review",
"finish": END,
},
)
builder.add_edge("accept", END)
builder.add_edge("reject", END)
graph = builder.compile(
checkpointer=InMemorySaver()
)
policy = Context(spending_limit=1000)
def run_purchase(
thread_id: str,
item: str,
amount: int,
decision: bool = False,
):
config = {
"configurable": {"thread_id": thread_id},
"recursion_limit": 10,
}
result = graph.invoke(
{"item": item, "amount": amount},
config,
context=policy,
)
if result.get("__interrupt__"):
print("Human approval requested:", item)
result = graph.invoke(
Command(resume=decision),
config,
context=policy,
)
return result["status"]
scenarios = [
("purchase-1", "Keyboard", 100, False, "accepted"),
("purchase-2", "Laptop", 1500, True, "accepted"),
("purchase-3", "Server", 5000, False, "rejected"),
("purchase-4", "", -100, False, "invalid"),
]
for thread_id, item, amount, decision, expected in scenarios:
actual = run_purchase(
thread_id,
item,
amount,
decision,
)
assert actual == expected, (actual, expected)
print(f"{thread_id}: {actual}")
print("All four scenarios passed.")Summary
- Choose agentic AI projects that solve measurable business problems rather than simply demonstrating model capabilities.
- Combine deterministic workflows with model-driven decisions instead of giving language models unrestricted control.
- Use specialized agents only when delegation, context isolation, or independent permissions provide measurable benefits.
- Treat persistent execution, authorization, human approval, and recovery as architectural requirements.
- Evaluate agent behavior using reproducible datasets, trajectory checks, business metrics, and production traces.
- Select infrastructure according to application requirements rather than adopting every available technology.
- Continue learning through official documentation, increasingly challenging projects, and systematic experimentation.