Every new judgment system eventually has to find its place in the process.
By Ed Bednar
Lab: 004
Technology: LangGraph, Anthropic Claude, SQLite
Prerequisites:
Lab 003: Judgment as a Service with Anthropic Claude and Pydantic
Estimated Time: 60-90 minutes
1.0 From Services to Processes
In this lab, we move from implementing individual AI services to orchestrating them within an enterprise business process.
Using LangGraph, we’ll compose enterprise systems, retrieval services, and AI judgment services into a single stateful workflow that demonstrates the next evolution of process architecture.
Each step invokes an existing enterprise capability. Some execute deterministic enterprise services, such as creating an order in the ERP system. Others invoke probabilistic AI judgment services, such as evaluating a supplier’s proposed delivery date.
As the workflow executes, it evaluates the result of each step, updates the current process state, and determines what happens next.
Process Orchestration with LangGraph
LangGraph is a framework for implementing stateful business processes that we’ll use to combine enterprise systems, AI services, and business logic into a single executable workflow.
The workflow is represented as a directed graph, where each node performs a well-defined business function and conditional edges determine the next step based on the outcome of the current one.
Throughout execution, LangGraph maintains a shared process state that captures the information required by each step. As services execute, they update that state while producing a complete, auditable record of the process.
The enterprise systems created in Lab 001, the retrieval infrastructure introduced in Lab 002, and the AI judgment services implemented in Lab 003 are reused without modification. LangGraph coordinates these existing capabilities, allowing them to execute as a single business process while preserving clear boundaries between the individual services.
A Note About the Probabilistic System Components
This lab demonstrates a realistic AI-assisted development workflow in which software is generated, evaluated, refined, and verified through successive prompts. The implementation produced by the initial Claude Code prompt1 serves as the starting point rather than the final solution.
As we work through the verification steps, we’ll evaluate the generated implementation under realistic operating conditions. Based on those observations, we’ll use two additional Claude Code prompts2,3 to refine the simulated environment.
We’ll then use a controlled test harness to verify a process path that the randomized simulation does not naturally exercise.
The verification section intentionally documents this iterative engineering process rather than presenting only the final implementation.
2.0 Architecture Blueprint
Figure 1 illustrates the enterprise process architecture implemented in this lab. The blueprint introduces the Enterprise Process Application together with the software assets and components required to define, execute, and manage the Order Fulfillment Process Service.
The blueprint also introduces a Process Audit Repository that records process execution for later analysis. In subsequent labs, this repository becomes the foundation for AI observability and human oversight.

3.0 Artifacts Created
Claude Code will generate five artifacts that collectively implement the LangGraph process introduced in this lab.
Together, these artifacts define the executable process, coordinate enterprise and AI services, record process execution, and provide utilities for running workflow instances.
3.1 orchestration/db.py
Implements the process audit repository.
The module:
- Initializes the SQLite database.
- Defines the order_events schema.
- Provides a reusable logging function that records:
- Process events.
- Execution status.
- Serialized process state.
- AI-generated decisions, confidence values, and rationales.
3.2 orchestration/graph.py
Implements the LangGraph process model.
The module:
- Defines the typed OrderState.
- Models the order fulfillment workflow as a stateful process graph.
- Implements the eight process nodes.
- Configures conditional routing between deterministic and probabilistic process steps.
- Compiles the executable LangGraph process.
3.3 orchestration/run.py
Executes a single order fulfillment process.
The utility:
- Initializes the audit repository.
- Generates a representative purchase order.
- Invokes the LangGraph process.
- Displays the resulting process status.
- Displays any AI-generated decisions produced during execution.
3.4 orchestration/run_batch.py
Executes multiple order fulfillment processes.
The utility:
- Processes twenty purchase orders in sequence.
- Summarizes the resulting process outcomes.
- Provides a mechanism for evaluating process behavior across randomized business scenarios.
3.5 Audit Repository
Stores the process audit trail.
The repository:
- Records every process event generated during execution.
- Captures node transitions, execution status, serialized process state, AI decisions, confidence – values, and supporting rationales.
- Is implemented using SQLite in this lab.
- Provides the foundation for AI observability and human oversight introduced in subsequent labs.
4.0 Generate the LangGraph Process Model
4.1 Prompt Overview
In this section, you will use Claude Code to generate the LangGraph process model introduced in the previous sections.
The prompt instructs Claude Code to:
- Create a SQLite audit repository for recording process events and AI decisions.
- Define a typed OrderState that carries business data and execution status throughout the workflow.
- Implement eight LangGraph nodes representing the order fulfillment process.
- Invoke the existing ERP, warehouse, retrieval, and AI judgment services without modifying their service boundaries.
- Model business exceptions and technical failures as explicit process outcomes.
- Configure conditional routing based on validation results and AI decisions.
- Compile the process with separate completion and exception end states.
- Create a runner for executing a single purchase order.
- Create a batch runner for executing twenty purchase orders and summarizing the results.
The process consists of the following nodes:
- receive_po
- calculate_service_level
- confirm_order
- wait_for_dispatch
- evaluate_acceptance
- process_invoice
- handle_exception
- close_order
Together, these nodes define the executable business process. Each node encapsulates a single business responsibility, while LangGraph manages state transitions and conditional routing between them.
4.2 Claude Code Prompt
Copy the following prompt into Claude Code exactly as shown.
Create an orchestration/ package and an audit/ directory.
First, create audit/trail.db by setting up the SQLite schema.
Create orchestration/db.py with a function init_db() that creates the database at
audit/trail.db with a single table: order_events with columns:
id (integer primary key autoincrement)
order_id (text)
event_type (text)
node_name (text)
status (text)
payload (text, stores JSON)
ai_decision (text, nullable)
ai_confidence (real, nullable)
ai_rationale (text, nullable)
created_at (text, ISO datetime)
Also implement log_event(order_id, event_type, node_name, status, payload_dict,
ai_decision=None, ai_confidence=None, ai_rationale=None) that inserts a row.
orchestration/graph.py
Build a LangGraph StateGraph.
Define the state schema as a TypedDict named OrderState with these fields:
po: dict
order_id: str
order_confirmation: dict
service_level: dict
sl_decision: dict
manifest: dict
accepted_items: list
qa_notes: str
acceptance_decision: dict
invoice: dict
invoice_decision: dict
error: str
status: str
All fields optional with defaults of None or empty string.
Implement these eight node functions, each takes state: OrderState, returns dict of updated fields:
receive_po(state): Validate that state['po'] has po_number, vendor_id, and line_items.
If missing any, set error and status='INVALID_PO', return.
Log the event. Otherwise set status='RECEIVED'.
calculate_service_level(state): Call erp_system.create_order(state['po']).
If OrderCreationError is raised, set error, status='ERP_FAILURE', log, return.
Then call erp_system.get_service_level(order_id, po's requested_delivery_date).
Store order_confirmation and service_level in state. Log the event.
confirm_order(state): Retrieve contract context from rag.pipeline using the line item
descriptions as the query. Call evaluate_service_level from llm.judgment.
Store the result as sl_decision. Log the event with ai_decision, ai_confidence, ai_rationale.
Route: accept -> wait_for_dispatch, negotiate -> handle_exception with NEGOTIATION_REQUIRED,
reject -> handle_exception with SL_REJECTED.
wait_for_dispatch(state): Call warehouse_system.create_shipping_manifest(order_id, items).
Call warehouse_system.notify_dispatch(manifest_id).
Store manifest in state. Log the event.
evaluate_acceptance(state): Build a realistic received_items list from the manifest.
Set qa_notes to a realistic QA inspection note string.
Retrieve contract context. Call evaluate_material_acceptance from llm.judgment.
Store acceptance_decision. Log with AI fields.
Route: accept or conditional_accept -> process_invoice, reject -> handle_exception with QA_REJECTION.
process_invoice(state): Call erp_system.get_invoice(order_id). Retrieve contract context.
Call evaluate_invoice from llm.judgment. Store invoice and invoice_decision. Log with AI fields.
Route: approve -> close_order, flag_for_review or reject -> handle_exception with INVOICE_EXCEPTION.
handle_exception(state): Log the exception with full state payload. Set status if not already set.
Print a summary of the exception.
close_order(state): Set status='COMPLETED'. Log the completion with full state payload.
Print a completion summary.
Wire the graph:
Add all eight nodes.
Set receive_po as the entry point.
receive_po -> calculate_service_level (or handle_exception on error).
calculate_service_level -> confirm_order (or handle_exception on error).
confirm_order -> conditional routing based on sl_decision.decision.
wait_for_dispatch -> evaluate_acceptance.
evaluate_acceptance -> conditional routing based on acceptance_decision.decision.
process_invoice -> conditional routing based on invoice_decision.decision.
handle_exception and close_order -> END.
Compile and return the graph.
orchestration/run.py
Import the compiled graph and po_generator.
Call init_db() to ensure the database exists.
Generate one PO using generate_po().
Print the PO number and requested delivery date.
Run the graph: result = graph.invoke({'po': po, 'order_id': '', ...all other fields empty})
Print the final status and, if any AI decisions were made, print them.
orchestration/run_batch.py
Run 20 POs through the graph in sequence.
Print a summary: total orders, count by final status, any AI decisions that caused exceptions.
orchestration/__init__.py
Import graph.5.0 Verify the Implementation
Verification in this lab is more involved than simply confirming that the graph compiles or that a single order reaches an end state. The process includes randomized enterprise-system behavior and probabilistic AI judgment services, so different runs can produce different outcomes.
The verification sequence evaluates the implementation at three levels:
- The LangGraph process executes and routes state correctly.
- The simulated enterprise services produce coherent business data.
- Every significant process path can be exercised, including paths that may not occur naturally during a small number of randomized runs.
The initial implementation also contains a limitation that prevents the process from progressing beyond its first AI judgment under most conditions.
Rather than replacing the generated code with a corrected version, we’ll use additional Claude Code prompts to refine the implementation and then verify the updated process.
5.1 Run the Order Fulfillment Process
Start by running one generated purchase order through the graph.
Command
python3.11 orchestration/run.pyExample Output
Traceback (most recent call last):
File ".../orchestration/run.py", line 3, in <module>
from orchestration.db import init_db
ModuleNotFoundError: No module named 'orchestration'Verify That
The initial command fails because run.py is part of the orchestration package but is being executed as a standalone script. In that mode, Python does not resolve the project directory as the package root.
Run the module through the package instead:
Command
python3.11 -m orchestration.runExample Output
Loading weights: 100%|…| 103/103 [00:00<00:00, 7991.81it/s]
Generated PO-46169 — requested delivery date: 2026-08-24
[EXCEPTION] order_id='ORD-45276' status=NEGOTIATION_REQUIRED error=''
Final status: NEGOTIATION_REQUIRED
sl_decision: {
'decision': 'negotiate',
'confidence': 0.72,
'rationale': 'The vendor cannot cover the full PO quantity by the requested date...',
'suggested_counter_date': '2026-09-14'
}Verify That
- The embedding model loads successfully.
- A purchase order is generated.
- The graph creates an ERP order.
- The service-level judgment returns a validated decision.
- LangGraph routes negotiate to handle_exception.
- The final process status is NEGOTIATION_REQUIRED.
The empty error field is expected. This path represents a business exception created by an AI decision, not a technical failure.
5.2 Run Multiple Orders
Because the ERP stubs and judgment services produce variable results, run the graph several times.
Command
for i in $(seq 1 5); do
echo
echo "===== RUN $i ====="
python3.11 -m orchestration.run
doneExample Output
===== RUN 1 =====
[EXCEPTION] order_id='ORD-41136' status=NEGOTIATION_REQUIRED error=''
Final status: NEGOTIATION_REQUIRED
===== RUN 2 =====
[EXCEPTION] order_id='ORD-74021' status=SL_REJECTED error=''
Final status: SL_REJECTED
===== RUN 3 =====
[EXCEPTION] order_id='PO-84547' status=ERP_FAILURE error='Inventory unavailable'
Final status: ERP_FAILUREVerify That
The graph produces valid exception outcomes, including:
NEGOTIATION_REQUIRED
SL_REJECTED
ERP_FAILUREHowever, if nearly every successful ERP order stops at confirm_order, the downstream process nodes are not being exercised:
wait_for_dispatch
evaluate_acceptance
process_invoice
close_orderThis does not necessarily indicate a LangGraph defect. It may indicate that the simulated enterprise data is causing the AI judgment service to recommend negotiation or rejection for most orders.
5.3 Inspect the Service-Level Data
Inspect the ERP implementation that produces the order confirmation and service-level commitment.
Command
sed -n '1,280p' stubs/erp_system.pyExample Output
def create_order(po: dict) -> dict:
line_items = po.get("line_items", [])
requested_quantity = sum(item.get("quantity", 0) for item in line_items) or 1
confirmed_quantity = random.randint(
max(1, int(requested_quantity * 0.85)),
requested_quantity,
)
return {
"order_id": order_id,
"confirmed_quantity": confirmed_quantity,
"estimated_ship_date": estimated_ship_date,
}
def get_service_level(order_id: str, requested_delivery_date: str) -> dict:
available_quantity = random.randint(50, 500)
return {
"committed_date": committed.isoformat(),
"confidence_score": confidence_score,
"available_quantity": available_quantity,
}Verify That
The two ERP operations are not describing the same business reality.
create_order() calculates confirmed_quantity from the purchase order, but get_service_level() generates available_quantity independently. The judgment service can therefore receive contradictory values such as:
Requested quantity: 722
Confirmed quantity: 680
Available quantity: 214The AI is behaving reasonably when it interprets that combination as a material fulfillment risk.
The process is not broken. The simulated enterprise data contract is inconsistent.
Use Claude Code to correct the relationship between the order confirmation and the service-level commitment.
Claude Code Prompt #2
Update the ERP service-level implementation so that service-level commitments
are internally consistent with the order that was just created.
In stubs/erp_system.py:
- Modify get_service_level() to accept confirmed_quantity as an additional parameter.
- Generate available_quantity relative to confirmed_quantity rather than as an
unrelated random value.
- Approximately 70% of orders should have full availability
(available_quantity == confirmed_quantity).
- Approximately 20% should have a modest shortfall, between 85% and 99% of
confirmed quantity.
- Approximately 10% should have a significant shortfall, below 85% of confirmed
quantity.
- Preserve the existing delivery-date and confidence-score behavior.
In orchestration/graph.py:
- Update the call to get_service_level() to pass
order_confirmation["confirmed_quantity"].
- Make no other changes to the process graph or routing logic.After Claude Code completes the change, inspect both the function and its caller.
Command
grep -n "def get_service_level" -A25 stubs/erp_system.pygrep -n "get_service_level" -A6 -B3 orchestration/graph.pyVerify That
- get_service_level() accepts confirmed_quantity.
- available_quantity is calculated relative to that quantity.
- calculate_service_level() passes the confirmed quantity returned by create_order().
- No graph nodes, edges, or routing rules were changed.
5.4 Re-run the Process After the First Correction
Run several more orders.
Command
for i in $(seq 1 5); do
echo
echo "===== RUN $i ====="
python3.11 -m orchestration.run
doneExample Output
Generated PO-82947 — requested delivery date: 2026-08-05
[EXCEPTION] order_id='ORD-41136' status=NEGOTIATION_REQUIRED error=''
Final status: NEGOTIATION_REQUIRED
sl_decision: {
'decision': 'negotiate',
'confidence': 0.72,
'rationale': 'The PO requests 326 units, but the vendor has committed only 280...'
}Verify That
The service-level commitment is now based on the confirmed order quantity rather than the original purchase order. However, many orders may still return a negotiate decision.
This occurs because create_order() intentionally confirms only 85% to 100% of the requested quantity. Even if the available quantity fully satisfies the confirmed order, the confirmed quantity itself may represent a material reduction from the customer’s original request. So the AI judgment service correctly recommends negotiation.
Now we’ll use Claude Code to refine the simulated data generation at the source. And after applying the refinement, you’ll regenerate the implementation and rerun the verification steps.
The resulting distribution should produce a representative mix of accepted, negotiated, and rejected service-level decisions while preserving the overall process architecture.
Claude Code Prompt #3
Update stubs/erp_system.py so that the simulated ERP order confirmation and
service-level commitment produce a realistic distribution that allows the
process to proceed beyond the first AI judgment.
In create_order():
- Generate confirmed_quantity relative to the total requested PO quantity.
- Approximately 80% of successful order creations should confirm the full
requested quantity.
- Approximately 15% should confirm between 90% and 99% of the requested quantity.
- Approximately 5% should confirm between 75% and 89% of the requested quantity.
- Preserve the existing 10% order-creation failure behavior.
In get_service_level():
- Continue accepting confirmed_quantity.
- Approximately 80% of calls should return
available_quantity == confirmed_quantity.
- Approximately 15% should return between 90% and 99% of confirmed quantity.
- Approximately 5% should return between 75% and 89% of confirmed quantity.
- Preserve the existing committed-date and confidence behavior.
Do not modify llm/judgment.py or any LangGraph routing logic.5.5 Verify the Revised ERP Distribution
Before running the graph again, inspect the ERP outputs directly.
Command
python3.11 - <<'PY'
from stubs import erp_system, po_generator
for i in range(10):
po = po_generator.generate_po()
requested = sum(item["quantity"] for item in po["line_items"])
try:
confirmation = erp_system.create_order(po)
except erp_system.OrderCreationError as exc:
print(i + 1, "ERP_FAILURE", exc)
continue
service_level = erp_system.get_service_level(
confirmation["order_id"],
po["requested_delivery_date"],
confirmation["confirmed_quantity"],
)
print(
i + 1,
"requested=", requested,
"confirmed=", confirmation["confirmed_quantity"],
"available=", service_level["available_quantity"],
"date=", service_level["committed_date"],
"confidence=", service_level["confidence_score"],
)
PYExample Output
1 requested= 722 confirmed= 722 available= 722 date= 2026-08-23 confidence= 0.84
2 requested= 525 confirmed= 525 available= 525 date= 2026-08-25 confidence= 0.70
3 requested= 487 confirmed= 487 available= 487 date= 2026-08-04 confidence= 0.95
4 requested= 679 confirmed= 679 available= 679 date= 2026-07-19 confidence= 0.92
5 requested= 674 confirmed= 674 available= 657 date= 2026-08-06 confidence= 0.94
6 requested= 1010 confirmed= 1010 available= 912 date= 2026-08-21 confidence= 0.71
7 requested= 69 confirmed= 69 available= 69 date= 2026-07-20 confidence= 0.94
8 requested= 864 confirmed= 802 available= 748 date= 2026-07-18 confidence= 0.76
9 requested= 680 confirmed= 680 available= 680 date= 2026-07-18 confidence= 0.89
10 requested= 1273 confirmed= 1273 available= 1273 date= 2026-07-18 confidence= 0.77Verify That
- Several orders have matching requested, confirmed, and available quantities.
- Some orders contain modest availability shortfalls.
- Some orders contain larger confirmation or availability shortfalls.
- Confidence scores and committed dates remain variable.
- The data can now produce both successful and exception scenarios.
This verifies the simulation independently of the LLM and the process graph.
5.6 Run a Larger Batch of Orders
Run the twenty-order batch defined by the implementation.
Command
python3.11 -m orchestration.run_batchExample Output
[EXCEPTION] order_id='ORD-98416' status=NEGOTIATION_REQUIRED error=''
[EXCEPTION] order_id='ORD-43702' status=INVOICE_EXCEPTION error=''
[EXCEPTION] order_id='PO-84547' status=ERP_FAILURE error='Invalid purchasing organization'
...
=== Batch Summary ===
Total orders: 20
By final status:
NEGOTIATION_REQUIRED: 15
ERP_FAILURE: 3
INVOICE_EXCEPTION: 2
AI decisions that caused exceptions: 17Verify That
- Twenty orders execute without an unhandled graph failure.
- ERP failures route to handle_exception.
- Service-level negotiations route to handle_exception.
- At least some orders proceed through material acceptance and invoice evaluation.
- Invoice exceptions demonstrate that the process reached process_invoice.
- The batch runner summarizes final process statuses.
The absence of a COMPLETED result does not prove that close_order is broken. It means that no randomized scenario in this particular batch produced all three required decisions:
service level: accept
material acceptance: accept or conditional_accept
invoice: approveThe batch also reveals two additional characteristics of the simulation.
First, the AI judgment service applies a conservative service-level policy. It frequently treats confidence values below approximately 0.90 or 0.95 as requiring negotiation, even when quantities and dates match.
Second, the invoice stub generates invoices independently of the original purchase order. The resulting invoice can contain unrelated part numbers, descriptions, quantities, and prices. The AI correctly identifies these as invoice exceptions.
These outcomes are legitimate process results, but they make natural execution of the successful path less likely.
5.7 Verify the Successful Path with a Controlled Test Harness
Use a controlled test harness to verify the complete path without modifying the application files.
The harness replaces the randomized ERP responses and probabilistic judgment results for one execution only. When the command finishes, the original implementations are automatically restored.
Command
python3.11 - <<'PY'
from unittest.mock import patch
from llm import judgment
from orchestration.db import init_db
from orchestration.graph import graph
from stubs import erp_system, po_generator
init_db()
po = po_generator.generate_po()
requested_quantity = sum(item["quantity"] for item in po["line_items"])
order_confirmation = {
"order_id": "ORD-COMPLETE-TEST",
"confirmed_quantity": requested_quantity,
"estimated_ship_date": po["requested_delivery_date"],
}
service_level = {
"committed_date": po["requested_delivery_date"],
"confidence_score": 0.98,
"available_quantity": requested_quantity,
}
service_level_decision = judgment.ServiceLevelDecision(
decision="accept",
confidence=0.99,
rationale="Controlled verification result for the successful process path.",
suggested_counter_date=None,
)
material_decision = judgment.MaterialAcceptanceDecision(
decision="accept",
defect_flags=[],
rationale="Controlled verification result: all received material is acceptable.",
)
invoice_decision = judgment.InvoiceDecision(
decision="approve",
variance_detected=False,
variance_amount=None,
rationale="Controlled verification result: invoice approved.",
)
with (
patch.object(
erp_system,
"create_order",
return_value=order_confirmation,
),
patch.object(
erp_system,
"get_service_level",
return_value=service_level,
),
patch.object(
judgment,
"evaluate_service_level",
return_value=service_level_decision,
),
patch.object(
judgment,
"evaluate_material_acceptance",
return_value=material_decision,
),
patch.object(
judgment,
"evaluate_invoice",
return_value=invoice_decision,
),
):
result = graph.invoke({"po": po})
print()
print("Final status:", result["status"])
print("Service-level decision:", result["sl_decision"]["decision"])
print("Material decision:", result["acceptance_decision"]["decision"])
print("Invoice decision:", result["invoice_decision"]["decision"])
PYExample Output
[COMPLETED] order_id='ORD-COMPLETE-TEST' po_number='PO-48217'
Final status: COMPLETED
Service-level decision: accept
Material decision: accept
Invoice decision: approveVerify That
The graph traverses the complete successful path:
receive_po
→ calculate_service_level
→ confirm_order
→ wait_for_dispatch
→ evaluate_acceptance
→ process_invoice
→ close_order
→ ENDThis is not a substitute for randomized testing. It is targeted verification of a process path that the random simulation did not naturally reach during the batch.
Controlled test data is particularly important when verifying:
- Low-Probability Paths
- Exception Handling
- Failover Behavior
- Recovery Procedures
- Process Completion Conditions
- Probabilistic Services
5.8 Verify the Completed Order in the Audit Trail
Confirm that the controlled order was recorded at each process step.
Command
python3.11 - <<'PY'
import sqlite3
conn = sqlite3.connect("audit/trail.db")
rows = conn.execute(
"""
SELECT node_name, event_type, status
FROM order_events
WHERE order_id = 'ORD-COMPLETE-TEST'
ORDER BY id
"""
).fetchall()
for row in rows:
print(row)
PYExample Output
('calculate_service_level', 'SERVICE_LEVEL_CALCULATED', 'SERVICE_LEVEL_CALCULATED')
('confirm_order', 'SERVICE_LEVEL_DECISION', 'SL_ACCEPTED')
('wait_for_dispatch', 'DISPATCH_NOTIFIED', 'DISPATCHED')
('evaluate_acceptance', 'MATERIAL_ACCEPTANCE_DECISION', 'MATERIAL_ACCEPTED')
('process_invoice', 'INVOICE_DECISION', 'INVOICE_APPROVED')
('close_order', 'ORDER_COMPLETED', 'COMPLETED')Verify That
- Every downstream node executed.
- The service-level decision was recorded as SL_ACCEPTED.
- The warehouse dispatch was recorded.
- Material acceptance was recorded.
- Invoice approval was recorded.
- close_order recorded the final COMPLETED event.
The initial receive_po event may be stored using the purchase-order number before the ERP order identifier exists. The remaining events use ORD-COMPLETE-TEST.
5.9 Verify All Process Nodes
Query the audit trail for node execution counts.
Command
python3.11 - <<'PY'
import sqlite3
conn = sqlite3.connect("audit/trail.db")
rows = conn.execute(
"""
SELECT node_name, COUNT(*)
FROM order_events
GROUP BY node_name
ORDER BY node_name
"""
).fetchall()
for node_name, count in rows:
print(f"{node_name}: {count}")
PYExample Output
calculate_service_level: 34
close_order: 1
confirm_order: 31
evaluate_acceptance: 4
handle_exception: 30
process_invoice: 4
receive_po: 34
wait_for_dispatch: 4Verify That
All eight process nodes appear:
receive_po
calculate_service_level
confirm_order
wait_for_dispatch
evaluate_acceptance
process_invoice
handle_exception
close_orderConditional routing will cause some nodes to execute more frequently than others.
5.10 Verify AI Decisions in the Audit Trail
Inspect the judgment decisions and rationales recorded by the process.
Command
python3.11 - <<'PY'
import sqlite3
conn = sqlite3.connect("audit/trail.db")
rows = conn.execute(
"""
SELECT
node_name,
status,
ai_decision,
ai_confidence,
substr(ai_rationale, 1, 120)
FROM order_events
WHERE ai_decision IS NOT NULL
ORDER BY id DESC
LIMIT 15
"""
).fetchall()
for row in rows:
print(row)
PYExample Output
('process_invoice', 'INVOICE_APPROVED', 'approve', None,
'Controlled verification result: invoice approved.')
('evaluate_acceptance', 'MATERIAL_ACCEPTED', 'accept', None,
'Controlled verification result: all received material is acceptable.')
('confirm_order', 'SL_ACCEPTED', 'accept', 0.99,
'Controlled verification result for the successful process path.')
('confirm_order', 'NEGOTIATION_REQUIRED', 'negotiate', 0.72,
'The vendor cannot fully satisfy the requested quantity...')Verify That
- confirm_order records the service-level decision.
- evaluate_acceptance records the material-acceptance decision.
- process_invoice records the invoice decision.
- AI rationales are retained with the process event.
- Service-level confidence is recorded.
- None is expected for material and invoice confidence because those Pydantic models do not define confidence fields.
This creates an auditable link between probabilistic judgment and deterministic process routing.
5.11 Verify Invalid Purchase Order Routing
Use an invalid purchase order to test validation and exception routing.
Command
python3.11 - <<'PY'
from orchestration.db import init_db
from orchestration.graph import graph
init_db()
result = graph.invoke(
{
"po": {
"po_number": "PO-INVALID-TEST",
"line_items": [],
}
}
)
print("Final status:", result["status"])
print("Error:", result["error"])
PYExample Output
[EXCEPTION] order_id='PO-INVALID-TEST' status=INVALID_PO error='PO is missing required fields: vendor_id, line_items'
Final status: INVALID_PO
Error: PO is missing required fields: vendor_id, line_itemsVerify That
- receive_po detects the missing vendor_id.
- An empty line_items list is treated as invalid.
- The graph does not invoke the ERP service.
- The process routes directly to handle_exception.
- The final status is INVALID_PO.
- The validation error remains in process state.
Now confirm the exception path in the audit trail.
Command
python3.11 - <<'PY'
import sqlite3
conn = sqlite3.connect("audit/trail.db")
rows = conn.execute(
"""
SELECT node_name, event_type, status
FROM order_events
WHERE order_id = 'PO-INVALID-TEST'
ORDER BY id
"""
).fetchall()
for row in rows:
print(row)
PYExample Output
('receive_po', 'PO_VALIDATION', 'INVALID_PO')
('handle_exception', 'EXCEPTION', 'INVALID_PO')Verify That
The invalid-input path is:
receive_po
→ handle_exception
→ ENDThe process rejects invalid state before calling downstream enterprise or AI services.
6.0 Lab Summary
In this lab, you implemented an executable process that coordinates deterministic enterprise services and probabilistic AI reasoning within a single workflow.
6.1 What You Built
During this lab, you:
- Implemented a LangGraph process that models the end-to-end order fulfillment workflow.
- Defined a typed process state that carries business data and execution status throughout the workflow.
- Coordinated enterprise services, retrieval services, and AI judgment services as reusable process nodes.
- Implemented conditional routing based on AI-generated business decisions and deterministic system outcomes.
- Recorded process execution, AI decisions, confidence values, and supporting rationales in an auditable repository.
- Executed both individual and batch process instances to evaluate the behavior of the workflow across multiple business scenarios.
Unlike the previous labs, verification also demonstrated an important characteristic of AI-assisted software engineering. The initial implementation generated by Claude Code successfully produced the requested process, but verification identified opportunities to improve the simulated enterprise environment.
Additional prompts refined the generated implementation by producing more consistent ERP behavior, while a controlled test harness verified a successful process path that was not naturally exercised during randomized execution.
These refinements demonstrated a realistic development workflow in which AI-generated software is evaluated, refined, and verified through successive prompts and targeted testing. The underlying LangGraph process architecture remained unchanged.
Most importantly, this lab demonstrated that enterprise processes provide the structure that coordinates both deterministic systems and probabilistic AI capabilities within a single executable architecture.
7.0 Next Lab
The process audit repository introduced in this lab will become the foundation for the next stage of the architecture.
In Lab 005: Human Oversight by Design with Streamlit, we’ll build an operational interface that enables AI-assisted decisions to be observed, audited, and, when necessary, overridden by human operators.
With human oversight, you’ll be able to:
- Maintain accountability for AI-assisted business processes.
- Monitor process execution in real time.
- Review AI decisions, confidence scores, and supporting rationales.
- Investigate business exceptions requiring human intervention.
- Record human overrides as part of the permanent audit trail.
