Exciting Technical Explanation of examples-customer-service-main.py

This document provides a deep dive into the examples-customer-service-main.py script, a powerful demonstration of a multi-agent customer service system for an airline. This example showcases the capabilities of the agents library to create a sophisticated and interactive customer support experience.

Executive Summary

The examples-customer-service-main.py script simulates a customer service chatbot for an airline. It's not just a single bot; it's a team of specialized AI agents working together to provide efficient and accurate customer support. This multi-agent architecture allows for a more flexible and scalable solution compared to a monolithic chatbot.

The system consists of three distinct agents:

  1. Triage Agent: The first point of contact, responsible for understanding the customer's intent and routing them to the appropriate specialist.
  2. FAQ Agent: A knowledgeable agent that can answer frequently asked questions about the airline's policies.
  3. Seat Booking Agent: A helpful assistant that can book or update a passenger's seat on a flight.

Deep Dive into the Code

Let's break down the key components of the script and understand how they work together to create this intelligent customer service system.

1. The Agents

The core of the application is the three agents, each with its own specific role and capabilities.

TriageAgent

The TriageAgent is the front door to the customer service system. Its primary responsibility is to understand the user's request and delegate it to the appropriate specialist agent.

triage_agent = Agent[AirlineAgentContext](
    name="Triage Agent",
    handoff_description="A triage agent that can delegate a customer's request to the appropriate agent.",
    instructions=(
        f"{RECOMMENDED_PROMPT_PREFIX} "
        "You are a helpful triaging agent. You can use your tools to delegate questions to other appropriate agents."
    ),
    handoffs=[
        faq_agent,
        handoff(agent=seat_booking_agent, on_handoff=on_seat_booking_handoff),
    ],
)

The handoffs parameter is crucial here. It defines a list of other agents that the TriageAgent can hand the conversation over to. In this case, it can hand off to faq_agent or seat_booking_agent.

FAQAgent

The FAQAgent is a specialist in answering frequently asked questions. It uses a tool called faq_lookup_tool to find answers to common questions.

faq_agent = Agent[AirlineAgentContext](
    name="FAQ Agent",
    handoff_description="A helpful agent that can answer questions about the airline.",
    instructions=f"""{RECOMMENDED_PROMPT_PREFIX}
    You are an FAQ agent. ...
    Use the following routine to support the customer.
    # Routine
    1. Identify the last question asked by the customer.
    2. Use the faq lookup tool to answer the question. Do not rely on your own knowledge.
    3. If you cannot answer the question, transfer back to the triage agent.""",
    tools=[faq_lookup_tool],
)

The tools parameter provides the FAQAgent with the faq_lookup_tool, which it uses to answer questions. If the tool cannot answer the question, the agent is instructed to hand the conversation back to the TriageAgent.

SeatBookingAgent

The SeatBookingAgent is responsible for handling seat booking requests. It has a tool called update_seat that allows it to update a passenger's seat.

seat_booking_agent = Agent[AirlineAgentContext](
    name="Seat Booking Agent",
    handoff_description="A helpful agent that can update a seat on a flight.",
    instructions=f"""{RECOMMENDED_PROMPT_PREFIX}
    You are a seat booking agent. ...
    Use the following routine to support the customer.
    # Routine
    1. Ask for their confirmation number.
    2. Ask the customer what their desired seat number is.
    3. Use the update seat tool to update the seat on the flight.
    If the customer asks a question that is not related to the routine, transfer back to the triage agent. """,
    tools=[update_seat],
)

The SeatBookingAgent follows a specific routine to guide the user through the seat booking process.

2. The Tools

The agents use tools to perform specific actions. These tools are defined as Python functions and are decorated with @function_tool.

faq_lookup_tool

This tool takes a question as input and returns a pre-defined answer if it matches any of the keywords.

@function_tool(
    name_override="faq_lookup_tool", description_override="Lookup frequently asked questions."
)
async def faq_lookup_tool(question: str) -> str:
    # ... implementation ...

update_seat

This tool updates the seat for a given confirmation number.

@function_tool
async def update_seat(
    context: RunContextWrapper[AirlineAgentContext], confirmation_number: str, new_seat: str
) -> str:
    # ... implementation ...

3. Context Management

The AirlineAgentContext is a Pydantic BaseModel that is used to maintain the state of the conversation.

class AirlineAgentContext(BaseModel):
    passenger_name: str | None = None
    confirmation_number: str | None = None
    seat_number: str | None = None
    flight_number: str | None = None

This context is passed between the agents, allowing them to share information and maintain a consistent conversation with the user.

4. Conversation Flow

The main function simulates a conversation with the customer service system.

async def main():
    current_agent: Agent[AirlineAgentContext] = triage_agent
    input_items: list[TResponseInputItem] = []
    context = AirlineAgentContext()
    # ...
    while True:
        user_input = input_with_fallback(
            "Enter your message: ",
            "What are your store hours?",
        )
        with trace("Customer service", group_id=conversation_id):
            input_items.append({"content": user_input, "role": "user"})
            result = await Runner.run(current_agent, input_items, context=context)
            # ...

The Runner.run() function is the engine that drives the conversation. It takes the current agent, the conversation history (input_items), and the context as input, and returns the result of the agent's turn.

Sample Conversation Analysis

The provided output in examples-customer-service-main.py.txt demonstrates the system in action.

  1. The user starts by asking to book a seat. The TriageAgent hands off the conversation to the SeatBookingAgent.
  2. The SeatBookingAgent guides the user through the seat booking process, asking for the confirmation number and the desired seat.
  3. The SeatBookingAgent then uses the update_seat tool to update the seat.
  4. The user then asks a question about flights to Dubai. The SeatBookingAgent hands the conversation back to the TriageAgent.
  5. The TriageAgent then hands the conversation to the FAQAgent.
  6. The FAQAgent uses the faq_lookup_tool but cannot find an answer, so it informs the user and offers to transfer them to another agent.

Conclusion

The examples-customer-service-main.py script is an excellent example of how to build a powerful and flexible customer service system using a multi-agent architecture. By breaking down the problem into smaller, specialized agents, we can create a more robust and maintainable solution. The agents library provides all the necessary tools to build such systems, including agent creation, tool definition, handoffs, and context management. This example is a great starting point for anyone looking to build their own intelligent agent-based applications.