使用CrewAI的併發查詢解決系統

使用CrewAI的併發查詢解決系統

人工智慧時代企業不斷尋求創新方法來提升客戶支援服務。其中一種方法就是利用協同工作的人工智慧代理來高效解決客戶查詢。本文探討了如何利用 CrewAI、OpenAI 的 GPT 模型和 Google Gemini 實現併發查詢解決系統。該系統採用多個並行操作的專業代理,無縫處理客戶查詢,縮短響應時間並提高準確性。

  • 瞭解人工智慧代理如何通過自動回覆和總結關鍵資訊來高效處理客戶查詢。
  • 瞭解 CrewAI 如何實現多代理協作以改進客戶支援工作流程。
  • 探索不同型別的人工智慧代理(如查詢解析器和彙總器)及其在客戶服務自動化中的作用。
  • 使用 Python的 asyncio 實現併發查詢處理,以提高響應效率。
  • 通過整合人工智慧驅動的自動化來優化客戶支援系統,從而提高準確性和可擴充套件性。

AI代理如何協同工作?

併發查詢解決系統採用多代理框架,為每個代理分配特定的角色。該系統採用了 CrewAI,這是一個能讓人工智慧代理有效協作的框架。

系統的主要組成部分包括

  • 查詢解決代理:負責瞭解客戶詢問並提供準確答覆。
  • 摘要代理:總結解決過程,以便快速審查和將來參考。
  • LLMs (大型語言模型):包括 GPT-4o 和 Gemini 等模型,每個模型都有不同的配置,以平衡速度和準確性。
  • 任務管理:向代理動態分配任務,確保併發查詢處理。

併發查詢解決系統的實現

要將人工智慧代理框架從概念轉化為現實,結構化的實施方法至關重要。下面,我們將概述為有效解決查詢問題而設定和整合人工智慧代理所涉及的關鍵步驟。

步驟 1:設定 API 金鑰

OpenAI API 金鑰使用 os 模組儲存為環境變數。這樣,系統就可以安全地驗證 API 請求,而無需硬編碼敏感憑據。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
# Set the API key as an environment variable
os.environ["OPENAI_API_KEY"] = ""
import os # Set the API key as an environment variable os.environ["OPENAI_API_KEY"] = ""
import os 
# Set the API key as an environment variable
os.environ["OPENAI_API_KEY"] = ""

系統使用 os 模組與作業系統互動。

系統將 OPENAI_API_KEY 設定為環境變數,以便對 OpenAI 的 API 請求進行驗證。

步驟 2:匯入所需庫函式

匯入必要的庫,包括用於處理非同步操作的 asynciocrewai 元件(如AgentCrewTask 和 LLM)。這些對於定義和管理人工智慧代理至關重要。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import asyncio
from crewai import Agent, Crew, Task, LLM, Process
import google.generativeai as genai
import asyncio from crewai import Agent, Crew, Task, LLM, Process import google.generativeai as genai
import asyncio
from crewai import Agent, Crew, Task, LLM, Process
import google.generativeai as genai
  • asyncio:Python 用於非同步程式設計的內建模組,支援併發執行。
  • Agent:代表具有特定職責的人工智慧工作者。
  • Crew:管理多個代理及其互動。
  • Task:定義每個代理應該做什麼。
  • LLM:指定使用的大型語言模型。
  • Process:定義任務的執行方式,是順序執行還是並行執行。
  • google.generativeai: 用於使用谷歌生成式人工智慧模型的庫(本片段未使用,但可能包含在內以備將來擴充套件之用)。

步驟 3:初始化LLM

以不同的溫度設定初始化三個不同的 LLM 例項(GPT-4oGPT-4)。溫度控制響應的創造性,確保人工智慧生成答案的準確性和靈活性之間的平衡。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Initialize the LLM with Gemini
llm_1 = LLM(
model="gpt-4o",
temperature=0.7)
llm_2 = LLM(
model="gpt-4",
temperature=0.2)
llm_3 = LLM(
model="gpt-4o",
temperature=0.3)系統會建立三個 LLM 例項,每個例項都有不同的配置。
# Initialize the LLM with Gemini llm_1 = LLM( model="gpt-4o", temperature=0.7) llm_2 = LLM( model="gpt-4", temperature=0.2) llm_3 = LLM( model="gpt-4o", temperature=0.3)系統會建立三個 LLM 例項,每個例項都有不同的配置。
# Initialize the LLM with Gemini
llm_1 = LLM(
model="gpt-4o",
temperature=0.7)
llm_2 = LLM(
model="gpt-4",
temperature=0.2)
llm_3 = LLM(
model="gpt-4o",
temperature=0.3)系統會建立三個 LLM 例項,每個例項都有不同的配置。

引數:

  • model: 指定要使用的 OpenAI 模型(gpt-4o 或 gpt-4)。
  • temperature: 控制響應的隨機性(0 = 確定性,1 = 更有創造力)。

這些不同的模型和溫度有助於平衡準確性和創造性。

步驟 4:定義人工智慧代理

每個代理都有特定的角色和預定義的目標。我們建立了兩個人工智慧代理:

  • Query Resolver:處理客戶查詢並提供詳細回覆。
  • Summary Generator:每個代理都有確定的角色、目標和背景故事,以指導其互動。

Query Resolver代理

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
query_resolution_agent = Agent(
llm=llm_1,
role="Query Resolver",
backstory="An AI agent that resolves customer queries efficiently and professionally.",
goal="Resolve customer queries accurately and provide helpful solutions.",
verbose=True
)
query_resolution_agent = Agent( llm=llm_1, role="Query Resolver", backstory="An AI agent that resolves customer queries efficiently and professionally.", goal="Resolve customer queries accurately and provide helpful solutions.", verbose=True )
query_resolution_agent = Agent(
llm=llm_1,
role="Query Resolver",
backstory="An AI agent that resolves customer queries efficiently and professionally.",
goal="Resolve customer queries accurately and provide helpful solutions.",
verbose=True
)

讓我們看看這個程式碼塊中發生了什麼

  • Agent Creation:query_resolution_agent 是一個人工智慧助手,負責解決客戶的詢問。
  • Model Selection:它使用 llm_1,配置為 GPT-4o,溫度為 0.7。這種平衡可以做出既有創意又準確的回覆。
  • Role:系統指定該代理為查詢解決者。
  • Backstory:開發人員對代理進行程式設計,使其充當專業的客戶服務助理,確保高效、專業的回覆。
  • Goal:為使用者查詢提供準確的解決方案。
  • Verbose Mode:verbose=True 可確保記錄詳細日誌,幫助開發人員除錯和跟蹤其效能。

Summary代理

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
summary_agent = Agent(
llm=llm_2,
role="Summary Generator",
backstory="An AI agent that summarizes the resolution of customer queries.",
goal="Provide a concise summary of the query resolution process.",
verbose=True
)
summary_agent = Agent( llm=llm_2, role="Summary Generator", backstory="An AI agent that summarizes the resolution of customer queries.", goal="Provide a concise summary of the query resolution process.", verbose=True )
summary_agent = Agent(
llm=llm_2,
role="Summary Generator",
backstory="An AI agent that summarizes the resolution of customer queries.",
goal="Provide a concise summary of the query resolution process.",
verbose=True
)

程式碼塊包括:

  • Agent Creation:summary_agent 用於彙總查詢結果。
  • Model Selection:使用 temperature 為 0.2 的 llm_2 (GPT-4),使其響應更加確定和精確。
  • Role:該代理充當摘要生成器。
  • Backstory:它能簡明扼要地總結查詢決議,以便快速參考。
  • Goal:它能簡明扼要地總結客戶查詢的解決情況。
  • Verbose Mode:verbose=True 可確保在需要時提供除錯資訊。

步驟 5:定義任務

系統會動態分配任務,以確保並行查詢處理。

本節定義了並行查詢解決系統中分配給人工智慧代理的任務。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
resolution_task = Task(
description="Resolve the customer query: {query}.",
expected_output="A detailed resolution for the customer query.",
agent=query_resolution_agent
)
summary_task = Task(
description="Summarize the resolution of the customer query: {query}.",
expected_output="A concise summary of the query resolution.",
agent=summary_agent
)
resolution_task = Task( description="Resolve the customer query: {query}.", expected_output="A detailed resolution for the customer query.", agent=query_resolution_agent ) summary_task = Task( description="Summarize the resolution of the customer query: {query}.", expected_output="A concise summary of the query resolution.", agent=summary_agent )
resolution_task = Task(
description="Resolve the customer query: {query}.",
expected_output="A detailed resolution for the customer query.",
agent=query_resolution_agent
)
summary_task = Task(
description="Summarize the resolution of the customer query: {query}.",
expected_output="A concise summary of the query resolution.",
agent=summary_agent
)

程式碼說明

定義任務:

  • resolution_task: 該任務指示查詢解決代理分析和解決客戶查詢。
  • summary_task: 該任務指示摘要代理生成解決過程的簡要摘要。

動態查詢處理:

  • 執行任務時,系統會用實際客戶查詢替換 {query}
  • 這樣,系統就可以動態處理任何客戶查詢。

預期輸出:

  • resolution_task 希望得到對查詢的詳細回覆。
  • summary_task 生成查詢解決的簡明摘要。

代理分配:

  • 分配 query_resolution_agent 處理解決任務。
  • summary_agent 用於處理摘要任務。

重要性

  • 任務專業化:每個人工智慧代理都有特定的工作,從而確保效率和清晰度。
  • 可擴充套件性:您可以新增更多工和代理,以處理不同型別的客戶支援互動。
  • 並行處理:任務可同時執行,減少客戶等待時間。

步驟 6:使用人工智慧代理執行查詢

建立一個非同步函式來處理查詢。Crew 類組織代理和任務,按順序執行,以確保正確的查詢解析和彙總。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
async def execute_query(query: str):
crew = Crew(
agents=[query_resolution_agent, summary_agent],
tasks=[resolution_task, summary_task],
process=Process.sequential,
verbose=True
)
result = await crew.kickoff_async(inputs={"query": query})
return result
async def execute_query(query: str): crew = Crew( agents=[query_resolution_agent, summary_agent], tasks=[resolution_task, summary_task], process=Process.sequential, verbose=True ) result = await crew.kickoff_async(inputs={"query": query}) return result
async def execute_query(query: str):
crew = Crew(
agents=[query_resolution_agent, summary_agent],
tasks=[resolution_task, summary_task],
process=Process.sequential,
verbose=True
)
result = await crew.kickoff_async(inputs={"query": query})
return result

該函式定義了一個執行查詢的非同步流程。它建立一個 Crew 例項,其中包括

  • agents:參與流程的人工智慧代理(查詢解析器和摘要生成器)。
  • tasks:分配給代理的任務(查詢解析和摘要生成)。
  • process=Process.sequential:確保任務按順序執行。
  • verbose=True:啟用詳細日誌,以便更好地跟蹤。

該函式使用 await 非同步執行人工智慧代理並返回結果。

步驟 7:同時處理多個查詢

使用 asyncio.gather(),可以同時處理多個查詢。這樣,人工智慧代理就可以並行處理不同的客戶問題,從而縮短響應時間。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
async def handle_two_queries(query_1: str, query_2: str):
# Run both queries concurrently
results = await asyncio.gather(
execute_query(query_1),
execute_query(query_2)
)
return results
async def handle_two_queries(query_1: str, query_2: str): # Run both queries concurrently results = await asyncio.gather( execute_query(query_1), execute_query(query_2) ) return results
async def handle_two_queries(query_1: str, query_2: str):
# Run both queries concurrently
results = await asyncio.gather(
execute_query(query_1),
execute_query(query_2)
)
return results

asyncio.gather() 同時處理兩個查詢,大大縮短了響應時間。執行完成後,該函式將返回兩個查詢的結果

步驟 8:定義示例查詢

開發人員定義示例查詢來測試系統,涵蓋常見的客戶支援問題,如登入失敗和支付處理錯誤。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
query_1 = "I am unable to log in to my account. It says 'Invalid credentials', but I am sure I am using the correct username and password."
query_2 = "The payment gateway is not working. Also, a weird error message is displayed. My card has been charged, but the transaction is not going through."
query_1 = "I am unable to log in to my account. It says 'Invalid credentials', but I am sure I am using the correct username and password." query_2 = "The payment gateway is not working. Also, a weird error message is displayed. My card has been charged, but the transaction is not going through."
query_1 = "I am unable to log in to my account. It says 'Invalid credentials', but I am sure I am using the correct username and password."
query_2 = "The payment gateway is not working. Also, a weird error message is displayed. My card has been charged, but the transaction is not going through."

這些是測試系統的示例查詢。

查詢 1 涉及登入問題,查詢 2 則與支付閘道器錯誤有關。

步驟 9:設定事件迴圈

系統會初始化一個事件迴圈,以處理非同步操作。如果找不到現有的迴圈,系統會建立一個新的迴圈來管理 AI 任務的執行。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

本節確保事件迴圈可用於執行非同步任務。

如果系統檢測到沒有事件迴圈(發生 RuntimeError),則會建立一個新迴圈並將其設定為活動迴圈。

步驟 10: 在 Jupyter Notebook/Google Colab 中處理事件迴圈

由於 Jupyter 和 Colab 都有預先存在的事件迴圈,nest_asyncio.apply()可用於防止衝突,確保非同步查詢的順利執行。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Check if the event loop is already running
if loop.is_running():
# If the loop is running, use `nest_asyncio` to allow re-entrant event loops
import nest_asyncio
nest_asyncio.apply()
# Check if the event loop is already running if loop.is_running(): # If the loop is running, use `nest_asyncio` to allow re-entrant event loops import nest_asyncio nest_asyncio.apply()
# Check if the event loop is already running
if loop.is_running():
# If the loop is running, use `nest_asyncio` to allow re-entrant event loops
import nest_asyncio
nest_asyncio.apply()

Jupyter Notebooks 和 Google Colab 預先存在事件迴圈,在執行非同步函式時可能會導致錯誤。

nest_asyncio.apply()允許巢狀事件迴圈,從而解決了相容性問題。

步驟 11:執行查詢並列印結果

事件迴圈執行handle_two_queries(),併發處理查詢。系統會列印人工智慧生成的最終響應,顯示查詢結果和摘要。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Run the async function
results = loop.run_until_complete(handle_two_queries(query_1, query_2))
# Print the results
for i, result in enumerate(results):
print(f"Result for Query {i+1}:")
print(result)
print("\n---\n")
# Run the async function results = loop.run_until_complete(handle_two_queries(query_1, query_2)) # Print the results for i, result in enumerate(results): print(f"Result for Query {i+1}:") print(result) print("\n---\n")
# Run the async function
results = loop.run_until_complete(handle_two_queries(query_1, query_2))
# Print the results
for i, result in enumerate(results):
print(f"Result for Query {i+1}:")
print(result)
print("\n---\n")

loop.run_until_complete() 開始執行 handle_two_queries(),同時處理兩個查詢。

系統會列印結果,顯示人工智慧為每個查詢生成的決議。

執行查詢並列印結果

執行查詢並列印結果

併發查詢解析系統的優勢

下面,我們將瞭解併發查詢解析系統如何通過同時處理多個查詢來提高效率,從而加快響應時間並改善使用者體驗。

  • 更快的響應時間:並行執行可同時解決多個查詢。
  • 提高準確性:利用多個 LLM 可確保創造性和事實正確性之間的平衡。
  • 可擴充套件性:系統可處理大量查詢,無需人工干預。
  • 更好的客戶體驗:自動摘要可提供查詢解決方案的快速概覽。

併發查詢解決系統的應用

下面我們將探討併發查詢解決系統的各種應用,包括客戶支援自動化、聊天機器人中的實時查詢處理以及大規模服務請求的高效處理。

  • 客戶支援自動化:使人工智慧驅動的聊天機器人能夠同時解決多個客戶查詢,從而縮短響應時間。
  • 實時查詢處理:通過並行處理大量查詢,提高即時支援系統的效率。
  • 電子商務協助:簡化線上購物平臺中的產品查詢、訂單跟蹤和支付問題解決方案。
  • IT 服務檯管理:通過同時診斷和解決多個技術問題,為 IT 服務檯提供支援。
  • 醫療保健與遠端醫療:協助同時管理病人諮詢、預約安排和醫療建議。

小結

併發查詢解決系統展示了人工智慧驅動的多代理協作如何徹底改變客戶支援。通過利用 CrewAI、OpenAI 的 GPT 模型和 Google Gemini,企業可以自動處理查詢,提高效率和使用者滿意度。這種方法為未來更先進的人工智慧驅動服務解決方案鋪平了道路。

  • 人工智慧代理可簡化客戶支援,縮短響應時間。
  • CrewAI 使專業代理能夠有效地協同工作。
  • 使用 asyncio 可同時處理多個查詢。
  • 不同的 LLM 配置可兼顧準確性和創造性。
  • 系統可管理大量查詢,無需人工干預。
  • 自動摘要提供快速、清晰的查詢解決方案。

評論留言