A Multi-Agent Support Desk

Ma Mahalakshmi V Updated 16 Sep 2026
7 min read ·Lesson 53 of 224

What This Project Builds

This project combines every piece of the Agents SDK covered in this unit into one working system: a support desk with a triage agent (Lesson 4) that routes incoming customer messages to a billing specialist or a technical specialist, each equipped with its own tools (Lesson 3), protected by an input guardrail that screens for manipulation attempts and an output guardrail that catches refunds exceeding an auto-approval limit (Lesson 5), with the entire interaction automatically traced (Lesson 6). This is meant as a capstone exercise for the unit: rather than exercising each piece in isolation, it shows how they combine into a single coherent system, mirroring how Unit 8 and Unit 9's own capstone projects combined that unit's individual lessons into one application.

Step 1: Defining the Specialist Agents' Tools

from agents import function_tool

@function_tool
def get_order_status(order_id: str) -> str:
    """Look up the current status of a customer's order.

    Args:
        order_id: The order identifier, e.g. "4471".
    """
    order_statuses = {"4471": "shipped", "5502": "processing"}
    if not order_id.isdigit():
        return "Invalid order ID format. Order IDs are numeric."
    return order_statuses.get(order_id, "No order found with that ID.")

@function_tool
def issue_refund(order_id: str, amount: float) -> str:
    """Issue a refund for a specific order.

    Use this only after confirming the customer is eligible for a refund
    under the return policy.

    Args:
        order_id: The order identifier to refund.
        amount: The refund amount in US dollars.
    """
    return f"Refunded ${amount:.2f} for order {order_id}."

@function_tool
def restart_device_remotely(device_id: str) -> str:
    """Send a remote restart command to a registered device.

    Args:
        device_id: The registered device identifier.
    """
    return f"Restart command sent to device {device_id}."

Each tool follows Lesson 3's guidance directly: a clear, specific docstring the model uses to decide when the tool applies, and a curated return value rather than a raw exception for an invalid input, following Unit 8, Lesson 5's error-handling discipline.

Step 2: Defining the Guardrails

from agents import input_guardrail, output_guardrail, GuardrailFunctionOutput
import re

@input_guardrail
def block_prompt_injection_attempts(context, agent, input_text: str) -> GuardrailFunctionOutput:
    suspicious_phrases = ["ignore previous instructions", "reveal your system prompt"]
    is_suspicious = any(phrase in input_text.lower() for phrase in suspicious_phrases)
    return GuardrailFunctionOutput(
        output_info={"suspicious": is_suspicious},
        tripwire_triggered=is_suspicious,
    )

AUTO_APPROVAL_LIMIT = 500.0

@output_guardrail
def block_unapproved_refund_amounts(context, agent, output_text: str) -> GuardrailFunctionOutput:
    dollar_amounts = [float(match) for match in re.findall(r"\$(\d+(?:\.\d{2})?)", output_text)]
    exceeds_limit = any(amount > AUTO_APPROVAL_LIMIT for amount in dollar_amounts)
    return GuardrailFunctionOutput(
        output_info={"exceeds_limit": exceeds_limit},
        tripwire_triggered=exceeds_limit,
    )

AUTO_APPROVAL_LIMIT follows Unit 8, Lesson 5's least-privilege pattern directly: a refund at or below this threshold can be handled automatically, while anything above it trips the output guardrail and, as Step 5 covers, routes to human review rather than being sent to the customer automatically.

Step 3: Defining the Specialist and Triage Agents

from agents import Agent, Runner

billing_agent = Agent(
    name="Billing Agent",
    instructions=(
        "You help customers with billing questions and refunds. "
        "Only issue a refund after confirming eligibility under the return policy."
    ),
    model="gpt-5.6-terra",
    tools=[issue_refund],
    output_guardrails=[block_unapproved_refund_amounts],
)

technical_agent = Agent(
    name="Technical Agent",
    instructions="You help customers troubleshoot technical issues, including restarting devices.",
    model="gpt-5.6-terra",
    tools=[get_order_status, restart_device_remotely],
)

triage_agent = Agent(
    name="Triage Agent",
    instructions=(
        "Route the customer's message to the correct specialist agent.\n\n"
        "Examples:\n"
        "- 'I was charged twice' -> Billing Agent\n"
        "- 'The app crashes on startup' -> Technical Agent\n"
        "- 'My subscription renewed but I want a refund' -> Billing Agent\n\n"
        "Do not attempt to answer the question yourself."
    ),
    model="gpt-5.6-terra",
    input_guardrails=[block_prompt_injection_attempts],
    handoffs=[billing_agent, technical_agent],
)

Following Lesson 4's guidance, the input guardrail is attached only once, at the triage agent — the system's single entry point — protecting every specialist a request might eventually be routed to, rather than being duplicated inside billing_agent and technical_agent individually. The output guardrail, by contrast, is attached specifically to billing_agent, since refund amounts are a concern specific to that specialist, not the technical agent.

Step 4: Running the Support Desk

from agents import trace

def handle_support_message(message: str) -> dict:
    with trace("Support Desk Interaction"):
        result = Runner.run_sync(triage_agent, message, max_turns=10)

    return {
        "response": result.final_output,
        "handled_by": result.last_agent.name,
    }

outcome = handle_support_message("I was charged twice for order 4471, can I get a refund?")
print(f"Handled by: {outcome['handled_by']}")
print(f"Response: {outcome['response']}")

This single function is the whole system's entry point: a message comes in, gets traced as one grouped interaction (Lesson 6), routed through triage to the correct specialist (Lesson 4), and the specialist's response — potentially involving a tool call (Lesson 3) — comes back out, with max_turns bounding the run against a runaway interaction, following Lesson 2's guidance.

Step 5: Handling a Tripped Output Guardrail

A refund request exceeding AUTO_APPROVAL_LIMIT shouldn't simply fail silently — following Unit 8, Lesson 5's confirmation-step reasoning, it should route to human review instead.

def handle_support_message_with_review(message: str) -> dict:
    with trace("Support Desk Interaction"):
        result = Runner.run_sync(triage_agent, message, max_turns=10)

    if getattr(result, "output_guardrail_tripped", False):
        return {
            "response": "This refund amount requires manager approval before it can be processed.",
            "handled_by": result.last_agent.name,
            "needs_human_review": True,
        }

    return {
        "response": result.final_output,
        "handled_by": result.last_agent.name,
        "needs_human_review": False,
    }

Note: The exact field or mechanism for checking whether an output guardrail tripped can vary by SDK version. Confirm the current interface against the current official documentation.

This directly applies Lesson 5's guidance that a tripped guardrail should route toward human review for a genuinely consequential case, rather than being treated as an automatic hard failure with no path forward — a $600 refund request doesn't get silently blocked, it gets flagged for a person to review and approve.

Step 6: Testing the System's Logic Without Real Agent Runs

Following this course's dependency-injection testing pattern, the guardrail logic, tool logic, and result-handling logic can all be tested independently of any real agent run or model call.

def test_refund_guardrail_flags_amounts_over_limit():
    dollar_amounts_high = [750.0]
    dollar_amounts_low = [250.0]
    assert any(amount > AUTO_APPROVAL_LIMIT for amount in dollar_amounts_high) is True
    assert any(amount > AUTO_APPROVAL_LIMIT for amount in dollar_amounts_low) is False
    print("PASS: refund guardrail threshold logic correctly separates high and low amounts")

def test_order_status_tool_handles_unknown_order():
    order_statuses = {"4471": "shipped"}

    def get_order_status_logic(order_id: str) -> str:
        if not order_id.isdigit():
            return "Invalid order ID format. Order IDs are numeric."
        return order_statuses.get(order_id, "No order found with that ID.")

    assert get_order_status_logic("4471") == "shipped"
    assert get_order_status_logic("9999") == "No order found with that ID."
    print("PASS: order status tool logic handles both known and unknown order IDs correctly")

test_refund_guardrail_flags_amounts_over_limit()
test_order_status_tool_handles_unknown_order()

Testing each piece of business logic — the guardrail's threshold check, the tool's lookup behavior — independently of a real agent run verifies correctness quickly and deterministically, reserving real end-to-end Runner.run_sync() calls for a smaller set of tests confirming the whole system routes and responds sensibly against representative real messages.

Troubleshooting Checklist

  1. Is a message being routed to the wrong specialist? Revisit the triage agent's instructions and add more concrete routing examples, following Lesson 4's few-shot guidance, for the specific ambiguous case that's misrouting.
  2. Is a refund guardrail not tripping when it should? Confirm AUTO_APPROVAL_LIMIT and the regular expression extracting dollar amounts actually match the format the billing agent's responses use.
  3. Is a suspicious input getting through the input guardrail? Expand suspicious_phrases to cover the specific manipulation pattern that got through, and consider whether the check needs to be more sophisticated than a fixed phrase list for a production system.
  4. Is result.last_agent reporting the triage agent instead of a specialist? This suggests the handoff never actually occurred — check whether the triage agent's instructions clearly identify when a handoff is warranted.
  5. Is a run hitting max_turns without producing a final answer? Check whether a tool is being called repeatedly without its result satisfying the agent, following the same diagnosis Unit 8, Lesson 3's max_rounds cap was designed to guard against.

Extending the Project

Natural next steps for this project, each building on techniques from across this unit and this course: adding a third specialist agent for account-management questions with its own handoff from triage; combining the billing agent's tools with Unit 9's built-in file search over a policy-documents vector store, so refund eligibility decisions are grounded in the actual current return policy rather than the model's own general knowledge; and extending the output guardrail to check for additional consequential patterns beyond refund amount, such as account deletion or subscription cancellation language, each following the same tripwire-and-human-review pattern Step 5 established for large refunds.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about A Multi-Agent Support Desk and get answers drawn from it.

Signed-in readers only.