SPB Git

Repository Public

crewai-example.md 9.8 KB 224 lines markdown

1[CrewAI](https://docs.crewai.com/introduction) is a framework for orchestrating2autonomous AI agents that collaborate to achieve complex goals. It lets you3define agents by specifying roles, goals, and backstories, and then define tasks4for them.56This example demonstrates how to build a multi-agent system for analyzing7customer support data to identify issues and propose process improvements using8Gemini 3 Flash, generating a report intended to be read by a Chief Operating9Officer (COO).1011The guide will show you how to create a "crew" of AI agents that can do the12following tasks:13141. Fetch and analyze customer support data (simulated in this example).152. Identify recurring problems and process bottlenecks.163. Suggest actionable improvements.174. Compile the findings into a concise report suitable for a COO.1819You need a Gemini API key. If you don't already have one, you can [get one in20Google AI Studio](https://aistudio.google.com/apikey).2122    pip install "crewai[tools]"2324Set your Gemini API key as an environment variable named `GEMINI_API_KEY`, then25configure CrewAI to use the Gemini model.2627    import os28    from crewai import LLM2930    gemini_api_key = os.getenv("GEMINI_API_KEY")3132    gemini_llm = LLM(33        model='gemini/gemini-3.8-flash',34        api_key=gemini_api_key,35        temperature=1.0  # Use the Gemini 3 recommended temperature36    )3738## Define components3940Build CrewAI applications using **Tools** , **Agents** , **Tasks** , and the41**Crew** itself. The following sections explain each of these components.4243### Tools4445Tools are capabilities that agents can use to interact with the outside world or46perform specific actions. Here, you define a placeholder tool to simulate47fetching customer support data. In a real application, you would connect to a48database, API or file system. For more information on tools, see the [CrewAI49tools guide](https://docs.crewai.com/concepts/tools).5051    from crewai.tools import BaseTool5253    # Placeholder tool for fetching customer support data54    class CustomerSupportDataTool(BaseTool):55        name: str = "Customer Support Data Fetcher"56        description: str = (57          "Fetches recent customer support interactions, tickets, and feedback. "58          "Returns a summary string.")5960        def _run(self, argument: str) -> str:61            # In a real scenario, this would query a database or API.62            # For this example, return simulated data.63            print(f"--- Fetching data for query: {argument} ---")64            return (65                """Recent Support Data Summary:66    - 50 tickets related to 'login issues'. High resolution time (avg 48h).67    - 30 tickets about 'billing discrepancies'. Mostly resolved within 12h.68    - 20 tickets on 'feature requests'. Often closed without resolution.69    - Frequent feedback mentions 'confusing user interface' for password reset.70    - High volume of calls related to 'account verification process'.71    - Sentiment analysis shows growing frustration with 'login issues' resolution time.72    - Support agent notes indicate difficulty reproducing 'login issues'."""73            )7475    support_data_tool = CustomerSupportDataTool()7677### Agents7879Agents are the individual AI workers in your crew. Each agent has a specific80`role`, `goal`, `backstory`, assigned `llm`, and optional `tools`. For more81information on agents, see the [CrewAI agents82guide](https://docs.crewai.com/concepts/agents).8384    from crewai import Agent8586    # Agent 1: Data analyst87    data_analyst = Agent(88        role='Customer Support Data Analyst',89        goal='Analyze customer support data to identify trends, recurring issues, and key pain points.',90        backstory=(91            """You are an expert data analyst specializing in customer support operations.92            Your strength lies in identifying patterns and quantifying problems from raw support data."""93        ),94        verbose=True,95        allow_delegation=False,  # This agent focuses on its specific task96        tools=[support_data_tool],  # Assign the data fetching tool97        llm=gemini_llm  # Use the configured Gemini LLM98    )99100    # Agent 2: Process optimizer101    process_optimizer = Agent(102        role='Process Optimization Specialist',103        goal='Identify bottlenecks and inefficiencies in current support processes based on the data analysis. Propose actionable improvements.',104        backstory=(105            """You are a specialist in optimizing business processes, particularly in customer support.106            You excel at pinpointing root causes of delays and inefficiencies and suggesting concrete solutions."""107        ),108        verbose=True,109        allow_delegation=False,110        # No tools needed, this agent relies on the context provided by data_analyst.111        llm=gemini_llm112    )113114    # Agent 3: Report writer115    report_writer = Agent(116        role='Executive Report Writer',117        goal='Compile the analysis and improvement suggestions into a concise, clear, and actionable report for the COO.',118        backstory=(119            """You are a skilled writer adept at creating executive summaries and reports.120            You focus on clarity, conciseness, and highlighting the most critical information and recommendations for senior leadership."""121        ),122        verbose=True,123        allow_delegation=False,124        llm=gemini_llm125    )126127### Tasks128129Tasks define the specific assignments for the agents. Each task has a130`description`, `expected_output`, and is assigned to an `agent`. Tasks are run131sequentially by default and include the context of the previous task. For more132information on tasks, see the [CrewAI tasks133guide](https://docs.crewai.com/concepts/tasks).134135    from crewai import Task136137    # Task 1: Analyze data138    analysis_task = Task(139        description=(140            """Fetch and analyze the latest customer support interaction data (tickets, feedback, call logs)141            focusing on the last quarter. Identify the top 3-5 recurring issues, quantify their frequency142            and impact (e.g., resolution time, customer sentiment). Use the Customer Support Data Fetcher tool."""143        ),144        expected_output=(145            """A summary report detailing the key findings from the customer support data analysis, including:146    - Top 3-5 recurring issues with frequency.147    - Average resolution times for these issues.148    - Key customer pain points mentioned in feedback.149    - Any notable trends in sentiment or support agent observations."""150        ),151        agent=data_analyst  # Assign task to the data_analyst agent152    )153154    # Task 2: Identify bottlenecks and suggest improvements155    optimization_task = Task(156        description=(157            """Based on the data analysis report provided by the Data Analyst, identify the primary bottlenecks158            in the support processes contributing to the identified issues (especially the top recurring ones).159            Propose 2-3 concrete, actionable process improvements to address these bottlenecks.160            Consider potential impact and ease of implementation."""161        ),162        expected_output=(163            """A concise list identifying the main process bottlenecks (e.g., lack of documentation for agents,164            complex escalation path, UI issues) linked to the key problems.165    A list of 2-3 specific, actionable recommendations for process improvement166    (e.g., update agent knowledge base, simplify password reset UI, implement proactive monitoring)."""167        ),168        agent=process_optimizer  # Assign task to the process_optimizer agent169        # This task implicitly uses the output of analysis_task as context170    )171172    # Task 3: Compile COO report173    report_task = Task(174        description=(175            """Compile the findings from the Data Analyst and the recommendations from the Process Optimization Specialist176            into a single, concise executive report for the COO. The report should clearly state:177    1. The most critical customer support issues identified (with brief data points).178    2. The key process bottlenecks causing these issues.179    3. The recommended process improvements.180    Ensure the report is easy to understand, focuses on actionable insights, and is formatted professionally."""181        ),182        expected_output=(183            """A well-structured executive report (max 1 page) summarizing the critical support issues,184            underlying process bottlenecks, and clear, actionable recommendations for the COO.185            Use clear headings and bullet points."""186        ),187        agent=report_writer  # Assign task to the report_writer agent188    )189190### Crew191192The `Crew` brings the agents and tasks together, defining the workflow process193(such as "sequential").194195    from crewai import Crew, Process196197    support_analysis_crew = Crew(198        agents=[data_analyst, process_optimizer, report_writer],199        tasks=[analysis_task, optimization_task, report_task],200        process=Process.sequential,  # Tasks will run sequentially in the order defined201        verbose=True202    )203204## Run the crew205206Finally, kick off the crew execution with any necessary inputs.207208    # Start the crew's work209    print("--- Starting Customer Support Analysis Crew ---")210    # The 'inputs' dictionary provides initial context if needed by the first task.211    # In this case, the tool simulates data fetching regardless of the input.212    result = support_analysis_crew.kickoff(inputs={'data_query': 'last quarter support data'})213214    print("--- Crew Execution Finished ---")215    print("--- Final Report for COO ---")216    print(result)217218The script will now execute. The `Data Analyst` will use the tool, the `Process219Optimizer` will analyze the findings, and the `Report Writer` will compile the220final report, which is then printed to the console. The `verbose=True` setting221will show the detailed thought process and actions of each agent.222223To learn more about CrewAI, check out the [CrewAI224introduction](https://docs.crewai.com/introduction).
Files main
Menu

Theme