Skip to main contentSkip to footer
EsempioscriptadvancedEseguibilerouting-dag

Livello 2: Catene di prompt e routing — DAG deterministici

Più chiamate LLM in una sequenza fissa. È il codice a controllare il flusso, non il modello.

Fatti chiave

Livello
advanced
Runtime
Python • Pydantic + Python Dotenv
Pattern
Deterministic routing with explicit stage-by-stage visibility
Interazione
Sandbox live • Script
Aggiornato
14 marzo 2026

Naviga questo esempio

Vista rapida del flusso

Come questo esempio si muove tra input, esecuzione e risultato rivedibile
Livello 2: Catene di prompt… -> Route with explicit logic -> Run the agent task -> Classification -> Code routing -> Resolution

Ingresso

Livello 2: Catene di prompt…

Processo

Route with explicit logic

Esito

Classification

Perché esiste questa pagina

Questo esempio è mostrato sia come codice sorgente reale che come pattern di interazione orientato al prodotto, così i discenti possono collegare implementazione, UX e dottrina senza lasciare la libreria.

Flusso visivoCodice realeSandbox o walkthroughAccesso MCP
Come dovrebbe essere usato questo esempio nella piattaforma?

Usa prima la sandbox per comprendere il pattern di esperienza, poi ispeziona il sorgente per vedere come il confine del prodotto, il confine del modello e il confine della dottrina sono effettivamente implementati.

UX pattern: Deterministic routing with explicit stage-by-stage visibility
Multiple model calls, but fixed orchestration
Code chooses the route, not the model
Escalation remains a visible branch
Riferimenti sorgente
Voce di libreria
agents-agent-complexity-2-prompt-chains
Percorso sorgente
content/example-library/sources/agents/agent-complexity/2-prompt-chains.py
Librerie
pydantic, python-dotenv
Requisiti di runtime
Ambiente del repository locale
Principi correlati
Progettare per la delega piuttosto che per la manipolazione diretta, Sostituire la magia implicita con modelli mentali chiari, Rappresentare il lavoro delegato come un sistema, non solo come una conversazione, Ottimizzare per la guida, non solo per l'inizio

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}")
Cosa dovrebbe ispezionare il discente nel codice?

Cerca il punto esatto in cui lo scope del sistema è delimitato: definizioni di schema, impostazione del prompt, configurazione di runtime e il punto di chiamata che trasforma l'intenzione dell'utente in un'azione concreta del modello o del workflow.

classifier = Agent(
HANDLERS = {
classification = classifier.run_sync(ticket)
handler = HANDLERS[classification.output.category]
Come si relaziona la sandbox al sorgente?

La sandbox dovrebbe rendere leggibile l'UX: cosa vede l'utente, cosa sta decidendo il sistema e come il risultato diventa revisionabile. Il sorgente mostra poi come quel comportamento è effettivamente implementato.

Submit a support issue to the pipeline.
Watch the system classify the issue and choose the handler deterministically.
Inspect the final resolution and whether escalation was triggered.
SandboxDeterministic routing with explicit stage-by-stage visibility
Classify, route, then resolve

This simulation shows the product pattern behind deterministic orchestration: code owns the sequence, while each model call stays narrow and inspectable.

Spiegazione UX

The user still delegates once, but the experience now has visible internal stages: classify the ticket, route to the right handler, and then produce a resolution. The system should reveal that sequence instead of pretending the result arrived magically.

Spiegazione AI Design

Each model call is scoped to one job. Classification does not resolve, and handlers do not decide the route. Deterministic product code chooses the next step, keeping the workflow inspectable and easy to debug.

Guida all'interazione

  1. 1Submit a support issue to the pipeline.
  2. 2Watch the system classify the issue and choose the handler deterministically.
  3. 3Inspect the final resolution and whether escalation was triggered.

Pipeline input

ClassifierDeterministic route mapResolution handler

1. Classification

Run the classifier to expose the first system decision.

2. Code routing

The route becomes visible after classification.

3. Resolution

The chosen handler produces the final structured resolution.

What the learner should notice

  • Multiple model calls, but fixed orchestration
  • Code chooses the route, not the model
  • Escalation remains a visible branch
Usato in corsi e percorsi

Questo esempio attualmente è indipendente nella libreria, ma si connette comunque al sistema dei principi e alla famiglia di esempi più ampia.

Principi correlati

Runtime architecture

Usa questo esempio nei tuoi agenti

Questo esempio è disponibile anche tramite il layer agent-ready del blueprint. Usa la pagina Per agenti per recuperare MCP pubblico, export deterministici e setup per Claude o Cursor.

Definisci trigger, contesto e confini prima di aumentare l'autonomia
Rendi espliciti controllo, osservabilita e recovery nel runtime
Scegli i pattern operativi giusti prima di delegare ai workflow
Livello 2: Catene di prompt e routing — DAG deterministici