·6 min

AI Customer Support Chatbot Using OpenAI Swarm: Multi-Agent Routing

DK

Daniel Kliewer

Author, Sovereign AI

OpenAI SwarmChatbotsAI Customer SupportMulti-Agent SystemsPython
Sovereign AI book cover

From the Book

This is from Sovereign AI: Building Local-First Intelligent Systems.

Get the Book — $88
AI Customer Support Chatbot Using OpenAI Swarm: Multi-Agent Routing

Image

Guide to Building an AI-Powered Customer Support Chatbot Using Swarm

This guide will help you create an AI-powered customer support chatbot that utilizes OpenAI's Swarm to coordinate multiple specialized agents. Each agent will handle specific types of customer queries, such as billing issues, technical support, or general inquiries.


Prerequisites

  • Python 3.10+ installed on your machine.
  • OpenAI API Key: Obtain one from OpenAI.
  • Terminal Access: Ability to run commands in your operating system's terminal.
  • Git (optional): For version control.

Step 1: Set Up the Project Environment

1.1 Create a Project Directory and Navigate Into It

bash
1mkdir ai_customer_support_chatbot
2cd ai_customer_support_chatbot

1.2 Initialize a Git Repository (Optional)

bash
1git init

1.3 Create a Virtual Environment

bash
1python3 -m venv venv

1.4 Activate the Virtual Environment

  • On Linux/macOS:

    bash
    1source venv/bin/activate
  • On Windows:

    bash
    1venv\Scripts\activate

Step 2: Install Required Dependencies

2.1 Upgrade pip

bash
1pip install --upgrade pip

2.2 Install Swarm and Other Required Packages

bash
1pip install git+https://github.com/openai/swarm.git
2pip install python-dotenv

Step 3: Securely Store Your OpenAI API Key

3.1 Create a .env File to Store Environment Variables

bash
1touch .env

3.2 Add .env to .gitignore

bash
1echo ".env" >> .gitignore

3.3 Add Your API Key to .env

Open .env in a text editor and add:

ini
1OPENAI_API_KEY=your_openai_api_key_here

Note: Replace your_openai_api_key_here with your actual API key.


Step 4: Create the Main Script

4.1 Create main.py

bash
1touch main.py

4.2 Add the Following Code to main.py

python
1# main.py
2
3import os
4from dotenv import load_dotenv
5from swarm import Swarm, Agent
6
7# Load environment variables
8load_dotenv()
9openai_api_key = os.getenv("OPENAI_API_KEY")
10
11# Initialize Swarm client
12client = Swarm(openai_api_key=openai_api_key)
13
14# Define specialized agents
15
16# Billing Support Agent
17billing_agent = Agent(
18 name="Billing Support Agent",
19 instructions="""
20You are a helpful customer support agent specializing in billing issues.
21Assist the user with their billing inquiries, such as charges, refunds, and payment methods.
22If the query is not related to billing, politely inform the user and suggest contacting the appropriate department.
23""",
24)
25
26# Technical Support Agent
27technical_agent = Agent(
28 name="Technical Support Agent",
29 instructions="""
30You are a helpful customer support agent specializing in technical issues.
31Assist the user with technical problems, such as troubleshooting errors, connectivity issues, and software bugs.
32If the query is not related to technical support, politely inform the user and suggest contacting the appropriate department.
33""",
34)
35
36# General Inquiry Agent
37general_agent = Agent(
38 name="General Inquiry Agent",
39 instructions="""
40You are a helpful customer support agent handling general inquiries.
41Assist the user with questions about account information, product details, and other general topics.
42If the query is specialized (billing or technical), politely inform the user and suggest contacting the appropriate department.
43""",
44)
45
46# Define a function to triage the user's query
47def triage_query(context_variables, query: str):
48 """
49 Analyze the user's query and determine the appropriate agent to handle it.
50 """
51 if any(keyword in query.lower() for keyword in ["bill", "charge", "payment", "invoice", "refund"]):
52 return billing_agent
53 elif any(keyword in query.lower() for keyword in ["error", "issue", "bug", "technical", "problem", "troubleshoot"]):
54 return technical_agent
55 else:
56 return general_agent
57
58# Initial Agent (Triage Agent)
59triage_agent = Agent(
60 name="Triage Agent",
61 instructions="""
62You are an AI assistant that routes customer inquiries to the appropriate department.
63Analyze the user's message and determine which specialized agent should handle it.
64Call the function 'triage_query' to perform the routing.
65""",
66 functions=[triage_query],
67)
68
69def main():
70 # Start the conversation
71 user_message = input("User: ")
72
73 # Prepare the initial messages
74 messages = [
75 {"role": "user", "content": user_message}
76 ]
77
78 # Run the Swarm client with the triage agent
79 response = client.run(
80 agent=triage_agent,
81 messages=messages,
82 context_variables={},
83 max_turns=5,
84 debug=False
85 )
86
87 # Get the final response
88 final_agent = response.agent
89 final_message = response.messages[-1]["content"]
90
91 print(f"{final_agent.name}: {final_message}")
92
93if __name__ == "__main__":
94 main()

Step 5: Run the Application

5.1 Execute main.py

bash
1python main.py

5.2 Interact with the Chatbot

After running the script, you will be prompted to enter a user message:

User: I need help with a charge on my account.

The chatbot will process your input and route it to the appropriate agent.

Example Output:

Billing Support Agent: I'm sorry to hear you're experiencing issues with a charge on your account. Could you please provide more details so I can assist you further?

Additional Notes

  • Extending Functionality: You can add more specialized agents for other departments like Sales, Account Management, etc.
  • Improving Triage: Enhance the triage_query function to handle more complex routing logic.
  • Conversation Loop: Modify the script to allow multiple turns in the conversation by placing the interaction inside a loop.

Example: Extended Conversation Loop

To allow continuous interaction, update the main() function as follows:

python
1def main():
2 # Initialize context variables
3 context_variables = {}
4
5 # Prepare initial messages
6 messages = []
7
8 # Conversation loop
9 while True:
10 user_message = input("User: ")
11 if user_message.lower() in ["exit", "quit"]:
12 print("Chatbot: Thank you for contacting support. Goodbye!")
13 break
14
15 messages.append({"role": "user", "content": user_message})
16
17 # Run the Swarm client
18 response = client.run(
19 agent=triage_agent,
20 messages=messages,
21 context_variables=context_variables,
22 max_turns=5,
23 debug=False
24 )
25
26 # Get the latest agent and message
27 final_agent = response.agent
28 final_message = response.messages[-1]["content"]
29
30 print(f"{final_agent.name}: {final_message}")
31
32 # Update messages and context variables for the next turn
33 messages = response.messages
34 context_variables = response.context_variables

Step 6: Test the Extended Chatbot

6.1 Run the Application

bash
1python main.py

6.2 Sample Interaction

text
1User: I'm having trouble logging into my account.
2Technical Support Agent: I'm sorry to hear you're having trouble logging in. Could you please describe the issue you're experiencing, and any error messages you might have received?
3User: It says my password is incorrect, but I'm sure it's right.
4Technical Support Agent: Understood. It's possible that your password needs to be reset. Would you like me to guide you through the password reset process?
5User: Yes, please.
6Technical Support Agent: Certainly! To reset your password, please click on the "Forgot Password" link on the login page. You'll be prompted to enter your registered email address, and we'll send you instructions to create a new password.
7User: Thank you.
8Technical Support Agent: You're welcome! If you have any more questions or need further assistance, feel free to ask.
9User: exit
10Chatbot: Thank you for contacting support. Goodbye!

Conclusion

You've successfully built an AI-powered customer support chatbot using OpenAI's Swarm. The chatbot intelligently routes user queries to specialized agents based on the content of the message, providing a tailored support experience.


Happy Coding!


Note: This project uses OpenAI's Swarm, focusing on agent coordination and execution. By utilizing multiple agents with specific expertise, you can create a more dynamic and responsive chatbot that handles various customer needs efficiently.

Sovereign AI book cover

Sovereign AI: Building Local-First Intelligent Systems

by Daniel Kliewer · Paperback · 72 pages

The hands-on guide to building AI that runs on your hardware, keeps your data private, and eliminates cloud dependence. Working code included.