AI Agents: Revolutionizing Customer Service with 6 Python Files
Le brief IA que les pros lisent chaque soir
Les 7 actus IA du jour, décryptées en 5 min. Gratuit.
Inclus dès l'inscription : notre sélection des meilleurs guides & comparatifs IA.
Choisis ton rythme
Gratuit · Pas de spam · Désabonnement en 1 clic
A New Era for Customer Service: Collaborative AI Agents
In the field of customer relations, companies often resort to chatbots to handle basic interactions. However, these traditional tools quickly show their limitations when it comes to addressing complex requests. This is where the multi-agent system comes into play, a solution that allows for the creation of "teams" of specialized agents. These agents collaborate to autonomously resolve more sophisticated customer issues, going beyond simple automated responses. This article guides you through the creation of such a system for after-sales service (SAV), using a concrete case: managing refunds for defective products.
Concrete Example: Refund for a Defective Product
Imagine a customer requesting a refund after receiving a broken product. In this scenario, a logistics specialist agent will check the delivery details, a customer service agent will confirm the product's condition, and a financial agent will initiate the refund. This division of tasks allows for a quick and efficient handling of the request.
Understanding How a Multi-Agent System Works
To ensure smooth and continuous interaction, the multi-agent system utilizes short and long-term memory, integrated via RAG (Retrieval-Augmented Generation). Exchanges are structured in JSON format to guarantee optimal interoperability. Feedback loops allow a "critical agent" to validate responses before they are sent to the customer, thus ensuring service quality.
Addressing Complex Requests: A Step-by-Step Approach
To illustrate this technology, we will build a multi-agent system dedicated to customer relations. This project is broken down into several steps: creating the root folder, configuring the security file, setting up the system's brain, engine, interface, and memory. Here is what the final structure of our project looks like:
C:\Users\admin\MonProjetCrew\
├── venv/ # The isolated Python environment
├── knowledge/ # Internal PDFs and guides
├── .env # The secret [API](/glossaire/api) key
├── customer_service_crew.py # Definition of Agents and Tasks
├── main.py # For testing in console mode
└── app.py # To launch the Web interface (Streamlit)
To follow this tutorial, it is essential to have Python 3.10 or a later version, the Pip package manager, and an API key for a LLM (here, OpenAI).
1. Preparing the Root Folder
On Windows, start by opening the terminal with PowerShell. Create your workspace by entering the following command:
mkdir C:\Users\admin\MonProjetCrew
Next, navigate to this directory:
cd C:\Users\admin\MonProjetCrew
Create a virtual environment (venv) with the command:
python -m venv venv
Activate this environment:
.\venv\Scripts\activate
Finally, install the necessary libraries:
pip install crewai langchain-openai streamlit
2. Configuring the Security File: .env
At the root of your folder, create a text file named .env. This file should not have a .txt extension. To obtain your API key, go to platform.openai.com, select "API," not "ChatGPT." Note that OpenAI no longer offers automatic free credits upon registration. You will need to add a minimum amount to activate your key. Once done, copy your key into the .env file:
OPENAI_API_KEY=sk-proj-YOUR_KEY_HERE
3. The Brain of the System: customer_service_crew.py
To launch the "brain" of your system, create a file named customer_service_crew.py in VS Code. Open the MonProjetCrew folder via File > Open Folder... and create a new file by clicking the "+" icon next to your folder name. Insert the following code and save it:
from crewai import Agent, Task, Crew, Process
from dotenv import load_dotenv
load_dotenv() # Load environment variables from the .env file
# 1. Defining the Agents
classifier_agent = Agent(
role='Customer Request Classifier',
goal='Analyze incoming customer requests, identify the intent (technical, billing, information) and urgency level (low, medium, high).',
backstory='An expert in semantic analysis, this is the first point of contact with the customer. Their mission is to quickly understand the nature of each request to direct it to the right specialist.',
allow_delegation=False # This agent does not delegate, it classifies
)
specialist_agent = Agent(
role='Technical Support Specialist',
goal='Provide accurate solutions to technical problems identified by the classifier, using an internal knowledge base.',
backstory='An experienced engineer, they are well-versed in the company’s products and services. They can diagnose and propose detailed technical solutions.',
allow_delegation=True # Can delegate if more information is needed
)
response_agent = Agent(
role='Customer Response Writer',
goal='Draft clear, concise, professional, and empathetic responses based on the information provided by the other agents.',
backstory='A master of written communication, they ensure that each customer response is perfectly crafted, respects the company tone, and provides a satisfactory solution.',
allow_delegation=False # This agent writes the final response
)
# 2. Defining the Tasks
classify_task = Task(
description='Analyze the following customer request: "{{ customer_request }}" to determine its intent and urgency.',
expected_output='A JSON dictionary with the keys "intent" (e.g., "technical", "billing", "information") and "urgency" (e.g., "low", "medium", "high").',
agent=classifier_agent
)
research_task = Task(
description='Based on the intent "{{ intent }}" and urgency "{{ urgency }}" of the customer request, research the most relevant solution. The original request was: "{{ customer_request }}".',
expected_output='A detailed summary of the solution found, including steps to follow or relevant information.',
agent=specialist_agent
)
write_response_task = Task(
description='Draft a professional and empathetic response to the customer. The original request was: "{customer_request}"',
expected_output='The complete text of the email response to the customer.',
agent=response_agent,
context=[research_task] # <--- This line allows the writer to receive the "solution" found by the previous agent
)
# 3. Assembling the Crew
customer_service_crew = Crew(
agents=[classifier_agent, specialist_agent, response_agent],
tasks=[classify_task, research_task, write_response_task],
process=Process.sequential, # Tasks execute sequentially
)
# 4. Launching the Process
customer_request = "My internet has not been working since this morning, and I have an important video meeting in 1 hour!"
# Execute the first task to obtain intent and urgency
initial_output = customer_service_crew.kickoff(inputs={'customer_request': customer_request})
print("\n### Final Response from the Multi-Agent System:\n")
print(initial_output)
In this system, each customer request is processed by a chain of agents, each with a well-defined role. The classifier agent sorts and evaluates urgency, while the specialist agent seeks the technical solution. Finally, the response agent transforms this information into a polite and empathetic customer response.
4. The Memory: The Knowledge Folder
Create a folder named knowledge at the root of your project. Add a PDF file, for example, refund_conditions.pdf. In the customer_service_crew.py file, configure the specialist agent to use a reading tool, such as PDFSearchTool, which will point to this folder.
5. The Engine: main.py
This file converts the Python script into an interactive web application capable of reading PDF documents using RAG. The "library" (pdf_source) should point to the refund_conditions_exercise.pdf file. Streamlit, a Python library, is used for data visualization. Adjust the name of the PDF as needed.
import streamlit as st
from dotenv import load_dotenv
from crewai import Agent, Task, Crew
# --- NEW: Import for the PDF ---
from crewai.knowledge.source.pdf_knowledge_source import PDFKnowledgeSource
# 1. Page Configuration
st.set_page_config(page_title="My SAV Assistant", layout="centered")
st.title("???? Chat with the Refund Expert")
# --- NEW: Configure the knowledge source ---
pdf_source = PDFKnowledgeSource(
item_id="refund_policy",
file_paths=["refund_conditions_exercise.pdf"]
)
# 2. Input Area for the User
user_question = st.text_input("Ask your question about refunds:", placeholder="E.g., What is the timeframe for a refund?")
# 3. Create the agent (Modified to use Knowledge)
researcher = Agent(
role="Customer Service Expert",
goal="Provide accurate answers based exclusively on the provided refund documents",
backstory="You work in after-sales service. Your strength is finding the exact rule in the PDFs to assist customers.",
allow_delegation=False,
knowledge_sources=[pdf_source] # <--- We link the PDF to the agent here
)
# 4. Launch the action
if st.button("Send"):
if user_question:
with st.spinner("Searching the documents..."):
description = f"Using the documents at your disposal, respond
Brief IA — L'actualité IA en français
L'essentiel de l'actualité de l'intelligence artificielle, décrypté et expliqué chaque jour.