Skip to main contentSkip to footer
EsempioscriptintermediateEseguibileintent-router

Controllo: fornisce processi decisionali deterministici e controllo del flusso di processo.

Questo componente gestisce la logica if/then, il routing basato su condizioni e l’orchestrazione dei processi per un comportamento prevedibile.

Fatti chiave

Livello
intermediate • Blocchi di Costruzione degli Agenti
Runtime
Python • API OpenAI
Pattern
Model classification with code-owned routing
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
Controllo: fornisce processi decisionali deterministici… -> Route with explicit logic -> Intent detection -> Control branch -> Outcome -> Classification is probabilistic

Ingresso

Controllo: fornisce processi decisionali deterministici…

Processo

Route with explicit logic

Esito

Control branch

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: Model classification with code-owned routing
Classification is probabilistic
Routing is deterministic
The branch boundary should be visible to the user
Riferimenti sorgente
Voce di libreria
agents-building-blocks-5-control
Percorso sorgente
content/example-library/sources/agents/building-blocks/5-control.py
Librerie
openai, pydantic, requests
Requisiti di runtime
OPENAI_API_KEY
Principi correlati
Progettare per la delega piuttosto che per la manipolazione diretta, Sostituire la magia implicita con modelli mentali chiari, Stabilire fiducia attraverso l'ispezionabilità, Rendere espliciti i passaggi, le approvazioni e i blocchi, Ottimizzare per la guida, non solo per l'inizio

5-control.py

python
"""
Control: Provides deterministic decision-making and process flow control.
This component handles if/then logic, routing based on conditions, and process orchestration for predictable behavior.
"""

from openai import OpenAI
from pydantic import BaseModel
from typing import Literal


class IntentClassification(BaseModel):
    intent: Literal["question", "request", "complaint"]
    confidence: float
    reasoning: str


def route_based_on_intent(user_input: str) -> tuple[str, IntentClassification]:
    client = OpenAI()
    response = client.responses.parse(
        model="gpt-4o",
        input=[
            {
                "role": "system",
                "content": "Classify user input into one of three categories: question, request, or complaint. Provide your reasoning and confidence level.",
            },
            {"role": "user", "content": user_input},
        ],
        text_format=IntentClassification,
    )

    classification = response.output_parsed
    intent = classification.intent

    if intent == "question":
        result = answer_question(user_input)
    elif intent == "request":
        result = process_request(user_input)
    elif intent == "complaint":
        result = handle_complaint(user_input)
    else:
        result = "I'm not sure how to help with that."

    return result, classification


def answer_question(question: str) -> str:
    client = OpenAI()
    response = client.responses.create(
        model="gpt-4o", input=f"Answer this question: {question}"
    )
    return response.output[0].content[0].text


def process_request(request: str) -> str:
    return f"Processing your request: {request}"


def handle_complaint(complaint: str) -> str:
    return f"I understand your concern about: {complaint}. Let me escalate this."


if __name__ == "__main__":
    # Test different types of inputs
    test_inputs = [
        "What is machine learning?",
        "Please schedule a meeting for tomorrow",
        "I'm unhappy with the service quality",
    ]

    for user_input in test_inputs:
        print(f"\nInput: {user_input}")
        result, classification = route_based_on_intent(user_input)
        print(
            f"Intent: {classification.intent} (confidence: {classification.confidence})"
        )
        print(f"Reasoning: {classification.reasoning}")
        print(f"Response: {result}")
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.

class IntentClassification(BaseModel):
if intent == "question":
elif intent == "request":
elif intent == "complaint":
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.

Enter or load a user message.
Classify the message into a known intent.
Inspect the deterministic route and the resulting branch response.
SandboxModel classification with code-owned routing
Deterministic intent control layer

This simulation makes the control layer visible: classify intent once, route by deterministic code, and expose the chosen branch to the user.

Spiegazione UX

The experience should show that the system is not improvising every step. After one model classification, deterministic logic takes over and produces a clear branch for the user.

Spiegazione AI Design

Control is the boundary that keeps orchestration from drifting into hidden autonomy. The model proposes an intent classification, but the product owns the route and its consequences.

Guida all'interazione

  1. 1Enter or load a user message.
  2. 2Classify the message into a known intent.
  3. 3Inspect the deterministic route and the resulting branch response.

User message

Intent classificationDeterministic routing

Classification output

The intent and confidence appear here before the route executes.

Deterministic branch

The branch response should reflect product logic, not an opaque chat reply.

Control-layer lesson

  • Classification is probabilistic
  • Routing is deterministic
  • The branch boundary should be visible to the user
Usato in corsi e percorsi

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