AI Customer Support Chatbot Using OpenAI Swarm: Multi-Agent Routing
Daniel Kliewer
Author, Sovereign AI


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
bash1mkdir ai_customer_support_chatbot2cd ai_customer_support_chatbot
1.2 Initialize a Git Repository (Optional)
bash1git init
1.3 Create a Virtual Environment
bash1python3 -m venv venv
1.4 Activate the Virtual Environment
-
On Linux/macOS:
bash1source venv/bin/activate -
On Windows:
bash1venv\Scripts\activate
Step 2: Install Required Dependencies
2.1 Upgrade pip
bash1pip install --upgrade pip
2.2 Install Swarm and Other Required Packages
bash1pip install git+https://github.com/openai/swarm.git2pip install python-dotenv
Step 3: Securely Store Your OpenAI API Key
3.1 Create a .env File to Store Environment Variables
bash1touch .env
3.2 Add .env to .gitignore
bash1echo ".env" >> .gitignore
3.3 Add Your API Key to .env
Open .env in a text editor and add:
ini1OPENAI_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
bash1touch main.py
4.2 Add the Following Code to main.py
python1# main.py23import os4from dotenv import load_dotenv5from swarm import Swarm, Agent67# Load environment variables8load_dotenv()9openai_api_key = os.getenv("OPENAI_API_KEY")1011# Initialize Swarm client12client = Swarm(openai_api_key=openai_api_key)1314# Define specialized agents1516# Billing Support Agent17billing_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)2526# Technical Support Agent27technical_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)3536# General Inquiry Agent37general_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)4546# Define a function to triage the user's query47def 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_agent53 elif any(keyword in query.lower() for keyword in ["error", "issue", "bug", "technical", "problem", "troubleshoot"]):54 return technical_agent55 else:56 return general_agent5758# 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)6869def main():70 # Start the conversation71 user_message = input("User: ")7273 # Prepare the initial messages74 messages = [75 {"role": "user", "content": user_message}76 ]7778 # Run the Swarm client with the triage agent79 response = client.run(80 agent=triage_agent,81 messages=messages,82 context_variables={},83 max_turns=5,84 debug=False85 )8687 # Get the final response88 final_agent = response.agent89 final_message = response.messages[-1]["content"]9091 print(f"{final_agent.name}: {final_message}")9293if __name__ == "__main__":94 main()
Step 5: Run the Application
5.1 Execute main.py
bash1python 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_queryfunction 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:
python1def main():2 # Initialize context variables3 context_variables = {}45 # Prepare initial messages6 messages = []78 # Conversation loop9 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 break1415 messages.append({"role": "user", "content": user_message})1617 # Run the Swarm client18 response = client.run(19 agent=triage_agent,20 messages=messages,21 context_variables=context_variables,22 max_turns=5,23 debug=False24 )2526 # Get the latest agent and message27 final_agent = response.agent28 final_message = response.messages[-1]["content"]2930 print(f"{final_agent.name}: {final_message}")3132 # Update messages and context variables for the next turn33 messages = response.messages34 context_variables = response.context_variables
Step 6: Test the Extended Chatbot
6.1 Run the Application
bash1python main.py
6.2 Sample Interaction
text1User: 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: exit10Chatbot: 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: 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.