AI judgment becomes useful when systems can depend on it.
By Ed Bednar
Lab: 003
Technology: Claude Code, Python, Anthropic Claude, Pydantic
Prerequisites:
1. Lab 002: Context as Infrastructure with Qdrant, RAG, and Hugging Face
Estimated Time: 45-60 minutes
1.0 Introduction
Within our simulated manufacturing enterprise, purchase orders, shipments, and invoices must be evaluated against supplier contracts before they can be processed. These decisions depend on enterprise context, but they also require judgment.
This lab introduces AI judgment services that perform those evaluations using Anthropic Claude while exposing stable, typed contracts to enterprise applications.
1.1 Judgment as an Enterprise Service
Rather than embedding prompts throughout applications, AI capabilities should be exposed as reusable enterprise services that receive enterprise data and return structured business decisions.
This architectural boundary isolates prompt engineering, model selection, and response validation behind a stable service interface. Applications, workflows, and AI agents consume business capabilities rather than interacting directly with language models.
Within this lab, three judgment services are introduced:
- Service-Level Evaluation determines whether a supplier’s delivery commitment satisfies contractual obligations.
- Material Acceptance evaluates whether delivered components satisfy contractual quality standards.
- Invoice Evaluation determines whether supplier invoices conform to negotiated pricing and contractual payment terms.
Each service retrieves relevant enterprise context from the retrieval infrastructure developed in Lab 002 before performing AI-assisted reasoning.
1.2 Structured Outputs with Pydantic
Large language models produce probabilistic outputs, while enterprise applications depend on predictable interfaces and well-defined data contracts.
Left unconstrained, an LLM may return explanations, conversational text, or data that does not conform to the interface expected by downstream applications.
This lab addresses that challenge by introducing Pydantic, which validates AI responses against explicit data models before they are exposed to the rest of the enterprise.
1.3 Structured Data Contracts
Pydantic is a Python library for defining strongly typed data models. It validates AI responses against those models, ensuring that the data exposed to enterprise applications conforms to a well-defined contract.
In this lab, each judgment service returns a dedicated Pydantic model representing a specific business decision.
For example, the service-level evaluation returns a decision indicating whether the supplier commitment should be accepted, negotiated, or rejected, together with supporting information such as confidence, rationale, and an optional counterproposal.
Enterprise applications consume these validated models rather than raw language model output.
2.0 Architecture Blueprint
Lab 002 established the Enterprise Knowledge Application, providing a shared retrieval capability that supplies enterprise context to AI-enabled applications.
This lab extends the architecture by introducing the Enterprise Judgment Application, a reusable set of AI judgment services that encapsulate business decisions behind well-defined enterprise service interfaces, shown in Figure 2-1.

Each judgment service combines retrieved enterprise context with a large language model to evaluate a specific business scenario, such as supplier service levels, material acceptance, or invoice review.
As with the Enterprise Knowledge Application introduced in the previous lab, these judgment services are shared enterprise capabilities that can be reused across multiple business systems rather than embedded within individual applications.
3.0 Artifacts Created
Claude Code will generate three artifacts that collectively implement the AI judgment services introduced in this lab.
Together, these artifacts define the data models, implement the judgment services, and provide a utility for comparing language model responses.
3.1 llm/judgment.py
Implements the AI judgment services and their associated Pydantic response models.
The module:
- Returns a typed business decision to the calling application.
- Defines the Pydantic models for each business decision.
- Retrieves the enterprise context required for evaluation.
- Invokes the configured language model.
- Validates the returned response against the corresponding data contract.
3.2 llm/compare.py
Constructs representative business scenarios and executes all three judgment services against multiple language model backends.
The utility:
- Demonstrates how multiple AI implementations can be evaluated behind a common service interface.
- Executes identical business scenarios against each configured language model.
- Records the returned decisions, confidence values, rationale, and execution latency.
- Enables side-by-side comparison of different model implementations.
3.3 llm/init.py
Initializes the package and exposes the judgment services for use by the orchestration components introduced in subsequent implementation labs.
4.0 Generate the AI Judgment Services
In this section, you will use Claude Code to generate the AI judgment services introduced in the previous sections.
4.1 Prompt Overview
The prompt instructs Claude Code to:
- Create a set of enterprise AI judgment services organized within the llm package.
- Define strongly typed Pydantic models representing business decisions.
- Support both Anthropic Claude and Hugging Face language model backends through a configurable interface.
- Implement service-level evaluation using enterprise purchase order data, supplier commitments, and retrieved contract context.
- Implement material acceptance evaluation using warehouse information, quality inspection results, and retrieved contract context.
- Implement invoice evaluation using purchase orders, invoices, order confirmations, and retrieved contract context.
- Parse language model responses into validated Pydantic objects.
- Safely handle malformed AI responses by returning valid fallback decisions.
- Generate a comparison utility that executes identical business scenarios against multiple language model providers and reports differences in decisions, rationale, confidence, and latency.
- Expose the judgment services for use by subsequent implementation labs.
4.2 Claude Code Prompt
Copy the following prompt into Claude Code exactly as shown.
Create a llm/ package with two files.
llm/judgment.py
Define three Pydantic output models:
ServiceLevelDecision:
decision (Literal["accept","negotiate","reject"])
confidence (float)
rationale (str)
suggested_counter_date (Optional[str])
MaterialAcceptanceDecision:
decision (Literal["accept","conditional_accept","reject"])
defect_flags (list[str])
rationale (str)
InvoiceDecision:
decision (Literal["approve","flag_for_review","reject"])
variance_detected (bool)
variance_amount (Optional[float])
rationale (str)
Read the environment variable LLM_BACKEND.
Default to "anthropic" when the variable is not present.
Implement a private helper:
_call_anthropic(system_prompt: str, user_prompt: str) -> str
Use the Anthropic Python SDK and Claude Sonnet 4. Call the Messages API and return only the response text.
Implement a private helper:
_call_huggingface(system_prompt: str, user_prompt: str) -> str
Use huggingface_hub.InferenceClient with the model:
mistralai/Mistral-7B-Instruct-v0.3
Return only the response text.
Both helper functions must instruct the model to return only valid JSON with no markdown, code fences, commentary, or explanation.
Implement a helper function that safely parses model responses.
If the response contains Markdown code fences, remove them before attempting JSON parsing.
If parsing fails, return a safe fallback response rather than raising an exception.
Implement three public enterprise judgment services.
evaluate_service_level(
po: dict,
service_level: dict,
contract_context: list[str]
) -> ServiceLevelDecision
Build a prompt containing:
- purchase order
- supplier commitment
- retrieved contract clauses
Ask the model to determine whether the supplier commitment should be accepted, negotiated, or rejected.
Return a validated ServiceLevelDecision.
evaluate_material_acceptance(
manifest: dict,
received_items: list,
qa_notes: str,
contract_context: list[str]
) -> MaterialAcceptanceDecision
Build a prompt containing:
- shipping manifest
- received materials
- QA inspection notes
- retrieved contract clauses
Ask the model whether the shipment should be accepted, conditionally accepted, or rejected.
Return a validated MaterialAcceptanceDecision.
evaluate_invoice(
po: dict,
invoice: dict,
order_confirmation: dict,
contract_context: list[str]
) -> InvoiceDecision
Build a prompt containing:
- purchase order
- supplier invoice
- order confirmation
- retrieved contract clauses
Ask the model to determine whether the invoice should be approved, flagged for review, or rejected.
Detect pricing variances where appropriate.
Return a validated InvoiceDecision.
Each public function must:
- invoke the configured language model backend
- parse the returned JSON
- validate the response with Pydantic
- return a valid Pydantic object
If validation or parsing fails, return a valid fallback object explaining the failure in the rationale field.
------------------------------------------------------------
Create:
llm/compare.py
Import os before importing the judgment module.
Execute all three judgment services twice:
- once with LLM_BACKEND=anthropic
- once with LLM_BACKEND=huggingface
Build one realistic manufacturing scenario containing:
- a purchase order for steel components
- a supplier commitment four days beyond the requested delivery date
- a shipment with minor quality concerns
- an invoice containing a five percent pricing variance
Retrieve contract context from rag.pipeline before executing each judgment service.
For every execution print:
- judgment service
- backend
- decision
- confidence or variance information
- rationale
- latency in milliseconds
At the end produce a summary showing where both backends agreed and where they differed.
------------------------------------------------------------
Create:
llm/__init__.py
Import judgment.5.0 Verify the Implementation
Unlike previous labs, this verification focuses on both implementation correctness and the architectural behavior of probabilistic systems.
So the objective is not to reproduce identical outputs, but to verify that the services produce valid structured responses while remaining stable under varying AI behavior.
5.1 Verify Project Structure
Begin by confirming that Claude Code generated all of the required source files for the judgment services.
Command
python3.11 - <<'EOF'
from pathlib import Path
files = [
"llm/__init__.py",
"llm/judgment.py",
"llm/compare.py",
]
for file in files:
status = "FOUND" if Path(file).exists() else "MISSING"
print(f"{file}: {status}")
EOFExample Output
llm/__init__.py: FOUND
llm/judgment.py: FOUND
llm/compare.py: FOUNDVerify That
- All three source files were created successfully.
- The llm package is present.
- No files are reported as missing.
5.2 Verify the Pydantic Models
Confirm that the three Pydantic models load successfully and expose the expected response types.
Command
python3.11 - <<'EOF'
from llm.judgment import (
ServiceLevelDecision,
MaterialAcceptanceDecision,
InvoiceDecision,
)
print(ServiceLevelDecision.model_json_schema()["title"])
print(MaterialAcceptanceDecision.model_json_schema()["title"])
print(InvoiceDecision.model_json_schema()["title"])
EOF
Example Output
ServiceLevelDecision
MaterialAcceptanceDecision
InvoiceDecisionVerify That
- All three Pydantic models load successfully.
- The expected judgment models are available.
- No import or validation errors occur.
5.3 Verify Model Validation
Verify that Pydantic enforces the allowable decision values defined by the data contract.
Command
python3.11 - <<'EOF'
from pydantic import ValidationError
from llm.judgment import ServiceLevelDecision
try:
ServiceLevelDecision(
decision="maybe",
confidence=0.75,
rationale="Test"
)
except ValidationError as error:
print("Validation failed")
print(error.errors()[0]["msg"])
EOFExample Output
Validation failed
Input should be 'accept', 'negotiate', or 'reject'Verify That
- Invalid decision values are rejected.
- Pydantic enforces the defined response contract.
- Only supported business decisions are accepted.
5.4 Verify Backend Configuration
Confirm that both supported language model providers can be selected through configuration.
Command
python3.11 - <<'EOF'
import os
for backend in ["anthropic", "huggingface"]:
os.environ["LLM_BACKEND"] = backend
print(f"Configured backend: {os.environ['LLM_BACKEND']}")
EOFExample Output
Configured backend: anthropic
Configured backend: huggingfaceVerify That
- Both supported backends can be configured.
- Backend selection is controlled through the LLM_BACKEND environment variable.
- No code changes are required to switch providers.
5.5 Verify the Judgment Services
Execute all three judgment services using both supported language model providers.
Command
python3.11 -m llm.compareExample Output
[evaluate_service_level] backend=anthropic
decision: negotiate
confidence=0.72
latency_ms: 12419.6
[evaluate_material_acceptance] backend=anthropic
decision: conditional_accept
latency_ms: 12668.9
[evaluate_invoice] backend=anthropic
decision: flag_for_review
variance_amount=1331.5
latency_ms: 10390.8
[evaluate_service_level] backend=huggingface
decision: negotiate
confidence=0.81
latency_ms: 2000.9
...
=== Backend agreement summary ===
evaluate_service_level: AGREE
evaluate_material_acceptance: AGREE
evaluate_invoice: AGREEVerify That
- All three judgment services execute successfully.
- Both Anthropic Claude and Hugging Face complete every evaluation.
- Each response is converted into a valid Pydantic model.
- Latency information is reported for every evaluation.
- A backend agreement summary is produced.
5.6 Verify Safe Response Parsing
Confirm that malformed language model responses do not cause the application to fail.
Command
python3.11 - <<'EOF'
from unittest.mock import patch
from llm.judgment import evaluate_service_level
po = {
"requested_delivery_date": "2026-07-14",
"line_items": [],
}
service_level = {
"committed_date": "2026-07-18",
"confidence_score": 0.81,
"available_quantity": 340,
}
with patch("llm.judgment._call_llm", return_value="not valid json"):
result = evaluate_service_level(
po,
service_level,
["Sample contract clause"],
)
print(result.decision)
print(result.rationale)
EOF
Example Output
negotiate
Failed to parse LLM response as valid JSON...Verify That
- Invalid language model responses do not terminate the application.
- A valid fallback response is returned.
- Parsing failures are isolated within the judgment service.
5.7 Verify Response Serialization
Confirm that judgment results can be serialized into standard Python data structures for downstream processing.
Command
python3.11 - <<'EOF'
from pprint import pprint
from llm.judgment import ServiceLevelDecision
decision = ServiceLevelDecision(
decision="negotiate",
confidence=0.72,
rationale="Delivery commitment requires review.",
suggested_counter_date="2026-07-16",
)
pprint(decision.model_dump())
EOF
Example Output
{
'confidence': 0.72,
'decision': 'negotiate',
'rationale': 'Delivery commitment requires review.',
'suggested_counter_date': '2026-07-16'
}Verify That
- Pydantic models serialize successfully.
- Structured business decisions can be exchanged between application components.
- The judgment services expose predictable enterprise data structures.
6.0 Lab Summary
This lab built on the retrieval infrastructure in Lab 002 by incorporating AI judgment services that reason over that retrieval context while exposing results through strongly typed data models.
Pydantic validates every response returned by the language model, ensuring that downstream applications consume structured business decisions rather than unconstrained AI output.
6.1 Nondeterminism
An important architectural concern is that enterprise AI systems must accommodate probabilistic components.
This is easier said than done.
Large language models may produce different reasoning, confidence values, or recommendations when presented with identical inputs.
This behavior must be managed through validation so that enterprise systems can remain reliable when the components performing the reasoning are inherently probabilistic.
6.2 What You Built
During this lab, you:
- Created three enterprise AI judgment services for evaluating supplier commitments, material acceptance, and supplier invoices.
- Implemented strongly typed Pydantic models that define the data contracts returned by each judgment service.
- Integrated Anthropic Claude into reusable enterprise services that encapsulate AI reasoning.
- Implemented configurable support for multiple language model providers through a common service interface.
- Validated language model responses before exposing them to downstream applications.
- Implemented safe response parsing and fallback behavior for malformed AI responses.
- Compared multiple language model implementations using representative business scenarios.
- Verified that enterprise applications can consume AI-generated business decisions through predictable, typed data structures.
7.0 Next Lab
Enterprise systems typically consist of business processes that coordinate multiple services, manage state as work progresses, route exceptions, and determine what happens next based on the outcome of previous activities.
The next lab, Lab 004: Demonstrating the Next Evolution of Enterprise Process Architecture with LangGraph, introduces LangGraph as the orchestration engine for our simulated order fulfillment process.
The judgment services developed in this lab will become decision points within a workflow that coordinates purchasing, supplier commitments, warehouse operations, quality inspection, and invoice processing.
The Computer Is Going to Do Something – Join an ongoing, practical examination of technology strategy, enterprise architecture, systems engineering, and technology operations.
