Skip to main contentSkip to footer
ExamplescriptintermediateRunnableintent-router

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.

Key Facts

Level
intermediate • Agent Building Blocks
Runtime
Python • OpenAI API
Pattern
Model classification with code-owned routing
Interaction
Live sandbox • Script
Updated
14 March 2026

Navigate this example

High-level flow

How this example moves from input to execution and reviewable output
Control: Provides deterministic decision-making and… -> Route with explicit logic -> Intent detection -> Control branch -> Outcome -> Classification is probabilistic

Entry

Control: Provides deterministic decision-making and…

Process

Route with explicit logic

Outcome

Control branch

Why this page exists

This example is shown as both real source code and a product-facing interaction pattern so learners can connect implementation, UX, and doctrine without leaving the library.

Visual flowReal sourceSandbox or walkthroughMCP access
How should this example be used in the platform?

Use the sandbox to understand the experience pattern first, then inspect the source to see how the product boundary, model boundary, and doctrine boundary are actually implemented.

UX pattern: Model classification with code-owned routing
Classification is probabilistic
Routing is deterministic
The branch boundary should be visible to the user
Source references
Library entry
agents-building-blocks-5-control
Source path
content/example-library/sources/agents/building-blocks/5-control.py
Libraries
openai, pydantic, requests
Runtime requirements
OPENAI_API_KEY
Related principles
Design for delegation rather than direct manipulation, Replace implied magic with clear mental models, Establish trust through inspectability, Make hand-offs, approvals, and blockers explicit, Optimise for steering, not only initiating

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}")
What should the learner inspect in the code?

Look for the exact place where system scope is bounded: schema definitions, prompt framing, runtime configuration, and the call site that turns user intent into a concrete model or workflow action.

class IntentClassification(BaseModel):
if intent == "question":
elif intent == "request":
elif intent == "complaint":
How does the sandbox relate to the source?

The sandbox should make the UX legible: what the user sees, what the system is deciding, and how the result becomes reviewable. The source then shows how that behavior is actually implemented.

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.

UX explanation

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.

AI design explanation

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.

Interaction walkthrough

  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
Used in courses and paths

Related principles

Runtime architecture

Use this example in your agents

This example is also available through the blueprint’s agent-ready layer. Use the For agents page for the public MCP, deterministic exports, and Claude/Cursor setup.

Define triggers, context, and boundaries before increasing autonomy
Make control, observability, and recovery explicit in the runtime
Choose the right operational patterns before delegating to workflows