Gemini 2.5 Pro 및 CrewAI를 사용한 고객 지원 분석

CrewAI는 복잡한 목표를 달성하기 위해 협력하는 자율 AI 에이전트를 조정하기 위해 설계되었습니다. 특정 역할, 목표, 배경 스토리가 있는 에이전트를 정의한 다음 에이전트에게 태스크를 할당하여 멀티 에이전트 시스템의 개발을 간소화할 수 있습니다. 이 예에서는 COO (최고운영책임자) 사용 사례를 위한 멀티 에이전트 시스템을 빌드하는 방법을 보여줍니다. 즉, 고객 지원 데이터를 분석하여 문제를 파악하고 Gemini 2.5 Pro를 사용하여 ���로세스 개선을 제안합니다.

목표는 다음과 같은 작업을 할 수 있는 AI 상담사 '팀'을 만드는 것입니다.

  1. 고객 지원 데이터를 가져와 분석합니다 (이 예에서는 시뮬레이션됨).
  2. 반복되는 문제와 프로세스 병목 현상을 파악합니다.
  3. 조치 가능한 개선사항을 제안합니다.
  4. 발견한 내용을 COO에게 적합한 간결한 보고서로 작성합니다.

아직 Gemini API 키가 없다면 Google AI Studio에서 무료로 가져올 수 있습니다.

 pip install "crewai[tools]"

Gemini API 키를 GEMINI_API_KEY라는 환경 변수로 설정합니다. Gemini 2.5 Pro 모델을 사용하도록 CrewAI를 구성합니다.

import os
from crewai import LLM

# Read your API key from the environment variable
gemini_api_key = os.getenv("GEMINI_API_KEY")

if not gemini_api_key:
    raise ValueError("GEMINI_API_KEY environment variable not set.")

# Use Gemini 2.5 Pro Experimental model
gemini_llm = LLM(
    model='gemini/gemini-2.5-pro-preview-05-06', 
    api_key=gemini_api_key,
    temperature=0.0 # Lower temperature for more factual analysis
)

구성요소 정의

CrewAI 애플리케이션은 도구, 상담사, 작업, 크루 자체 등 여러 주요 구성요소를 사용하여 빌드됩니다.

도구

도구는 에이전트가 외부 세계와 상호작용하거나 특정 작업을 실행하는 데 사용할 수 있는 기능입니다. 여기서는 고객 지원 데이터 가져오기를 시뮬레이션하는 자리표시자 도구를 정의합니다. 실제 애플리케이션에서는 데이터베이스, API 또는 파일 시스템에 연결할 수 있습니다.

from crewai.tools import BaseTool

# Placeholder Tool for fetching customer support data
class CustomerSupportDataTool(BaseTool):
    name: str = "Customer Support Data Fetcher"
    description: str = "Fetches recent customer support interactions, tickets, and feedback. Returns a summary string."

    def _run(self, argument: str) -> str:
        # In a real scenario, this would query a database or API.
        # For this example, we return simulated data.
        print(f"--- Fetching data for query: {argument} ---")
        return (
            """Recent Support Data Summary:
- 50 tickets related to 'login issues'. High resolution time (avg 48h).
- 30 tickets about 'billing discrepancies'. Mostly resolved within 12h.
- 20 tickets on 'feature requests'. Often closed without resolution.
- Frequent feedback mentions 'confusing user interface' for password reset.
- High volume of calls related to 'account verification process'.
- Sentiment analysis shows growing frustration with 'login issues' resolution time.
- Support agent notes indicate difficulty reproducing 'login issues'."""
        )

support_data_tool = CustomerSupportDataTool()

에이전트

상담사는 크루의 개별 AI 작업자입니다. 각 에이전트에는 특정 role, goal, backstory, 할당된 llm, tools가 있을 수 있습니다.

from crewai import Agent

# Agent 1: Data Analyst
data_analyst = Agent(
    role='Customer Support Data Analyst',
    goal='Analyze customer support data to identify trends, recurring issues, and key pain points.',
    backstory=(
        """You are an expert data analyst specializing in customer support operations. 
        Your strength lies in identifying patterns and quantifying problems from raw support data."""
    ),
    verbose=True,
    allow_delegation=False, # This agent focuses on its specific task
    tools=[support_data_tool], # Assign the data fetching tool
    llm=gemini_llm # Use the configured Gemini LLM
)

# Agent 2: Process Optimizer
process_optimizer = Agent(
    role='Process Optimization Specialist',
    goal='Identify bottlenecks and inefficiencies in current support processes based on the data analysis. Propose actionable improvements.',
    backstory=(
        """You are a specialist in optimizing business processes, particularly in customer support. 
        You excel at pinpointing root causes of delays and inefficiencies and suggesting concrete solutions."""
    ),
    verbose=True,
    allow_delegation=False,
    # No specific tools needed, relies on the analysis context provided by the data_analyst
    llm=gemini_llm
)

# Agent 3: Report Writer
report_writer = Agent(
    role='Executive Report Writer',
    goal='Compile the analysis and improvement suggestions into a concise, clear, and actionable report for the COO.',
    backstory=(
        """You are a skilled writer adept at creating executive summaries and reports. 
        You focus on clarity, conciseness, and highlighting the most critical information and recommendations for senior leadership."""
    ),
    verbose=True,
    allow_delegation=False,
    llm=gemini_llm
)

작업

태스크는 상담사의 구체적인 할당을 정의합니다. 각 작업에는 description, expected_output가 있으며 agent에 할당됩니다. 태스크는 이전 태스크의 출력에 종속될 수 있습니다.

from crewai import Task

# Task 1: Analyze Data
analysis_task = Task(
    description=(
        """Fetch and analyze the latest customer support interaction data (tickets, feedback, call logs) 
        focusing on the last quarter. Identify the top 3-5 recurring issues, quantify their frequency 
        and impact (e.g., resolution time, customer sentiment). Use the Customer Support Data Fetcher tool."""
    ),
    expected_output=(
        """A summary report detailing the key findings from the customer support data analysis, including:
- Top 3-5 recurring issues with frequency.
- Average resolution times for these issues.
- Key customer pain points mentioned in feedback.
- Any notable trends in sentiment or support agent observations."""
    ),
    agent=data_analyst # Assign task to the data_analyst agent
)

# Task 2: Identify Bottlenecks and Suggest Improvements
optimization_task = Task(
    description=(
        """Based on the data analysis report provided by the Data Analyst, identify the primary bottlenecks 
        in the support processes contributing to the identified issues (especially the top recurring ones). 
        Propose 2-3 concrete, actionable process improvements to address these bottlenecks. 
        Consider potential impact and ease of implementation."""
    ),
    expected_output=(
        """A concise list identifying the main process bottlenecks (e.g., lack of documentation for agents, 
        complex escalation path, UI issues) linked to the key problems. 
A list of 2-3 specific, actionable recommendations for process improvement 
(e.g., update agent knowledge base, simplify password reset UI, implement proactive monitoring)."""
    ),
    agent=process_optimizer # Assign task to the process_optimizer agent
    # This task implicitly uses the output of analysis_task as context
)

# Task 3: Compile COO Report
report_task = Task(
    description=(
        """Compile the findings from the Data Analyst and the recommendations from the Process Optimization Specialist 
        into a single, concise executive report for the COO. The report should clearly state:
1. The most critical customer support issues identified (with brief data points).
2. The key process bottlenecks causing these issues.
3. The recommended process improvements.
Ensure the report is easy to understand, focuses on actionable insights, and is formatted professionally."""
    ),
    expected_output=(
        """A well-structured executive report (max 1 page) summarizing the critical support issues, 
        underlying process bottlenecks, and clear, actionable recommendations for the COO. 
        Use clear headings and bullet points."""
    ),
    agent=report_writer # Assign task to the report_writer agent
)

크루넥

Crew는 상담사와 태스크를 함께 가져와 워크플로 프로세스 (예: 순차적)를 정의합니다.

from crewai import Crew, Process

# Define the crew with agents, tasks, and process
support_analysis_crew = Crew(
    agents=[data_analyst, process_optimizer, report_writer],
    tasks=[analysis_task, optimization_task, report_task],
    process=Process.sequential,  # Tasks will run sequentially in the order defined
    verbose=True
)

크루 실행

마지막으로 필요한 입력으로 크루 실행을 시작합니다.

# Start the crew's work
print("--- Starting Customer Support Analysis Crew ---")
# The 'inputs' dictionary provides initial context if needed by the first task.
# In this case, the tool simulates data fetching regardless of the input.
result = support_analysis_crew.kickoff(inputs={'data_query': 'last quarter support data'})

print("--- Crew Execution Finished ---")
print("--- Final Report for COO ---")
print(result)

이제 스크립트가 실행됩니다. Data Analyst는 도구를 사용하고, Process Optimizer는 결과를 분석하고, Report Writer는 최종 보고서를 컴파일하여 콘솔에 출력합니다. verbose=True 설정에는 각 상담사의 사고 과정과 작업이 자세히 표시됩니다.