ExamplescriptadvancedRunnablerouting-dag
Level 2: Prompt Chains & Routing — Deterministic DAGs
Multiple LLM calls in a fixed sequence. Code controls the flow, not the model.
Key Facts
- Level
- advanced
- Runtime
- Python • Pydantic + Python Dotenv
- Pattern
- Deterministic routing with explicit stage-by-stage visibility
- Interaction
- Live sandbox • Script
- Updated
- 14 March 2026
Navigate this example
Library
Browse examplesReopen the wider library to compare adjacent patterns and linked learning paths.Interaction
Run sandbox nowTry the interaction directly in this example’s guided sandbox surface.Source
Open full sourceRead the real implementation, highlighted checkpoints, and runtime requirements.MCP
Call via MCPUse the same resource inside agents, deterministic exports, and MCP setup flows.
Linked principles
Model context
Model-agnosticLocal-viableNo tool calling requiredLow reasoning requirement
Sequential prompt chaining is structurally enforced. Each step is deterministic; model quality affects output quality but not pattern correctness.
2-prompt-chains.py
python
"""
Level 2: Prompt Chains & Routing — Deterministic DAGs
Multiple LLM calls in a fixed sequence. Code controls the flow, not the model.
"""
from enum import Enum
from pydantic import BaseModel
from pydantic_ai import Agent
from dotenv import load_dotenv
import nest_asyncio
load_dotenv()
nest_asyncio.apply()
# --- Models ---
class Category(str, Enum):
BILLING = "billing"
TECHNICAL = "technical"
GENERAL = "general"
class TicketClassification(BaseModel):
category: Category
confidence: float
class Resolution(BaseModel):
response: str
escalate: bool
# --- Agents (each is a single focused LLM call) ---
classifier = Agent(
"anthropic:claude-sonnet-4-6",
output_type=TicketClassification,
system_prompt="Classify the customer ticket into a category. Be precise.",
)
billing_handler = Agent(
"anthropic:claude-sonnet-4-6",
output_type=Resolution,
system_prompt=(
"You handle billing issues. Generate a resolution. "
"Set escalate=true if a refund over $100 is needed."
),
)
technical_handler = Agent(
"anthropic:claude-sonnet-4-6",
output_type=Resolution,
system_prompt=(
"You handle technical issues. Generate a resolution. "
"Set escalate=true if the issue requires engineering intervention."
),
)
general_handler = Agent(
"anthropic:claude-sonnet-4-6",
output_type=Resolution,
system_prompt="You handle general inquiries. Be helpful and concise.",
)
# --- DAG: classify → route → handle → validate ---
HANDLERS = {
Category.BILLING: billing_handler,
Category.TECHNICAL: technical_handler,
Category.GENERAL: general_handler,
}
def process_ticket(ticket: str) -> Resolution:
classification = classifier.run_sync(ticket)
print(
f"Classified as: {classification.output.category} ({classification.output.confidence:.0%})"
)
handler = HANDLERS[classification.output.category]
result = handler.run_sync(ticket)
if result.output.escalate:
print("Escalating to human agent")
return result.output
if __name__ == "__main__":
ticket = (
"I was charged twice for my subscription last month. "
"Order ID: #12345. The duplicate charge was $49.99."
)
resolution = process_ticket(ticket)
print(f"\nResponse: {resolution.response}")
Related principles
- P1delegationDesign for delegation rather than direct manipulationDesign experiences around the assignment of work, the expression of intent, the setting of constraints, and the review of results, rather than requiring users to execute each step manually.Open principle →
- P5delegationReplace implied magic with clear mental modelsThe product should help users understand what the system can do, what it is currently doing, what it cannot do, and what conditions govern its behaviour.Open principle →
- P9orchestrationRepresent delegated work as a system, not merely as a conversationWhere work involves multiple steps, agents, dependencies, or concurrent activities, it should be represented as a structured system rather than solely as a message stream.Open principle →
- P10delegationOptimise for steering, not only initiatingThe system should support users not only in starting tasks, but also in guiding, refining, reprioritising, and correcting work while it is underway.Open principle →