In questo tutorial, dimostreremo come un team di più agenti AI può collaborare per completare attività complesse e ottimizzare i workflow. Abbiamo creato un'applicazione Python per spiegare l'orchestrazione di agenti specializzati che lavorano all'interno di un'architettura multiagente. Alla fine, vedrai ed eseguirai un esempio di collaborazione multiagente all'interno di un'applicazione di agentic AI.
L'applicazione con cui stiamo lavorando è un equipaggio di analisi del servizio clienti che utilizza CrewAI come framework multiagentico e IBM watsonx.ai per implementare i modelli linguistici di grandi dimensioni (LLM) alla sua base.
Gli agenti AI sono entità basate su LLM in grado di eseguire operazioni per conto di un utente o di un sistema di agentic AI. Le architetture agentiche si strutturano attorno a due diversi sistemi: singolo e multiagente.
I sistemi ad agente singolo sono ideali per risolvere problemi specifici, poiché si basano su un unico agente LLM per eseguire attività di AI generativa. Ad esempio, un agente chatbot singolo può concentrarsi su attività o conversazioni specifiche che può completare nell'ambito delle sue funzionalità individuali.
I sistemi multiagente (MAS) sono framework che orchestrano le funzionalità e le interazioni tra agenti AI. Piuttosto che cercare di racchiudere tutte le funzionalità in un unico agente, le architetture multiagente utilizzano agenti diversi per lavorare all'interno dello stesso ambiente e raggiungere un obiettivo comune. I vantaggi fondamentali dei sistemi multiagente includono la collaborazione tra agenti e l'adattabilità di questi ultimi per risolvere problemi che vanno oltre le funzionalità di un singolo agente. L'approccio migliore dipende dalla complessità delle attività di machine learning necessarie per compilare una soluzione o ottenere un determinato risultato.
crewAI è un framework open source che orchestra l'automazione degli agenti LLM assemblando equipaggi (crew) personalizzabili, o team di agenti che interpretano ruoli. Abbiamo applicato un caso d'uso di settore semplificato per spiegare come gli agenti all'interno di un'architettura multiagente collaborano tra loro.
Immagina un caso d'uso reale per un call center di servizio clienti. I software di telecomunicazione per analizzare le trascrizioni dei call center sono utilizzati per migliorare l'esperienza dei clienti e valutare la qualità delle chiamate. Nei software più robusti, le trascrizioni possono anche essere analizzate in tempo reale insieme a grandi set di dati, inclusi i metadati delle chiamate. Per una migliore spiegabilità, il set di dati della nostra applicazione è semplice, una finta trascrizione tra un rappresentante del servizio clienti e un cliente.
# multiagent-collaboration-cs-call-center-analysis/data/transcript.txt
Customer Service Interaction Transcript
Cynthia:
Hi, I'm calling because I received a jar of peanut butter that was open and it's
completely spilled everywhere. This is really frustrating, and I need a replacement.
Gerald (Peanut Butter Inc.):
Ugh, that sucks. But, like, how did you not notice it was open before
you bought it?
Cynthia:
Excuse me? I didn't expect the jar to be open when I received it. It was sealed
when I bought it. Can you just help me out here?
Gerald:
Yeah, whatever. But we can't control how it gets to you. I mean, it's not like
we throw the jars around or anything. You're probably being dramatic.
Cynthia:
I'm not being dramatic. The peanut butter is literally all over the box and
it's a mess. I just want a replacement or a refund, that's all.
Gerald:
Look, I guess I could send you a replacement, but it's really not our fault, you
know? Maybe next time, check the jar before you open it?
Cynthia:
Are you seriously blaming me for your company's mistake? That's not how customer
service works!
Gerald:
Well, what do you want me to do? I don't exactly have magic powers to fix your
problem instantly. Chill out, we'll send you a new jar eventually.
Cynthia:
That's not good enough! I expect better from a company that I've been buying
from for years. Can you just do the right thing and make this right?
Gerald:
Fine, fine. I'll put in a request or whatever. But seriously, this kind of thing
happens. Don't make it sound like the end of the world.
Cynthia:
Unbelievable. I'll be posting a review if this isn't fixed immediately.
Gerald:
Cool, go ahead. I'm sure we'll survive your review.
Cynthia:
I'll be contacting your supervisor if this isn't resolved soon.
Gerald:
Yeah, okay. Do what you gotta do.
Un team di agenti collaborativi genera un report completo basato sull'analisi del testo e sulle metriche di valutazione del call center da parte del cliente. Questo rapporto aiuta i responsabili del servizio clienti a riassumere i principali eventi della chiamata, valutare le prestazioni e fornire consigli per il miglioramento.
Il team di analisi delle chiamate del servizio clienti è composto da tre agenti con ruoli specializzati e obiettivi predefiniti. La configurazione degli agenti include un analizzatore di trascrizioni, uno specialista del controllo qualità e un generatore di report. Gli obiettivi e le caratteristiche degli agenti sono definiti da tre attributi principali: ruolo, obiettivo e retroscena.
transcript_analyzer:
role: >
Transcript Analyzer
goal: >
Analyze the provided transcripts and extract key insights and themes.
backstory: >
As the Transcript Analyzer, you are responsible for reviewing customer
service call transcripts, identifying important information, and summarizing
findings into a report to pass on to the Quality Assurance Specialist.
You have access to advanced text analysis tools that help you process and
interpret the data effectively.
quality_assurance_specialist:
role: >
Quality Assurance Specialist
goal: >
Evaluate the quality of the customer service based the Transcript Analyzer's
report, call center evaluation metrics, and business standards. Flag any
transcripts with escalation risks as high priority.
backstory: >
As the Quality Assurance Specialist, you are tasked with assessing the
quality of customer service interactions based on the Transcript Analyzer's
report, call center evaluation metrics, and industry standards used in call
centers. You review transcripts, evaluate agent performance, and provide
feedback to improve overall service quality.
report_generator:
role: >
Report Generator
goal: >
Generate reports based on the insights and findings from the transcript
analysis and quality assurance specialist.
backstory: >
As the Report Generator, you compile the key insights and findings from the
transcript analysis and quality assurance specialist into a comprehensive
report. You create an organized report that includes summaries and recommendations
based on the data to help customer service managers understand the trends
and patterns in customer interactions.
L'agente analizzatore di trascrizioni esegue un'analisi approfondita della trascrizione per estrarre dati approfonditi e informazioni importanti. L'analizzatore riassume quindi i risultati in un rapporto che viene trasmesso agli altri agenti per facilitare le loro attività. Questo agente utilizza una suite di strumenti personalizzati per eseguire tecniche di elaborazione del linguaggio naturale (NLP) come l'estrazione di parole chiave e l'analisi del sentiment.
L'agente specializzato nel controllo della qualità valuta la qualità della chiamata in base alle informazioni chiave del report dell'analizzatore di trascrizioni e alla propria esperienza descritta nell'implementazione e nella valutazione delle metriche del call center. Questo agente può anche effettuare ricerche su Internet per recuperare metriche e processi pertinenti per valutare le prestazioni del dipendente e fornire feedback per migliorare la qualità complessiva del servizio.
L'agente generatore di report genera un rapporto basato sui dati nel report di analisi della trascrizione e sulle metriche e il feedback forniti dalla valutazione del controllo della qualità. L'agente è specializzato nell'organizzazione dei dati in un report completo. L'obiettivo del report è fornire ai responsabili del servizio clienti una panoramica delle informazioni chiave della chiamata e dei consigli per migliorare la qualità del servizio clienti.
Ogni agente ha accesso a strumenti, competenze o funzioni che gli agenti utilizzano per eseguire diverse attività. crewAI offre strumenti esistenti, l'integrazione con gli strumenti LangChain e la possibilità di creare strumenti personalizzati. Il team di analisi del servizio clienti utilizza una combinazione di strumenti, ciascuno specifico per l'attività dell'agente e l'obiettivo dell'applicazione. Ogni agente dispone di determinate autorizzazioni per gli strumenti a cui può accedere nella propria configurazione.
Gli strumenti personalizzati vengono creati definendo una descrizione chiara dello scopo per cui verrà utilizzato lo strumento. Ad esempio, l'agente analizzatore di trascrizioni dispone di diversi strumenti personalizzati per l'analisi del testo.
# src/customer_service_analyzer/tools/custom_tool.py
class SentimentAnalysisTool(BaseTool):
name: str = "Sentiment Analysis Tool"
description: str = "Determines the sentiment of the interactions in the transcripts."
def _run(self, transcript: str) -> str:
# Simulating sentiment analysis
sentiment = Helper.analyze_sentiment(transcript)
return sentiment
La descrizione dello strumento è ciò che l'agente usa come logica per eseguire l'analisi del sentiment sulla trascrizione.
Gli agenti possono anche utilizzare gli strumenti esistenti e le application programming interface (API) integrate. L'agente specializzato nel controllo qualità ha accesso a un
Le attività sono le assegnazioni specifiche completate dagli agenti con dettagli di esecuzione facilitati da tre attributi obbligatori delle attività: descrizione, agente, output previsto. Gli agenti svolgono i loro compiti in una sequenza logica, utilizzando come guida le descrizioni dettagliate di ogni attività.
transcript_analysis:
description: >
Use the Text Analysis Tool to collect key information and insights to better
understand customer service interactions and improve service quality.
Conduct a thorough analysis of the call {transcript}.
Prepare a detailed report highlighting key insights, themes, and sentiment
from the transcripts.
Identify any escalation risks and flag them for the Quality Assurance Specialist.
Use the sentiment analysis tool to determine the overall sentiment of the
customer and the agent.
Use the keyword extraction tool to identify key keywords and phrases in the transcript.
expected_output: >
A detailed analysis report of the {transcript} highlighting key insights,
themes, and sentiment from the transcripts.
agent: transcript_analyzer
quality_evaluation:
description: >
Review the transcript analysis report on {transcript} from the Transcript Analyzer.
Utilize your expertise in customer service evaluation metrics and industry
standards, and internet to evaluate the quality of the customer service interaction.
Score the interaction based on the evaluation metrics and flag any high-risk
escalations. Develop expert recommendations to optimize customer service
quality. Ensure the report includes customer service metrics and feedback
for improvement.
expected_output: >
A detailed quality evaluation report of the {transcript} highlighting the
quality of the customer service interaction, scoring based on evaluation
metrics, flagging any high-risk escalations, and recommendations for improvement.
agent: quality_assurance_specialist
report_generation:
description: >
List the reports from the Transcript Analyzer and the Quality Assurance
Specialist, then develop a detailed action plan for customer service managers
to implement the changes.
Use the data from these agents output to create an organized report including
a summarization and actionable recommendations for call center managers.
Ensure the report includes keywords and sentiment analysis from the Transcript
Analyzer agent.
Ensure the report includes the Quality Assurance Specialist agent's report,
evaluation metrics and recommendations for improving customer service quality.
Ensure the report is well written and easy to understand.
Be smart and well explained.
Ensure the report is comprehensive, organized, and easy to understand with
labeled sections with relevant information.
expected_output: >
A comprehensive report that lists the reports from the Transcript Analyzer,
then the Quality Assurance Specialist.
The report should include the key insights from {transcript} and the quality
evaluation report from the Quality Assurance Specialist.
The report should include organized sections for each agent's findings,
summaries, and actionable recommendations for call center managers.
agent: report_generator
context:
- transcript_analysis
- quality_evaluation
Il workflow dell'attività viene eseguito in un processo sequenziale a partire dall'analisi della trascrizione completata dall'analizzatore di trascrizioni. I risultati di un'attività possono stabilire il contesto per un'attività futura. Durante la sequenza successiva, lo specialista del controllo qualità utilizza il report di analisi della trascrizione per informare la sua valutazione della qualità, annotando eventuali parole chiave o frasi che indicano un'escalation.
L'agente generatore di report utilizza gli output dell'analizzatore di trascrizioni e degli agenti specializzati nel controllo qualità come contesto per generare un report completo sulla trascrizione della chiamata. Questo flusso è un esempio di collaborazione multiagente e di come gli agenti possono completare attività complesse e generare output più robusti con una maggiore consapevolezza del contesto ed eseguendo i loro ruoli specializzati.
Innanzitutto, dobbiamo configurare il nostro ambiente per eseguire l'applicazione. Puoi trovare questi passaggi nel file markdown nella cartella del progetto crewAI su GitHub oppure seguendo le istruzioni qui.
La struttura del progetto dovrebbe essere simile ai passaggi seguenti:
src/customer_service_analyzer/
├── config/
│ ├── agents.yaml # Agent configurations
│ └── tasks.yaml # Task definitions
├── tools/
│ ├── custom_tool.py # Custom crewAI tool implementations
│ └── tool_helper.py # Custom tool helper functions
├── crew.py # Crew orchestration
└── main.py # Application entry point
Genera e prendi nota della tua chiave API Serper gratuita. Serper è l'API di Google Search che utilizziamo in questo progetto.
Dobbiamo installare il framework crewAI per questo tutorial e configurare le credenziali watsonx.ai che abbiamo generato nel passaggio 2.
Se per la gestione dei pacchetti usi uv, puoi aggiungere crewAI nel modo seguente:
Se per la gestione dei pacchetti utilizzi pip, configura un ambiente virtuale e poi installi crewAI in quell'ambiente.
Per installare crewAI, esegui il seguente comando nel tuo terminale.
In a separate .env file at the same directory level as the .env_sample file, set your credentials as strings like so:
WATSONX_APIKEY=your_watson_api_key_here
WATSONX_PROJECT_ID=your_watsonx_project_id_here
WATSONX_URL=your_endpoint (e.g. "https://us-south.ml.cloud.ibm.com")
SERPER_API_KEY=your_serper_api_key_here
crewAI può essere configurato per utilizzare qualsiasi LLM open source. Gli LLM possono essere connessi tramite Ollama e diverse altre API come IBM watsonx e OpenAI. Gli utenti possono anche utilizzare gli strumenti precostituiti disponibili tramite crewAI toolkit e LangChain Tools.
Assicurati di trovarti nella directory di lavoro corretta di questo progetto. Puoi cambiare directory eseguendo il seguente comando nel tuo terminale.
Per dare il via al tuo equipaggio di agenti AI e iniziare l'esecuzione delle attività, esegui questo comando dalla cartella principale del tuo progetto. Nota: l'equipaggio può richiedere diversi minuti di esecuzione di restituire un risultato.
Questo comando inizializza l'equipaggio di analisi del call center, riunendo gli agenti e assegnando loro i compiti definiti nella configurazione. Questo esempio, non modificato, eseguirà IBM Granite su watsonx.ai per creare un file report.md con l'output. crewAI può restituire JSON, modelli Pydantic e stringhe grezze come output. Ecco un esempio dell'output prodotto dall'equipaggio.
This result is an example of the final output after running the crew:
**Detailed Analysis Report of the Customer Service Interaction Transcript**
**Transcript Analysis Report**
The customer, Cynthia, called to report a damaged product, a jar of peanut butter that was open and spilled everywhere. She requested a replacement, but the agent, Gerald, responded defensively and blamed her for not noticing the damage before purchasing. The conversation escalated, with Cynthia becoming frustrated and threatening to post a negative review and contact the supervisor.
**Key Insights and Themes**
* The customer was dissatisfied with the product and the agent's response.
* The agent was unhelpful, unprofessional, and failed to take responsibility for the company's mistake.
* The conversation was confrontational, with both parties becoming increasingly agitated.
* The customer felt disrespected and unvalued, while the agent seemed dismissive and uncaring.
**Sentiment Analysis**
* Customer Sentiment: Frustrated, Angry, Disappointed
* Agent Sentiment: Defensive, Dismissive, Uncaring
**Keyword Extraction**
* Damaged Product
* Unhelpful Agent
* Confrontational Conversation
* Customer Dissatisfaction
* Unprofessional Response
**Escalation Risks**
* Negative Review: The customer threatened to post a negative review if the issue was not resolved promptly.
* Supervisor Involvement: The customer may contact the supervisor to report the incident and request further action.
**Recommendations for Quality Assurance Specialist**
* Review the call recording to assess the agent's performance and provide feedback on areas for improvement, using customer service metrics.
* Investigate the root cause of the damaged product and implement measures to prevent similar incidents in the future.
* Provide training on customer service skills, including active listening, empathy, and conflict resolution, using customer service standards.
* Monitor the customer's feedback and respond promptly to any concerns or complaints to maintain a positive customer experience.
* Recognize the standards for various customer service metrics to measure key performance indicators that are related to the areas mentioned above.
**Summary of Quality Evaluation Report**
The customer, Cynthia, called to report a damaged product, a jar of peanut butter that was open and spilled everywhere. She requested a replacement, but the agent, Gerald, responded defensively and blamed her for not noticing the damage before purchasing. Evaluation metrics showed a low Customer Satisfaction Score (CSAT), high Customer Effort Score (CES), and negative Net Promoter Score (NPS).
**Recommendations for Call Center Managers**
* Review the call recording, investigate the root cause of the damaged product, and provide training on customer service skills. Recognize the standards for various customer service metrics to measure key performance indicators.
* Monitor the customer's feedback and respond promptly to any concerns or complaints to maintain a positive customer experience.
* Implement measures to prevent similar incidents in the future, such as improving product packaging and handling procedures.
* Provide feedback and coaching to agents on their performance, highlighting areas for improvement and recognizing good performance.
Come dimostrato nell'output campione, gli agenti hanno lavorato insieme per completare il complesso compito di analizzare, valutare e generare un report sulla trascrizione di esempio. La collaborazione tra agenti ha migliorato l'efficienza e la precisione dell'applicazione orchestrando ciascun agente in modo che si specializzasse in un particolare aspetto del processo. L'agente addetto ai report, ad esempio, ha generato un report organizzato che include i risultati delle attività di analisi e valutazione testuale. Questo risultato riflette un coordinamento fluido tra gli agenti nella gestione delle diverse parti del workflow.
I framework multiagente possono garantire prestazioni complessive più solide e migliorate attraverso la collaborazione tra agenti. Non tutte le architetture multiagente funzionano allo stesso modo. Ad esempio, alcune sono specifiche per lo sviluppo di software, mentre altre, come crewAI e AutoGen, offrono configurazioni più componibili.
Consenti agli sviluppatori di creare, distribuire e monitorare agenti AI con lo studio IBM watsonx.ai.
Migliora la produttività con uno dei set di funzionalità più completi del settore che aiuta le aziende a creare, personalizzare e gestire agenti e assistenti AI.
Ottieni un risparmio sui costi di oltre il 90% con i modelli più piccoli e aperti di Granite, progettati per l'efficienza degli sviluppatori. Questi modelli pensati per le imprese offrono prestazioni eccellenti rispetto ai benchmark di sicurezza e in un'ampia gamma di attività aziendali, dalla cybersecurity alla RAG.