[ { "source": "https://docs.crewai.com/en/observability/patronus-evaluation", "title": "Patronus AI Evaluation - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nPatronus AI Evaluation\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nPatronus AI Evaluation\nCopy page\nMonitor and evaluate CrewAI agent performance using Patronus AI’s comprehensive evaluation platform for LLM outputs and agent behaviors.\n​\nPatronus AI Evaluation\n\n\n​\nOverview\n\n\nPatronus AI\n provides comprehensive evaluation and monitoring capabilities for CrewAI agents, enabling you to assess model outputs, agent behaviors, and overall system performance. This integration allows you to implement continuous evaluation workflows that help maintain quality and reliability in production environments.\n\n\n​\nKey Features\n\n\n\n\nAutomated Evaluation\n: Real-time assessment of agent outputs and behaviors\n\n\nCustom Criteria\n: Define specific evaluation criteria tailored to your use cases\n\n\nPerformance Monitoring\n: Track agent performance metrics over time\n\n\nQuality Assurance\n: Ensure consistent output quality across different scenarios\n\n\nSafety & Compliance\n: Monitor for potential issues and policy violations\n\n\n\n\n​\nEvaluation Tools\n\n\nPatronus provides three main evaluation tools for different use cases:\n\n\n\n\nPatronusEvalTool\n: Allows agents to select the most appropriate evaluator and criteria for the evaluation task.\n\n\nPatronusPredefinedCriteriaEvalTool\n: Uses predefined evaluator and criteria specified by the user.\n\n\nPatronusLocalEvaluatorTool\n: Uses custom function evaluators defined by the user.\n\n\n\n\n​\nInstallation\n\n\nTo use these tools, you need to install the Patronus package:\n\n\nCopy\nAsk AI\nuv\n add\n patronus\n\n\n\n\nYou’ll also need to set up your Patronus API key as an environment variable:\n\n\nCopy\nAsk AI\nexport\n PATRONUS_API_KEY\n=\n\"your_patronus_api_key\"\n\n\n\n\n​\nSteps to Get Started\n\n\nTo effectively use the Patronus evaluation tools, follow these steps:\n\n\n\n\nInstall Patronus\n: Install the Patronus package using the command above.\n\n\nSet Up API Key\n: Set your Patronus API key as an environment variable.\n\n\nChoose the Right Tool\n: Select the appropriate Patronus evaluation tool based on your needs.\n\n\nConfigure the Tool\n: Configure the tool with the necessary parameters.\n\n\n\n\n​\nExamples\n\n\n​\nUsing PatronusEvalTool\n\n\nThe following example demonstrates how to use the \nPatronusEvalTool\n, which allows agents to select the most appropriate evaluator and criteria:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n PatronusEvalTool\n\n\n\n\n# Initialize the tool\n\n\npatronus_eval_tool \n=\n PatronusEvalTool()\n\n\n\n\n# Define an agent that uses the tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Coding Agent\"\n,\n\n\n goal\n=\n\"Generate high quality code and verify that the output is code\"\n,\n\n\n backstory\n=\n\"An experienced coder who can generate high quality python code.\"\n,\n\n\n tools\n=\n[patronus_eval_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Example task to generate and evaluate code\n\n\ngenerate_code_task \n=\n Task(\n\n\n description\n=\n\"Create a simple program to generate the first N numbers in the Fibonacci sequence. Select the most appropriate evaluator and criteria for evaluating your output.\"\n,\n\n\n expected_output\n=\n\"Program that generates the first N numbers in the Fibonacci sequence.\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[generate_code_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nUsing PatronusPredefinedCriteriaEvalTool\n\n\nThe following example demonstrates how to use the \nPatronusPredefinedCriteriaEvalTool\n, which uses predefined evaluator and criteria:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n PatronusPredefinedCriteriaEvalTool\n\n\n\n\n# Initialize the tool with predefined criteria\n\n\npatronus_eval_tool \n=\n PatronusPredefinedCriteriaEvalTool(\n\n\n evaluators\n=\n[{\n\"evaluator\"\n: \n\"judge\"\n, \n\"criteria\"\n: \n\"contains-code\"\n}]\n\n\n)\n\n\n\n\n# Define an agent that uses the tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Coding Agent\"\n,\n\n\n goal\n=\n\"Generate high quality code\"\n,\n\n\n backstory\n=\n\"An experienced coder who can generate high quality python code.\"\n,\n\n\n tools\n=\n[patronus_eval_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Example task to generate code\n\n\ngenerate_code_task \n=\n Task(\n\n\n description\n=\n\"Create a simple program to generate the first N numbers in the Fibonacci sequence.\"\n,\n\n\n expected_output\n=\n\"Program that generates the first N numbers in the Fibonacci sequence.\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[generate_code_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nUsing PatronusLocalEvaluatorTool\n\n\nThe following example demonstrates how to use the \nPatronusLocalEvaluatorTool\n, which uses custom function evaluators:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n PatronusLocalEvaluatorTool\n\n\nfrom\n patronus \nimport\n Client, EvaluationResult\n\n\nimport\n random\n\n\n\n\n# Initialize the Patronus client\n\n\nclient \n=\n Client()\n\n\n\n\n# Register a custom evaluator\n\n\n@client.register_local_evaluator\n(\n\"random_evaluator\"\n)\n\n\ndef\n random_evaluator\n(\n**\nkwargs\n):\n\n\n score \n=\n random.random()\n\n\n return\n EvaluationResult(\n\n\n score_raw\n=\nscore,\n\n\n pass_\n=\nscore \n>=\n 0.5\n,\n\n\n explanation\n=\n\"example explanation\"\n,\n\n\n )\n\n\n\n\n# Initialize the tool with the custom evaluator\n\n\npatronus_eval_tool \n=\n PatronusLocalEvaluatorTool(\n\n\n patronus_client\n=\nclient,\n\n\n evaluator\n=\n\"random_evaluator\"\n,\n\n\n evaluated_model_gold_answer\n=\n\"example label\"\n,\n\n\n)\n\n\n\n\n# Define an agent that uses the tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Coding Agent\"\n,\n\n\n goal\n=\n\"Generate high quality code\"\n,\n\n\n backstory\n=\n\"An experienced coder who can generate high quality python code.\"\n,\n\n\n tools\n=\n[patronus_eval_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Example task to generate code\n\n\ngenerate_code_task \n=\n Task(\n\n\n description\n=\n\"Create a simple program to generate the first N numbers in the Fibonacci sequence.\"\n,\n\n\n expected_output\n=\n\"Program that generates the first N numbers in the Fibonacci sequence.\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[generate_code_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nParameters\n\n\n​\nPatronusEvalTool\n\n\nThe \nPatronusEvalTool\n does not require any parameters during initialization. It automatically fetches available evaluators and criteria from the Patronus API.\n\n\n​\nPatronusPredefinedCriteriaEvalTool\n\n\nThe \nPatronusPredefinedCriteriaEvalTool\n accepts the following parameters during initialization:\n\n\n\n\nevaluators\n: Required. A list of dictionaries containing the evaluator and criteria to use. For example: \n[{\"evaluator\": \"judge\", \"criteria\": \"contains-code\"}]\n.\n\n\n\n\n​\nPatronusLocalEvaluatorTool\n\n\nThe \nPatronusLocalEvaluatorTool\n accepts the following parameters during initialization:\n\n\n\n\npatronus_client\n: Required. The Patronus client instance.\n\n\nevaluator\n: Optional. The name of the registered local evaluator to use. Default is an empty string.\n\n\nevaluated_model_gold_answer\n: Optional. The gold answer to use for evaluation. Default is an empty string.\n\n\n\n\n​\nUsage\n\n\nWhen using the Patronus evaluation tools, you provide the model input, output, and context, and the tool returns the evaluation results from the Patronus API.\n\n\nFor the \nPatronusEvalTool\n and \nPatronusPredefinedCriteriaEvalTool\n, the following parameters are required when calling the tool:\n\n\n\n\nevaluated_model_input\n: The agent’s task description in simple text.\n\n\nevaluated_model_output\n: The agent’s output of the task.\n\n\nevaluated_model_retrieved_context\n: The agent’s context.\n\n\n\n\nFor the \nPatronusLocalEvaluatorTool\n, the same parameters are required, but the evaluator and gold answer are specified during initialization.\n\n\n​\nConclusion\n\n\nThe Patronus evaluation tools provide a powerful way to evaluate and score model inputs and outputs using the Patronus AI platform. By enabling agents to evaluate their own outputs or the outputs of other agents, these tools can help improve the quality and reliability of CrewAI workflows.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOpik Integration\nPortkey Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nPatronus AI Evaluation\nOverview\nKey Features\nEvaluation Tools\nInstallation\nSteps to Get Started\nExamples\nUsing PatronusEvalTool\nUsing PatronusPredefinedCriteriaEvalTool\nUsing PatronusLocalEvaluatorTool\nParameters\nPatronusEvalTool\nPatronusPredefinedCriteriaEvalTool\nPatronusLocalEvaluatorTool\nUsage\nConclusion\nObservability\nPatronus AI Evaluation\nCopy page\nMonitor and evaluate CrewAI agent performance using Patronus AI’s comprehensive evaluation platform for LLM outputs and agent behaviors.\n​\nPatronus AI Evaluation\n\n\n​\nOverview\n\n\nPatronus AI\n provides comprehensive evaluation and monitoring capabilities for CrewAI agents, enabling you to assess model outputs, agent behaviors, and overall system performance. This integration allows you to implement continuous evaluation workflows that help maintain quality and reliability in production environments.\n\n\n​\nKey Features\n\n\n\n\nAutomated Evaluation\n: Real-time assessment of agent outputs and behaviors\n\n\nCustom Criteria\n: Define specific evaluation criteria tailored to your use cases\n\n\nPerformance Monitoring\n: Track agent performance metrics over time\n\n\nQuality Assurance\n: Ensure consistent output quality across different scenarios\n\n\nSafety & Compliance\n: Monitor for potential issues and policy violations\n\n\n\n\n​\nEvaluation Tools\n\n\nPatronus provides three main evaluation tools for different use cases:\n\n\n\n\nPatronusEvalTool\n: Allows agents to select the most appropriate evaluator and criteria for the evaluation task.\n\n\nPatronusPredefinedCriteriaEvalTool\n: Uses predefined evaluator and criteria specified by the user.\n\n\nPatronusLocalEvaluatorTool\n: Uses custom function evaluators defined by the user.\n\n\n\n\n​\nInstallation\n\n\nTo use these tools, you need to install the Patronus package:\n\n\nCopy\nAsk AI\nuv\n add\n patronus\n\n\n\n\nYou’ll also need to set up your Patronus API key as an environment variable:\n\n\nCopy\nAsk AI\nexport\n PATRONUS_API_KEY\n=\n\"your_patronus_api_key\"\n\n\n\n\n​\nSteps to Get Started\n\n\nTo effectively use the Patronus evaluation tools, follow these steps:\n\n\n\n\nInstall Patronus\n: Install the Patronus package using the command above.\n\n\nSet Up API Key\n: Set your Patronus API key as an environment variable.\n\n\nChoose the Right Tool\n: Select the appropriate Patronus evaluation tool based on your needs.\n\n\nConfigure the Tool\n: Configure the tool with the necessary parameters.\n\n\n\n\n​\nExamples\n\n\n​\nUsing PatronusEvalTool\n\n\nThe following example demonstrates how to use the \nPatronusEvalTool\n, which allows agents to select the most appropriate evaluator and criteria:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n PatronusEvalTool\n\n\n\n\n# Initialize the tool\n\n\npatronus_eval_tool \n=\n PatronusEvalTool()\n\n\n\n\n# Define an agent that uses the tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Coding Agent\"\n,\n\n\n goal\n=\n\"Generate high quality code and verify that the output is code\"\n,\n\n\n backstory\n=\n\"An experienced coder who can generate high quality python code.\"\n,\n\n\n tools\n=\n[patronus_eval_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Example task to generate and evaluate code\n\n\ngenerate_code_task \n=\n Task(\n\n\n description\n=\n\"Create a simple program to generate the first N numbers in the Fibonacci sequence. Select the most appropriate evaluator and criteria for evaluating your output.\"\n,\n\n\n expected_output\n=\n\"Program that generates the first N numbers in the Fibonacci sequence.\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[generate_code_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nUsing PatronusPredefinedCriteriaEvalTool\n\n\nThe following example demonstrates how to use the \nPatronusPredefinedCriteriaEvalTool\n, which uses predefined evaluator and criteria:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n PatronusPredefinedCriteriaEvalTool\n\n\n\n\n# Initialize the tool with predefined criteria\n\n\npatronus_eval_tool \n=\n PatronusPredefinedCriteriaEvalTool(\n\n\n evaluators\n=\n[{\n\"evaluator\"\n: \n\"judge\"\n, \n\"criteria\"\n: \n\"contains-code\"\n}]\n\n\n)\n\n\n\n\n# Define an agent that uses the tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Coding Agent\"\n,\n\n\n goal\n=\n\"Generate high quality code\"\n,\n\n\n backstory\n=\n\"An experienced coder who can generate high quality python code.\"\n,\n\n\n tools\n=\n[patronus_eval_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Example task to generate code\n\n\ngenerate_code_task \n=\n Task(\n\n\n description\n=\n\"Create a simple program to generate the first N numbers in the Fibonacci sequence.\"\n,\n\n\n expected_output\n=\n\"Program that generates the first N numbers in the Fibonacci sequence.\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[generate_code_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nUsing PatronusLocalEvaluatorTool\n\n\nThe following example demonstrates how to use the \nPatronusLocalEvaluatorTool\n, which uses custom function evaluators:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n PatronusLocalEvaluatorTool\n\n\nfrom\n patronus \nimport\n Client, EvaluationResult\n\n\nimport\n random\n\n\n\n\n# Initialize the Patronus client\n\n\nclient \n=\n Client()\n\n\n\n\n# Register a custom evaluator\n\n\n@client.register_local_evaluator\n(\n\"random_evaluator\"\n)\n\n\ndef\n random_evaluator\n(\n**\nkwargs\n):\n\n\n score \n=\n random.random()\n\n\n return\n EvaluationResult(\n\n\n score_raw\n=\nscore,\n\n\n pass_\n=\nscore \n>=\n 0.5\n,\n\n\n explanation\n=\n\"example explanation\"\n,\n\n\n )\n\n\n\n\n# Initialize the tool with the custom evaluator\n\n\npatronus_eval_tool \n=\n PatronusLocalEvaluatorTool(\n\n\n patronus_client\n=\nclient,\n\n\n evaluator\n=\n\"random_evaluator\"\n,\n\n\n evaluated_model_gold_answer\n=\n\"example label\"\n,\n\n\n)\n\n\n\n\n# Define an agent that uses the tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Coding Agent\"\n,\n\n\n goal\n=\n\"Generate high quality code\"\n,\n\n\n backstory\n=\n\"An experienced coder who can generate high quality python code.\"\n,\n\n\n tools\n=\n[patronus_eval_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Example task to generate code\n\n\ngenerate_code_task \n=\n Task(\n\n\n description\n=\n\"Create a simple program to generate the first N numbers in the Fibonacci sequence.\"\n,\n\n\n expected_output\n=\n\"Program that generates the first N numbers in the Fibonacci sequence.\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[generate_code_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nParameters\n\n\n​\nPatronusEvalTool\n\n\nThe \nPatronusEvalTool\n does not require any parameters during initialization. It automatically fetches available evaluators and criteria from the Patronus API.\n\n\n​\nPatronusPredefinedCriteriaEvalTool\n\n\nThe \nPatronusPredefinedCriteriaEvalTool\n accepts the following parameters during initialization:\n\n\n\n\nevaluators\n: Required. A list of dictionaries containing the evaluator and criteria to use. For example: \n[{\"evaluator\": \"judge\", \"criteria\": \"contains-code\"}]\n.\n\n\n\n\n​\nPatronusLocalEvaluatorTool\n\n\nThe \nPatronusLocalEvaluatorTool\n accepts the following parameters during initialization:\n\n\n\n\npatronus_client\n: Required. The Patronus client instance.\n\n\nevaluator\n: Optional. The name of the registered local evaluator to use. Default is an empty string.\n\n\nevaluated_model_gold_answer\n: Optional. The gold answer to use for evaluation. Default is an empty string.\n\n\n\n\n​\nUsage\n\n\nWhen using the Patronus evaluation tools, you provide the model input, output, and context, and the tool returns the evaluation results from the Patronus API.\n\n\nFor the \nPatronusEvalTool\n and \nPatronusPredefinedCriteriaEvalTool\n, the following parameters are required when calling the tool:\n\n\n\n\nevaluated_model_input\n: The agent’s task description in simple text.\n\n\nevaluated_model_output\n: The agent’s output of the task.\n\n\nevaluated_model_retrieved_context\n: The agent’s context.\n\n\n\n\nFor the \nPatronusLocalEvaluatorTool\n, the same parameters are required, but the evaluator and gold answer are specified during initialization.\n\n\n​\nConclusion\n\n\nThe Patronus evaluation tools provide a powerful way to evaluate and score model inputs and outputs using the Patronus AI platform. By enabling agents to evaluate their own outputs or the outputs of other agents, these tools can help improve the quality and reliability of CrewAI workflows.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOpik Integration\nPortkey Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nPatronus AI Evaluation\nOverview\nKey Features\nEvaluation Tools\nInstallation\nSteps to Get Started\nExamples\nUsing PatronusEvalTool\nUsing PatronusPredefinedCriteriaEvalTool\nUsing PatronusLocalEvaluatorTool\nParameters\nPatronusEvalTool\nPatronusPredefinedCriteriaEvalTool\nPatronusLocalEvaluatorTool\nUsage\nConclusion" }, { "source": "https://docs.crewai.com/en/concepts/reasoning", "title": "Reasoning - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nReasoning\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nReasoning\nCopy page\nLearn how to enable and use agent reasoning to improve task execution.\n​\nOverview\n\n\nAgent reasoning is a feature that allows agents to reflect on a task and create a plan before execution. This helps agents approach tasks more methodically and ensures they’re ready to perform the assigned work.\n\n\n​\nUsage\n\n\nTo enable reasoning for an agent, simply set \nreasoning=True\n when creating the agent:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze complex datasets and provide insights\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with expertise in finding patterns in complex data.\"\n,\n\n\n reasoning\n=\nTrue\n, \n# Enable reasoning\n\n\n max_reasoning_attempts\n=\n3\n # Optional: Set a maximum number of reasoning attempts\n\n\n)\n\n\n\n\n​\nHow It Works\n\n\nWhen reasoning is enabled, before executing a task, the agent will:\n\n\n\n\nReflect on the task and create a detailed plan\n\n\nEvaluate whether it’s ready to execute the task\n\n\nRefine the plan as necessary until it’s ready or max_reasoning_attempts is reached\n\n\nInject the reasoning plan into the task description before execution\n\n\n\n\nThis process helps the agent break down complex tasks into manageable steps and identify potential challenges before starting.\n\n\n​\nConfiguration Options\n\n\n​\nreasoning\nbool\ndefault:\n\"False\"\nEnable or disable reasoning\n\n\n​\nmax_reasoning_attempts\nint\ndefault:\n\"None\"\nMaximum number of attempts to refine the plan before proceeding with execution. If None (default), the agent will continue refining until it’s ready.\n\n\n​\nExample\n\n\nHere’s a complete example:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create an agent with reasoning enabled\n\n\nanalyst \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights\"\n,\n\n\n backstory\n=\n\"You are an expert data analyst.\"\n,\n\n\n reasoning\n=\nTrue\n,\n\n\n max_reasoning_attempts\n=\n3\n # Optional: Set a limit on reasoning attempts\n\n\n)\n\n\n\n\n# Create a task\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the provided sales data and identify key trends.\"\n,\n\n\n expected_output\n=\n\"A report highlighting the top 3 sales trends.\"\n,\n\n\n agent\n=\nanalyst\n\n\n)\n\n\n\n\n# Create a crew and run the task\n\n\ncrew \n=\n Crew(\nagents\n=\n[analyst], \ntasks\n=\n[analysis_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\n\n\n​\nError Handling\n\n\nThe reasoning process is designed to be robust, with error handling built in. If an error occurs during reasoning, the agent will proceed with executing the task without the reasoning plan. This ensures that tasks can still be executed even if the reasoning process fails.\n\n\nHere’s how to handle potential errors in your code:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task\n\n\nimport\n logging\n\n\n\n\n# Set up logging to capture any reasoning errors\n\n\nlogging.basicConfig(\nlevel\n=\nlogging.\nINFO\n)\n\n\n\n\n# Create an agent with reasoning enabled\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights\"\n,\n\n\n reasoning\n=\nTrue\n,\n\n\n max_reasoning_attempts\n=\n3\n\n\n)\n\n\n\n\n# Create a task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Analyze the provided sales data and identify key trends.\"\n,\n\n\n expected_output\n=\n\"A report highlighting the top 3 sales trends.\"\n,\n\n\n agent\n=\nagent\n\n\n)\n\n\n\n\n# Execute the task\n\n\n# If an error occurs during reasoning, it will be logged and execution will continue\n\n\nresult \n=\n agent.execute_task(task)\n\n\n\n\n​\nExample Reasoning Output\n\n\nHere’s an example of what a reasoning plan might look like for a data analysis task:\n\n\nCopy\nAsk AI\nTask: Analyze the provided sales data and identify key trends.\n\n\n\n\nReasoning Plan:\n\n\nI'll analyze the sales data to identify the top 3 trends.\n\n\n\n\n1. Understanding of the task:\n\n\n I need to analyze sales data to identify key trends that would be valuable for business decision-making.\n\n\n\n\n2. Key steps I'll take:\n\n\n - First, I'll examine the data structure to understand what fields are available\n\n\n - Then I'll perform exploratory data analysis to identify patterns\n\n\n - Next, I'll analyze sales by time periods to identify temporal trends\n\n\n - I'll also analyze sales by product categories and customer segments\n\n\n - Finally, I'll identify the top 3 most significant trends\n\n\n\n\n3. Approach to challenges:\n\n\n - If the data has missing values, I'll decide whether to fill or filter them\n\n\n - If the data has outliers, I'll investigate whether they're valid data points or errors\n\n\n - If trends aren't immediately obvious, I'll apply statistical methods to uncover patterns\n\n\n\n\n4. Use of available tools:\n\n\n - I'll use data analysis tools to explore and visualize the data\n\n\n - I'll use statistical tools to identify significant patterns\n\n\n - I'll use knowledge retrieval to access relevant information about sales analysis\n\n\n\n\n5. Expected outcome:\n\n\n A concise report highlighting the top 3 sales trends with supporting evidence from the data.\n\n\n\n\nREADY: I am ready to execute the task.\n\n\n\n\nThis reasoning plan helps the agent organize its approach to the task, consider potential challenges, and ensure it delivers the expected output.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMemory\nPlanning\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nUsage\nHow It Works\nConfiguration Options\nExample\nError Handling\nExample Reasoning Output\nCore Concepts\nReasoning\nCopy page\nLearn how to enable and use agent reasoning to improve task execution.\n​\nOverview\n\n\nAgent reasoning is a feature that allows agents to reflect on a task and create a plan before execution. This helps agents approach tasks more methodically and ensures they’re ready to perform the assigned work.\n\n\n​\nUsage\n\n\nTo enable reasoning for an agent, simply set \nreasoning=True\n when creating the agent:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze complex datasets and provide insights\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with expertise in finding patterns in complex data.\"\n,\n\n\n reasoning\n=\nTrue\n, \n# Enable reasoning\n\n\n max_reasoning_attempts\n=\n3\n # Optional: Set a maximum number of reasoning attempts\n\n\n)\n\n\n\n\n​\nHow It Works\n\n\nWhen reasoning is enabled, before executing a task, the agent will:\n\n\n\n\nReflect on the task and create a detailed plan\n\n\nEvaluate whether it’s ready to execute the task\n\n\nRefine the plan as necessary until it’s ready or max_reasoning_attempts is reached\n\n\nInject the reasoning plan into the task description before execution\n\n\n\n\nThis process helps the agent break down complex tasks into manageable steps and identify potential challenges before starting.\n\n\n​\nConfiguration Options\n\n\n​\nreasoning\nbool\ndefault:\n\"False\"\nEnable or disable reasoning\n\n\n​\nmax_reasoning_attempts\nint\ndefault:\n\"None\"\nMaximum number of attempts to refine the plan before proceeding with execution. If None (default), the agent will continue refining until it’s ready.\n\n\n​\nExample\n\n\nHere’s a complete example:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create an agent with reasoning enabled\n\n\nanalyst \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights\"\n,\n\n\n backstory\n=\n\"You are an expert data analyst.\"\n,\n\n\n reasoning\n=\nTrue\n,\n\n\n max_reasoning_attempts\n=\n3\n # Optional: Set a limit on reasoning attempts\n\n\n)\n\n\n\n\n# Create a task\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the provided sales data and identify key trends.\"\n,\n\n\n expected_output\n=\n\"A report highlighting the top 3 sales trends.\"\n,\n\n\n agent\n=\nanalyst\n\n\n)\n\n\n\n\n# Create a crew and run the task\n\n\ncrew \n=\n Crew(\nagents\n=\n[analyst], \ntasks\n=\n[analysis_task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\n\n\n​\nError Handling\n\n\nThe reasoning process is designed to be robust, with error handling built in. If an error occurs during reasoning, the agent will proceed with executing the task without the reasoning plan. This ensures that tasks can still be executed even if the reasoning process fails.\n\n\nHere’s how to handle potential errors in your code:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task\n\n\nimport\n logging\n\n\n\n\n# Set up logging to capture any reasoning errors\n\n\nlogging.basicConfig(\nlevel\n=\nlogging.\nINFO\n)\n\n\n\n\n# Create an agent with reasoning enabled\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights\"\n,\n\n\n reasoning\n=\nTrue\n,\n\n\n max_reasoning_attempts\n=\n3\n\n\n)\n\n\n\n\n# Create a task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Analyze the provided sales data and identify key trends.\"\n,\n\n\n expected_output\n=\n\"A report highlighting the top 3 sales trends.\"\n,\n\n\n agent\n=\nagent\n\n\n)\n\n\n\n\n# Execute the task\n\n\n# If an error occurs during reasoning, it will be logged and execution will continue\n\n\nresult \n=\n agent.execute_task(task)\n\n\n\n\n​\nExample Reasoning Output\n\n\nHere’s an example of what a reasoning plan might look like for a data analysis task:\n\n\nCopy\nAsk AI\nTask: Analyze the provided sales data and identify key trends.\n\n\n\n\nReasoning Plan:\n\n\nI'll analyze the sales data to identify the top 3 trends.\n\n\n\n\n1. Understanding of the task:\n\n\n I need to analyze sales data to identify key trends that would be valuable for business decision-making.\n\n\n\n\n2. Key steps I'll take:\n\n\n - First, I'll examine the data structure to understand what fields are available\n\n\n - Then I'll perform exploratory data analysis to identify patterns\n\n\n - Next, I'll analyze sales by time periods to identify temporal trends\n\n\n - I'll also analyze sales by product categories and customer segments\n\n\n - Finally, I'll identify the top 3 most significant trends\n\n\n\n\n3. Approach to challenges:\n\n\n - If the data has missing values, I'll decide whether to fill or filter them\n\n\n - If the data has outliers, I'll investigate whether they're valid data points or errors\n\n\n - If trends aren't immediately obvious, I'll apply statistical methods to uncover patterns\n\n\n\n\n4. Use of available tools:\n\n\n - I'll use data analysis tools to explore and visualize the data\n\n\n - I'll use statistical tools to identify significant patterns\n\n\n - I'll use knowledge retrieval to access relevant information about sales analysis\n\n\n\n\n5. Expected outcome:\n\n\n A concise report highlighting the top 3 sales trends with supporting evidence from the data.\n\n\n\n\nREADY: I am ready to execute the task.\n\n\n\n\nThis reasoning plan helps the agent organize its approach to the task, consider potential challenges, and ensure it delivers the expected output.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMemory\nPlanning\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nUsage\nHow It Works\nConfiguration Options\nExample\nError Handling\nExample Reasoning Output" }, { "source": "https://docs.crewai.com/en/observability/portkey", "title": "Portkey Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nPortkey Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nPortkey Integration\nCopy page\nHow to use Portkey with CrewAI\n\n\n​\nIntroduction\n\n\nPortkey enhances CrewAI with production-readiness features, turning your experimental agent crews into robust systems by providing:\n\n\n\n\nComplete observability\n of every agent step, tool use, and interaction\n\n\nBuilt-in reliability\n with fallbacks, retries, and load balancing\n\n\nCost tracking and optimization\n to manage your AI spend\n\n\nAccess to 200+ LLMs\n through a single integration\n\n\nGuardrails\n to keep agent behavior safe and compliant\n\n\nVersion-controlled prompts\n for consistent agent performance\n\n\n\n\n​\nInstallation & Setup\n\n\n1\nInstall the required packages\nCopy\nAsk AI\npip\n install\n -U\n crewai\n portkey-ai\n\n\nGenerate API Key\nCreate a Portkey API key with optional budget/rate limits from the \nPortkey dashboard\n. You can also attach configurations for reliability, caching, and more to this key. More on this later.\n3\nConfigure CrewAI with Portkey\nThe integration is simple - you just need to update the LLM configuration in your CrewAI setup:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Create an LLM instance with Portkey integration\n\n\ngpt_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n, \n# We are using a Virtual key, so this is a placeholder\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_LLM_VIRTUAL_KEY\"\n,\n\n\n trace_id\n=\n\"unique-trace-id\"\n, \n# Optional, for request tracing\n\n\n )\n\n\n)\n\n\n\n\n#Use them in your Crew Agents like this:\n\n\n\n\n\t@agent\n\n\n\tdef\n lead_market_analyst\n(\nself\n) -> Agent:\n\n\n\t\treturn\n Agent(\n\n\n\t\t\tconfig\n=\nself\n.agents_config[\n'lead_market_analyst'\n],\n\n\n\t\t\tverbose\n=\nTrue\n,\n\n\n\t\t\tmemory\n=\nFalse\n,\n\n\n\t\t\tllm\n=\ngpt_llm\n\n\n\t\t)\n\n\n\n\nWhat are Virtual Keys?\n Virtual keys in Portkey securely store your LLM provider API keys (OpenAI, Anthropic, etc.) in an encrypted vault. They allow for easier key rotation and budget management. \nLearn more about virtual keys here\n.\n\n\n​\nProduction Features\n\n\n​\n1. Enhanced Observability\n\n\nPortkey provides comprehensive observability for your CrewAI agents, helping you understand exactly what’s happening during each execution.\n\n\nTraces\nLogs\nMetrics & Dashboards\nMetadata Filtering\nTraces provide a hierarchical view of your crew’s execution, showing the sequence of LLM calls, tool invocations, and state transitions.\nCopy\nAsk AI\n# Add trace_id to enable hierarchical tracing in Portkey\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n trace_id\n=\n\"unique-session-id\"\n # Add unique trace ID\n\n\n )\n\n\n)\n\n\nTraces provide a hierarchical view of your crew’s execution, showing the sequence of LLM calls, tool invocations, and state transitions.\nCopy\nAsk AI\n# Add trace_id to enable hierarchical tracing in Portkey\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n trace_id\n=\n\"unique-session-id\"\n # Add unique trace ID\n\n\n )\n\n\n)\n\n\nPortkey logs every interaction with LLMs, including:\n\n\nComplete request and response payloads\n\n\nLatency and token usage metrics\n\n\nCost calculations\n\n\nTool calls and function executions\n\n\nAll logs can be filtered by metadata, trace IDs, models, and more, making it easy to debug specific crew runs.\nPortkey provides built-in dashboards that help you:\n\n\nTrack cost and token usage across all crew runs\n\n\nAnalyze performance metrics like latency and success rates\n\n\nIdentify bottlenecks in your agent workflows\n\n\nCompare different crew configurations and LLMs\n\n\nYou can filter and segment all metrics by custom metadata to analyze specific crew types, user groups, or use cases.\nAdd custom metadata to your CrewAI LLM configuration to enable powerful filtering and segmentation:\nCopy\nAsk AI\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n metadata\n=\n{\n\n\n \"crew_type\"\n: \n\"research_crew\"\n,\n\n\n \"environment\"\n: \n\"production\"\n,\n\n\n \"_user\"\n: \n\"user_123\"\n, \n# Special _user field for user analytics\n\n\n \"request_source\"\n: \n\"mobile_app\"\n\n\n }\n\n\n )\n\n\n)\n\n\nThis metadata can be used to filter logs, traces, and metrics on the Portkey dashboard, allowing you to analyze specific crew runs, users, or environments.\n\n\n​\n2. Reliability - Keep Your Crews Running Smoothly\n\n\nWhen running crews in production, things can go wrong - API rate limits, network issues, or provider outages. Portkey’s reliability features ensure your agents keep running smoothly even when problems occur.\n\n\nIt’s simple to enable fallback in your CrewAI setup by using a Portkey Config:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Create LLM with fallback configuration\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n max_tokens\n=\n1000\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"strategy\"\n: {\n\n\n \"mode\"\n: \n\"fallback\"\n\n\n },\n\n\n \"targets\"\n: [\n\n\n {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"api_key\"\n: \n\"YOUR_OPENAI_API_KEY\"\n,\n\n\n \"override_params\"\n: {\n\"model\"\n: \n\"gpt-4o\"\n}\n\n\n },\n\n\n {\n\n\n \"provider\"\n: \n\"anthropic\"\n,\n\n\n \"api_key\"\n: \n\"YOUR_ANTHROPIC_API_KEY\"\n,\n\n\n \"override_params\"\n: {\n\"model\"\n: \n\"claude-3-opus-20240229\"\n}\n\n\n }\n\n\n ]\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Use this LLM configuration with your agents\n\n\n\n\nThis configuration will automatically try Claude if the GPT-4o request fails, ensuring your crew can continue operating.\n\n\nAutomatic Retries\nHandles temporary failures automatically. If an LLM call fails, Portkey will retry the same request for the specified number of times - perfect for rate limits or network blips.\nRequest Timeouts\nPrevent your agents from hanging. Set timeouts to ensure you get responses (or can fail gracefully) within your required timeframes.\nConditional Routing\nSend different requests to different providers. Route complex reasoning to GPT-4, creative tasks to Claude, and quick responses to Gemini based on your needs.\nFallbacks\nKeep running even if your primary provider fails. Automatically switch to backup providers to maintain availability.\nLoad Balancing\nSpread requests across multiple API keys or providers. Great for high-volume crew operations and staying within rate limits.\n\n\n​\n3. Prompting in CrewAI\n\n\nPortkey’s Prompt Engineering Studio helps you create, manage, and optimize the prompts used in your CrewAI agents. Instead of hardcoding prompts or instructions, use Portkey’s prompt rendering API to dynamically fetch and apply your versioned prompts.\n\n\nManage prompts in Portkey's Prompt Library\n\n\nPrompt Playground\nUsing Prompt Templates\nPrompt Versioning\nMustache Templating for variables\nPrompt Playground is a place to compare, test and deploy perfect prompts for your AI application. It’s where you experiment with different models, test variables, compare outputs, and refine your prompt engineering strategy before deploying to production. It allows you to:\n\n\nIteratively develop prompts before using them in your agents\n\n\nTest prompts with different variables and models\n\n\nCompare outputs between different prompt versions\n\n\nCollaborate with team members on prompt development\n\n\nThis visual environment makes it easier to craft effective prompts for each step in your CrewAI agents’ workflow.\nPrompt Playground is a place to compare, test and deploy perfect prompts for your AI application. It’s where you experiment with different models, test variables, compare outputs, and refine your prompt engineering strategy before deploying to production. It allows you to:\n\n\nIteratively develop prompts before using them in your agents\n\n\nTest prompts with different variables and models\n\n\nCompare outputs between different prompt versions\n\n\nCollaborate with team members on prompt development\n\n\nThis visual environment makes it easier to craft effective prompts for each step in your CrewAI agents’ workflow.\nThe Prompt Render API retrieves your prompt templates with all parameters configured:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n, Portkey\n\n\n\n\n# Initialize Portkey admin client\n\n\nportkey_admin \n=\n Portkey(\napi_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n)\n\n\n\n\n# Retrieve prompt using the render API\n\n\nprompt_data \n=\n portkey_client.prompts.render(\n\n\n prompt_id\n=\n\"YOUR_PROMPT_ID\"\n,\n\n\n variables\n=\n{\n\n\n \"agent_role\"\n: \n\"Senior Research Scientist\"\n,\n\n\n }\n\n\n)\n\n\n\n\nbackstory_agent_prompt\n=\nprompt_data.data.messages[\n0\n][\n\"content\"\n]\n\n\n\n\n\n\n# Set up LLM with Portkey integration\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n\n\n )\n\n\n)\n\n\n\n\n# Create agent using the rendered prompt\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\nbackstory_agent, \n# Use the rendered prompt\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nYou can:\n\n\nCreate multiple versions of the same prompt\n\n\nCompare performance between versions\n\n\nRoll back to previous versions if needed\n\n\nSpecify which version to use in your code:\n\n\nCopy\nAsk AI\n# Use a specific prompt version\n\n\nprompt_data \n=\n portkey_admin.prompts.render(\n\n\n prompt_id\n=\n\"YOUR_PROMPT_ID@version_number\"\n,\n\n\n variables\n=\n{\n\n\n \"agent_role\"\n: \n\"Senior Research Scientist\"\n,\n\n\n \"agent_goal\"\n: \n\"Discover groundbreaking insights\"\n\n\n }\n\n\n)\n\n\nPortkey prompts use Mustache-style templating for easy variable substitution:\nCopy\nAsk AI\nYou are a {{agent_role}} with expertise in {{domain}}.\n\n\n\n\nYour mission is to {{agent_goal}} by leveraging your knowledge\n\n\nand experience in the field.\n\n\n\n\nAlways maintain a {{tone}} tone and focus on providing {{focus_area}}.\n\n\nWhen rendering, simply pass the variables:\nCopy\nAsk AI\nprompt_data \n=\n portkey_admin.prompts.render(\n\n\n prompt_id\n=\n\"YOUR_PROMPT_ID\"\n,\n\n\n variables\n=\n{\n\n\n \"agent_role\"\n: \n\"Senior Research Scientist\"\n,\n\n\n \"domain\"\n: \n\"artificial intelligence\"\n,\n\n\n \"agent_goal\"\n: \n\"discover groundbreaking insights\"\n,\n\n\n \"tone\"\n: \n\"professional\"\n,\n\n\n \"focus_area\"\n: \n\"practical applications\"\n\n\n }\n\n\n)\n\n\n\n\nPrompt Engineering Studio\nLearn more about Portkey’s prompt management features\n\n\n​\n4. Guardrails for Safe Crews\n\n\nGuardrails ensure your CrewAI agents operate safely and respond appropriately in all situations.\n\n\nWhy Use Guardrails?\n\n\nCrewAI agents can experience various failure modes:\n\n\n\n\nGenerating harmful or inappropriate content\n\n\nLeaking sensitive information like PII\n\n\nHallucinating incorrect information\n\n\nGenerating outputs in incorrect formats\n\n\n\n\nPortkey’s guardrails add protections for both inputs and outputs.\n\n\nImplementing Guardrails\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Create LLM with guardrails\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"input_guardrails\"\n: [\n\"guardrails-id-xxx\"\n, \n\"guardrails-id-yyy\"\n],\n\n\n \"output_guardrails\"\n: [\n\"guardrails-id-zzz\"\n]\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with guardrailed LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\n\n\nPortkey’s guardrails can:\n\n\n\n\nDetect and redact PII in both inputs and outputs\n\n\nFilter harmful or inappropriate content\n\n\nValidate response formats against schemas\n\n\nCheck for hallucinations against ground truth\n\n\nApply custom business logic and rules\n\n\n\n\nLearn More About Guardrails\nExplore Portkey’s guardrail features to enhance agent safety\n\n\n​\n5. User Tracking with Metadata\n\n\nTrack individual users through your CrewAI agents using Portkey’s metadata system.\n\n\nWhat is Metadata in Portkey?\n\n\nMetadata allows you to associate custom data with each request, enabling filtering, segmentation, and analytics. The special \n_user\n field is specifically designed for user tracking.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with user tracking\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n metadata\n=\n{\n\n\n \"_user\"\n: \n\"user_123\"\n, \n# Special _user field for user analytics\n\n\n \"user_tier\"\n: \n\"premium\"\n,\n\n\n \"user_company\"\n: \n\"Acme Corp\"\n,\n\n\n \"session_id\"\n: \n\"abc-123\"\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with tracked LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\n\n\nFilter Analytics by User\n\n\nWith metadata in place, you can filter analytics by user and analyze performance metrics on a per-user basis:\n\n\nFilter analytics by user\n\n\nThis enables:\n\n\n\n\nPer-user cost tracking and budgeting\n\n\nPersonalized user analytics\n\n\nTeam or organization-level metrics\n\n\nEnvironment-specific monitoring (staging vs. production)\n\n\n\n\nLearn More About Metadata\nExplore how to use custom metadata to enhance your analytics\n\n\n​\n6. Caching for Efficient Crews\n\n\nImplement caching to make your CrewAI agents more efficient and cost-effective:\n\n\nSimple Caching\nSemantic Caching\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with simple caching\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"cache\"\n: {\n\n\n \"mode\"\n: \n\"simple\"\n\n\n }\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with cached LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nSimple caching performs exact matches on input prompts, caching identical requests to avoid redundant model executions.\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with simple caching\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"cache\"\n: {\n\n\n \"mode\"\n: \n\"simple\"\n\n\n }\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with cached LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nSimple caching performs exact matches on input prompts, caching identical requests to avoid redundant model executions.\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with semantic caching\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"cache\"\n: {\n\n\n \"mode\"\n: \n\"semantic\"\n\n\n }\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with semantically cached LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nSemantic caching considers the contextual similarity between input requests, caching responses for semantically similar inputs.\n\n\n​\n7. Model Interoperability\n\n\nCrewAI supports multiple LLM providers, and Portkey extends this capability by providing access to over 200 LLMs through a unified interface. You can easily switch between different models without changing your core agent logic:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Set up LLMs with different providers\n\n\nopenai_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n\n\n )\n\n\n)\n\n\n\n\nanthropic_llm \n=\n LLM(\n\n\n model\n=\n\"claude-3-5-sonnet-latest\"\n,\n\n\n max_tokens\n=\n1000\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_ANTHROPIC_VIRTUAL_KEY\"\n\n\n )\n\n\n)\n\n\n\n\n# Choose which LLM to use for each agent based on your needs\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nopenai_llm \n# Use anthropic_llm for Anthropic\n\n\n)\n\n\n\n\nPortkey provides access to LLMs from providers including:\n\n\n\n\nOpenAI (GPT-4o, GPT-4 Turbo, etc.)\n\n\nAnthropic (Claude 3.5 Sonnet, Claude 3 Opus, etc.)\n\n\nMistral AI (Mistral Large, Mistral Medium, etc.)\n\n\nGoogle Vertex AI (Gemini 1.5 Pro, etc.)\n\n\nCohere (Command, Command-R, etc.)\n\n\nAWS Bedrock (Claude, Titan, etc.)\n\n\nLocal/Private Models\n\n\n\n\nSupported Providers\nSee the full list of LLM providers supported by Portkey\n\n\n​\nSet Up Enterprise Governance for CrewAI\n\n\nWhy Enterprise Governance?\n\nIf you are using CrewAI inside your organization, you need to consider several governance aspects:\n\n\n\n\nCost Management\n: Controlling and tracking AI spending across teams\n\n\nAccess Control\n: Managing which teams can use specific models\n\n\nUsage Analytics\n: Understanding how AI is being used across the organization\n\n\nSecurity & Compliance\n: Maintaining enterprise security standards\n\n\nReliability\n: Ensuring consistent service across all users\n\n\n\n\nPortkey adds a comprehensive governance layer to address these enterprise needs. Let’s implement these controls step by step.\n\n\n1\nCreate Virtual Key\nVirtual Keys are Portkey’s secure way to manage your LLM provider API keys. They provide essential controls like:\n\n\nBudget limits for API usage\n\n\nRate limiting capabilities\n\n\nSecure API key storage\n\n\nTo create a virtual key:\nGo to \nVirtual Keys\n in the Portkey App. Save and copy the virtual key ID\nSave your virtual key ID - you’ll need it for the next step.\n2\nCreate Default Config\nConfigs in Portkey define how your requests are routed, with features like advanced routing, fallbacks, and retries.\nTo create your config:\n\n\nGo to \nConfigs\n in Portkey dashboard\n\n\nCreate new config with:\n\n\nCopy\nAsk AI\n{\n\n\n \"virtual_key\"\n: \n\"YOUR_VIRTUAL_KEY_FROM_STEP1\"\n,\n\n\n \t\"override_params\"\n: {\n\n\n \"model\"\n: \n\"gpt-4o\"\n // Your preferred model name\n\n\n }\n\n\n}\n\n\n\n\n\n\nSave and note the Config name for the next step\n\n\n3\nConfigure Portkey API Key\nNow create a Portkey API key and attach the config you created in Step 2:\n\n\nGo to \nAPI Keys\n in Portkey and Create new API key\n\n\nSelect your config from \nStep 2\n\n\nGenerate and save your API key\n\n\n4\nConnect to CrewAI\nAfter setting up your Portkey API key with the attached config, connect it to your CrewAI agents:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n PORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with your API key\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n\n\n)\n\n\n\n\n# Create agent with Portkey-enabled LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\n\n\nStep 1: Implement Budget Controls & Rate Limits\n​\nStep 1: Implement Budget Controls & Rate Limits\nVirtual Keys enable granular control over LLM access at the team/department level. This helps you:\n\n\nSet up \nbudget limits\n\n\nPrevent unexpected usage spikes using Rate limits\n\n\nTrack departmental spending\n\n\n​\nSetting Up Department-Specific Controls:\n\n\nNavigate to \nVirtual Keys\n in Portkey dashboard\n\n\nCreate new Virtual Key for each department with budget limits and rate limits\n\n\nConfigure department-specific limits\n\n\nStep 2: Define Model Access Rules\n​\nStep 2: Define Model Access Rules\nAs your AI usage scales, controlling which teams can access specific models becomes crucial. Portkey Configs provide this control layer with features like:\n​\nAccess Control Features:\n\n\nModel Restrictions\n: Limit access to specific models\n\n\nData Protection\n: Implement guardrails for sensitive data\n\n\nReliability Controls\n: Add fallbacks and retry logic\n\n\n​\nExample Configuration:\nHere’s a basic configuration to route requests to OpenAI, specifically using GPT-4o:\nCopy\nAsk AI\n{\n\n\n\t\"strategy\"\n: {\n\n\n\t\t\"mode\"\n: \n\"single\"\n\n\n\t},\n\n\n\t\"targets\"\n: [\n\n\n\t\t{\n\n\n\t\t\t\"virtual_key\"\n: \n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n\t\t\t\"override_params\"\n: {\n\n\n\t\t\t\t\"model\"\n: \n\"gpt-4o\"\n\n\n\t\t\t}\n\n\n\t\t}\n\n\n\t]\n\n\n}\n\n\nCreate your config on the \nConfigs page\n in your Portkey dashboard.\nConfigs can be updated anytime to adjust controls without affecting running applications.\nStep 3: Implement Access Controls\n​\nStep 3: Implement Access Controls\nCreate User-specific API keys that automatically:\n\n\nTrack usage per user/team with the help of virtual keys\n\n\nApply appropriate configs to route requests\n\n\nCollect relevant metadata to filter logs\n\n\nEnforce access permissions\n\n\nCreate API keys through:\n\n\nPortkey App\n\n\nAPI Key Management API\n\n\nExample using Python SDK:\nCopy\nAsk AI\nfrom\n portkey_ai \nimport\n Portkey\n\n\n\n\nportkey \n=\n Portkey(\napi_key\n=\n\"YOUR_ADMIN_API_KEY\"\n)\n\n\n\n\napi_key \n=\n portkey.api_keys.create(\n\n\n name\n=\n\"engineering-team\"\n,\n\n\n type\n=\n\"organisation\"\n,\n\n\n workspace_id\n=\n\"YOUR_WORKSPACE_ID\"\n,\n\n\n defaults\n=\n{\n\n\n \"config_id\"\n: \n\"your-config-id\"\n,\n\n\n \"metadata\"\n: {\n\n\n \"environment\"\n: \n\"production\"\n,\n\n\n \"department\"\n: \n\"engineering\"\n\n\n }\n\n\n },\n\n\n scopes\n=\n[\n\"logs.view\"\n, \n\"configs.read\"\n]\n\n\n)\n\n\nFor detailed key management instructions, see our \nAPI Keys documentation\n.\nStep 4: Deploy & Monitor\n​\nStep 4: Deploy & Monitor\nAfter distributing API keys to your team members, your enterprise-ready CrewAI setup is ready to go. Each team member can now use their designated API keys with appropriate access levels and budget controls.\nMonitor usage in Portkey dashboard:\n\n\nCost tracking by department\n\n\nModel usage patterns\n\n\nRequest volumes\n\n\nError rates\n\n\n\n\n​\nEnterprise Features Now Available\nYour CrewAI integration now has:\n\n\nDepartmental budget controls\n\n\nModel access governance\n\n\nUsage tracking & attribution\n\n\nSecurity guardrails\n\n\nReliability features\n\n\n\n\n​\nFrequently Asked Questions\n\n\nHow does Portkey enhance CrewAI?\nPortkey adds production-readiness to CrewAI through comprehensive observability (traces, logs, metrics), reliability features (fallbacks, retries, caching), and access to 200+ LLMs through a unified interface. This makes it easier to debug, optimize, and scale your agent applications.\nCan I use Portkey with existing CrewAI applications?\nYes! Portkey integrates seamlessly with existing CrewAI applications. You just need to update your LLM configuration code with the Portkey-enabled version. The rest of your agent and crew code remains unchanged.\nDoes Portkey work with all CrewAI features?\nPortkey supports all CrewAI features, including agents, tools, human-in-the-loop workflows, and all task process types (sequential, hierarchical, etc.). It adds observability and reliability without limiting any of the framework’s functionality.\nCan I track usage across multiple agents in a crew?\nYes, Portkey allows you to use a consistent \ntrace_id\n across multiple agents in a crew to track the entire workflow. This is especially useful for complex crews where you want to understand the full execution path across multiple agents.\nHow do I filter logs and traces for specific crew runs?\nPortkey allows you to add custom metadata to your LLM configuration, which you can then use for filtering. Add fields like \ncrew_name\n, \ncrew_type\n, or \nsession_id\n to easily find and analyze specific crew executions.\nCan I use my own API keys with Portkey?\nYes! Portkey uses your own API keys for the various LLM providers. It securely stores them as virtual keys, allowing you to easily manage and rotate keys without changing your code.\n\n\n​\nResources\n\n\nCrewAI Docs\nOfficial CrewAI documentation\nBook a Demo\nGet personalized guidance on implementing this integration\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nPatronus AI Evaluation\nWeave Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nInstallation & Setup\nProduction Features\n1. Enhanced Observability\n2. Reliability - Keep Your Crews Running Smoothly\n3. Prompting in CrewAI\n4. Guardrails for Safe Crews\n5. User Tracking with Metadata\n6. Caching for Efficient Crews\n7. Model Interoperability\nSet Up Enterprise Governance for CrewAI\nFrequently Asked Questions\nResources\nObservability\nPortkey Integration\nCopy page\nHow to use Portkey with CrewAI\n\n\n​\nIntroduction\n\n\nPortkey enhances CrewAI with production-readiness features, turning your experimental agent crews into robust systems by providing:\n\n\n\n\nComplete observability\n of every agent step, tool use, and interaction\n\n\nBuilt-in reliability\n with fallbacks, retries, and load balancing\n\n\nCost tracking and optimization\n to manage your AI spend\n\n\nAccess to 200+ LLMs\n through a single integration\n\n\nGuardrails\n to keep agent behavior safe and compliant\n\n\nVersion-controlled prompts\n for consistent agent performance\n\n\n\n\n​\nInstallation & Setup\n\n\n1\nInstall the required packages\nCopy\nAsk AI\npip\n install\n -U\n crewai\n portkey-ai\n\n\nGenerate API Key\nCreate a Portkey API key with optional budget/rate limits from the \nPortkey dashboard\n. You can also attach configurations for reliability, caching, and more to this key. More on this later.\n3\nConfigure CrewAI with Portkey\nThe integration is simple - you just need to update the LLM configuration in your CrewAI setup:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Create an LLM instance with Portkey integration\n\n\ngpt_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n, \n# We are using a Virtual key, so this is a placeholder\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_LLM_VIRTUAL_KEY\"\n,\n\n\n trace_id\n=\n\"unique-trace-id\"\n, \n# Optional, for request tracing\n\n\n )\n\n\n)\n\n\n\n\n#Use them in your Crew Agents like this:\n\n\n\n\n\t@agent\n\n\n\tdef\n lead_market_analyst\n(\nself\n) -> Agent:\n\n\n\t\treturn\n Agent(\n\n\n\t\t\tconfig\n=\nself\n.agents_config[\n'lead_market_analyst'\n],\n\n\n\t\t\tverbose\n=\nTrue\n,\n\n\n\t\t\tmemory\n=\nFalse\n,\n\n\n\t\t\tllm\n=\ngpt_llm\n\n\n\t\t)\n\n\n\n\nWhat are Virtual Keys?\n Virtual keys in Portkey securely store your LLM provider API keys (OpenAI, Anthropic, etc.) in an encrypted vault. They allow for easier key rotation and budget management. \nLearn more about virtual keys here\n.\n\n\n​\nProduction Features\n\n\n​\n1. Enhanced Observability\n\n\nPortkey provides comprehensive observability for your CrewAI agents, helping you understand exactly what’s happening during each execution.\n\n\nTraces\nLogs\nMetrics & Dashboards\nMetadata Filtering\nTraces provide a hierarchical view of your crew’s execution, showing the sequence of LLM calls, tool invocations, and state transitions.\nCopy\nAsk AI\n# Add trace_id to enable hierarchical tracing in Portkey\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n trace_id\n=\n\"unique-session-id\"\n # Add unique trace ID\n\n\n )\n\n\n)\n\n\nTraces provide a hierarchical view of your crew’s execution, showing the sequence of LLM calls, tool invocations, and state transitions.\nCopy\nAsk AI\n# Add trace_id to enable hierarchical tracing in Portkey\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n trace_id\n=\n\"unique-session-id\"\n # Add unique trace ID\n\n\n )\n\n\n)\n\n\nPortkey logs every interaction with LLMs, including:\n\n\nComplete request and response payloads\n\n\nLatency and token usage metrics\n\n\nCost calculations\n\n\nTool calls and function executions\n\n\nAll logs can be filtered by metadata, trace IDs, models, and more, making it easy to debug specific crew runs.\nPortkey provides built-in dashboards that help you:\n\n\nTrack cost and token usage across all crew runs\n\n\nAnalyze performance metrics like latency and success rates\n\n\nIdentify bottlenecks in your agent workflows\n\n\nCompare different crew configurations and LLMs\n\n\nYou can filter and segment all metrics by custom metadata to analyze specific crew types, user groups, or use cases.\nAdd custom metadata to your CrewAI LLM configuration to enable powerful filtering and segmentation:\nCopy\nAsk AI\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n metadata\n=\n{\n\n\n \"crew_type\"\n: \n\"research_crew\"\n,\n\n\n \"environment\"\n: \n\"production\"\n,\n\n\n \"_user\"\n: \n\"user_123\"\n, \n# Special _user field for user analytics\n\n\n \"request_source\"\n: \n\"mobile_app\"\n\n\n }\n\n\n )\n\n\n)\n\n\nThis metadata can be used to filter logs, traces, and metrics on the Portkey dashboard, allowing you to analyze specific crew runs, users, or environments.\n\n\n​\n2. Reliability - Keep Your Crews Running Smoothly\n\n\nWhen running crews in production, things can go wrong - API rate limits, network issues, or provider outages. Portkey’s reliability features ensure your agents keep running smoothly even when problems occur.\n\n\nIt’s simple to enable fallback in your CrewAI setup by using a Portkey Config:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Create LLM with fallback configuration\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n max_tokens\n=\n1000\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"strategy\"\n: {\n\n\n \"mode\"\n: \n\"fallback\"\n\n\n },\n\n\n \"targets\"\n: [\n\n\n {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"api_key\"\n: \n\"YOUR_OPENAI_API_KEY\"\n,\n\n\n \"override_params\"\n: {\n\"model\"\n: \n\"gpt-4o\"\n}\n\n\n },\n\n\n {\n\n\n \"provider\"\n: \n\"anthropic\"\n,\n\n\n \"api_key\"\n: \n\"YOUR_ANTHROPIC_API_KEY\"\n,\n\n\n \"override_params\"\n: {\n\"model\"\n: \n\"claude-3-opus-20240229\"\n}\n\n\n }\n\n\n ]\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Use this LLM configuration with your agents\n\n\n\n\nThis configuration will automatically try Claude if the GPT-4o request fails, ensuring your crew can continue operating.\n\n\nAutomatic Retries\nHandles temporary failures automatically. If an LLM call fails, Portkey will retry the same request for the specified number of times - perfect for rate limits or network blips.\nRequest Timeouts\nPrevent your agents from hanging. Set timeouts to ensure you get responses (or can fail gracefully) within your required timeframes.\nConditional Routing\nSend different requests to different providers. Route complex reasoning to GPT-4, creative tasks to Claude, and quick responses to Gemini based on your needs.\nFallbacks\nKeep running even if your primary provider fails. Automatically switch to backup providers to maintain availability.\nLoad Balancing\nSpread requests across multiple API keys or providers. Great for high-volume crew operations and staying within rate limits.\n\n\n​\n3. Prompting in CrewAI\n\n\nPortkey’s Prompt Engineering Studio helps you create, manage, and optimize the prompts used in your CrewAI agents. Instead of hardcoding prompts or instructions, use Portkey’s prompt rendering API to dynamically fetch and apply your versioned prompts.\n\n\nManage prompts in Portkey's Prompt Library\n\n\nPrompt Playground\nUsing Prompt Templates\nPrompt Versioning\nMustache Templating for variables\nPrompt Playground is a place to compare, test and deploy perfect prompts for your AI application. It’s where you experiment with different models, test variables, compare outputs, and refine your prompt engineering strategy before deploying to production. It allows you to:\n\n\nIteratively develop prompts before using them in your agents\n\n\nTest prompts with different variables and models\n\n\nCompare outputs between different prompt versions\n\n\nCollaborate with team members on prompt development\n\n\nThis visual environment makes it easier to craft effective prompts for each step in your CrewAI agents’ workflow.\nPrompt Playground is a place to compare, test and deploy perfect prompts for your AI application. It’s where you experiment with different models, test variables, compare outputs, and refine your prompt engineering strategy before deploying to production. It allows you to:\n\n\nIteratively develop prompts before using them in your agents\n\n\nTest prompts with different variables and models\n\n\nCompare outputs between different prompt versions\n\n\nCollaborate with team members on prompt development\n\n\nThis visual environment makes it easier to craft effective prompts for each step in your CrewAI agents’ workflow.\nThe Prompt Render API retrieves your prompt templates with all parameters configured:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n, Portkey\n\n\n\n\n# Initialize Portkey admin client\n\n\nportkey_admin \n=\n Portkey(\napi_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n)\n\n\n\n\n# Retrieve prompt using the render API\n\n\nprompt_data \n=\n portkey_client.prompts.render(\n\n\n prompt_id\n=\n\"YOUR_PROMPT_ID\"\n,\n\n\n variables\n=\n{\n\n\n \"agent_role\"\n: \n\"Senior Research Scientist\"\n,\n\n\n }\n\n\n)\n\n\n\n\nbackstory_agent_prompt\n=\nprompt_data.data.messages[\n0\n][\n\"content\"\n]\n\n\n\n\n\n\n# Set up LLM with Portkey integration\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n\n\n )\n\n\n)\n\n\n\n\n# Create agent using the rendered prompt\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\nbackstory_agent, \n# Use the rendered prompt\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nYou can:\n\n\nCreate multiple versions of the same prompt\n\n\nCompare performance between versions\n\n\nRoll back to previous versions if needed\n\n\nSpecify which version to use in your code:\n\n\nCopy\nAsk AI\n# Use a specific prompt version\n\n\nprompt_data \n=\n portkey_admin.prompts.render(\n\n\n prompt_id\n=\n\"YOUR_PROMPT_ID@version_number\"\n,\n\n\n variables\n=\n{\n\n\n \"agent_role\"\n: \n\"Senior Research Scientist\"\n,\n\n\n \"agent_goal\"\n: \n\"Discover groundbreaking insights\"\n\n\n }\n\n\n)\n\n\nPortkey prompts use Mustache-style templating for easy variable substitution:\nCopy\nAsk AI\nYou are a {{agent_role}} with expertise in {{domain}}.\n\n\n\n\nYour mission is to {{agent_goal}} by leveraging your knowledge\n\n\nand experience in the field.\n\n\n\n\nAlways maintain a {{tone}} tone and focus on providing {{focus_area}}.\n\n\nWhen rendering, simply pass the variables:\nCopy\nAsk AI\nprompt_data \n=\n portkey_admin.prompts.render(\n\n\n prompt_id\n=\n\"YOUR_PROMPT_ID\"\n,\n\n\n variables\n=\n{\n\n\n \"agent_role\"\n: \n\"Senior Research Scientist\"\n,\n\n\n \"domain\"\n: \n\"artificial intelligence\"\n,\n\n\n \"agent_goal\"\n: \n\"discover groundbreaking insights\"\n,\n\n\n \"tone\"\n: \n\"professional\"\n,\n\n\n \"focus_area\"\n: \n\"practical applications\"\n\n\n }\n\n\n)\n\n\n\n\nPrompt Engineering Studio\nLearn more about Portkey’s prompt management features\n\n\n​\n4. Guardrails for Safe Crews\n\n\nGuardrails ensure your CrewAI agents operate safely and respond appropriately in all situations.\n\n\nWhy Use Guardrails?\n\n\nCrewAI agents can experience various failure modes:\n\n\n\n\nGenerating harmful or inappropriate content\n\n\nLeaking sensitive information like PII\n\n\nHallucinating incorrect information\n\n\nGenerating outputs in incorrect formats\n\n\n\n\nPortkey’s guardrails add protections for both inputs and outputs.\n\n\nImplementing Guardrails\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Create LLM with guardrails\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"input_guardrails\"\n: [\n\"guardrails-id-xxx\"\n, \n\"guardrails-id-yyy\"\n],\n\n\n \"output_guardrails\"\n: [\n\"guardrails-id-zzz\"\n]\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with guardrailed LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\n\n\nPortkey’s guardrails can:\n\n\n\n\nDetect and redact PII in both inputs and outputs\n\n\nFilter harmful or inappropriate content\n\n\nValidate response formats against schemas\n\n\nCheck for hallucinations against ground truth\n\n\nApply custom business logic and rules\n\n\n\n\nLearn More About Guardrails\nExplore Portkey’s guardrail features to enhance agent safety\n\n\n​\n5. User Tracking with Metadata\n\n\nTrack individual users through your CrewAI agents using Portkey’s metadata system.\n\n\nWhat is Metadata in Portkey?\n\n\nMetadata allows you to associate custom data with each request, enabling filtering, segmentation, and analytics. The special \n_user\n field is specifically designed for user tracking.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with user tracking\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n metadata\n=\n{\n\n\n \"_user\"\n: \n\"user_123\"\n, \n# Special _user field for user analytics\n\n\n \"user_tier\"\n: \n\"premium\"\n,\n\n\n \"user_company\"\n: \n\"Acme Corp\"\n,\n\n\n \"session_id\"\n: \n\"abc-123\"\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with tracked LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\n\n\nFilter Analytics by User\n\n\nWith metadata in place, you can filter analytics by user and analyze performance metrics on a per-user basis:\n\n\nFilter analytics by user\n\n\nThis enables:\n\n\n\n\nPer-user cost tracking and budgeting\n\n\nPersonalized user analytics\n\n\nTeam or organization-level metrics\n\n\nEnvironment-specific monitoring (staging vs. production)\n\n\n\n\nLearn More About Metadata\nExplore how to use custom metadata to enhance your analytics\n\n\n​\n6. Caching for Efficient Crews\n\n\nImplement caching to make your CrewAI agents more efficient and cost-effective:\n\n\nSimple Caching\nSemantic Caching\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with simple caching\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"cache\"\n: {\n\n\n \"mode\"\n: \n\"simple\"\n\n\n }\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with cached LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nSimple caching performs exact matches on input prompts, caching identical requests to avoid redundant model executions.\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with simple caching\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"cache\"\n: {\n\n\n \"mode\"\n: \n\"simple\"\n\n\n }\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with cached LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nSimple caching performs exact matches on input prompts, caching identical requests to avoid redundant model executions.\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with semantic caching\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n config\n=\n{\n\n\n \"cache\"\n: {\n\n\n \"mode\"\n: \n\"semantic\"\n\n\n }\n\n\n }\n\n\n )\n\n\n)\n\n\n\n\n# Create agent with semantically cached LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\nSemantic caching considers the contextual similarity between input requests, caching responses for semantically similar inputs.\n\n\n​\n7. Model Interoperability\n\n\nCrewAI supports multiple LLM providers, and Portkey extends this capability by providing access to over 200 LLMs through a unified interface. You can easily switch between different models without changing your core agent logic:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n createHeaders, \nPORTKEY_GATEWAY_URL\n\n\n\n\n# Set up LLMs with different providers\n\n\nopenai_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_OPENAI_VIRTUAL_KEY\"\n\n\n )\n\n\n)\n\n\n\n\nanthropic_llm \n=\n LLM(\n\n\n model\n=\n\"claude-3-5-sonnet-latest\"\n,\n\n\n max_tokens\n=\n1000\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"dummy\"\n,\n\n\n extra_headers\n=\ncreateHeaders(\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n,\n\n\n virtual_key\n=\n\"YOUR_ANTHROPIC_VIRTUAL_KEY\"\n\n\n )\n\n\n)\n\n\n\n\n# Choose which LLM to use for each agent based on your needs\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nopenai_llm \n# Use anthropic_llm for Anthropic\n\n\n)\n\n\n\n\nPortkey provides access to LLMs from providers including:\n\n\n\n\nOpenAI (GPT-4o, GPT-4 Turbo, etc.)\n\n\nAnthropic (Claude 3.5 Sonnet, Claude 3 Opus, etc.)\n\n\nMistral AI (Mistral Large, Mistral Medium, etc.)\n\n\nGoogle Vertex AI (Gemini 1.5 Pro, etc.)\n\n\nCohere (Command, Command-R, etc.)\n\n\nAWS Bedrock (Claude, Titan, etc.)\n\n\nLocal/Private Models\n\n\n\n\nSupported Providers\nSee the full list of LLM providers supported by Portkey\n\n\n​\nSet Up Enterprise Governance for CrewAI\n\n\nWhy Enterprise Governance?\n\nIf you are using CrewAI inside your organization, you need to consider several governance aspects:\n\n\n\n\nCost Management\n: Controlling and tracking AI spending across teams\n\n\nAccess Control\n: Managing which teams can use specific models\n\n\nUsage Analytics\n: Understanding how AI is being used across the organization\n\n\nSecurity & Compliance\n: Maintaining enterprise security standards\n\n\nReliability\n: Ensuring consistent service across all users\n\n\n\n\nPortkey adds a comprehensive governance layer to address these enterprise needs. Let’s implement these controls step by step.\n\n\n1\nCreate Virtual Key\nVirtual Keys are Portkey’s secure way to manage your LLM provider API keys. They provide essential controls like:\n\n\nBudget limits for API usage\n\n\nRate limiting capabilities\n\n\nSecure API key storage\n\n\nTo create a virtual key:\nGo to \nVirtual Keys\n in the Portkey App. Save and copy the virtual key ID\nSave your virtual key ID - you’ll need it for the next step.\n2\nCreate Default Config\nConfigs in Portkey define how your requests are routed, with features like advanced routing, fallbacks, and retries.\nTo create your config:\n\n\nGo to \nConfigs\n in Portkey dashboard\n\n\nCreate new config with:\n\n\nCopy\nAsk AI\n{\n\n\n \"virtual_key\"\n: \n\"YOUR_VIRTUAL_KEY_FROM_STEP1\"\n,\n\n\n \t\"override_params\"\n: {\n\n\n \"model\"\n: \n\"gpt-4o\"\n // Your preferred model name\n\n\n }\n\n\n}\n\n\n\n\n\n\nSave and note the Config name for the next step\n\n\n3\nConfigure Portkey API Key\nNow create a Portkey API key and attach the config you created in Step 2:\n\n\nGo to \nAPI Keys\n in Portkey and Create new API key\n\n\nSelect your config from \nStep 2\n\n\nGenerate and save your API key\n\n\n4\nConnect to CrewAI\nAfter setting up your Portkey API key with the attached config, connect it to your CrewAI agents:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\nfrom\n portkey_ai \nimport\n PORTKEY_GATEWAY_URL\n\n\n\n\n# Configure LLM with your API key\n\n\nportkey_llm \n=\n LLM(\n\n\n model\n=\n\"gpt-4o\"\n,\n\n\n base_url\n=\nPORTKEY_GATEWAY_URL\n,\n\n\n api_key\n=\n\"YOUR_PORTKEY_API_KEY\"\n\n\n)\n\n\n\n\n# Create agent with Portkey-enabled LLM\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Scientist\"\n,\n\n\n goal\n=\n\"Discover groundbreaking insights about the assigned topic\"\n,\n\n\n backstory\n=\n\"You are an expert researcher with deep domain knowledge.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nportkey_llm\n\n\n)\n\n\n\n\nStep 1: Implement Budget Controls & Rate Limits\n​\nStep 1: Implement Budget Controls & Rate Limits\nVirtual Keys enable granular control over LLM access at the team/department level. This helps you:\n\n\nSet up \nbudget limits\n\n\nPrevent unexpected usage spikes using Rate limits\n\n\nTrack departmental spending\n\n\n​\nSetting Up Department-Specific Controls:\n\n\nNavigate to \nVirtual Keys\n in Portkey dashboard\n\n\nCreate new Virtual Key for each department with budget limits and rate limits\n\n\nConfigure department-specific limits\n\n\nStep 2: Define Model Access Rules\n​\nStep 2: Define Model Access Rules\nAs your AI usage scales, controlling which teams can access specific models becomes crucial. Portkey Configs provide this control layer with features like:\n​\nAccess Control Features:\n\n\nModel Restrictions\n: Limit access to specific models\n\n\nData Protection\n: Implement guardrails for sensitive data\n\n\nReliability Controls\n: Add fallbacks and retry logic\n\n\n​\nExample Configuration:\nHere’s a basic configuration to route requests to OpenAI, specifically using GPT-4o:\nCopy\nAsk AI\n{\n\n\n\t\"strategy\"\n: {\n\n\n\t\t\"mode\"\n: \n\"single\"\n\n\n\t},\n\n\n\t\"targets\"\n: [\n\n\n\t\t{\n\n\n\t\t\t\"virtual_key\"\n: \n\"YOUR_OPENAI_VIRTUAL_KEY\"\n,\n\n\n\t\t\t\"override_params\"\n: {\n\n\n\t\t\t\t\"model\"\n: \n\"gpt-4o\"\n\n\n\t\t\t}\n\n\n\t\t}\n\n\n\t]\n\n\n}\n\n\nCreate your config on the \nConfigs page\n in your Portkey dashboard.\nConfigs can be updated anytime to adjust controls without affecting running applications.\nStep 3: Implement Access Controls\n​\nStep 3: Implement Access Controls\nCreate User-specific API keys that automatically:\n\n\nTrack usage per user/team with the help of virtual keys\n\n\nApply appropriate configs to route requests\n\n\nCollect relevant metadata to filter logs\n\n\nEnforce access permissions\n\n\nCreate API keys through:\n\n\nPortkey App\n\n\nAPI Key Management API\n\n\nExample using Python SDK:\nCopy\nAsk AI\nfrom\n portkey_ai \nimport\n Portkey\n\n\n\n\nportkey \n=\n Portkey(\napi_key\n=\n\"YOUR_ADMIN_API_KEY\"\n)\n\n\n\n\napi_key \n=\n portkey.api_keys.create(\n\n\n name\n=\n\"engineering-team\"\n,\n\n\n type\n=\n\"organisation\"\n,\n\n\n workspace_id\n=\n\"YOUR_WORKSPACE_ID\"\n,\n\n\n defaults\n=\n{\n\n\n \"config_id\"\n: \n\"your-config-id\"\n,\n\n\n \"metadata\"\n: {\n\n\n \"environment\"\n: \n\"production\"\n,\n\n\n \"department\"\n: \n\"engineering\"\n\n\n }\n\n\n },\n\n\n scopes\n=\n[\n\"logs.view\"\n, \n\"configs.read\"\n]\n\n\n)\n\n\nFor detailed key management instructions, see our \nAPI Keys documentation\n.\nStep 4: Deploy & Monitor\n​\nStep 4: Deploy & Monitor\nAfter distributing API keys to your team members, your enterprise-ready CrewAI setup is ready to go. Each team member can now use their designated API keys with appropriate access levels and budget controls.\nMonitor usage in Portkey dashboard:\n\n\nCost tracking by department\n\n\nModel usage patterns\n\n\nRequest volumes\n\n\nError rates\n\n\n\n\n​\nEnterprise Features Now Available\nYour CrewAI integration now has:\n\n\nDepartmental budget controls\n\n\nModel access governance\n\n\nUsage tracking & attribution\n\n\nSecurity guardrails\n\n\nReliability features\n\n\n\n\n​\nFrequently Asked Questions\n\n\nHow does Portkey enhance CrewAI?\nPortkey adds production-readiness to CrewAI through comprehensive observability (traces, logs, metrics), reliability features (fallbacks, retries, caching), and access to 200+ LLMs through a unified interface. This makes it easier to debug, optimize, and scale your agent applications.\nCan I use Portkey with existing CrewAI applications?\nYes! Portkey integrates seamlessly with existing CrewAI applications. You just need to update your LLM configuration code with the Portkey-enabled version. The rest of your agent and crew code remains unchanged.\nDoes Portkey work with all CrewAI features?\nPortkey supports all CrewAI features, including agents, tools, human-in-the-loop workflows, and all task process types (sequential, hierarchical, etc.). It adds observability and reliability without limiting any of the framework’s functionality.\nCan I track usage across multiple agents in a crew?\nYes, Portkey allows you to use a consistent \ntrace_id\n across multiple agents in a crew to track the entire workflow. This is especially useful for complex crews where you want to understand the full execution path across multiple agents.\nHow do I filter logs and traces for specific crew runs?\nPortkey allows you to add custom metadata to your LLM configuration, which you can then use for filtering. Add fields like \ncrew_name\n, \ncrew_type\n, or \nsession_id\n to easily find and analyze specific crew executions.\nCan I use my own API keys with Portkey?\nYes! Portkey uses your own API keys for the various LLM providers. It securely stores them as virtual keys, allowing you to easily manage and rotate keys without changing your code.\n\n\n​\nResources\n\n\nCrewAI Docs\nOfficial CrewAI documentation\nBook a Demo\nGet personalized guidance on implementing this integration\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nPatronus AI Evaluation\nWeave Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nInstallation & Setup\nProduction Features\n1. Enhanced Observability\n2. Reliability - Keep Your Crews Running Smoothly\n3. Prompting in CrewAI\n4. Guardrails for Safe Crews\n5. User Tracking with Metadata\n6. Caching for Efficient Crews\n7. Model Interoperability\nSet Up Enterprise Governance for CrewAI\nFrequently Asked Questions\nResources" }, { "source": "https://docs.crewai.com/en/guides/flows/first-flow", "title": "Build Your First Flow - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nFlows\nBuild Your First Flow\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nBuild Your First Flow\nMastering Flow State Management\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nFlows\nBuild Your First Flow\nCopy page\nLearn how to create structured, event-driven workflows with precise control over execution.\n​\nTaking Control of AI Workflows with Flows\n\n\nCrewAI Flows represent the next level in AI orchestration - combining the collaborative power of AI agent crews with the precision and flexibility of procedural programming. While crews excel at agent collaboration, flows give you fine-grained control over exactly how and when different components of your AI system interact.\n\n\nIn this guide, we’ll walk through creating a powerful CrewAI Flow that generates a comprehensive learning guide on any topic. This tutorial will demonstrate how Flows provide structured, event-driven control over your AI workflows by combining regular code, direct LLM calls, and crew-based processing.\n\n\n​\nWhat Makes Flows Powerful\n\n\nFlows enable you to:\n\n\n\n\nCombine different AI interaction patterns\n - Use crews for complex collaborative tasks, direct LLM calls for simpler operations, and regular code for procedural logic\n\n\nBuild event-driven systems\n - Define how components respond to specific events and data changes\n\n\nMaintain state across components\n - Share and transform data between different parts of your application\n\n\nIntegrate with external systems\n - Seamlessly connect your AI workflow with databases, APIs, and user interfaces\n\n\nCreate complex execution paths\n - Design conditional branches, parallel processing, and dynamic workflows\n\n\n\n\n​\nWhat You’ll Build and Learn\n\n\nBy the end of this guide, you’ll have:\n\n\n\n\nCreated a sophisticated content generation system\n that combines user input, AI planning, and multi-agent content creation\n\n\nOrchestrated the flow of information\n between different components of your system\n\n\nImplemented event-driven architecture\n where each step responds to the completion of previous steps\n\n\nBuilt a foundation for more complex AI applications\n that you can expand and customize\n\n\n\n\nThis guide creator flow demonstrates fundamental patterns that can be applied to create much more advanced applications, such as:\n\n\n\n\nInteractive AI assistants that combine multiple specialized subsystems\n\n\nComplex data processing pipelines with AI-enhanced transformations\n\n\nAutonomous agents that integrate with external services and APIs\n\n\nMulti-stage decision-making systems with human-in-the-loop processes\n\n\n\n\nLet’s dive in and build your first flow!\n\n\n​\nPrerequisites\n\n\nBefore starting, make sure you have:\n\n\n\n\nInstalled CrewAI following the \ninstallation guide\n\n\nSet up your LLM API key in your environment, following the \nLLM setup\nguide\n\n\nBasic understanding of Python\n\n\n\n\n​\nStep 1: Create a New CrewAI Flow Project\n\n\nFirst, let’s create a new CrewAI Flow project using the CLI. This command sets up a scaffolded project with all the necessary directories and template files for your flow.\n\n\nCopy\nAsk AI\ncrewai\n create\n flow\n guide_creator_flow\n\n\ncd\n guide_creator_flow\n\n\n\n\nThis will generate a project with the basic structure needed for your flow.\n\n\nCrewAI Framework Overview\n\n\n​\nStep 2: Understanding the Project Structure\n\n\nThe generated project has the following structure. Take a moment to familiarize yourself with it, as understanding this structure will help you create more complex flows in the future.\n\n\nCopy\nAsk AI\nguide_creator_flow/\n\n\n├── .gitignore\n\n\n├── pyproject.toml\n\n\n├── README.md\n\n\n├── .env\n\n\n├── main.py\n\n\n├── crews/\n\n\n│ └── poem_crew/\n\n\n│ ├── config/\n\n\n│ │ ├── agents.yaml\n\n\n│ │ └── tasks.yaml\n\n\n│ └── poem_crew.py\n\n\n└── tools/\n\n\n └── custom_tool.py\n\n\n\n\nThis structure provides a clear separation between different components of your flow:\n\n\n\n\nThe main flow logic in the \nmain.py\n file\n\n\nSpecialized crews in the \ncrews\n directory\n\n\nCustom tools in the \ntools\n directory\n\n\n\n\nWe’ll modify this structure to create our guide creator flow, which will orchestrate the process of generating comprehensive learning guides.\n\n\n​\nStep 3: Add a Content Writer Crew\n\n\nOur flow will need a specialized crew to handle the content creation process. Let’s use the CrewAI CLI to add a content writer crew:\n\n\nCopy\nAsk AI\ncrewai\n flow\n add-crew\n content-crew\n\n\n\n\nThis command automatically creates the necessary directories and template files for your crew. The content writer crew will be responsible for writing and reviewing sections of our guide, working within the overall flow orchestrated by our main application.\n\n\n​\nStep 4: Configure the Content Writer Crew\n\n\nNow, let’s modify the generated files for the content writer crew. We’ll set up two specialized agents - a writer and a reviewer - that will collaborate to create high-quality content for our guide.\n\n\n\n\n\n\nFirst, update the agents configuration file to define our content creation team:\n\n\nRemember to set \nllm\n to the provider you are using.\n\n\n\n\n\n\nCopy\nAsk AI\n# src/guide_creator_flow/crews/content_crew/config/agents.yaml\n\n\ncontent_writer\n:\n\n\n role\n: \n>\n\n\n Educational Content Writer\n\n\n goal\n: \n>\n\n\n Create engaging, informative content that thoroughly explains the assigned topic\n\n\n and provides valuable insights to the reader\n\n\n backstory\n: \n>\n\n\n You are a talented educational writer with expertise in creating clear, engaging\n\n\n content. You have a gift for explaining complex concepts in accessible language\n\n\n and organizing information in a way that helps readers build their understanding.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\ncontent_reviewer\n:\n\n\n role\n: \n>\n\n\n Educational Content Reviewer and Editor\n\n\n goal\n: \n>\n\n\n Ensure content is accurate, comprehensive, well-structured, and maintains\n\n\n consistency with previously written sections\n\n\n backstory\n: \n>\n\n\n You are a meticulous editor with years of experience reviewing educational\n\n\n content. You have an eye for detail, clarity, and coherence. You excel at\n\n\n improving content while maintaining the original author's voice and ensuring\n\n\n consistent quality across multiple sections.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\nThese agent definitions establish the specialized roles and perspectives that will shape how our AI agents approach content creation. Notice how each agent has a distinct purpose and expertise.\n\n\n\n\nNext, update the tasks configuration file to define the specific writing and reviewing tasks:\n\n\n\n\nCopy\nAsk AI\n# src/guide_creator_flow/crews/content_crew/config/tasks.yaml\n\n\nwrite_section_task\n:\n\n\n description\n: \n>\n\n\n Write a comprehensive section on the topic: \"{section_title}\"\n\n\n\n\n Section description: {section_description}\n\n\n Target audience: {audience_level} level learners\n\n\n\n\n Your content should:\n\n\n 1. Begin with a brief introduction to the section topic\n\n\n 2. Explain all key concepts clearly with examples\n\n\n 3. Include practical applications or exercises where appropriate\n\n\n 4. End with a summary of key points\n\n\n 5. Be approximately 500-800 words in length\n\n\n\n\n Format your content in Markdown with appropriate headings, lists, and emphasis.\n\n\n\n\n Previously written sections:\n\n\n {previous_sections}\n\n\n\n\n Make sure your content maintains consistency with previously written sections\n\n\n and builds upon concepts that have already been explained.\n\n\n expected_output\n: \n>\n\n\n A well-structured, comprehensive section in Markdown format that thoroughly\n\n\n explains the topic and is appropriate for the target audience.\n\n\n agent\n: \ncontent_writer\n\n\n\n\nreview_section_task\n:\n\n\n description\n: \n>\n\n\n Review and improve the following section on \"{section_title}\":\n\n\n\n\n {draft_content}\n\n\n\n\n Target audience: {audience_level} level learners\n\n\n\n\n Previously written sections:\n\n\n {previous_sections}\n\n\n\n\n Your review should:\n\n\n 1. Fix any grammatical or spelling errors\n\n\n 2. Improve clarity and readability\n\n\n 3. Ensure content is comprehensive and accurate\n\n\n 4. Verify consistency with previously written sections\n\n\n 5. Enhance the structure and flow\n\n\n 6. Add any missing key information\n\n\n\n\n Provide the improved version of the section in Markdown format.\n\n\n expected_output\n: \n>\n\n\n An improved, polished version of the section that maintains the original\n\n\n structure but enhances clarity, accuracy, and consistency.\n\n\n agent\n: \ncontent_reviewer\n\n\n context\n:\n\n\n - \nwrite_section_task\n\n\n\n\nThese task definitions provide detailed instructions to our agents, ensuring they produce content that meets our quality standards. Note how the \ncontext\n parameter in the review task creates a workflow where the reviewer has access to the writer’s output.\n\n\n\n\nNow, update the crew implementation file to define how our agents and tasks work together:\n\n\n\n\nCopy\nAsk AI\n# src/guide_creator_flow/crews/content_crew/content_crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n ContentCrew\n():\n\n\n \"\"\"Content writing crew\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n @agent\n\n\n def\n content_writer\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'content_writer'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @agent\n\n\n def\n content_reviewer\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'content_reviewer'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n write_section_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'write_section_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n review_section_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'review_section_task'\n], \n# type: ignore[index]\n\n\n context\n=\n[\nself\n.write_section_task()]\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the content writing crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nThis crew definition establishes the relationship between our agents and tasks, setting up a sequential process where the content writer creates a draft and then the reviewer improves it. While this crew can function independently, in our flow it will be orchestrated as part of a larger system.\n\n\n​\nStep 5: Create the Flow\n\n\nNow comes the exciting part - creating the flow that will orchestrate the entire guide creation process. This is where we’ll combine regular Python code, direct LLM calls, and our content creation crew into a cohesive system.\n\n\nOur flow will:\n\n\n\n\nGet user input for a topic and audience level\n\n\nMake a direct LLM call to create a structured guide outline\n\n\nProcess each section sequentially using the content writer crew\n\n\nCombine everything into a final comprehensive document\n\n\n\n\nLet’s create our flow in the \nmain.py\n file:\n\n\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\nimport\n json\n\n\nimport\n os\n\n\nfrom\n typing \nimport\n List, Dict\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\nfrom\n crewai \nimport\n LLM\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n guide_creator_flow.crews.content_crew.content_crew \nimport\n ContentCrew\n\n\n\n\n# Define our models for structured data\n\n\nclass\n Section\n(\nBaseModel\n):\n\n\n title: \nstr\n =\n Field(\ndescription\n=\n\"Title of the section\"\n)\n\n\n description: \nstr\n =\n Field(\ndescription\n=\n\"Brief description of what the section should cover\"\n)\n\n\n\n\nclass\n GuideOutline\n(\nBaseModel\n):\n\n\n title: \nstr\n =\n Field(\ndescription\n=\n\"Title of the guide\"\n)\n\n\n introduction: \nstr\n =\n Field(\ndescription\n=\n\"Introduction to the topic\"\n)\n\n\n target_audience: \nstr\n =\n Field(\ndescription\n=\n\"Description of the target audience\"\n)\n\n\n sections: List[Section] \n=\n Field(\ndescription\n=\n\"List of sections in the guide\"\n)\n\n\n conclusion: \nstr\n =\n Field(\ndescription\n=\n\"Conclusion or summary of the guide\"\n)\n\n\n\n\n# Define our flow state\n\n\nclass\n GuideCreatorState\n(\nBaseModel\n):\n\n\n topic: \nstr\n =\n \"\"\n\n\n audience_level: \nstr\n =\n \"\"\n\n\n guide_outline: GuideOutline \n=\n None\n\n\n sections_content: Dict[\nstr\n, \nstr\n] \n=\n {}\n\n\n\n\nclass\n GuideCreatorFlow\n(Flow[GuideCreatorState]):\n\n\n \"\"\"Flow for creating a comprehensive guide on any topic\"\"\"\n\n\n\n\n @start\n()\n\n\n def\n get_user_input\n(\nself\n):\n\n\n \"\"\"Get input from the user about the guide topic and audience\"\"\"\n\n\n print\n(\n\"\n\\n\n=== Create Your Comprehensive Guide ===\n\\n\n\"\n)\n\n\n\n\n # Get user input\n\n\n self\n.state.topic \n=\n input\n(\n\"What topic would you like to create a guide for? \"\n)\n\n\n\n\n # Get audience level with validation\n\n\n while\n True\n:\n\n\n audience \n=\n input\n(\n\"Who is your target audience? (beginner/intermediate/advanced) \"\n).lower()\n\n\n if\n audience \nin\n [\n\"beginner\"\n, \n\"intermediate\"\n, \n\"advanced\"\n]:\n\n\n self\n.state.audience_level \n=\n audience\n\n\n break\n\n\n print\n(\n\"Please enter 'beginner', 'intermediate', or 'advanced'\"\n)\n\n\n\n\n print\n(\nf\n\"\n\\n\nCreating a guide on \n{\nself\n.state.topic\n}\n for \n{\nself\n.state.audience_level\n}\n audience...\n\\n\n\"\n)\n\n\n return\n self\n.state\n\n\n\n\n @listen\n(get_user_input)\n\n\n def\n create_guide_outline\n(\nself\n, \nstate\n):\n\n\n \"\"\"Create a structured outline for the guide using a direct LLM call\"\"\"\n\n\n print\n(\n\"Creating guide outline...\"\n)\n\n\n\n\n # Initialize the LLM\n\n\n llm \n=\n LLM(\nmodel\n=\n\"openai/gpt-4o-mini\"\n, \nresponse_format\n=\nGuideOutline)\n\n\n\n\n # Create the messages for the outline\n\n\n messages \n=\n [\n\n\n {\n\"role\"\n: \n\"system\"\n, \n\"content\"\n: \n\"You are a helpful assistant designed to output JSON.\"\n},\n\n\n {\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: \nf\n\"\"\"\n\n\n Create a detailed outline for a comprehensive guide on \"\n{\nstate.topic\n}\n\" for \n{\nstate.audience_level\n}\n level learners.\n\n\n\n\n The outline should include:\n\n\n 1. A compelling title for the guide\n\n\n 2. An introduction to the topic\n\n\n 3. 4-6 main sections that cover the most important aspects of the topic\n\n\n 4. A conclusion or summary\n\n\n\n\n For each section, provide a clear title and a brief description of what it should cover.\n\n\n \"\"\"\n}\n\n\n ]\n\n\n\n\n # Make the LLM call with JSON response format\n\n\n response \n=\n llm.call(\nmessages\n=\nmessages)\n\n\n\n\n # Parse the JSON response\n\n\n outline_dict \n=\n json.loads(response)\n\n\n self\n.state.guide_outline \n=\n GuideOutline(\n**\noutline_dict)\n\n\n\n\n # Ensure output directory exists before saving\n\n\n os.makedirs(\n\"output\"\n, \nexist_ok\n=\nTrue\n)\n\n\n\n\n # Save the outline to a file\n\n\n with\n open\n(\n\"output/guide_outline.json\"\n, \n\"w\"\n) \nas\n f:\n\n\n json.dump(outline_dict, f, \nindent\n=\n2\n)\n\n\n\n\n print\n(\nf\n\"Guide outline created with \n{\nlen\n(\nself\n.state.guide_outline.sections)\n}\n sections\"\n)\n\n\n return\n self\n.state.guide_outline\n\n\n\n\n @listen\n(create_guide_outline)\n\n\n def\n write_and_compile_guide\n(\nself\n, \noutline\n):\n\n\n \"\"\"Write all sections and compile the guide\"\"\"\n\n\n print\n(\n\"Writing guide sections and compiling...\"\n)\n\n\n completed_sections \n=\n []\n\n\n\n\n # Process sections one by one to maintain context flow\n\n\n for\n section \nin\n outline.sections:\n\n\n print\n(\nf\n\"Processing section: \n{\nsection.title\n}\n\"\n)\n\n\n\n\n # Build context from previous sections\n\n\n previous_sections_text \n=\n \"\"\n\n\n if\n completed_sections:\n\n\n previous_sections_text \n=\n \"# Previously Written Sections\n\\n\\n\n\"\n\n\n for\n title \nin\n completed_sections:\n\n\n previous_sections_text \n+=\n f\n\"## \n{\ntitle\n}\n\\n\\n\n\"\n\n\n previous_sections_text \n+=\n self\n.state.sections_content.get(title, \n\"\"\n) \n+\n \"\n\\n\\n\n\"\n\n\n else\n:\n\n\n previous_sections_text \n=\n \"No previous sections written yet.\"\n\n\n\n\n # Run the content crew for this section\n\n\n result \n=\n ContentCrew().crew().kickoff(\ninputs\n=\n{\n\n\n \"section_title\"\n: section.title,\n\n\n \"section_description\"\n: section.description,\n\n\n \"audience_level\"\n: \nself\n.state.audience_level,\n\n\n \"previous_sections\"\n: previous_sections_text,\n\n\n \"draft_content\"\n: \n\"\"\n\n\n })\n\n\n\n\n # Store the content\n\n\n self\n.state.sections_content[section.title] \n=\n result.raw\n\n\n completed_sections.append(section.title)\n\n\n print\n(\nf\n\"Section completed: \n{\nsection.title\n}\n\"\n)\n\n\n\n\n # Compile the final guide\n\n\n guide_content \n=\n f\n\"# \n{\noutline.title\n}\n\\n\\n\n\"\n\n\n guide_content \n+=\n f\n\"## Introduction\n\\n\\n\n{\noutline.introduction\n}\n\\n\\n\n\"\n\n\n\n\n # Add each section in order\n\n\n for\n section \nin\n outline.sections:\n\n\n section_content \n=\n self\n.state.sections_content.get(section.title, \n\"\"\n)\n\n\n guide_content \n+=\n f\n\"\n\\n\\n\n{\nsection_content\n}\n\\n\\n\n\"\n\n\n\n\n # Add conclusion\n\n\n guide_content \n+=\n f\n\"## Conclusion\n\\n\\n\n{\noutline.conclusion\n}\n\\n\\n\n\"\n\n\n\n\n # Save the guide\n\n\n with\n open\n(\n\"output/complete_guide.md\"\n, \n\"w\"\n) \nas\n f:\n\n\n f.write(guide_content)\n\n\n\n\n print\n(\n\"\n\\n\nComplete guide compiled and saved to output/complete_guide.md\"\n)\n\n\n return\n \"Guide creation completed successfully\"\n\n\n\n\ndef\n kickoff\n():\n\n\n \"\"\"Run the guide creator flow\"\"\"\n\n\n GuideCreatorFlow().kickoff()\n\n\n print\n(\n\"\n\\n\n=== Flow Complete ===\"\n)\n\n\n print\n(\n\"Your comprehensive guide is ready in the output directory.\"\n)\n\n\n print\n(\n\"Open output/complete_guide.md to view it.\"\n)\n\n\n\n\ndef\n plot\n():\n\n\n \"\"\"Generate a visualization of the flow\"\"\"\n\n\n flow \n=\n GuideCreatorFlow()\n\n\n flow.plot(\n\"guide_creator_flow\"\n)\n\n\n print\n(\n\"Flow visualization saved to guide_creator_flow.html\"\n)\n\n\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n kickoff()\n\n\n\n\nLet’s analyze what’s happening in this flow:\n\n\n\n\nWe define Pydantic models for structured data, ensuring type safety and clear data representation\n\n\nWe create a state class to maintain data across different steps of the flow\n\n\nWe implement three main flow steps:\n\n\n\n\nGetting user input with the \n@start()\n decorator\n\n\nCreating a guide outline with a direct LLM call\n\n\nProcessing sections with our content crew\n\n\n\n\n\n\nWe use the \n@listen()\n decorator to establish event-driven relationships between steps\n\n\n\n\nThis is the power of flows - combining different types of processing (user interaction, direct LLM calls, crew-based tasks) into a coherent, event-driven system.\n\n\n​\nStep 6: Set Up Your Environment Variables\n\n\nCreate a \n.env\n file in your project root with your API keys. See the \nLLM setup\nguide\n for details on configuring a provider.\n\n\n.env\nCopy\nAsk AI\nOPENAI_API_KEY\n=\nyour_openai_api_key\n\n\n# or\n\n\nGEMINI_API_KEY\n=\nyour_gemini_api_key\n\n\n# or\n\n\nANTHROPIC_API_KEY\n=\nyour_anthropic_api_key\n\n\n\n\n​\nStep 7: Install Dependencies\n\n\nInstall the required dependencies:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\n​\nStep 8: Run Your Flow\n\n\nNow it’s time to see your flow in action! Run it using the CrewAI CLI:\n\n\nCopy\nAsk AI\ncrewai\n flow\n kickoff\n\n\n\n\nWhen you run this command, you’ll see your flow spring to life:\n\n\n\n\nIt will prompt you for a topic and audience level\n\n\nIt will create a structured outline for your guide\n\n\nIt will process each section, with the content writer and reviewer collaborating on each\n\n\nFinally, it will compile everything into a comprehensive guide\n\n\n\n\nThis demonstrates the power of flows to orchestrate complex processes involving multiple components, both AI and non-AI.\n\n\n​\nStep 9: Visualize Your Flow\n\n\nOne of the powerful features of flows is the ability to visualize their structure:\n\n\nCopy\nAsk AI\ncrewai\n flow\n plot\n\n\n\n\nThis will create an HTML file that shows the structure of your flow, including the relationships between different steps and the data that flows between them. This visualization can be invaluable for understanding and debugging complex flows.\n\n\n​\nStep 10: Review the Output\n\n\nOnce the flow completes, you’ll find two files in the \noutput\n directory:\n\n\n\n\nguide_outline.json\n: Contains the structured outline of the guide\n\n\ncomplete_guide.md\n: The comprehensive guide with all sections\n\n\n\n\nTake a moment to review these files and appreciate what you’ve built - a system that combines user input, direct AI interactions, and collaborative agent work to produce a complex, high-quality output.\n\n\n​\nThe Art of the Possible: Beyond Your First Flow\n\n\nWhat you’ve learned in this guide provides a foundation for creating much more sophisticated AI systems. Here are some ways you could extend this basic flow:\n\n\n​\nEnhancing User Interaction\n\n\nYou could create more interactive flows with:\n\n\n\n\nWeb interfaces for input and output\n\n\nReal-time progress updates\n\n\nInteractive feedback and refinement loops\n\n\nMulti-stage user interactions\n\n\n\n\n​\nAdding More Processing Steps\n\n\nYou could expand your flow with additional steps for:\n\n\n\n\nResearch before outline creation\n\n\nImage generation for illustrations\n\n\nCode snippet generation for technical guides\n\n\nFinal quality assurance and fact-checking\n\n\n\n\n​\nCreating More Complex Flows\n\n\nYou could implement more sophisticated flow patterns:\n\n\n\n\nConditional branching based on user preferences or content type\n\n\nParallel processing of independent sections\n\n\nIterative refinement loops with feedback\n\n\nIntegration with external APIs and services\n\n\n\n\n​\nApplying to Different Domains\n\n\nThe same patterns can be applied to create flows for:\n\n\n\n\nInteractive storytelling\n: Create personalized stories based on user input\n\n\nBusiness intelligence\n: Process data, generate insights, and create reports\n\n\nProduct development\n: Facilitate ideation, design, and planning\n\n\nEducational systems\n: Create personalized learning experiences\n\n\n\n\n​\nKey Features Demonstrated\n\n\nThis guide creator flow demonstrates several powerful features of CrewAI:\n\n\n\n\nUser interaction\n: The flow collects input directly from the user\n\n\nDirect LLM calls\n: Uses the LLM class for efficient, single-purpose AI interactions\n\n\nStructured data with Pydantic\n: Uses Pydantic models to ensure type safety\n\n\nSequential processing with context\n: Writes sections in order, providing previous sections for context\n\n\nMulti-agent crews\n: Leverages specialized agents (writer and reviewer) for content creation\n\n\nState management\n: Maintains state across different steps of the process\n\n\nEvent-driven architecture\n: Uses the \n@listen\n decorator to respond to events\n\n\n\n\n​\nUnderstanding the Flow Structure\n\n\nLet’s break down the key components of flows to help you understand how to build your own:\n\n\n​\n1. Direct LLM Calls\n\n\nFlows allow you to make direct calls to language models when you need simple, structured responses:\n\n\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"model-id-here\"\n, \n# gpt-4o, gemini-2.0-flash, anthropic/claude...\n\n\n response_format\n=\nGuideOutline\n\n\n)\n\n\nresponse \n=\n llm.call(\nmessages\n=\nmessages)\n\n\n\n\nThis is more efficient than using a crew when you need a specific, structured output.\n\n\n​\n2. Event-Driven Architecture\n\n\nFlows use decorators to establish relationships between components:\n\n\nCopy\nAsk AI\n@start\n()\n\n\ndef\n get_user_input\n(\nself\n):\n\n\n # First step in the flow\n\n\n # ...\n\n\n\n\n@listen\n(get_user_input)\n\n\ndef\n create_guide_outline\n(\nself\n, \nstate\n):\n\n\n # This runs when get_user_input completes\n\n\n # ...\n\n\n\n\nThis creates a clear, declarative structure for your application.\n\n\n​\n3. State Management\n\n\nFlows maintain state across steps, making it easy to share data:\n\n\nCopy\nAsk AI\nclass\n GuideCreatorState\n(\nBaseModel\n):\n\n\n topic: \nstr\n =\n \"\"\n\n\n audience_level: \nstr\n =\n \"\"\n\n\n guide_outline: GuideOutline \n=\n None\n\n\n sections_content: Dict[\nstr\n, \nstr\n] \n=\n {}\n\n\n\n\nThis provides a type-safe way to track and transform data throughout your flow.\n\n\n​\n4. Crew Integration\n\n\nFlows can seamlessly integrate with crews for complex collaborative tasks:\n\n\nCopy\nAsk AI\nresult \n=\n ContentCrew().crew().kickoff(\ninputs\n=\n{\n\n\n \"section_title\"\n: section.title,\n\n\n # ...\n\n\n})\n\n\n\n\nThis allows you to use the right tool for each part of your application - direct LLM calls for simple tasks and crews for complex collaboration.\n\n\n​\nNext Steps\n\n\nNow that you’ve built your first flow, you can:\n\n\n\n\nExperiment with more complex flow structures and patterns\n\n\nTry using \n@router()\n to create conditional branches in your flows\n\n\nExplore the \nand_\n and \nor_\n functions for more complex parallel execution\n\n\nConnect your flow to external APIs, databases, or user interfaces\n\n\nCombine multiple specialized crews in a single flow\n\n\n\n\nCongratulations! You’ve successfully built your first CrewAI Flow that combines regular code, direct LLM calls, and crew-based processing to create a comprehensive guide. These foundational skills enable you to create increasingly sophisticated AI applications that can tackle complex, multi-stage problems through a combination of procedural control and collaborative intelligence.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nBuild Your First Crew\nMastering Flow State Management\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nTaking Control of AI Workflows with Flows\nWhat Makes Flows Powerful\nWhat You’ll Build and Learn\nPrerequisites\nStep 1: Create a New CrewAI Flow Project\nStep 2: Understanding the Project Structure\nStep 3: Add a Content Writer Crew\nStep 4: Configure the Content Writer Crew\nStep 5: Create the Flow\nStep 6: Set Up Your Environment Variables\nStep 7: Install Dependencies\nStep 8: Run Your Flow\nStep 9: Visualize Your Flow\nStep 10: Review the Output\nThe Art of the Possible: Beyond Your First Flow\nEnhancing User Interaction\nAdding More Processing Steps\nCreating More Complex Flows\nApplying to Different Domains\nKey Features Demonstrated\nUnderstanding the Flow Structure\n1. Direct LLM Calls\n2. Event-Driven Architecture\n3. State Management\n4. Crew Integration\nNext Steps\nFlows\nBuild Your First Flow\nCopy page\nLearn how to create structured, event-driven workflows with precise control over execution.\n​\nTaking Control of AI Workflows with Flows\n\n\nCrewAI Flows represent the next level in AI orchestration - combining the collaborative power of AI agent crews with the precision and flexibility of procedural programming. While crews excel at agent collaboration, flows give you fine-grained control over exactly how and when different components of your AI system interact.\n\n\nIn this guide, we’ll walk through creating a powerful CrewAI Flow that generates a comprehensive learning guide on any topic. This tutorial will demonstrate how Flows provide structured, event-driven control over your AI workflows by combining regular code, direct LLM calls, and crew-based processing.\n\n\n​\nWhat Makes Flows Powerful\n\n\nFlows enable you to:\n\n\n\n\nCombine different AI interaction patterns\n - Use crews for complex collaborative tasks, direct LLM calls for simpler operations, and regular code for procedural logic\n\n\nBuild event-driven systems\n - Define how components respond to specific events and data changes\n\n\nMaintain state across components\n - Share and transform data between different parts of your application\n\n\nIntegrate with external systems\n - Seamlessly connect your AI workflow with databases, APIs, and user interfaces\n\n\nCreate complex execution paths\n - Design conditional branches, parallel processing, and dynamic workflows\n\n\n\n\n​\nWhat You’ll Build and Learn\n\n\nBy the end of this guide, you’ll have:\n\n\n\n\nCreated a sophisticated content generation system\n that combines user input, AI planning, and multi-agent content creation\n\n\nOrchestrated the flow of information\n between different components of your system\n\n\nImplemented event-driven architecture\n where each step responds to the completion of previous steps\n\n\nBuilt a foundation for more complex AI applications\n that you can expand and customize\n\n\n\n\nThis guide creator flow demonstrates fundamental patterns that can be applied to create much more advanced applications, such as:\n\n\n\n\nInteractive AI assistants that combine multiple specialized subsystems\n\n\nComplex data processing pipelines with AI-enhanced transformations\n\n\nAutonomous agents that integrate with external services and APIs\n\n\nMulti-stage decision-making systems with human-in-the-loop processes\n\n\n\n\nLet’s dive in and build your first flow!\n\n\n​\nPrerequisites\n\n\nBefore starting, make sure you have:\n\n\n\n\nInstalled CrewAI following the \ninstallation guide\n\n\nSet up your LLM API key in your environment, following the \nLLM setup\nguide\n\n\nBasic understanding of Python\n\n\n\n\n​\nStep 1: Create a New CrewAI Flow Project\n\n\nFirst, let’s create a new CrewAI Flow project using the CLI. This command sets up a scaffolded project with all the necessary directories and template files for your flow.\n\n\nCopy\nAsk AI\ncrewai\n create\n flow\n guide_creator_flow\n\n\ncd\n guide_creator_flow\n\n\n\n\nThis will generate a project with the basic structure needed for your flow.\n\n\nCrewAI Framework Overview\n\n\n​\nStep 2: Understanding the Project Structure\n\n\nThe generated project has the following structure. Take a moment to familiarize yourself with it, as understanding this structure will help you create more complex flows in the future.\n\n\nCopy\nAsk AI\nguide_creator_flow/\n\n\n├── .gitignore\n\n\n├── pyproject.toml\n\n\n├── README.md\n\n\n├── .env\n\n\n├── main.py\n\n\n├── crews/\n\n\n│ └── poem_crew/\n\n\n│ ├── config/\n\n\n│ │ ├── agents.yaml\n\n\n│ │ └── tasks.yaml\n\n\n│ └── poem_crew.py\n\n\n└── tools/\n\n\n └── custom_tool.py\n\n\n\n\nThis structure provides a clear separation between different components of your flow:\n\n\n\n\nThe main flow logic in the \nmain.py\n file\n\n\nSpecialized crews in the \ncrews\n directory\n\n\nCustom tools in the \ntools\n directory\n\n\n\n\nWe’ll modify this structure to create our guide creator flow, which will orchestrate the process of generating comprehensive learning guides.\n\n\n​\nStep 3: Add a Content Writer Crew\n\n\nOur flow will need a specialized crew to handle the content creation process. Let’s use the CrewAI CLI to add a content writer crew:\n\n\nCopy\nAsk AI\ncrewai\n flow\n add-crew\n content-crew\n\n\n\n\nThis command automatically creates the necessary directories and template files for your crew. The content writer crew will be responsible for writing and reviewing sections of our guide, working within the overall flow orchestrated by our main application.\n\n\n​\nStep 4: Configure the Content Writer Crew\n\n\nNow, let’s modify the generated files for the content writer crew. We’ll set up two specialized agents - a writer and a reviewer - that will collaborate to create high-quality content for our guide.\n\n\n\n\n\n\nFirst, update the agents configuration file to define our content creation team:\n\n\nRemember to set \nllm\n to the provider you are using.\n\n\n\n\n\n\nCopy\nAsk AI\n# src/guide_creator_flow/crews/content_crew/config/agents.yaml\n\n\ncontent_writer\n:\n\n\n role\n: \n>\n\n\n Educational Content Writer\n\n\n goal\n: \n>\n\n\n Create engaging, informative content that thoroughly explains the assigned topic\n\n\n and provides valuable insights to the reader\n\n\n backstory\n: \n>\n\n\n You are a talented educational writer with expertise in creating clear, engaging\n\n\n content. You have a gift for explaining complex concepts in accessible language\n\n\n and organizing information in a way that helps readers build their understanding.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\ncontent_reviewer\n:\n\n\n role\n: \n>\n\n\n Educational Content Reviewer and Editor\n\n\n goal\n: \n>\n\n\n Ensure content is accurate, comprehensive, well-structured, and maintains\n\n\n consistency with previously written sections\n\n\n backstory\n: \n>\n\n\n You are a meticulous editor with years of experience reviewing educational\n\n\n content. You have an eye for detail, clarity, and coherence. You excel at\n\n\n improving content while maintaining the original author's voice and ensuring\n\n\n consistent quality across multiple sections.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\nThese agent definitions establish the specialized roles and perspectives that will shape how our AI agents approach content creation. Notice how each agent has a distinct purpose and expertise.\n\n\n\n\nNext, update the tasks configuration file to define the specific writing and reviewing tasks:\n\n\n\n\nCopy\nAsk AI\n# src/guide_creator_flow/crews/content_crew/config/tasks.yaml\n\n\nwrite_section_task\n:\n\n\n description\n: \n>\n\n\n Write a comprehensive section on the topic: \"{section_title}\"\n\n\n\n\n Section description: {section_description}\n\n\n Target audience: {audience_level} level learners\n\n\n\n\n Your content should:\n\n\n 1. Begin with a brief introduction to the section topic\n\n\n 2. Explain all key concepts clearly with examples\n\n\n 3. Include practical applications or exercises where appropriate\n\n\n 4. End with a summary of key points\n\n\n 5. Be approximately 500-800 words in length\n\n\n\n\n Format your content in Markdown with appropriate headings, lists, and emphasis.\n\n\n\n\n Previously written sections:\n\n\n {previous_sections}\n\n\n\n\n Make sure your content maintains consistency with previously written sections\n\n\n and builds upon concepts that have already been explained.\n\n\n expected_output\n: \n>\n\n\n A well-structured, comprehensive section in Markdown format that thoroughly\n\n\n explains the topic and is appropriate for the target audience.\n\n\n agent\n: \ncontent_writer\n\n\n\n\nreview_section_task\n:\n\n\n description\n: \n>\n\n\n Review and improve the following section on \"{section_title}\":\n\n\n\n\n {draft_content}\n\n\n\n\n Target audience: {audience_level} level learners\n\n\n\n\n Previously written sections:\n\n\n {previous_sections}\n\n\n\n\n Your review should:\n\n\n 1. Fix any grammatical or spelling errors\n\n\n 2. Improve clarity and readability\n\n\n 3. Ensure content is comprehensive and accurate\n\n\n 4. Verify consistency with previously written sections\n\n\n 5. Enhance the structure and flow\n\n\n 6. Add any missing key information\n\n\n\n\n Provide the improved version of the section in Markdown format.\n\n\n expected_output\n: \n>\n\n\n An improved, polished version of the section that maintains the original\n\n\n structure but enhances clarity, accuracy, and consistency.\n\n\n agent\n: \ncontent_reviewer\n\n\n context\n:\n\n\n - \nwrite_section_task\n\n\n\n\nThese task definitions provide detailed instructions to our agents, ensuring they produce content that meets our quality standards. Note how the \ncontext\n parameter in the review task creates a workflow where the reviewer has access to the writer’s output.\n\n\n\n\nNow, update the crew implementation file to define how our agents and tasks work together:\n\n\n\n\nCopy\nAsk AI\n# src/guide_creator_flow/crews/content_crew/content_crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n ContentCrew\n():\n\n\n \"\"\"Content writing crew\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n @agent\n\n\n def\n content_writer\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'content_writer'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @agent\n\n\n def\n content_reviewer\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'content_reviewer'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n write_section_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'write_section_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n review_section_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'review_section_task'\n], \n# type: ignore[index]\n\n\n context\n=\n[\nself\n.write_section_task()]\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the content writing crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nThis crew definition establishes the relationship between our agents and tasks, setting up a sequential process where the content writer creates a draft and then the reviewer improves it. While this crew can function independently, in our flow it will be orchestrated as part of a larger system.\n\n\n​\nStep 5: Create the Flow\n\n\nNow comes the exciting part - creating the flow that will orchestrate the entire guide creation process. This is where we’ll combine regular Python code, direct LLM calls, and our content creation crew into a cohesive system.\n\n\nOur flow will:\n\n\n\n\nGet user input for a topic and audience level\n\n\nMake a direct LLM call to create a structured guide outline\n\n\nProcess each section sequentially using the content writer crew\n\n\nCombine everything into a final comprehensive document\n\n\n\n\nLet’s create our flow in the \nmain.py\n file:\n\n\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\nimport\n json\n\n\nimport\n os\n\n\nfrom\n typing \nimport\n List, Dict\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\nfrom\n crewai \nimport\n LLM\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n guide_creator_flow.crews.content_crew.content_crew \nimport\n ContentCrew\n\n\n\n\n# Define our models for structured data\n\n\nclass\n Section\n(\nBaseModel\n):\n\n\n title: \nstr\n =\n Field(\ndescription\n=\n\"Title of the section\"\n)\n\n\n description: \nstr\n =\n Field(\ndescription\n=\n\"Brief description of what the section should cover\"\n)\n\n\n\n\nclass\n GuideOutline\n(\nBaseModel\n):\n\n\n title: \nstr\n =\n Field(\ndescription\n=\n\"Title of the guide\"\n)\n\n\n introduction: \nstr\n =\n Field(\ndescription\n=\n\"Introduction to the topic\"\n)\n\n\n target_audience: \nstr\n =\n Field(\ndescription\n=\n\"Description of the target audience\"\n)\n\n\n sections: List[Section] \n=\n Field(\ndescription\n=\n\"List of sections in the guide\"\n)\n\n\n conclusion: \nstr\n =\n Field(\ndescription\n=\n\"Conclusion or summary of the guide\"\n)\n\n\n\n\n# Define our flow state\n\n\nclass\n GuideCreatorState\n(\nBaseModel\n):\n\n\n topic: \nstr\n =\n \"\"\n\n\n audience_level: \nstr\n =\n \"\"\n\n\n guide_outline: GuideOutline \n=\n None\n\n\n sections_content: Dict[\nstr\n, \nstr\n] \n=\n {}\n\n\n\n\nclass\n GuideCreatorFlow\n(Flow[GuideCreatorState]):\n\n\n \"\"\"Flow for creating a comprehensive guide on any topic\"\"\"\n\n\n\n\n @start\n()\n\n\n def\n get_user_input\n(\nself\n):\n\n\n \"\"\"Get input from the user about the guide topic and audience\"\"\"\n\n\n print\n(\n\"\n\\n\n=== Create Your Comprehensive Guide ===\n\\n\n\"\n)\n\n\n\n\n # Get user input\n\n\n self\n.state.topic \n=\n input\n(\n\"What topic would you like to create a guide for? \"\n)\n\n\n\n\n # Get audience level with validation\n\n\n while\n True\n:\n\n\n audience \n=\n input\n(\n\"Who is your target audience? (beginner/intermediate/advanced) \"\n).lower()\n\n\n if\n audience \nin\n [\n\"beginner\"\n, \n\"intermediate\"\n, \n\"advanced\"\n]:\n\n\n self\n.state.audience_level \n=\n audience\n\n\n break\n\n\n print\n(\n\"Please enter 'beginner', 'intermediate', or 'advanced'\"\n)\n\n\n\n\n print\n(\nf\n\"\n\\n\nCreating a guide on \n{\nself\n.state.topic\n}\n for \n{\nself\n.state.audience_level\n}\n audience...\n\\n\n\"\n)\n\n\n return\n self\n.state\n\n\n\n\n @listen\n(get_user_input)\n\n\n def\n create_guide_outline\n(\nself\n, \nstate\n):\n\n\n \"\"\"Create a structured outline for the guide using a direct LLM call\"\"\"\n\n\n print\n(\n\"Creating guide outline...\"\n)\n\n\n\n\n # Initialize the LLM\n\n\n llm \n=\n LLM(\nmodel\n=\n\"openai/gpt-4o-mini\"\n, \nresponse_format\n=\nGuideOutline)\n\n\n\n\n # Create the messages for the outline\n\n\n messages \n=\n [\n\n\n {\n\"role\"\n: \n\"system\"\n, \n\"content\"\n: \n\"You are a helpful assistant designed to output JSON.\"\n},\n\n\n {\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: \nf\n\"\"\"\n\n\n Create a detailed outline for a comprehensive guide on \"\n{\nstate.topic\n}\n\" for \n{\nstate.audience_level\n}\n level learners.\n\n\n\n\n The outline should include:\n\n\n 1. A compelling title for the guide\n\n\n 2. An introduction to the topic\n\n\n 3. 4-6 main sections that cover the most important aspects of the topic\n\n\n 4. A conclusion or summary\n\n\n\n\n For each section, provide a clear title and a brief description of what it should cover.\n\n\n \"\"\"\n}\n\n\n ]\n\n\n\n\n # Make the LLM call with JSON response format\n\n\n response \n=\n llm.call(\nmessages\n=\nmessages)\n\n\n\n\n # Parse the JSON response\n\n\n outline_dict \n=\n json.loads(response)\n\n\n self\n.state.guide_outline \n=\n GuideOutline(\n**\noutline_dict)\n\n\n\n\n # Ensure output directory exists before saving\n\n\n os.makedirs(\n\"output\"\n, \nexist_ok\n=\nTrue\n)\n\n\n\n\n # Save the outline to a file\n\n\n with\n open\n(\n\"output/guide_outline.json\"\n, \n\"w\"\n) \nas\n f:\n\n\n json.dump(outline_dict, f, \nindent\n=\n2\n)\n\n\n\n\n print\n(\nf\n\"Guide outline created with \n{\nlen\n(\nself\n.state.guide_outline.sections)\n}\n sections\"\n)\n\n\n return\n self\n.state.guide_outline\n\n\n\n\n @listen\n(create_guide_outline)\n\n\n def\n write_and_compile_guide\n(\nself\n, \noutline\n):\n\n\n \"\"\"Write all sections and compile the guide\"\"\"\n\n\n print\n(\n\"Writing guide sections and compiling...\"\n)\n\n\n completed_sections \n=\n []\n\n\n\n\n # Process sections one by one to maintain context flow\n\n\n for\n section \nin\n outline.sections:\n\n\n print\n(\nf\n\"Processing section: \n{\nsection.title\n}\n\"\n)\n\n\n\n\n # Build context from previous sections\n\n\n previous_sections_text \n=\n \"\"\n\n\n if\n completed_sections:\n\n\n previous_sections_text \n=\n \"# Previously Written Sections\n\\n\\n\n\"\n\n\n for\n title \nin\n completed_sections:\n\n\n previous_sections_text \n+=\n f\n\"## \n{\ntitle\n}\n\\n\\n\n\"\n\n\n previous_sections_text \n+=\n self\n.state.sections_content.get(title, \n\"\"\n) \n+\n \"\n\\n\\n\n\"\n\n\n else\n:\n\n\n previous_sections_text \n=\n \"No previous sections written yet.\"\n\n\n\n\n # Run the content crew for this section\n\n\n result \n=\n ContentCrew().crew().kickoff(\ninputs\n=\n{\n\n\n \"section_title\"\n: section.title,\n\n\n \"section_description\"\n: section.description,\n\n\n \"audience_level\"\n: \nself\n.state.audience_level,\n\n\n \"previous_sections\"\n: previous_sections_text,\n\n\n \"draft_content\"\n: \n\"\"\n\n\n })\n\n\n\n\n # Store the content\n\n\n self\n.state.sections_content[section.title] \n=\n result.raw\n\n\n completed_sections.append(section.title)\n\n\n print\n(\nf\n\"Section completed: \n{\nsection.title\n}\n\"\n)\n\n\n\n\n # Compile the final guide\n\n\n guide_content \n=\n f\n\"# \n{\noutline.title\n}\n\\n\\n\n\"\n\n\n guide_content \n+=\n f\n\"## Introduction\n\\n\\n\n{\noutline.introduction\n}\n\\n\\n\n\"\n\n\n\n\n # Add each section in order\n\n\n for\n section \nin\n outline.sections:\n\n\n section_content \n=\n self\n.state.sections_content.get(section.title, \n\"\"\n)\n\n\n guide_content \n+=\n f\n\"\n\\n\\n\n{\nsection_content\n}\n\\n\\n\n\"\n\n\n\n\n # Add conclusion\n\n\n guide_content \n+=\n f\n\"## Conclusion\n\\n\\n\n{\noutline.conclusion\n}\n\\n\\n\n\"\n\n\n\n\n # Save the guide\n\n\n with\n open\n(\n\"output/complete_guide.md\"\n, \n\"w\"\n) \nas\n f:\n\n\n f.write(guide_content)\n\n\n\n\n print\n(\n\"\n\\n\nComplete guide compiled and saved to output/complete_guide.md\"\n)\n\n\n return\n \"Guide creation completed successfully\"\n\n\n\n\ndef\n kickoff\n():\n\n\n \"\"\"Run the guide creator flow\"\"\"\n\n\n GuideCreatorFlow().kickoff()\n\n\n print\n(\n\"\n\\n\n=== Flow Complete ===\"\n)\n\n\n print\n(\n\"Your comprehensive guide is ready in the output directory.\"\n)\n\n\n print\n(\n\"Open output/complete_guide.md to view it.\"\n)\n\n\n\n\ndef\n plot\n():\n\n\n \"\"\"Generate a visualization of the flow\"\"\"\n\n\n flow \n=\n GuideCreatorFlow()\n\n\n flow.plot(\n\"guide_creator_flow\"\n)\n\n\n print\n(\n\"Flow visualization saved to guide_creator_flow.html\"\n)\n\n\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n kickoff()\n\n\n\n\nLet’s analyze what’s happening in this flow:\n\n\n\n\nWe define Pydantic models for structured data, ensuring type safety and clear data representation\n\n\nWe create a state class to maintain data across different steps of the flow\n\n\nWe implement three main flow steps:\n\n\n\n\nGetting user input with the \n@start()\n decorator\n\n\nCreating a guide outline with a direct LLM call\n\n\nProcessing sections with our content crew\n\n\n\n\n\n\nWe use the \n@listen()\n decorator to establish event-driven relationships between steps\n\n\n\n\nThis is the power of flows - combining different types of processing (user interaction, direct LLM calls, crew-based tasks) into a coherent, event-driven system.\n\n\n​\nStep 6: Set Up Your Environment Variables\n\n\nCreate a \n.env\n file in your project root with your API keys. See the \nLLM setup\nguide\n for details on configuring a provider.\n\n\n.env\nCopy\nAsk AI\nOPENAI_API_KEY\n=\nyour_openai_api_key\n\n\n# or\n\n\nGEMINI_API_KEY\n=\nyour_gemini_api_key\n\n\n# or\n\n\nANTHROPIC_API_KEY\n=\nyour_anthropic_api_key\n\n\n\n\n​\nStep 7: Install Dependencies\n\n\nInstall the required dependencies:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\n​\nStep 8: Run Your Flow\n\n\nNow it’s time to see your flow in action! Run it using the CrewAI CLI:\n\n\nCopy\nAsk AI\ncrewai\n flow\n kickoff\n\n\n\n\nWhen you run this command, you’ll see your flow spring to life:\n\n\n\n\nIt will prompt you for a topic and audience level\n\n\nIt will create a structured outline for your guide\n\n\nIt will process each section, with the content writer and reviewer collaborating on each\n\n\nFinally, it will compile everything into a comprehensive guide\n\n\n\n\nThis demonstrates the power of flows to orchestrate complex processes involving multiple components, both AI and non-AI.\n\n\n​\nStep 9: Visualize Your Flow\n\n\nOne of the powerful features of flows is the ability to visualize their structure:\n\n\nCopy\nAsk AI\ncrewai\n flow\n plot\n\n\n\n\nThis will create an HTML file that shows the structure of your flow, including the relationships between different steps and the data that flows between them. This visualization can be invaluable for understanding and debugging complex flows.\n\n\n​\nStep 10: Review the Output\n\n\nOnce the flow completes, you’ll find two files in the \noutput\n directory:\n\n\n\n\nguide_outline.json\n: Contains the structured outline of the guide\n\n\ncomplete_guide.md\n: The comprehensive guide with all sections\n\n\n\n\nTake a moment to review these files and appreciate what you’ve built - a system that combines user input, direct AI interactions, and collaborative agent work to produce a complex, high-quality output.\n\n\n​\nThe Art of the Possible: Beyond Your First Flow\n\n\nWhat you’ve learned in this guide provides a foundation for creating much more sophisticated AI systems. Here are some ways you could extend this basic flow:\n\n\n​\nEnhancing User Interaction\n\n\nYou could create more interactive flows with:\n\n\n\n\nWeb interfaces for input and output\n\n\nReal-time progress updates\n\n\nInteractive feedback and refinement loops\n\n\nMulti-stage user interactions\n\n\n\n\n​\nAdding More Processing Steps\n\n\nYou could expand your flow with additional steps for:\n\n\n\n\nResearch before outline creation\n\n\nImage generation for illustrations\n\n\nCode snippet generation for technical guides\n\n\nFinal quality assurance and fact-checking\n\n\n\n\n​\nCreating More Complex Flows\n\n\nYou could implement more sophisticated flow patterns:\n\n\n\n\nConditional branching based on user preferences or content type\n\n\nParallel processing of independent sections\n\n\nIterative refinement loops with feedback\n\n\nIntegration with external APIs and services\n\n\n\n\n​\nApplying to Different Domains\n\n\nThe same patterns can be applied to create flows for:\n\n\n\n\nInteractive storytelling\n: Create personalized stories based on user input\n\n\nBusiness intelligence\n: Process data, generate insights, and create reports\n\n\nProduct development\n: Facilitate ideation, design, and planning\n\n\nEducational systems\n: Create personalized learning experiences\n\n\n\n\n​\nKey Features Demonstrated\n\n\nThis guide creator flow demonstrates several powerful features of CrewAI:\n\n\n\n\nUser interaction\n: The flow collects input directly from the user\n\n\nDirect LLM calls\n: Uses the LLM class for efficient, single-purpose AI interactions\n\n\nStructured data with Pydantic\n: Uses Pydantic models to ensure type safety\n\n\nSequential processing with context\n: Writes sections in order, providing previous sections for context\n\n\nMulti-agent crews\n: Leverages specialized agents (writer and reviewer) for content creation\n\n\nState management\n: Maintains state across different steps of the process\n\n\nEvent-driven architecture\n: Uses the \n@listen\n decorator to respond to events\n\n\n\n\n​\nUnderstanding the Flow Structure\n\n\nLet’s break down the key components of flows to help you understand how to build your own:\n\n\n​\n1. Direct LLM Calls\n\n\nFlows allow you to make direct calls to language models when you need simple, structured responses:\n\n\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"model-id-here\"\n, \n# gpt-4o, gemini-2.0-flash, anthropic/claude...\n\n\n response_format\n=\nGuideOutline\n\n\n)\n\n\nresponse \n=\n llm.call(\nmessages\n=\nmessages)\n\n\n\n\nThis is more efficient than using a crew when you need a specific, structured output.\n\n\n​\n2. Event-Driven Architecture\n\n\nFlows use decorators to establish relationships between components:\n\n\nCopy\nAsk AI\n@start\n()\n\n\ndef\n get_user_input\n(\nself\n):\n\n\n # First step in the flow\n\n\n # ...\n\n\n\n\n@listen\n(get_user_input)\n\n\ndef\n create_guide_outline\n(\nself\n, \nstate\n):\n\n\n # This runs when get_user_input completes\n\n\n # ...\n\n\n\n\nThis creates a clear, declarative structure for your application.\n\n\n​\n3. State Management\n\n\nFlows maintain state across steps, making it easy to share data:\n\n\nCopy\nAsk AI\nclass\n GuideCreatorState\n(\nBaseModel\n):\n\n\n topic: \nstr\n =\n \"\"\n\n\n audience_level: \nstr\n =\n \"\"\n\n\n guide_outline: GuideOutline \n=\n None\n\n\n sections_content: Dict[\nstr\n, \nstr\n] \n=\n {}\n\n\n\n\nThis provides a type-safe way to track and transform data throughout your flow.\n\n\n​\n4. Crew Integration\n\n\nFlows can seamlessly integrate with crews for complex collaborative tasks:\n\n\nCopy\nAsk AI\nresult \n=\n ContentCrew().crew().kickoff(\ninputs\n=\n{\n\n\n \"section_title\"\n: section.title,\n\n\n # ...\n\n\n})\n\n\n\n\nThis allows you to use the right tool for each part of your application - direct LLM calls for simple tasks and crews for complex collaboration.\n\n\n​\nNext Steps\n\n\nNow that you’ve built your first flow, you can:\n\n\n\n\nExperiment with more complex flow structures and patterns\n\n\nTry using \n@router()\n to create conditional branches in your flows\n\n\nExplore the \nand_\n and \nor_\n functions for more complex parallel execution\n\n\nConnect your flow to external APIs, databases, or user interfaces\n\n\nCombine multiple specialized crews in a single flow\n\n\n\n\nCongratulations! You’ve successfully built your first CrewAI Flow that combines regular code, direct LLM calls, and crew-based processing to create a comprehensive guide. These foundational skills enable you to create increasingly sophisticated AI applications that can tackle complex, multi-stage problems through a combination of procedural control and collaborative intelligence.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nBuild Your First Crew\nMastering Flow State Management\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nTaking Control of AI Workflows with Flows\nWhat Makes Flows Powerful\nWhat You’ll Build and Learn\nPrerequisites\nStep 1: Create a New CrewAI Flow Project\nStep 2: Understanding the Project Structure\nStep 3: Add a Content Writer Crew\nStep 4: Configure the Content Writer Crew\nStep 5: Create the Flow\nStep 6: Set Up Your Environment Variables\nStep 7: Install Dependencies\nStep 8: Run Your Flow\nStep 9: Visualize Your Flow\nStep 10: Review the Output\nThe Art of the Possible: Beyond Your First Flow\nEnhancing User Interaction\nAdding More Processing Steps\nCreating More Complex Flows\nApplying to Different Domains\nKey Features Demonstrated\nUnderstanding the Flow Structure\n1. Direct LLM Calls\n2. Event-Driven Architecture\n3. State Management\n4. Crew Integration\nNext Steps" }, { "source": "https://docs.crewai.com/en/installation", "title": "Installation - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nInstallation\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nInstallation\nCopy page\nGet started with CrewAI - Install, configure, and build your first AI crew\n​\nVideo Tutorial\n\n\nWatch this video tutorial for a step-by-step demonstration of the installation process:\n\n\n\n\n​\nText Tutorial\n\n\nPython Version Requirements\nCrewAI requires \nPython >=3.10 and <3.14\n. Here’s how to check your version:\nCopy\nAsk AI\npython3\n --version\n\n\nIf you need to update Python, visit \npython.org/downloads\n\n\nCrewAI uses the \nuv\n as its dependency management and package handling tool. It simplifies project setup and execution, offering a seamless experience.\n\n\nIf you haven’t installed \nuv\n yet, follow \nstep 1\n to quickly get it set up on your system, else you can skip to \nstep 2\n.\n\n\n1\nInstall uv\n\n\n\n\nOn macOS/Linux:\n\n\nUse \ncurl\n to download the script and execute it with \nsh\n:\n\n\nCopy\nAsk AI\ncurl\n -LsSf\n https://astral.sh/uv/install.sh\n |\n sh\n\n\n\n\nIf your system doesn’t have \ncurl\n, you can use \nwget\n:\n\n\nCopy\nAsk AI\nwget\n -qO-\n https://astral.sh/uv/install.sh\n |\n sh\n\n\n\n\n\n\n\n\nOn Windows:\n\n\nUse \nirm\n to download the script and \niex\n to execute it:\n\n\nCopy\nAsk AI\npowershell\n -ExecutionPolicy\n ByPass\n -c\n \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n\n\n\nIf you run into any issues, refer to \nUV’s installation guide\n for more information.\n\n\n\n\n2\nInstall CrewAI 🚀\n\n\n\n\nRun the following command to install \ncrewai\n CLI:\n\n\nCopy\nAsk AI\nuv\n tool\n install\n crewai\n\n\n\n\nIf you encounter a \nPATH\n warning, run this command to update your shell:\nCopy\nAsk AI\nuv\n tool\n update-shell\n\n\n\n\nIf you encounter the \nchroma-hnswlib==0.7.6\n build error (\nfatal error C1083: Cannot open include file: 'float.h'\n) on Windows, install \nVisual Studio Build Tools\n with \nDesktop development with C++\n.\n\n\n\n\n\n\nTo verify that \ncrewai\n is installed, run:\n\n\nCopy\nAsk AI\nuv\n tool\n list\n\n\n\n\n\n\n\n\nYou should see something like:\n\n\nCopy\nAsk AI\ncrewai\n v0.102.0\n\n\n-\n crewai\n\n\n\n\n\n\n\n\nIf you need to update \ncrewai\n, run:\n\n\nCopy\nAsk AI\nuv\n tool\n install\n crewai\n --upgrade\n\n\n\n\n\n\nInstallation successful! You’re ready to create your first crew! 🎉\n\n\n​\nCreating a CrewAI Project\n\n\nWe recommend using the \nYAML\n template scaffolding for a structured approach to defining agents and tasks. Here’s how to get started:\n\n\n1\nGenerate Project Scaffolding\n\n\n\n\nRun the \ncrewai\n CLI command:\n\n\nCopy\nAsk AI\ncrewai\n create\n crew\n <\nyour_project_nam\ne\n>\n\n\n\n\n\n\n\n\nThis creates a new project with the following structure:\n\n\nCopy\nAsk AI\nmy_project/\n\n\n├── .gitignore\n\n\n├── knowledge/\n\n\n├── pyproject.toml\n\n\n├── README.md\n\n\n├── .env\n\n\n└── src/\n\n\n └── my_project/\n\n\n ├── __init__.py\n\n\n ├── main.py\n\n\n ├── crew.py\n\n\n ├── tools/\n\n\n │ ├── custom_tool.py\n\n\n │ └── __init__.py\n\n\n └── config/\n\n\n ├── agents.yaml\n\n\n └── tasks.yaml\n\n\n\n\n\n\n2\nCustomize Your Project\n\n\n\n\nYour project will contain these essential files:\n\n\nFile\nPurpose\nagents.yaml\nDefine your AI agents and their roles\ntasks.yaml\nSet up agent tasks and workflows\n.env\nStore API keys and environment variables\nmain.py\nProject entry point and execution flow\ncrew.py\nCrew orchestration and coordination\ntools/\nDirectory for custom agent tools\nknowledge/\nDirectory for knowledge base\n\n\n\n\n\n\nStart by editing \nagents.yaml\n and \ntasks.yaml\n to define your crew’s behavior.\n\n\n\n\n\n\nKeep sensitive information like API keys in \n.env\n.\n\n\n\n\n3\nRun your Crew\n\n\nBefore you run your crew, make sure to run:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\n\n\nIf you need to install additional packages, use:\n\n\nCopy\nAsk AI\nuv\n add\n <\npackage-nam\ne\n>\n\n\n\n\n\n\nTo run your crew, execute the following command in the root of your project:\n\n\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\n\n\n\n\n​\nEnterprise Installation Options\n\n\nFor teams and organizations, CrewAI offers enterprise deployment options that eliminate setup complexity:\n​\nCrewAI Enterprise (SaaS)\n\n\nZero installation required - just sign up for free at \napp.crewai.com\n\n\nAutomatic updates and maintenance\n\n\nManaged infrastructure and scaling\n\n\nBuild Crews with no Code\n\n\n​\nCrewAI Factory (Self-hosted)\n\n\nContainerized deployment for your infrastructure\n\n\nSupports any hyperscaler including on prem deployments\n\n\nIntegration with your existing security systems\n\n\nExplore Enterprise Options\nLearn about CrewAI’s enterprise offerings and schedule a demo\n\n\n​\nNext Steps\n\n\nBuild Your First Agent\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nIntroduction\nQuickstart\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nVideo Tutorial\nText Tutorial\nCreating a CrewAI Project\nEnterprise Installation Options\nNext Steps\nGet Started\nInstallation\nCopy page\nGet started with CrewAI - Install, configure, and build your first AI crew\n​\nVideo Tutorial\n\n\nWatch this video tutorial for a step-by-step demonstration of the installation process:\n\n\n\n\n​\nText Tutorial\n\n\nPython Version Requirements\nCrewAI requires \nPython >=3.10 and <3.14\n. Here’s how to check your version:\nCopy\nAsk AI\npython3\n --version\n\n\nIf you need to update Python, visit \npython.org/downloads\n\n\nCrewAI uses the \nuv\n as its dependency management and package handling tool. It simplifies project setup and execution, offering a seamless experience.\n\n\nIf you haven’t installed \nuv\n yet, follow \nstep 1\n to quickly get it set up on your system, else you can skip to \nstep 2\n.\n\n\n1\nInstall uv\n\n\n\n\nOn macOS/Linux:\n\n\nUse \ncurl\n to download the script and execute it with \nsh\n:\n\n\nCopy\nAsk AI\ncurl\n -LsSf\n https://astral.sh/uv/install.sh\n |\n sh\n\n\n\n\nIf your system doesn’t have \ncurl\n, you can use \nwget\n:\n\n\nCopy\nAsk AI\nwget\n -qO-\n https://astral.sh/uv/install.sh\n |\n sh\n\n\n\n\n\n\n\n\nOn Windows:\n\n\nUse \nirm\n to download the script and \niex\n to execute it:\n\n\nCopy\nAsk AI\npowershell\n -ExecutionPolicy\n ByPass\n -c\n \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n\n\n\nIf you run into any issues, refer to \nUV’s installation guide\n for more information.\n\n\n\n\n2\nInstall CrewAI 🚀\n\n\n\n\nRun the following command to install \ncrewai\n CLI:\n\n\nCopy\nAsk AI\nuv\n tool\n install\n crewai\n\n\n\n\nIf you encounter a \nPATH\n warning, run this command to update your shell:\nCopy\nAsk AI\nuv\n tool\n update-shell\n\n\n\n\nIf you encounter the \nchroma-hnswlib==0.7.6\n build error (\nfatal error C1083: Cannot open include file: 'float.h'\n) on Windows, install \nVisual Studio Build Tools\n with \nDesktop development with C++\n.\n\n\n\n\n\n\nTo verify that \ncrewai\n is installed, run:\n\n\nCopy\nAsk AI\nuv\n tool\n list\n\n\n\n\n\n\n\n\nYou should see something like:\n\n\nCopy\nAsk AI\ncrewai\n v0.102.0\n\n\n-\n crewai\n\n\n\n\n\n\n\n\nIf you need to update \ncrewai\n, run:\n\n\nCopy\nAsk AI\nuv\n tool\n install\n crewai\n --upgrade\n\n\n\n\n\n\nInstallation successful! You’re ready to create your first crew! 🎉\n\n\n​\nCreating a CrewAI Project\n\n\nWe recommend using the \nYAML\n template scaffolding for a structured approach to defining agents and tasks. Here’s how to get started:\n\n\n1\nGenerate Project Scaffolding\n\n\n\n\nRun the \ncrewai\n CLI command:\n\n\nCopy\nAsk AI\ncrewai\n create\n crew\n <\nyour_project_nam\ne\n>\n\n\n\n\n\n\n\n\nThis creates a new project with the following structure:\n\n\nCopy\nAsk AI\nmy_project/\n\n\n├── .gitignore\n\n\n├── knowledge/\n\n\n├── pyproject.toml\n\n\n├── README.md\n\n\n├── .env\n\n\n└── src/\n\n\n └── my_project/\n\n\n ├── __init__.py\n\n\n ├── main.py\n\n\n ├── crew.py\n\n\n ├── tools/\n\n\n │ ├── custom_tool.py\n\n\n │ └── __init__.py\n\n\n └── config/\n\n\n ├── agents.yaml\n\n\n └── tasks.yaml\n\n\n\n\n\n\n2\nCustomize Your Project\n\n\n\n\nYour project will contain these essential files:\n\n\nFile\nPurpose\nagents.yaml\nDefine your AI agents and their roles\ntasks.yaml\nSet up agent tasks and workflows\n.env\nStore API keys and environment variables\nmain.py\nProject entry point and execution flow\ncrew.py\nCrew orchestration and coordination\ntools/\nDirectory for custom agent tools\nknowledge/\nDirectory for knowledge base\n\n\n\n\n\n\nStart by editing \nagents.yaml\n and \ntasks.yaml\n to define your crew’s behavior.\n\n\n\n\n\n\nKeep sensitive information like API keys in \n.env\n.\n\n\n\n\n3\nRun your Crew\n\n\nBefore you run your crew, make sure to run:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\n\n\nIf you need to install additional packages, use:\n\n\nCopy\nAsk AI\nuv\n add\n <\npackage-nam\ne\n>\n\n\n\n\n\n\nTo run your crew, execute the following command in the root of your project:\n\n\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\n\n\n\n\n​\nEnterprise Installation Options\n\n\nFor teams and organizations, CrewAI offers enterprise deployment options that eliminate setup complexity:\n​\nCrewAI Enterprise (SaaS)\n\n\nZero installation required - just sign up for free at \napp.crewai.com\n\n\nAutomatic updates and maintenance\n\n\nManaged infrastructure and scaling\n\n\nBuild Crews with no Code\n\n\n​\nCrewAI Factory (Self-hosted)\n\n\nContainerized deployment for your infrastructure\n\n\nSupports any hyperscaler including on prem deployments\n\n\nIntegration with your existing security systems\n\n\nExplore Enterprise Options\nLearn about CrewAI’s enterprise offerings and schedule a demo\n\n\n​\nNext Steps\n\n\nBuild Your First Agent\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nIntroduction\nQuickstart\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nVideo Tutorial\nText Tutorial\nCreating a CrewAI Project\nEnterprise Installation Options\nNext Steps" }, { "source": "https://docs.crewai.com/en/learn/custom-manager-agent", "title": "Custom Manager Agent - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nCustom Manager Agent\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nCustom Manager Agent\nCopy page\nLearn how to set a custom agent as the manager in CrewAI, providing more control over task management and coordination.\n​\nSetting a Specific Agent as Manager in CrewAI\n\n\nCrewAI allows users to set a specific agent as the manager of the crew, providing more control over the management and coordination of tasks.\nThis feature enables the customization of the managerial role to better fit your project’s requirements.\n\n\n​\nUsing the \nmanager_agent\n Attribute\n\n\n​\nCustom Manager Agent\n\n\nThe \nmanager_agent\n attribute allows you to define a custom agent to manage the crew. This agent will oversee the entire process, ensuring that tasks are completed efficiently and to the highest standard.\n\n\n​\nExample\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Conduct thorough research and analysis on AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Senior Writer\"\n,\n\n\n goal\n=\n\"Create compelling content about AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're a senior writer, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently writing content for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\n# Define your task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.\"\n,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Define the manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Instantiate your crew with a custom manager\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[task],\n\n\n manager_agent\n=\nmanager,\n\n\n process\n=\nProcess.hierarchical,\n\n\n)\n\n\n\n\n# Start the crew's work\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nBenefits of a Custom Manager Agent\n\n\n\n\nEnhanced Control\n: Tailor the management approach to fit the specific needs of your project.\n\n\nImproved Coordination\n: Ensure efficient task coordination and management by an experienced agent.\n\n\nCustomizable Management\n: Define managerial roles and responsibilities that align with your project’s goals.\n\n\n\n\n​\nSetting a Manager LLM\n\n\nIf you’re using the hierarchical process and don’t want to set a custom manager agent, you can specify the language model for the manager:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nmanager_llm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[task],\n\n\n process\n=\nProcess.hierarchical,\n\n\n manager_llm\n=\nmanager_llm\n\n\n)\n\n\n\n\nEither \nmanager_agent\n or \nmanager_llm\n must be set when using the hierarchical process.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCustom LLM Implementation\nCustomize Agents\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nSetting a Specific Agent as Manager in CrewAI\nUsing the manager_agent Attribute\nCustom Manager Agent\nExample\nBenefits of a Custom Manager Agent\nSetting a Manager LLM\nLearn\nCustom Manager Agent\nCopy page\nLearn how to set a custom agent as the manager in CrewAI, providing more control over task management and coordination.\n​\nSetting a Specific Agent as Manager in CrewAI\n\n\nCrewAI allows users to set a specific agent as the manager of the crew, providing more control over the management and coordination of tasks.\nThis feature enables the customization of the managerial role to better fit your project’s requirements.\n\n\n​\nUsing the \nmanager_agent\n Attribute\n\n\n​\nCustom Manager Agent\n\n\nThe \nmanager_agent\n attribute allows you to define a custom agent to manage the crew. This agent will oversee the entire process, ensuring that tasks are completed efficiently and to the highest standard.\n\n\n​\nExample\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Conduct thorough research and analysis on AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Senior Writer\"\n,\n\n\n goal\n=\n\"Create compelling content about AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're a senior writer, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently writing content for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\n# Define your task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.\"\n,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Define the manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Instantiate your crew with a custom manager\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[task],\n\n\n manager_agent\n=\nmanager,\n\n\n process\n=\nProcess.hierarchical,\n\n\n)\n\n\n\n\n# Start the crew's work\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nBenefits of a Custom Manager Agent\n\n\n\n\nEnhanced Control\n: Tailor the management approach to fit the specific needs of your project.\n\n\nImproved Coordination\n: Ensure efficient task coordination and management by an experienced agent.\n\n\nCustomizable Management\n: Define managerial roles and responsibilities that align with your project’s goals.\n\n\n\n\n​\nSetting a Manager LLM\n\n\nIf you’re using the hierarchical process and don’t want to set a custom manager agent, you can specify the language model for the manager:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nmanager_llm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[task],\n\n\n process\n=\nProcess.hierarchical,\n\n\n manager_llm\n=\nmanager_llm\n\n\n)\n\n\n\n\nEither \nmanager_agent\n or \nmanager_llm\n must be set when using the hierarchical process.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCustom LLM Implementation\nCustomize Agents\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nSetting a Specific Agent as Manager in CrewAI\nUsing the manager_agent Attribute\nCustom Manager Agent\nExample\nBenefits of a Custom Manager Agent\nSetting a Manager LLM" }, { "source": "https://docs.crewai.com/en/telemetry", "title": "Telemetry - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nTelemetry\nTelemetry\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nTelemetry\nTelemetry\nCopy page\nUnderstanding the telemetry data collected by CrewAI and how it contributes to the enhancement of the library.\n​\nTelemetry\n\n\nBy default, we collect no data that would be considered personal information under GDPR and other privacy regulations.\nWe do collect Tool’s names and Agent’s roles, so be advised not to include any personal information in the tool’s names or the Agent’s roles.\nBecause no personal information is collected, it’s not necessary to worry about data residency.\nWhen \nshare_crew\n is enabled, additional data is collected which may contain personal information if included by the user.\nUsers should exercise caution when enabling this feature to ensure compliance with privacy regulations.\n\n\nCrewAI utilizes anonymous telemetry to gather usage statistics with the primary goal of enhancing the library.\nOur focus is on improving and developing the features, integrations, and tools most utilized by our users.\n\n\nIt’s pivotal to understand that by default, \nNO personal data is collected\n concerning prompts, task descriptions, agents’ backstories or goals,\nusage of tools, API calls, responses, any data processed by the agents, or secrets and environment variables.\nWhen the \nshare_crew\n feature is enabled, detailed data including task descriptions, agents’ backstories or goals, and other specific attributes are collected\nto provide deeper insights. This expanded data collection may include personal information if users have incorporated it into their crews or tasks.\nUsers should carefully consider the content of their crews and tasks before enabling \nshare_crew\n.\nUsers can disable telemetry by setting the environment variable \nCREWAI_DISABLE_TELEMETRY\n to \ntrue\n or by setting \nOTEL_SDK_DISABLED\n to \ntrue\n (note that the latter disables all OpenTelemetry instrumentation globally).\n\n\n​\nExamples:\n\n\nCopy\nAsk AI\n# Disable CrewAI telemetry only\n\n\nos.environ[\n'CREWAI_DISABLE_TELEMETRY'\n] \n=\n 'true'\n\n\n\n\n# Disable all OpenTelemetry (including CrewAI)\n\n\nos.environ[\n'OTEL_SDK_DISABLED'\n] \n=\n 'true'\n\n\n\n\n​\nData Explanation:\n\n\nDefaulted\nData\nReason and Specifics\nYes\nCrewAI and Python Version\nTracks software versions. Example: CrewAI v1.2.3, Python 3.8.10. No personal data.\nYes\nCrew Metadata\nIncludes: randomly generated key and ID, process type (e.g., ‘sequential’, ‘parallel’), boolean flag for memory usage (true/false), count of tasks, count of agents. All non-personal.\nYes\nAgent Data\nIncludes: randomly generated key and ID, role name (should not include personal info), boolean settings (verbose, delegation enabled, code execution allowed), max iterations, max RPM, max retry limit, LLM info (see LLM Attributes), list of tool names (should not include personal info). No personal data.\nYes\nTask Metadata\nIncludes: randomly generated key and ID, boolean execution settings (async_execution, human_input), associated agent’s role and key, list of tool names. All non-personal.\nYes\nTool Usage Statistics\nIncludes: tool name (should not include personal info), number of usage attempts (integer), LLM attributes used. No personal data.\nYes\nTest Execution Data\nIncludes: crew’s randomly generated key and ID, number of iterations, model name used, quality score (float), execution time (in seconds). All non-personal.\nYes\nTask Lifecycle Data\nIncludes: creation and execution start/end times, crew and task identifiers. Stored as spans with timestamps. No personal data.\nYes\nLLM Attributes\nIncludes: name, model_name, model, top_k, temperature, and class name of the LLM. All technical, non-personal data.\nYes\nCrew Deployment attempt using crewAI CLI\nIncludes: The fact a deploy is being made and crew id, and if it’s trying to pull logs, no other data.\nNo\nAgent’s Expanded Data\nIncludes: goal description, backstory text, i18n prompt file identifier. Users should ensure no personal info is included in text fields.\nNo\nDetailed Task Information\nIncludes: task description, expected output description, context references. Users should ensure no personal info is included in these fields.\nNo\nEnvironment Information\nIncludes: platform, release, system, version, and CPU count. Example: ‘Windows 10’, ‘x86_64’. No personal data.\nNo\nCrew and Task Inputs and Outputs\nIncludes: input parameters and output results as non-identifiable data. Users should ensure no personal info is included.\nNo\nComprehensive Crew Execution Data\nIncludes: detailed logs of crew operations, all agents and tasks data, final output. All non-personal and technical in nature.\n\n\n“No” in the “Defaulted” column indicates that this data is only collected when \nshare_crew\n is set to \ntrue\n.\n\n\n​\nOpt-In Further Telemetry Sharing\n\n\nUsers can choose to share their complete telemetry data by enabling the \nshare_crew\n attribute to \nTrue\n in their crew configurations.\nEnabling \nshare_crew\n results in the collection of detailed crew and task execution data, including \ngoal\n, \nbackstory\n, \ncontext\n, and \noutput\n of tasks.\nThis enables a deeper insight into usage patterns.\n\n\nIf you enable \nshare_crew\n, the collected data may include personal information if it has been incorporated into crew configurations, task descriptions, or outputs.\nUsers should carefully review their data and ensure compliance with GDPR and other applicable privacy regulations before enabling this feature.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nUsing Annotations in crew.py\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nTelemetry\nExamples:\nData Explanation:\nOpt-In Further Telemetry Sharing\nTelemetry\nTelemetry\nCopy page\nUnderstanding the telemetry data collected by CrewAI and how it contributes to the enhancement of the library.\n​\nTelemetry\n\n\nBy default, we collect no data that would be considered personal information under GDPR and other privacy regulations.\nWe do collect Tool’s names and Agent’s roles, so be advised not to include any personal information in the tool’s names or the Agent’s roles.\nBecause no personal information is collected, it’s not necessary to worry about data residency.\nWhen \nshare_crew\n is enabled, additional data is collected which may contain personal information if included by the user.\nUsers should exercise caution when enabling this feature to ensure compliance with privacy regulations.\n\n\nCrewAI utilizes anonymous telemetry to gather usage statistics with the primary goal of enhancing the library.\nOur focus is on improving and developing the features, integrations, and tools most utilized by our users.\n\n\nIt’s pivotal to understand that by default, \nNO personal data is collected\n concerning prompts, task descriptions, agents’ backstories or goals,\nusage of tools, API calls, responses, any data processed by the agents, or secrets and environment variables.\nWhen the \nshare_crew\n feature is enabled, detailed data including task descriptions, agents’ backstories or goals, and other specific attributes are collected\nto provide deeper insights. This expanded data collection may include personal information if users have incorporated it into their crews or tasks.\nUsers should carefully consider the content of their crews and tasks before enabling \nshare_crew\n.\nUsers can disable telemetry by setting the environment variable \nCREWAI_DISABLE_TELEMETRY\n to \ntrue\n or by setting \nOTEL_SDK_DISABLED\n to \ntrue\n (note that the latter disables all OpenTelemetry instrumentation globally).\n\n\n​\nExamples:\n\n\nCopy\nAsk AI\n# Disable CrewAI telemetry only\n\n\nos.environ[\n'CREWAI_DISABLE_TELEMETRY'\n] \n=\n 'true'\n\n\n\n\n# Disable all OpenTelemetry (including CrewAI)\n\n\nos.environ[\n'OTEL_SDK_DISABLED'\n] \n=\n 'true'\n\n\n\n\n​\nData Explanation:\n\n\nDefaulted\nData\nReason and Specifics\nYes\nCrewAI and Python Version\nTracks software versions. Example: CrewAI v1.2.3, Python 3.8.10. No personal data.\nYes\nCrew Metadata\nIncludes: randomly generated key and ID, process type (e.g., ‘sequential’, ‘parallel’), boolean flag for memory usage (true/false), count of tasks, count of agents. All non-personal.\nYes\nAgent Data\nIncludes: randomly generated key and ID, role name (should not include personal info), boolean settings (verbose, delegation enabled, code execution allowed), max iterations, max RPM, max retry limit, LLM info (see LLM Attributes), list of tool names (should not include personal info). No personal data.\nYes\nTask Metadata\nIncludes: randomly generated key and ID, boolean execution settings (async_execution, human_input), associated agent’s role and key, list of tool names. All non-personal.\nYes\nTool Usage Statistics\nIncludes: tool name (should not include personal info), number of usage attempts (integer), LLM attributes used. No personal data.\nYes\nTest Execution Data\nIncludes: crew’s randomly generated key and ID, number of iterations, model name used, quality score (float), execution time (in seconds). All non-personal.\nYes\nTask Lifecycle Data\nIncludes: creation and execution start/end times, crew and task identifiers. Stored as spans with timestamps. No personal data.\nYes\nLLM Attributes\nIncludes: name, model_name, model, top_k, temperature, and class name of the LLM. All technical, non-personal data.\nYes\nCrew Deployment attempt using crewAI CLI\nIncludes: The fact a deploy is being made and crew id, and if it’s trying to pull logs, no other data.\nNo\nAgent’s Expanded Data\nIncludes: goal description, backstory text, i18n prompt file identifier. Users should ensure no personal info is included in text fields.\nNo\nDetailed Task Information\nIncludes: task description, expected output description, context references. Users should ensure no personal info is included in these fields.\nNo\nEnvironment Information\nIncludes: platform, release, system, version, and CPU count. Example: ‘Windows 10’, ‘x86_64’. No personal data.\nNo\nCrew and Task Inputs and Outputs\nIncludes: input parameters and output results as non-identifiable data. Users should ensure no personal info is included.\nNo\nComprehensive Crew Execution Data\nIncludes: detailed logs of crew operations, all agents and tasks data, final output. All non-personal and technical in nature.\n\n\n“No” in the “Defaulted” column indicates that this data is only collected when \nshare_crew\n is set to \ntrue\n.\n\n\n​\nOpt-In Further Telemetry Sharing\n\n\nUsers can choose to share their complete telemetry data by enabling the \nshare_crew\n attribute to \nTrue\n in their crew configurations.\nEnabling \nshare_crew\n results in the collection of detailed crew and task execution data, including \ngoal\n, \nbackstory\n, \ncontext\n, and \noutput\n of tasks.\nThis enables a deeper insight into usage patterns.\n\n\nIf you enable \nshare_crew\n, the collected data may include personal information if it has been incorporated into crew configurations, task descriptions, or outputs.\nUsers should carefully review their data and ensure compliance with GDPR and other applicable privacy regulations before enabling this feature.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nUsing Annotations in crew.py\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nTelemetry\nExamples:\nData Explanation:\nOpt-In Further Telemetry Sharing" }, { "source": "https://docs.crewai.com/en/learn/conditional-tasks", "title": "Conditional Tasks - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nConditional Tasks\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nConditional Tasks\nCopy page\nLearn how to use conditional tasks in a crewAI kickoff\n​\nIntroduction\n\n\nConditional Tasks in crewAI allow for dynamic workflow adaptation based on the outcomes of previous tasks.\nThis powerful feature enables crews to make decisions and execute tasks selectively, enhancing the flexibility and efficiency of your AI-driven processes.\n\n\n​\nExample Usage\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n List\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\nfrom\n crewai \nimport\n Agent, Crew\n\n\nfrom\n crewai.tasks.conditional_task \nimport\n ConditionalTask\n\n\nfrom\n crewai.tasks.task_output \nimport\n TaskOutput\n\n\nfrom\n crewai.task \nimport\n Task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Define a condition function for the conditional task\n\n\n# If false, the task will be skipped, if true, then execute the task.\n\n\ndef\n is_data_missing\n(\noutput\n: TaskOutput) -> \nbool\n:\n\n\n return\n len\n(output.pydantic.events) \n<\n 10\n # this will skip this task\n\n\n\n\n# Define the agents\n\n\ndata_fetcher_agent \n=\n Agent(\n\n\n role\n=\n\"Data Fetcher\"\n,\n\n\n goal\n=\n\"Fetch data online using Serper tool\"\n,\n\n\n backstory\n=\n\"Backstory 1\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n)\n\n\n\n\ndata_processor_agent \n=\n Agent(\n\n\n role\n=\n\"Data Processor\"\n,\n\n\n goal\n=\n\"Process fetched data\"\n,\n\n\n backstory\n=\n\"Backstory 2\"\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nsummary_generator_agent \n=\n Agent(\n\n\n role\n=\n\"Summary Generator\"\n,\n\n\n goal\n=\n\"Generate summary from fetched data\"\n,\n\n\n backstory\n=\n\"Backstory 3\"\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nclass\n EventOutput\n(\nBaseModel\n):\n\n\n events: List[\nstr\n]\n\n\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"Fetch data about events in San Francisco using Serper tool\"\n,\n\n\n expected_output\n=\n\"List of 10 things to do in SF this week\"\n,\n\n\n agent\n=\ndata_fetcher_agent,\n\n\n output_pydantic\n=\nEventOutput,\n\n\n)\n\n\n\n\nconditional_task \n=\n ConditionalTask(\n\n\n description\n=\n\"\"\"\n\n\n Check if data is missing. If we have less than 10 events,\n\n\n fetch more events using Serper tool so that\n\n\n we have a total of 10 events in SF this week..\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"List of 10 Things to do in SF this week\"\n,\n\n\n condition\n=\nis_data_missing,\n\n\n agent\n=\ndata_processor_agent,\n\n\n)\n\n\n\n\ntask3 \n=\n Task(\n\n\n description\n=\n\"Generate summary of events in San Francisco from fetched data\"\n,\n\n\n expected_output\n=\n\"A complete report on the customer and their customers and competitors, including their demographics, preferences, market positioning and audience engagement.\"\n,\n\n\n agent\n=\nsummary_generator_agent,\n\n\n)\n\n\n\n\n# Create a crew with the tasks\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[data_fetcher_agent, data_processor_agent, summary_generator_agent],\n\n\n tasks\n=\n[task1, conditional_task, task3],\n\n\n verbose\n=\nTrue\n,\n\n\n planning\n=\nTrue\n\n\n)\n\n\n\n\n# Run the crew\n\n\nresult \n=\n crew.kickoff()\n\n\nprint\n(\n\"results\"\n, result)\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nStrategic LLM Selection Guide\nCoding Agents\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nExample Usage\nLearn\nConditional Tasks\nCopy page\nLearn how to use conditional tasks in a crewAI kickoff\n​\nIntroduction\n\n\nConditional Tasks in crewAI allow for dynamic workflow adaptation based on the outcomes of previous tasks.\nThis powerful feature enables crews to make decisions and execute tasks selectively, enhancing the flexibility and efficiency of your AI-driven processes.\n\n\n​\nExample Usage\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n List\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\nfrom\n crewai \nimport\n Agent, Crew\n\n\nfrom\n crewai.tasks.conditional_task \nimport\n ConditionalTask\n\n\nfrom\n crewai.tasks.task_output \nimport\n TaskOutput\n\n\nfrom\n crewai.task \nimport\n Task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Define a condition function for the conditional task\n\n\n# If false, the task will be skipped, if true, then execute the task.\n\n\ndef\n is_data_missing\n(\noutput\n: TaskOutput) -> \nbool\n:\n\n\n return\n len\n(output.pydantic.events) \n<\n 10\n # this will skip this task\n\n\n\n\n# Define the agents\n\n\ndata_fetcher_agent \n=\n Agent(\n\n\n role\n=\n\"Data Fetcher\"\n,\n\n\n goal\n=\n\"Fetch data online using Serper tool\"\n,\n\n\n backstory\n=\n\"Backstory 1\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n)\n\n\n\n\ndata_processor_agent \n=\n Agent(\n\n\n role\n=\n\"Data Processor\"\n,\n\n\n goal\n=\n\"Process fetched data\"\n,\n\n\n backstory\n=\n\"Backstory 2\"\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nsummary_generator_agent \n=\n Agent(\n\n\n role\n=\n\"Summary Generator\"\n,\n\n\n goal\n=\n\"Generate summary from fetched data\"\n,\n\n\n backstory\n=\n\"Backstory 3\"\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nclass\n EventOutput\n(\nBaseModel\n):\n\n\n events: List[\nstr\n]\n\n\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"Fetch data about events in San Francisco using Serper tool\"\n,\n\n\n expected_output\n=\n\"List of 10 things to do in SF this week\"\n,\n\n\n agent\n=\ndata_fetcher_agent,\n\n\n output_pydantic\n=\nEventOutput,\n\n\n)\n\n\n\n\nconditional_task \n=\n ConditionalTask(\n\n\n description\n=\n\"\"\"\n\n\n Check if data is missing. If we have less than 10 events,\n\n\n fetch more events using Serper tool so that\n\n\n we have a total of 10 events in SF this week..\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"List of 10 Things to do in SF this week\"\n,\n\n\n condition\n=\nis_data_missing,\n\n\n agent\n=\ndata_processor_agent,\n\n\n)\n\n\n\n\ntask3 \n=\n Task(\n\n\n description\n=\n\"Generate summary of events in San Francisco from fetched data\"\n,\n\n\n expected_output\n=\n\"A complete report on the customer and their customers and competitors, including their demographics, preferences, market positioning and audience engagement.\"\n,\n\n\n agent\n=\nsummary_generator_agent,\n\n\n)\n\n\n\n\n# Create a crew with the tasks\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[data_fetcher_agent, data_processor_agent, summary_generator_agent],\n\n\n tasks\n=\n[task1, conditional_task, task3],\n\n\n verbose\n=\nTrue\n,\n\n\n planning\n=\nTrue\n\n\n)\n\n\n\n\n# Run the crew\n\n\nresult \n=\n crew.kickoff()\n\n\nprint\n(\n\"results\"\n, result)\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nStrategic LLM Selection Guide\nCoding Agents\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nExample Usage" }, { "source": "https://docs.crewai.com/#when-to-use-crews-vs-flows", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/learn/using-annotations", "title": "Using Annotations in crew.py - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nUsing Annotations in crew.py\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nUsing Annotations in crew.py\nCopy page\nLearn how to use annotations to properly structure agents, tasks, and components in CrewAI\nThis guide explains how to use annotations to properly reference \nagents\n, \ntasks\n, and other components in the \ncrew.py\n file.\n\n\n​\nIntroduction\n\n\nAnnotations in the CrewAI framework are used to decorate classes and methods, providing metadata and functionality to various components of your crew. These annotations help in organizing and structuring your code, making it more readable and maintainable.\n\n\n​\nAvailable Annotations\n\n\nThe CrewAI framework provides the following annotations:\n\n\n\n\n@CrewBase\n: Used to decorate the main crew class.\n\n\n@agent\n: Decorates methods that define and return Agent objects.\n\n\n@task\n: Decorates methods that define and return Task objects.\n\n\n@crew\n: Decorates the method that creates and returns the Crew object.\n\n\n@llm\n: Decorates methods that initialize and return Language Model objects.\n\n\n@tool\n: Decorates methods that initialize and return Tool objects.\n\n\n@callback\n: Used for defining callback methods.\n\n\n@output_json\n: Used for methods that output JSON data.\n\n\n@output_pydantic\n: Used for methods that output Pydantic models.\n\n\n@cache_handler\n: Used for defining cache handling methods.\n\n\n\n\n​\nUsage Examples\n\n\nLet’s go through examples of how to use these annotations:\n\n\n​\n1. Crew Base Class\n\n\nCopy\nAsk AI\n@CrewBase\n\n\nclass\n LinkedinProfileCrew\n():\n\n\n \"\"\"LinkedinProfile crew\"\"\"\n\n\n agents_config \n=\n 'config/agents.yaml'\n\n\n tasks_config \n=\n 'config/tasks.yaml'\n\n\n\n\nThe \n@CrewBase\n annotation is used to decorate the main crew class. This class typically contains configurations and methods for creating agents, tasks, and the crew itself.\n\n\n​\n2. Tool Definition\n\n\nCopy\nAsk AI\n@tool\n\n\ndef\n myLinkedInProfileTool\n(\nself\n):\n\n\n return\n LinkedInProfileTool()\n\n\n\n\nThe \n@tool\n annotation is used to decorate methods that return tool objects. These tools can be used by agents to perform specific tasks.\n\n\n​\n3. LLM Definition\n\n\nCopy\nAsk AI\n@llm\n\n\ndef\n groq_llm\n(\nself\n):\n\n\n api_key \n=\n os.getenv(\n'api_key'\n)\n\n\n return\n ChatGroq(\napi_key\n=\napi_key, \ntemperature\n=\n0\n, \nmodel_name\n=\n\"mixtral-8x7b-32768\"\n)\n\n\n\n\nThe \n@llm\n annotation is used to decorate methods that initialize and return Language Model objects. These LLMs are used by agents for natural language processing tasks.\n\n\n​\n4. Agent Definition\n\n\nCopy\nAsk AI\n@agent\n\n\ndef\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n]\n\n\n )\n\n\n\n\nThe \n@agent\n annotation is used to decorate methods that define and return Agent objects.\n\n\n​\n5. Task Definition\n\n\nCopy\nAsk AI\n@task\n\n\ndef\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_linkedin_task'\n],\n\n\n agent\n=\nself\n.researcher()\n\n\n )\n\n\n\n\nThe \n@task\n annotation is used to decorate methods that define and return Task objects. These methods specify the task configuration and the agent responsible for the task.\n\n\n​\n6. Crew Creation\n\n\nCopy\nAsk AI\n@crew\n\n\ndef\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the LinkedinProfile crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\nThe \n@crew\n annotation is used to decorate the method that creates and returns the \nCrew\n object. This method assembles all the components (agents and tasks) into a functional crew.\n\n\n​\nYAML Configuration\n\n\nThe agent configurations are typically stored in a YAML file. Here’s an example of how the \nagents.yaml\n file might look for the researcher agent:\n\n\nCopy\nAsk AI\nresearcher\n:\n\n\n role\n: \n>\n\n\n LinkedIn Profile Senior Data Researcher\n\n\n goal\n: \n>\n\n\n Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}\n\n\n Generate a Dall-E image based on domain {domain}\n\n\n backstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.\n\n\n Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting\n\n\n professional information clearly and concisely.\n\n\n allow_delegation\n: \nFalse\n\n\n verbose\n: \nTrue\n\n\n llm\n: \ngroq_llm\n\n\n tools\n:\n\n\n - \nmyLinkedInProfileTool\n\n\n - \nmySerperDevTool\n\n\n - \nmyDallETool\n\n\n\n\nThis YAML configuration corresponds to the researcher agent defined in the \nLinkedinProfileCrew\n class. The configuration specifies the agent’s role, goal, backstory, and other properties such as the LLM and tools it uses.\n\n\nNote how the \nllm\n and \ntools\n in the YAML file correspond to the methods decorated with \n@llm\n and \n@tool\n in the Python class.\n\n\n​\nBest Practices\n\n\n\n\nConsistent Naming\n: Use clear and consistent naming conventions for your methods. For example, agent methods could be named after their roles (e.g., researcher, reporting_analyst).\n\n\nEnvironment Variables\n: Use environment variables for sensitive information like API keys.\n\n\nFlexibility\n: Design your crew to be flexible by allowing easy addition or removal of agents and tasks.\n\n\nYAML-Code Correspondence\n: Ensure that the names and structures in your YAML files correspond correctly to the decorated methods in your Python code.\n\n\n\n\nBy following these guidelines and properly using annotations, you can create well-structured and maintainable crews using the CrewAI framework.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nSequential Processes\nTelemetry\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nAvailable Annotations\nUsage Examples\n1. Crew Base Class\n2. Tool Definition\n3. LLM Definition\n4. Agent Definition\n5. Task Definition\n6. Crew Creation\nYAML Configuration\nBest Practices\nLearn\nUsing Annotations in crew.py\nCopy page\nLearn how to use annotations to properly structure agents, tasks, and components in CrewAI\nThis guide explains how to use annotations to properly reference \nagents\n, \ntasks\n, and other components in the \ncrew.py\n file.\n\n\n​\nIntroduction\n\n\nAnnotations in the CrewAI framework are used to decorate classes and methods, providing metadata and functionality to various components of your crew. These annotations help in organizing and structuring your code, making it more readable and maintainable.\n\n\n​\nAvailable Annotations\n\n\nThe CrewAI framework provides the following annotations:\n\n\n\n\n@CrewBase\n: Used to decorate the main crew class.\n\n\n@agent\n: Decorates methods that define and return Agent objects.\n\n\n@task\n: Decorates methods that define and return Task objects.\n\n\n@crew\n: Decorates the method that creates and returns the Crew object.\n\n\n@llm\n: Decorates methods that initialize and return Language Model objects.\n\n\n@tool\n: Decorates methods that initialize and return Tool objects.\n\n\n@callback\n: Used for defining callback methods.\n\n\n@output_json\n: Used for methods that output JSON data.\n\n\n@output_pydantic\n: Used for methods that output Pydantic models.\n\n\n@cache_handler\n: Used for defining cache handling methods.\n\n\n\n\n​\nUsage Examples\n\n\nLet’s go through examples of how to use these annotations:\n\n\n​\n1. Crew Base Class\n\n\nCopy\nAsk AI\n@CrewBase\n\n\nclass\n LinkedinProfileCrew\n():\n\n\n \"\"\"LinkedinProfile crew\"\"\"\n\n\n agents_config \n=\n 'config/agents.yaml'\n\n\n tasks_config \n=\n 'config/tasks.yaml'\n\n\n\n\nThe \n@CrewBase\n annotation is used to decorate the main crew class. This class typically contains configurations and methods for creating agents, tasks, and the crew itself.\n\n\n​\n2. Tool Definition\n\n\nCopy\nAsk AI\n@tool\n\n\ndef\n myLinkedInProfileTool\n(\nself\n):\n\n\n return\n LinkedInProfileTool()\n\n\n\n\nThe \n@tool\n annotation is used to decorate methods that return tool objects. These tools can be used by agents to perform specific tasks.\n\n\n​\n3. LLM Definition\n\n\nCopy\nAsk AI\n@llm\n\n\ndef\n groq_llm\n(\nself\n):\n\n\n api_key \n=\n os.getenv(\n'api_key'\n)\n\n\n return\n ChatGroq(\napi_key\n=\napi_key, \ntemperature\n=\n0\n, \nmodel_name\n=\n\"mixtral-8x7b-32768\"\n)\n\n\n\n\nThe \n@llm\n annotation is used to decorate methods that initialize and return Language Model objects. These LLMs are used by agents for natural language processing tasks.\n\n\n​\n4. Agent Definition\n\n\nCopy\nAsk AI\n@agent\n\n\ndef\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n]\n\n\n )\n\n\n\n\nThe \n@agent\n annotation is used to decorate methods that define and return Agent objects.\n\n\n​\n5. Task Definition\n\n\nCopy\nAsk AI\n@task\n\n\ndef\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_linkedin_task'\n],\n\n\n agent\n=\nself\n.researcher()\n\n\n )\n\n\n\n\nThe \n@task\n annotation is used to decorate methods that define and return Task objects. These methods specify the task configuration and the agent responsible for the task.\n\n\n​\n6. Crew Creation\n\n\nCopy\nAsk AI\n@crew\n\n\ndef\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the LinkedinProfile crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\nThe \n@crew\n annotation is used to decorate the method that creates and returns the \nCrew\n object. This method assembles all the components (agents and tasks) into a functional crew.\n\n\n​\nYAML Configuration\n\n\nThe agent configurations are typically stored in a YAML file. Here’s an example of how the \nagents.yaml\n file might look for the researcher agent:\n\n\nCopy\nAsk AI\nresearcher\n:\n\n\n role\n: \n>\n\n\n LinkedIn Profile Senior Data Researcher\n\n\n goal\n: \n>\n\n\n Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}\n\n\n Generate a Dall-E image based on domain {domain}\n\n\n backstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.\n\n\n Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting\n\n\n professional information clearly and concisely.\n\n\n allow_delegation\n: \nFalse\n\n\n verbose\n: \nTrue\n\n\n llm\n: \ngroq_llm\n\n\n tools\n:\n\n\n - \nmyLinkedInProfileTool\n\n\n - \nmySerperDevTool\n\n\n - \nmyDallETool\n\n\n\n\nThis YAML configuration corresponds to the researcher agent defined in the \nLinkedinProfileCrew\n class. The configuration specifies the agent’s role, goal, backstory, and other properties such as the LLM and tools it uses.\n\n\nNote how the \nllm\n and \ntools\n in the YAML file correspond to the methods decorated with \n@llm\n and \n@tool\n in the Python class.\n\n\n​\nBest Practices\n\n\n\n\nConsistent Naming\n: Use clear and consistent naming conventions for your methods. For example, agent methods could be named after their roles (e.g., researcher, reporting_analyst).\n\n\nEnvironment Variables\n: Use environment variables for sensitive information like API keys.\n\n\nFlexibility\n: Design your crew to be flexible by allowing easy addition or removal of agents and tasks.\n\n\nYAML-Code Correspondence\n: Ensure that the names and structures in your YAML files correspond correctly to the decorated methods in your Python code.\n\n\n\n\nBy following these guidelines and properly using annotations, you can create well-structured and maintainable crews using the CrewAI framework.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nSequential Processes\nTelemetry\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nAvailable Annotations\nUsage Examples\n1. Crew Base Class\n2. Tool Definition\n3. LLM Definition\n4. Agent Definition\n5. Task Definition\n6. Crew Creation\nYAML Configuration\nBest Practices" }, { "source": "https://docs.crewai.com/en/observability/overview", "title": "Overview - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nOverview\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nOverview\nCopy page\nMonitor, evaluate, and optimize your CrewAI agents with comprehensive observability tools\n​\nObservability for CrewAI\n\n\nObservability is crucial for understanding how your CrewAI agents perform, identifying bottlenecks, and ensuring reliable operation in production environments. This section covers various tools and platforms that provide monitoring, evaluation, and optimization capabilities for your agent workflows.\n\n\n​\nWhy Observability Matters\n\n\n\n\nPerformance Monitoring\n: Track agent execution times, token usage, and resource consumption\n\n\nQuality Assurance\n: Evaluate output quality and consistency across different scenarios\n\n\nDebugging\n: Identify and resolve issues in agent behavior and task execution\n\n\nCost Management\n: Monitor LLM API usage and associated costs\n\n\nContinuous Improvement\n: Gather insights to optimize agent performance over time\n\n\n\n\n​\nAvailable Observability Tools\n\n\n​\nMonitoring & Tracing Platforms\n\n\nAgentOps\nSession replays, metrics, and monitoring for agent development and production.\nOpenLIT\nOpenTelemetry-native monitoring with cost tracking and performance analytics.\nMLflow\nMachine learning lifecycle management with tracing and evaluation capabilities.\nLangfuse\nLLM engineering platform with detailed tracing and analytics.\nLangtrace\nOpen-source observability for LLMs and agent frameworks.\nArize Phoenix\nAI observability platform for monitoring and troubleshooting.\nPortkey\nAI gateway with comprehensive monitoring and reliability features.\nOpik\nDebug, evaluate, and monitor LLM applications with comprehensive tracing.\nWeave\nWeights & Biases platform for tracking and evaluating AI applications.\n\n\n​\nEvaluation & Quality Assurance\n\n\nPatronus AI\nComprehensive evaluation platform for LLM outputs and agent behaviors.\n\n\n​\nKey Observability Metrics\n\n\n​\nPerformance Metrics\n\n\n\n\nExecution Time\n: How long agents take to complete tasks\n\n\nToken Usage\n: Input/output tokens consumed by LLM calls\n\n\nAPI Latency\n: Response times from external services\n\n\nSuccess Rate\n: Percentage of successfully completed tasks\n\n\n\n\n​\nQuality Metrics\n\n\n\n\nOutput Accuracy\n: Correctness of agent responses\n\n\nConsistency\n: Reliability across similar inputs\n\n\nRelevance\n: How well outputs match expected results\n\n\nSafety\n: Compliance with content policies and guidelines\n\n\n\n\n​\nCost Metrics\n\n\n\n\nAPI Costs\n: Expenses from LLM provider usage\n\n\nResource Utilization\n: Compute and memory consumption\n\n\nCost per Task\n: Economic efficiency of agent operations\n\n\nBudget Tracking\n: Monitoring against spending limits\n\n\n\n\n​\nGetting Started\n\n\n\n\nChoose Your Tools\n: Select observability platforms that match your needs\n\n\nInstrument Your Code\n: Add monitoring to your CrewAI applications\n\n\nSet Up Dashboards\n: Configure visualizations for key metrics\n\n\nDefine Alerts\n: Create notifications for important events\n\n\nEstablish Baselines\n: Measure initial performance for comparison\n\n\nIterate and Improve\n: Use insights to optimize your agents\n\n\n\n\n​\nBest Practices\n\n\n​\nDevelopment Phase\n\n\n\n\nUse detailed tracing to understand agent behavior\n\n\nImplement evaluation metrics early in development\n\n\nMonitor resource usage during testing\n\n\nSet up automated quality checks\n\n\n\n\n​\nProduction Phase\n\n\n\n\nImplement comprehensive monitoring and alerting\n\n\nTrack performance trends over time\n\n\nMonitor for anomalies and degradation\n\n\nMaintain cost visibility and control\n\n\n\n\n​\nContinuous Improvement\n\n\n\n\nRegular performance reviews and optimization\n\n\nA/B testing of different agent configurations\n\n\nFeedback loops for quality improvement\n\n\nDocumentation of lessons learned\n\n\n\n\nChoose the observability tools that best fit your use case, infrastructure, and monitoring requirements to ensure your CrewAI agents perform reliably and efficiently.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMultiOn Tool\nAgentOps Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nObservability for CrewAI\nWhy Observability Matters\nAvailable Observability Tools\nMonitoring & Tracing Platforms\nEvaluation & Quality Assurance\nKey Observability Metrics\nPerformance Metrics\nQuality Metrics\nCost Metrics\nGetting Started\nBest Practices\nDevelopment Phase\nProduction Phase\nContinuous Improvement\nObservability\nOverview\nCopy page\nMonitor, evaluate, and optimize your CrewAI agents with comprehensive observability tools\n​\nObservability for CrewAI\n\n\nObservability is crucial for understanding how your CrewAI agents perform, identifying bottlenecks, and ensuring reliable operation in production environments. This section covers various tools and platforms that provide monitoring, evaluation, and optimization capabilities for your agent workflows.\n\n\n​\nWhy Observability Matters\n\n\n\n\nPerformance Monitoring\n: Track agent execution times, token usage, and resource consumption\n\n\nQuality Assurance\n: Evaluate output quality and consistency across different scenarios\n\n\nDebugging\n: Identify and resolve issues in agent behavior and task execution\n\n\nCost Management\n: Monitor LLM API usage and associated costs\n\n\nContinuous Improvement\n: Gather insights to optimize agent performance over time\n\n\n\n\n​\nAvailable Observability Tools\n\n\n​\nMonitoring & Tracing Platforms\n\n\nAgentOps\nSession replays, metrics, and monitoring for agent development and production.\nOpenLIT\nOpenTelemetry-native monitoring with cost tracking and performance analytics.\nMLflow\nMachine learning lifecycle management with tracing and evaluation capabilities.\nLangfuse\nLLM engineering platform with detailed tracing and analytics.\nLangtrace\nOpen-source observability for LLMs and agent frameworks.\nArize Phoenix\nAI observability platform for monitoring and troubleshooting.\nPortkey\nAI gateway with comprehensive monitoring and reliability features.\nOpik\nDebug, evaluate, and monitor LLM applications with comprehensive tracing.\nWeave\nWeights & Biases platform for tracking and evaluating AI applications.\n\n\n​\nEvaluation & Quality Assurance\n\n\nPatronus AI\nComprehensive evaluation platform for LLM outputs and agent behaviors.\n\n\n​\nKey Observability Metrics\n\n\n​\nPerformance Metrics\n\n\n\n\nExecution Time\n: How long agents take to complete tasks\n\n\nToken Usage\n: Input/output tokens consumed by LLM calls\n\n\nAPI Latency\n: Response times from external services\n\n\nSuccess Rate\n: Percentage of successfully completed tasks\n\n\n\n\n​\nQuality Metrics\n\n\n\n\nOutput Accuracy\n: Correctness of agent responses\n\n\nConsistency\n: Reliability across similar inputs\n\n\nRelevance\n: How well outputs match expected results\n\n\nSafety\n: Compliance with content policies and guidelines\n\n\n\n\n​\nCost Metrics\n\n\n\n\nAPI Costs\n: Expenses from LLM provider usage\n\n\nResource Utilization\n: Compute and memory consumption\n\n\nCost per Task\n: Economic efficiency of agent operations\n\n\nBudget Tracking\n: Monitoring against spending limits\n\n\n\n\n​\nGetting Started\n\n\n\n\nChoose Your Tools\n: Select observability platforms that match your needs\n\n\nInstrument Your Code\n: Add monitoring to your CrewAI applications\n\n\nSet Up Dashboards\n: Configure visualizations for key metrics\n\n\nDefine Alerts\n: Create notifications for important events\n\n\nEstablish Baselines\n: Measure initial performance for comparison\n\n\nIterate and Improve\n: Use insights to optimize your agents\n\n\n\n\n​\nBest Practices\n\n\n​\nDevelopment Phase\n\n\n\n\nUse detailed tracing to understand agent behavior\n\n\nImplement evaluation metrics early in development\n\n\nMonitor resource usage during testing\n\n\nSet up automated quality checks\n\n\n\n\n​\nProduction Phase\n\n\n\n\nImplement comprehensive monitoring and alerting\n\n\nTrack performance trends over time\n\n\nMonitor for anomalies and degradation\n\n\nMaintain cost visibility and control\n\n\n\n\n​\nContinuous Improvement\n\n\n\n\nRegular performance reviews and optimization\n\n\nA/B testing of different agent configurations\n\n\nFeedback loops for quality improvement\n\n\nDocumentation of lessons learned\n\n\n\n\nChoose the observability tools that best fit your use case, infrastructure, and monitoring requirements to ensure your CrewAI agents perform reliably and efficiently.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMultiOn Tool\nAgentOps Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nObservability for CrewAI\nWhy Observability Matters\nAvailable Observability Tools\nMonitoring & Tracing Platforms\nEvaluation & Quality Assurance\nKey Observability Metrics\nPerformance Metrics\nQuality Metrics\nCost Metrics\nGetting Started\nBest Practices\nDevelopment Phase\nProduction Phase\nContinuous Improvement" }, { "source": "https://docs.crewai.com/en/observability/mlflow", "title": "MLflow Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nMLflow Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nMLflow Integration\nCopy page\nQuickly start monitoring your Agents with MLflow.\n​\nMLflow Overview\n\n\nMLflow\n is an open-source platform to assist machine learning practitioners and teams in handling the complexities of the machine learning process.\n\n\nIt provides a tracing feature that enhances LLM observability in your Generative AI applications by capturing detailed information about the execution of your application’s services.\nTracing provides a way to record the inputs, outputs, and metadata associated with each intermediate step of a request, enabling you to easily pinpoint the source of bugs and unexpected behaviors.\n\n\n\n\n​\nFeatures\n\n\n\n\nTracing Dashboard\n: Monitor activities of your crewAI agents with detailed dashboards that include inputs, outputs and metadata of spans.\n\n\nAutomated Tracing\n: A fully automated integration with crewAI, which can be enabled by running \nmlflow.crewai.autolog()\n.\n\n\nManual Trace Instrumentation with minor efforts\n: Customize trace instrumentation through MLflow’s high-level fluent APIs such as decorators, function wrappers and context managers.\n\n\nOpenTelemetry Compatibility\n: MLflow Tracing supports exporting traces to an OpenTelemetry Collector, which can then be used to export traces to various backends such as Jaeger, Zipkin, and AWS X-Ray.\n\n\nPackage and Deploy Agents\n: Package and deploy your crewAI agents to an inference server with a variety of deployment targets.\n\n\nSecurely Host LLMs\n: Host multiple LLM from various providers in one unified endpoint through MFflow gateway.\n\n\nEvaluation\n: Evaluate your crewAI agents with a wide range of metrics using a convenient API \nmlflow.evaluate()\n.\n\n\n\n\n​\nSetup Instructions\n\n\n1\nInstall MLflow package\nCopy\nAsk AI\n# The crewAI integration is available in mlflow>=2.19.0\n\n\npip\n install\n mlflow\n\n\n2\nStart MFflow tracking server\nCopy\nAsk AI\n# This process is optional, but it is recommended to use MLflow tracking server for better visualization and broader features.\n\n\nmlflow\n server\n\n\n3\nInitialize MLflow in Your Application\nAdd the following two lines to your application code:\nCopy\nAsk AI\nimport\n mlflow\n\n\n\n\nmlflow.crewai.autolog()\n\n\n\n\n# Optional: Set a tracking URI and an experiment name if you have a tracking server\n\n\nmlflow.set_tracking_uri(\n\"http://localhost:5000\"\n)\n\n\nmlflow.set_experiment(\n\"CrewAI\"\n)\n\n\nExample Usage for tracing CrewAI Agents:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool, WebsiteSearchTool\n\n\n\n\nfrom\n textwrap \nimport\n dedent\n\n\n\n\ncontent \n=\n \"Users name is John. He is 30 years old and lives in San Francisco.\"\n\n\nstring_source \n=\n StringKnowledgeSource(\n\n\n content\n=\ncontent, \nmetadata\n=\n{\n\"preference\"\n: \n\"personal\"\n}\n\n\n)\n\n\n\n\nsearch_tool \n=\n WebsiteSearchTool()\n\n\n\n\n\n\nclass\n TripAgents\n:\n\n\n def\n city_selection_agent\n(\nself\n):\n\n\n return\n Agent(\n\n\n role\n=\n\"City Selection Expert\"\n,\n\n\n goal\n=\n\"Select the best city based on weather, season, and prices\"\n,\n\n\n backstory\n=\n\"An expert in analyzing travel data to pick ideal destinations\"\n,\n\n\n tools\n=\n[\n\n\n search_tool,\n\n\n ],\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n def\n local_expert\n(\nself\n):\n\n\n return\n Agent(\n\n\n role\n=\n\"Local Expert at this city\"\n,\n\n\n goal\n=\n\"Provide the BEST insights about the selected city\"\n,\n\n\n backstory\n=\n\"\"\"A knowledgeable local guide with extensive information\n\n\n about the city, it's attractions and customs\"\"\"\n,\n\n\n tools\n=\n[search_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n\n\nclass\n TripTasks\n:\n\n\n def\n identify_task\n(\nself\n, \nagent\n, \norigin\n, \ncities\n, \ninterests\n, \nrange\n):\n\n\n return\n Task(\n\n\n description\n=\ndedent(\n\n\n f\n\"\"\"\n\n\n Analyze and select the best city for the trip based\n\n\n on specific criteria such as weather patterns, seasonal\n\n\n events, and travel costs. This task involves comparing\n\n\n multiple cities, considering factors like current weather\n\n\n conditions, upcoming cultural or seasonal events, and\n\n\n overall travel expenses.\n\n\n Your final answer must be a detailed\n\n\n report on the chosen city, and everything you found out\n\n\n about it, including the actual flight costs, weather\n\n\n forecast and attractions.\n\n\n\n\n Traveling from: \n{\norigin\n}\n\n\n City Options: \n{\ncities\n}\n\n\n Trip Date: \n{\nrange\n}\n\n\n Traveler Interests: \n{\ninterests\n}\n\n\n \"\"\"\n\n\n ),\n\n\n agent\n=\nagent,\n\n\n expected_output\n=\n\"Detailed report on the chosen city including flight costs, weather forecast, and attractions\"\n,\n\n\n )\n\n\n\n\n def\n gather_task\n(\nself\n, \nagent\n, \norigin\n, \ninterests\n, \nrange\n):\n\n\n return\n Task(\n\n\n description\n=\ndedent(\n\n\n f\n\"\"\"\n\n\n As a local expert on this city you must compile an\n\n\n in-depth guide for someone traveling there and wanting\n\n\n to have THE BEST trip ever!\n\n\n Gather information about key attractions, local customs,\n\n\n special events, and daily activity recommendations.\n\n\n Find the best spots to go to, the kind of place only a\n\n\n local would know.\n\n\n This guide should provide a thorough overview of what\n\n\n the city has to offer, including hidden gems, cultural\n\n\n hotspots, must-visit landmarks, weather forecasts, and\n\n\n high level costs.\n\n\n The final answer must be a comprehensive city guide,\n\n\n rich in cultural insights and practical tips,\n\n\n tailored to enhance the travel experience.\n\n\n\n\n Trip Date: \n{\nrange\n}\n\n\n Traveling from: \n{\norigin\n}\n\n\n Traveler Interests: \n{\ninterests\n}\n\n\n \"\"\"\n\n\n ),\n\n\n agent\n=\nagent,\n\n\n expected_output\n=\n\"Comprehensive city guide including hidden gems, cultural hotspots, and practical travel tips\"\n,\n\n\n )\n\n\n\n\n\n\nclass\n TripCrew\n:\n\n\n def\n __init__\n(\nself\n, \norigin\n, \ncities\n, \ndate_range\n, \ninterests\n):\n\n\n self\n.cities \n=\n cities\n\n\n self\n.origin \n=\n origin\n\n\n self\n.interests \n=\n interests\n\n\n self\n.date_range \n=\n date_range\n\n\n\n\n def\n run\n(\nself\n):\n\n\n agents \n=\n TripAgents()\n\n\n tasks \n=\n TripTasks()\n\n\n\n\n city_selector_agent \n=\n agents.city_selection_agent()\n\n\n local_expert_agent \n=\n agents.local_expert()\n\n\n\n\n identify_task \n=\n tasks.identify_task(\n\n\n city_selector_agent,\n\n\n self\n.origin,\n\n\n self\n.cities,\n\n\n self\n.interests,\n\n\n self\n.date_range,\n\n\n )\n\n\n gather_task \n=\n tasks.gather_task(\n\n\n local_expert_agent, \nself\n.origin, \nself\n.interests, \nself\n.date_range\n\n\n )\n\n\n\n\n crew \n=\n Crew(\n\n\n agents\n=\n[city_selector_agent, local_expert_agent],\n\n\n tasks\n=\n[identify_task, gather_task],\n\n\n verbose\n=\nTrue\n,\n\n\n memory\n=\nTrue\n,\n\n\n knowledge\n=\n{\n\n\n \"sources\"\n: [string_source],\n\n\n \"metadata\"\n: {\n\"preference\"\n: \n\"personal\"\n},\n\n\n },\n\n\n )\n\n\n\n\n result \n=\n crew.kickoff()\n\n\n return\n result\n\n\n\n\n\n\ntrip_crew \n=\n TripCrew(\n\"California\"\n, \n\"Tokyo\"\n, \n\"Dec 12 - Dec 20\"\n, \n\"sports\"\n)\n\n\nresult \n=\n trip_crew.run()\n\n\n\n\nprint\n(result)\n\n\nRefer to \nMLflow Tracing Documentation\n for more configurations and use cases.\n4\nVisualize Activities of Agents\nNow traces for your crewAI agents are captured by MLflow.\nLet’s visit MLflow tracking server to view the traces and get insights into your Agents.\nOpen \n127.0.0.1:5000\n on your browser to visit MLflow tracking server.\nMLflow Tracing Dashboard\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMaxim Integration\nOpenLIT Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nMLflow Overview\nFeatures\nSetup Instructions\nObservability\nMLflow Integration\nCopy page\nQuickly start monitoring your Agents with MLflow.\n​\nMLflow Overview\n\n\nMLflow\n is an open-source platform to assist machine learning practitioners and teams in handling the complexities of the machine learning process.\n\n\nIt provides a tracing feature that enhances LLM observability in your Generative AI applications by capturing detailed information about the execution of your application’s services.\nTracing provides a way to record the inputs, outputs, and metadata associated with each intermediate step of a request, enabling you to easily pinpoint the source of bugs and unexpected behaviors.\n\n\n\n\n​\nFeatures\n\n\n\n\nTracing Dashboard\n: Monitor activities of your crewAI agents with detailed dashboards that include inputs, outputs and metadata of spans.\n\n\nAutomated Tracing\n: A fully automated integration with crewAI, which can be enabled by running \nmlflow.crewai.autolog()\n.\n\n\nManual Trace Instrumentation with minor efforts\n: Customize trace instrumentation through MLflow’s high-level fluent APIs such as decorators, function wrappers and context managers.\n\n\nOpenTelemetry Compatibility\n: MLflow Tracing supports exporting traces to an OpenTelemetry Collector, which can then be used to export traces to various backends such as Jaeger, Zipkin, and AWS X-Ray.\n\n\nPackage and Deploy Agents\n: Package and deploy your crewAI agents to an inference server with a variety of deployment targets.\n\n\nSecurely Host LLMs\n: Host multiple LLM from various providers in one unified endpoint through MFflow gateway.\n\n\nEvaluation\n: Evaluate your crewAI agents with a wide range of metrics using a convenient API \nmlflow.evaluate()\n.\n\n\n\n\n​\nSetup Instructions\n\n\n1\nInstall MLflow package\nCopy\nAsk AI\n# The crewAI integration is available in mlflow>=2.19.0\n\n\npip\n install\n mlflow\n\n\n2\nStart MFflow tracking server\nCopy\nAsk AI\n# This process is optional, but it is recommended to use MLflow tracking server for better visualization and broader features.\n\n\nmlflow\n server\n\n\n3\nInitialize MLflow in Your Application\nAdd the following two lines to your application code:\nCopy\nAsk AI\nimport\n mlflow\n\n\n\n\nmlflow.crewai.autolog()\n\n\n\n\n# Optional: Set a tracking URI and an experiment name if you have a tracking server\n\n\nmlflow.set_tracking_uri(\n\"http://localhost:5000\"\n)\n\n\nmlflow.set_experiment(\n\"CrewAI\"\n)\n\n\nExample Usage for tracing CrewAI Agents:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool, WebsiteSearchTool\n\n\n\n\nfrom\n textwrap \nimport\n dedent\n\n\n\n\ncontent \n=\n \"Users name is John. He is 30 years old and lives in San Francisco.\"\n\n\nstring_source \n=\n StringKnowledgeSource(\n\n\n content\n=\ncontent, \nmetadata\n=\n{\n\"preference\"\n: \n\"personal\"\n}\n\n\n)\n\n\n\n\nsearch_tool \n=\n WebsiteSearchTool()\n\n\n\n\n\n\nclass\n TripAgents\n:\n\n\n def\n city_selection_agent\n(\nself\n):\n\n\n return\n Agent(\n\n\n role\n=\n\"City Selection Expert\"\n,\n\n\n goal\n=\n\"Select the best city based on weather, season, and prices\"\n,\n\n\n backstory\n=\n\"An expert in analyzing travel data to pick ideal destinations\"\n,\n\n\n tools\n=\n[\n\n\n search_tool,\n\n\n ],\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n def\n local_expert\n(\nself\n):\n\n\n return\n Agent(\n\n\n role\n=\n\"Local Expert at this city\"\n,\n\n\n goal\n=\n\"Provide the BEST insights about the selected city\"\n,\n\n\n backstory\n=\n\"\"\"A knowledgeable local guide with extensive information\n\n\n about the city, it's attractions and customs\"\"\"\n,\n\n\n tools\n=\n[search_tool],\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n\n\nclass\n TripTasks\n:\n\n\n def\n identify_task\n(\nself\n, \nagent\n, \norigin\n, \ncities\n, \ninterests\n, \nrange\n):\n\n\n return\n Task(\n\n\n description\n=\ndedent(\n\n\n f\n\"\"\"\n\n\n Analyze and select the best city for the trip based\n\n\n on specific criteria such as weather patterns, seasonal\n\n\n events, and travel costs. This task involves comparing\n\n\n multiple cities, considering factors like current weather\n\n\n conditions, upcoming cultural or seasonal events, and\n\n\n overall travel expenses.\n\n\n Your final answer must be a detailed\n\n\n report on the chosen city, and everything you found out\n\n\n about it, including the actual flight costs, weather\n\n\n forecast and attractions.\n\n\n\n\n Traveling from: \n{\norigin\n}\n\n\n City Options: \n{\ncities\n}\n\n\n Trip Date: \n{\nrange\n}\n\n\n Traveler Interests: \n{\ninterests\n}\n\n\n \"\"\"\n\n\n ),\n\n\n agent\n=\nagent,\n\n\n expected_output\n=\n\"Detailed report on the chosen city including flight costs, weather forecast, and attractions\"\n,\n\n\n )\n\n\n\n\n def\n gather_task\n(\nself\n, \nagent\n, \norigin\n, \ninterests\n, \nrange\n):\n\n\n return\n Task(\n\n\n description\n=\ndedent(\n\n\n f\n\"\"\"\n\n\n As a local expert on this city you must compile an\n\n\n in-depth guide for someone traveling there and wanting\n\n\n to have THE BEST trip ever!\n\n\n Gather information about key attractions, local customs,\n\n\n special events, and daily activity recommendations.\n\n\n Find the best spots to go to, the kind of place only a\n\n\n local would know.\n\n\n This guide should provide a thorough overview of what\n\n\n the city has to offer, including hidden gems, cultural\n\n\n hotspots, must-visit landmarks, weather forecasts, and\n\n\n high level costs.\n\n\n The final answer must be a comprehensive city guide,\n\n\n rich in cultural insights and practical tips,\n\n\n tailored to enhance the travel experience.\n\n\n\n\n Trip Date: \n{\nrange\n}\n\n\n Traveling from: \n{\norigin\n}\n\n\n Traveler Interests: \n{\ninterests\n}\n\n\n \"\"\"\n\n\n ),\n\n\n agent\n=\nagent,\n\n\n expected_output\n=\n\"Comprehensive city guide including hidden gems, cultural hotspots, and practical travel tips\"\n,\n\n\n )\n\n\n\n\n\n\nclass\n TripCrew\n:\n\n\n def\n __init__\n(\nself\n, \norigin\n, \ncities\n, \ndate_range\n, \ninterests\n):\n\n\n self\n.cities \n=\n cities\n\n\n self\n.origin \n=\n origin\n\n\n self\n.interests \n=\n interests\n\n\n self\n.date_range \n=\n date_range\n\n\n\n\n def\n run\n(\nself\n):\n\n\n agents \n=\n TripAgents()\n\n\n tasks \n=\n TripTasks()\n\n\n\n\n city_selector_agent \n=\n agents.city_selection_agent()\n\n\n local_expert_agent \n=\n agents.local_expert()\n\n\n\n\n identify_task \n=\n tasks.identify_task(\n\n\n city_selector_agent,\n\n\n self\n.origin,\n\n\n self\n.cities,\n\n\n self\n.interests,\n\n\n self\n.date_range,\n\n\n )\n\n\n gather_task \n=\n tasks.gather_task(\n\n\n local_expert_agent, \nself\n.origin, \nself\n.interests, \nself\n.date_range\n\n\n )\n\n\n\n\n crew \n=\n Crew(\n\n\n agents\n=\n[city_selector_agent, local_expert_agent],\n\n\n tasks\n=\n[identify_task, gather_task],\n\n\n verbose\n=\nTrue\n,\n\n\n memory\n=\nTrue\n,\n\n\n knowledge\n=\n{\n\n\n \"sources\"\n: [string_source],\n\n\n \"metadata\"\n: {\n\"preference\"\n: \n\"personal\"\n},\n\n\n },\n\n\n )\n\n\n\n\n result \n=\n crew.kickoff()\n\n\n return\n result\n\n\n\n\n\n\ntrip_crew \n=\n TripCrew(\n\"California\"\n, \n\"Tokyo\"\n, \n\"Dec 12 - Dec 20\"\n, \n\"sports\"\n)\n\n\nresult \n=\n trip_crew.run()\n\n\n\n\nprint\n(result)\n\n\nRefer to \nMLflow Tracing Documentation\n for more configurations and use cases.\n4\nVisualize Activities of Agents\nNow traces for your crewAI agents are captured by MLflow.\nLet’s visit MLflow tracking server to view the traces and get insights into your Agents.\nOpen \n127.0.0.1:5000\n on your browser to visit MLflow tracking server.\nMLflow Tracing Dashboard\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMaxim Integration\nOpenLIT Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nMLflow Overview\nFeatures\nSetup Instructions" }, { "source": "https://docs.crewai.com/en/observability/arize-phoenix", "title": "Arize Phoenix - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nArize Phoenix\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nArize Phoenix\nCopy page\nArize Phoenix integration for CrewAI with OpenTelemetry and OpenInference\n​\nArize Phoenix Integration\n\n\nThis guide demonstrates how to integrate \nArize Phoenix\n with \nCrewAI\n using OpenTelemetry via the \nOpenInference\n SDK. By the end of this guide, you will be able to trace your CrewAI agents and easily debug your agents.\n\n\n\n\nWhat is Arize Phoenix?\n \nArize Phoenix\n is an LLM observability platform that provides tracing and evaluation for AI applications.\n\n\n\n\n\n\n​\nGet Started\n\n\nWe’ll walk through a simple example of using CrewAI and integrating it with Arize Phoenix via OpenTelemetry using OpenInference.\n\n\nYou can also access this guide on \nGoogle Colab\n.\n\n\n​\nStep 1: Install Dependencies\n\n\nCopy\nAsk AI\npip\n install\n openinference-instrumentation-crewai\n crewai\n crewai-tools\n arize-phoenix-otel\n\n\n\n\n​\nStep 2: Set Up Environment Variables\n\n\nSetup Phoenix Cloud API keys and configure OpenTelemetry to send traces to Phoenix. Phoenix Cloud is a hosted version of Arize Phoenix, but it is not required to use this integration.\n\n\nYou can get your free Serper API key \nhere\n.\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n getpass \nimport\n getpass\n\n\n\n\n# Get your Phoenix Cloud credentials\n\n\nPHOENIX_API_KEY\n =\n getpass(\n\"🔑 Enter your Phoenix Cloud API Key: \"\n)\n\n\n\n\n# Get API keys for services\n\n\nOPENAI_API_KEY\n =\n getpass(\n\"🔑 Enter your OpenAI API key: \"\n)\n\n\nSERPER_API_KEY\n =\n getpass(\n\"🔑 Enter your Serper API key: \"\n)\n\n\n\n\n# Set environment variables\n\n\nos.environ[\n\"PHOENIX_CLIENT_HEADERS\"\n] \n=\n f\n\"api_key=\n{\nPHOENIX_API_KEY\n}\n\"\n\n\nos.environ[\n\"PHOENIX_COLLECTOR_ENDPOINT\"\n] \n=\n \"https://app.phoenix.arize.com\"\n # Phoenix Cloud, change this to your own endpoint if you are using a self-hosted instance\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n OPENAI_API_KEY\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n SERPER_API_KEY\n\n\n\n\n​\nStep 3: Initialize OpenTelemetry with Phoenix\n\n\nInitialize the OpenInference OpenTelemetry instrumentation SDK to start capturing traces and send them to Phoenix.\n\n\nCopy\nAsk AI\nfrom\n phoenix.otel \nimport\n register\n\n\n\n\ntracer_provider \n=\n register(\n\n\n project_name\n=\n\"crewai-tracing-demo\"\n,\n\n\n auto_instrument\n=\nTrue\n,\n\n\n)\n\n\n\n\n​\nStep 4: Create a CrewAI Application\n\n\nWe’ll create a CrewAI application where two agents collaborate to research and write a blog post about AI advancements.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n openinference.instrumentation.crewai \nimport\n CrewAIInstrumentor\n\n\nfrom\n phoenix.otel \nimport\n register\n\n\n\n\n# setup monitoring for your crew\n\n\ntracer_provider \n=\n register(\n\n\n endpoint\n=\n\"http://localhost:6006/v1/traces\"\n)\n\n\nCrewAIInstrumentor().instrument(\nskip_dep_check\n=\nTrue\n, \ntracer_provider\n=\ntracer_provider)\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\n# Define your agents with roles and goals\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Analyst\"\n,\n\n\n goal\n=\n\"Uncover cutting-edge developments in AI and data science\"\n,\n\n\n backstory\n=\n\"\"\"You work at a leading tech think tank.\n\n\n Your expertise lies in identifying emerging trends.\n\n\n You have a knack for dissecting complex data and presenting actionable insights.\"\"\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n # You can pass an optional llm attribute specifying what model you wanna use.\n\n\n # llm=ChatOpenAI(model_name=\"gpt-3.5\", temperature=0.7),\n\n\n tools\n=\n[search_tool],\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Tech Content Strategist\"\n,\n\n\n goal\n=\n\"Craft compelling content on tech advancements\"\n,\n\n\n backstory\n=\n\"\"\"You are a renowned Content Strategist, known for your insightful and engaging articles.\n\n\n You transform complex concepts into compelling narratives.\"\"\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Create tasks for your agents\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"\"\"Conduct a comprehensive analysis of the latest advancements in AI in 2024.\n\n\n Identify key trends, breakthrough technologies, and potential industry impacts.\"\"\"\n,\n\n\n expected_output\n=\n\"Full analysis report in bullet points\"\n,\n\n\n agent\n=\nresearcher,\n\n\n)\n\n\n\n\ntask2 \n=\n Task(\n\n\n description\n=\n\"\"\"Using the insights provided, develop an engaging blog\n\n\n post that highlights the most significant AI advancements.\n\n\n Your post should be informative yet accessible, catering to a tech-savvy audience.\n\n\n Make it sound cool, avoid complex words so it doesn't sound like AI.\"\"\"\n,\n\n\n expected_output\n=\n\"Full blog post of at least 4 paragraphs\"\n,\n\n\n agent\n=\nwriter,\n\n\n)\n\n\n\n\n# Instantiate your crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer], \ntasks\n=\n[task1, task2], \nverbose\n=\n1\n, \nprocess\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Get your crew to work!\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(\n\"######################\"\n)\n\n\nprint\n(result)\n\n\n\n\n​\nStep 5: View Traces in Phoenix\n\n\nAfter running the agent, you can view the traces generated by your CrewAI application in Phoenix. You should see detailed steps of the agent interactions and LLM calls, which can help you debug and optimize your AI agents.\n\n\nLog into your Phoenix Cloud account and navigate to the project you specified in the \nproject_name\n parameter. You’ll see a timeline view of your trace with all the agent interactions, tool usages, and LLM calls.\n\n\n\n\n​\nVersion Compatibility Information\n\n\n\n\nPython 3.8+\n\n\nCrewAI >= 0.86.0\n\n\nArize Phoenix >= 7.0.1\n\n\nOpenTelemetry SDK >= 1.31.0\n\n\n\n\n​\nReferences\n\n\n\n\nPhoenix Documentation\n - Overview of the Phoenix platform.\n\n\nCrewAI Documentation\n - Overview of the CrewAI framework.\n\n\nOpenTelemetry Docs\n - OpenTelemetry guide\n\n\nOpenInference GitHub\n - Source code for OpenInference SDK.\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nAgentOps Integration\nLangfuse Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nArize Phoenix Integration\nGet Started\nStep 1: Install Dependencies\nStep 2: Set Up Environment Variables\nStep 3: Initialize OpenTelemetry with Phoenix\nStep 4: Create a CrewAI Application\nStep 5: View Traces in Phoenix\nVersion Compatibility Information\nReferences\nObservability\nArize Phoenix\nCopy page\nArize Phoenix integration for CrewAI with OpenTelemetry and OpenInference\n​\nArize Phoenix Integration\n\n\nThis guide demonstrates how to integrate \nArize Phoenix\n with \nCrewAI\n using OpenTelemetry via the \nOpenInference\n SDK. By the end of this guide, you will be able to trace your CrewAI agents and easily debug your agents.\n\n\n\n\nWhat is Arize Phoenix?\n \nArize Phoenix\n is an LLM observability platform that provides tracing and evaluation for AI applications.\n\n\n\n\n\n\n​\nGet Started\n\n\nWe’ll walk through a simple example of using CrewAI and integrating it with Arize Phoenix via OpenTelemetry using OpenInference.\n\n\nYou can also access this guide on \nGoogle Colab\n.\n\n\n​\nStep 1: Install Dependencies\n\n\nCopy\nAsk AI\npip\n install\n openinference-instrumentation-crewai\n crewai\n crewai-tools\n arize-phoenix-otel\n\n\n\n\n​\nStep 2: Set Up Environment Variables\n\n\nSetup Phoenix Cloud API keys and configure OpenTelemetry to send traces to Phoenix. Phoenix Cloud is a hosted version of Arize Phoenix, but it is not required to use this integration.\n\n\nYou can get your free Serper API key \nhere\n.\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n getpass \nimport\n getpass\n\n\n\n\n# Get your Phoenix Cloud credentials\n\n\nPHOENIX_API_KEY\n =\n getpass(\n\"🔑 Enter your Phoenix Cloud API Key: \"\n)\n\n\n\n\n# Get API keys for services\n\n\nOPENAI_API_KEY\n =\n getpass(\n\"🔑 Enter your OpenAI API key: \"\n)\n\n\nSERPER_API_KEY\n =\n getpass(\n\"🔑 Enter your Serper API key: \"\n)\n\n\n\n\n# Set environment variables\n\n\nos.environ[\n\"PHOENIX_CLIENT_HEADERS\"\n] \n=\n f\n\"api_key=\n{\nPHOENIX_API_KEY\n}\n\"\n\n\nos.environ[\n\"PHOENIX_COLLECTOR_ENDPOINT\"\n] \n=\n \"https://app.phoenix.arize.com\"\n # Phoenix Cloud, change this to your own endpoint if you are using a self-hosted instance\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n OPENAI_API_KEY\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n SERPER_API_KEY\n\n\n\n\n​\nStep 3: Initialize OpenTelemetry with Phoenix\n\n\nInitialize the OpenInference OpenTelemetry instrumentation SDK to start capturing traces and send them to Phoenix.\n\n\nCopy\nAsk AI\nfrom\n phoenix.otel \nimport\n register\n\n\n\n\ntracer_provider \n=\n register(\n\n\n project_name\n=\n\"crewai-tracing-demo\"\n,\n\n\n auto_instrument\n=\nTrue\n,\n\n\n)\n\n\n\n\n​\nStep 4: Create a CrewAI Application\n\n\nWe’ll create a CrewAI application where two agents collaborate to research and write a blog post about AI advancements.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n openinference.instrumentation.crewai \nimport\n CrewAIInstrumentor\n\n\nfrom\n phoenix.otel \nimport\n register\n\n\n\n\n# setup monitoring for your crew\n\n\ntracer_provider \n=\n register(\n\n\n endpoint\n=\n\"http://localhost:6006/v1/traces\"\n)\n\n\nCrewAIInstrumentor().instrument(\nskip_dep_check\n=\nTrue\n, \ntracer_provider\n=\ntracer_provider)\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\n# Define your agents with roles and goals\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Senior Research Analyst\"\n,\n\n\n goal\n=\n\"Uncover cutting-edge developments in AI and data science\"\n,\n\n\n backstory\n=\n\"\"\"You work at a leading tech think tank.\n\n\n Your expertise lies in identifying emerging trends.\n\n\n You have a knack for dissecting complex data and presenting actionable insights.\"\"\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n # You can pass an optional llm attribute specifying what model you wanna use.\n\n\n # llm=ChatOpenAI(model_name=\"gpt-3.5\", temperature=0.7),\n\n\n tools\n=\n[search_tool],\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Tech Content Strategist\"\n,\n\n\n goal\n=\n\"Craft compelling content on tech advancements\"\n,\n\n\n backstory\n=\n\"\"\"You are a renowned Content Strategist, known for your insightful and engaging articles.\n\n\n You transform complex concepts into compelling narratives.\"\"\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Create tasks for your agents\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"\"\"Conduct a comprehensive analysis of the latest advancements in AI in 2024.\n\n\n Identify key trends, breakthrough technologies, and potential industry impacts.\"\"\"\n,\n\n\n expected_output\n=\n\"Full analysis report in bullet points\"\n,\n\n\n agent\n=\nresearcher,\n\n\n)\n\n\n\n\ntask2 \n=\n Task(\n\n\n description\n=\n\"\"\"Using the insights provided, develop an engaging blog\n\n\n post that highlights the most significant AI advancements.\n\n\n Your post should be informative yet accessible, catering to a tech-savvy audience.\n\n\n Make it sound cool, avoid complex words so it doesn't sound like AI.\"\"\"\n,\n\n\n expected_output\n=\n\"Full blog post of at least 4 paragraphs\"\n,\n\n\n agent\n=\nwriter,\n\n\n)\n\n\n\n\n# Instantiate your crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer], \ntasks\n=\n[task1, task2], \nverbose\n=\n1\n, \nprocess\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Get your crew to work!\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(\n\"######################\"\n)\n\n\nprint\n(result)\n\n\n\n\n​\nStep 5: View Traces in Phoenix\n\n\nAfter running the agent, you can view the traces generated by your CrewAI application in Phoenix. You should see detailed steps of the agent interactions and LLM calls, which can help you debug and optimize your AI agents.\n\n\nLog into your Phoenix Cloud account and navigate to the project you specified in the \nproject_name\n parameter. You’ll see a timeline view of your trace with all the agent interactions, tool usages, and LLM calls.\n\n\n\n\n​\nVersion Compatibility Information\n\n\n\n\nPython 3.8+\n\n\nCrewAI >= 0.86.0\n\n\nArize Phoenix >= 7.0.1\n\n\nOpenTelemetry SDK >= 1.31.0\n\n\n\n\n​\nReferences\n\n\n\n\nPhoenix Documentation\n - Overview of the Phoenix platform.\n\n\nCrewAI Documentation\n - Overview of the CrewAI framework.\n\n\nOpenTelemetry Docs\n - OpenTelemetry guide\n\n\nOpenInference GitHub\n - Source code for OpenInference SDK.\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nAgentOps Integration\nLangfuse Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nArize Phoenix Integration\nGet Started\nStep 1: Install Dependencies\nStep 2: Set Up Environment Variables\nStep 3: Initialize OpenTelemetry with Phoenix\nStep 4: Create a CrewAI Application\nStep 5: View Traces in Phoenix\nVersion Compatibility Information\nReferences" }, { "source": "https://docs.crewai.com/en/learn/create-custom-tools", "title": "Create Custom Tools - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nCreate Custom Tools\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nCreate Custom Tools\nCopy page\nComprehensive guide on crafting, using, and managing custom tools within the CrewAI framework, including new functionalities and error handling.\n​\nCreating and Utilizing Tools in CrewAI\n\n\nThis guide provides detailed instructions on creating custom tools for the CrewAI framework and how to efficiently manage and utilize these tools,\nincorporating the latest functionalities such as tool delegation, error handling, and dynamic tool calling. It also highlights the importance of collaboration tools,\nenabling agents to perform a wide range of actions.\n\n\n​\nSubclassing \nBaseTool\n\n\nTo create a personalized tool, inherit from \nBaseTool\n and define the necessary attributes, including the \nargs_schema\n for input validation, and the \n_run\n method.\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Type\n\n\nfrom\n crewai.tools \nimport\n BaseTool\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nclass\n MyToolInput\n(\nBaseModel\n):\n\n\n \"\"\"Input schema for MyCustomTool.\"\"\"\n\n\n argument: \nstr\n =\n Field(\n...\n, \ndescription\n=\n\"Description of the argument.\"\n)\n\n\n\n\nclass\n MyCustomTool\n(\nBaseTool\n):\n\n\n name: \nstr\n =\n \"Name of my tool\"\n\n\n description: \nstr\n =\n \"What this tool does. It's vital for effective utilization.\"\n\n\n args_schema: Type[BaseModel] \n=\n MyToolInput\n\n\n\n\n def\n _run\n(\nself\n, \nargument\n: \nstr\n) -> \nstr\n:\n\n\n # Your tool's logic here\n\n\n return\n \"Tool's result\"\n\n\n\n\n​\nUsing the \ntool\n Decorator\n\n\nAlternatively, you can use the tool decorator \n@tool\n. This approach allows you to define the tool’s attributes and functionality directly within a function,\noffering a concise and efficient way to create specialized tools tailored to your needs.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n\n\n@tool\n(\n\"Tool Name\"\n)\n\n\ndef\n my_simple_tool\n(\nquestion\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Tool description for clarity.\"\"\"\n\n\n # Tool logic here\n\n\n return\n \"Tool output\"\n\n\n\n\n​\nDefining a Cache Function for the Tool\n\n\nTo optimize tool performance with caching, define custom caching strategies using the \ncache_function\n attribute.\n\n\nCode\nCopy\nAsk AI\n@tool\n(\n\"Tool with Caching\"\n)\n\n\ndef\n cached_tool\n(\nargument\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Tool functionality description.\"\"\"\n\n\n return\n \"Cacheable result\"\n\n\n\n\ndef\n my_cache_strategy\n(\narguments\n: \ndict\n, \nresult\n: \nstr\n) -> \nbool\n:\n\n\n # Define custom caching logic\n\n\n return\n True\n if\n some_condition \nelse\n False\n\n\n\n\ncached_tool.cache_function \n=\n my_cache_strategy\n\n\n\n\nBy adhering to these guidelines and incorporating new functionalities and collaboration tools into your tool creation and management processes,\nyou can leverage the full capabilities of the CrewAI framework, enhancing both the development experience and the efficiency of your AI agents.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCoding Agents\nCustom LLM Implementation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nCreating and Utilizing Tools in CrewAI\nSubclassing BaseTool\nUsing the tool Decorator\nDefining a Cache Function for the Tool\nLearn\nCreate Custom Tools\nCopy page\nComprehensive guide on crafting, using, and managing custom tools within the CrewAI framework, including new functionalities and error handling.\n​\nCreating and Utilizing Tools in CrewAI\n\n\nThis guide provides detailed instructions on creating custom tools for the CrewAI framework and how to efficiently manage and utilize these tools,\nincorporating the latest functionalities such as tool delegation, error handling, and dynamic tool calling. It also highlights the importance of collaboration tools,\nenabling agents to perform a wide range of actions.\n\n\n​\nSubclassing \nBaseTool\n\n\nTo create a personalized tool, inherit from \nBaseTool\n and define the necessary attributes, including the \nargs_schema\n for input validation, and the \n_run\n method.\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Type\n\n\nfrom\n crewai.tools \nimport\n BaseTool\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nclass\n MyToolInput\n(\nBaseModel\n):\n\n\n \"\"\"Input schema for MyCustomTool.\"\"\"\n\n\n argument: \nstr\n =\n Field(\n...\n, \ndescription\n=\n\"Description of the argument.\"\n)\n\n\n\n\nclass\n MyCustomTool\n(\nBaseTool\n):\n\n\n name: \nstr\n =\n \"Name of my tool\"\n\n\n description: \nstr\n =\n \"What this tool does. It's vital for effective utilization.\"\n\n\n args_schema: Type[BaseModel] \n=\n MyToolInput\n\n\n\n\n def\n _run\n(\nself\n, \nargument\n: \nstr\n) -> \nstr\n:\n\n\n # Your tool's logic here\n\n\n return\n \"Tool's result\"\n\n\n\n\n​\nUsing the \ntool\n Decorator\n\n\nAlternatively, you can use the tool decorator \n@tool\n. This approach allows you to define the tool’s attributes and functionality directly within a function,\noffering a concise and efficient way to create specialized tools tailored to your needs.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n\n\n@tool\n(\n\"Tool Name\"\n)\n\n\ndef\n my_simple_tool\n(\nquestion\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Tool description for clarity.\"\"\"\n\n\n # Tool logic here\n\n\n return\n \"Tool output\"\n\n\n\n\n​\nDefining a Cache Function for the Tool\n\n\nTo optimize tool performance with caching, define custom caching strategies using the \ncache_function\n attribute.\n\n\nCode\nCopy\nAsk AI\n@tool\n(\n\"Tool with Caching\"\n)\n\n\ndef\n cached_tool\n(\nargument\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Tool functionality description.\"\"\"\n\n\n return\n \"Cacheable result\"\n\n\n\n\ndef\n my_cache_strategy\n(\narguments\n: \ndict\n, \nresult\n: \nstr\n) -> \nbool\n:\n\n\n # Define custom caching logic\n\n\n return\n True\n if\n some_condition \nelse\n False\n\n\n\n\ncached_tool.cache_function \n=\n my_cache_strategy\n\n\n\n\nBy adhering to these guidelines and incorporating new functionalities and collaboration tools into your tool creation and management processes,\nyou can leverage the full capabilities of the CrewAI framework, enhancing both the development experience and the efficiency of your AI agents.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCoding Agents\nCustom LLM Implementation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nCreating and Utilizing Tools in CrewAI\nSubclassing BaseTool\nUsing the tool Decorator\nDefining a Cache Function for the Tool" }, { "source": "https://docs.crewai.com/en/concepts/event-listener", "title": "Event Listeners - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nEvent Listeners\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nEvent Listeners\nCopy page\nTap into CrewAI events to build custom integrations and monitoring\n​\nOverview\n\n\nCrewAI provides a powerful event system that allows you to listen for and react to various events that occur during the execution of your Crew. This feature enables you to build custom integrations, monitoring solutions, logging systems, or any other functionality that needs to be triggered based on CrewAI’s internal events.\n\n\n​\nHow It Works\n\n\nCrewAI uses an event bus architecture to emit events throughout the execution lifecycle. The event system is built on the following components:\n\n\n\n\nCrewAIEventsBus\n: A singleton event bus that manages event registration and emission\n\n\nBaseEvent\n: Base class for all events in the system\n\n\nBaseEventListener\n: Abstract base class for creating custom event listeners\n\n\n\n\nWhen specific actions occur in CrewAI (like a Crew starting execution, an Agent completing a task, or a tool being used), the system emits corresponding events. You can register handlers for these events to execute custom code when they occur.\n\n\nCrewAI Enterprise provides a built-in Prompt Tracing feature that leverages the event system to track, store, and visualize all prompts, completions, and associated metadata. This provides powerful debugging capabilities and transparency into your agent operations.\nWith Prompt Tracing you can:\n\n\nView the complete history of all prompts sent to your LLM\n\n\nTrack token usage and costs\n\n\nDebug agent reasoning failures\n\n\nShare prompt sequences with your team\n\n\nCompare different prompt strategies\n\n\nExport traces for compliance and auditing\n\n\n\n\n​\nCreating a Custom Event Listener\n\n\nTo create a custom event listener, you need to:\n\n\n\n\nCreate a class that inherits from \nBaseEventListener\n\n\nImplement the \nsetup_listeners\n method\n\n\nRegister handlers for the events you’re interested in\n\n\nCreate an instance of your listener in the appropriate file\n\n\n\n\nHere’s a simple example of a custom event listener class:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n (\n\n\n CrewKickoffStartedEvent,\n\n\n CrewKickoffCompletedEvent,\n\n\n AgentExecutionCompletedEvent,\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n):\n\n\n super\n().\n__init__\n()\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(CrewKickoffStartedEvent)\n\n\n def\n on_crew_started\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Crew '\n{\nevent.crew_name\n}\n' has started execution!\"\n)\n\n\n\n\n @crewai_event_bus.on\n(CrewKickoffCompletedEvent)\n\n\n def\n on_crew_completed\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Crew '\n{\nevent.crew_name\n}\n' has completed execution!\"\n)\n\n\n print\n(\nf\n\"Output: \n{\nevent.output\n}\n\"\n)\n\n\n\n\n @crewai_event_bus.on\n(AgentExecutionCompletedEvent)\n\n\n def\n on_agent_execution_completed\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Agent '\n{\nevent.agent.role\n}\n' completed task\"\n)\n\n\n print\n(\nf\n\"Output: \n{\nevent.output\n}\n\"\n)\n\n\n\n\n​\nProperly Registering Your Listener\n\n\nSimply defining your listener class isn’t enough. You need to create an instance of it and ensure it’s imported in your application. This ensures that:\n\n\n\n\nThe event handlers are registered with the event bus\n\n\nThe listener instance remains in memory (not garbage collected)\n\n\nThe listener is active when events are emitted\n\n\n\n\n​\nOption 1: Import and Instantiate in Your Crew or Flow Implementation\n\n\nThe most important thing is to create an instance of your listener in the file where your Crew or Flow is defined and executed:\n\n\n​\nFor Crew-based Applications\n\n\nCreate and import your listener at the top of your Crew implementation file:\n\n\nCopy\nAsk AI\n# In your crew.py file\n\n\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\nfrom\n my_listeners \nimport\n MyCustomListener\n\n\n\n\n# Create an instance of your listener\n\n\nmy_listener \n=\n MyCustomListener()\n\n\n\n\nclass\n MyCustomCrew\n:\n\n\n # Your crew implementation...\n\n\n\n\n def\n crew\n(\nself\n):\n\n\n return\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n # ...\n\n\n )\n\n\n\n\n​\nFor Flow-based Applications\n\n\nCreate and import your listener at the top of your Flow implementation file:\n\n\nCopy\nAsk AI\n# In your main.py or flow.py file\n\n\nfrom\n crewai.flow \nimport\n Flow, listen, start\n\n\nfrom\n my_listeners \nimport\n MyCustomListener\n\n\n\n\n# Create an instance of your listener\n\n\nmy_listener \n=\n MyCustomListener()\n\n\n\n\nclass\n MyCustomFlow\n(\nFlow\n):\n\n\n # Your flow implementation...\n\n\n\n\n @start\n()\n\n\n def\n first_step\n(\nself\n):\n\n\n # ...\n\n\n\n\nThis ensures that your listener is loaded and active when your Crew or Flow is executed.\n\n\n​\nOption 2: Create a Package for Your Listeners\n\n\nFor a more structured approach, especially if you have multiple listeners:\n\n\n\n\nCreate a package for your listeners:\n\n\n\n\nCopy\nAsk AI\nmy_project/\n\n\n ├── listeners/\n\n\n │ ├── __init__.py\n\n\n │ ├── my_custom_listener.py\n\n\n │ └── another_listener.py\n\n\n\n\n\n\nIn \nmy_custom_listener.py\n, define your listener class and create an instance:\n\n\n\n\nCopy\nAsk AI\n# my_custom_listener.py\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n# ... import events ...\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n # ... implementation ...\n\n\n\n\n# Create an instance of your listener\n\n\nmy_custom_listener \n=\n MyCustomListener()\n\n\n\n\n\n\nIn \n__init__.py\n, import the listener instances to ensure they’re loaded:\n\n\n\n\nCopy\nAsk AI\n# __init__.py\n\n\nfrom\n .my_custom_listener \nimport\n my_custom_listener\n\n\nfrom\n .another_listener \nimport\n another_listener\n\n\n\n\n# Optionally export them if you need to access them elsewhere\n\n\n__all__\n =\n [\n'my_custom_listener'\n, \n'another_listener'\n]\n\n\n\n\n\n\nImport your listeners package in your Crew or Flow file:\n\n\n\n\nCopy\nAsk AI\n# In your crew.py or flow.py file\n\n\nimport\n my_project.listeners \n# This loads all your listeners\n\n\n\n\nclass\n MyCustomCrew\n:\n\n\n # Your crew implementation...\n\n\n\n\nThis is exactly how CrewAI’s built-in \nagentops_listener\n is registered. In the CrewAI codebase, you’ll find:\n\n\nCopy\nAsk AI\n# src/crewai/utilities/events/third_party/__init__.py\n\n\nfrom\n .agentops_listener \nimport\n agentops_listener\n\n\n\n\nThis ensures the \nagentops_listener\n is loaded when the \ncrewai.utilities.events\n package is imported.\n\n\n​\nAvailable Event Types\n\n\nCrewAI provides a wide range of events that you can listen for:\n\n\n​\nCrew Events\n\n\n\n\nCrewKickoffStartedEvent\n: Emitted when a Crew starts execution\n\n\nCrewKickoffCompletedEvent\n: Emitted when a Crew completes execution\n\n\nCrewKickoffFailedEvent\n: Emitted when a Crew fails to complete execution\n\n\nCrewTestStartedEvent\n: Emitted when a Crew starts testing\n\n\nCrewTestCompletedEvent\n: Emitted when a Crew completes testing\n\n\nCrewTestFailedEvent\n: Emitted when a Crew fails to complete testing\n\n\nCrewTrainStartedEvent\n: Emitted when a Crew starts training\n\n\nCrewTrainCompletedEvent\n: Emitted when a Crew completes training\n\n\nCrewTrainFailedEvent\n: Emitted when a Crew fails to complete training\n\n\n\n\n​\nAgent Events\n\n\n\n\nAgentExecutionStartedEvent\n: Emitted when an Agent starts executing a task\n\n\nAgentExecutionCompletedEvent\n: Emitted when an Agent completes executing a task\n\n\nAgentExecutionErrorEvent\n: Emitted when an Agent encounters an error during execution\n\n\n\n\n​\nTask Events\n\n\n\n\nTaskStartedEvent\n: Emitted when a Task starts execution\n\n\nTaskCompletedEvent\n: Emitted when a Task completes execution\n\n\nTaskFailedEvent\n: Emitted when a Task fails to complete execution\n\n\nTaskEvaluationEvent\n: Emitted when a Task is evaluated\n\n\n\n\n​\nTool Usage Events\n\n\n\n\nToolUsageStartedEvent\n: Emitted when a tool execution is started\n\n\nToolUsageFinishedEvent\n: Emitted when a tool execution is completed\n\n\nToolUsageErrorEvent\n: Emitted when a tool execution encounters an error\n\n\nToolValidateInputErrorEvent\n: Emitted when a tool input validation encounters an error\n\n\nToolExecutionErrorEvent\n: Emitted when a tool execution encounters an error\n\n\nToolSelectionErrorEvent\n: Emitted when there’s an error selecting a tool\n\n\n\n\n​\nKnowledge Events\n\n\n\n\nKnowledgeRetrievalStartedEvent\n: Emitted when a knowledge retrieval is started\n\n\nKnowledgeRetrievalCompletedEvent\n: Emitted when a knowledge retrieval is completed\n\n\nKnowledgeQueryStartedEvent\n: Emitted when a knowledge query is started\n\n\nKnowledgeQueryCompletedEvent\n: Emitted when a knowledge query is completed\n\n\nKnowledgeQueryFailedEvent\n: Emitted when a knowledge query fails\n\n\nKnowledgeSearchQueryFailedEvent\n: Emitted when a knowledge search query fails\n\n\n\n\n​\nLLM Guardrail Events\n\n\n\n\nLLMGuardrailStartedEvent\n: Emitted when a guardrail validation starts. Contains details about the guardrail being applied and retry count.\n\n\nLLMGuardrailCompletedEvent\n: Emitted when a guardrail validation completes. Contains details about validation success/failure, results, and error messages if any.\n\n\n\n\n​\nFlow Events\n\n\n\n\nFlowCreatedEvent\n: Emitted when a Flow is created\n\n\nFlowStartedEvent\n: Emitted when a Flow starts execution\n\n\nFlowFinishedEvent\n: Emitted when a Flow completes execution\n\n\nFlowPlotEvent\n: Emitted when a Flow is plotted\n\n\nMethodExecutionStartedEvent\n: Emitted when a Flow method starts execution\n\n\nMethodExecutionFinishedEvent\n: Emitted when a Flow method completes execution\n\n\nMethodExecutionFailedEvent\n: Emitted when a Flow method fails to complete execution\n\n\n\n\n​\nLLM Events\n\n\n\n\nLLMCallStartedEvent\n: Emitted when an LLM call starts\n\n\nLLMCallCompletedEvent\n: Emitted when an LLM call completes\n\n\nLLMCallFailedEvent\n: Emitted when an LLM call fails\n\n\nLLMStreamChunkEvent\n: Emitted for each chunk received during streaming LLM responses\n\n\n\n\n​\nMemory Events\n\n\n\n\nMemoryQueryStartedEvent\n: Emitted when a memory query is started. Contains the query, limit, and optional score threshold.\n\n\nMemoryQueryCompletedEvent\n: Emitted when a memory query is completed successfully. Contains the query, results, limit, score threshold, and query execution time.\n\n\nMemoryQueryFailedEvent\n: Emitted when a memory query fails. Contains the query, limit, score threshold, and error message.\n\n\nMemorySaveStartedEvent\n: Emitted when a memory save operation is started. Contains the value to be saved, metadata, and optional agent role.\n\n\nMemorySaveCompletedEvent\n: Emitted when a memory save operation is completed successfully. Contains the saved value, metadata, agent role, and save execution time.\n\n\nMemorySaveFailedEvent\n: Emitted when a memory save operation fails. Contains the value, metadata, agent role, and error message.\n\n\nMemoryRetrievalStartedEvent\n: Emitted when memory retrieval for a task prompt starts. Contains the optional task ID.\n\n\nMemoryRetrievalCompletedEvent\n: Emitted when memory retrieval for a task prompt completes successfully. Contains the task ID, memory content, and retrieval execution time.\n\n\n\n\n​\nEvent Handler Structure\n\n\nEach event handler receives two parameters:\n\n\n\n\nsource\n: The object that emitted the event\n\n\nevent\n: The event instance, containing event-specific data\n\n\n\n\nThe structure of the event object depends on the event type, but all events inherit from \nBaseEvent\n and include:\n\n\n\n\ntimestamp\n: The time when the event was emitted\n\n\ntype\n: A string identifier for the event type\n\n\n\n\nAdditional fields vary by event type. For example, \nCrewKickoffCompletedEvent\n includes \ncrew_name\n and \noutput\n fields.\n\n\n​\nReal-World Example: Integration with AgentOps\n\n\nCrewAI includes an example of a third-party integration with \nAgentOps\n, a monitoring and observability platform for AI agents. Here’s how it’s implemented:\n\n\nCopy\nAsk AI\nfrom\n typing \nimport\n Optional\n\n\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n CrewKickoffCompletedEvent,\n\n\n ToolUsageErrorEvent,\n\n\n ToolUsageStartedEvent,\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events.crew_events \nimport\n CrewKickoffStartedEvent\n\n\nfrom\n crewai.utilities.events.task_events \nimport\n TaskEvaluationEvent\n\n\n\n\ntry\n:\n\n\n import\n agentops\n\n\n AGENTOPS_INSTALLED\n =\n True\n\n\nexcept\n ImportError\n:\n\n\n AGENTOPS_INSTALLED\n =\n False\n\n\n\n\nclass\n AgentOpsListener\n(\nBaseEventListener\n):\n\n\n tool_event: Optional[\n\"agentops.ToolEvent\"\n] \n=\n None\n\n\n session: Optional[\n\"agentops.Session\"\n] \n=\n None\n\n\n\n\n def\n __init__\n(\nself\n):\n\n\n super\n().\n__init__\n()\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n if\n not\n AGENTOPS_INSTALLED\n:\n\n\n return\n\n\n\n\n @crewai_event_bus.on\n(CrewKickoffStartedEvent)\n\n\n def\n on_crew_kickoff_started\n(\nsource\n, \nevent\n: CrewKickoffStartedEvent):\n\n\n self\n.session \n=\n agentops.init()\n\n\n for\n agent \nin\n source.agents:\n\n\n if\n self\n.session:\n\n\n self\n.session.create_agent(\n\n\n name\n=\nagent.role,\n\n\n agent_id\n=\nstr\n(agent.id),\n\n\n )\n\n\n\n\n @crewai_event_bus.on\n(CrewKickoffCompletedEvent)\n\n\n def\n on_crew_kickoff_completed\n(\nsource\n, \nevent\n: CrewKickoffCompletedEvent):\n\n\n if\n self\n.session:\n\n\n self\n.session.end_session(\n\n\n end_state\n=\n\"Success\"\n,\n\n\n end_state_reason\n=\n\"Finished Execution\"\n,\n\n\n )\n\n\n\n\n @crewai_event_bus.on\n(ToolUsageStartedEvent)\n\n\n def\n on_tool_usage_started\n(\nsource\n, \nevent\n: ToolUsageStartedEvent):\n\n\n self\n.tool_event \n=\n agentops.ToolEvent(\nname\n=\nevent.tool_name)\n\n\n if\n self\n.session:\n\n\n self\n.session.record(\nself\n.tool_event)\n\n\n\n\n @crewai_event_bus.on\n(ToolUsageErrorEvent)\n\n\n def\n on_tool_usage_error\n(\nsource\n, \nevent\n: ToolUsageErrorEvent):\n\n\n agentops.ErrorEvent(\nexception\n=\nevent.error, \ntrigger_event\n=\nself\n.tool_event)\n\n\n\n\nThis listener initializes an AgentOps session when a Crew starts, registers agents with AgentOps, tracks tool usage, and ends the session when the Crew completes.\n\n\nThe AgentOps listener is registered in CrewAI’s event system through the import in \nsrc/crewai/utilities/events/third_party/__init__.py\n:\n\n\nCopy\nAsk AI\nfrom\n .agentops_listener \nimport\n agentops_listener\n\n\n\n\nThis ensures the \nagentops_listener\n is loaded when the \ncrewai.utilities.events\n package is imported.\n\n\n​\nAdvanced Usage: Scoped Handlers\n\n\nFor temporary event handling (useful for testing or specific operations), you can use the \nscoped_handlers\n context manager:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n crewai_event_bus, CrewKickoffStartedEvent\n\n\n\n\nwith\n crewai_event_bus.scoped_handlers():\n\n\n @crewai_event_bus.on\n(CrewKickoffStartedEvent)\n\n\n def\n temp_handler\n(\nsource\n, \nevent\n):\n\n\n print\n(\n\"This handler only exists within this context\"\n)\n\n\n\n\n # Do something that emits events\n\n\n\n\n# Outside the context, the temporary handler is removed\n\n\n\n\n​\nUse Cases\n\n\nEvent listeners can be used for a variety of purposes:\n\n\n\n\nLogging and Monitoring\n: Track the execution of your Crew and log important events\n\n\nAnalytics\n: Collect data about your Crew’s performance and behavior\n\n\nDebugging\n: Set up temporary listeners to debug specific issues\n\n\nIntegration\n: Connect CrewAI with external systems like monitoring platforms, databases, or notification services\n\n\nCustom Behavior\n: Trigger custom actions based on specific events\n\n\n\n\n​\nBest Practices\n\n\n\n\nKeep Handlers Light\n: Event handlers should be lightweight and avoid blocking operations\n\n\nError Handling\n: Include proper error handling in your event handlers to prevent exceptions from affecting the main execution\n\n\nCleanup\n: If your listener allocates resources, ensure they’re properly cleaned up\n\n\nSelective Listening\n: Only listen for events you actually need to handle\n\n\nTesting\n: Test your event listeners in isolation to ensure they behave as expected\n\n\n\n\nBy leveraging CrewAI’s event system, you can extend its functionality and integrate it seamlessly with your existing infrastructure.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTools\nMCP Servers as Tools in CrewAI\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nHow It Works\nCreating a Custom Event Listener\nProperly Registering Your Listener\nOption 1: Import and Instantiate in Your Crew or Flow Implementation\nFor Crew-based Applications\nFor Flow-based Applications\nOption 2: Create a Package for Your Listeners\nAvailable Event Types\nCrew Events\nAgent Events\nTask Events\nTool Usage Events\nKnowledge Events\nLLM Guardrail Events\nFlow Events\nLLM Events\nMemory Events\nEvent Handler Structure\nReal-World Example: Integration with AgentOps\nAdvanced Usage: Scoped Handlers\nUse Cases\nBest Practices\nCore Concepts\nEvent Listeners\nCopy page\nTap into CrewAI events to build custom integrations and monitoring\n​\nOverview\n\n\nCrewAI provides a powerful event system that allows you to listen for and react to various events that occur during the execution of your Crew. This feature enables you to build custom integrations, monitoring solutions, logging systems, or any other functionality that needs to be triggered based on CrewAI’s internal events.\n\n\n​\nHow It Works\n\n\nCrewAI uses an event bus architecture to emit events throughout the execution lifecycle. The event system is built on the following components:\n\n\n\n\nCrewAIEventsBus\n: A singleton event bus that manages event registration and emission\n\n\nBaseEvent\n: Base class for all events in the system\n\n\nBaseEventListener\n: Abstract base class for creating custom event listeners\n\n\n\n\nWhen specific actions occur in CrewAI (like a Crew starting execution, an Agent completing a task, or a tool being used), the system emits corresponding events. You can register handlers for these events to execute custom code when they occur.\n\n\nCrewAI Enterprise provides a built-in Prompt Tracing feature that leverages the event system to track, store, and visualize all prompts, completions, and associated metadata. This provides powerful debugging capabilities and transparency into your agent operations.\nWith Prompt Tracing you can:\n\n\nView the complete history of all prompts sent to your LLM\n\n\nTrack token usage and costs\n\n\nDebug agent reasoning failures\n\n\nShare prompt sequences with your team\n\n\nCompare different prompt strategies\n\n\nExport traces for compliance and auditing\n\n\n\n\n​\nCreating a Custom Event Listener\n\n\nTo create a custom event listener, you need to:\n\n\n\n\nCreate a class that inherits from \nBaseEventListener\n\n\nImplement the \nsetup_listeners\n method\n\n\nRegister handlers for the events you’re interested in\n\n\nCreate an instance of your listener in the appropriate file\n\n\n\n\nHere’s a simple example of a custom event listener class:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n (\n\n\n CrewKickoffStartedEvent,\n\n\n CrewKickoffCompletedEvent,\n\n\n AgentExecutionCompletedEvent,\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n):\n\n\n super\n().\n__init__\n()\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(CrewKickoffStartedEvent)\n\n\n def\n on_crew_started\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Crew '\n{\nevent.crew_name\n}\n' has started execution!\"\n)\n\n\n\n\n @crewai_event_bus.on\n(CrewKickoffCompletedEvent)\n\n\n def\n on_crew_completed\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Crew '\n{\nevent.crew_name\n}\n' has completed execution!\"\n)\n\n\n print\n(\nf\n\"Output: \n{\nevent.output\n}\n\"\n)\n\n\n\n\n @crewai_event_bus.on\n(AgentExecutionCompletedEvent)\n\n\n def\n on_agent_execution_completed\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Agent '\n{\nevent.agent.role\n}\n' completed task\"\n)\n\n\n print\n(\nf\n\"Output: \n{\nevent.output\n}\n\"\n)\n\n\n\n\n​\nProperly Registering Your Listener\n\n\nSimply defining your listener class isn’t enough. You need to create an instance of it and ensure it’s imported in your application. This ensures that:\n\n\n\n\nThe event handlers are registered with the event bus\n\n\nThe listener instance remains in memory (not garbage collected)\n\n\nThe listener is active when events are emitted\n\n\n\n\n​\nOption 1: Import and Instantiate in Your Crew or Flow Implementation\n\n\nThe most important thing is to create an instance of your listener in the file where your Crew or Flow is defined and executed:\n\n\n​\nFor Crew-based Applications\n\n\nCreate and import your listener at the top of your Crew implementation file:\n\n\nCopy\nAsk AI\n# In your crew.py file\n\n\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\nfrom\n my_listeners \nimport\n MyCustomListener\n\n\n\n\n# Create an instance of your listener\n\n\nmy_listener \n=\n MyCustomListener()\n\n\n\n\nclass\n MyCustomCrew\n:\n\n\n # Your crew implementation...\n\n\n\n\n def\n crew\n(\nself\n):\n\n\n return\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n # ...\n\n\n )\n\n\n\n\n​\nFor Flow-based Applications\n\n\nCreate and import your listener at the top of your Flow implementation file:\n\n\nCopy\nAsk AI\n# In your main.py or flow.py file\n\n\nfrom\n crewai.flow \nimport\n Flow, listen, start\n\n\nfrom\n my_listeners \nimport\n MyCustomListener\n\n\n\n\n# Create an instance of your listener\n\n\nmy_listener \n=\n MyCustomListener()\n\n\n\n\nclass\n MyCustomFlow\n(\nFlow\n):\n\n\n # Your flow implementation...\n\n\n\n\n @start\n()\n\n\n def\n first_step\n(\nself\n):\n\n\n # ...\n\n\n\n\nThis ensures that your listener is loaded and active when your Crew or Flow is executed.\n\n\n​\nOption 2: Create a Package for Your Listeners\n\n\nFor a more structured approach, especially if you have multiple listeners:\n\n\n\n\nCreate a package for your listeners:\n\n\n\n\nCopy\nAsk AI\nmy_project/\n\n\n ├── listeners/\n\n\n │ ├── __init__.py\n\n\n │ ├── my_custom_listener.py\n\n\n │ └── another_listener.py\n\n\n\n\n\n\nIn \nmy_custom_listener.py\n, define your listener class and create an instance:\n\n\n\n\nCopy\nAsk AI\n# my_custom_listener.py\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n# ... import events ...\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n # ... implementation ...\n\n\n\n\n# Create an instance of your listener\n\n\nmy_custom_listener \n=\n MyCustomListener()\n\n\n\n\n\n\nIn \n__init__.py\n, import the listener instances to ensure they’re loaded:\n\n\n\n\nCopy\nAsk AI\n# __init__.py\n\n\nfrom\n .my_custom_listener \nimport\n my_custom_listener\n\n\nfrom\n .another_listener \nimport\n another_listener\n\n\n\n\n# Optionally export them if you need to access them elsewhere\n\n\n__all__\n =\n [\n'my_custom_listener'\n, \n'another_listener'\n]\n\n\n\n\n\n\nImport your listeners package in your Crew or Flow file:\n\n\n\n\nCopy\nAsk AI\n# In your crew.py or flow.py file\n\n\nimport\n my_project.listeners \n# This loads all your listeners\n\n\n\n\nclass\n MyCustomCrew\n:\n\n\n # Your crew implementation...\n\n\n\n\nThis is exactly how CrewAI’s built-in \nagentops_listener\n is registered. In the CrewAI codebase, you’ll find:\n\n\nCopy\nAsk AI\n# src/crewai/utilities/events/third_party/__init__.py\n\n\nfrom\n .agentops_listener \nimport\n agentops_listener\n\n\n\n\nThis ensures the \nagentops_listener\n is loaded when the \ncrewai.utilities.events\n package is imported.\n\n\n​\nAvailable Event Types\n\n\nCrewAI provides a wide range of events that you can listen for:\n\n\n​\nCrew Events\n\n\n\n\nCrewKickoffStartedEvent\n: Emitted when a Crew starts execution\n\n\nCrewKickoffCompletedEvent\n: Emitted when a Crew completes execution\n\n\nCrewKickoffFailedEvent\n: Emitted when a Crew fails to complete execution\n\n\nCrewTestStartedEvent\n: Emitted when a Crew starts testing\n\n\nCrewTestCompletedEvent\n: Emitted when a Crew completes testing\n\n\nCrewTestFailedEvent\n: Emitted when a Crew fails to complete testing\n\n\nCrewTrainStartedEvent\n: Emitted when a Crew starts training\n\n\nCrewTrainCompletedEvent\n: Emitted when a Crew completes training\n\n\nCrewTrainFailedEvent\n: Emitted when a Crew fails to complete training\n\n\n\n\n​\nAgent Events\n\n\n\n\nAgentExecutionStartedEvent\n: Emitted when an Agent starts executing a task\n\n\nAgentExecutionCompletedEvent\n: Emitted when an Agent completes executing a task\n\n\nAgentExecutionErrorEvent\n: Emitted when an Agent encounters an error during execution\n\n\n\n\n​\nTask Events\n\n\n\n\nTaskStartedEvent\n: Emitted when a Task starts execution\n\n\nTaskCompletedEvent\n: Emitted when a Task completes execution\n\n\nTaskFailedEvent\n: Emitted when a Task fails to complete execution\n\n\nTaskEvaluationEvent\n: Emitted when a Task is evaluated\n\n\n\n\n​\nTool Usage Events\n\n\n\n\nToolUsageStartedEvent\n: Emitted when a tool execution is started\n\n\nToolUsageFinishedEvent\n: Emitted when a tool execution is completed\n\n\nToolUsageErrorEvent\n: Emitted when a tool execution encounters an error\n\n\nToolValidateInputErrorEvent\n: Emitted when a tool input validation encounters an error\n\n\nToolExecutionErrorEvent\n: Emitted when a tool execution encounters an error\n\n\nToolSelectionErrorEvent\n: Emitted when there’s an error selecting a tool\n\n\n\n\n​\nKnowledge Events\n\n\n\n\nKnowledgeRetrievalStartedEvent\n: Emitted when a knowledge retrieval is started\n\n\nKnowledgeRetrievalCompletedEvent\n: Emitted when a knowledge retrieval is completed\n\n\nKnowledgeQueryStartedEvent\n: Emitted when a knowledge query is started\n\n\nKnowledgeQueryCompletedEvent\n: Emitted when a knowledge query is completed\n\n\nKnowledgeQueryFailedEvent\n: Emitted when a knowledge query fails\n\n\nKnowledgeSearchQueryFailedEvent\n: Emitted when a knowledge search query fails\n\n\n\n\n​\nLLM Guardrail Events\n\n\n\n\nLLMGuardrailStartedEvent\n: Emitted when a guardrail validation starts. Contains details about the guardrail being applied and retry count.\n\n\nLLMGuardrailCompletedEvent\n: Emitted when a guardrail validation completes. Contains details about validation success/failure, results, and error messages if any.\n\n\n\n\n​\nFlow Events\n\n\n\n\nFlowCreatedEvent\n: Emitted when a Flow is created\n\n\nFlowStartedEvent\n: Emitted when a Flow starts execution\n\n\nFlowFinishedEvent\n: Emitted when a Flow completes execution\n\n\nFlowPlotEvent\n: Emitted when a Flow is plotted\n\n\nMethodExecutionStartedEvent\n: Emitted when a Flow method starts execution\n\n\nMethodExecutionFinishedEvent\n: Emitted when a Flow method completes execution\n\n\nMethodExecutionFailedEvent\n: Emitted when a Flow method fails to complete execution\n\n\n\n\n​\nLLM Events\n\n\n\n\nLLMCallStartedEvent\n: Emitted when an LLM call starts\n\n\nLLMCallCompletedEvent\n: Emitted when an LLM call completes\n\n\nLLMCallFailedEvent\n: Emitted when an LLM call fails\n\n\nLLMStreamChunkEvent\n: Emitted for each chunk received during streaming LLM responses\n\n\n\n\n​\nMemory Events\n\n\n\n\nMemoryQueryStartedEvent\n: Emitted when a memory query is started. Contains the query, limit, and optional score threshold.\n\n\nMemoryQueryCompletedEvent\n: Emitted when a memory query is completed successfully. Contains the query, results, limit, score threshold, and query execution time.\n\n\nMemoryQueryFailedEvent\n: Emitted when a memory query fails. Contains the query, limit, score threshold, and error message.\n\n\nMemorySaveStartedEvent\n: Emitted when a memory save operation is started. Contains the value to be saved, metadata, and optional agent role.\n\n\nMemorySaveCompletedEvent\n: Emitted when a memory save operation is completed successfully. Contains the saved value, metadata, agent role, and save execution time.\n\n\nMemorySaveFailedEvent\n: Emitted when a memory save operation fails. Contains the value, metadata, agent role, and error message.\n\n\nMemoryRetrievalStartedEvent\n: Emitted when memory retrieval for a task prompt starts. Contains the optional task ID.\n\n\nMemoryRetrievalCompletedEvent\n: Emitted when memory retrieval for a task prompt completes successfully. Contains the task ID, memory content, and retrieval execution time.\n\n\n\n\n​\nEvent Handler Structure\n\n\nEach event handler receives two parameters:\n\n\n\n\nsource\n: The object that emitted the event\n\n\nevent\n: The event instance, containing event-specific data\n\n\n\n\nThe structure of the event object depends on the event type, but all events inherit from \nBaseEvent\n and include:\n\n\n\n\ntimestamp\n: The time when the event was emitted\n\n\ntype\n: A string identifier for the event type\n\n\n\n\nAdditional fields vary by event type. For example, \nCrewKickoffCompletedEvent\n includes \ncrew_name\n and \noutput\n fields.\n\n\n​\nReal-World Example: Integration with AgentOps\n\n\nCrewAI includes an example of a third-party integration with \nAgentOps\n, a monitoring and observability platform for AI agents. Here’s how it’s implemented:\n\n\nCopy\nAsk AI\nfrom\n typing \nimport\n Optional\n\n\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n CrewKickoffCompletedEvent,\n\n\n ToolUsageErrorEvent,\n\n\n ToolUsageStartedEvent,\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events.crew_events \nimport\n CrewKickoffStartedEvent\n\n\nfrom\n crewai.utilities.events.task_events \nimport\n TaskEvaluationEvent\n\n\n\n\ntry\n:\n\n\n import\n agentops\n\n\n AGENTOPS_INSTALLED\n =\n True\n\n\nexcept\n ImportError\n:\n\n\n AGENTOPS_INSTALLED\n =\n False\n\n\n\n\nclass\n AgentOpsListener\n(\nBaseEventListener\n):\n\n\n tool_event: Optional[\n\"agentops.ToolEvent\"\n] \n=\n None\n\n\n session: Optional[\n\"agentops.Session\"\n] \n=\n None\n\n\n\n\n def\n __init__\n(\nself\n):\n\n\n super\n().\n__init__\n()\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n if\n not\n AGENTOPS_INSTALLED\n:\n\n\n return\n\n\n\n\n @crewai_event_bus.on\n(CrewKickoffStartedEvent)\n\n\n def\n on_crew_kickoff_started\n(\nsource\n, \nevent\n: CrewKickoffStartedEvent):\n\n\n self\n.session \n=\n agentops.init()\n\n\n for\n agent \nin\n source.agents:\n\n\n if\n self\n.session:\n\n\n self\n.session.create_agent(\n\n\n name\n=\nagent.role,\n\n\n agent_id\n=\nstr\n(agent.id),\n\n\n )\n\n\n\n\n @crewai_event_bus.on\n(CrewKickoffCompletedEvent)\n\n\n def\n on_crew_kickoff_completed\n(\nsource\n, \nevent\n: CrewKickoffCompletedEvent):\n\n\n if\n self\n.session:\n\n\n self\n.session.end_session(\n\n\n end_state\n=\n\"Success\"\n,\n\n\n end_state_reason\n=\n\"Finished Execution\"\n,\n\n\n )\n\n\n\n\n @crewai_event_bus.on\n(ToolUsageStartedEvent)\n\n\n def\n on_tool_usage_started\n(\nsource\n, \nevent\n: ToolUsageStartedEvent):\n\n\n self\n.tool_event \n=\n agentops.ToolEvent(\nname\n=\nevent.tool_name)\n\n\n if\n self\n.session:\n\n\n self\n.session.record(\nself\n.tool_event)\n\n\n\n\n @crewai_event_bus.on\n(ToolUsageErrorEvent)\n\n\n def\n on_tool_usage_error\n(\nsource\n, \nevent\n: ToolUsageErrorEvent):\n\n\n agentops.ErrorEvent(\nexception\n=\nevent.error, \ntrigger_event\n=\nself\n.tool_event)\n\n\n\n\nThis listener initializes an AgentOps session when a Crew starts, registers agents with AgentOps, tracks tool usage, and ends the session when the Crew completes.\n\n\nThe AgentOps listener is registered in CrewAI’s event system through the import in \nsrc/crewai/utilities/events/third_party/__init__.py\n:\n\n\nCopy\nAsk AI\nfrom\n .agentops_listener \nimport\n agentops_listener\n\n\n\n\nThis ensures the \nagentops_listener\n is loaded when the \ncrewai.utilities.events\n package is imported.\n\n\n​\nAdvanced Usage: Scoped Handlers\n\n\nFor temporary event handling (useful for testing or specific operations), you can use the \nscoped_handlers\n context manager:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n crewai_event_bus, CrewKickoffStartedEvent\n\n\n\n\nwith\n crewai_event_bus.scoped_handlers():\n\n\n @crewai_event_bus.on\n(CrewKickoffStartedEvent)\n\n\n def\n temp_handler\n(\nsource\n, \nevent\n):\n\n\n print\n(\n\"This handler only exists within this context\"\n)\n\n\n\n\n # Do something that emits events\n\n\n\n\n# Outside the context, the temporary handler is removed\n\n\n\n\n​\nUse Cases\n\n\nEvent listeners can be used for a variety of purposes:\n\n\n\n\nLogging and Monitoring\n: Track the execution of your Crew and log important events\n\n\nAnalytics\n: Collect data about your Crew’s performance and behavior\n\n\nDebugging\n: Set up temporary listeners to debug specific issues\n\n\nIntegration\n: Connect CrewAI with external systems like monitoring platforms, databases, or notification services\n\n\nCustom Behavior\n: Trigger custom actions based on specific events\n\n\n\n\n​\nBest Practices\n\n\n\n\nKeep Handlers Light\n: Event handlers should be lightweight and avoid blocking operations\n\n\nError Handling\n: Include proper error handling in your event handlers to prevent exceptions from affecting the main execution\n\n\nCleanup\n: If your listener allocates resources, ensure they’re properly cleaned up\n\n\nSelective Listening\n: Only listen for events you actually need to handle\n\n\nTesting\n: Test your event listeners in isolation to ensure they behave as expected\n\n\n\n\nBy leveraging CrewAI’s event system, you can extend its functionality and integrate it seamlessly with your existing infrastructure.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTools\nMCP Servers as Tools in CrewAI\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nHow It Works\nCreating a Custom Event Listener\nProperly Registering Your Listener\nOption 1: Import and Instantiate in Your Crew or Flow Implementation\nFor Crew-based Applications\nFor Flow-based Applications\nOption 2: Create a Package for Your Listeners\nAvailable Event Types\nCrew Events\nAgent Events\nTask Events\nTool Usage Events\nKnowledge Events\nLLM Guardrail Events\nFlow Events\nLLM Events\nMemory Events\nEvent Handler Structure\nReal-World Example: Integration with AgentOps\nAdvanced Usage: Scoped Handlers\nUse Cases\nBest Practices" }, { "source": "https://docs.crewai.com/en/learn/llm-selection-guide", "title": "Strategic LLM Selection Guide - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nStrategic LLM Selection Guide\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nStrategic LLM Selection Guide\nCopy page\nStrategic framework for choosing the right LLM for your CrewAI AI agents and writing effective task and agent definitions\n​\nThe CrewAI Approach to LLM Selection\n\n\nRather than prescriptive model recommendations, we advocate for a \nthinking framework\n that helps you make informed decisions based on your specific use case, constraints, and requirements. The LLM landscape evolves rapidly, with new models emerging regularly and existing ones being updated frequently. What matters most is developing a systematic approach to evaluation that remains relevant regardless of which specific models are available.\n\n\nThis guide focuses on strategic thinking rather than specific model recommendations, as the LLM landscape evolves rapidly.\n\n\n​\nQuick Decision Framework\n\n\n1\nAnalyze Your Tasks\nBegin by deeply understanding what your tasks actually require. Consider the cognitive complexity involved, the depth of reasoning needed, the format of expected outputs, and the amount of context the model will need to process. This foundational analysis will guide every subsequent decision.\n2\nMap Model Capabilities\nOnce you understand your requirements, map them to model strengths. Different model families excel at different types of work; some are optimized for reasoning and analysis, others for creativity and content generation, and others for speed and efficiency.\n3\nConsider Constraints\nFactor in your real-world operational constraints including budget limitations, latency requirements, data privacy needs, and infrastructure capabilities. The theoretically best model may not be the practically best choice for your situation.\n4\nTest and Iterate\nStart with reliable, well-understood models and optimize based on actual performance in your specific use case. Real-world results often differ from theoretical benchmarks, so empirical testing is crucial.\n\n\n​\nCore Selection Framework\n\n\n​\na. Task-First Thinking\n\n\nThe most critical step in LLM selection is understanding what your task actually demands. Too often, teams select models based on general reputation or benchmark scores without carefully analyzing their specific requirements. This approach leads to either over-engineering simple tasks with expensive, complex models, or under-powering sophisticated work with models that lack the necessary capabilities.\n\n\nReasoning Complexity\nOutput Requirements\nContext Needs\n\n\n\n\nSimple Tasks\n represent the majority of everyday AI work and include basic instruction following, straightforward data processing, and simple formatting operations. These tasks typically have clear inputs and outputs with minimal ambiguity. The cognitive load is low, and the model primarily needs to follow explicit instructions rather than engage in complex reasoning.\n\n\n\n\n\n\nComplex Tasks\n require multi-step reasoning, strategic thinking, and the ability to handle ambiguous or incomplete information. These might involve analyzing multiple data sources, developing comprehensive strategies, or solving problems that require breaking down into smaller components. The model needs to maintain context across multiple reasoning steps and often must make inferences that aren’t explicitly stated.\n\n\n\n\n\n\nCreative Tasks\n demand a different type of cognitive capability focused on generating novel, engaging, and contextually appropriate content. This includes storytelling, marketing copy creation, and creative problem-solving. The model needs to understand nuance, tone, and audience while producing content that feels authentic and engaging rather than formulaic.\n\n\n\n\n\n\n\n\nSimple Tasks\n represent the majority of everyday AI work and include basic instruction following, straightforward data processing, and simple formatting operations. These tasks typically have clear inputs and outputs with minimal ambiguity. The cognitive load is low, and the model primarily needs to follow explicit instructions rather than engage in complex reasoning.\n\n\n\n\n\n\nComplex Tasks\n require multi-step reasoning, strategic thinking, and the ability to handle ambiguous or incomplete information. These might involve analyzing multiple data sources, developing comprehensive strategies, or solving problems that require breaking down into smaller components. The model needs to maintain context across multiple reasoning steps and often must make inferences that aren’t explicitly stated.\n\n\n\n\n\n\nCreative Tasks\n demand a different type of cognitive capability focused on generating novel, engaging, and contextually appropriate content. This includes storytelling, marketing copy creation, and creative problem-solving. The model needs to understand nuance, tone, and audience while producing content that feels authentic and engaging rather than formulaic.\n\n\n\n\n\n\n\n\nStructured Data\n tasks require precision and consistency in format adherence. When working with JSON, XML, or database formats, the model must reliably produce syntactically correct output that can be programmatically processed. These tasks often have strict validation requirements and little tolerance for format errors, making reliability more important than creativity.\n\n\n\n\n\n\nCreative Content\n outputs demand a balance of technical competence and creative flair. The model needs to understand audience, tone, and brand voice while producing content that engages readers and achieves specific communication goals. Quality here is often subjective and requires models that can adapt their writing style to different contexts and purposes.\n\n\n\n\n\n\nTechnical Content\n sits between structured data and creative content, requiring both precision and clarity. Documentation, code generation, and technical analysis need to be accurate and comprehensive while remaining accessible to the intended audience. The model must understand complex technical concepts and communicate them effectively.\n\n\n\n\n\n\n\n\nShort Context\n scenarios involve focused, immediate tasks where the model needs to process limited information quickly. These are often transactional interactions where speed and efficiency matter more than deep understanding. The model doesn’t need to maintain extensive conversation history or process large documents.\n\n\n\n\n\n\nLong Context\n requirements emerge when working with substantial documents, extended conversations, or complex multi-part tasks. The model needs to maintain coherence across thousands of tokens while referencing earlier information accurately. This capability becomes crucial for document analysis, comprehensive research, and sophisticated dialogue systems.\n\n\n\n\n\n\nVery Long Context\n scenarios push the boundaries of what’s currently possible, involving massive document processing, extensive research synthesis, or complex multi-session interactions. These use cases require models specifically designed for extended context handling and often involve trade-offs between context length and processing speed.\n\n\n\n\n\n\n​\nb. Model Capability Mapping\n\n\nUnderstanding model capabilities requires looking beyond marketing claims and benchmark scores to understand the fundamental strengths and limitations of different model architectures and training approaches.\n\n\nReasoning Models\nReasoning models represent a specialized category designed specifically for complex, multi-step thinking tasks. These models excel when problems require careful analysis, strategic planning, or systematic problem decomposition. They typically employ techniques like chain-of-thought reasoning or tree-of-thought processing to work through complex problems step by step.\nThe strength of reasoning models lies in their ability to maintain logical consistency across extended reasoning chains and to break down complex problems into manageable components. They’re particularly valuable for strategic planning, complex analysis, and situations where the quality of reasoning matters more than speed of response.\nHowever, reasoning models often come with trade-offs in terms of speed and cost. They may also be less suitable for creative tasks or simple operations where their sophisticated reasoning capabilities aren’t needed. Consider these models when your tasks involve genuine complexity that benefits from systematic, step-by-step analysis.\nGeneral Purpose Models\nGeneral purpose models offer the most balanced approach to LLM selection, providing solid performance across a wide range of tasks without extreme specialization in any particular area. These models are trained on diverse datasets and optimized for versatility rather than peak performance in specific domains.\nThe primary advantage of general purpose models is their reliability and predictability across different types of work. They handle most standard business tasks competently, from research and analysis to content creation and data processing. This makes them excellent choices for teams that need consistent performance across varied workflows.\nWhile general purpose models may not achieve the peak performance of specialized alternatives in specific domains, they offer operational simplicity and reduced complexity in model management. They’re often the best starting point for new projects, allowing teams to understand their specific needs before potentially optimizing with more specialized models.\nFast & Efficient Models\nFast and efficient models prioritize speed, cost-effectiveness, and resource efficiency over sophisticated reasoning capabilities. These models are optimized for high-throughput scenarios where quick responses and low operational costs are more important than nuanced understanding or complex reasoning.\nThese models excel in scenarios involving routine operations, simple data processing, function calling, and high-volume tasks where the cognitive requirements are relatively straightforward. They’re particularly valuable for applications that need to process many requests quickly or operate within tight budget constraints.\nThe key consideration with efficient models is ensuring that their capabilities align with your task requirements. While they can handle many routine operations effectively, they may struggle with tasks requiring nuanced understanding, complex reasoning, or sophisticated content generation. They’re best used for well-defined, routine operations where speed and cost matter more than sophistication.\nCreative Models\nCreative models are specifically optimized for content generation, writing quality, and creative thinking tasks. These models typically excel at understanding nuance, tone, and style while producing engaging, contextually appropriate content that feels natural and authentic.\nThe strength of creative models lies in their ability to adapt writing style to different audiences, maintain consistent voice and tone, and generate content that engages readers effectively. They often perform better on tasks involving storytelling, marketing copy, brand communications, and other content where creativity and engagement are primary goals.\nWhen selecting creative models, consider not just their ability to generate text, but their understanding of audience, context, and purpose. The best creative models can adapt their output to match specific brand voices, target different audience segments, and maintain consistency across extended content pieces.\nOpen Source Models\nOpen source models offer unique advantages in terms of cost control, customization potential, data privacy, and deployment flexibility. These models can be run locally or on private infrastructure, providing complete control over data handling and model behavior.\nThe primary benefits of open source models include elimination of per-token costs, ability to fine-tune for specific use cases, complete data privacy, and independence from external API providers. They’re particularly valuable for organizations with strict data privacy requirements, budget constraints, or specific customization needs.\nHowever, open source models require more technical expertise to deploy and maintain effectively. Teams need to consider infrastructure costs, model management complexity, and the ongoing effort required to keep models updated and optimized. The total cost of ownership may be higher than cloud-based alternatives when factoring in technical overhead.\n\n\n​\nStrategic Configuration Patterns\n\n\n​\na. Multi-Model Approach\n\n\nUse different models for different purposes within the same crew to optimize both performance and cost.\n\n\nThe most sophisticated CrewAI implementations often employ multiple models strategically, assigning different models to different agents based on their specific roles and requirements. This approach allows teams to optimize for both performance and cost by using the most appropriate model for each type of work.\n\n\nPlanning agents benefit from reasoning models that can handle complex strategic thinking and multi-step analysis. These agents often serve as the “brain” of the operation, developing strategies and coordinating other agents’ work. Content agents, on the other hand, perform best with creative models that excel at writing quality and audience engagement. Processing agents handling routine operations can use efficient models that prioritize speed and cost-effectiveness.\n\n\nExample: Research and Analysis Crew\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, \nLLM\n\n\n\n\n# High-capability reasoning model for strategic planning\n\n\nmanager_llm \n=\n LLM(\nmodel\n=\n\"gemini-2.5-flash-preview-05-20\"\n, \ntemperature\n=\n0.1\n)\n\n\n\n\n# Creative model for content generation\n\n\ncontent_llm \n=\n LLM(\nmodel\n=\n\"claude-3-5-sonnet-20241022\"\n, \ntemperature\n=\n0.7\n)\n\n\n\n\n# Efficient model for data processing\n\n\nprocessing_llm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n)\n\n\n\n\nresearch_manager \n=\n Agent(\n\n\n role\n=\n\"Research Strategy Manager\"\n,\n\n\n goal\n=\n\"Develop comprehensive research strategies and coordinate team efforts\"\n,\n\n\n backstory\n=\n\"Expert research strategist with deep analytical capabilities\"\n,\n\n\n llm\n=\nmanager_llm, \n# High-capability model for complex reasoning\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ncontent_writer \n=\n Agent(\n\n\n role\n=\n\"Research Content Writer\"\n,\n\n\n goal\n=\n\"Transform research findings into compelling, well-structured reports\"\n,\n\n\n backstory\n=\n\"Skilled writer who excels at making complex topics accessible\"\n,\n\n\n llm\n=\ncontent_llm, \n# Creative model for engaging content\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ndata_processor \n=\n Agent(\n\n\n role\n=\n\"Data Analysis Specialist\"\n, \n\n\n goal\n=\n\"Extract and organize key data points from research sources\"\n,\n\n\n backstory\n=\n\"Detail-oriented analyst focused on accuracy and efficiency\"\n,\n\n\n llm\n=\nprocessing_llm, \n# Fast, cost-effective model for routine tasks\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_manager, content_writer, data_processor],\n\n\n tasks\n=\n[\n...\n], \n# Your specific tasks\n\n\n manager_llm\n=\nmanager_llm, \n# Manager uses the reasoning model\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nThe key to successful multi-model implementation is understanding how different agents interact and ensuring that model capabilities align with agent responsibilities. This requires careful planning but can result in significant improvements in both output quality and operational efficiency.\n\n\n​\nb. Component-Specific Selection\n\n\nManager LLM\nFunction Calling LLM\nAgent-Specific Overrides\nThe manager LLM plays a crucial role in hierarchical CrewAI processes, serving as the coordination point for multiple agents and tasks. This model needs to excel at delegation, task prioritization, and maintaining context across multiple concurrent operations.\nEffective manager LLMs require strong reasoning capabilities to make good delegation decisions, consistent performance to ensure predictable coordination, and excellent context management to track the state of multiple agents simultaneously. The model needs to understand the capabilities and limitations of different agents while optimizing task allocation for efficiency and quality.\nCost considerations are particularly important for manager LLMs since they’re involved in every operation. The model needs to provide sufficient capability for effective coordination while remaining cost-effective for frequent use. This often means finding models that offer good reasoning capabilities without the premium pricing of the most sophisticated options.\nThe manager LLM plays a crucial role in hierarchical CrewAI processes, serving as the coordination point for multiple agents and tasks. This model needs to excel at delegation, task prioritization, and maintaining context across multiple concurrent operations.\nEffective manager LLMs require strong reasoning capabilities to make good delegation decisions, consistent performance to ensure predictable coordination, and excellent context management to track the state of multiple agents simultaneously. The model needs to understand the capabilities and limitations of different agents while optimizing task allocation for efficiency and quality.\nCost considerations are particularly important for manager LLMs since they’re involved in every operation. The model needs to provide sufficient capability for effective coordination while remaining cost-effective for frequent use. This often means finding models that offer good reasoning capabilities without the premium pricing of the most sophisticated options.\nFunction calling LLMs handle tool usage across all agents, making them critical for crews that rely heavily on external tools and APIs. These models need to excel at understanding tool capabilities, extracting parameters accurately, and handling tool responses effectively.\nThe most important characteristics for function calling LLMs are precision and reliability rather than creativity or sophisticated reasoning. The model needs to consistently extract the correct parameters from natural language requests and handle tool responses appropriately. Speed is also important since tool usage often involves multiple round trips that can impact overall performance.\nMany teams find that specialized function calling models or general purpose models with strong tool support work better than creative or reasoning-focused models for this role. The key is ensuring that the model can reliably bridge the gap between natural language instructions and structured tool calls.\nIndividual agents can override crew-level LLM settings when their specific needs differ significantly from the general crew requirements. This capability allows for fine-tuned optimization while maintaining operational simplicity for most agents.\nConsider agent-specific overrides when an agent’s role requires capabilities that differ substantially from other crew members. For example, a creative writing agent might benefit from a model optimized for content generation, while a data analysis agent might perform better with a reasoning-focused model.\nThe challenge with agent-specific overrides is balancing optimization with operational complexity. Each additional model adds complexity to deployment, monitoring, and cost management. Teams should focus overrides on agents where the performance improvement justifies the additional complexity.\n\n\n​\nTask Definition Framework\n\n\n​\na. Focus on Clarity Over Complexity\n\n\nEffective task definition is often more important than model selection in determining the quality of CrewAI outputs. Well-defined tasks provide clear direction and context that enable even modest models to perform well, while poorly defined tasks can cause even sophisticated models to produce unsatisfactory results.\n\n\nEffective Task Descriptions\nThe best task descriptions strike a balance between providing sufficient detail and maintaining clarity. They should define the specific objective clearly enough that there’s no ambiguity about what success looks like, while explaining the approach or methodology in enough detail that the agent understands how to proceed.\nEffective task descriptions include relevant context and constraints that help the agent understand the broader purpose and any limitations they need to work within. They break complex work into focused steps that can be executed systematically, rather than presenting overwhelming, multi-faceted objectives that are difficult to approach systematically.\nCommon mistakes include being too vague about objectives, failing to provide necessary context, setting unclear success criteria, or combining multiple unrelated tasks into a single description. The goal is to provide enough information for the agent to succeed while maintaining focus on a single, clear objective.\nExpected Output Guidelines\nExpected output guidelines serve as a contract between the task definition and the agent, clearly specifying what the deliverable should look like and how it will be evaluated. These guidelines should describe both the format and structure needed, as well as the key elements that must be included for the output to be considered complete.\nThe best output guidelines provide concrete examples of quality indicators and define completion criteria clearly enough that both the agent and human reviewers can assess whether the task has been completed successfully. This reduces ambiguity and helps ensure consistent results across multiple task executions.\nAvoid generic output descriptions that could apply to any task, missing format specifications that leave agents guessing about structure, unclear quality standards that make evaluation difficult, or failing to provide examples or templates that help agents understand expectations.\n\n\n​\nb. Task Sequencing Strategy\n\n\nSequential Dependencies\nParallel Execution\nSequential task dependencies are essential when tasks build upon previous outputs, information flows from one task to another, or quality depends on the completion of prerequisite work. This approach ensures that each task has access to the information and context it needs to succeed.\nImplementing sequential dependencies effectively requires using the context parameter to chain related tasks, building complexity gradually through task progression, and ensuring that each task produces outputs that serve as meaningful inputs for subsequent tasks. The goal is to maintain logical flow between dependent tasks while avoiding unnecessary bottlenecks.\nSequential dependencies work best when there’s a clear logical progression from one task to another and when the output of one task genuinely improves the quality or feasibility of subsequent tasks. However, they can create bottlenecks if not managed carefully, so it’s important to identify which dependencies are truly necessary versus those that are merely convenient.\nSequential task dependencies are essential when tasks build upon previous outputs, information flows from one task to another, or quality depends on the completion of prerequisite work. This approach ensures that each task has access to the information and context it needs to succeed.\nImplementing sequential dependencies effectively requires using the context parameter to chain related tasks, building complexity gradually through task progression, and ensuring that each task produces outputs that serve as meaningful inputs for subsequent tasks. The goal is to maintain logical flow between dependent tasks while avoiding unnecessary bottlenecks.\nSequential dependencies work best when there’s a clear logical progression from one task to another and when the output of one task genuinely improves the quality or feasibility of subsequent tasks. However, they can create bottlenecks if not managed carefully, so it’s important to identify which dependencies are truly necessary versus those that are merely convenient.\nParallel execution becomes valuable when tasks are independent of each other, time efficiency is important, or different expertise areas are involved that don’t require coordination. This approach can significantly reduce overall execution time while allowing specialized agents to work on their areas of strength simultaneously.\nSuccessful parallel execution requires identifying tasks that can truly run independently, grouping related but separate work streams effectively, and planning for result integration when parallel tasks need to be combined into a final deliverable. The key is ensuring that parallel tasks don’t create conflicts or redundancies that reduce overall quality.\nConsider parallel execution when you have multiple independent research streams, different types of analysis that don’t depend on each other, or content creation tasks that can be developed simultaneously. However, be mindful of resource allocation and ensure that parallel execution doesn’t overwhelm your available model capacity or budget.\n\n\n​\nOptimizing Agent Configuration for LLM Performance\n\n\n​\na. Role-Driven LLM Selection\n\n\nGeneric agent roles make it impossible to select the right LLM. Specific roles enable targeted model optimization.\n\n\nThe specificity of your agent roles directly determines which LLM capabilities matter most for optimal performance. This creates a strategic opportunity to match precise model strengths with agent responsibilities.\n\n\nGeneric vs. Specific Role Impact on LLM Choice:\n\n\nWhen defining roles, think about the specific domain knowledge, working style, and decision-making frameworks that would be most valuable for the tasks the agent will handle. The more specific and contextual the role definition, the better the model can embody that role effectively.\n\n\nCopy\nAsk AI\n# ✅ Specific role - clear LLM requirements\n\n\nspecific_agent \n=\n Agent(\n\n\n role\n=\n\"SaaS Revenue Operations Analyst\"\n, \n# Clear domain expertise needed\n\n\n goal\n=\n\"Analyze recurring revenue metrics and identify growth opportunities\"\n,\n\n\n backstory\n=\n\"Specialist in SaaS business models with deep understanding of ARR, churn, and expansion revenue\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n) \n# Reasoning model justified for complex analysis\n\n\n)\n\n\n\n\nRole-to-Model Mapping Strategy:\n\n\n\n\n“Research Analyst”\n → Reasoning model (GPT-4o, Claude Sonnet) for complex analysis\n\n\n“Content Editor”\n → Creative model (Claude, GPT-4o) for writing quality\n\n\n“Data Processor”\n → Efficient model (GPT-4o-mini, Gemini Flash) for structured tasks\n\n\n“API Coordinator”\n → Function-calling optimized model (GPT-4o, Claude) for tool usage\n\n\n\n\n​\nb. Backstory as Model Context Amplifier\n\n\nStrategic backstories multiply your chosen LLM’s effectiveness by providing domain-specific context that generic prompting cannot achieve.\n\n\nA well-crafted backstory transforms your LLM choice from generic capability to specialized expertise. This is especially crucial for cost optimization - a well-contextualized efficient model can outperform a premium model without proper context.\n\n\nContext-Driven Performance Example:\n\n\nCopy\nAsk AI\n# Context amplifies model effectiveness\n\n\ndomain_expert \n=\n Agent(\n\n\n role\n=\n\"B2B SaaS Marketing Strategist\"\n,\n\n\n goal\n=\n\"Develop comprehensive go-to-market strategies for enterprise software\"\n,\n\n\n backstory\n=\n\"\"\"\n\n\n You have 10+ years of experience scaling B2B SaaS companies from Series A to IPO. \n\n\n You understand the nuances of enterprise sales cycles, the importance of product-market \n\n\n fit in different verticals, and how to balance growth metrics with unit economics. \n\n\n You've worked with companies like Salesforce, HubSpot, and emerging unicorns, giving \n\n\n you perspective on both established and disruptive go-to-market strategies.\n\n\n \"\"\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n, \ntemperature\n=\n0.3\n) \n# Balanced creativity with domain knowledge\n\n\n)\n\n\n\n\n# This context enables Claude to perform like a domain expert\n\n\n# Without it, even it would produce generic marketing advice\n\n\n\n\nBackstory Elements That Enhance LLM Performance:\n\n\n\n\nDomain Experience\n: “10+ years in enterprise SaaS sales”\n\n\nSpecific Expertise\n: “Specializes in technical due diligence for Series B+ rounds”\n\n\nWorking Style\n: “Prefers data-driven decisions with clear documentation”\n\n\nQuality Standards\n: “Insists on citing sources and showing analytical work”\n\n\n\n\n​\nc. Holistic Agent-LLM Optimization\n\n\nThe most effective agent configurations create synergy between role specificity, backstory depth, and LLM selection. Each element reinforces the others to maximize model performance.\n\n\nOptimization Framework:\n\n\nCopy\nAsk AI\n# Example: Technical Documentation Agent\n\n\ntech_writer \n=\n Agent(\n\n\n role\n=\n\"API Documentation Specialist\"\n, \n# Specific role for clear LLM requirements\n\n\n goal\n=\n\"Create comprehensive, developer-friendly API documentation\"\n,\n\n\n backstory\n=\n\"\"\"\n\n\n You're a technical writer with 8+ years documenting REST APIs, GraphQL endpoints, \n\n\n and SDK integration guides. You've worked with developer tools companies and \n\n\n understand what developers need: clear examples, comprehensive error handling, \n\n\n and practical use cases. You prioritize accuracy and usability over marketing fluff.\n\n\n \"\"\"\n,\n\n\n llm\n=\nLLM(\n\n\n model\n=\n\"claude-3-5-sonnet\"\n, \n# Excellent for technical writing\n\n\n temperature\n=\n0.1\n # Low temperature for accuracy\n\n\n ),\n\n\n tools\n=\n[code_analyzer_tool, api_scanner_tool],\n\n\n verbose\n=\nTrue\n \n\n\n)\n\n\n\n\nAlignment Checklist:\n\n\n\n\n✅ \nRole Specificity\n: Clear domain and responsibilities\n\n\n✅ \nLLM Match\n: Model strengths align with role requirements\n\n\n✅ \nBackstory Depth\n: Provides domain context the LLM can leverage\n\n\n✅ \nTool Integration\n: Tools support the agent’s specialized function\n\n\n✅ \nParameter Tuning\n: Temperature and settings optimize for role needs\n\n\n\n\nThe key is creating agents where every configuration choice reinforces your LLM selection strategy, maximizing performance while optimizing costs.\n\n\n​\nPractical Implementation Checklist\n\n\nRather than repeating the strategic framework, here’s a tactical checklist for implementing your LLM selection decisions in CrewAI:\n\n\nAudit Your Current Setup\nWhat to Review:\n\n\nAre all agents using the same LLM by default?\n\n\nWhich agents handle the most complex reasoning tasks?\n\n\nWhich agents primarily do data processing or formatting?\n\n\nAre any agents heavily tool-dependent?\n\n\nAction\n: Document current agent roles and identify optimization opportunities.\nImplement Crew-Level Strategy\nSet Your Baseline:\nCopy\nAsk AI\n# Start with a reliable default for the crew\n\n\ndefault_crew_llm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n) \n# Cost-effective baseline\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n\n\n)\n\n\nAction\n: Establish your crew’s default LLM before optimizing individual agents.\nOptimize High-Impact Agents\nIdentify and Upgrade Key Agents:\nCopy\nAsk AI\n# Manager or coordination agents\n\n\nmanager_agent \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gemini-2.5-flash-preview-05-20\"\n), \n# Premium for coordination\n\n\n # ... rest of config\n\n\n)\n\n\n\n\n# Creative or customer-facing agents \n\n\ncontent_agent \n=\n Agent(\n\n\n role\n=\n\"Content Creator\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n), \n# Best for writing\n\n\n # ... rest of config\n\n\n)\n\n\nAction\n: Upgrade 20% of your agents that handle 80% of the complexity.\nValidate with Enterprise Testing\nOnce you deploy your agents to production:\n\n\nUse \nCrewAI Enterprise platform\n to A/B test your model selections\n\n\nRun multiple iterations with real inputs to measure consistency and performance\n\n\nCompare cost vs. performance across your optimized setup\n\n\nShare results with your team for collaborative decision-making\n\n\nAction\n: Replace guesswork with data-driven validation using the testing platform.\n\n\n​\nWhen to Use Different Model Types\n\n\nReasoning Models\nCreative Models\nEfficient Models\nOpen Source Models\nReasoning models become essential when tasks require genuine multi-step logical thinking, strategic planning, or high-level decision making that benefits from systematic analysis. These models excel when problems need to be broken down into components and analyzed systematically rather than handled through pattern matching or simple instruction following.\nConsider reasoning models for business strategy development, complex data analysis that requires drawing insights from multiple sources, multi-step problem solving where each step depends on previous analysis, and strategic planning tasks that require considering multiple variables and their interactions.\nHowever, reasoning models often come with higher costs and slower response times, so they’re best reserved for tasks where their sophisticated capabilities provide genuine value rather than being used for simple operations that don’t require complex reasoning.\nReasoning models become essential when tasks require genuine multi-step logical thinking, strategic planning, or high-level decision making that benefits from systematic analysis. These models excel when problems need to be broken down into components and analyzed systematically rather than handled through pattern matching or simple instruction following.\nConsider reasoning models for business strategy development, complex data analysis that requires drawing insights from multiple sources, multi-step problem solving where each step depends on previous analysis, and strategic planning tasks that require considering multiple variables and their interactions.\nHowever, reasoning models often come with higher costs and slower response times, so they’re best reserved for tasks where their sophisticated capabilities provide genuine value rather than being used for simple operations that don’t require complex reasoning.\nCreative models become valuable when content generation is the primary output and the quality, style, and engagement level of that content directly impact success. These models excel when writing quality and style matter significantly, creative ideation or brainstorming is needed, or brand voice and tone are important considerations.\nUse creative models for blog post writing and article creation, marketing copy that needs to engage and persuade, creative storytelling and narrative development, and brand communications where voice and tone are crucial. These models often understand nuance and context better than general purpose alternatives.\nCreative models may be less suitable for technical or analytical tasks where precision and factual accuracy are more important than engagement and style. They’re best used when the creative and communicative aspects of the output are primary success factors.\nEfficient models are ideal for high-frequency, routine operations where speed and cost optimization are priorities. These models work best when tasks have clear, well-defined parameters and don’t require sophisticated reasoning or creative capabilities.\nConsider efficient models for data processing and transformation tasks, simple formatting and organization operations, function calling and tool usage where precision matters more than sophistication, and high-volume operations where cost per operation is a significant factor.\nThe key with efficient models is ensuring that their capabilities align with task requirements. They can handle many routine operations effectively but may struggle with tasks requiring nuanced understanding, complex reasoning, or sophisticated content generation.\nOpen source models become attractive when budget constraints are significant, data privacy requirements exist, customization needs are important, or local deployment is required for operational or compliance reasons.\nConsider open source models for internal company tools where data privacy is paramount, privacy-sensitive applications that can’t use external APIs, cost-optimized deployments where per-token pricing is prohibitive, and situations requiring custom model modifications or fine-tuning.\nHowever, open source models require more technical expertise to deploy and maintain effectively. Consider the total cost of ownership including infrastructure, technical overhead, and ongoing maintenance when evaluating open source options.\n\n\n​\nCommon CrewAI Model Selection Pitfalls\n\n\nThe 'One Model Fits All' Trap\nThe Problem\n: Using the same LLM for all agents in a crew, regardless of their specific roles and responsibilities. This is often the default approach but rarely optimal.\nReal Example\n: Using GPT-4o for both a strategic planning manager and a data extraction agent. The manager needs reasoning capabilities worth the premium cost, but the data extractor could perform just as well with GPT-4o-mini at a fraction of the price.\nCrewAI Solution\n: Leverage agent-specific LLM configuration to match model capabilities with agent roles:\nCopy\nAsk AI\n# Strategic agent gets premium model\n\n\nmanager \n=\n Agent(\nrole\n=\n\"Strategy Manager\"\n, \nllm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n))\n\n\n\n\n# Processing agent gets efficient model \n\n\nprocessor \n=\n Agent(\nrole\n=\n\"Data Processor\"\n, \nllm\n=\nLLM(\nmodel\n=\n\"gpt-4o-mini\"\n))\n\n\nIgnoring Crew-Level vs Agent-Level LLM Hierarchy\nThe Problem\n: Not understanding how CrewAI’s LLM hierarchy works - crew LLM, manager LLM, and agent LLM settings can conflict or be poorly coordinated.\nReal Example\n: Setting a crew to use Claude, but having agents configured with GPT models, creating inconsistent behavior and unnecessary model switching overhead.\nCrewAI Solution\n: Plan your LLM hierarchy strategically:\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent1, agent2],\n\n\n tasks\n=\n[task1, task2],\n\n\n manager_llm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n), \n# For crew coordination\n\n\n process\n=\nProcess.hierarchical \n# When using manager_llm\n\n\n)\n\n\n\n\n# Agents inherit crew LLM unless specifically overridden\n\n\nagent1 \n=\n Agent(\nllm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n)) \n# Override for specific needs\n\n\nFunction Calling Model Mismatch\nThe Problem\n: Choosing models based on general capabilities while ignoring function calling performance for tool-heavy CrewAI workflows.\nReal Example\n: Selecting a creative-focused model for an agent that primarily needs to call APIs, search tools, or process structured data. The agent struggles with tool parameter extraction and reliable function calls.\nCrewAI Solution\n: Prioritize function calling capabilities for tool-heavy agents:\nCopy\nAsk AI\n# For agents that use many tools\n\n\ntool_agent \n=\n Agent(\n\n\n role\n=\n\"API Integration Specialist\"\n,\n\n\n tools\n=\n[search_tool, api_tool, data_tool],\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n), \n# Excellent function calling\n\n\n # OR\n\n\n llm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n) \n# Also strong with tools\n\n\n)\n\n\nPremature Optimization Without Testing\nThe Problem\n: Making complex model selection decisions based on theoretical performance without validating with actual CrewAI workflows and tasks.\nReal Example\n: Implementing elaborate model switching logic based on task types without testing if the performance gains justify the operational complexity.\nCrewAI Solution\n: Start simple, then optimize based on real performance data:\nCopy\nAsk AI\n# Start with this\n\n\ncrew \n=\n Crew(\nagents\n=\n[\n...\n], \ntasks\n=\n[\n...\n], \nllm\n=\nLLM(\nmodel\n=\n\"gpt-4o-mini\"\n))\n\n\n\n\n# Test performance, then optimize specific agents as needed\n\n\n# Use Enterprise platform testing to validate improvements\n\n\nOverlooking Context and Memory Limitations\nThe Problem\n: Not considering how model context windows interact with CrewAI’s memory and context sharing between agents.\nReal Example\n: Using a short-context model for agents that need to maintain conversation history across multiple task iterations, or in crews with extensive agent-to-agent communication.\nCrewAI Solution\n: Match context capabilities to crew communication patterns.\n\n\n​\nTesting and Iteration Strategy\n\n\nStart Simple\nBegin with reliable, general-purpose models that are well-understood and widely supported. This provides a stable foundation for understanding your specific requirements and performance expectations before optimizing for specialized needs.\nMeasure What Matters\nDevelop metrics that align with your specific use case and business requirements rather than relying solely on general benchmarks. Focus on measuring outcomes that directly impact your success rather than theoretical performance indicators.\nIterate Based on Results\nMake model changes based on observed performance in your specific context rather than theoretical considerations or general recommendations. Real-world performance often differs significantly from benchmark results or general reputation.\nConsider Total Cost\nEvaluate the complete cost of ownership including model costs, development time, maintenance overhead, and operational complexity. The cheapest model per token may not be the most cost-effective choice when considering all factors.\n\n\nFocus on understanding your requirements first, then select models that best match those needs. The best LLM choice is the one that consistently delivers the results you need within your operational constraints.\n\n\n​\nEnterprise-Grade Model Validation\n\n\nFor teams serious about optimizing their LLM selection, the \nCrewAI Enterprise platform\n provides sophisticated testing capabilities that go far beyond basic CLI testing. The platform enables comprehensive model evaluation that helps you make data-driven decisions about your LLM strategy.\n\n\n\n\nAdvanced Testing Features:\n\n\n\n\n\n\nMulti-Model Comparison\n: Test multiple LLMs simultaneously across the same tasks and inputs. Compare performance between GPT-4o, Claude, Llama, Groq, Cerebras, and other leading models in parallel to identify the best fit for your specific use case.\n\n\n\n\n\n\nStatistical Rigor\n: Configure multiple iterations with consistent inputs to measure reliability and performance variance. This helps identify models that not only perform well but do so consistently across runs.\n\n\n\n\n\n\nReal-World Validation\n: Use your actual crew inputs and scenarios rather than synthetic benchmarks. The platform allows you to test with your specific industry context, company information, and real use cases for more accurate evaluation.\n\n\n\n\n\n\nComprehensive Analytics\n: Access detailed performance metrics, execution times, and cost analysis across all tested models. This enables data-driven decision making rather than relying on general model reputation or theoretical capabilities.\n\n\n\n\n\n\nTeam Collaboration\n: Share testing results and model performance data across your team, enabling collaborative decision-making and consistent model selection strategies across projects.\n\n\n\n\n\n\nGo to \napp.crewai.com\n to get started!\n\n\nThe Enterprise platform transforms model selection from guesswork into a data-driven process, enabling you to validate the principles in this guide with your actual use cases and requirements.\n\n\n​\nKey Principles Summary\n\n\nTask-Driven Selection\nChoose models based on what the task actually requires, not theoretical capabilities or general reputation.\nCapability Matching\nAlign model strengths with agent roles and responsibilities for optimal performance.\nStrategic Consistency\nMaintain coherent model selection strategy across related components and workflows.\nPractical Testing\nValidate choices through real-world usage rather than benchmarks alone.\nIterative Improvement\nStart simple and optimize based on actual performance and needs.\nOperational Balance\nBalance performance requirements with cost and complexity constraints.\n\n\nRemember: The best LLM choice is the one that consistently delivers the results you need within your operational constraints. Focus on understanding your requirements first, then select models that best match those needs.\n\n\n​\nCurrent Model Landscape (June 2025)\n\n\nSnapshot in Time\n: The following model rankings represent current leaderboard standings as of June 2025, compiled from \nLMSys Arena\n, \nArtificial Analysis\n, and other leading benchmarks. LLM performance, availability, and pricing change rapidly. Always conduct your own evaluations with your specific use cases and data.\n\n\n​\nLeading Models by Category\n\n\nThe tables below show a representative sample of current top-performing models across different categories, with guidance on their suitability for CrewAI agents:\n\n\nThese tables/metrics showcase selected leading models in each category and are not exhaustive. Many excellent models exist beyond those listed here. The goal is to illustrate the types of capabilities to look for rather than provide a complete catalog.\n\n\nReasoning & Planning\nCoding & Technical\nSpeed & Efficiency\nBalanced Performance\nBest for Manager LLMs and Complex Analysis\nModel\nIntelligence Score\nCost ($/M tokens)\nSpeed\nBest Use in CrewAI\no3\n70\n$17.50\nFast\nManager LLM for complex multi-agent coordination\nGemini 2.5 Pro\n69\n$3.44\nFast\nStrategic planning agents, research coordination\nDeepSeek R1\n68\n$0.96\nModerate\nCost-effective reasoning for budget-conscious crews\nClaude 4 Sonnet\n53\n$6.00\nFast\nAnalysis agents requiring nuanced understanding\nQwen3 235B (Reasoning)\n62\n$2.63\nModerate\nOpen-source alternative for reasoning tasks\nThese models excel at multi-step reasoning and are ideal for agents that need to develop strategies, coordinate other agents, or analyze complex information.\nBest for Manager LLMs and Complex Analysis\nModel\nIntelligence Score\nCost ($/M tokens)\nSpeed\nBest Use in CrewAI\no3\n70\n$17.50\nFast\nManager LLM for complex multi-agent coordination\nGemini 2.5 Pro\n69\n$3.44\nFast\nStrategic planning agents, research coordination\nDeepSeek R1\n68\n$0.96\nModerate\nCost-effective reasoning for budget-conscious crews\nClaude 4 Sonnet\n53\n$6.00\nFast\nAnalysis agents requiring nuanced understanding\nQwen3 235B (Reasoning)\n62\n$2.63\nModerate\nOpen-source alternative for reasoning tasks\nThese models excel at multi-step reasoning and are ideal for agents that need to develop strategies, coordinate other agents, or analyze complex information.\nBest for Development and Tool-Heavy Workflows\nModel\nCoding Performance\nTool Use Score\nCost ($/M tokens)\nBest Use in CrewAI\nClaude 4 Sonnet\nExcellent\n72.7%\n$6.00\nPrimary coding agent, technical documentation\nClaude 4 Opus\nExcellent\n72.5%\n$30.00\nComplex software architecture, code review\nDeepSeek V3\nVery Good\nHigh\n$0.48\nCost-effective coding for routine development\nQwen2.5 Coder 32B\nVery Good\nMedium\n$0.15\nBudget-friendly coding agent\nLlama 3.1 405B\nGood\n81.1%\n$3.50\nFunction calling LLM for tool-heavy workflows\nThese models are optimized for code generation, debugging, and technical problem-solving, making them ideal for development-focused crews.\nBest for High-Throughput and Real-Time Applications\nModel\nSpeed (tokens/s)\nLatency (TTFT)\nCost ($/M tokens)\nBest Use in CrewAI\nLlama 4 Scout\n2,600\n0.33s\n$0.27\nHigh-volume processing agents\nGemini 2.5 Flash\n376\n0.30s\n$0.26\nReal-time response agents\nDeepSeek R1 Distill\n383\nVariable\n$0.04\nCost-optimized high-speed processing\nLlama 3.3 70B\n2,500\n0.52s\n$0.60\nBalanced speed and capability\nNova Micro\nHigh\n0.30s\n$0.04\nSimple, fast task execution\nThese models prioritize speed and efficiency, perfect for agents handling routine operations or requiring quick responses. \nPro tip\n: Pairing these models with fast inference providers like Groq can achieve even better performance, especially for open-source models like Llama.\nBest All-Around Models for General Crews\nModel\nOverall Score\nVersatility\nCost ($/M tokens)\nBest Use in CrewAI\nGPT-4.1\n53\nExcellent\n$3.50\nGeneral-purpose crew LLM\nClaude 3.7 Sonnet\n48\nVery Good\n$6.00\nBalanced reasoning and creativity\nGemini 2.0 Flash\n48\nGood\n$0.17\nCost-effective general use\nLlama 4 Maverick\n51\nGood\n$0.37\nOpen-source general purpose\nQwen3 32B\n44\nGood\n$1.23\nBudget-friendly versatility\nThese models offer good performance across multiple dimensions, suitable for crews with diverse task requirements.\n\n\n​\nSelection Framework for Current Models\n\n\nHigh-Performance Crews\nWhen performance is the priority\n: Use top-tier models like \no3\n, \nGemini 2.5 Pro\n, or \nClaude 4 Sonnet\n for manager LLMs and critical agents. These models excel at complex reasoning and coordination but come with higher costs.\nStrategy\n: Implement a multi-model approach where premium models handle strategic thinking while efficient models handle routine operations.\nCost-Conscious Crews\nWhen budget is a primary constraint\n: Focus on models like \nDeepSeek R1\n, \nLlama 4 Scout\n, or \nGemini 2.0 Flash\n. These provide strong performance at significantly lower costs.\nStrategy\n: Use cost-effective models for most agents, reserving premium models only for the most critical decision-making roles.\nSpecialized Workflows\nFor specific domain expertise\n: Choose models optimized for your primary use case. \nClaude 4\n series for coding, \nGemini 2.5 Pro\n for research, \nLlama 405B\n for function calling.\nStrategy\n: Select models based on your crew’s primary function, ensuring the core capability aligns with model strengths.\nEnterprise & Privacy\nFor data-sensitive operations\n: Consider open-source models like \nLlama 4\n series, \nDeepSeek V3\n, or \nQwen3\n that can be deployed locally while maintaining competitive performance.\nStrategy\n: Deploy open-source models on private infrastructure, accepting potential performance trade-offs for data control.\n\n\n​\nKey Considerations for Model Selection\n\n\n\n\n\n\nPerformance Trends\n: The current landscape shows strong competition between reasoning-focused models (o3, Gemini 2.5 Pro) and balanced models (Claude 4, GPT-4.1). Specialized models like DeepSeek R1 offer excellent cost-performance ratios.\n\n\n\n\n\n\nSpeed vs. Intelligence Trade-offs\n: Models like Llama 4 Scout prioritize speed (2,600 tokens/s) while maintaining reasonable intelligence, whereas models like o3 maximize reasoning capability at the cost of speed and price.\n\n\n\n\n\n\nOpen Source Viability\n: The gap between open-source and proprietary models continues to narrow, with models like Llama 4 Maverick and DeepSeek V3 offering competitive performance at attractive price points. Fast inference providers particularly shine with open-source models, often delivering better speed-to-cost ratios than proprietary alternatives.\n\n\n\n\n\n\nTesting is Essential\n: Leaderboard rankings provide general guidance, but your specific use case, prompting style, and evaluation criteria may produce different results. Always test candidate models with your actual tasks and data before making final decisions.\n\n\n​\nPractical Implementation Strategy\n\n\n1\nStart with Proven Models\nBegin with well-established models like \nGPT-4.1\n, \nClaude 3.7 Sonnet\n, or \nGemini 2.0 Flash\n that offer good performance across multiple dimensions and have extensive real-world validation.\n2\nIdentify Specialized Needs\nDetermine if your crew has specific requirements (coding, reasoning, speed) that would benefit from specialized models like \nClaude 4 Sonnet\n for development or \no3\n for complex analysis. For speed-critical applications, consider fast inference providers like \nGroq\n alongside model selection.\n3\nImplement Multi-Model Strategy\nUse different models for different agents based on their roles. High-capability models for managers and complex tasks, efficient models for routine operations.\n4\nMonitor and Optimize\nTrack performance metrics relevant to your use case and be prepared to adjust model selections as new models are released or pricing changes.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOverview\nConditional Tasks\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nThe CrewAI Approach to LLM Selection\nQuick Decision Framework\nCore Selection Framework\na. Task-First Thinking\nb. Model Capability Mapping\nStrategic Configuration Patterns\na. Multi-Model Approach\nb. Component-Specific Selection\nTask Definition Framework\na. Focus on Clarity Over Complexity\nb. Task Sequencing Strategy\nOptimizing Agent Configuration for LLM Performance\na. Role-Driven LLM Selection\nb. Backstory as Model Context Amplifier\nc. Holistic Agent-LLM Optimization\nPractical Implementation Checklist\nWhen to Use Different Model Types\nCommon CrewAI Model Selection Pitfalls\nTesting and Iteration Strategy\nEnterprise-Grade Model Validation\nKey Principles Summary\nCurrent Model Landscape (June 2025)\nLeading Models by Category\nSelection Framework for Current Models\nKey Considerations for Model Selection\nPractical Implementation Strategy\nLearn\nStrategic LLM Selection Guide\nCopy page\nStrategic framework for choosing the right LLM for your CrewAI AI agents and writing effective task and agent definitions\n​\nThe CrewAI Approach to LLM Selection\n\n\nRather than prescriptive model recommendations, we advocate for a \nthinking framework\n that helps you make informed decisions based on your specific use case, constraints, and requirements. The LLM landscape evolves rapidly, with new models emerging regularly and existing ones being updated frequently. What matters most is developing a systematic approach to evaluation that remains relevant regardless of which specific models are available.\n\n\nThis guide focuses on strategic thinking rather than specific model recommendations, as the LLM landscape evolves rapidly.\n\n\n​\nQuick Decision Framework\n\n\n1\nAnalyze Your Tasks\nBegin by deeply understanding what your tasks actually require. Consider the cognitive complexity involved, the depth of reasoning needed, the format of expected outputs, and the amount of context the model will need to process. This foundational analysis will guide every subsequent decision.\n2\nMap Model Capabilities\nOnce you understand your requirements, map them to model strengths. Different model families excel at different types of work; some are optimized for reasoning and analysis, others for creativity and content generation, and others for speed and efficiency.\n3\nConsider Constraints\nFactor in your real-world operational constraints including budget limitations, latency requirements, data privacy needs, and infrastructure capabilities. The theoretically best model may not be the practically best choice for your situation.\n4\nTest and Iterate\nStart with reliable, well-understood models and optimize based on actual performance in your specific use case. Real-world results often differ from theoretical benchmarks, so empirical testing is crucial.\n\n\n​\nCore Selection Framework\n\n\n​\na. Task-First Thinking\n\n\nThe most critical step in LLM selection is understanding what your task actually demands. Too often, teams select models based on general reputation or benchmark scores without carefully analyzing their specific requirements. This approach leads to either over-engineering simple tasks with expensive, complex models, or under-powering sophisticated work with models that lack the necessary capabilities.\n\n\nReasoning Complexity\nOutput Requirements\nContext Needs\n\n\n\n\nSimple Tasks\n represent the majority of everyday AI work and include basic instruction following, straightforward data processing, and simple formatting operations. These tasks typically have clear inputs and outputs with minimal ambiguity. The cognitive load is low, and the model primarily needs to follow explicit instructions rather than engage in complex reasoning.\n\n\n\n\n\n\nComplex Tasks\n require multi-step reasoning, strategic thinking, and the ability to handle ambiguous or incomplete information. These might involve analyzing multiple data sources, developing comprehensive strategies, or solving problems that require breaking down into smaller components. The model needs to maintain context across multiple reasoning steps and often must make inferences that aren’t explicitly stated.\n\n\n\n\n\n\nCreative Tasks\n demand a different type of cognitive capability focused on generating novel, engaging, and contextually appropriate content. This includes storytelling, marketing copy creation, and creative problem-solving. The model needs to understand nuance, tone, and audience while producing content that feels authentic and engaging rather than formulaic.\n\n\n\n\n\n\n\n\nSimple Tasks\n represent the majority of everyday AI work and include basic instruction following, straightforward data processing, and simple formatting operations. These tasks typically have clear inputs and outputs with minimal ambiguity. The cognitive load is low, and the model primarily needs to follow explicit instructions rather than engage in complex reasoning.\n\n\n\n\n\n\nComplex Tasks\n require multi-step reasoning, strategic thinking, and the ability to handle ambiguous or incomplete information. These might involve analyzing multiple data sources, developing comprehensive strategies, or solving problems that require breaking down into smaller components. The model needs to maintain context across multiple reasoning steps and often must make inferences that aren’t explicitly stated.\n\n\n\n\n\n\nCreative Tasks\n demand a different type of cognitive capability focused on generating novel, engaging, and contextually appropriate content. This includes storytelling, marketing copy creation, and creative problem-solving. The model needs to understand nuance, tone, and audience while producing content that feels authentic and engaging rather than formulaic.\n\n\n\n\n\n\n\n\nStructured Data\n tasks require precision and consistency in format adherence. When working with JSON, XML, or database formats, the model must reliably produce syntactically correct output that can be programmatically processed. These tasks often have strict validation requirements and little tolerance for format errors, making reliability more important than creativity.\n\n\n\n\n\n\nCreative Content\n outputs demand a balance of technical competence and creative flair. The model needs to understand audience, tone, and brand voice while producing content that engages readers and achieves specific communication goals. Quality here is often subjective and requires models that can adapt their writing style to different contexts and purposes.\n\n\n\n\n\n\nTechnical Content\n sits between structured data and creative content, requiring both precision and clarity. Documentation, code generation, and technical analysis need to be accurate and comprehensive while remaining accessible to the intended audience. The model must understand complex technical concepts and communicate them effectively.\n\n\n\n\n\n\n\n\nShort Context\n scenarios involve focused, immediate tasks where the model needs to process limited information quickly. These are often transactional interactions where speed and efficiency matter more than deep understanding. The model doesn’t need to maintain extensive conversation history or process large documents.\n\n\n\n\n\n\nLong Context\n requirements emerge when working with substantial documents, extended conversations, or complex multi-part tasks. The model needs to maintain coherence across thousands of tokens while referencing earlier information accurately. This capability becomes crucial for document analysis, comprehensive research, and sophisticated dialogue systems.\n\n\n\n\n\n\nVery Long Context\n scenarios push the boundaries of what’s currently possible, involving massive document processing, extensive research synthesis, or complex multi-session interactions. These use cases require models specifically designed for extended context handling and often involve trade-offs between context length and processing speed.\n\n\n\n\n\n\n​\nb. Model Capability Mapping\n\n\nUnderstanding model capabilities requires looking beyond marketing claims and benchmark scores to understand the fundamental strengths and limitations of different model architectures and training approaches.\n\n\nReasoning Models\nReasoning models represent a specialized category designed specifically for complex, multi-step thinking tasks. These models excel when problems require careful analysis, strategic planning, or systematic problem decomposition. They typically employ techniques like chain-of-thought reasoning or tree-of-thought processing to work through complex problems step by step.\nThe strength of reasoning models lies in their ability to maintain logical consistency across extended reasoning chains and to break down complex problems into manageable components. They’re particularly valuable for strategic planning, complex analysis, and situations where the quality of reasoning matters more than speed of response.\nHowever, reasoning models often come with trade-offs in terms of speed and cost. They may also be less suitable for creative tasks or simple operations where their sophisticated reasoning capabilities aren’t needed. Consider these models when your tasks involve genuine complexity that benefits from systematic, step-by-step analysis.\nGeneral Purpose Models\nGeneral purpose models offer the most balanced approach to LLM selection, providing solid performance across a wide range of tasks without extreme specialization in any particular area. These models are trained on diverse datasets and optimized for versatility rather than peak performance in specific domains.\nThe primary advantage of general purpose models is their reliability and predictability across different types of work. They handle most standard business tasks competently, from research and analysis to content creation and data processing. This makes them excellent choices for teams that need consistent performance across varied workflows.\nWhile general purpose models may not achieve the peak performance of specialized alternatives in specific domains, they offer operational simplicity and reduced complexity in model management. They’re often the best starting point for new projects, allowing teams to understand their specific needs before potentially optimizing with more specialized models.\nFast & Efficient Models\nFast and efficient models prioritize speed, cost-effectiveness, and resource efficiency over sophisticated reasoning capabilities. These models are optimized for high-throughput scenarios where quick responses and low operational costs are more important than nuanced understanding or complex reasoning.\nThese models excel in scenarios involving routine operations, simple data processing, function calling, and high-volume tasks where the cognitive requirements are relatively straightforward. They’re particularly valuable for applications that need to process many requests quickly or operate within tight budget constraints.\nThe key consideration with efficient models is ensuring that their capabilities align with your task requirements. While they can handle many routine operations effectively, they may struggle with tasks requiring nuanced understanding, complex reasoning, or sophisticated content generation. They’re best used for well-defined, routine operations where speed and cost matter more than sophistication.\nCreative Models\nCreative models are specifically optimized for content generation, writing quality, and creative thinking tasks. These models typically excel at understanding nuance, tone, and style while producing engaging, contextually appropriate content that feels natural and authentic.\nThe strength of creative models lies in their ability to adapt writing style to different audiences, maintain consistent voice and tone, and generate content that engages readers effectively. They often perform better on tasks involving storytelling, marketing copy, brand communications, and other content where creativity and engagement are primary goals.\nWhen selecting creative models, consider not just their ability to generate text, but their understanding of audience, context, and purpose. The best creative models can adapt their output to match specific brand voices, target different audience segments, and maintain consistency across extended content pieces.\nOpen Source Models\nOpen source models offer unique advantages in terms of cost control, customization potential, data privacy, and deployment flexibility. These models can be run locally or on private infrastructure, providing complete control over data handling and model behavior.\nThe primary benefits of open source models include elimination of per-token costs, ability to fine-tune for specific use cases, complete data privacy, and independence from external API providers. They’re particularly valuable for organizations with strict data privacy requirements, budget constraints, or specific customization needs.\nHowever, open source models require more technical expertise to deploy and maintain effectively. Teams need to consider infrastructure costs, model management complexity, and the ongoing effort required to keep models updated and optimized. The total cost of ownership may be higher than cloud-based alternatives when factoring in technical overhead.\n\n\n​\nStrategic Configuration Patterns\n\n\n​\na. Multi-Model Approach\n\n\nUse different models for different purposes within the same crew to optimize both performance and cost.\n\n\nThe most sophisticated CrewAI implementations often employ multiple models strategically, assigning different models to different agents based on their specific roles and requirements. This approach allows teams to optimize for both performance and cost by using the most appropriate model for each type of work.\n\n\nPlanning agents benefit from reasoning models that can handle complex strategic thinking and multi-step analysis. These agents often serve as the “brain” of the operation, developing strategies and coordinating other agents’ work. Content agents, on the other hand, perform best with creative models that excel at writing quality and audience engagement. Processing agents handling routine operations can use efficient models that prioritize speed and cost-effectiveness.\n\n\nExample: Research and Analysis Crew\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, \nLLM\n\n\n\n\n# High-capability reasoning model for strategic planning\n\n\nmanager_llm \n=\n LLM(\nmodel\n=\n\"gemini-2.5-flash-preview-05-20\"\n, \ntemperature\n=\n0.1\n)\n\n\n\n\n# Creative model for content generation\n\n\ncontent_llm \n=\n LLM(\nmodel\n=\n\"claude-3-5-sonnet-20241022\"\n, \ntemperature\n=\n0.7\n)\n\n\n\n\n# Efficient model for data processing\n\n\nprocessing_llm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n)\n\n\n\n\nresearch_manager \n=\n Agent(\n\n\n role\n=\n\"Research Strategy Manager\"\n,\n\n\n goal\n=\n\"Develop comprehensive research strategies and coordinate team efforts\"\n,\n\n\n backstory\n=\n\"Expert research strategist with deep analytical capabilities\"\n,\n\n\n llm\n=\nmanager_llm, \n# High-capability model for complex reasoning\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ncontent_writer \n=\n Agent(\n\n\n role\n=\n\"Research Content Writer\"\n,\n\n\n goal\n=\n\"Transform research findings into compelling, well-structured reports\"\n,\n\n\n backstory\n=\n\"Skilled writer who excels at making complex topics accessible\"\n,\n\n\n llm\n=\ncontent_llm, \n# Creative model for engaging content\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ndata_processor \n=\n Agent(\n\n\n role\n=\n\"Data Analysis Specialist\"\n, \n\n\n goal\n=\n\"Extract and organize key data points from research sources\"\n,\n\n\n backstory\n=\n\"Detail-oriented analyst focused on accuracy and efficiency\"\n,\n\n\n llm\n=\nprocessing_llm, \n# Fast, cost-effective model for routine tasks\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_manager, content_writer, data_processor],\n\n\n tasks\n=\n[\n...\n], \n# Your specific tasks\n\n\n manager_llm\n=\nmanager_llm, \n# Manager uses the reasoning model\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nThe key to successful multi-model implementation is understanding how different agents interact and ensuring that model capabilities align with agent responsibilities. This requires careful planning but can result in significant improvements in both output quality and operational efficiency.\n\n\n​\nb. Component-Specific Selection\n\n\nManager LLM\nFunction Calling LLM\nAgent-Specific Overrides\nThe manager LLM plays a crucial role in hierarchical CrewAI processes, serving as the coordination point for multiple agents and tasks. This model needs to excel at delegation, task prioritization, and maintaining context across multiple concurrent operations.\nEffective manager LLMs require strong reasoning capabilities to make good delegation decisions, consistent performance to ensure predictable coordination, and excellent context management to track the state of multiple agents simultaneously. The model needs to understand the capabilities and limitations of different agents while optimizing task allocation for efficiency and quality.\nCost considerations are particularly important for manager LLMs since they’re involved in every operation. The model needs to provide sufficient capability for effective coordination while remaining cost-effective for frequent use. This often means finding models that offer good reasoning capabilities without the premium pricing of the most sophisticated options.\nThe manager LLM plays a crucial role in hierarchical CrewAI processes, serving as the coordination point for multiple agents and tasks. This model needs to excel at delegation, task prioritization, and maintaining context across multiple concurrent operations.\nEffective manager LLMs require strong reasoning capabilities to make good delegation decisions, consistent performance to ensure predictable coordination, and excellent context management to track the state of multiple agents simultaneously. The model needs to understand the capabilities and limitations of different agents while optimizing task allocation for efficiency and quality.\nCost considerations are particularly important for manager LLMs since they’re involved in every operation. The model needs to provide sufficient capability for effective coordination while remaining cost-effective for frequent use. This often means finding models that offer good reasoning capabilities without the premium pricing of the most sophisticated options.\nFunction calling LLMs handle tool usage across all agents, making them critical for crews that rely heavily on external tools and APIs. These models need to excel at understanding tool capabilities, extracting parameters accurately, and handling tool responses effectively.\nThe most important characteristics for function calling LLMs are precision and reliability rather than creativity or sophisticated reasoning. The model needs to consistently extract the correct parameters from natural language requests and handle tool responses appropriately. Speed is also important since tool usage often involves multiple round trips that can impact overall performance.\nMany teams find that specialized function calling models or general purpose models with strong tool support work better than creative or reasoning-focused models for this role. The key is ensuring that the model can reliably bridge the gap between natural language instructions and structured tool calls.\nIndividual agents can override crew-level LLM settings when their specific needs differ significantly from the general crew requirements. This capability allows for fine-tuned optimization while maintaining operational simplicity for most agents.\nConsider agent-specific overrides when an agent’s role requires capabilities that differ substantially from other crew members. For example, a creative writing agent might benefit from a model optimized for content generation, while a data analysis agent might perform better with a reasoning-focused model.\nThe challenge with agent-specific overrides is balancing optimization with operational complexity. Each additional model adds complexity to deployment, monitoring, and cost management. Teams should focus overrides on agents where the performance improvement justifies the additional complexity.\n\n\n​\nTask Definition Framework\n\n\n​\na. Focus on Clarity Over Complexity\n\n\nEffective task definition is often more important than model selection in determining the quality of CrewAI outputs. Well-defined tasks provide clear direction and context that enable even modest models to perform well, while poorly defined tasks can cause even sophisticated models to produce unsatisfactory results.\n\n\nEffective Task Descriptions\nThe best task descriptions strike a balance between providing sufficient detail and maintaining clarity. They should define the specific objective clearly enough that there’s no ambiguity about what success looks like, while explaining the approach or methodology in enough detail that the agent understands how to proceed.\nEffective task descriptions include relevant context and constraints that help the agent understand the broader purpose and any limitations they need to work within. They break complex work into focused steps that can be executed systematically, rather than presenting overwhelming, multi-faceted objectives that are difficult to approach systematically.\nCommon mistakes include being too vague about objectives, failing to provide necessary context, setting unclear success criteria, or combining multiple unrelated tasks into a single description. The goal is to provide enough information for the agent to succeed while maintaining focus on a single, clear objective.\nExpected Output Guidelines\nExpected output guidelines serve as a contract between the task definition and the agent, clearly specifying what the deliverable should look like and how it will be evaluated. These guidelines should describe both the format and structure needed, as well as the key elements that must be included for the output to be considered complete.\nThe best output guidelines provide concrete examples of quality indicators and define completion criteria clearly enough that both the agent and human reviewers can assess whether the task has been completed successfully. This reduces ambiguity and helps ensure consistent results across multiple task executions.\nAvoid generic output descriptions that could apply to any task, missing format specifications that leave agents guessing about structure, unclear quality standards that make evaluation difficult, or failing to provide examples or templates that help agents understand expectations.\n\n\n​\nb. Task Sequencing Strategy\n\n\nSequential Dependencies\nParallel Execution\nSequential task dependencies are essential when tasks build upon previous outputs, information flows from one task to another, or quality depends on the completion of prerequisite work. This approach ensures that each task has access to the information and context it needs to succeed.\nImplementing sequential dependencies effectively requires using the context parameter to chain related tasks, building complexity gradually through task progression, and ensuring that each task produces outputs that serve as meaningful inputs for subsequent tasks. The goal is to maintain logical flow between dependent tasks while avoiding unnecessary bottlenecks.\nSequential dependencies work best when there’s a clear logical progression from one task to another and when the output of one task genuinely improves the quality or feasibility of subsequent tasks. However, they can create bottlenecks if not managed carefully, so it’s important to identify which dependencies are truly necessary versus those that are merely convenient.\nSequential task dependencies are essential when tasks build upon previous outputs, information flows from one task to another, or quality depends on the completion of prerequisite work. This approach ensures that each task has access to the information and context it needs to succeed.\nImplementing sequential dependencies effectively requires using the context parameter to chain related tasks, building complexity gradually through task progression, and ensuring that each task produces outputs that serve as meaningful inputs for subsequent tasks. The goal is to maintain logical flow between dependent tasks while avoiding unnecessary bottlenecks.\nSequential dependencies work best when there’s a clear logical progression from one task to another and when the output of one task genuinely improves the quality or feasibility of subsequent tasks. However, they can create bottlenecks if not managed carefully, so it’s important to identify which dependencies are truly necessary versus those that are merely convenient.\nParallel execution becomes valuable when tasks are independent of each other, time efficiency is important, or different expertise areas are involved that don’t require coordination. This approach can significantly reduce overall execution time while allowing specialized agents to work on their areas of strength simultaneously.\nSuccessful parallel execution requires identifying tasks that can truly run independently, grouping related but separate work streams effectively, and planning for result integration when parallel tasks need to be combined into a final deliverable. The key is ensuring that parallel tasks don’t create conflicts or redundancies that reduce overall quality.\nConsider parallel execution when you have multiple independent research streams, different types of analysis that don’t depend on each other, or content creation tasks that can be developed simultaneously. However, be mindful of resource allocation and ensure that parallel execution doesn’t overwhelm your available model capacity or budget.\n\n\n​\nOptimizing Agent Configuration for LLM Performance\n\n\n​\na. Role-Driven LLM Selection\n\n\nGeneric agent roles make it impossible to select the right LLM. Specific roles enable targeted model optimization.\n\n\nThe specificity of your agent roles directly determines which LLM capabilities matter most for optimal performance. This creates a strategic opportunity to match precise model strengths with agent responsibilities.\n\n\nGeneric vs. Specific Role Impact on LLM Choice:\n\n\nWhen defining roles, think about the specific domain knowledge, working style, and decision-making frameworks that would be most valuable for the tasks the agent will handle. The more specific and contextual the role definition, the better the model can embody that role effectively.\n\n\nCopy\nAsk AI\n# ✅ Specific role - clear LLM requirements\n\n\nspecific_agent \n=\n Agent(\n\n\n role\n=\n\"SaaS Revenue Operations Analyst\"\n, \n# Clear domain expertise needed\n\n\n goal\n=\n\"Analyze recurring revenue metrics and identify growth opportunities\"\n,\n\n\n backstory\n=\n\"Specialist in SaaS business models with deep understanding of ARR, churn, and expansion revenue\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n) \n# Reasoning model justified for complex analysis\n\n\n)\n\n\n\n\nRole-to-Model Mapping Strategy:\n\n\n\n\n“Research Analyst”\n → Reasoning model (GPT-4o, Claude Sonnet) for complex analysis\n\n\n“Content Editor”\n → Creative model (Claude, GPT-4o) for writing quality\n\n\n“Data Processor”\n → Efficient model (GPT-4o-mini, Gemini Flash) for structured tasks\n\n\n“API Coordinator”\n → Function-calling optimized model (GPT-4o, Claude) for tool usage\n\n\n\n\n​\nb. Backstory as Model Context Amplifier\n\n\nStrategic backstories multiply your chosen LLM’s effectiveness by providing domain-specific context that generic prompting cannot achieve.\n\n\nA well-crafted backstory transforms your LLM choice from generic capability to specialized expertise. This is especially crucial for cost optimization - a well-contextualized efficient model can outperform a premium model without proper context.\n\n\nContext-Driven Performance Example:\n\n\nCopy\nAsk AI\n# Context amplifies model effectiveness\n\n\ndomain_expert \n=\n Agent(\n\n\n role\n=\n\"B2B SaaS Marketing Strategist\"\n,\n\n\n goal\n=\n\"Develop comprehensive go-to-market strategies for enterprise software\"\n,\n\n\n backstory\n=\n\"\"\"\n\n\n You have 10+ years of experience scaling B2B SaaS companies from Series A to IPO. \n\n\n You understand the nuances of enterprise sales cycles, the importance of product-market \n\n\n fit in different verticals, and how to balance growth metrics with unit economics. \n\n\n You've worked with companies like Salesforce, HubSpot, and emerging unicorns, giving \n\n\n you perspective on both established and disruptive go-to-market strategies.\n\n\n \"\"\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n, \ntemperature\n=\n0.3\n) \n# Balanced creativity with domain knowledge\n\n\n)\n\n\n\n\n# This context enables Claude to perform like a domain expert\n\n\n# Without it, even it would produce generic marketing advice\n\n\n\n\nBackstory Elements That Enhance LLM Performance:\n\n\n\n\nDomain Experience\n: “10+ years in enterprise SaaS sales”\n\n\nSpecific Expertise\n: “Specializes in technical due diligence for Series B+ rounds”\n\n\nWorking Style\n: “Prefers data-driven decisions with clear documentation”\n\n\nQuality Standards\n: “Insists on citing sources and showing analytical work”\n\n\n\n\n​\nc. Holistic Agent-LLM Optimization\n\n\nThe most effective agent configurations create synergy between role specificity, backstory depth, and LLM selection. Each element reinforces the others to maximize model performance.\n\n\nOptimization Framework:\n\n\nCopy\nAsk AI\n# Example: Technical Documentation Agent\n\n\ntech_writer \n=\n Agent(\n\n\n role\n=\n\"API Documentation Specialist\"\n, \n# Specific role for clear LLM requirements\n\n\n goal\n=\n\"Create comprehensive, developer-friendly API documentation\"\n,\n\n\n backstory\n=\n\"\"\"\n\n\n You're a technical writer with 8+ years documenting REST APIs, GraphQL endpoints, \n\n\n and SDK integration guides. You've worked with developer tools companies and \n\n\n understand what developers need: clear examples, comprehensive error handling, \n\n\n and practical use cases. You prioritize accuracy and usability over marketing fluff.\n\n\n \"\"\"\n,\n\n\n llm\n=\nLLM(\n\n\n model\n=\n\"claude-3-5-sonnet\"\n, \n# Excellent for technical writing\n\n\n temperature\n=\n0.1\n # Low temperature for accuracy\n\n\n ),\n\n\n tools\n=\n[code_analyzer_tool, api_scanner_tool],\n\n\n verbose\n=\nTrue\n \n\n\n)\n\n\n\n\nAlignment Checklist:\n\n\n\n\n✅ \nRole Specificity\n: Clear domain and responsibilities\n\n\n✅ \nLLM Match\n: Model strengths align with role requirements\n\n\n✅ \nBackstory Depth\n: Provides domain context the LLM can leverage\n\n\n✅ \nTool Integration\n: Tools support the agent’s specialized function\n\n\n✅ \nParameter Tuning\n: Temperature and settings optimize for role needs\n\n\n\n\nThe key is creating agents where every configuration choice reinforces your LLM selection strategy, maximizing performance while optimizing costs.\n\n\n​\nPractical Implementation Checklist\n\n\nRather than repeating the strategic framework, here’s a tactical checklist for implementing your LLM selection decisions in CrewAI:\n\n\nAudit Your Current Setup\nWhat to Review:\n\n\nAre all agents using the same LLM by default?\n\n\nWhich agents handle the most complex reasoning tasks?\n\n\nWhich agents primarily do data processing or formatting?\n\n\nAre any agents heavily tool-dependent?\n\n\nAction\n: Document current agent roles and identify optimization opportunities.\nImplement Crew-Level Strategy\nSet Your Baseline:\nCopy\nAsk AI\n# Start with a reliable default for the crew\n\n\ndefault_crew_llm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n) \n# Cost-effective baseline\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n\n\n)\n\n\nAction\n: Establish your crew’s default LLM before optimizing individual agents.\nOptimize High-Impact Agents\nIdentify and Upgrade Key Agents:\nCopy\nAsk AI\n# Manager or coordination agents\n\n\nmanager_agent \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gemini-2.5-flash-preview-05-20\"\n), \n# Premium for coordination\n\n\n # ... rest of config\n\n\n)\n\n\n\n\n# Creative or customer-facing agents \n\n\ncontent_agent \n=\n Agent(\n\n\n role\n=\n\"Content Creator\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n), \n# Best for writing\n\n\n # ... rest of config\n\n\n)\n\n\nAction\n: Upgrade 20% of your agents that handle 80% of the complexity.\nValidate with Enterprise Testing\nOnce you deploy your agents to production:\n\n\nUse \nCrewAI Enterprise platform\n to A/B test your model selections\n\n\nRun multiple iterations with real inputs to measure consistency and performance\n\n\nCompare cost vs. performance across your optimized setup\n\n\nShare results with your team for collaborative decision-making\n\n\nAction\n: Replace guesswork with data-driven validation using the testing platform.\n\n\n​\nWhen to Use Different Model Types\n\n\nReasoning Models\nCreative Models\nEfficient Models\nOpen Source Models\nReasoning models become essential when tasks require genuine multi-step logical thinking, strategic planning, or high-level decision making that benefits from systematic analysis. These models excel when problems need to be broken down into components and analyzed systematically rather than handled through pattern matching or simple instruction following.\nConsider reasoning models for business strategy development, complex data analysis that requires drawing insights from multiple sources, multi-step problem solving where each step depends on previous analysis, and strategic planning tasks that require considering multiple variables and their interactions.\nHowever, reasoning models often come with higher costs and slower response times, so they’re best reserved for tasks where their sophisticated capabilities provide genuine value rather than being used for simple operations that don’t require complex reasoning.\nReasoning models become essential when tasks require genuine multi-step logical thinking, strategic planning, or high-level decision making that benefits from systematic analysis. These models excel when problems need to be broken down into components and analyzed systematically rather than handled through pattern matching or simple instruction following.\nConsider reasoning models for business strategy development, complex data analysis that requires drawing insights from multiple sources, multi-step problem solving where each step depends on previous analysis, and strategic planning tasks that require considering multiple variables and their interactions.\nHowever, reasoning models often come with higher costs and slower response times, so they’re best reserved for tasks where their sophisticated capabilities provide genuine value rather than being used for simple operations that don’t require complex reasoning.\nCreative models become valuable when content generation is the primary output and the quality, style, and engagement level of that content directly impact success. These models excel when writing quality and style matter significantly, creative ideation or brainstorming is needed, or brand voice and tone are important considerations.\nUse creative models for blog post writing and article creation, marketing copy that needs to engage and persuade, creative storytelling and narrative development, and brand communications where voice and tone are crucial. These models often understand nuance and context better than general purpose alternatives.\nCreative models may be less suitable for technical or analytical tasks where precision and factual accuracy are more important than engagement and style. They’re best used when the creative and communicative aspects of the output are primary success factors.\nEfficient models are ideal for high-frequency, routine operations where speed and cost optimization are priorities. These models work best when tasks have clear, well-defined parameters and don’t require sophisticated reasoning or creative capabilities.\nConsider efficient models for data processing and transformation tasks, simple formatting and organization operations, function calling and tool usage where precision matters more than sophistication, and high-volume operations where cost per operation is a significant factor.\nThe key with efficient models is ensuring that their capabilities align with task requirements. They can handle many routine operations effectively but may struggle with tasks requiring nuanced understanding, complex reasoning, or sophisticated content generation.\nOpen source models become attractive when budget constraints are significant, data privacy requirements exist, customization needs are important, or local deployment is required for operational or compliance reasons.\nConsider open source models for internal company tools where data privacy is paramount, privacy-sensitive applications that can’t use external APIs, cost-optimized deployments where per-token pricing is prohibitive, and situations requiring custom model modifications or fine-tuning.\nHowever, open source models require more technical expertise to deploy and maintain effectively. Consider the total cost of ownership including infrastructure, technical overhead, and ongoing maintenance when evaluating open source options.\n\n\n​\nCommon CrewAI Model Selection Pitfalls\n\n\nThe 'One Model Fits All' Trap\nThe Problem\n: Using the same LLM for all agents in a crew, regardless of their specific roles and responsibilities. This is often the default approach but rarely optimal.\nReal Example\n: Using GPT-4o for both a strategic planning manager and a data extraction agent. The manager needs reasoning capabilities worth the premium cost, but the data extractor could perform just as well with GPT-4o-mini at a fraction of the price.\nCrewAI Solution\n: Leverage agent-specific LLM configuration to match model capabilities with agent roles:\nCopy\nAsk AI\n# Strategic agent gets premium model\n\n\nmanager \n=\n Agent(\nrole\n=\n\"Strategy Manager\"\n, \nllm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n))\n\n\n\n\n# Processing agent gets efficient model \n\n\nprocessor \n=\n Agent(\nrole\n=\n\"Data Processor\"\n, \nllm\n=\nLLM(\nmodel\n=\n\"gpt-4o-mini\"\n))\n\n\nIgnoring Crew-Level vs Agent-Level LLM Hierarchy\nThe Problem\n: Not understanding how CrewAI’s LLM hierarchy works - crew LLM, manager LLM, and agent LLM settings can conflict or be poorly coordinated.\nReal Example\n: Setting a crew to use Claude, but having agents configured with GPT models, creating inconsistent behavior and unnecessary model switching overhead.\nCrewAI Solution\n: Plan your LLM hierarchy strategically:\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent1, agent2],\n\n\n tasks\n=\n[task1, task2],\n\n\n manager_llm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n), \n# For crew coordination\n\n\n process\n=\nProcess.hierarchical \n# When using manager_llm\n\n\n)\n\n\n\n\n# Agents inherit crew LLM unless specifically overridden\n\n\nagent1 \n=\n Agent(\nllm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n)) \n# Override for specific needs\n\n\nFunction Calling Model Mismatch\nThe Problem\n: Choosing models based on general capabilities while ignoring function calling performance for tool-heavy CrewAI workflows.\nReal Example\n: Selecting a creative-focused model for an agent that primarily needs to call APIs, search tools, or process structured data. The agent struggles with tool parameter extraction and reliable function calls.\nCrewAI Solution\n: Prioritize function calling capabilities for tool-heavy agents:\nCopy\nAsk AI\n# For agents that use many tools\n\n\ntool_agent \n=\n Agent(\n\n\n role\n=\n\"API Integration Specialist\"\n,\n\n\n tools\n=\n[search_tool, api_tool, data_tool],\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4o\"\n), \n# Excellent function calling\n\n\n # OR\n\n\n llm\n=\nLLM(\nmodel\n=\n\"claude-3-5-sonnet\"\n) \n# Also strong with tools\n\n\n)\n\n\nPremature Optimization Without Testing\nThe Problem\n: Making complex model selection decisions based on theoretical performance without validating with actual CrewAI workflows and tasks.\nReal Example\n: Implementing elaborate model switching logic based on task types without testing if the performance gains justify the operational complexity.\nCrewAI Solution\n: Start simple, then optimize based on real performance data:\nCopy\nAsk AI\n# Start with this\n\n\ncrew \n=\n Crew(\nagents\n=\n[\n...\n], \ntasks\n=\n[\n...\n], \nllm\n=\nLLM(\nmodel\n=\n\"gpt-4o-mini\"\n))\n\n\n\n\n# Test performance, then optimize specific agents as needed\n\n\n# Use Enterprise platform testing to validate improvements\n\n\nOverlooking Context and Memory Limitations\nThe Problem\n: Not considering how model context windows interact with CrewAI’s memory and context sharing between agents.\nReal Example\n: Using a short-context model for agents that need to maintain conversation history across multiple task iterations, or in crews with extensive agent-to-agent communication.\nCrewAI Solution\n: Match context capabilities to crew communication patterns.\n\n\n​\nTesting and Iteration Strategy\n\n\nStart Simple\nBegin with reliable, general-purpose models that are well-understood and widely supported. This provides a stable foundation for understanding your specific requirements and performance expectations before optimizing for specialized needs.\nMeasure What Matters\nDevelop metrics that align with your specific use case and business requirements rather than relying solely on general benchmarks. Focus on measuring outcomes that directly impact your success rather than theoretical performance indicators.\nIterate Based on Results\nMake model changes based on observed performance in your specific context rather than theoretical considerations or general recommendations. Real-world performance often differs significantly from benchmark results or general reputation.\nConsider Total Cost\nEvaluate the complete cost of ownership including model costs, development time, maintenance overhead, and operational complexity. The cheapest model per token may not be the most cost-effective choice when considering all factors.\n\n\nFocus on understanding your requirements first, then select models that best match those needs. The best LLM choice is the one that consistently delivers the results you need within your operational constraints.\n\n\n​\nEnterprise-Grade Model Validation\n\n\nFor teams serious about optimizing their LLM selection, the \nCrewAI Enterprise platform\n provides sophisticated testing capabilities that go far beyond basic CLI testing. The platform enables comprehensive model evaluation that helps you make data-driven decisions about your LLM strategy.\n\n\n\n\nAdvanced Testing Features:\n\n\n\n\n\n\nMulti-Model Comparison\n: Test multiple LLMs simultaneously across the same tasks and inputs. Compare performance between GPT-4o, Claude, Llama, Groq, Cerebras, and other leading models in parallel to identify the best fit for your specific use case.\n\n\n\n\n\n\nStatistical Rigor\n: Configure multiple iterations with consistent inputs to measure reliability and performance variance. This helps identify models that not only perform well but do so consistently across runs.\n\n\n\n\n\n\nReal-World Validation\n: Use your actual crew inputs and scenarios rather than synthetic benchmarks. The platform allows you to test with your specific industry context, company information, and real use cases for more accurate evaluation.\n\n\n\n\n\n\nComprehensive Analytics\n: Access detailed performance metrics, execution times, and cost analysis across all tested models. This enables data-driven decision making rather than relying on general model reputation or theoretical capabilities.\n\n\n\n\n\n\nTeam Collaboration\n: Share testing results and model performance data across your team, enabling collaborative decision-making and consistent model selection strategies across projects.\n\n\n\n\n\n\nGo to \napp.crewai.com\n to get started!\n\n\nThe Enterprise platform transforms model selection from guesswork into a data-driven process, enabling you to validate the principles in this guide with your actual use cases and requirements.\n\n\n​\nKey Principles Summary\n\n\nTask-Driven Selection\nChoose models based on what the task actually requires, not theoretical capabilities or general reputation.\nCapability Matching\nAlign model strengths with agent roles and responsibilities for optimal performance.\nStrategic Consistency\nMaintain coherent model selection strategy across related components and workflows.\nPractical Testing\nValidate choices through real-world usage rather than benchmarks alone.\nIterative Improvement\nStart simple and optimize based on actual performance and needs.\nOperational Balance\nBalance performance requirements with cost and complexity constraints.\n\n\nRemember: The best LLM choice is the one that consistently delivers the results you need within your operational constraints. Focus on understanding your requirements first, then select models that best match those needs.\n\n\n​\nCurrent Model Landscape (June 2025)\n\n\nSnapshot in Time\n: The following model rankings represent current leaderboard standings as of June 2025, compiled from \nLMSys Arena\n, \nArtificial Analysis\n, and other leading benchmarks. LLM performance, availability, and pricing change rapidly. Always conduct your own evaluations with your specific use cases and data.\n\n\n​\nLeading Models by Category\n\n\nThe tables below show a representative sample of current top-performing models across different categories, with guidance on their suitability for CrewAI agents:\n\n\nThese tables/metrics showcase selected leading models in each category and are not exhaustive. Many excellent models exist beyond those listed here. The goal is to illustrate the types of capabilities to look for rather than provide a complete catalog.\n\n\nReasoning & Planning\nCoding & Technical\nSpeed & Efficiency\nBalanced Performance\nBest for Manager LLMs and Complex Analysis\nModel\nIntelligence Score\nCost ($/M tokens)\nSpeed\nBest Use in CrewAI\no3\n70\n$17.50\nFast\nManager LLM for complex multi-agent coordination\nGemini 2.5 Pro\n69\n$3.44\nFast\nStrategic planning agents, research coordination\nDeepSeek R1\n68\n$0.96\nModerate\nCost-effective reasoning for budget-conscious crews\nClaude 4 Sonnet\n53\n$6.00\nFast\nAnalysis agents requiring nuanced understanding\nQwen3 235B (Reasoning)\n62\n$2.63\nModerate\nOpen-source alternative for reasoning tasks\nThese models excel at multi-step reasoning and are ideal for agents that need to develop strategies, coordinate other agents, or analyze complex information.\nBest for Manager LLMs and Complex Analysis\nModel\nIntelligence Score\nCost ($/M tokens)\nSpeed\nBest Use in CrewAI\no3\n70\n$17.50\nFast\nManager LLM for complex multi-agent coordination\nGemini 2.5 Pro\n69\n$3.44\nFast\nStrategic planning agents, research coordination\nDeepSeek R1\n68\n$0.96\nModerate\nCost-effective reasoning for budget-conscious crews\nClaude 4 Sonnet\n53\n$6.00\nFast\nAnalysis agents requiring nuanced understanding\nQwen3 235B (Reasoning)\n62\n$2.63\nModerate\nOpen-source alternative for reasoning tasks\nThese models excel at multi-step reasoning and are ideal for agents that need to develop strategies, coordinate other agents, or analyze complex information.\nBest for Development and Tool-Heavy Workflows\nModel\nCoding Performance\nTool Use Score\nCost ($/M tokens)\nBest Use in CrewAI\nClaude 4 Sonnet\nExcellent\n72.7%\n$6.00\nPrimary coding agent, technical documentation\nClaude 4 Opus\nExcellent\n72.5%\n$30.00\nComplex software architecture, code review\nDeepSeek V3\nVery Good\nHigh\n$0.48\nCost-effective coding for routine development\nQwen2.5 Coder 32B\nVery Good\nMedium\n$0.15\nBudget-friendly coding agent\nLlama 3.1 405B\nGood\n81.1%\n$3.50\nFunction calling LLM for tool-heavy workflows\nThese models are optimized for code generation, debugging, and technical problem-solving, making them ideal for development-focused crews.\nBest for High-Throughput and Real-Time Applications\nModel\nSpeed (tokens/s)\nLatency (TTFT)\nCost ($/M tokens)\nBest Use in CrewAI\nLlama 4 Scout\n2,600\n0.33s\n$0.27\nHigh-volume processing agents\nGemini 2.5 Flash\n376\n0.30s\n$0.26\nReal-time response agents\nDeepSeek R1 Distill\n383\nVariable\n$0.04\nCost-optimized high-speed processing\nLlama 3.3 70B\n2,500\n0.52s\n$0.60\nBalanced speed and capability\nNova Micro\nHigh\n0.30s\n$0.04\nSimple, fast task execution\nThese models prioritize speed and efficiency, perfect for agents handling routine operations or requiring quick responses. \nPro tip\n: Pairing these models with fast inference providers like Groq can achieve even better performance, especially for open-source models like Llama.\nBest All-Around Models for General Crews\nModel\nOverall Score\nVersatility\nCost ($/M tokens)\nBest Use in CrewAI\nGPT-4.1\n53\nExcellent\n$3.50\nGeneral-purpose crew LLM\nClaude 3.7 Sonnet\n48\nVery Good\n$6.00\nBalanced reasoning and creativity\nGemini 2.0 Flash\n48\nGood\n$0.17\nCost-effective general use\nLlama 4 Maverick\n51\nGood\n$0.37\nOpen-source general purpose\nQwen3 32B\n44\nGood\n$1.23\nBudget-friendly versatility\nThese models offer good performance across multiple dimensions, suitable for crews with diverse task requirements.\n\n\n​\nSelection Framework for Current Models\n\n\nHigh-Performance Crews\nWhen performance is the priority\n: Use top-tier models like \no3\n, \nGemini 2.5 Pro\n, or \nClaude 4 Sonnet\n for manager LLMs and critical agents. These models excel at complex reasoning and coordination but come with higher costs.\nStrategy\n: Implement a multi-model approach where premium models handle strategic thinking while efficient models handle routine operations.\nCost-Conscious Crews\nWhen budget is a primary constraint\n: Focus on models like \nDeepSeek R1\n, \nLlama 4 Scout\n, or \nGemini 2.0 Flash\n. These provide strong performance at significantly lower costs.\nStrategy\n: Use cost-effective models for most agents, reserving premium models only for the most critical decision-making roles.\nSpecialized Workflows\nFor specific domain expertise\n: Choose models optimized for your primary use case. \nClaude 4\n series for coding, \nGemini 2.5 Pro\n for research, \nLlama 405B\n for function calling.\nStrategy\n: Select models based on your crew’s primary function, ensuring the core capability aligns with model strengths.\nEnterprise & Privacy\nFor data-sensitive operations\n: Consider open-source models like \nLlama 4\n series, \nDeepSeek V3\n, or \nQwen3\n that can be deployed locally while maintaining competitive performance.\nStrategy\n: Deploy open-source models on private infrastructure, accepting potential performance trade-offs for data control.\n\n\n​\nKey Considerations for Model Selection\n\n\n\n\n\n\nPerformance Trends\n: The current landscape shows strong competition between reasoning-focused models (o3, Gemini 2.5 Pro) and balanced models (Claude 4, GPT-4.1). Specialized models like DeepSeek R1 offer excellent cost-performance ratios.\n\n\n\n\n\n\nSpeed vs. Intelligence Trade-offs\n: Models like Llama 4 Scout prioritize speed (2,600 tokens/s) while maintaining reasonable intelligence, whereas models like o3 maximize reasoning capability at the cost of speed and price.\n\n\n\n\n\n\nOpen Source Viability\n: The gap between open-source and proprietary models continues to narrow, with models like Llama 4 Maverick and DeepSeek V3 offering competitive performance at attractive price points. Fast inference providers particularly shine with open-source models, often delivering better speed-to-cost ratios than proprietary alternatives.\n\n\n\n\n\n\nTesting is Essential\n: Leaderboard rankings provide general guidance, but your specific use case, prompting style, and evaluation criteria may produce different results. Always test candidate models with your actual tasks and data before making final decisions.\n\n\n​\nPractical Implementation Strategy\n\n\n1\nStart with Proven Models\nBegin with well-established models like \nGPT-4.1\n, \nClaude 3.7 Sonnet\n, or \nGemini 2.0 Flash\n that offer good performance across multiple dimensions and have extensive real-world validation.\n2\nIdentify Specialized Needs\nDetermine if your crew has specific requirements (coding, reasoning, speed) that would benefit from specialized models like \nClaude 4 Sonnet\n for development or \no3\n for complex analysis. For speed-critical applications, consider fast inference providers like \nGroq\n alongside model selection.\n3\nImplement Multi-Model Strategy\nUse different models for different agents based on their roles. High-capability models for managers and complex tasks, efficient models for routine operations.\n4\nMonitor and Optimize\nTrack performance metrics relevant to your use case and be prepared to adjust model selections as new models are released or pricing changes.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOverview\nConditional Tasks\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nThe CrewAI Approach to LLM Selection\nQuick Decision Framework\nCore Selection Framework\na. Task-First Thinking\nb. Model Capability Mapping\nStrategic Configuration Patterns\na. Multi-Model Approach\nb. Component-Specific Selection\nTask Definition Framework\na. Focus on Clarity Over Complexity\nb. Task Sequencing Strategy\nOptimizing Agent Configuration for LLM Performance\na. Role-Driven LLM Selection\nb. Backstory as Model Context Amplifier\nc. Holistic Agent-LLM Optimization\nPractical Implementation Checklist\nWhen to Use Different Model Types\nCommon CrewAI Model Selection Pitfalls\nTesting and Iteration Strategy\nEnterprise-Grade Model Validation\nKey Principles Summary\nCurrent Model Landscape (June 2025)\nLeading Models by Category\nSelection Framework for Current Models\nKey Considerations for Model Selection\nPractical Implementation Strategy" }, { "source": "https://docs.crewai.com/en/learn/human-input-on-execution", "title": "Human Input on Execution - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nHuman Input on Execution\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nHuman Input on Execution\nCopy page\nIntegrating CrewAI with human input during execution in complex decision-making processes and leveraging the full capabilities of the agent’s attributes and tools.\n​\nHuman input in agent execution\n\n\nHuman input is critical in several agent execution scenarios, allowing agents to request additional information or clarification when necessary.\nThis feature is especially useful in complex decision-making processes or when agents require more details to complete a task effectively.\n\n\n​\nUsing human input with CrewAI\n\n\nTo integrate human input into agent execution, set the \nhuman_input\n flag in the task definition. When enabled, the agent prompts the user for input before delivering its final answer.\nThis input can provide extra context, clarify ambiguities, or validate the agent’s output.\n\n\n​\nExample:\n\n\nCopy\nAsk AI\npip\n install\n crewai\n\n\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n # serper.dev API key\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\n\n\n# Loading Tools\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\n# Define your agents with roles, goals, tools, and additional attributes\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Senior Research Analyst'\n,\n\n\n goal\n=\n'Uncover cutting-edge developments in AI and data science'\n,\n\n\n backstory\n=\n(\n\n\n \"You are a Senior Research Analyst at a leading tech think tank. \"\n\n\n \"Your expertise lies in identifying emerging trends and technologies in AI and data science. \"\n\n\n \"You have a knack for dissecting complex data and presenting actionable insights.\"\n\n\n ),\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Tech Content Strategist'\n,\n\n\n goal\n=\n'Craft compelling content on tech advancements'\n,\n\n\n backstory\n=\n(\n\n\n \"You are a renowned Tech Content Strategist, known for your insightful and engaging articles on technology and innovation. \"\n\n\n \"With a deep understanding of the tech industry, you transform complex concepts into compelling narratives.\"\n\n\n ),\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n tools\n=\n[search_tool],\n\n\n cache\n=\nFalse\n, \n# Disable cache for this agent\n\n\n)\n\n\n\n\n# Create tasks for your agents\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n(\n\n\n \"Conduct a comprehensive analysis of the latest advancements in AI in 2025. \"\n\n\n \"Identify key trends, breakthrough technologies, and potential industry impacts. \"\n\n\n \"Compile your findings in a detailed report. \"\n\n\n \"Make sure to check with a human if the draft is good before finalizing your answer.\"\n\n\n ),\n\n\n expected_output\n=\n'A comprehensive full report on the latest AI advancements in 2025, leave nothing out'\n,\n\n\n agent\n=\nresearcher,\n\n\n human_input\n=\nTrue\n\n\n)\n\n\n\n\ntask2 \n=\n Task(\n\n\n description\n=\n(\n\n\n \"Using the insights from the researcher\n\\'\ns report, develop an engaging blog post that highlights the most significant AI advancements. \"\n\n\n \"Your post should be informative yet accessible, catering to a tech-savvy audience. \"\n\n\n \"Aim for a narrative that captures the essence of these breakthroughs and their implications for the future.\"\n\n\n ),\n\n\n expected_output\n=\n'A compelling 3 paragraphs blog post formatted as markdown about the latest AI advancements in 2025'\n,\n\n\n agent\n=\nwriter,\n\n\n human_input\n=\nTrue\n\n\n)\n\n\n\n\n# Instantiate your crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[task1, task2],\n\n\n verbose\n=\nTrue\n,\n\n\n memory\n=\nTrue\n,\n\n\n planning\n=\nTrue\n # Enable planning feature for the crew\n\n\n)\n\n\n\n\n# Get your crew to work!\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(\n\"######################\"\n)\n\n\nprint\n(result)\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nHierarchical Process\nKickoff Crew Asynchronously\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nHuman input in agent execution\nUsing human input with CrewAI\nExample:\nLearn\nHuman Input on Execution\nCopy page\nIntegrating CrewAI with human input during execution in complex decision-making processes and leveraging the full capabilities of the agent’s attributes and tools.\n​\nHuman input in agent execution\n\n\nHuman input is critical in several agent execution scenarios, allowing agents to request additional information or clarification when necessary.\nThis feature is especially useful in complex decision-making processes or when agents require more details to complete a task effectively.\n\n\n​\nUsing human input with CrewAI\n\n\nTo integrate human input into agent execution, set the \nhuman_input\n flag in the task definition. When enabled, the agent prompts the user for input before delivering its final answer.\nThis input can provide extra context, clarify ambiguities, or validate the agent’s output.\n\n\n​\nExample:\n\n\nCopy\nAsk AI\npip\n install\n crewai\n\n\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n # serper.dev API key\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\n\n\n# Loading Tools\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\n# Define your agents with roles, goals, tools, and additional attributes\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Senior Research Analyst'\n,\n\n\n goal\n=\n'Uncover cutting-edge developments in AI and data science'\n,\n\n\n backstory\n=\n(\n\n\n \"You are a Senior Research Analyst at a leading tech think tank. \"\n\n\n \"Your expertise lies in identifying emerging trends and technologies in AI and data science. \"\n\n\n \"You have a knack for dissecting complex data and presenting actionable insights.\"\n\n\n ),\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Tech Content Strategist'\n,\n\n\n goal\n=\n'Craft compelling content on tech advancements'\n,\n\n\n backstory\n=\n(\n\n\n \"You are a renowned Tech Content Strategist, known for your insightful and engaging articles on technology and innovation. \"\n\n\n \"With a deep understanding of the tech industry, you transform complex concepts into compelling narratives.\"\n\n\n ),\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n tools\n=\n[search_tool],\n\n\n cache\n=\nFalse\n, \n# Disable cache for this agent\n\n\n)\n\n\n\n\n# Create tasks for your agents\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n(\n\n\n \"Conduct a comprehensive analysis of the latest advancements in AI in 2025. \"\n\n\n \"Identify key trends, breakthrough technologies, and potential industry impacts. \"\n\n\n \"Compile your findings in a detailed report. \"\n\n\n \"Make sure to check with a human if the draft is good before finalizing your answer.\"\n\n\n ),\n\n\n expected_output\n=\n'A comprehensive full report on the latest AI advancements in 2025, leave nothing out'\n,\n\n\n agent\n=\nresearcher,\n\n\n human_input\n=\nTrue\n\n\n)\n\n\n\n\ntask2 \n=\n Task(\n\n\n description\n=\n(\n\n\n \"Using the insights from the researcher\n\\'\ns report, develop an engaging blog post that highlights the most significant AI advancements. \"\n\n\n \"Your post should be informative yet accessible, catering to a tech-savvy audience. \"\n\n\n \"Aim for a narrative that captures the essence of these breakthroughs and their implications for the future.\"\n\n\n ),\n\n\n expected_output\n=\n'A compelling 3 paragraphs blog post formatted as markdown about the latest AI advancements in 2025'\n,\n\n\n agent\n=\nwriter,\n\n\n human_input\n=\nTrue\n\n\n)\n\n\n\n\n# Instantiate your crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[task1, task2],\n\n\n verbose\n=\nTrue\n,\n\n\n memory\n=\nTrue\n,\n\n\n planning\n=\nTrue\n # Enable planning feature for the crew\n\n\n)\n\n\n\n\n# Get your crew to work!\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(\n\"######################\"\n)\n\n\nprint\n(result)\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nHierarchical Process\nKickoff Crew Asynchronously\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nHuman input in agent execution\nUsing human input with CrewAI\nExample:" }, { "source": "https://docs.crewai.com/en/learn/kickoff-for-each", "title": "Kickoff Crew for Each - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nKickoff Crew for Each\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nKickoff Crew for Each\nCopy page\nKickoff Crew for Each Item in a List\n​\nIntroduction\n\n\nCrewAI provides the ability to kickoff a crew for each item in a list, allowing you to execute the crew for each item in the list.\nThis feature is particularly useful when you need to perform the same set of tasks for multiple items.\n\n\n​\nKicking Off a Crew for Each Item\n\n\nTo kickoff a crew for each item in a list, use the \nkickoff_for_each()\n method.\nThis method executes the crew for each item in the list, allowing you to process multiple items efficiently.\n\n\nHere’s an example of how to kickoff a crew for each item in a list:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age calculated from the dataset\"\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task],\n\n\n verbose\n=\nTrue\n,\n\n\n memory\n=\nFalse\n\n\n)\n\n\n\n\ndatasets \n=\n [\n\n\n { \n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n] },\n\n\n { \n\"ages\"\n: [\n20\n, \n25\n, \n30\n, \n35\n, \n40\n] },\n\n\n { \n\"ages\"\n: [\n30\n, \n35\n, \n40\n, \n45\n, \n50\n] }\n\n\n]\n\n\n\n\n# Execute the crew\n\n\nresult \n=\n analysis_crew.kickoff_for_each(\ninputs\n=\ndatasets)\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nKickoff Crew Asynchronously\nConnect to any LLM\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nKicking Off a Crew for Each Item\nLearn\nKickoff Crew for Each\nCopy page\nKickoff Crew for Each Item in a List\n​\nIntroduction\n\n\nCrewAI provides the ability to kickoff a crew for each item in a list, allowing you to execute the crew for each item in the list.\nThis feature is particularly useful when you need to perform the same set of tasks for multiple items.\n\n\n​\nKicking Off a Crew for Each Item\n\n\nTo kickoff a crew for each item in a list, use the \nkickoff_for_each()\n method.\nThis method executes the crew for each item in the list, allowing you to process multiple items efficiently.\n\n\nHere’s an example of how to kickoff a crew for each item in a list:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age calculated from the dataset\"\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task],\n\n\n verbose\n=\nTrue\n,\n\n\n memory\n=\nFalse\n\n\n)\n\n\n\n\ndatasets \n=\n [\n\n\n { \n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n] },\n\n\n { \n\"ages\"\n: [\n20\n, \n25\n, \n30\n, \n35\n, \n40\n] },\n\n\n { \n\"ages\"\n: [\n30\n, \n35\n, \n40\n, \n45\n, \n50\n] }\n\n\n]\n\n\n\n\n# Execute the crew\n\n\nresult \n=\n analysis_crew.kickoff_for_each(\ninputs\n=\ndatasets)\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nKickoff Crew Asynchronously\nConnect to any LLM\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nKicking Off a Crew for Each Item" }, { "source": "https://docs.crewai.com/", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/concepts/planning", "title": "Planning - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nPlanning\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nPlanning\nCopy page\nLearn how to add planning to your CrewAI Crew and improve their performance.\n​\nOverview\n\n\nThe planning feature in CrewAI allows you to add planning capability to your crew. When enabled, before each Crew iteration,\nall Crew information is sent to an AgentPlanner that will plan the tasks step by step, and this plan will be added to each task description.\n\n\n​\nUsing the Planning Feature\n\n\nGetting started with the planning feature is very easy, the only step required is to add \nplanning=True\n to your Crew:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task, Process\n\n\n\n\n# Assemble your crew with planning capabilities\n\n\nmy_crew \n=\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n planning\n=\nTrue\n,\n\n\n)\n\n\n\n\nFrom this point on, your crew will have planning enabled, and the tasks will be planned before each iteration.\n\n\nWhen planning is enabled, crewAI will use \ngpt-4o-mini\n as the default LLM for planning, which requires a valid OpenAI API key. Since your agents might be using different LLMs, this could cause confusion if you don’t have an OpenAI API key configured or if you’re experiencing unexpected behavior related to LLM API calls.\n\n\n​\nPlanning LLM\n\n\nNow you can define the LLM that will be used to plan the tasks.\n\n\nWhen running the base case example, you will see something like the output below, which represents the output of the \nAgentPlanner\n\nresponsible for creating the step-by-step logic to add to the Agents’ tasks.\n\n\nCode\nResult\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task, Process\n\n\n\n\n# Assemble your crew with planning capabilities and custom LLM\n\n\nmy_crew \n=\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n planning\n=\nTrue\n,\n\n\n planning_llm\n=\n\"gpt-4o\"\n\n\n)\n\n\n\n\n# Run the crew\n\n\nmy_crew.kickoff()\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nReasoning\nTesting\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nUsing the Planning Feature\nPlanning LLM\nCore Concepts\nPlanning\nCopy page\nLearn how to add planning to your CrewAI Crew and improve their performance.\n​\nOverview\n\n\nThe planning feature in CrewAI allows you to add planning capability to your crew. When enabled, before each Crew iteration,\nall Crew information is sent to an AgentPlanner that will plan the tasks step by step, and this plan will be added to each task description.\n\n\n​\nUsing the Planning Feature\n\n\nGetting started with the planning feature is very easy, the only step required is to add \nplanning=True\n to your Crew:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task, Process\n\n\n\n\n# Assemble your crew with planning capabilities\n\n\nmy_crew \n=\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n planning\n=\nTrue\n,\n\n\n)\n\n\n\n\nFrom this point on, your crew will have planning enabled, and the tasks will be planned before each iteration.\n\n\nWhen planning is enabled, crewAI will use \ngpt-4o-mini\n as the default LLM for planning, which requires a valid OpenAI API key. Since your agents might be using different LLMs, this could cause confusion if you don’t have an OpenAI API key configured or if you’re experiencing unexpected behavior related to LLM API calls.\n\n\n​\nPlanning LLM\n\n\nNow you can define the LLM that will be used to plan the tasks.\n\n\nWhen running the base case example, you will see something like the output below, which represents the output of the \nAgentPlanner\n\nresponsible for creating the step-by-step logic to add to the Agents’ tasks.\n\n\nCode\nResult\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task, Process\n\n\n\n\n# Assemble your crew with planning capabilities and custom LLM\n\n\nmy_crew \n=\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n planning\n=\nTrue\n,\n\n\n planning_llm\n=\n\"gpt-4o\"\n\n\n)\n\n\n\n\n# Run the crew\n\n\nmy_crew.kickoff()\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nReasoning\nTesting\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nUsing the Planning Feature\nPlanning LLM" }, { "source": "https://docs.crewai.com/en/mcp/streamable-http", "title": "Streamable HTTP Transport - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nMCP Integration\nStreamable HTTP Transport\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nMCP Integration\nStreamable HTTP Transport\nCopy page\nLearn how to connect CrewAI to remote MCP servers using the flexible Streamable HTTP transport.\n​\nOverview\n\n\nStreamable HTTP transport provides a flexible way to connect to remote MCP servers. It’s often built upon HTTP and can support various communication patterns, including request-response and streaming, sometimes utilizing Server-Sent Events (SSE) for server-to-client streams within a broader HTTP interaction.\n\n\n​\nKey Concepts\n\n\n\n\nRemote Servers\n: Designed for MCP servers hosted remotely.\n\n\nFlexibility\n: Can support more complex interaction patterns than plain SSE, potentially including bi-directional communication if the server implements it.\n\n\nMCPServerAdapter\n Configuration\n: You’ll need to provide the server’s base URL for MCP communication and specify \n\"streamable-http\"\n as the transport type.\n\n\n\n\n​\nConnecting via Streamable HTTP\n\n\nYou have two primary methods for managing the connection lifecycle with a Streamable HTTP MCP server:\n\n\n​\n1. Fully Managed Connection (Recommended)\n\n\nThe recommended approach is to use a Python context manager (\nwith\n statement), which handles the connection’s setup and teardown automatically.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n, \n# Replace with your actual Streamable HTTP server URL\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n}\n\n\n\n\ntry\n:\n\n\n with\n MCPServerAdapter(server_params) \nas\n tools:\n\n\n print\n(\nf\n\"Available tools from Streamable HTTP MCP server: \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n http_agent \n=\n Agent(\n\n\n role\n=\n\"HTTP Service Integrator\"\n,\n\n\n goal\n=\n\"Utilize tools from a remote MCP server via Streamable HTTP.\"\n,\n\n\n backstory\n=\n\"An AI agent adept at interacting with complex web services.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n http_task \n=\n Task(\n\n\n description\n=\n\"Perform a complex data query using a tool from the Streamable HTTP server.\"\n,\n\n\n expected_output\n=\n\"The result of the complex data query.\"\n,\n\n\n agent\n=\nhttp_agent,\n\n\n )\n\n\n\n\n http_crew \n=\n Crew(\n\n\n agents\n=\n[http_agent],\n\n\n tasks\n=\n[http_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n result \n=\n http_crew.kickoff() \n\n\n print\n(\n\"\n\\n\nCrew Task Result (Streamable HTTP - Managed):\n\\n\n\"\n, result)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Error connecting to or using Streamable HTTP MCP server (Managed): \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the Streamable HTTP MCP server is running and accessible at the specified URL.\"\n)\n\n\n\n\n\n\nNote:\n Replace \n\"http://localhost:8001/mcp\"\n with the actual URL of your Streamable HTTP MCP server.\n\n\n​\n2. Manual Connection Lifecycle\n\n\nFor scenarios requiring more explicit control, you can manage the \nMCPServerAdapter\n connection manually.\n\n\nIt is \ncritical\n to call \nmcp_server_adapter.stop()\n when you are done to close the connection and free up resources. A \ntry...finally\n block is the safest way to ensure this.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n, \n# Replace with your actual Streamable HTTP server URL\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n}\n\n\n\n\nmcp_server_adapter \n=\n None\n \n\n\ntry\n:\n\n\n mcp_server_adapter \n=\n MCPServerAdapter(server_params)\n\n\n mcp_server_adapter.start()\n\n\n tools \n=\n mcp_server_adapter.tools\n\n\n print\n(\nf\n\"Available tools (manual Streamable HTTP): \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n manual_http_agent \n=\n Agent(\n\n\n role\n=\n\"Advanced Web Service User\"\n,\n\n\n goal\n=\n\"Interact with an MCP server using manually managed Streamable HTTP connections.\"\n,\n\n\n backstory\n=\n\"An AI specialist in fine-tuning HTTP-based service integrations.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n \n\n\n data_processing_task \n=\n Task(\n\n\n description\n=\n\"Submit data for processing and retrieve results via Streamable HTTP.\"\n,\n\n\n expected_output\n=\n\"Processed data or confirmation.\"\n,\n\n\n agent\n=\nmanual_http_agent\n\n\n )\n\n\n \n\n\n data_crew \n=\n Crew(\n\n\n agents\n=\n[manual_http_agent],\n\n\n tasks\n=\n[data_processing_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n result \n=\n data_crew.kickoff()\n\n\n print\n(\n\"\n\\n\nCrew Task Result (Streamable HTTP - Manual):\n\\n\n\"\n, result)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"An error occurred during manual Streamable HTTP MCP integration: \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the Streamable HTTP MCP server is running and accessible.\"\n)\n\n\nfinally\n:\n\n\n if\n mcp_server_adapter \nand\n mcp_server_adapter.is_connected:\n\n\n print\n(\n\"Stopping Streamable HTTP MCP server connection (manual)...\"\n)\n\n\n mcp_server_adapter.stop() \n# **Crucial: Ensure stop is called**\n\n\n elif\n mcp_server_adapter:\n\n\n print\n(\n\"Streamable HTTP MCP server adapter was not connected. No stop needed or start failed.\"\n)\n\n\n\n\n​\nSecurity Considerations\n\n\nWhen using Streamable HTTP transport, general web security best practices are paramount:\n\n\n\n\nUse HTTPS\n: Always prefer HTTPS (HTTP Secure) for your MCP server URLs to encrypt data in transit.\n\n\nAuthentication\n: Implement robust authentication mechanisms if your MCP server exposes sensitive tools or data.\n\n\nInput Validation\n: Ensure your MCP server validates all incoming requests and parameters.\n\n\n\n\nFor a comprehensive guide on securing your MCP integrations, please refer to our \nSecurity Considerations\n page and the official \nMCP Transport Security documentation\n.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nSSE Transport\nConnecting to Multiple MCP Servers\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nKey Concepts\nConnecting via Streamable HTTP\n1. Fully Managed Connection (Recommended)\n2. Manual Connection Lifecycle\nSecurity Considerations\nMCP Integration\nStreamable HTTP Transport\nCopy page\nLearn how to connect CrewAI to remote MCP servers using the flexible Streamable HTTP transport.\n​\nOverview\n\n\nStreamable HTTP transport provides a flexible way to connect to remote MCP servers. It’s often built upon HTTP and can support various communication patterns, including request-response and streaming, sometimes utilizing Server-Sent Events (SSE) for server-to-client streams within a broader HTTP interaction.\n\n\n​\nKey Concepts\n\n\n\n\nRemote Servers\n: Designed for MCP servers hosted remotely.\n\n\nFlexibility\n: Can support more complex interaction patterns than plain SSE, potentially including bi-directional communication if the server implements it.\n\n\nMCPServerAdapter\n Configuration\n: You’ll need to provide the server’s base URL for MCP communication and specify \n\"streamable-http\"\n as the transport type.\n\n\n\n\n​\nConnecting via Streamable HTTP\n\n\nYou have two primary methods for managing the connection lifecycle with a Streamable HTTP MCP server:\n\n\n​\n1. Fully Managed Connection (Recommended)\n\n\nThe recommended approach is to use a Python context manager (\nwith\n statement), which handles the connection’s setup and teardown automatically.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n, \n# Replace with your actual Streamable HTTP server URL\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n}\n\n\n\n\ntry\n:\n\n\n with\n MCPServerAdapter(server_params) \nas\n tools:\n\n\n print\n(\nf\n\"Available tools from Streamable HTTP MCP server: \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n http_agent \n=\n Agent(\n\n\n role\n=\n\"HTTP Service Integrator\"\n,\n\n\n goal\n=\n\"Utilize tools from a remote MCP server via Streamable HTTP.\"\n,\n\n\n backstory\n=\n\"An AI agent adept at interacting with complex web services.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n http_task \n=\n Task(\n\n\n description\n=\n\"Perform a complex data query using a tool from the Streamable HTTP server.\"\n,\n\n\n expected_output\n=\n\"The result of the complex data query.\"\n,\n\n\n agent\n=\nhttp_agent,\n\n\n )\n\n\n\n\n http_crew \n=\n Crew(\n\n\n agents\n=\n[http_agent],\n\n\n tasks\n=\n[http_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n result \n=\n http_crew.kickoff() \n\n\n print\n(\n\"\n\\n\nCrew Task Result (Streamable HTTP - Managed):\n\\n\n\"\n, result)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Error connecting to or using Streamable HTTP MCP server (Managed): \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the Streamable HTTP MCP server is running and accessible at the specified URL.\"\n)\n\n\n\n\n\n\nNote:\n Replace \n\"http://localhost:8001/mcp\"\n with the actual URL of your Streamable HTTP MCP server.\n\n\n​\n2. Manual Connection Lifecycle\n\n\nFor scenarios requiring more explicit control, you can manage the \nMCPServerAdapter\n connection manually.\n\n\nIt is \ncritical\n to call \nmcp_server_adapter.stop()\n when you are done to close the connection and free up resources. A \ntry...finally\n block is the safest way to ensure this.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n, \n# Replace with your actual Streamable HTTP server URL\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n}\n\n\n\n\nmcp_server_adapter \n=\n None\n \n\n\ntry\n:\n\n\n mcp_server_adapter \n=\n MCPServerAdapter(server_params)\n\n\n mcp_server_adapter.start()\n\n\n tools \n=\n mcp_server_adapter.tools\n\n\n print\n(\nf\n\"Available tools (manual Streamable HTTP): \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n manual_http_agent \n=\n Agent(\n\n\n role\n=\n\"Advanced Web Service User\"\n,\n\n\n goal\n=\n\"Interact with an MCP server using manually managed Streamable HTTP connections.\"\n,\n\n\n backstory\n=\n\"An AI specialist in fine-tuning HTTP-based service integrations.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n \n\n\n data_processing_task \n=\n Task(\n\n\n description\n=\n\"Submit data for processing and retrieve results via Streamable HTTP.\"\n,\n\n\n expected_output\n=\n\"Processed data or confirmation.\"\n,\n\n\n agent\n=\nmanual_http_agent\n\n\n )\n\n\n \n\n\n data_crew \n=\n Crew(\n\n\n agents\n=\n[manual_http_agent],\n\n\n tasks\n=\n[data_processing_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n result \n=\n data_crew.kickoff()\n\n\n print\n(\n\"\n\\n\nCrew Task Result (Streamable HTTP - Manual):\n\\n\n\"\n, result)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"An error occurred during manual Streamable HTTP MCP integration: \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the Streamable HTTP MCP server is running and accessible.\"\n)\n\n\nfinally\n:\n\n\n if\n mcp_server_adapter \nand\n mcp_server_adapter.is_connected:\n\n\n print\n(\n\"Stopping Streamable HTTP MCP server connection (manual)...\"\n)\n\n\n mcp_server_adapter.stop() \n# **Crucial: Ensure stop is called**\n\n\n elif\n mcp_server_adapter:\n\n\n print\n(\n\"Streamable HTTP MCP server adapter was not connected. No stop needed or start failed.\"\n)\n\n\n\n\n​\nSecurity Considerations\n\n\nWhen using Streamable HTTP transport, general web security best practices are paramount:\n\n\n\n\nUse HTTPS\n: Always prefer HTTPS (HTTP Secure) for your MCP server URLs to encrypt data in transit.\n\n\nAuthentication\n: Implement robust authentication mechanisms if your MCP server exposes sensitive tools or data.\n\n\nInput Validation\n: Ensure your MCP server validates all incoming requests and parameters.\n\n\n\n\nFor a comprehensive guide on securing your MCP integrations, please refer to our \nSecurity Considerations\n page and the official \nMCP Transport Security documentation\n.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nSSE Transport\nConnecting to Multiple MCP Servers\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nKey Concepts\nConnecting via Streamable HTTP\n1. Fully Managed Connection (Recommended)\n2. Manual Connection Lifecycle\nSecurity Considerations" }, { "source": "https://docs.crewai.com/#how-crews-work", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/tools/overview", "title": "Tools Overview - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nTools\nTools Overview\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nTools\nTools Overview\nCopy page\nDiscover CrewAI’s extensive library of 40+ tools to supercharge your AI agents\nCrewAI provides an extensive library of pre-built tools to enhance your agents’ capabilities. From file processing to web scraping, database queries to AI services - we’ve got you covered.\n\n\n​\nTool Categories\n\n\nFile & Document\nRead, write, and search through various file formats including PDF, DOCX, JSON, CSV, and more. Perfect for document processing workflows.\nWeb Scraping & Browsing\nExtract data from websites, automate browser interactions, and scrape content at scale with tools like Firecrawl, Selenium, and more.\nSearch & Research\nPerform web searches, find code repositories, research YouTube content, and discover information across the internet.\nDatabase & Data\nConnect to SQL databases, vector stores, and data warehouses. Query MySQL, PostgreSQL, Snowflake, Qdrant, and Weaviate.\nAI & Machine Learning\nGenerate images with DALL-E, process vision tasks, integrate with LangChain, build RAG systems, and leverage code interpreters.\nCloud & Storage\nInteract with cloud services including AWS S3, Amazon Bedrock, and other cloud storage and AI services.\nAutomation & Integration\nAutomate workflows with Apify, Composio, and other integration platforms to connect your agents with external services.\n\n\n​\nQuick Access\n\n\nNeed a specific tool? Here are some popular choices:\n\n\nRAG Tool\nImplement Retrieval-Augmented Generation\nSerper Dev\nGoogle search API\nFile Read\nRead any file type\nScrape Website\nExtract web content\nCode Interpreter\nExecute Python code\nS3 Reader\nAccess AWS S3 files\n\n\n​\nGetting Started\n\n\nTo use any tool in your CrewAI project:\n\n\n\n\nImport\n the tool in your crew configuration\n\n\nAdd\n it to your agent’s tools list\n\n\nConfigure\n any required API keys or settings\n\n\n\n\nCopy\nAsk AI\nfrom\n crewai_tools \nimport\n FileReadTool, SerperDevTool\n\n\n\n\n# Add tools to your agent\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Research Analyst\"\n,\n\n\n tools\n=\n[FileReadTool(), SerperDevTool()],\n\n\n # ... other configuration\n\n\n)\n\n\n\n\nReady to explore? Pick a category above to discover tools that fit your use case!\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMCP Security Considerations\nOverview\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nTool Categories\nQuick Access\nGetting Started\nTools\nTools Overview\nCopy page\nDiscover CrewAI’s extensive library of 40+ tools to supercharge your AI agents\nCrewAI provides an extensive library of pre-built tools to enhance your agents’ capabilities. From file processing to web scraping, database queries to AI services - we’ve got you covered.\n\n\n​\nTool Categories\n\n\nFile & Document\nRead, write, and search through various file formats including PDF, DOCX, JSON, CSV, and more. Perfect for document processing workflows.\nWeb Scraping & Browsing\nExtract data from websites, automate browser interactions, and scrape content at scale with tools like Firecrawl, Selenium, and more.\nSearch & Research\nPerform web searches, find code repositories, research YouTube content, and discover information across the internet.\nDatabase & Data\nConnect to SQL databases, vector stores, and data warehouses. Query MySQL, PostgreSQL, Snowflake, Qdrant, and Weaviate.\nAI & Machine Learning\nGenerate images with DALL-E, process vision tasks, integrate with LangChain, build RAG systems, and leverage code interpreters.\nCloud & Storage\nInteract with cloud services including AWS S3, Amazon Bedrock, and other cloud storage and AI services.\nAutomation & Integration\nAutomate workflows with Apify, Composio, and other integration platforms to connect your agents with external services.\n\n\n​\nQuick Access\n\n\nNeed a specific tool? Here are some popular choices:\n\n\nRAG Tool\nImplement Retrieval-Augmented Generation\nSerper Dev\nGoogle search API\nFile Read\nRead any file type\nScrape Website\nExtract web content\nCode Interpreter\nExecute Python code\nS3 Reader\nAccess AWS S3 files\n\n\n​\nGetting Started\n\n\nTo use any tool in your CrewAI project:\n\n\n\n\nImport\n the tool in your crew configuration\n\n\nAdd\n it to your agent’s tools list\n\n\nConfigure\n any required API keys or settings\n\n\n\n\nCopy\nAsk AI\nfrom\n crewai_tools \nimport\n FileReadTool, SerperDevTool\n\n\n\n\n# Add tools to your agent\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Research Analyst\"\n,\n\n\n tools\n=\n[FileReadTool(), SerperDevTool()],\n\n\n # ... other configuration\n\n\n)\n\n\n\n\nReady to explore? Pick a category above to discover tools that fit your use case!\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMCP Security Considerations\nOverview\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nTool Categories\nQuick Access\nGetting Started" }, { "source": "https://docs.crewai.com/en/observability/weave", "title": "Weave Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nWeave Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nWeave Integration\nCopy page\nLearn how to use Weights & Biases (W&B) Weave to track, experiment with, evaluate, and improve your CrewAI applications.\n​\nWeave Overview\n\n\nWeights & Biases (W&B) Weave\n is a framework for tracking, experimenting with, evaluating, deploying, and improving LLM-based applications.\n\n\n\n\nWeave provides comprehensive support for every stage of your CrewAI application development:\n\n\n\n\nTracing & Monitoring\n: Automatically track LLM calls and application logic to debug and analyze production systems\n\n\nSystematic Iteration\n: Refine and iterate on prompts, datasets, and models\n\n\nEvaluation\n: Use custom or pre-built scorers to systematically assess and enhance agent performance\n\n\nGuardrails\n: Protect your agents with pre- and post-safeguards for content moderation and prompt safety\n\n\n\n\nWeave automatically captures traces for your CrewAI applications, enabling you to monitor and analyze your agents’ performance, interactions, and execution flow. This helps you build better evaluation datasets and optimize your agent workflows.\n\n\n​\nSetup Instructions\n\n\n1\nInstall required packages\nCopy\nAsk AI\npip\n install\n crewai\n weave\n\n\n2\nSet up W&B Account\nSign up for a \nWeights & Biases account\n if you haven’t already. You’ll need this to view your traces and metrics.\n3\nInitialize Weave in Your Application\nAdd the following code to your application:\nCopy\nAsk AI\nimport\n weave\n\n\n\n\n# Initialize Weave with your project name\n\n\nweave.init(\nproject_name\n=\n\"crewai_demo\"\n)\n\n\nAfter initialization, Weave will provide a URL where you can view your traces and metrics.\n4\nCreate your Crews/Flows\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, \nLLM\n, Process\n\n\n\n\n# Create an LLM with a temperature of 0 to ensure deterministic outputs\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n, \ntemperature\n=\n0\n)\n\n\n\n\n# Create agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Research Analyst'\n,\n\n\n goal\n=\n'Find and analyze the best investment opportunities'\n,\n\n\n backstory\n=\n'Expert in financial analysis and market research'\n,\n\n\n llm\n=\nllm,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Report Writer'\n,\n\n\n goal\n=\n'Write clear and concise investment reports'\n,\n\n\n backstory\n=\n'Experienced in creating detailed financial reports'\n,\n\n\n llm\n=\nllm,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\n# Create tasks\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n'Deep research on the \n{topic}\n'\n,\n\n\n expected_output\n=\n'Comprehensive market data including key players, market size, and growth trends.'\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n'Write a detailed report based on the research'\n,\n\n\n expected_output\n=\n'The report should be easy to read and understand. Use bullet points where applicable.'\n,\n\n\n agent\n=\nwriter\n\n\n)\n\n\n\n\n# Create a crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[research_task, writing_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n)\n\n\n\n\n# Run the crew\n\n\nresult \n=\n crew.kickoff(\ninputs\n=\n{\n\"topic\"\n: \n\"AI in material science\"\n})\n\n\nprint\n(result)\n\n\n5\nView Traces in Weave\nAfter running your CrewAI application, visit the Weave URL provided during initialization to view:\n\n\nLLM calls and their metadata\n\n\nAgent interactions and task execution flow\n\n\nPerformance metrics like latency and token usage\n\n\nAny errors or issues that occurred during execution\n\n\nWeave Tracing Dashboard\n\n\n​\nFeatures\n\n\n\n\nWeave automatically captures all CrewAI operations: agent interactions and task executions; LLM calls with metadata and token usage; tool usage and results.\n\n\nThe integration supports all CrewAI execution methods: \nkickoff()\n, \nkickoff_for_each()\n, \nkickoff_async()\n, and \nkickoff_for_each_async()\n.\n\n\nAutomatic tracing of all \ncrewAI-tools\n.\n\n\nFlow feature support with decorator patching (\n@start\n, \n@listen\n, \n@router\n, \n@or_\n, \n@and_\n).\n\n\nTrack custom guardrails passed to CrewAI \nTask\n with \n@weave.op()\n.\n\n\n\n\nFor detailed information on what’s supported, visit the \nWeave CrewAI documentation\n.\n\n\n​\nResources\n\n\n\n\n📘 Weave Documentation\n\n\n📊 Example Weave x CrewAI dashboard\n\n\n🐦 X\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nPortkey Integration\nOverview\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWeave Overview\nSetup Instructions\nFeatures\nResources\nObservability\nWeave Integration\nCopy page\nLearn how to use Weights & Biases (W&B) Weave to track, experiment with, evaluate, and improve your CrewAI applications.\n​\nWeave Overview\n\n\nWeights & Biases (W&B) Weave\n is a framework for tracking, experimenting with, evaluating, deploying, and improving LLM-based applications.\n\n\n\n\nWeave provides comprehensive support for every stage of your CrewAI application development:\n\n\n\n\nTracing & Monitoring\n: Automatically track LLM calls and application logic to debug and analyze production systems\n\n\nSystematic Iteration\n: Refine and iterate on prompts, datasets, and models\n\n\nEvaluation\n: Use custom or pre-built scorers to systematically assess and enhance agent performance\n\n\nGuardrails\n: Protect your agents with pre- and post-safeguards for content moderation and prompt safety\n\n\n\n\nWeave automatically captures traces for your CrewAI applications, enabling you to monitor and analyze your agents’ performance, interactions, and execution flow. This helps you build better evaluation datasets and optimize your agent workflows.\n\n\n​\nSetup Instructions\n\n\n1\nInstall required packages\nCopy\nAsk AI\npip\n install\n crewai\n weave\n\n\n2\nSet up W&B Account\nSign up for a \nWeights & Biases account\n if you haven’t already. You’ll need this to view your traces and metrics.\n3\nInitialize Weave in Your Application\nAdd the following code to your application:\nCopy\nAsk AI\nimport\n weave\n\n\n\n\n# Initialize Weave with your project name\n\n\nweave.init(\nproject_name\n=\n\"crewai_demo\"\n)\n\n\nAfter initialization, Weave will provide a URL where you can view your traces and metrics.\n4\nCreate your Crews/Flows\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, \nLLM\n, Process\n\n\n\n\n# Create an LLM with a temperature of 0 to ensure deterministic outputs\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n, \ntemperature\n=\n0\n)\n\n\n\n\n# Create agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Research Analyst'\n,\n\n\n goal\n=\n'Find and analyze the best investment opportunities'\n,\n\n\n backstory\n=\n'Expert in financial analysis and market research'\n,\n\n\n llm\n=\nllm,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Report Writer'\n,\n\n\n goal\n=\n'Write clear and concise investment reports'\n,\n\n\n backstory\n=\n'Experienced in creating detailed financial reports'\n,\n\n\n llm\n=\nllm,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n)\n\n\n\n\n# Create tasks\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n'Deep research on the \n{topic}\n'\n,\n\n\n expected_output\n=\n'Comprehensive market data including key players, market size, and growth trends.'\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n'Write a detailed report based on the research'\n,\n\n\n expected_output\n=\n'The report should be easy to read and understand. Use bullet points where applicable.'\n,\n\n\n agent\n=\nwriter\n\n\n)\n\n\n\n\n# Create a crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[research_task, writing_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n)\n\n\n\n\n# Run the crew\n\n\nresult \n=\n crew.kickoff(\ninputs\n=\n{\n\"topic\"\n: \n\"AI in material science\"\n})\n\n\nprint\n(result)\n\n\n5\nView Traces in Weave\nAfter running your CrewAI application, visit the Weave URL provided during initialization to view:\n\n\nLLM calls and their metadata\n\n\nAgent interactions and task execution flow\n\n\nPerformance metrics like latency and token usage\n\n\nAny errors or issues that occurred during execution\n\n\nWeave Tracing Dashboard\n\n\n​\nFeatures\n\n\n\n\nWeave automatically captures all CrewAI operations: agent interactions and task executions; LLM calls with metadata and token usage; tool usage and results.\n\n\nThe integration supports all CrewAI execution methods: \nkickoff()\n, \nkickoff_for_each()\n, \nkickoff_async()\n, and \nkickoff_for_each_async()\n.\n\n\nAutomatic tracing of all \ncrewAI-tools\n.\n\n\nFlow feature support with decorator patching (\n@start\n, \n@listen\n, \n@router\n, \n@or_\n, \n@and_\n).\n\n\nTrack custom guardrails passed to CrewAI \nTask\n with \n@weave.op()\n.\n\n\n\n\nFor detailed information on what’s supported, visit the \nWeave CrewAI documentation\n.\n\n\n​\nResources\n\n\n\n\n📘 Weave Documentation\n\n\n📊 Example Weave x CrewAI dashboard\n\n\n🐦 X\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nPortkey Integration\nOverview\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWeave Overview\nSetup Instructions\nFeatures\nResources" }, { "source": "https://docs.crewai.com/en/enterprise/introduction", "title": "CrewAI Enterprise - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGetting Started\nCrewAI Enterprise\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGetting Started\nCrewAI Enterprise\nFeatures\nTool Repository\nWebhook Streaming\nTraces\nHallucination Guardrail\nIntegrations\nAgent Repositories\nIntegration Docs\nAsana Integration\nBox Integration\nClickUp Integration\nGitHub Integration\nGmail Integration\nGoogle Calendar Integration\nGoogle Sheets Integration\nHubSpot Integration\nJira Integration\nLinear Integration\nNotion Integration\nSalesforce Integration\nShopify Integration\nSlack Integration\nStripe Integration\nZendesk Integration\nHow-To Guides\nBuild Crew\nDeploy Crew\nKickoff Crew\nUpdate Crew\nEnable Crew Studio\nAzure OpenAI Setup\nHubSpot Trigger\nReact Component Export\nSalesforce Trigger\nSlack Trigger\nTeam Management\nWebhook Automation\nHITL Workflows\nZapier Trigger\nResources\nFAQs\nGetting Started\nCrewAI Enterprise\nCopy page\nDeploy, monitor, and scale your AI agent workflows\n​\nIntroduction\n\n\nCrewAI Enterprise provides a platform for deploying, monitoring, and scaling your crews and agents in a production environment.\n\n\n\n\nCrewAI Enterprise extends the power of the open-source framework with features designed for production deployments, collaboration, and scalability. Deploy your crews to a managed infrastructure and monitor their execution in real-time.\n\n\n​\nKey Features\n\n\nCrew Deployments\nDeploy your crews to a managed infrastructure with a few clicks\nAPI Access\nAccess your deployed crews via REST API for integration with existing systems\nObservability\nMonitor your crews with detailed execution traces and logs\nTool Repository\nPublish and install tools to enhance your crews’ capabilities\nWebhook Streaming\nStream real-time events and updates to your systems\nCrew Studio\nCreate and customize crews using a no-code/low-code interface\n\n\n​\nDeployment Options\n\n\nGitHub Integration\nConnect directly to your GitHub repositories to deploy code\nCrew Studio\nDeploy crews created through the no-code Crew Studio interface\nCLI Deployment\nUse the CrewAI CLI for more advanced deployment workflows\n\n\n​\nGetting Started\n\n\n1\nSign up for an account\nCreate your account at \napp.crewai.com\nSign Up\nSign Up\n2\nBuild your first crew\nUse code or Crew Studio to build your crew\nBuild Crew\nBuild Crew\n3\nDeploy your crew\nDeploy your crew to the Enterprise platform\nDeploy Crew\nDeploy Crew\n4\nAccess your crew\nIntegrate with your crew via the generated API endpoints\nAPI Access\nUse the Crew API\n\n\nFor detailed instructions, check out our \ndeployment guide\n or click the button below to get started.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTool Repository\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nKey Features\nDeployment Options\nGetting Started\nGetting Started\nCrewAI Enterprise\nCopy page\nDeploy, monitor, and scale your AI agent workflows\n​\nIntroduction\n\n\nCrewAI Enterprise provides a platform for deploying, monitoring, and scaling your crews and agents in a production environment.\n\n\n\n\nCrewAI Enterprise extends the power of the open-source framework with features designed for production deployments, collaboration, and scalability. Deploy your crews to a managed infrastructure and monitor their execution in real-time.\n\n\n​\nKey Features\n\n\nCrew Deployments\nDeploy your crews to a managed infrastructure with a few clicks\nAPI Access\nAccess your deployed crews via REST API for integration with existing systems\nObservability\nMonitor your crews with detailed execution traces and logs\nTool Repository\nPublish and install tools to enhance your crews’ capabilities\nWebhook Streaming\nStream real-time events and updates to your systems\nCrew Studio\nCreate and customize crews using a no-code/low-code interface\n\n\n​\nDeployment Options\n\n\nGitHub Integration\nConnect directly to your GitHub repositories to deploy code\nCrew Studio\nDeploy crews created through the no-code Crew Studio interface\nCLI Deployment\nUse the CrewAI CLI for more advanced deployment workflows\n\n\n​\nGetting Started\n\n\n1\nSign up for an account\nCreate your account at \napp.crewai.com\nSign Up\nSign Up\n2\nBuild your first crew\nUse code or Crew Studio to build your crew\nBuild Crew\nBuild Crew\n3\nDeploy your crew\nDeploy your crew to the Enterprise platform\nDeploy Crew\nDeploy Crew\n4\nAccess your crew\nIntegrate with your crew via the generated API endpoints\nAPI Access\nUse the Crew API\n\n\nFor detailed instructions, check out our \ndeployment guide\n or click the button below to get started.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTool Repository\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nKey Features\nDeployment Options\nGetting Started" }, { "source": "https://docs.crewai.com/en/concepts/processes", "title": "Processes - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nProcesses\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nProcesses\nCopy page\nDetailed guide on workflow management through processes in CrewAI, with updated implementation details.\n​\nOverview\n\n\nProcesses orchestrate the execution of tasks by agents, akin to project management in human teams.\nThese processes ensure tasks are distributed and executed efficiently, in alignment with a predefined strategy.\n\n\n​\nProcess Implementations\n\n\n\n\nSequential\n: Executes tasks sequentially, ensuring tasks are completed in an orderly progression.\n\n\nHierarchical\n: Organizes tasks in a managerial hierarchy, where tasks are delegated and executed based on a structured chain of command. A manager language model (\nmanager_llm\n) or a custom manager agent (\nmanager_agent\n) must be specified in the crew to enable the hierarchical process, facilitating the creation and management of tasks by the manager.\n\n\nConsensual Process (Planned)\n: Aiming for collaborative decision-making among agents on task execution, this process type introduces a democratic approach to task management within CrewAI. It is planned for future development and is not currently implemented in the codebase.\n\n\n\n\n​\nThe Role of Processes in Teamwork\n\n\nProcesses enable individual agents to operate as a cohesive unit, streamlining their efforts to achieve common objectives with efficiency and coherence.\n\n\n​\nAssigning Processes to a Crew\n\n\nTo assign a process to a crew, specify the process type upon crew creation to set the execution strategy. For a hierarchical process, ensure to define \nmanager_llm\n or \nmanager_agent\n for the manager agent.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Process\n\n\n\n\n# Example: Creating a crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\nmy_agents,\n\n\n tasks\n=\nmy_tasks,\n\n\n process\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Example: Creating a crew with a hierarchical process\n\n\n# Ensure to provide a manager_llm or manager_agent\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\nmy_agents,\n\n\n tasks\n=\nmy_tasks,\n\n\n process\n=\nProcess.hierarchical,\n\n\n manager_llm\n=\n\"gpt-4o\"\n\n\n # or\n\n\n # manager_agent=my_manager_agent\n\n\n)\n\n\n\n\nNote:\n Ensure \nmy_agents\n and \nmy_tasks\n are defined prior to creating a \nCrew\n object, and for the hierarchical process, either \nmanager_llm\n or \nmanager_agent\n is also required.\n\n\n​\nSequential Process\n\n\nThis method mirrors dynamic team workflows, progressing through tasks in a thoughtful and systematic manner. Task execution follows the predefined order in the task list, with the output of one task serving as context for the next.\n\n\nTo customize task context, utilize the \ncontext\n parameter in the \nTask\n class to specify outputs that should be used as context for subsequent tasks.\n\n\n​\nHierarchical Process\n\n\nEmulates a corporate hierarchy, CrewAI allows specifying a custom manager agent or automatically creates one, requiring the specification of a manager language model (\nmanager_llm\n). This agent oversees task execution, including planning, delegation, and validation. Tasks are not pre-assigned; the manager allocates tasks to agents based on their capabilities, reviews outputs, and assesses task completion.\n\n\n​\nProcess Class: Detailed Overview\n\n\nThe \nProcess\n class is implemented as an enumeration (\nEnum\n), ensuring type safety and restricting process values to the defined types (\nsequential\n, \nhierarchical\n). The consensual process is planned for future inclusion, emphasizing our commitment to continuous development and innovation.\n\n\n​\nConclusion\n\n\nThe structured collaboration facilitated by processes within CrewAI is crucial for enabling systematic teamwork among agents.\nThis documentation has been updated to reflect the latest features, enhancements, and the planned integration of the Consensual Process, ensuring users have access to the most current and comprehensive information.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nLLMs\nCollaboration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nProcess Implementations\nThe Role of Processes in Teamwork\nAssigning Processes to a Crew\nSequential Process\nHierarchical Process\nProcess Class: Detailed Overview\nConclusion\nCore Concepts\nProcesses\nCopy page\nDetailed guide on workflow management through processes in CrewAI, with updated implementation details.\n​\nOverview\n\n\nProcesses orchestrate the execution of tasks by agents, akin to project management in human teams.\nThese processes ensure tasks are distributed and executed efficiently, in alignment with a predefined strategy.\n\n\n​\nProcess Implementations\n\n\n\n\nSequential\n: Executes tasks sequentially, ensuring tasks are completed in an orderly progression.\n\n\nHierarchical\n: Organizes tasks in a managerial hierarchy, where tasks are delegated and executed based on a structured chain of command. A manager language model (\nmanager_llm\n) or a custom manager agent (\nmanager_agent\n) must be specified in the crew to enable the hierarchical process, facilitating the creation and management of tasks by the manager.\n\n\nConsensual Process (Planned)\n: Aiming for collaborative decision-making among agents on task execution, this process type introduces a democratic approach to task management within CrewAI. It is planned for future development and is not currently implemented in the codebase.\n\n\n\n\n​\nThe Role of Processes in Teamwork\n\n\nProcesses enable individual agents to operate as a cohesive unit, streamlining their efforts to achieve common objectives with efficiency and coherence.\n\n\n​\nAssigning Processes to a Crew\n\n\nTo assign a process to a crew, specify the process type upon crew creation to set the execution strategy. For a hierarchical process, ensure to define \nmanager_llm\n or \nmanager_agent\n for the manager agent.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Process\n\n\n\n\n# Example: Creating a crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\nmy_agents,\n\n\n tasks\n=\nmy_tasks,\n\n\n process\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Example: Creating a crew with a hierarchical process\n\n\n# Ensure to provide a manager_llm or manager_agent\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\nmy_agents,\n\n\n tasks\n=\nmy_tasks,\n\n\n process\n=\nProcess.hierarchical,\n\n\n manager_llm\n=\n\"gpt-4o\"\n\n\n # or\n\n\n # manager_agent=my_manager_agent\n\n\n)\n\n\n\n\nNote:\n Ensure \nmy_agents\n and \nmy_tasks\n are defined prior to creating a \nCrew\n object, and for the hierarchical process, either \nmanager_llm\n or \nmanager_agent\n is also required.\n\n\n​\nSequential Process\n\n\nThis method mirrors dynamic team workflows, progressing through tasks in a thoughtful and systematic manner. Task execution follows the predefined order in the task list, with the output of one task serving as context for the next.\n\n\nTo customize task context, utilize the \ncontext\n parameter in the \nTask\n class to specify outputs that should be used as context for subsequent tasks.\n\n\n​\nHierarchical Process\n\n\nEmulates a corporate hierarchy, CrewAI allows specifying a custom manager agent or automatically creates one, requiring the specification of a manager language model (\nmanager_llm\n). This agent oversees task execution, including planning, delegation, and validation. Tasks are not pre-assigned; the manager allocates tasks to agents based on their capabilities, reviews outputs, and assesses task completion.\n\n\n​\nProcess Class: Detailed Overview\n\n\nThe \nProcess\n class is implemented as an enumeration (\nEnum\n), ensuring type safety and restricting process values to the defined types (\nsequential\n, \nhierarchical\n). The consensual process is planned for future inclusion, emphasizing our commitment to continuous development and innovation.\n\n\n​\nConclusion\n\n\nThe structured collaboration facilitated by processes within CrewAI is crucial for enabling systematic teamwork among agents.\nThis documentation has been updated to reflect the latest features, enhancements, and the planned integration of the Consensual Process, ensuring users have access to the most current and comprehensive information.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nLLMs\nCollaboration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nProcess Implementations\nThe Role of Processes in Teamwork\nAssigning Processes to a Crew\nSequential Process\nHierarchical Process\nProcess Class: Detailed Overview\nConclusion" }, { "source": "https://docs.crewai.com/en/concepts/memory", "title": "Memory - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nMemory\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nMemory\nCopy page\nLeveraging memory systems in the CrewAI framework to enhance agent capabilities.\n​\nOverview\n\n\nThe CrewAI framework provides a sophisticated memory system designed to significantly enhance AI agent capabilities. CrewAI offers \nthree distinct memory approaches\n that serve different use cases:\n\n\n\n\nBasic Memory System\n - Built-in short-term, long-term, and entity memory\n\n\nUser Memory\n - User-specific memory with Mem0 integration (legacy approach)\n\n\nExternal Memory\n - Standalone external memory providers (new approach)\n\n\n\n\n​\nMemory System Components\n\n\nComponent\nDescription\nShort-Term Memory\nTemporarily stores recent interactions and outcomes using \nRAG\n, enabling agents to recall and utilize information relevant to their current context during the current executions.\nLong-Term Memory\nPreserves valuable insights and learnings from past executions, allowing agents to build and refine their knowledge over time.\nEntity Memory\nCaptures and organizes information about entities (people, places, concepts) encountered during tasks, facilitating deeper understanding and relationship mapping. Uses \nRAG\n for storing entity information.\nContextual Memory\nMaintains the context of interactions by combining \nShortTermMemory\n, \nLongTermMemory\n, and \nEntityMemory\n, aiding in the coherence and relevance of agent responses over a sequence of tasks or a conversation.\n\n\n​\n1. Basic Memory System (Recommended)\n\n\nThe simplest and most commonly used approach. Enable memory for your crew with a single parameter:\n\n\n​\nQuick Start\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task, Process\n\n\n\n\n# Enable basic memory system\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n process\n=\nProcess.sequential,\n\n\n memory\n=\nTrue\n, \n# Enables short-term, long-term, and entity memory\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nHow It Works\n\n\n\n\nShort-Term Memory\n: Uses ChromaDB with RAG for current context\n\n\nLong-Term Memory\n: Uses SQLite3 to store task results across sessions\n\n\nEntity Memory\n: Uses RAG to track entities (people, places, concepts)\n\n\nStorage Location\n: Platform-specific location via \nappdirs\n package\n\n\nCustom Storage Directory\n: Set \nCREWAI_STORAGE_DIR\n environment variable\n\n\n\n\n​\nStorage Location Transparency\n\n\nUnderstanding Storage Locations\n: CrewAI uses platform-specific directories to store memory and knowledge files following OS conventions. Understanding these locations helps with production deployments, backups, and debugging.\n\n\n​\nWhere CrewAI Stores Files\n\n\nBy default, CrewAI uses the \nappdirs\n library to determine storage locations following platform conventions. Here’s exactly where your files are stored:\n\n\n​\nDefault Storage Locations by Platform\n\n\nmacOS:\n\n\nCopy\nAsk AI\n~/Library/Application Support/CrewAI/{project_name}/\n\n\n├── knowledge/ # Knowledge base ChromaDB files\n\n\n├── short_term_memory/ # Short-term memory ChromaDB files\n\n\n├── long_term_memory/ # Long-term memory ChromaDB files\n\n\n├── entities/ # Entity memory ChromaDB files\n\n\n└── long_term_memory_storage.db # SQLite database\n\n\n\n\nLinux:\n\n\nCopy\nAsk AI\n~/.local/share/CrewAI/{project_name}/\n\n\n├── knowledge/\n\n\n├── short_term_memory/\n\n\n├── long_term_memory/\n\n\n├── entities/\n\n\n└── long_term_memory_storage.db\n\n\n\n\nWindows:\n\n\nCopy\nAsk AI\nC:\\Users\\{username}\\AppData\\Local\\CrewAI\\{project_name}\\\n\n\n├── knowledge\\\n\n\n├── short_term_memory\\\n\n\n├── long_term_memory\\\n\n\n├── entities\\\n\n\n└── long_term_memory_storage.db\n\n\n\n\n​\nFinding Your Storage Location\n\n\nTo see exactly where CrewAI is storing files on your system:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\nimport\n os\n\n\n\n\n# Get the base storage path\n\n\nstorage_path \n=\n db_storage_path()\n\n\nprint\n(\nf\n\"CrewAI storage location: \n{\nstorage_path\n}\n\"\n)\n\n\n\n\n# List all CrewAI storage directories\n\n\nif\n os.path.exists(storage_path):\n\n\n print\n(\n\"\n\\n\nStored files and directories:\"\n)\n\n\n for\n item \nin\n os.listdir(storage_path):\n\n\n item_path \n=\n os.path.join(storage_path, item)\n\n\n if\n os.path.isdir(item_path):\n\n\n print\n(\nf\n\"📁 \n{\nitem\n}\n/\"\n)\n\n\n # Show ChromaDB collections\n\n\n if\n os.path.exists(item_path):\n\n\n for\n subitem \nin\n os.listdir(item_path):\n\n\n print\n(\nf\n\" └── \n{\nsubitem\n}\n\"\n)\n\n\n else\n:\n\n\n print\n(\nf\n\"📄 \n{\nitem\n}\n\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No CrewAI storage directory found yet.\"\n)\n\n\n\n\n​\nControlling Storage Locations\n\n\n​\nOption 1: Environment Variable (Recommended)\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Set custom storage location\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n \"./my_project_storage\"\n\n\n\n\n# All memory and knowledge will now be stored in ./my_project_storage/\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n\n\n)\n\n\n\n\n​\nOption 2: Custom Storage Paths\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\nfrom\n crewai.memory \nimport\n LongTermMemory\n\n\nfrom\n crewai.memory.storage.ltm_sqlite_storage \nimport\n LTMSQLiteStorage\n\n\n\n\n# Configure custom storage location\n\n\ncustom_storage_path \n=\n \"./storage\"\n\n\nos.makedirs(custom_storage_path, \nexist_ok\n=\nTrue\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n long_term_memory\n=\nLongTermMemory(\n\n\n storage\n=\nLTMSQLiteStorage(\n\n\n db_path\n=\nf\n\"\n{\ncustom_storage_path\n}\n/memory.db\"\n\n\n )\n\n\n )\n\n\n)\n\n\n\n\n​\nOption 3: Project-Specific Storage\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n pathlib \nimport\n Path\n\n\n\n\n# Store in project directory\n\n\nproject_root \n=\n Path(\n__file__\n).parent\n\n\nstorage_dir \n=\n project_root \n/\n \"crewai_storage\"\n\n\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n str\n(storage_dir)\n\n\n\n\n# Now all storage will be in your project directory\n\n\n\n\n​\nEmbedding Provider Defaults\n\n\nDefault Embedding Provider\n: CrewAI defaults to OpenAI embeddings for consistency and reliability. You can easily customize this to match your LLM provider or use local embeddings.\n\n\n​\nUnderstanding Default Behavior\n\n\nCopy\nAsk AI\n# When using Claude as your LLM...\n\n\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Analyst\"\n,\n\n\n goal\n=\n\"Analyze data\"\n,\n\n\n backstory\n=\n\"Expert analyst\"\n,\n\n\n llm\n=\nLLM(\nprovider\n=\n\"anthropic\"\n, \nmodel\n=\n\"claude-3-sonnet\"\n) \n# Using Claude\n\n\n)\n\n\n\n\n# CrewAI will use OpenAI embeddings by default for consistency\n\n\n# You can easily customize this to match your preferred provider\n\n\n\n\n​\nCustomizing Embedding Providers\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Option 1: Match your LLM provider\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"anthropic\"\n, \n# Match your LLM provider\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-anthropic-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Option 2: Use local embeddings (no external API calls)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n }\n\n\n)\n\n\n\n\n​\nDebugging Storage Issues\n\n\n​\nCheck Storage Permissions\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\nstorage_path \n=\n db_storage_path()\n\n\nprint\n(\nf\n\"Storage path: \n{\nstorage_path\n}\n\"\n)\n\n\nprint\n(\nf\n\"Path exists: \n{\nos.path.exists(storage_path)\n}\n\"\n)\n\n\nprint\n(\nf\n\"Is writable: \n{\nos.access(storage_path, os.\nW_OK\n) \nif\n os.path.exists(storage_path) \nelse\n 'Path does not exist'\n}\n\"\n)\n\n\n\n\n# Create with proper permissions\n\n\nif\n not\n os.path.exists(storage_path):\n\n\n os.makedirs(storage_path, \nmode\n=\n0o\n755\n, \nexist_ok\n=\nTrue\n)\n\n\n print\n(\nf\n\"Created storage directory: \n{\nstorage_path\n}\n\"\n)\n\n\n\n\n​\nInspect ChromaDB Collections\n\n\nCopy\nAsk AI\nimport\n chromadb\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\n# Connect to CrewAI's ChromaDB\n\n\nstorage_path \n=\n db_storage_path()\n\n\nchroma_path \n=\n os.path.join(storage_path, \n\"knowledge\"\n)\n\n\n\n\nif\n os.path.exists(chroma_path):\n\n\n client \n=\n chromadb.PersistentClient(\npath\n=\nchroma_path)\n\n\n collections \n=\n client.list_collections()\n\n\n\n\n print\n(\n\"ChromaDB Collections:\"\n)\n\n\n for\n collection \nin\n collections:\n\n\n print\n(\nf\n\" - \n{\ncollection.name\n}\n: \n{\ncollection.count()\n}\n documents\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No ChromaDB storage found\"\n)\n\n\n\n\n​\nReset Storage (Debugging)\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Reset all memory storage\n\n\ncrew \n=\n Crew(\nagents\n=\n[\n...\n], \ntasks\n=\n[\n...\n], \nmemory\n=\nTrue\n)\n\n\n\n\n# Reset specific memory types\n\n\ncrew.reset_memories(\ncommand_type\n=\n'short'\n) \n# Short-term memory\n\n\ncrew.reset_memories(\ncommand_type\n=\n'long'\n) \n# Long-term memory\n\n\ncrew.reset_memories(\ncommand_type\n=\n'entity'\n) \n# Entity memory\n\n\ncrew.reset_memories(\ncommand_type\n=\n'knowledge'\n) \n# Knowledge storage\n\n\n\n\n​\nProduction Best Practices\n\n\n\n\nSet \nCREWAI_STORAGE_DIR\n to a known location in production for better control\n\n\nChoose explicit embedding providers\n to match your LLM setup\n\n\nMonitor storage directory size\n for large-scale deployments\n\n\nInclude storage directories\n in your backup strategy\n\n\nSet appropriate file permissions\n (0o755 for directories, 0o644 for files)\n\n\nUse project-relative paths\n for containerized deployments\n\n\n\n\n​\nCommon Storage Issues\n\n\n“ChromaDB permission denied” errors:\n\n\nCopy\nAsk AI\n# Fix permissions\n\n\nchmod\n -R\n 755\n ~/.local/share/CrewAI/\n\n\n\n\n“Database is locked” errors:\n\n\nCopy\nAsk AI\n# Ensure only one CrewAI instance accesses storage\n\n\nimport\n fcntl\n\n\nimport\n os\n\n\n\n\nstorage_path \n=\n db_storage_path()\n\n\nlock_file \n=\n os.path.join(storage_path, \n\".crewai.lock\"\n)\n\n\n\n\nwith\n open\n(lock_file, \n'w'\n) \nas\n f:\n\n\n fcntl.flock(f.fileno(), fcntl.\nLOCK_EX\n |\n fcntl.\nLOCK_NB\n)\n\n\n # Your CrewAI code here\n\n\n\n\nStorage not persisting between runs:\n\n\nCopy\nAsk AI\n# Verify storage location is consistent\n\n\nimport\n os\n\n\nprint\n(\n\"CREWAI_STORAGE_DIR:\"\n, os.getenv(\n\"CREWAI_STORAGE_DIR\"\n))\n\n\nprint\n(\n\"Current working directory:\"\n, os.getcwd())\n\n\nprint\n(\n\"Computed storage path:\"\n, db_storage_path())\n\n\n\n\n​\nCustom Embedder Configuration\n\n\nCrewAI supports multiple embedding providers to give you flexibility in choosing the best option for your use case. Here’s a comprehensive guide to configuring different embedding providers for your memory system.\n\n\n​\nWhy Choose Different Embedding Providers?\n\n\n\n\nCost Optimization\n: Local embeddings (Ollama) are free after initial setup\n\n\nPrivacy\n: Keep your data local with Ollama or use your preferred cloud provider\n\n\nPerformance\n: Some models work better for specific domains or languages\n\n\nConsistency\n: Match your embedding provider with your LLM provider\n\n\nCompliance\n: Meet specific regulatory or organizational requirements\n\n\n\n\n​\nOpenAI Embeddings (Default)\n\n\nOpenAI provides reliable, high-quality embeddings that work well for most use cases.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Basic OpenAI configuration (uses environment OPENAI_API_KEY)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n # or \"text-embedding-3-large\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Advanced OpenAI configuration\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-openai-api-key\"\n, \n# Optional: override env var\n\n\n \"model\"\n: \n\"text-embedding-3-large\"\n,\n\n\n \"dimensions\"\n: \n1536\n, \n# Optional: reduce dimensions for smaller storage\n\n\n \"organization_id\"\n: \n\"your-org-id\"\n # Optional: for organization accounts\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAzure OpenAI Embeddings\n\n\nFor enterprise users with Azure OpenAI deployments.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n, \n# Use openai provider for Azure\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-azure-api-key\"\n,\n\n\n \"api_base\"\n: \n\"https://your-resource.openai.azure.com/\"\n,\n\n\n \"api_type\"\n: \n\"azure\"\n,\n\n\n \"api_version\"\n: \n\"2023-05-15\"\n,\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n,\n\n\n \"deployment_id\"\n: \n\"your-deployment-name\"\n # Azure deployment name\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nGoogle AI Embeddings\n\n\nUse Google’s text embedding models for integration with Google Cloud services.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-google-api-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-004\"\n # or \"text-embedding-preview-0409\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nVertex AI Embeddings\n\n\nFor Google Cloud users with Vertex AI access.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"vertexai\"\n,\n\n\n \"config\"\n: {\n\n\n \"project_id\"\n: \n\"your-gcp-project-id\"\n,\n\n\n \"region\"\n: \n\"us-central1\"\n, \n# or your preferred region\n\n\n \"api_key\"\n: \n\"your-service-account-key\"\n,\n\n\n \"model_name\"\n: \n\"textembedding-gecko\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nOllama Embeddings (Local)\n\n\nRun embeddings locally for privacy and cost savings.\n\n\nCopy\nAsk AI\n# First, install and run Ollama locally, then pull an embedding model:\n\n\n# ollama pull mxbai-embed-large\n\n\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"mxbai-embed-large\"\n, \n# or \"nomic-embed-text\"\n\n\n \"url\"\n: \n\"http://localhost:11434/api/embeddings\"\n # Default Ollama URL\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# For custom Ollama installations\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"mxbai-embed-large\"\n,\n\n\n \"url\"\n: \n\"http://your-ollama-server:11434/api/embeddings\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nCohere Embeddings\n\n\nUse Cohere’s embedding models for multilingual support.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"cohere\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-cohere-api-key\"\n,\n\n\n \"model\"\n: \n\"embed-english-v3.0\"\n # or \"embed-multilingual-v3.0\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nVoyageAI Embeddings\n\n\nHigh-performance embeddings optimized for retrieval tasks.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"voyageai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-voyage-api-key\"\n,\n\n\n \"model\"\n: \n\"voyage-large-2\"\n, \n# or \"voyage-code-2\" for code\n\n\n \"input_type\"\n: \n\"document\"\n # or \"query\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAWS Bedrock Embeddings\n\n\nFor AWS users with Bedrock access.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"bedrock\"\n,\n\n\n \"config\"\n: {\n\n\n \"aws_access_key_id\"\n: \n\"your-access-key\"\n,\n\n\n \"aws_secret_access_key\"\n: \n\"your-secret-key\"\n,\n\n\n \"region_name\"\n: \n\"us-east-1\"\n,\n\n\n \"model\"\n: \n\"amazon.titan-embed-text-v1\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nHugging Face Embeddings\n\n\nUse open-source models from Hugging Face.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"huggingface\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-hf-token\"\n, \n# Optional for public models\n\n\n \"model\"\n: \n\"sentence-transformers/all-MiniLM-L6-v2\"\n,\n\n\n \"api_url\"\n: \n\"https://api-inference.huggingface.co\"\n # or your custom endpoint\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nIBM Watson Embeddings\n\n\nFor IBM Cloud users.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"watson\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-watson-api-key\"\n,\n\n\n \"url\"\n: \n\"your-watson-instance-url\"\n,\n\n\n \"model\"\n: \n\"ibm/slate-125m-english-rtrvr\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nChoosing the Right Embedding Provider\n\n\nProvider\nBest For\nPros\nCons\nOpenAI\nGeneral use, reliability\nHigh quality, well-tested\nCost, requires API key\nOllama\nPrivacy, cost savings\nFree, local, private\nRequires local setup\nGoogle AI\nGoogle ecosystem\nGood performance\nRequires Google account\nAzure OpenAI\nEnterprise, compliance\nEnterprise features\nComplex setup\nCohere\nMultilingual content\nGreat language support\nSpecialized use case\nVoyageAI\nRetrieval tasks\nOptimized for search\nNewer provider\n\n\n​\nEnvironment Variable Configuration\n\n\nFor security, store API keys in environment variables:\n\n\nCopy\nAsk AI\nimport\n os\n\n\n\n\n# Set environment variables\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"your-openai-key\"\n\n\nos.environ[\n\"GOOGLE_API_KEY\"\n] \n=\n \"your-google-key\"\n\n\nos.environ[\n\"COHERE_API_KEY\"\n] \n=\n \"your-cohere-key\"\n\n\n\n\n# Use without exposing keys in code\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n\n\n # API key automatically loaded from environment\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nTesting Different Embedding Providers\n\n\nCompare embedding providers for your specific use case:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\n# Test different providers with the same data\n\n\nproviders_to_test \n=\n [\n\n\n {\n\n\n \"name\"\n: \n\"OpenAI\"\n,\n\n\n \"config\"\n: {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n },\n\n\n {\n\n\n \"name\"\n: \n\"Ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n }\n\n\n }\n\n\n]\n\n\n\n\nfor\n provider \nin\n providers_to_test:\n\n\n print\n(\nf\n\"\n\\n\nTesting \n{\nprovider[\n'name'\n]\n}\n embeddings...\"\n)\n\n\n\n\n # Create crew with specific embedder\n\n\n crew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\nprovider[\n'config'\n]\n\n\n )\n\n\n\n\n # Run your test and measure performance\n\n\n result \n=\n crew.kickoff()\n\n\n print\n(\nf\n\"\n{\nprovider[\n'name'\n]\n}\n completed successfully\"\n)\n\n\n\n\n​\nTroubleshooting Embedding Issues\n\n\nModel not found errors:\n\n\nCopy\nAsk AI\n# Verify model availability\n\n\nfrom\n crewai.utilities.embedding_configurator \nimport\n EmbeddingConfigurator\n\n\n\n\nconfigurator \n=\n EmbeddingConfigurator()\n\n\ntry\n:\n\n\n embedder \n=\n configurator.configure_embedder({\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n })\n\n\n print\n(\n\"Embedder configured successfully\"\n)\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Configuration error: \n{\ne\n}\n\"\n)\n\n\n\n\nAPI key issues:\n\n\nCopy\nAsk AI\nimport\n os\n\n\n\n\n# Check if API keys are set\n\n\nrequired_keys \n=\n [\n\"OPENAI_API_KEY\"\n, \n\"GOOGLE_API_KEY\"\n, \n\"COHERE_API_KEY\"\n]\n\n\nfor\n key \nin\n required_keys:\n\n\n if\n os.getenv(key):\n\n\n print\n(\nf\n\"✅ \n{\nkey\n}\n is set\"\n)\n\n\n else\n:\n\n\n print\n(\nf\n\"❌ \n{\nkey\n}\n is not set\"\n)\n\n\n\n\nPerformance comparison:\n\n\nCopy\nAsk AI\nimport\n time\n\n\n\n\ndef\n test_embedding_performance\n(\nembedder_config\n, \ntest_text\n=\n\"This is a test document\"\n):\n\n\n start_time \n=\n time.time()\n\n\n\n\n crew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\nembedder_config\n\n\n )\n\n\n\n\n # Simulate memory operation\n\n\n crew.kickoff()\n\n\n\n\n end_time \n=\n time.time()\n\n\n return\n end_time \n-\n start_time\n\n\n\n\n# Compare performance\n\n\nopenai_time \n=\n test_embedding_performance({\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n})\n\n\n\n\nollama_time \n=\n test_embedding_performance({\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n})\n\n\n\n\nprint\n(\nf\n\"OpenAI: \n{\nopenai_time\n:.2f}\ns\"\n)\n\n\nprint\n(\nf\n\"Ollama: \n{\nollama_time\n:.2f}\ns\"\n)\n\n\n\n\n​\n2. User Memory with Mem0 (Legacy)\n\n\nLegacy Approach\n: While fully functional, this approach is considered legacy. For new projects requiring user-specific memory, consider using External Memory instead.\n\n\nUser Memory integrates with \nMem0\n to provide user-specific memory that persists across sessions and integrates with the crew’s contextual memory system.\n\n\n​\nPrerequisites\n\n\nCopy\nAsk AI\npip\n install\n mem0ai\n\n\n\n\n​\nMem0 Cloud Configuration\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew, Process\n\n\n\n\n# Set your Mem0 API key\n\n\nos.environ[\n\"MEM0_API_KEY\"\n] \n=\n \"m0-your-api-key\"\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n, \n# Required for contextual memory integration\n\n\n memory_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\"user_id\"\n: \n\"john\"\n},\n\n\n \"user_memory\"\n: {} \n# Required - triggers user memory initialization\n\n\n },\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nAdvanced Mem0 Configuration\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n memory_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\n\n \"user_id\"\n: \n\"john\"\n,\n\n\n \"org_id\"\n: \n\"my_org_id\"\n, \n# Optional\n\n\n \"project_id\"\n: \n\"my_project_id\"\n, \n# Optional\n\n\n \"api_key\"\n: \n\"custom-api-key\"\n # Optional - overrides env var\n\n\n },\n\n\n \"user_memory\"\n: {}\n\n\n }\n\n\n)\n\n\n\n\n​\nLocal Mem0 Configuration\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n memory_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\n\n \"user_id\"\n: \n\"john\"\n,\n\n\n \"local_mem0_config\"\n: {\n\n\n \"vector_store\"\n: {\n\n\n \"provider\"\n: \n\"qdrant\"\n,\n\n\n \"config\"\n: {\n\"host\"\n: \n\"localhost\"\n, \n\"port\"\n: \n6333\n}\n\n\n },\n\n\n \"llm\"\n: {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"api_key\"\n: \n\"your-api-key\"\n, \n\"model\"\n: \n\"gpt-4\"\n}\n\n\n },\n\n\n \"embedder\"\n: {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"api_key\"\n: \n\"your-api-key\"\n, \n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n }\n\n\n },\n\n\n \"user_memory\"\n: {}\n\n\n }\n\n\n)\n\n\n\n\n​\n3. External Memory (New Approach)\n\n\nExternal Memory provides a standalone memory system that operates independently from the crew’s built-in memory. This is ideal for specialized memory providers or cross-application memory sharing.\n\n\n​\nBasic External Memory with Mem0\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.memory.external.external_memory \nimport\n ExternalMemory\n\n\n\n\nos.environ[\n\"MEM0_API_KEY\"\n] \n=\n \"your-api-key\"\n\n\n\n\n# Create external memory instance\n\n\nexternal_memory \n=\n ExternalMemory(\n\n\n embedder_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\"user_id\"\n: \n\"U-123\"\n}\n\n\n }\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n external_memory\n=\nexternal_memory, \n# Separate from basic memory\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nCustom Storage Implementation\n\n\nCopy\nAsk AI\nfrom\n crewai.memory.external.external_memory \nimport\n ExternalMemory\n\n\nfrom\n crewai.memory.storage.interface \nimport\n Storage\n\n\n\n\nclass\n CustomStorage\n(\nStorage\n):\n\n\n def\n __init__\n(\nself\n):\n\n\n self\n.memories \n=\n []\n\n\n\n\n def\n save\n(\nself\n, \nvalue\n, \nmetadata\n=\nNone\n, \nagent\n=\nNone\n):\n\n\n self\n.memories.append({\n\n\n \"value\"\n: value,\n\n\n \"metadata\"\n: metadata,\n\n\n \"agent\"\n: agent\n\n\n })\n\n\n\n\n def\n search\n(\nself\n, \nquery\n, \nlimit\n=\n10\n, \nscore_threshold\n=\n0.5\n):\n\n\n # Implement your search logic here\n\n\n return\n [m \nfor\n m \nin\n self\n.memories \nif\n query.lower() \nin\n str\n(m[\n\"value\"\n]).lower()]\n\n\n\n\n def\n reset\n(\nself\n):\n\n\n self\n.memories \n=\n []\n\n\n\n\n# Use custom storage\n\n\nexternal_memory \n=\n ExternalMemory(\nstorage\n=\nCustomStorage())\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n external_memory\n=\nexternal_memory\n\n\n)\n\n\n\n\n​\nMemory System Comparison\n\n\nFeature\nBasic Memory\nUser Memory (Legacy)\nExternal Memory\nSetup Complexity\nSimple\nMedium\nMedium\nIntegration\nBuilt-in contextual\nContextual + User-specific\nStandalone\nStorage\nLocal files\nMem0 Cloud/Local\nCustom/Mem0\nCross-session\n✅\n✅\n✅\nUser-specific\n❌\n✅\n✅\nCustom providers\nLimited\nMem0 only\nAny provider\nRecommended for\nMost use cases\nLegacy projects\nSpecialized needs\n\n\n​\nSupported Embedding Providers\n\n\n​\nOpenAI (Default)\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n)\n\n\n\n\n​\nOllama\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n }\n\n\n)\n\n\n\n\n​\nGoogle AI\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-api-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-004\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAzure OpenAI\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-api-key\"\n,\n\n\n \"api_base\"\n: \n\"https://your-resource.openai.azure.com/\"\n,\n\n\n \"api_version\"\n: \n\"2023-05-15\"\n,\n\n\n \"model_name\"\n: \n\"text-embedding-3-small\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nVertex AI\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"vertexai\"\n,\n\n\n \"config\"\n: {\n\n\n \"project_id\"\n: \n\"your-project-id\"\n,\n\n\n \"region\"\n: \n\"your-region\"\n,\n\n\n \"api_key\"\n: \n\"your-api-key\"\n,\n\n\n \"model_name\"\n: \n\"textembedding-gecko\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nSecurity Best Practices\n\n\n​\nEnvironment Variables\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Store sensitive data in environment variables\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: os.getenv(\n\"OPENAI_API_KEY\"\n),\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nStorage Security\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\nfrom\n crewai.memory \nimport\n LongTermMemory\n\n\nfrom\n crewai.memory.storage.ltm_sqlite_storage \nimport\n LTMSQLiteStorage\n\n\n\n\n# Use secure storage paths\n\n\nstorage_path \n=\n os.getenv(\n\"CREWAI_STORAGE_DIR\"\n, \n\"./storage\"\n)\n\n\nos.makedirs(storage_path, \nmode\n=\n0o\n700\n, \nexist_ok\n=\nTrue\n) \n# Restricted permissions\n\n\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n long_term_memory\n=\nLongTermMemory(\n\n\n storage\n=\nLTMSQLiteStorage(\n\n\n db_path\n=\nf\n\"\n{\nstorage_path\n}\n/memory.db\"\n\n\n )\n\n\n )\n\n\n)\n\n\n\n\n​\nTroubleshooting\n\n\n​\nCommon Issues\n\n\nMemory not persisting between sessions?\n\n\n\n\nCheck \nCREWAI_STORAGE_DIR\n environment variable\n\n\nEnsure write permissions to storage directory\n\n\nVerify memory is enabled with \nmemory=True\n\n\n\n\nMem0 authentication errors?\n\n\n\n\nVerify \nMEM0_API_KEY\n environment variable is set\n\n\nCheck API key permissions on Mem0 dashboard\n\n\nEnsure \nmem0ai\n package is installed\n\n\n\n\nHigh memory usage with large datasets?\n\n\n\n\nConsider using External Memory with custom storage\n\n\nImplement pagination in custom storage search methods\n\n\nUse smaller embedding models for reduced memory footprint\n\n\n\n\n​\nPerformance Tips\n\n\n\n\nUse \nmemory=True\n for most use cases (simplest and fastest)\n\n\nOnly use User Memory if you need user-specific persistence\n\n\nConsider External Memory for high-scale or specialized requirements\n\n\nChoose smaller embedding models for faster processing\n\n\nSet appropriate search limits to control memory retrieval size\n\n\n\n\n​\nBenefits of Using CrewAI’s Memory System\n\n\n\n\n🦾 \nAdaptive Learning:\n Crews become more efficient over time, adapting to new information and refining their approach to tasks.\n\n\n🫡 \nEnhanced Personalization:\n Memory enables agents to remember user preferences and historical interactions, leading to personalized experiences.\n\n\n🧠 \nImproved Problem Solving:\n Access to a rich memory store aids agents in making more informed decisions, drawing on past learnings and contextual insights.\n\n\n\n\n​\nMemory Events\n\n\nCrewAI’s event system provides powerful insights into memory operations. By leveraging memory events, you can monitor, debug, and optimize your memory system’s performance and behavior.\n\n\n​\nAvailable Memory Events\n\n\nCrewAI emits the following memory-related events:\n\n\nEvent\nDescription\nKey Properties\nMemoryQueryStartedEvent\nEmitted when a memory query begins\nquery\n, \nlimit\n, \nscore_threshold\nMemoryQueryCompletedEvent\nEmitted when a memory query completes successfully\nquery\n, \nresults\n, \nlimit\n, \nscore_threshold\n, \nquery_time_ms\nMemoryQueryFailedEvent\nEmitted when a memory query fails\nquery\n, \nlimit\n, \nscore_threshold\n, \nerror\nMemorySaveStartedEvent\nEmitted when a memory save operation begins\nvalue\n, \nmetadata\n, \nagent_role\nMemorySaveCompletedEvent\nEmitted when a memory save operation completes successfully\nvalue\n, \nmetadata\n, \nagent_role\n, \nsave_time_ms\nMemorySaveFailedEvent\nEmitted when a memory save operation fails\nvalue\n, \nmetadata\n, \nagent_role\n, \nerror\nMemoryRetrievalStartedEvent\nEmitted when memory retrieval for a task prompt starts\ntask_id\nMemoryRetrievalCompletedEvent\nEmitted when memory retrieval completes successfully\ntask_id\n, \nmemory_content\n, \nretrieval_time_ms\n\n\n​\nPractical Applications\n\n\n​\n1. Memory Performance Monitoring\n\n\nTrack memory operation timing to optimize your application:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemoryQueryCompletedEvent,\n\n\n MemorySaveCompletedEvent\n\n\n)\n\n\nimport\n time\n\n\n\n\nclass\n MemoryPerformanceMonitor\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n):\n\n\n super\n().\n__init__\n()\n\n\n self\n.query_times \n=\n []\n\n\n self\n.save_times \n=\n []\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemoryQueryCompletedEvent)\n\n\n def\n on_memory_query_completed\n(\nsource\n, \nevent\n: MemoryQueryCompletedEvent):\n\n\n self\n.query_times.append(event.query_time_ms)\n\n\n print\n(\nf\n\"Memory query completed in \n{\nevent.query_time_ms\n:.2f}\nms. Query: '\n{\nevent.query\n}\n'\"\n)\n\n\n print\n(\nf\n\"Average query time: \n{\nsum\n(\nself\n.query_times)\n/\nlen\n(\nself\n.query_times)\n:.2f}\nms\"\n)\n\n\n\n\n @crewai_event_bus.on\n(MemorySaveCompletedEvent)\n\n\n def\n on_memory_save_completed\n(\nsource\n, \nevent\n: MemorySaveCompletedEvent):\n\n\n self\n.save_times.append(event.save_time_ms)\n\n\n print\n(\nf\n\"Memory save completed in \n{\nevent.save_time_ms\n:.2f}\nms\"\n)\n\n\n print\n(\nf\n\"Average save time: \n{\nsum\n(\nself\n.save_times)\n/\nlen\n(\nself\n.save_times)\n:.2f}\nms\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nmemory_monitor \n=\n MemoryPerformanceMonitor()\n\n\n\n\n​\n2. Memory Content Logging\n\n\nLog memory operations for debugging and insights:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemorySaveStartedEvent,\n\n\n MemoryQueryStartedEvent,\n\n\n MemoryRetrievalCompletedEvent\n\n\n)\n\n\nimport\n logging\n\n\n\n\n# Configure logging\n\n\nlogger \n=\n logging.getLogger(\n'memory_events'\n)\n\n\n\n\nclass\n MemoryLogger\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemorySaveStartedEvent)\n\n\n def\n on_memory_save_started\n(\nsource\n, \nevent\n: MemorySaveStartedEvent):\n\n\n if\n event.agent_role:\n\n\n logger.info(\nf\n\"Agent '\n{\nevent.agent_role\n}\n' saving memory: \n{\nevent.value[:\n50\n]\n}\n...\"\n)\n\n\n else\n:\n\n\n logger.info(\nf\n\"Saving memory: \n{\nevent.value[:\n50\n]\n}\n...\"\n)\n\n\n\n\n @crewai_event_bus.on\n(MemoryQueryStartedEvent)\n\n\n def\n on_memory_query_started\n(\nsource\n, \nevent\n: MemoryQueryStartedEvent):\n\n\n logger.info(\nf\n\"Memory query started: '\n{\nevent.query\n}\n' (limit: \n{\nevent.limit\n}\n)\"\n)\n\n\n\n\n @crewai_event_bus.on\n(MemoryRetrievalCompletedEvent)\n\n\n def\n on_memory_retrieval_completed\n(\nsource\n, \nevent\n: MemoryRetrievalCompletedEvent):\n\n\n if\n event.task_id:\n\n\n logger.info(\nf\n\"Memory retrieved for task \n{\nevent.task_id\n}\n in \n{\nevent.retrieval_time_ms\n:.2f}\nms\"\n)\n\n\n else\n:\n\n\n logger.info(\nf\n\"Memory retrieved in \n{\nevent.retrieval_time_ms\n:.2f}\nms\"\n)\n\n\n logger.debug(\nf\n\"Memory content: \n{\nevent.memory_content\n}\n\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nmemory_logger \n=\n MemoryLogger()\n\n\n\n\n​\n3. Error Tracking and Notifications\n\n\nCapture and respond to memory errors:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemorySaveFailedEvent,\n\n\n MemoryQueryFailedEvent\n\n\n)\n\n\nimport\n logging\n\n\nfrom\n typing \nimport\n Optional\n\n\n\n\n# Configure logging\n\n\nlogger \n=\n logging.getLogger(\n'memory_errors'\n)\n\n\n\n\nclass\n MemoryErrorTracker\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n, \nnotify_email\n: Optional[\nstr\n] \n=\n None\n):\n\n\n super\n().\n__init__\n()\n\n\n self\n.notify_email \n=\n notify_email\n\n\n self\n.error_count \n=\n 0\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemorySaveFailedEvent)\n\n\n def\n on_memory_save_failed\n(\nsource\n, \nevent\n: MemorySaveFailedEvent):\n\n\n self\n.error_count \n+=\n 1\n\n\n agent_info \n=\n f\n\"Agent '\n{\nevent.agent_role\n}\n'\"\n if\n event.agent_role \nelse\n \"Unknown agent\"\n\n\n error_message \n=\n f\n\"Memory save failed: \n{\nevent.error\n}\n. \n{\nagent_info\n}\n\"\n\n\n logger.error(error_message)\n\n\n\n\n if\n self\n.notify_email \nand\n self\n.error_count \n%\n 5\n ==\n 0\n:\n\n\n self\n._send_notification(error_message)\n\n\n\n\n @crewai_event_bus.on\n(MemoryQueryFailedEvent)\n\n\n def\n on_memory_query_failed\n(\nsource\n, \nevent\n: MemoryQueryFailedEvent):\n\n\n self\n.error_count \n+=\n 1\n\n\n error_message \n=\n f\n\"Memory query failed: \n{\nevent.error\n}\n. Query: '\n{\nevent.query\n}\n'\"\n\n\n logger.error(error_message)\n\n\n\n\n if\n self\n.notify_email \nand\n self\n.error_count \n%\n 5\n ==\n 0\n:\n\n\n self\n._send_notification(error_message)\n\n\n\n\n def\n _send_notification\n(\nself\n, \nmessage\n):\n\n\n # Implement your notification system (email, Slack, etc.)\n\n\n print\n(\nf\n\"[NOTIFICATION] Would send to \n{\nself\n.notify_email\n}\n: \n{\nmessage\n}\n\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nerror_tracker \n=\n MemoryErrorTracker(\nnotify_email\n=\n\"admin@example.com\"\n)\n\n\n\n\n​\nIntegrating with Analytics Platforms\n\n\nMemory events can be forwarded to analytics and monitoring platforms to track performance metrics, detect anomalies, and visualize memory usage patterns:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemoryQueryCompletedEvent,\n\n\n MemorySaveCompletedEvent\n\n\n)\n\n\n\n\nclass\n MemoryAnalyticsForwarder\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n, \nanalytics_client\n):\n\n\n super\n().\n__init__\n()\n\n\n self\n.client \n=\n analytics_client\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemoryQueryCompletedEvent)\n\n\n def\n on_memory_query_completed\n(\nsource\n, \nevent\n: MemoryQueryCompletedEvent):\n\n\n # Forward query metrics to analytics platform\n\n\n self\n.client.track_metric({\n\n\n \"event_type\"\n: \n\"memory_query\"\n,\n\n\n \"query\"\n: event.query,\n\n\n \"duration_ms\"\n: event.query_time_ms,\n\n\n \"result_count\"\n: \nlen\n(event.results) \nif\n hasattr\n(event.results, \n\"__len__\"\n) \nelse\n 0\n,\n\n\n \"timestamp\"\n: event.timestamp\n\n\n })\n\n\n\n\n @crewai_event_bus.on\n(MemorySaveCompletedEvent)\n\n\n def\n on_memory_save_completed\n(\nsource\n, \nevent\n: MemorySaveCompletedEvent):\n\n\n # Forward save metrics to analytics platform\n\n\n self\n.client.track_metric({\n\n\n \"event_type\"\n: \n\"memory_save\"\n,\n\n\n \"agent_role\"\n: event.agent_role,\n\n\n \"duration_ms\"\n: event.save_time_ms,\n\n\n \"timestamp\"\n: event.timestamp\n\n\n })\n\n\n\n\n​\nBest Practices for Memory Event Listeners\n\n\n\n\nKeep handlers lightweight\n: Avoid complex processing in event handlers to prevent performance impacts\n\n\nUse appropriate logging levels\n: Use INFO for normal operations, DEBUG for details, ERROR for issues\n\n\nBatch metrics when possible\n: Accumulate metrics before sending to external systems\n\n\nHandle exceptions gracefully\n: Ensure your event handlers don’t crash due to unexpected data\n\n\nConsider memory consumption\n: Be mindful of storing large amounts of event data\n\n\n\n\n​\nConclusion\n\n\nIntegrating CrewAI’s memory system into your projects is straightforward. By leveraging the provided memory components and configurations,\nyou can quickly empower your agents with the ability to remember, reason, and learn from their interactions, unlocking new levels of intelligence and capability.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTraining\nReasoning\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nMemory System Components\n1. Basic Memory System (Recommended)\nQuick Start\nHow It Works\nStorage Location Transparency\nWhere CrewAI Stores Files\nDefault Storage Locations by Platform\nFinding Your Storage Location\nControlling Storage Locations\nOption 1: Environment Variable (Recommended)\nOption 2: Custom Storage Paths\nOption 3: Project-Specific Storage\nEmbedding Provider Defaults\nUnderstanding Default Behavior\nCustomizing Embedding Providers\nDebugging Storage Issues\nCheck Storage Permissions\nInspect ChromaDB Collections\nReset Storage (Debugging)\nProduction Best Practices\nCommon Storage Issues\nCustom Embedder Configuration\nWhy Choose Different Embedding Providers?\nOpenAI Embeddings (Default)\nAzure OpenAI Embeddings\nGoogle AI Embeddings\nVertex AI Embeddings\nOllama Embeddings (Local)\nCohere Embeddings\nVoyageAI Embeddings\nAWS Bedrock Embeddings\nHugging Face Embeddings\nIBM Watson Embeddings\nChoosing the Right Embedding Provider\nEnvironment Variable Configuration\nTesting Different Embedding Providers\nTroubleshooting Embedding Issues\n2. User Memory with Mem0 (Legacy)\nPrerequisites\nMem0 Cloud Configuration\nAdvanced Mem0 Configuration\nLocal Mem0 Configuration\n3. External Memory (New Approach)\nBasic External Memory with Mem0\nCustom Storage Implementation\nMemory System Comparison\nSupported Embedding Providers\nOpenAI (Default)\nOllama\nGoogle AI\nAzure OpenAI\nVertex AI\nSecurity Best Practices\nEnvironment Variables\nStorage Security\nTroubleshooting\nCommon Issues\nPerformance Tips\nBenefits of Using CrewAI’s Memory System\nMemory Events\nAvailable Memory Events\nPractical Applications\n1. Memory Performance Monitoring\n2. Memory Content Logging\n3. Error Tracking and Notifications\nIntegrating with Analytics Platforms\nBest Practices for Memory Event Listeners\nConclusion\nCore Concepts\nMemory\nCopy page\nLeveraging memory systems in the CrewAI framework to enhance agent capabilities.\n​\nOverview\n\n\nThe CrewAI framework provides a sophisticated memory system designed to significantly enhance AI agent capabilities. CrewAI offers \nthree distinct memory approaches\n that serve different use cases:\n\n\n\n\nBasic Memory System\n - Built-in short-term, long-term, and entity memory\n\n\nUser Memory\n - User-specific memory with Mem0 integration (legacy approach)\n\n\nExternal Memory\n - Standalone external memory providers (new approach)\n\n\n\n\n​\nMemory System Components\n\n\nComponent\nDescription\nShort-Term Memory\nTemporarily stores recent interactions and outcomes using \nRAG\n, enabling agents to recall and utilize information relevant to their current context during the current executions.\nLong-Term Memory\nPreserves valuable insights and learnings from past executions, allowing agents to build and refine their knowledge over time.\nEntity Memory\nCaptures and organizes information about entities (people, places, concepts) encountered during tasks, facilitating deeper understanding and relationship mapping. Uses \nRAG\n for storing entity information.\nContextual Memory\nMaintains the context of interactions by combining \nShortTermMemory\n, \nLongTermMemory\n, and \nEntityMemory\n, aiding in the coherence and relevance of agent responses over a sequence of tasks or a conversation.\n\n\n​\n1. Basic Memory System (Recommended)\n\n\nThe simplest and most commonly used approach. Enable memory for your crew with a single parameter:\n\n\n​\nQuick Start\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Agent, Task, Process\n\n\n\n\n# Enable basic memory system\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n process\n=\nProcess.sequential,\n\n\n memory\n=\nTrue\n, \n# Enables short-term, long-term, and entity memory\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nHow It Works\n\n\n\n\nShort-Term Memory\n: Uses ChromaDB with RAG for current context\n\n\nLong-Term Memory\n: Uses SQLite3 to store task results across sessions\n\n\nEntity Memory\n: Uses RAG to track entities (people, places, concepts)\n\n\nStorage Location\n: Platform-specific location via \nappdirs\n package\n\n\nCustom Storage Directory\n: Set \nCREWAI_STORAGE_DIR\n environment variable\n\n\n\n\n​\nStorage Location Transparency\n\n\nUnderstanding Storage Locations\n: CrewAI uses platform-specific directories to store memory and knowledge files following OS conventions. Understanding these locations helps with production deployments, backups, and debugging.\n\n\n​\nWhere CrewAI Stores Files\n\n\nBy default, CrewAI uses the \nappdirs\n library to determine storage locations following platform conventions. Here’s exactly where your files are stored:\n\n\n​\nDefault Storage Locations by Platform\n\n\nmacOS:\n\n\nCopy\nAsk AI\n~/Library/Application Support/CrewAI/{project_name}/\n\n\n├── knowledge/ # Knowledge base ChromaDB files\n\n\n├── short_term_memory/ # Short-term memory ChromaDB files\n\n\n├── long_term_memory/ # Long-term memory ChromaDB files\n\n\n├── entities/ # Entity memory ChromaDB files\n\n\n└── long_term_memory_storage.db # SQLite database\n\n\n\n\nLinux:\n\n\nCopy\nAsk AI\n~/.local/share/CrewAI/{project_name}/\n\n\n├── knowledge/\n\n\n├── short_term_memory/\n\n\n├── long_term_memory/\n\n\n├── entities/\n\n\n└── long_term_memory_storage.db\n\n\n\n\nWindows:\n\n\nCopy\nAsk AI\nC:\\Users\\{username}\\AppData\\Local\\CrewAI\\{project_name}\\\n\n\n├── knowledge\\\n\n\n├── short_term_memory\\\n\n\n├── long_term_memory\\\n\n\n├── entities\\\n\n\n└── long_term_memory_storage.db\n\n\n\n\n​\nFinding Your Storage Location\n\n\nTo see exactly where CrewAI is storing files on your system:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\nimport\n os\n\n\n\n\n# Get the base storage path\n\n\nstorage_path \n=\n db_storage_path()\n\n\nprint\n(\nf\n\"CrewAI storage location: \n{\nstorage_path\n}\n\"\n)\n\n\n\n\n# List all CrewAI storage directories\n\n\nif\n os.path.exists(storage_path):\n\n\n print\n(\n\"\n\\n\nStored files and directories:\"\n)\n\n\n for\n item \nin\n os.listdir(storage_path):\n\n\n item_path \n=\n os.path.join(storage_path, item)\n\n\n if\n os.path.isdir(item_path):\n\n\n print\n(\nf\n\"📁 \n{\nitem\n}\n/\"\n)\n\n\n # Show ChromaDB collections\n\n\n if\n os.path.exists(item_path):\n\n\n for\n subitem \nin\n os.listdir(item_path):\n\n\n print\n(\nf\n\" └── \n{\nsubitem\n}\n\"\n)\n\n\n else\n:\n\n\n print\n(\nf\n\"📄 \n{\nitem\n}\n\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No CrewAI storage directory found yet.\"\n)\n\n\n\n\n​\nControlling Storage Locations\n\n\n​\nOption 1: Environment Variable (Recommended)\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Set custom storage location\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n \"./my_project_storage\"\n\n\n\n\n# All memory and knowledge will now be stored in ./my_project_storage/\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n\n\n)\n\n\n\n\n​\nOption 2: Custom Storage Paths\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\nfrom\n crewai.memory \nimport\n LongTermMemory\n\n\nfrom\n crewai.memory.storage.ltm_sqlite_storage \nimport\n LTMSQLiteStorage\n\n\n\n\n# Configure custom storage location\n\n\ncustom_storage_path \n=\n \"./storage\"\n\n\nos.makedirs(custom_storage_path, \nexist_ok\n=\nTrue\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n long_term_memory\n=\nLongTermMemory(\n\n\n storage\n=\nLTMSQLiteStorage(\n\n\n db_path\n=\nf\n\"\n{\ncustom_storage_path\n}\n/memory.db\"\n\n\n )\n\n\n )\n\n\n)\n\n\n\n\n​\nOption 3: Project-Specific Storage\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n pathlib \nimport\n Path\n\n\n\n\n# Store in project directory\n\n\nproject_root \n=\n Path(\n__file__\n).parent\n\n\nstorage_dir \n=\n project_root \n/\n \"crewai_storage\"\n\n\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n str\n(storage_dir)\n\n\n\n\n# Now all storage will be in your project directory\n\n\n\n\n​\nEmbedding Provider Defaults\n\n\nDefault Embedding Provider\n: CrewAI defaults to OpenAI embeddings for consistency and reliability. You can easily customize this to match your LLM provider or use local embeddings.\n\n\n​\nUnderstanding Default Behavior\n\n\nCopy\nAsk AI\n# When using Claude as your LLM...\n\n\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Analyst\"\n,\n\n\n goal\n=\n\"Analyze data\"\n,\n\n\n backstory\n=\n\"Expert analyst\"\n,\n\n\n llm\n=\nLLM(\nprovider\n=\n\"anthropic\"\n, \nmodel\n=\n\"claude-3-sonnet\"\n) \n# Using Claude\n\n\n)\n\n\n\n\n# CrewAI will use OpenAI embeddings by default for consistency\n\n\n# You can easily customize this to match your preferred provider\n\n\n\n\n​\nCustomizing Embedding Providers\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Option 1: Match your LLM provider\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"anthropic\"\n, \n# Match your LLM provider\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-anthropic-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Option 2: Use local embeddings (no external API calls)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n }\n\n\n)\n\n\n\n\n​\nDebugging Storage Issues\n\n\n​\nCheck Storage Permissions\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\nstorage_path \n=\n db_storage_path()\n\n\nprint\n(\nf\n\"Storage path: \n{\nstorage_path\n}\n\"\n)\n\n\nprint\n(\nf\n\"Path exists: \n{\nos.path.exists(storage_path)\n}\n\"\n)\n\n\nprint\n(\nf\n\"Is writable: \n{\nos.access(storage_path, os.\nW_OK\n) \nif\n os.path.exists(storage_path) \nelse\n 'Path does not exist'\n}\n\"\n)\n\n\n\n\n# Create with proper permissions\n\n\nif\n not\n os.path.exists(storage_path):\n\n\n os.makedirs(storage_path, \nmode\n=\n0o\n755\n, \nexist_ok\n=\nTrue\n)\n\n\n print\n(\nf\n\"Created storage directory: \n{\nstorage_path\n}\n\"\n)\n\n\n\n\n​\nInspect ChromaDB Collections\n\n\nCopy\nAsk AI\nimport\n chromadb\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\n# Connect to CrewAI's ChromaDB\n\n\nstorage_path \n=\n db_storage_path()\n\n\nchroma_path \n=\n os.path.join(storage_path, \n\"knowledge\"\n)\n\n\n\n\nif\n os.path.exists(chroma_path):\n\n\n client \n=\n chromadb.PersistentClient(\npath\n=\nchroma_path)\n\n\n collections \n=\n client.list_collections()\n\n\n\n\n print\n(\n\"ChromaDB Collections:\"\n)\n\n\n for\n collection \nin\n collections:\n\n\n print\n(\nf\n\" - \n{\ncollection.name\n}\n: \n{\ncollection.count()\n}\n documents\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No ChromaDB storage found\"\n)\n\n\n\n\n​\nReset Storage (Debugging)\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Reset all memory storage\n\n\ncrew \n=\n Crew(\nagents\n=\n[\n...\n], \ntasks\n=\n[\n...\n], \nmemory\n=\nTrue\n)\n\n\n\n\n# Reset specific memory types\n\n\ncrew.reset_memories(\ncommand_type\n=\n'short'\n) \n# Short-term memory\n\n\ncrew.reset_memories(\ncommand_type\n=\n'long'\n) \n# Long-term memory\n\n\ncrew.reset_memories(\ncommand_type\n=\n'entity'\n) \n# Entity memory\n\n\ncrew.reset_memories(\ncommand_type\n=\n'knowledge'\n) \n# Knowledge storage\n\n\n\n\n​\nProduction Best Practices\n\n\n\n\nSet \nCREWAI_STORAGE_DIR\n to a known location in production for better control\n\n\nChoose explicit embedding providers\n to match your LLM setup\n\n\nMonitor storage directory size\n for large-scale deployments\n\n\nInclude storage directories\n in your backup strategy\n\n\nSet appropriate file permissions\n (0o755 for directories, 0o644 for files)\n\n\nUse project-relative paths\n for containerized deployments\n\n\n\n\n​\nCommon Storage Issues\n\n\n“ChromaDB permission denied” errors:\n\n\nCopy\nAsk AI\n# Fix permissions\n\n\nchmod\n -R\n 755\n ~/.local/share/CrewAI/\n\n\n\n\n“Database is locked” errors:\n\n\nCopy\nAsk AI\n# Ensure only one CrewAI instance accesses storage\n\n\nimport\n fcntl\n\n\nimport\n os\n\n\n\n\nstorage_path \n=\n db_storage_path()\n\n\nlock_file \n=\n os.path.join(storage_path, \n\".crewai.lock\"\n)\n\n\n\n\nwith\n open\n(lock_file, \n'w'\n) \nas\n f:\n\n\n fcntl.flock(f.fileno(), fcntl.\nLOCK_EX\n |\n fcntl.\nLOCK_NB\n)\n\n\n # Your CrewAI code here\n\n\n\n\nStorage not persisting between runs:\n\n\nCopy\nAsk AI\n# Verify storage location is consistent\n\n\nimport\n os\n\n\nprint\n(\n\"CREWAI_STORAGE_DIR:\"\n, os.getenv(\n\"CREWAI_STORAGE_DIR\"\n))\n\n\nprint\n(\n\"Current working directory:\"\n, os.getcwd())\n\n\nprint\n(\n\"Computed storage path:\"\n, db_storage_path())\n\n\n\n\n​\nCustom Embedder Configuration\n\n\nCrewAI supports multiple embedding providers to give you flexibility in choosing the best option for your use case. Here’s a comprehensive guide to configuring different embedding providers for your memory system.\n\n\n​\nWhy Choose Different Embedding Providers?\n\n\n\n\nCost Optimization\n: Local embeddings (Ollama) are free after initial setup\n\n\nPrivacy\n: Keep your data local with Ollama or use your preferred cloud provider\n\n\nPerformance\n: Some models work better for specific domains or languages\n\n\nConsistency\n: Match your embedding provider with your LLM provider\n\n\nCompliance\n: Meet specific regulatory or organizational requirements\n\n\n\n\n​\nOpenAI Embeddings (Default)\n\n\nOpenAI provides reliable, high-quality embeddings that work well for most use cases.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Basic OpenAI configuration (uses environment OPENAI_API_KEY)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n # or \"text-embedding-3-large\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Advanced OpenAI configuration\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-openai-api-key\"\n, \n# Optional: override env var\n\n\n \"model\"\n: \n\"text-embedding-3-large\"\n,\n\n\n \"dimensions\"\n: \n1536\n, \n# Optional: reduce dimensions for smaller storage\n\n\n \"organization_id\"\n: \n\"your-org-id\"\n # Optional: for organization accounts\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAzure OpenAI Embeddings\n\n\nFor enterprise users with Azure OpenAI deployments.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n, \n# Use openai provider for Azure\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-azure-api-key\"\n,\n\n\n \"api_base\"\n: \n\"https://your-resource.openai.azure.com/\"\n,\n\n\n \"api_type\"\n: \n\"azure\"\n,\n\n\n \"api_version\"\n: \n\"2023-05-15\"\n,\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n,\n\n\n \"deployment_id\"\n: \n\"your-deployment-name\"\n # Azure deployment name\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nGoogle AI Embeddings\n\n\nUse Google’s text embedding models for integration with Google Cloud services.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-google-api-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-004\"\n # or \"text-embedding-preview-0409\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nVertex AI Embeddings\n\n\nFor Google Cloud users with Vertex AI access.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"vertexai\"\n,\n\n\n \"config\"\n: {\n\n\n \"project_id\"\n: \n\"your-gcp-project-id\"\n,\n\n\n \"region\"\n: \n\"us-central1\"\n, \n# or your preferred region\n\n\n \"api_key\"\n: \n\"your-service-account-key\"\n,\n\n\n \"model_name\"\n: \n\"textembedding-gecko\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nOllama Embeddings (Local)\n\n\nRun embeddings locally for privacy and cost savings.\n\n\nCopy\nAsk AI\n# First, install and run Ollama locally, then pull an embedding model:\n\n\n# ollama pull mxbai-embed-large\n\n\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"mxbai-embed-large\"\n, \n# or \"nomic-embed-text\"\n\n\n \"url\"\n: \n\"http://localhost:11434/api/embeddings\"\n # Default Ollama URL\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# For custom Ollama installations\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"mxbai-embed-large\"\n,\n\n\n \"url\"\n: \n\"http://your-ollama-server:11434/api/embeddings\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nCohere Embeddings\n\n\nUse Cohere’s embedding models for multilingual support.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"cohere\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-cohere-api-key\"\n,\n\n\n \"model\"\n: \n\"embed-english-v3.0\"\n # or \"embed-multilingual-v3.0\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nVoyageAI Embeddings\n\n\nHigh-performance embeddings optimized for retrieval tasks.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"voyageai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-voyage-api-key\"\n,\n\n\n \"model\"\n: \n\"voyage-large-2\"\n, \n# or \"voyage-code-2\" for code\n\n\n \"input_type\"\n: \n\"document\"\n # or \"query\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAWS Bedrock Embeddings\n\n\nFor AWS users with Bedrock access.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"bedrock\"\n,\n\n\n \"config\"\n: {\n\n\n \"aws_access_key_id\"\n: \n\"your-access-key\"\n,\n\n\n \"aws_secret_access_key\"\n: \n\"your-secret-key\"\n,\n\n\n \"region_name\"\n: \n\"us-east-1\"\n,\n\n\n \"model\"\n: \n\"amazon.titan-embed-text-v1\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nHugging Face Embeddings\n\n\nUse open-source models from Hugging Face.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"huggingface\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-hf-token\"\n, \n# Optional for public models\n\n\n \"model\"\n: \n\"sentence-transformers/all-MiniLM-L6-v2\"\n,\n\n\n \"api_url\"\n: \n\"https://api-inference.huggingface.co\"\n # or your custom endpoint\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nIBM Watson Embeddings\n\n\nFor IBM Cloud users.\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"watson\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-watson-api-key\"\n,\n\n\n \"url\"\n: \n\"your-watson-instance-url\"\n,\n\n\n \"model\"\n: \n\"ibm/slate-125m-english-rtrvr\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nChoosing the Right Embedding Provider\n\n\nProvider\nBest For\nPros\nCons\nOpenAI\nGeneral use, reliability\nHigh quality, well-tested\nCost, requires API key\nOllama\nPrivacy, cost savings\nFree, local, private\nRequires local setup\nGoogle AI\nGoogle ecosystem\nGood performance\nRequires Google account\nAzure OpenAI\nEnterprise, compliance\nEnterprise features\nComplex setup\nCohere\nMultilingual content\nGreat language support\nSpecialized use case\nVoyageAI\nRetrieval tasks\nOptimized for search\nNewer provider\n\n\n​\nEnvironment Variable Configuration\n\n\nFor security, store API keys in environment variables:\n\n\nCopy\nAsk AI\nimport\n os\n\n\n\n\n# Set environment variables\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"your-openai-key\"\n\n\nos.environ[\n\"GOOGLE_API_KEY\"\n] \n=\n \"your-google-key\"\n\n\nos.environ[\n\"COHERE_API_KEY\"\n] \n=\n \"your-cohere-key\"\n\n\n\n\n# Use without exposing keys in code\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n\n\n # API key automatically loaded from environment\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nTesting Different Embedding Providers\n\n\nCompare embedding providers for your specific use case:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\n# Test different providers with the same data\n\n\nproviders_to_test \n=\n [\n\n\n {\n\n\n \"name\"\n: \n\"OpenAI\"\n,\n\n\n \"config\"\n: {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n },\n\n\n {\n\n\n \"name\"\n: \n\"Ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n }\n\n\n }\n\n\n]\n\n\n\n\nfor\n provider \nin\n providers_to_test:\n\n\n print\n(\nf\n\"\n\\n\nTesting \n{\nprovider[\n'name'\n]\n}\n embeddings...\"\n)\n\n\n\n\n # Create crew with specific embedder\n\n\n crew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\nprovider[\n'config'\n]\n\n\n )\n\n\n\n\n # Run your test and measure performance\n\n\n result \n=\n crew.kickoff()\n\n\n print\n(\nf\n\"\n{\nprovider[\n'name'\n]\n}\n completed successfully\"\n)\n\n\n\n\n​\nTroubleshooting Embedding Issues\n\n\nModel not found errors:\n\n\nCopy\nAsk AI\n# Verify model availability\n\n\nfrom\n crewai.utilities.embedding_configurator \nimport\n EmbeddingConfigurator\n\n\n\n\nconfigurator \n=\n EmbeddingConfigurator()\n\n\ntry\n:\n\n\n embedder \n=\n configurator.configure_embedder({\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n })\n\n\n print\n(\n\"Embedder configured successfully\"\n)\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Configuration error: \n{\ne\n}\n\"\n)\n\n\n\n\nAPI key issues:\n\n\nCopy\nAsk AI\nimport\n os\n\n\n\n\n# Check if API keys are set\n\n\nrequired_keys \n=\n [\n\"OPENAI_API_KEY\"\n, \n\"GOOGLE_API_KEY\"\n, \n\"COHERE_API_KEY\"\n]\n\n\nfor\n key \nin\n required_keys:\n\n\n if\n os.getenv(key):\n\n\n print\n(\nf\n\"✅ \n{\nkey\n}\n is set\"\n)\n\n\n else\n:\n\n\n print\n(\nf\n\"❌ \n{\nkey\n}\n is not set\"\n)\n\n\n\n\nPerformance comparison:\n\n\nCopy\nAsk AI\nimport\n time\n\n\n\n\ndef\n test_embedding_performance\n(\nembedder_config\n, \ntest_text\n=\n\"This is a test document\"\n):\n\n\n start_time \n=\n time.time()\n\n\n\n\n crew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\nembedder_config\n\n\n )\n\n\n\n\n # Simulate memory operation\n\n\n crew.kickoff()\n\n\n\n\n end_time \n=\n time.time()\n\n\n return\n end_time \n-\n start_time\n\n\n\n\n# Compare performance\n\n\nopenai_time \n=\n test_embedding_performance({\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n})\n\n\n\n\nollama_time \n=\n test_embedding_performance({\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n})\n\n\n\n\nprint\n(\nf\n\"OpenAI: \n{\nopenai_time\n:.2f}\ns\"\n)\n\n\nprint\n(\nf\n\"Ollama: \n{\nollama_time\n:.2f}\ns\"\n)\n\n\n\n\n​\n2. User Memory with Mem0 (Legacy)\n\n\nLegacy Approach\n: While fully functional, this approach is considered legacy. For new projects requiring user-specific memory, consider using External Memory instead.\n\n\nUser Memory integrates with \nMem0\n to provide user-specific memory that persists across sessions and integrates with the crew’s contextual memory system.\n\n\n​\nPrerequisites\n\n\nCopy\nAsk AI\npip\n install\n mem0ai\n\n\n\n\n​\nMem0 Cloud Configuration\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew, Process\n\n\n\n\n# Set your Mem0 API key\n\n\nos.environ[\n\"MEM0_API_KEY\"\n] \n=\n \"m0-your-api-key\"\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n, \n# Required for contextual memory integration\n\n\n memory_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\"user_id\"\n: \n\"john\"\n},\n\n\n \"user_memory\"\n: {} \n# Required - triggers user memory initialization\n\n\n },\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nAdvanced Mem0 Configuration\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n memory_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\n\n \"user_id\"\n: \n\"john\"\n,\n\n\n \"org_id\"\n: \n\"my_org_id\"\n, \n# Optional\n\n\n \"project_id\"\n: \n\"my_project_id\"\n, \n# Optional\n\n\n \"api_key\"\n: \n\"custom-api-key\"\n # Optional - overrides env var\n\n\n },\n\n\n \"user_memory\"\n: {}\n\n\n }\n\n\n)\n\n\n\n\n​\nLocal Mem0 Configuration\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n memory\n=\nTrue\n,\n\n\n memory_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\n\n \"user_id\"\n: \n\"john\"\n,\n\n\n \"local_mem0_config\"\n: {\n\n\n \"vector_store\"\n: {\n\n\n \"provider\"\n: \n\"qdrant\"\n,\n\n\n \"config\"\n: {\n\"host\"\n: \n\"localhost\"\n, \n\"port\"\n: \n6333\n}\n\n\n },\n\n\n \"llm\"\n: {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"api_key\"\n: \n\"your-api-key\"\n, \n\"model\"\n: \n\"gpt-4\"\n}\n\n\n },\n\n\n \"embedder\"\n: {\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"api_key\"\n: \n\"your-api-key\"\n, \n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n }\n\n\n },\n\n\n \"user_memory\"\n: {}\n\n\n }\n\n\n)\n\n\n\n\n​\n3. External Memory (New Approach)\n\n\nExternal Memory provides a standalone memory system that operates independently from the crew’s built-in memory. This is ideal for specialized memory providers or cross-application memory sharing.\n\n\n​\nBasic External Memory with Mem0\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.memory.external.external_memory \nimport\n ExternalMemory\n\n\n\n\nos.environ[\n\"MEM0_API_KEY\"\n] \n=\n \"your-api-key\"\n\n\n\n\n# Create external memory instance\n\n\nexternal_memory \n=\n ExternalMemory(\n\n\n embedder_config\n=\n{\n\n\n \"provider\"\n: \n\"mem0\"\n,\n\n\n \"config\"\n: {\n\"user_id\"\n: \n\"U-123\"\n}\n\n\n }\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n external_memory\n=\nexternal_memory, \n# Separate from basic memory\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nCustom Storage Implementation\n\n\nCopy\nAsk AI\nfrom\n crewai.memory.external.external_memory \nimport\n ExternalMemory\n\n\nfrom\n crewai.memory.storage.interface \nimport\n Storage\n\n\n\n\nclass\n CustomStorage\n(\nStorage\n):\n\n\n def\n __init__\n(\nself\n):\n\n\n self\n.memories \n=\n []\n\n\n\n\n def\n save\n(\nself\n, \nvalue\n, \nmetadata\n=\nNone\n, \nagent\n=\nNone\n):\n\n\n self\n.memories.append({\n\n\n \"value\"\n: value,\n\n\n \"metadata\"\n: metadata,\n\n\n \"agent\"\n: agent\n\n\n })\n\n\n\n\n def\n search\n(\nself\n, \nquery\n, \nlimit\n=\n10\n, \nscore_threshold\n=\n0.5\n):\n\n\n # Implement your search logic here\n\n\n return\n [m \nfor\n m \nin\n self\n.memories \nif\n query.lower() \nin\n str\n(m[\n\"value\"\n]).lower()]\n\n\n\n\n def\n reset\n(\nself\n):\n\n\n self\n.memories \n=\n []\n\n\n\n\n# Use custom storage\n\n\nexternal_memory \n=\n ExternalMemory(\nstorage\n=\nCustomStorage())\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n external_memory\n=\nexternal_memory\n\n\n)\n\n\n\n\n​\nMemory System Comparison\n\n\nFeature\nBasic Memory\nUser Memory (Legacy)\nExternal Memory\nSetup Complexity\nSimple\nMedium\nMedium\nIntegration\nBuilt-in contextual\nContextual + User-specific\nStandalone\nStorage\nLocal files\nMem0 Cloud/Local\nCustom/Mem0\nCross-session\n✅\n✅\n✅\nUser-specific\n❌\n✅\n✅\nCustom providers\nLimited\nMem0 only\nAny provider\nRecommended for\nMost use cases\nLegacy projects\nSpecialized needs\n\n\n​\nSupported Embedding Providers\n\n\n​\nOpenAI (Default)\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n)\n\n\n\n\n​\nOllama\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n }\n\n\n)\n\n\n\n\n​\nGoogle AI\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-api-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-004\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAzure OpenAI\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-api-key\"\n,\n\n\n \"api_base\"\n: \n\"https://your-resource.openai.azure.com/\"\n,\n\n\n \"api_version\"\n: \n\"2023-05-15\"\n,\n\n\n \"model_name\"\n: \n\"text-embedding-3-small\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nVertex AI\n\n\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"vertexai\"\n,\n\n\n \"config\"\n: {\n\n\n \"project_id\"\n: \n\"your-project-id\"\n,\n\n\n \"region\"\n: \n\"your-region\"\n,\n\n\n \"api_key\"\n: \n\"your-api-key\"\n,\n\n\n \"model_name\"\n: \n\"textembedding-gecko\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nSecurity Best Practices\n\n\n​\nEnvironment Variables\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Store sensitive data in environment variables\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: os.getenv(\n\"OPENAI_API_KEY\"\n),\n\n\n \"model\"\n: \n\"text-embedding-3-small\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nStorage Security\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\nfrom\n crewai.memory \nimport\n LongTermMemory\n\n\nfrom\n crewai.memory.storage.ltm_sqlite_storage \nimport\n LTMSQLiteStorage\n\n\n\n\n# Use secure storage paths\n\n\nstorage_path \n=\n os.getenv(\n\"CREWAI_STORAGE_DIR\"\n, \n\"./storage\"\n)\n\n\nos.makedirs(storage_path, \nmode\n=\n0o\n700\n, \nexist_ok\n=\nTrue\n) \n# Restricted permissions\n\n\n\n\ncrew \n=\n Crew(\n\n\n memory\n=\nTrue\n,\n\n\n long_term_memory\n=\nLongTermMemory(\n\n\n storage\n=\nLTMSQLiteStorage(\n\n\n db_path\n=\nf\n\"\n{\nstorage_path\n}\n/memory.db\"\n\n\n )\n\n\n )\n\n\n)\n\n\n\n\n​\nTroubleshooting\n\n\n​\nCommon Issues\n\n\nMemory not persisting between sessions?\n\n\n\n\nCheck \nCREWAI_STORAGE_DIR\n environment variable\n\n\nEnsure write permissions to storage directory\n\n\nVerify memory is enabled with \nmemory=True\n\n\n\n\nMem0 authentication errors?\n\n\n\n\nVerify \nMEM0_API_KEY\n environment variable is set\n\n\nCheck API key permissions on Mem0 dashboard\n\n\nEnsure \nmem0ai\n package is installed\n\n\n\n\nHigh memory usage with large datasets?\n\n\n\n\nConsider using External Memory with custom storage\n\n\nImplement pagination in custom storage search methods\n\n\nUse smaller embedding models for reduced memory footprint\n\n\n\n\n​\nPerformance Tips\n\n\n\n\nUse \nmemory=True\n for most use cases (simplest and fastest)\n\n\nOnly use User Memory if you need user-specific persistence\n\n\nConsider External Memory for high-scale or specialized requirements\n\n\nChoose smaller embedding models for faster processing\n\n\nSet appropriate search limits to control memory retrieval size\n\n\n\n\n​\nBenefits of Using CrewAI’s Memory System\n\n\n\n\n🦾 \nAdaptive Learning:\n Crews become more efficient over time, adapting to new information and refining their approach to tasks.\n\n\n🫡 \nEnhanced Personalization:\n Memory enables agents to remember user preferences and historical interactions, leading to personalized experiences.\n\n\n🧠 \nImproved Problem Solving:\n Access to a rich memory store aids agents in making more informed decisions, drawing on past learnings and contextual insights.\n\n\n\n\n​\nMemory Events\n\n\nCrewAI’s event system provides powerful insights into memory operations. By leveraging memory events, you can monitor, debug, and optimize your memory system’s performance and behavior.\n\n\n​\nAvailable Memory Events\n\n\nCrewAI emits the following memory-related events:\n\n\nEvent\nDescription\nKey Properties\nMemoryQueryStartedEvent\nEmitted when a memory query begins\nquery\n, \nlimit\n, \nscore_threshold\nMemoryQueryCompletedEvent\nEmitted when a memory query completes successfully\nquery\n, \nresults\n, \nlimit\n, \nscore_threshold\n, \nquery_time_ms\nMemoryQueryFailedEvent\nEmitted when a memory query fails\nquery\n, \nlimit\n, \nscore_threshold\n, \nerror\nMemorySaveStartedEvent\nEmitted when a memory save operation begins\nvalue\n, \nmetadata\n, \nagent_role\nMemorySaveCompletedEvent\nEmitted when a memory save operation completes successfully\nvalue\n, \nmetadata\n, \nagent_role\n, \nsave_time_ms\nMemorySaveFailedEvent\nEmitted when a memory save operation fails\nvalue\n, \nmetadata\n, \nagent_role\n, \nerror\nMemoryRetrievalStartedEvent\nEmitted when memory retrieval for a task prompt starts\ntask_id\nMemoryRetrievalCompletedEvent\nEmitted when memory retrieval completes successfully\ntask_id\n, \nmemory_content\n, \nretrieval_time_ms\n\n\n​\nPractical Applications\n\n\n​\n1. Memory Performance Monitoring\n\n\nTrack memory operation timing to optimize your application:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemoryQueryCompletedEvent,\n\n\n MemorySaveCompletedEvent\n\n\n)\n\n\nimport\n time\n\n\n\n\nclass\n MemoryPerformanceMonitor\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n):\n\n\n super\n().\n__init__\n()\n\n\n self\n.query_times \n=\n []\n\n\n self\n.save_times \n=\n []\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemoryQueryCompletedEvent)\n\n\n def\n on_memory_query_completed\n(\nsource\n, \nevent\n: MemoryQueryCompletedEvent):\n\n\n self\n.query_times.append(event.query_time_ms)\n\n\n print\n(\nf\n\"Memory query completed in \n{\nevent.query_time_ms\n:.2f}\nms. Query: '\n{\nevent.query\n}\n'\"\n)\n\n\n print\n(\nf\n\"Average query time: \n{\nsum\n(\nself\n.query_times)\n/\nlen\n(\nself\n.query_times)\n:.2f}\nms\"\n)\n\n\n\n\n @crewai_event_bus.on\n(MemorySaveCompletedEvent)\n\n\n def\n on_memory_save_completed\n(\nsource\n, \nevent\n: MemorySaveCompletedEvent):\n\n\n self\n.save_times.append(event.save_time_ms)\n\n\n print\n(\nf\n\"Memory save completed in \n{\nevent.save_time_ms\n:.2f}\nms\"\n)\n\n\n print\n(\nf\n\"Average save time: \n{\nsum\n(\nself\n.save_times)\n/\nlen\n(\nself\n.save_times)\n:.2f}\nms\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nmemory_monitor \n=\n MemoryPerformanceMonitor()\n\n\n\n\n​\n2. Memory Content Logging\n\n\nLog memory operations for debugging and insights:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemorySaveStartedEvent,\n\n\n MemoryQueryStartedEvent,\n\n\n MemoryRetrievalCompletedEvent\n\n\n)\n\n\nimport\n logging\n\n\n\n\n# Configure logging\n\n\nlogger \n=\n logging.getLogger(\n'memory_events'\n)\n\n\n\n\nclass\n MemoryLogger\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemorySaveStartedEvent)\n\n\n def\n on_memory_save_started\n(\nsource\n, \nevent\n: MemorySaveStartedEvent):\n\n\n if\n event.agent_role:\n\n\n logger.info(\nf\n\"Agent '\n{\nevent.agent_role\n}\n' saving memory: \n{\nevent.value[:\n50\n]\n}\n...\"\n)\n\n\n else\n:\n\n\n logger.info(\nf\n\"Saving memory: \n{\nevent.value[:\n50\n]\n}\n...\"\n)\n\n\n\n\n @crewai_event_bus.on\n(MemoryQueryStartedEvent)\n\n\n def\n on_memory_query_started\n(\nsource\n, \nevent\n: MemoryQueryStartedEvent):\n\n\n logger.info(\nf\n\"Memory query started: '\n{\nevent.query\n}\n' (limit: \n{\nevent.limit\n}\n)\"\n)\n\n\n\n\n @crewai_event_bus.on\n(MemoryRetrievalCompletedEvent)\n\n\n def\n on_memory_retrieval_completed\n(\nsource\n, \nevent\n: MemoryRetrievalCompletedEvent):\n\n\n if\n event.task_id:\n\n\n logger.info(\nf\n\"Memory retrieved for task \n{\nevent.task_id\n}\n in \n{\nevent.retrieval_time_ms\n:.2f}\nms\"\n)\n\n\n else\n:\n\n\n logger.info(\nf\n\"Memory retrieved in \n{\nevent.retrieval_time_ms\n:.2f}\nms\"\n)\n\n\n logger.debug(\nf\n\"Memory content: \n{\nevent.memory_content\n}\n\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nmemory_logger \n=\n MemoryLogger()\n\n\n\n\n​\n3. Error Tracking and Notifications\n\n\nCapture and respond to memory errors:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemorySaveFailedEvent,\n\n\n MemoryQueryFailedEvent\n\n\n)\n\n\nimport\n logging\n\n\nfrom\n typing \nimport\n Optional\n\n\n\n\n# Configure logging\n\n\nlogger \n=\n logging.getLogger(\n'memory_errors'\n)\n\n\n\n\nclass\n MemoryErrorTracker\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n, \nnotify_email\n: Optional[\nstr\n] \n=\n None\n):\n\n\n super\n().\n__init__\n()\n\n\n self\n.notify_email \n=\n notify_email\n\n\n self\n.error_count \n=\n 0\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemorySaveFailedEvent)\n\n\n def\n on_memory_save_failed\n(\nsource\n, \nevent\n: MemorySaveFailedEvent):\n\n\n self\n.error_count \n+=\n 1\n\n\n agent_info \n=\n f\n\"Agent '\n{\nevent.agent_role\n}\n'\"\n if\n event.agent_role \nelse\n \"Unknown agent\"\n\n\n error_message \n=\n f\n\"Memory save failed: \n{\nevent.error\n}\n. \n{\nagent_info\n}\n\"\n\n\n logger.error(error_message)\n\n\n\n\n if\n self\n.notify_email \nand\n self\n.error_count \n%\n 5\n ==\n 0\n:\n\n\n self\n._send_notification(error_message)\n\n\n\n\n @crewai_event_bus.on\n(MemoryQueryFailedEvent)\n\n\n def\n on_memory_query_failed\n(\nsource\n, \nevent\n: MemoryQueryFailedEvent):\n\n\n self\n.error_count \n+=\n 1\n\n\n error_message \n=\n f\n\"Memory query failed: \n{\nevent.error\n}\n. Query: '\n{\nevent.query\n}\n'\"\n\n\n logger.error(error_message)\n\n\n\n\n if\n self\n.notify_email \nand\n self\n.error_count \n%\n 5\n ==\n 0\n:\n\n\n self\n._send_notification(error_message)\n\n\n\n\n def\n _send_notification\n(\nself\n, \nmessage\n):\n\n\n # Implement your notification system (email, Slack, etc.)\n\n\n print\n(\nf\n\"[NOTIFICATION] Would send to \n{\nself\n.notify_email\n}\n: \n{\nmessage\n}\n\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nerror_tracker \n=\n MemoryErrorTracker(\nnotify_email\n=\n\"admin@example.com\"\n)\n\n\n\n\n​\nIntegrating with Analytics Platforms\n\n\nMemory events can be forwarded to analytics and monitoring platforms to track performance metrics, detect anomalies, and visualize memory usage patterns:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\nfrom\n crewai.utilities.events \nimport\n (\n\n\n MemoryQueryCompletedEvent,\n\n\n MemorySaveCompletedEvent\n\n\n)\n\n\n\n\nclass\n MemoryAnalyticsForwarder\n(\nBaseEventListener\n):\n\n\n def\n __init__\n(\nself\n, \nanalytics_client\n):\n\n\n super\n().\n__init__\n()\n\n\n self\n.client \n=\n analytics_client\n\n\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(MemoryQueryCompletedEvent)\n\n\n def\n on_memory_query_completed\n(\nsource\n, \nevent\n: MemoryQueryCompletedEvent):\n\n\n # Forward query metrics to analytics platform\n\n\n self\n.client.track_metric({\n\n\n \"event_type\"\n: \n\"memory_query\"\n,\n\n\n \"query\"\n: event.query,\n\n\n \"duration_ms\"\n: event.query_time_ms,\n\n\n \"result_count\"\n: \nlen\n(event.results) \nif\n hasattr\n(event.results, \n\"__len__\"\n) \nelse\n 0\n,\n\n\n \"timestamp\"\n: event.timestamp\n\n\n })\n\n\n\n\n @crewai_event_bus.on\n(MemorySaveCompletedEvent)\n\n\n def\n on_memory_save_completed\n(\nsource\n, \nevent\n: MemorySaveCompletedEvent):\n\n\n # Forward save metrics to analytics platform\n\n\n self\n.client.track_metric({\n\n\n \"event_type\"\n: \n\"memory_save\"\n,\n\n\n \"agent_role\"\n: event.agent_role,\n\n\n \"duration_ms\"\n: event.save_time_ms,\n\n\n \"timestamp\"\n: event.timestamp\n\n\n })\n\n\n\n\n​\nBest Practices for Memory Event Listeners\n\n\n\n\nKeep handlers lightweight\n: Avoid complex processing in event handlers to prevent performance impacts\n\n\nUse appropriate logging levels\n: Use INFO for normal operations, DEBUG for details, ERROR for issues\n\n\nBatch metrics when possible\n: Accumulate metrics before sending to external systems\n\n\nHandle exceptions gracefully\n: Ensure your event handlers don’t crash due to unexpected data\n\n\nConsider memory consumption\n: Be mindful of storing large amounts of event data\n\n\n\n\n​\nConclusion\n\n\nIntegrating CrewAI’s memory system into your projects is straightforward. By leveraging the provided memory components and configurations,\nyou can quickly empower your agents with the ability to remember, reason, and learn from their interactions, unlocking new levels of intelligence and capability.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTraining\nReasoning\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nMemory System Components\n1. Basic Memory System (Recommended)\nQuick Start\nHow It Works\nStorage Location Transparency\nWhere CrewAI Stores Files\nDefault Storage Locations by Platform\nFinding Your Storage Location\nControlling Storage Locations\nOption 1: Environment Variable (Recommended)\nOption 2: Custom Storage Paths\nOption 3: Project-Specific Storage\nEmbedding Provider Defaults\nUnderstanding Default Behavior\nCustomizing Embedding Providers\nDebugging Storage Issues\nCheck Storage Permissions\nInspect ChromaDB Collections\nReset Storage (Debugging)\nProduction Best Practices\nCommon Storage Issues\nCustom Embedder Configuration\nWhy Choose Different Embedding Providers?\nOpenAI Embeddings (Default)\nAzure OpenAI Embeddings\nGoogle AI Embeddings\nVertex AI Embeddings\nOllama Embeddings (Local)\nCohere Embeddings\nVoyageAI Embeddings\nAWS Bedrock Embeddings\nHugging Face Embeddings\nIBM Watson Embeddings\nChoosing the Right Embedding Provider\nEnvironment Variable Configuration\nTesting Different Embedding Providers\nTroubleshooting Embedding Issues\n2. User Memory with Mem0 (Legacy)\nPrerequisites\nMem0 Cloud Configuration\nAdvanced Mem0 Configuration\nLocal Mem0 Configuration\n3. External Memory (New Approach)\nBasic External Memory with Mem0\nCustom Storage Implementation\nMemory System Comparison\nSupported Embedding Providers\nOpenAI (Default)\nOllama\nGoogle AI\nAzure OpenAI\nVertex AI\nSecurity Best Practices\nEnvironment Variables\nStorage Security\nTroubleshooting\nCommon Issues\nPerformance Tips\nBenefits of Using CrewAI’s Memory System\nMemory Events\nAvailable Memory Events\nPractical Applications\n1. Memory Performance Monitoring\n2. Memory Content Logging\n3. Error Tracking and Notifications\nIntegrating with Analytics Platforms\nBest Practices for Memory Event Listeners\nConclusion" }, { "source": "https://docs.crewai.com/en/concepts/collaboration", "title": "Collaboration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nCollaboration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nCollaboration\nCopy page\nHow to enable agents to work together, delegate tasks, and communicate effectively within CrewAI teams.\n​\nOverview\n\n\nCollaboration in CrewAI enables agents to work together as a team by delegating tasks and asking questions to leverage each other’s expertise. When \nallow_delegation=True\n, agents automatically gain access to powerful collaboration tools.\n\n\n​\nQuick Start: Enable Collaboration\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\n\n\n# Enable collaboration for agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Research Specialist\"\n,\n\n\n goal\n=\n\"Conduct thorough research on any topic\"\n,\n\n\n backstory\n=\n\"Expert researcher with access to various sources\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# 🔑 Key setting for collaboration\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Content Writer\"\n, \n\n\n goal\n=\n\"Create engaging content based on research\"\n,\n\n\n backstory\n=\n\"Skilled writer who transforms research into compelling content\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# 🔑 Enables asking questions to other agents\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Agents can now collaborate automatically\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[\n...\n],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nHow Agent Collaboration Works\n\n\nWhen \nallow_delegation=True\n, CrewAI automatically provides agents with two powerful tools:\n\n\n​\n1. \nDelegate Work Tool\n\n\nAllows agents to assign tasks to teammates with specific expertise.\n\n\nCopy\nAsk AI\n# Agent automatically gets this tool:\n\n\n# Delegate work to coworker(task: str, context: str, coworker: str)\n\n\n\n\n​\n2. \nAsk Question Tool\n\n\nEnables agents to ask specific questions to gather information from colleagues.\n\n\nCopy\nAsk AI\n# Agent automatically gets this tool:\n\n\n# Ask question to coworker(question: str, context: str, coworker: str)\n\n\n\n\n​\nCollaboration in Action\n\n\nHere’s a complete example showing agents collaborating on a content creation task:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\n\n\n# Create collaborative agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Research Specialist\"\n,\n\n\n goal\n=\n\"Find accurate, up-to-date information on any topic\"\n,\n\n\n backstory\n=\n\"\"\"You're a meticulous researcher with expertise in finding \n\n\n reliable sources and fact-checking information across various domains.\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Content Writer\"\n,\n\n\n goal\n=\n\"Create engaging, well-structured content\"\n,\n\n\n backstory\n=\n\"\"\"You're a skilled content writer who excels at transforming \n\n\n research into compelling, readable content for different audiences.\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\neditor \n=\n Agent(\n\n\n role\n=\n\"Content Editor\"\n,\n\n\n goal\n=\n\"Ensure content quality and consistency\"\n,\n\n\n backstory\n=\n\"\"\"You're an experienced editor with an eye for detail, \n\n\n ensuring content meets high standards for clarity and accuracy.\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that encourages collaboration\n\n\narticle_task \n=\n Task(\n\n\n description\n=\n\"\"\"Write a comprehensive 1000-word article about 'The Future of AI in Healthcare'.\n\n\n \n\n\n The article should include:\n\n\n - Current AI applications in healthcare\n\n\n - Emerging trends and technologies \n\n\n - Potential challenges and ethical considerations\n\n\n - Expert predictions for the next 5 years\n\n\n \n\n\n Collaborate with your teammates to ensure accuracy and quality.\"\"\"\n,\n\n\n expected_output\n=\n\"A well-researched, engaging 1000-word article with proper structure and citations\"\n,\n\n\n agent\n=\nwriter \n# Writer leads, but can delegate research to researcher\n\n\n)\n\n\n\n\n# Create collaborative crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer, editor],\n\n\n tasks\n=\n[article_task],\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nCollaboration Patterns\n\n\n​\nPattern 1: Research → Write → Edit\n\n\nCopy\nAsk AI\nresearch_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in quantum computing\"\n,\n\n\n expected_output\n=\n\"Comprehensive research summary with key findings and sources\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n\"Write an article based on the research findings\"\n,\n\n\n expected_output\n=\n\"Engaging 800-word article about quantum computing\"\n,\n\n\n agent\n=\nwriter,\n\n\n context\n=\n[research_task] \n# Gets research output as context\n\n\n)\n\n\n\n\nediting_task \n=\n Task(\n\n\n description\n=\n\"Edit and polish the article for publication\"\n,\n\n\n expected_output\n=\n\"Publication-ready article with improved clarity and flow\"\n,\n\n\n agent\n=\neditor,\n\n\n context\n=\n[writing_task] \n# Gets article draft as context\n\n\n)\n\n\n\n\n​\nPattern 2: Collaborative Single Task\n\n\nCopy\nAsk AI\ncollaborative_task \n=\n Task(\n\n\n description\n=\n\"\"\"Create a marketing strategy for a new AI product.\n\n\n \n\n\n Writer: Focus on messaging and content strategy\n\n\n Researcher: Provide market analysis and competitor insights\n\n\n \n\n\n Work together to create a comprehensive strategy.\"\"\"\n,\n\n\n expected_output\n=\n\"Complete marketing strategy with research backing\"\n,\n\n\n agent\n=\nwriter \n# Lead agent, but can delegate to researcher\n\n\n)\n\n\n\n\n​\nHierarchical Collaboration\n\n\nFor complex projects, use a hierarchical process with a manager agent:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\n\n\n# Manager agent coordinates the team\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Coordinate team efforts and ensure project success\"\n,\n\n\n backstory\n=\n\"Experienced project manager skilled at delegation and quality control\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Specialist agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Provide accurate research and analysis\"\n,\n\n\n backstory\n=\n\"Expert researcher with deep analytical skills\"\n,\n\n\n allow_delegation\n=\nFalse\n, \n# Specialists focus on their expertise\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Writer\"\n, \n\n\n goal\n=\n\"Create compelling content\"\n,\n\n\n backstory\n=\n\"Skilled writer who creates engaging content\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Manager-led task\n\n\nproject_task \n=\n Task(\n\n\n description\n=\n\"Create a comprehensive market analysis report with recommendations\"\n,\n\n\n expected_output\n=\n\"Executive summary, detailed analysis, and strategic recommendations\"\n,\n\n\n agent\n=\nmanager \n# Manager will delegate to specialists\n\n\n)\n\n\n\n\n# Hierarchical crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[manager, researcher, writer],\n\n\n tasks\n=\n[project_task],\n\n\n process\n=\nProcess.hierarchical, \n# Manager coordinates everything\n\n\n manager_llm\n=\n\"gpt-4o\"\n, \n# Specify LLM for manager\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nBest Practices for Collaboration\n\n\n​\n1. \nClear Role Definition\n\n\nCopy\nAsk AI\n# ✅ Good: Specific, complementary roles\n\n\nresearcher \n=\n Agent(\nrole\n=\n\"Market Research Analyst\"\n, \n...\n)\n\n\nwriter \n=\n Agent(\nrole\n=\n\"Technical Content Writer\"\n, \n...\n)\n\n\n\n\n# ❌ Avoid: Overlapping or vague roles \n\n\nagent1 \n=\n Agent(\nrole\n=\n\"General Assistant\"\n, \n...\n)\n\n\nagent2 \n=\n Agent(\nrole\n=\n\"Helper\"\n, \n...\n)\n\n\n\n\n​\n2. \nStrategic Delegation Enabling\n\n\nCopy\nAsk AI\n# ✅ Enable delegation for coordinators and generalists\n\n\nlead_agent \n=\n Agent(\n\n\n role\n=\n\"Content Lead\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# Can delegate to specialists\n\n\n ...\n\n\n)\n\n\n\n\n# ✅ Disable for focused specialists (optional)\n\n\nspecialist_agent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n, \n\n\n allow_delegation\n=\nFalse\n, \n# Focuses on core expertise\n\n\n ...\n\n\n)\n\n\n\n\n​\n3. \nContext Sharing\n\n\nCopy\nAsk AI\n# ✅ Use context parameter for task dependencies\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n\"Write article based on research\"\n,\n\n\n agent\n=\nwriter,\n\n\n context\n=\n[research_task], \n# Shares research results\n\n\n ...\n\n\n)\n\n\n\n\n​\n4. \nClear Task Descriptions\n\n\nCopy\nAsk AI\n# ✅ Specific, actionable descriptions\n\n\nTask(\n\n\n description\n=\n\"\"\"Research competitors in the AI chatbot space.\n\n\n Focus on: pricing models, key features, target markets.\n\n\n Provide data in a structured format.\"\"\"\n,\n\n\n ...\n\n\n)\n\n\n\n\n# ❌ Vague descriptions that don't guide collaboration\n\n\nTask(\ndescription\n=\n\"Do some research about chatbots\"\n, \n...\n)\n\n\n\n\n​\nTroubleshooting Collaboration\n\n\n​\nIssue: Agents Not Collaborating\n\n\nSymptoms:\n Agents work in isolation, no delegation occurs\n\n\nCopy\nAsk AI\n# ✅ Solution: Ensure delegation is enabled\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"...\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# This is required!\n\n\n ...\n\n\n)\n\n\n\n\n​\nIssue: Too Much Back-and-Forth\n\n\nSymptoms:\n Agents ask excessive questions, slow progress\n\n\nCopy\nAsk AI\n# ✅ Solution: Provide better context and specific roles\n\n\nTask(\n\n\n description\n=\n\"\"\"Write a technical blog post about machine learning.\n\n\n \n\n\n Context: Target audience is software developers with basic ML knowledge.\n\n\n Length: 1200 words\n\n\n Include: code examples, practical applications, best practices\n\n\n \n\n\n If you need specific technical details, delegate research to the researcher.\"\"\"\n,\n\n\n ...\n\n\n)\n\n\n\n\n​\nIssue: Delegation Loops\n\n\nSymptoms:\n Agents delegate back and forth indefinitely\n\n\nCopy\nAsk AI\n# ✅ Solution: Clear hierarchy and responsibilities\n\n\nmanager \n=\n Agent(\nrole\n=\n\"Manager\"\n, \nallow_delegation\n=\nTrue\n)\n\n\nspecialist1 \n=\n Agent(\nrole\n=\n\"Specialist A\"\n, \nallow_delegation\n=\nFalse\n) \n# No re-delegation\n\n\nspecialist2 \n=\n Agent(\nrole\n=\n\"Specialist B\"\n, \nallow_delegation\n=\nFalse\n)\n\n\n\n\n​\nAdvanced Collaboration Features\n\n\n​\nCustom Collaboration Rules\n\n\nCopy\nAsk AI\n# Set specific collaboration guidelines in agent backstory\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Senior Developer\"\n,\n\n\n backstory\n=\n\"\"\"You lead development projects and coordinate with team members.\n\n\n \n\n\n Collaboration guidelines:\n\n\n - Delegate research tasks to the Research Analyst\n\n\n - Ask the Designer for UI/UX guidance \n\n\n - Consult the QA Engineer for testing strategies\n\n\n - Only escalate blocking issues to the Project Manager\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n\n\n)\n\n\n\n\n​\nMonitoring Collaboration\n\n\nCopy\nAsk AI\ndef\n track_collaboration\n(\noutput\n):\n\n\n \"\"\"Track collaboration patterns\"\"\"\n\n\n if\n \"Delegate work to coworker\"\n in\n output.raw:\n\n\n print\n(\n\"🤝 Delegation occurred\"\n)\n\n\n if\n \"Ask question to coworker\"\n in\n output.raw:\n\n\n print\n(\n\"❓ Question asked\"\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n step_callback\n=\ntrack_collaboration, \n# Monitor collaboration\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nMemory and Learning\n\n\nEnable agents to remember past collaborations:\n\n\nCopy\nAsk AI\nagent \n=\n Agent(\n\n\n role\n=\n\"Content Lead\"\n,\n\n\n memory\n=\nTrue\n, \n# Remembers past interactions\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWith memory enabled, agents learn from previous collaborations and improve their delegation decisions over time.\n\n\n​\nNext Steps\n\n\n\n\nTry the examples\n: Start with the basic collaboration example\n\n\nExperiment with roles\n: Test different agent role combinations\n\n\nMonitor interactions\n: Use \nverbose=True\n to see collaboration in action\n\n\nOptimize task descriptions\n: Clear tasks lead to better collaboration\n\n\nScale up\n: Try hierarchical processes for complex projects\n\n\n\n\nCollaboration transforms individual AI agents into powerful teams that can tackle complex, multi-faceted challenges together.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nProcesses\nTraining\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nQuick Start: Enable Collaboration\nHow Agent Collaboration Works\n1. Delegate Work Tool\n2. Ask Question Tool\nCollaboration in Action\nCollaboration Patterns\nPattern 1: Research → Write → Edit\nPattern 2: Collaborative Single Task\nHierarchical Collaboration\nBest Practices for Collaboration\n1. Clear Role Definition\n2. Strategic Delegation Enabling\n3. Context Sharing\n4. Clear Task Descriptions\nTroubleshooting Collaboration\nIssue: Agents Not Collaborating\nIssue: Too Much Back-and-Forth\nIssue: Delegation Loops\nAdvanced Collaboration Features\nCustom Collaboration Rules\nMonitoring Collaboration\nMemory and Learning\nNext Steps\nCore Concepts\nCollaboration\nCopy page\nHow to enable agents to work together, delegate tasks, and communicate effectively within CrewAI teams.\n​\nOverview\n\n\nCollaboration in CrewAI enables agents to work together as a team by delegating tasks and asking questions to leverage each other’s expertise. When \nallow_delegation=True\n, agents automatically gain access to powerful collaboration tools.\n\n\n​\nQuick Start: Enable Collaboration\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\n\n\n# Enable collaboration for agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Research Specialist\"\n,\n\n\n goal\n=\n\"Conduct thorough research on any topic\"\n,\n\n\n backstory\n=\n\"Expert researcher with access to various sources\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# 🔑 Key setting for collaboration\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Content Writer\"\n, \n\n\n goal\n=\n\"Create engaging content based on research\"\n,\n\n\n backstory\n=\n\"Skilled writer who transforms research into compelling content\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# 🔑 Enables asking questions to other agents\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Agents can now collaborate automatically\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[\n...\n],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nHow Agent Collaboration Works\n\n\nWhen \nallow_delegation=True\n, CrewAI automatically provides agents with two powerful tools:\n\n\n​\n1. \nDelegate Work Tool\n\n\nAllows agents to assign tasks to teammates with specific expertise.\n\n\nCopy\nAsk AI\n# Agent automatically gets this tool:\n\n\n# Delegate work to coworker(task: str, context: str, coworker: str)\n\n\n\n\n​\n2. \nAsk Question Tool\n\n\nEnables agents to ask specific questions to gather information from colleagues.\n\n\nCopy\nAsk AI\n# Agent automatically gets this tool:\n\n\n# Ask question to coworker(question: str, context: str, coworker: str)\n\n\n\n\n​\nCollaboration in Action\n\n\nHere’s a complete example showing agents collaborating on a content creation task:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\n\n\n# Create collaborative agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Research Specialist\"\n,\n\n\n goal\n=\n\"Find accurate, up-to-date information on any topic\"\n,\n\n\n backstory\n=\n\"\"\"You're a meticulous researcher with expertise in finding \n\n\n reliable sources and fact-checking information across various domains.\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Content Writer\"\n,\n\n\n goal\n=\n\"Create engaging, well-structured content\"\n,\n\n\n backstory\n=\n\"\"\"You're a skilled content writer who excels at transforming \n\n\n research into compelling, readable content for different audiences.\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\neditor \n=\n Agent(\n\n\n role\n=\n\"Content Editor\"\n,\n\n\n goal\n=\n\"Ensure content quality and consistency\"\n,\n\n\n backstory\n=\n\"\"\"You're an experienced editor with an eye for detail, \n\n\n ensuring content meets high standards for clarity and accuracy.\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that encourages collaboration\n\n\narticle_task \n=\n Task(\n\n\n description\n=\n\"\"\"Write a comprehensive 1000-word article about 'The Future of AI in Healthcare'.\n\n\n \n\n\n The article should include:\n\n\n - Current AI applications in healthcare\n\n\n - Emerging trends and technologies \n\n\n - Potential challenges and ethical considerations\n\n\n - Expert predictions for the next 5 years\n\n\n \n\n\n Collaborate with your teammates to ensure accuracy and quality.\"\"\"\n,\n\n\n expected_output\n=\n\"A well-researched, engaging 1000-word article with proper structure and citations\"\n,\n\n\n agent\n=\nwriter \n# Writer leads, but can delegate research to researcher\n\n\n)\n\n\n\n\n# Create collaborative crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer, editor],\n\n\n tasks\n=\n[article_task],\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nCollaboration Patterns\n\n\n​\nPattern 1: Research → Write → Edit\n\n\nCopy\nAsk AI\nresearch_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in quantum computing\"\n,\n\n\n expected_output\n=\n\"Comprehensive research summary with key findings and sources\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n\"Write an article based on the research findings\"\n,\n\n\n expected_output\n=\n\"Engaging 800-word article about quantum computing\"\n,\n\n\n agent\n=\nwriter,\n\n\n context\n=\n[research_task] \n# Gets research output as context\n\n\n)\n\n\n\n\nediting_task \n=\n Task(\n\n\n description\n=\n\"Edit and polish the article for publication\"\n,\n\n\n expected_output\n=\n\"Publication-ready article with improved clarity and flow\"\n,\n\n\n agent\n=\neditor,\n\n\n context\n=\n[writing_task] \n# Gets article draft as context\n\n\n)\n\n\n\n\n​\nPattern 2: Collaborative Single Task\n\n\nCopy\nAsk AI\ncollaborative_task \n=\n Task(\n\n\n description\n=\n\"\"\"Create a marketing strategy for a new AI product.\n\n\n \n\n\n Writer: Focus on messaging and content strategy\n\n\n Researcher: Provide market analysis and competitor insights\n\n\n \n\n\n Work together to create a comprehensive strategy.\"\"\"\n,\n\n\n expected_output\n=\n\"Complete marketing strategy with research backing\"\n,\n\n\n agent\n=\nwriter \n# Lead agent, but can delegate to researcher\n\n\n)\n\n\n\n\n​\nHierarchical Collaboration\n\n\nFor complex projects, use a hierarchical process with a manager agent:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\n\n\n# Manager agent coordinates the team\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Coordinate team efforts and ensure project success\"\n,\n\n\n backstory\n=\n\"Experienced project manager skilled at delegation and quality control\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Specialist agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Provide accurate research and analysis\"\n,\n\n\n backstory\n=\n\"Expert researcher with deep analytical skills\"\n,\n\n\n allow_delegation\n=\nFalse\n, \n# Specialists focus on their expertise\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Writer\"\n, \n\n\n goal\n=\n\"Create compelling content\"\n,\n\n\n backstory\n=\n\"Skilled writer who creates engaging content\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Manager-led task\n\n\nproject_task \n=\n Task(\n\n\n description\n=\n\"Create a comprehensive market analysis report with recommendations\"\n,\n\n\n expected_output\n=\n\"Executive summary, detailed analysis, and strategic recommendations\"\n,\n\n\n agent\n=\nmanager \n# Manager will delegate to specialists\n\n\n)\n\n\n\n\n# Hierarchical crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[manager, researcher, writer],\n\n\n tasks\n=\n[project_task],\n\n\n process\n=\nProcess.hierarchical, \n# Manager coordinates everything\n\n\n manager_llm\n=\n\"gpt-4o\"\n, \n# Specify LLM for manager\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nBest Practices for Collaboration\n\n\n​\n1. \nClear Role Definition\n\n\nCopy\nAsk AI\n# ✅ Good: Specific, complementary roles\n\n\nresearcher \n=\n Agent(\nrole\n=\n\"Market Research Analyst\"\n, \n...\n)\n\n\nwriter \n=\n Agent(\nrole\n=\n\"Technical Content Writer\"\n, \n...\n)\n\n\n\n\n# ❌ Avoid: Overlapping or vague roles \n\n\nagent1 \n=\n Agent(\nrole\n=\n\"General Assistant\"\n, \n...\n)\n\n\nagent2 \n=\n Agent(\nrole\n=\n\"Helper\"\n, \n...\n)\n\n\n\n\n​\n2. \nStrategic Delegation Enabling\n\n\nCopy\nAsk AI\n# ✅ Enable delegation for coordinators and generalists\n\n\nlead_agent \n=\n Agent(\n\n\n role\n=\n\"Content Lead\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# Can delegate to specialists\n\n\n ...\n\n\n)\n\n\n\n\n# ✅ Disable for focused specialists (optional)\n\n\nspecialist_agent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n, \n\n\n allow_delegation\n=\nFalse\n, \n# Focuses on core expertise\n\n\n ...\n\n\n)\n\n\n\n\n​\n3. \nContext Sharing\n\n\nCopy\nAsk AI\n# ✅ Use context parameter for task dependencies\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n\"Write article based on research\"\n,\n\n\n agent\n=\nwriter,\n\n\n context\n=\n[research_task], \n# Shares research results\n\n\n ...\n\n\n)\n\n\n\n\n​\n4. \nClear Task Descriptions\n\n\nCopy\nAsk AI\n# ✅ Specific, actionable descriptions\n\n\nTask(\n\n\n description\n=\n\"\"\"Research competitors in the AI chatbot space.\n\n\n Focus on: pricing models, key features, target markets.\n\n\n Provide data in a structured format.\"\"\"\n,\n\n\n ...\n\n\n)\n\n\n\n\n# ❌ Vague descriptions that don't guide collaboration\n\n\nTask(\ndescription\n=\n\"Do some research about chatbots\"\n, \n...\n)\n\n\n\n\n​\nTroubleshooting Collaboration\n\n\n​\nIssue: Agents Not Collaborating\n\n\nSymptoms:\n Agents work in isolation, no delegation occurs\n\n\nCopy\nAsk AI\n# ✅ Solution: Ensure delegation is enabled\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"...\"\n,\n\n\n allow_delegation\n=\nTrue\n, \n# This is required!\n\n\n ...\n\n\n)\n\n\n\n\n​\nIssue: Too Much Back-and-Forth\n\n\nSymptoms:\n Agents ask excessive questions, slow progress\n\n\nCopy\nAsk AI\n# ✅ Solution: Provide better context and specific roles\n\n\nTask(\n\n\n description\n=\n\"\"\"Write a technical blog post about machine learning.\n\n\n \n\n\n Context: Target audience is software developers with basic ML knowledge.\n\n\n Length: 1200 words\n\n\n Include: code examples, practical applications, best practices\n\n\n \n\n\n If you need specific technical details, delegate research to the researcher.\"\"\"\n,\n\n\n ...\n\n\n)\n\n\n\n\n​\nIssue: Delegation Loops\n\n\nSymptoms:\n Agents delegate back and forth indefinitely\n\n\nCopy\nAsk AI\n# ✅ Solution: Clear hierarchy and responsibilities\n\n\nmanager \n=\n Agent(\nrole\n=\n\"Manager\"\n, \nallow_delegation\n=\nTrue\n)\n\n\nspecialist1 \n=\n Agent(\nrole\n=\n\"Specialist A\"\n, \nallow_delegation\n=\nFalse\n) \n# No re-delegation\n\n\nspecialist2 \n=\n Agent(\nrole\n=\n\"Specialist B\"\n, \nallow_delegation\n=\nFalse\n)\n\n\n\n\n​\nAdvanced Collaboration Features\n\n\n​\nCustom Collaboration Rules\n\n\nCopy\nAsk AI\n# Set specific collaboration guidelines in agent backstory\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Senior Developer\"\n,\n\n\n backstory\n=\n\"\"\"You lead development projects and coordinate with team members.\n\n\n \n\n\n Collaboration guidelines:\n\n\n - Delegate research tasks to the Research Analyst\n\n\n - Ask the Designer for UI/UX guidance \n\n\n - Consult the QA Engineer for testing strategies\n\n\n - Only escalate blocking issues to the Project Manager\"\"\"\n,\n\n\n allow_delegation\n=\nTrue\n\n\n)\n\n\n\n\n​\nMonitoring Collaboration\n\n\nCopy\nAsk AI\ndef\n track_collaboration\n(\noutput\n):\n\n\n \"\"\"Track collaboration patterns\"\"\"\n\n\n if\n \"Delegate work to coworker\"\n in\n output.raw:\n\n\n print\n(\n\"🤝 Delegation occurred\"\n)\n\n\n if\n \"Ask question to coworker\"\n in\n output.raw:\n\n\n print\n(\n\"❓ Question asked\"\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n step_callback\n=\ntrack_collaboration, \n# Monitor collaboration\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nMemory and Learning\n\n\nEnable agents to remember past collaborations:\n\n\nCopy\nAsk AI\nagent \n=\n Agent(\n\n\n role\n=\n\"Content Lead\"\n,\n\n\n memory\n=\nTrue\n, \n# Remembers past interactions\n\n\n allow_delegation\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWith memory enabled, agents learn from previous collaborations and improve their delegation decisions over time.\n\n\n​\nNext Steps\n\n\n\n\nTry the examples\n: Start with the basic collaboration example\n\n\nExperiment with roles\n: Test different agent role combinations\n\n\nMonitor interactions\n: Use \nverbose=True\n to see collaboration in action\n\n\nOptimize task descriptions\n: Clear tasks lead to better collaboration\n\n\nScale up\n: Try hierarchical processes for complex projects\n\n\n\n\nCollaboration transforms individual AI agents into powerful teams that can tackle complex, multi-faceted challenges together.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nProcesses\nTraining\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nQuick Start: Enable Collaboration\nHow Agent Collaboration Works\n1. Delegate Work Tool\n2. Ask Question Tool\nCollaboration in Action\nCollaboration Patterns\nPattern 1: Research → Write → Edit\nPattern 2: Collaborative Single Task\nHierarchical Collaboration\nBest Practices for Collaboration\n1. Clear Role Definition\n2. Strategic Delegation Enabling\n3. Context Sharing\n4. Clear Task Descriptions\nTroubleshooting Collaboration\nIssue: Agents Not Collaborating\nIssue: Too Much Back-and-Forth\nIssue: Delegation Loops\nAdvanced Collaboration Features\nCustom Collaboration Rules\nMonitoring Collaboration\nMemory and Learning\nNext Steps" }, { "source": "https://docs.crewai.com/en/mcp/multiple-servers", "title": "Connecting to Multiple MCP Servers - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nMCP Integration\nConnecting to Multiple MCP Servers\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nMCP Integration\nConnecting to Multiple MCP Servers\nCopy page\nLearn how to use MCPServerAdapter in CrewAI to connect to multiple MCP servers simultaneously and aggregate their tools.\n​\nOverview\n\n\nMCPServerAdapter\n in \ncrewai-tools\n allows you to connect to multiple MCP servers concurrently. This is useful when your agents need to access tools distributed across different services or environments. The adapter aggregates tools from all specified servers, making them available to your CrewAI agents.\n\n\n​\nConfiguration\n\n\nTo connect to multiple servers, you provide a list of server parameter dictionaries to \nMCPServerAdapter\n. Each dictionary in the list should define the parameters for one MCP server.\n\n\nSupported transport types for each server in the list include \nstdio\n, \nsse\n, and \nstreamable-http\n.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters \n# Needed for Stdio example\n\n\n\n\n# Define parameters for multiple MCP servers\n\n\nserver_params_list \n=\n [\n\n\n # Streamable HTTP Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n, \n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n },\n\n\n # SSE Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n,\n\n\n \"transport\"\n: \n\"sse\"\n\n\n },\n\n\n # StdIO Server\n\n\n StdioServerParameters(\n\n\n command\n=\n\"python3\"\n,\n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n )\n\n\n]\n\n\n\n\ntry\n:\n\n\n with\n MCPServerAdapter(server_params_list) \nas\n aggregated_tools:\n\n\n print\n(\nf\n\"Available aggregated tools: \n{\n[tool.name \nfor\n tool \nin\n aggregated_tools]\n}\n\"\n)\n\n\n\n\n multi_server_agent \n=\n Agent(\n\n\n role\n=\n\"Versatile Assistant\"\n,\n\n\n goal\n=\n\"Utilize tools from local Stdio, remote SSE, and remote HTTP MCP servers.\"\n,\n\n\n backstory\n=\n\"An AI agent capable of leveraging a diverse set of tools from multiple sources.\"\n,\n\n\n tools\n=\naggregated_tools, \n# All tools are available here\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n ...\n # Your other agent, tasks, and crew code here\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Error connecting to or using multiple MCP servers (Managed): \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure all MCP servers are running and accessible with correct configurations.\"\n)\n\n\n\n\n\n\n​\nConnection Management\n\n\nWhen using the context manager (\nwith\n statement), \nMCPServerAdapter\n handles the lifecycle (start and stop) of all connections to the configured MCP servers. This simplifies resource management and ensures that all connections are properly closed when the context is exited.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nStreamable HTTP Transport\nMCP Security Considerations\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nConfiguration\nConnection Management\nMCP Integration\nConnecting to Multiple MCP Servers\nCopy page\nLearn how to use MCPServerAdapter in CrewAI to connect to multiple MCP servers simultaneously and aggregate their tools.\n​\nOverview\n\n\nMCPServerAdapter\n in \ncrewai-tools\n allows you to connect to multiple MCP servers concurrently. This is useful when your agents need to access tools distributed across different services or environments. The adapter aggregates tools from all specified servers, making them available to your CrewAI agents.\n\n\n​\nConfiguration\n\n\nTo connect to multiple servers, you provide a list of server parameter dictionaries to \nMCPServerAdapter\n. Each dictionary in the list should define the parameters for one MCP server.\n\n\nSupported transport types for each server in the list include \nstdio\n, \nsse\n, and \nstreamable-http\n.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters \n# Needed for Stdio example\n\n\n\n\n# Define parameters for multiple MCP servers\n\n\nserver_params_list \n=\n [\n\n\n # Streamable HTTP Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n, \n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n },\n\n\n # SSE Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n,\n\n\n \"transport\"\n: \n\"sse\"\n\n\n },\n\n\n # StdIO Server\n\n\n StdioServerParameters(\n\n\n command\n=\n\"python3\"\n,\n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n )\n\n\n]\n\n\n\n\ntry\n:\n\n\n with\n MCPServerAdapter(server_params_list) \nas\n aggregated_tools:\n\n\n print\n(\nf\n\"Available aggregated tools: \n{\n[tool.name \nfor\n tool \nin\n aggregated_tools]\n}\n\"\n)\n\n\n\n\n multi_server_agent \n=\n Agent(\n\n\n role\n=\n\"Versatile Assistant\"\n,\n\n\n goal\n=\n\"Utilize tools from local Stdio, remote SSE, and remote HTTP MCP servers.\"\n,\n\n\n backstory\n=\n\"An AI agent capable of leveraging a diverse set of tools from multiple sources.\"\n,\n\n\n tools\n=\naggregated_tools, \n# All tools are available here\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n ...\n # Your other agent, tasks, and crew code here\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Error connecting to or using multiple MCP servers (Managed): \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure all MCP servers are running and accessible with correct configurations.\"\n)\n\n\n\n\n\n\n​\nConnection Management\n\n\nWhen using the context manager (\nwith\n statement), \nMCPServerAdapter\n handles the lifecycle (start and stop) of all connections to the configured MCP servers. This simplifies resource management and ensures that all connections are properly closed when the context is exited.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nStreamable HTTP Transport\nMCP Security Considerations\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nConfiguration\nConnection Management" }, { "source": "https://docs.crewai.com/#key-features", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/concepts/testing", "title": "Testing - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nTesting\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nTesting\nCopy page\nLearn how to test your CrewAI Crew and evaluate their performance.\n​\nOverview\n\n\nTesting is a crucial part of the development process, and it is essential to ensure that your crew is performing as expected. With crewAI, you can easily test your crew and evaluate its performance using the built-in testing capabilities.\n\n\n​\nUsing the Testing Feature\n\n\nWe added the CLI command \ncrewai test\n to make it easy to test your crew. This command will run your crew for a specified number of iterations and provide detailed performance metrics. The parameters are \nn_iterations\n and \nmodel\n, which are optional and default to 2 and \ngpt-4o-mini\n respectively. For now, the only provider available is OpenAI.\n\n\nCopy\nAsk AI\ncrewai\n test\n\n\n\n\nIf you want to run more iterations or use a different model, you can specify the parameters like this:\n\n\nCopy\nAsk AI\ncrewai\n test\n --n_iterations\n 5\n --model\n gpt-4o\n\n\n\n\nor using the short forms:\n\n\nCopy\nAsk AI\ncrewai\n test\n -n\n 5\n -m\n gpt-4o\n\n\n\n\nWhen you run the \ncrewai test\n command, the crew will be executed for the specified number of iterations, and the performance metrics will be displayed at the end of the run.\n\n\nA table of scores at the end will show the performance of the crew in terms of the following metrics:\n\n\n\n\nTasks/Crew/Agents\nRun 1\nRun 2\nAvg. Total\nAgents\nAdditional Info\nTask 1\n9.0\n9.5\n9.2\nProfessional Insights\nResearcher\nTask 2\n9.0\n10.0\n9.5\nCompany Profile Investigator\nTask 3\n9.0\n9.0\n9.0\nAutomation Insights\nSpecialist\nTask 4\n9.0\n9.0\n9.0\nFinal Report Compiler\nAutomation Insights Specialist\nCrew\n9.00\n9.38\n9.2\nExecution Time (s)\n126\n145\n135\n\n\nThe example above shows the test results for two runs of the crew with two tasks, with the average total score for each task and the crew as a whole.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nPlanning\nCLI\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nUsing the Testing Feature\nCore Concepts\nTesting\nCopy page\nLearn how to test your CrewAI Crew and evaluate their performance.\n​\nOverview\n\n\nTesting is a crucial part of the development process, and it is essential to ensure that your crew is performing as expected. With crewAI, you can easily test your crew and evaluate its performance using the built-in testing capabilities.\n\n\n​\nUsing the Testing Feature\n\n\nWe added the CLI command \ncrewai test\n to make it easy to test your crew. This command will run your crew for a specified number of iterations and provide detailed performance metrics. The parameters are \nn_iterations\n and \nmodel\n, which are optional and default to 2 and \ngpt-4o-mini\n respectively. For now, the only provider available is OpenAI.\n\n\nCopy\nAsk AI\ncrewai\n test\n\n\n\n\nIf you want to run more iterations or use a different model, you can specify the parameters like this:\n\n\nCopy\nAsk AI\ncrewai\n test\n --n_iterations\n 5\n --model\n gpt-4o\n\n\n\n\nor using the short forms:\n\n\nCopy\nAsk AI\ncrewai\n test\n -n\n 5\n -m\n gpt-4o\n\n\n\n\nWhen you run the \ncrewai test\n command, the crew will be executed for the specified number of iterations, and the performance metrics will be displayed at the end of the run.\n\n\nA table of scores at the end will show the performance of the crew in terms of the following metrics:\n\n\n\n\nTasks/Crew/Agents\nRun 1\nRun 2\nAvg. Total\nAgents\nAdditional Info\nTask 1\n9.0\n9.5\n9.2\nProfessional Insights\nResearcher\nTask 2\n9.0\n10.0\n9.5\nCompany Profile Investigator\nTask 3\n9.0\n9.0\n9.0\nAutomation Insights\nSpecialist\nTask 4\n9.0\n9.0\n9.0\nFinal Report Compiler\nAutomation Insights Specialist\nCrew\n9.00\n9.38\n9.2\nExecution Time (s)\n126\n145\n135\n\n\nThe example above shows the test results for two runs of the crew with two tasks, with the average total score for each task and the crew as a whole.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nPlanning\nCLI\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nUsing the Testing Feature" }, { "source": "https://docs.crewai.com/en/observability/opik", "title": "Opik Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nOpik Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nOpik Integration\nCopy page\nLearn how to use Comet Opik to debug, evaluate, and monitor your CrewAI applications with comprehensive tracing, automated evaluations, and production-ready dashboards.\n​\nOpik Overview\n\n\nWith \nComet Opik\n, debug, evaluate, and monitor your LLM applications, RAG systems, and agentic workflows with comprehensive tracing, automated evaluations, and production-ready dashboards.\n\n\nOpik Agent Dashboard\n\n\nOpik provides comprehensive support for every stage of your CrewAI application development:\n\n\n\n\nLog Traces and Spans\n: Automatically track LLM calls and application logic to debug and analyze development and production systems. Manually or programmatically annotate, view, and compare responses across projects.\n\n\nEvaluate Your LLM Application’s Performance\n: Evaluate against a custom test set and run built-in evaluation metrics or define your own metrics in the SDK or UI.\n\n\nTest Within Your CI/CD Pipeline\n: Establish reliable performance baselines with Opik’s LLM unit tests, built on PyTest. Run online evaluations for continuous monitoring in production.\n\n\nMonitor & Analyze Production Data\n: Understand your models’ performance on unseen data in production and generate datasets for new dev iterations.\n\n\n\n\n​\nSetup\n\n\nComet provides a hosted version of the Opik platform, or you can run the platform locally.\n\n\nTo use the hosted version, simply \ncreate a free Comet account\n and grab you API Key.\n\n\nTo run the Opik platform locally, see our \ninstallation guide\n for more information.\n\n\nFor this guide we will use CrewAI’s quickstart example.\n\n\n1\nInstall required packages\nCopy\nAsk AI\npip\n install\n crewai\n crewai-tools\n opik\n --upgrade\n\n\n2\nConfigure Opik\nCopy\nAsk AI\nimport\n opik\n\n\nopik.configure(\nuse_local\n=\nFalse\n)\n\n\n3\nPrepare environment\nFirst, we set up our API keys for our LLM-provider as environment variables:\nCopy\nAsk AI\nimport\n os\n\n\nimport\n getpass\n\n\n\n\nif\n \"OPENAI_API_KEY\"\n not\n in\n os.environ:\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n getpass.getpass(\n\"Enter your OpenAI API key: \"\n)\n\n\n4\nUsing CrewAI\nThe first step is to create our project. We will use an example from CrewAI’s documentation:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\n\n\n\n\nclass\n YourCrewName\n:\n\n\n def\n agent_one\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data trends in the market\"\n,\n\n\n backstory\n=\n\"An experienced data analyst with a background in economics\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n def\n agent_two\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Market Researcher\"\n,\n\n\n goal\n=\n\"Gather information on market dynamics\"\n,\n\n\n backstory\n=\n\"A diligent researcher with a keen eye for detail\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n def\n task_one\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n name\n=\n\"Collect Data Task\"\n,\n\n\n description\n=\n\"Collect recent market data and identify trends.\"\n,\n\n\n expected_output\n=\n\"A report summarizing key trends in the market.\"\n,\n\n\n agent\n=\nself\n.agent_one(),\n\n\n )\n\n\n\n\n def\n task_two\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n name\n=\n\"Market Research Task\"\n,\n\n\n description\n=\n\"Research factors affecting market dynamics.\"\n,\n\n\n expected_output\n=\n\"An analysis of factors influencing the market.\"\n,\n\n\n agent\n=\nself\n.agent_two(),\n\n\n )\n\n\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\n[\nself\n.agent_one(), \nself\n.agent_two()],\n\n\n tasks\n=\n[\nself\n.task_one(), \nself\n.task_two()],\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nNow we can import Opik’s tracker and run our crew:\nCopy\nAsk AI\nfrom\n opik.integrations.crewai \nimport\n track_crewai\n\n\n\n\ntrack_crewai(\nproject_name\n=\n\"crewai-integration-demo\"\n)\n\n\n\n\nmy_crew \n=\n YourCrewName().crew()\n\n\nresult \n=\n my_crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\nAfter running your CrewAI application, visit the Opik app to view:\n\n\nLLM traces, spans, and their metadata\n\n\nAgent interactions and task execution flow\n\n\nPerformance metrics like latency and token usage\n\n\nEvaluation metrics (built-in or custom)\n\n\n\n\n​\nResources\n\n\n\n\n🦉 Opik Documentation\n\n\n👉 Opik + CrewAI Colab\n\n\n🐦 X\n\n\n💬 Slack\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOpenLIT Integration\nPatronus AI Evaluation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOpik Overview\nSetup\nResources\nObservability\nOpik Integration\nCopy page\nLearn how to use Comet Opik to debug, evaluate, and monitor your CrewAI applications with comprehensive tracing, automated evaluations, and production-ready dashboards.\n​\nOpik Overview\n\n\nWith \nComet Opik\n, debug, evaluate, and monitor your LLM applications, RAG systems, and agentic workflows with comprehensive tracing, automated evaluations, and production-ready dashboards.\n\n\nOpik Agent Dashboard\n\n\nOpik provides comprehensive support for every stage of your CrewAI application development:\n\n\n\n\nLog Traces and Spans\n: Automatically track LLM calls and application logic to debug and analyze development and production systems. Manually or programmatically annotate, view, and compare responses across projects.\n\n\nEvaluate Your LLM Application’s Performance\n: Evaluate against a custom test set and run built-in evaluation metrics or define your own metrics in the SDK or UI.\n\n\nTest Within Your CI/CD Pipeline\n: Establish reliable performance baselines with Opik’s LLM unit tests, built on PyTest. Run online evaluations for continuous monitoring in production.\n\n\nMonitor & Analyze Production Data\n: Understand your models’ performance on unseen data in production and generate datasets for new dev iterations.\n\n\n\n\n​\nSetup\n\n\nComet provides a hosted version of the Opik platform, or you can run the platform locally.\n\n\nTo use the hosted version, simply \ncreate a free Comet account\n and grab you API Key.\n\n\nTo run the Opik platform locally, see our \ninstallation guide\n for more information.\n\n\nFor this guide we will use CrewAI’s quickstart example.\n\n\n1\nInstall required packages\nCopy\nAsk AI\npip\n install\n crewai\n crewai-tools\n opik\n --upgrade\n\n\n2\nConfigure Opik\nCopy\nAsk AI\nimport\n opik\n\n\nopik.configure(\nuse_local\n=\nFalse\n)\n\n\n3\nPrepare environment\nFirst, we set up our API keys for our LLM-provider as environment variables:\nCopy\nAsk AI\nimport\n os\n\n\nimport\n getpass\n\n\n\n\nif\n \"OPENAI_API_KEY\"\n not\n in\n os.environ:\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n getpass.getpass(\n\"Enter your OpenAI API key: \"\n)\n\n\n4\nUsing CrewAI\nThe first step is to create our project. We will use an example from CrewAI’s documentation:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\n\n\n\n\nclass\n YourCrewName\n:\n\n\n def\n agent_one\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data trends in the market\"\n,\n\n\n backstory\n=\n\"An experienced data analyst with a background in economics\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n def\n agent_two\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Market Researcher\"\n,\n\n\n goal\n=\n\"Gather information on market dynamics\"\n,\n\n\n backstory\n=\n\"A diligent researcher with a keen eye for detail\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n def\n task_one\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n name\n=\n\"Collect Data Task\"\n,\n\n\n description\n=\n\"Collect recent market data and identify trends.\"\n,\n\n\n expected_output\n=\n\"A report summarizing key trends in the market.\"\n,\n\n\n agent\n=\nself\n.agent_one(),\n\n\n )\n\n\n\n\n def\n task_two\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n name\n=\n\"Market Research Task\"\n,\n\n\n description\n=\n\"Research factors affecting market dynamics.\"\n,\n\n\n expected_output\n=\n\"An analysis of factors influencing the market.\"\n,\n\n\n agent\n=\nself\n.agent_two(),\n\n\n )\n\n\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\n[\nself\n.agent_one(), \nself\n.agent_two()],\n\n\n tasks\n=\n[\nself\n.task_one(), \nself\n.task_two()],\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nNow we can import Opik’s tracker and run our crew:\nCopy\nAsk AI\nfrom\n opik.integrations.crewai \nimport\n track_crewai\n\n\n\n\ntrack_crewai(\nproject_name\n=\n\"crewai-integration-demo\"\n)\n\n\n\n\nmy_crew \n=\n YourCrewName().crew()\n\n\nresult \n=\n my_crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\nAfter running your CrewAI application, visit the Opik app to view:\n\n\nLLM traces, spans, and their metadata\n\n\nAgent interactions and task execution flow\n\n\nPerformance metrics like latency and token usage\n\n\nEvaluation metrics (built-in or custom)\n\n\n\n\n​\nResources\n\n\n\n\n🦉 Opik Documentation\n\n\n👉 Opik + CrewAI Colab\n\n\n🐦 X\n\n\n💬 Slack\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOpenLIT Integration\nPatronus AI Evaluation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOpik Overview\nSetup\nResources" }, { "source": "https://docs.crewai.com/en/learn/sequential-process", "title": "Sequential Processes - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nSequential Processes\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nSequential Processes\nCopy page\nA comprehensive guide to utilizing the sequential processes for task execution in CrewAI projects.\n​\nIntroduction\n\n\nCrewAI offers a flexible framework for executing tasks in a structured manner, supporting both sequential and hierarchical processes.\nThis guide outlines how to effectively implement these processes to ensure efficient task execution and project completion.\n\n\n​\nSequential Process Overview\n\n\nThe sequential process ensures tasks are executed one after the other, following a linear progression.\nThis approach is ideal for projects requiring tasks to be completed in a specific order.\n\n\n​\nKey Features\n\n\n\n\nLinear Task Flow\n: Ensures orderly progression by handling tasks in a predetermined sequence.\n\n\nSimplicity\n: Best suited for projects with clear, step-by-step tasks.\n\n\nEasy Monitoring\n: Facilitates easy tracking of task completion and project progress.\n\n\n\n\n​\nImplementing the Sequential Process\n\n\nTo use the sequential process, assemble your crew and define tasks in the order they need to be executed.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Process, Agent, Task, TaskOutput, CrewOutput\n\n\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Researcher'\n,\n\n\n goal\n=\n'Conduct foundational research'\n,\n\n\n backstory\n=\n'An experienced researcher with a passion for uncovering insights'\n\n\n)\n\n\nanalyst \n=\n Agent(\n\n\n role\n=\n'Data Analyst'\n,\n\n\n goal\n=\n'Analyze research findings'\n,\n\n\n backstory\n=\n'A meticulous analyst with a knack for uncovering patterns'\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Writer'\n,\n\n\n goal\n=\n'Draft the final report'\n,\n\n\n backstory\n=\n'A skilled writer with a talent for crafting compelling narratives'\n\n\n)\n\n\n\n\n# Define your tasks\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n'Gather relevant data...'\n, \n\n\n agent\n=\nresearcher, \n\n\n expected_output\n=\n'Raw Data'\n\n\n)\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n'Analyze the data...'\n, \n\n\n agent\n=\nanalyst, \n\n\n expected_output\n=\n'Data Insights'\n\n\n)\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n'Compose the report...'\n, \n\n\n agent\n=\nwriter, \n\n\n expected_output\n=\n'Final Report'\n\n\n)\n\n\n\n\n# Form the crew with a sequential process\n\n\nreport_crew \n=\n Crew(\n\n\n agents\n=\n[researcher, analyst, writer],\n\n\n tasks\n=\n[research_task, analysis_task, writing_task],\n\n\n process\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Execute the crew\n\n\nresult \n=\n report_crew.kickoff()\n\n\n\n\n# Accessing the type-safe output\n\n\ntask_output: TaskOutput \n=\n result.tasks[\n0\n].output\n\n\ncrew_output: CrewOutput \n=\n result.output\n\n\n\n\n​\nNote:\n\n\nEach task in a sequential process \nmust\n have an agent assigned. Ensure that every \nTask\n includes an \nagent\n parameter.\n\n\n​\nWorkflow in Action\n\n\n\n\nInitial Task\n: In a sequential process, the first agent completes their task and signals completion.\n\n\nSubsequent Tasks\n: Agents pick up their tasks based on the process type, with outcomes of preceding tasks or directives guiding their execution.\n\n\nCompletion\n: The process concludes once the final task is executed, leading to project completion.\n\n\n\n\n​\nAdvanced Features\n\n\n​\nTask Delegation\n\n\nIn sequential processes, if an agent has \nallow_delegation\n set to \nTrue\n, they can delegate tasks to other agents in the crew.\nThis feature is automatically set up when there are multiple agents in the crew.\n\n\n​\nAsynchronous Execution\n\n\nTasks can be executed asynchronously, allowing for parallel processing when appropriate.\nTo create an asynchronous task, set \nasync_execution=True\n when defining the task.\n\n\n​\nMemory and Caching\n\n\nCrewAI supports both memory and caching features:\n\n\n\n\nMemory\n: Enable by setting \nmemory=True\n when creating the Crew. This allows agents to retain information across tasks.\n\n\nCaching\n: By default, caching is enabled. Set \ncache=False\n to disable it.\n\n\n\n\n​\nCallbacks\n\n\nYou can set callbacks at both the task and step level:\n\n\n\n\ntask_callback\n: Executed after each task completion.\n\n\nstep_callback\n: Executed after each step in an agent’s execution.\n\n\n\n\n​\nUsage Metrics\n\n\nCrewAI tracks token usage across all tasks and agents. You can access these metrics after execution.\n\n\n​\nBest Practices for Sequential Processes\n\n\n\n\nOrder Matters\n: Arrange tasks in a logical sequence where each task builds upon the previous one.\n\n\nClear Task Descriptions\n: Provide detailed descriptions for each task to guide the agents effectively.\n\n\nAppropriate Agent Selection\n: Match agents’ skills and roles to the requirements of each task.\n\n\nUse Context\n: Leverage the context from previous tasks to inform subsequent ones.\n\n\n\n\nThis updated documentation ensures that details accurately reflect the latest changes in the codebase and clearly describes how to leverage new features and configurations.\nThe content is kept simple and direct to ensure easy understanding.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nReplay Tasks from Latest Crew Kickoff\nUsing Annotations in crew.py\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nSequential Process Overview\nKey Features\nImplementing the Sequential Process\nNote:\nWorkflow in Action\nAdvanced Features\nTask Delegation\nAsynchronous Execution\nMemory and Caching\nCallbacks\nUsage Metrics\nBest Practices for Sequential Processes\nLearn\nSequential Processes\nCopy page\nA comprehensive guide to utilizing the sequential processes for task execution in CrewAI projects.\n​\nIntroduction\n\n\nCrewAI offers a flexible framework for executing tasks in a structured manner, supporting both sequential and hierarchical processes.\nThis guide outlines how to effectively implement these processes to ensure efficient task execution and project completion.\n\n\n​\nSequential Process Overview\n\n\nThe sequential process ensures tasks are executed one after the other, following a linear progression.\nThis approach is ideal for projects requiring tasks to be completed in a specific order.\n\n\n​\nKey Features\n\n\n\n\nLinear Task Flow\n: Ensures orderly progression by handling tasks in a predetermined sequence.\n\n\nSimplicity\n: Best suited for projects with clear, step-by-step tasks.\n\n\nEasy Monitoring\n: Facilitates easy tracking of task completion and project progress.\n\n\n\n\n​\nImplementing the Sequential Process\n\n\nTo use the sequential process, assemble your crew and define tasks in the order they need to be executed.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Process, Agent, Task, TaskOutput, CrewOutput\n\n\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Researcher'\n,\n\n\n goal\n=\n'Conduct foundational research'\n,\n\n\n backstory\n=\n'An experienced researcher with a passion for uncovering insights'\n\n\n)\n\n\nanalyst \n=\n Agent(\n\n\n role\n=\n'Data Analyst'\n,\n\n\n goal\n=\n'Analyze research findings'\n,\n\n\n backstory\n=\n'A meticulous analyst with a knack for uncovering patterns'\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Writer'\n,\n\n\n goal\n=\n'Draft the final report'\n,\n\n\n backstory\n=\n'A skilled writer with a talent for crafting compelling narratives'\n\n\n)\n\n\n\n\n# Define your tasks\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n'Gather relevant data...'\n, \n\n\n agent\n=\nresearcher, \n\n\n expected_output\n=\n'Raw Data'\n\n\n)\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n'Analyze the data...'\n, \n\n\n agent\n=\nanalyst, \n\n\n expected_output\n=\n'Data Insights'\n\n\n)\n\n\nwriting_task \n=\n Task(\n\n\n description\n=\n'Compose the report...'\n, \n\n\n agent\n=\nwriter, \n\n\n expected_output\n=\n'Final Report'\n\n\n)\n\n\n\n\n# Form the crew with a sequential process\n\n\nreport_crew \n=\n Crew(\n\n\n agents\n=\n[researcher, analyst, writer],\n\n\n tasks\n=\n[research_task, analysis_task, writing_task],\n\n\n process\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Execute the crew\n\n\nresult \n=\n report_crew.kickoff()\n\n\n\n\n# Accessing the type-safe output\n\n\ntask_output: TaskOutput \n=\n result.tasks[\n0\n].output\n\n\ncrew_output: CrewOutput \n=\n result.output\n\n\n\n\n​\nNote:\n\n\nEach task in a sequential process \nmust\n have an agent assigned. Ensure that every \nTask\n includes an \nagent\n parameter.\n\n\n​\nWorkflow in Action\n\n\n\n\nInitial Task\n: In a sequential process, the first agent completes their task and signals completion.\n\n\nSubsequent Tasks\n: Agents pick up their tasks based on the process type, with outcomes of preceding tasks or directives guiding their execution.\n\n\nCompletion\n: The process concludes once the final task is executed, leading to project completion.\n\n\n\n\n​\nAdvanced Features\n\n\n​\nTask Delegation\n\n\nIn sequential processes, if an agent has \nallow_delegation\n set to \nTrue\n, they can delegate tasks to other agents in the crew.\nThis feature is automatically set up when there are multiple agents in the crew.\n\n\n​\nAsynchronous Execution\n\n\nTasks can be executed asynchronously, allowing for parallel processing when appropriate.\nTo create an asynchronous task, set \nasync_execution=True\n when defining the task.\n\n\n​\nMemory and Caching\n\n\nCrewAI supports both memory and caching features:\n\n\n\n\nMemory\n: Enable by setting \nmemory=True\n when creating the Crew. This allows agents to retain information across tasks.\n\n\nCaching\n: By default, caching is enabled. Set \ncache=False\n to disable it.\n\n\n\n\n​\nCallbacks\n\n\nYou can set callbacks at both the task and step level:\n\n\n\n\ntask_callback\n: Executed after each task completion.\n\n\nstep_callback\n: Executed after each step in an agent’s execution.\n\n\n\n\n​\nUsage Metrics\n\n\nCrewAI tracks token usage across all tasks and agents. You can access these metrics after execution.\n\n\n​\nBest Practices for Sequential Processes\n\n\n\n\nOrder Matters\n: Arrange tasks in a logical sequence where each task builds upon the previous one.\n\n\nClear Task Descriptions\n: Provide detailed descriptions for each task to guide the agents effectively.\n\n\nAppropriate Agent Selection\n: Match agents’ skills and roles to the requirements of each task.\n\n\nUse Context\n: Leverage the context from previous tasks to inform subsequent ones.\n\n\n\n\nThis updated documentation ensures that details accurately reflect the latest changes in the codebase and clearly describes how to leverage new features and configurations.\nThe content is kept simple and direct to ensure easy understanding.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nReplay Tasks from Latest Crew Kickoff\nUsing Annotations in crew.py\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nSequential Process Overview\nKey Features\nImplementing the Sequential Process\nNote:\nWorkflow in Action\nAdvanced Features\nTask Delegation\nAsynchronous Execution\nMemory and Caching\nCallbacks\nUsage Metrics\nBest Practices for Sequential Processes" }, { "source": "https://docs.crewai.com/#how-flows-work", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/observability/agentops", "title": "AgentOps Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nAgentOps Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nAgentOps Integration\nCopy page\nUnderstanding and logging your agent performance with AgentOps.\n​\nIntroduction\n\n\nObservability is a key aspect of developing and deploying conversational AI agents. It allows developers to understand how their agents are performing,\nhow their agents are interacting with users, and how their agents use external tools and APIs.\nAgentOps is a product independent of CrewAI that provides a comprehensive observability solution for agents.\n\n\n​\nAgentOps\n\n\nAgentOps\n provides session replays, metrics, and monitoring for agents.\n\n\nAt a high level, AgentOps gives you the ability to monitor cost, token usage, latency, agent failures, session-wide statistics, and more.\nFor more info, check out the \nAgentOps Repo\n.\n\n\n​\nOverview\n\n\nAgentOps provides monitoring for agents in development and production.\nIt provides a dashboard for tracking agent performance, session replays, and custom reporting.\n\n\nAdditionally, AgentOps provides session drilldowns for viewing Crew agent interactions, LLM calls, and tool usage in real-time.\nThis feature is useful for debugging and understanding how agents interact with users as well as other agents.\n\n\n\n\n\n\n\n\n​\nFeatures\n\n\n\n\nLLM Cost Management and Tracking\n: Track spend with foundation model providers.\n\n\nReplay Analytics\n: Watch step-by-step agent execution graphs.\n\n\nRecursive Thought Detection\n: Identify when agents fall into infinite loops.\n\n\nCustom Reporting\n: Create custom analytics on agent performance.\n\n\nAnalytics Dashboard\n: Monitor high-level statistics about agents in development and production.\n\n\nPublic Model Testing\n: Test your agents against benchmarks and leaderboards.\n\n\nCustom Tests\n: Run your agents against domain-specific tests.\n\n\nTime Travel Debugging\n: Restart your sessions from checkpoints.\n\n\nCompliance and Security\n: Create audit logs and detect potential threats such as profanity and PII leaks.\n\n\nPrompt Injection Detection\n: Identify potential code injection and secret leaks.\n\n\n\n\n​\nUsing AgentOps\n\n\n1\nCreate an API Key\nCreate a user API key here: \nCreate API Key\n2\nConfigure Your Environment\nAdd your API key to your environment variables:\nCopy\nAsk AI\nAGENTOPS_API_KEY\n=<\nYOUR_AGENTOPS_API_KEY\n>\n\n\n3\nInstall AgentOps\nInstall AgentOps with:\nCopy\nAsk AI\npip\n install\n 'crewai[agentops]'\n\n\nor\nCopy\nAsk AI\npip\n install\n agentops\n\n\n4\nInitialize AgentOps\nBefore using \nCrew\n in your script, include these lines:\nCopy\nAsk AI\nimport\n agentops\n\n\nagentops.init()\n\n\nThis will initiate an AgentOps session as well as automatically track Crew agents. For further info on how to outfit more complex agentic systems,\ncheck out the \nAgentOps documentation\n or join the \nDiscord\n.\n\n\n​\nCrew + AgentOps Examples\n\n\nJob Posting\nExample of a Crew agent that generates job posts.\nMarkdown Validator\nExample of a Crew agent that validates Markdown files.\nInstagram Post\nExample of a Crew agent that generates Instagram posts.\n\n\n​\nFurther Information\n\n\nTo get started, create an \nAgentOps account\n.\n\n\nFor feature requests or bug reports, please reach out to the AgentOps team on the \nAgentOps Repo\n.\n\n\n​\nExtra links\n\n\n🐦 Twitter\n\n\n  •  \n\n\n📢 Discord\n\n\n  •  \n\n\n🖇️ AgentOps Dashboard\n\n\n  •  \n\n\n📙 Documentation\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOverview\nArize Phoenix\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nAgentOps\nOverview\nFeatures\nUsing AgentOps\nCrew + AgentOps Examples\nFurther Information\nExtra links\nObservability\nAgentOps Integration\nCopy page\nUnderstanding and logging your agent performance with AgentOps.\n​\nIntroduction\n\n\nObservability is a key aspect of developing and deploying conversational AI agents. It allows developers to understand how their agents are performing,\nhow their agents are interacting with users, and how their agents use external tools and APIs.\nAgentOps is a product independent of CrewAI that provides a comprehensive observability solution for agents.\n\n\n​\nAgentOps\n\n\nAgentOps\n provides session replays, metrics, and monitoring for agents.\n\n\nAt a high level, AgentOps gives you the ability to monitor cost, token usage, latency, agent failures, session-wide statistics, and more.\nFor more info, check out the \nAgentOps Repo\n.\n\n\n​\nOverview\n\n\nAgentOps provides monitoring for agents in development and production.\nIt provides a dashboard for tracking agent performance, session replays, and custom reporting.\n\n\nAdditionally, AgentOps provides session drilldowns for viewing Crew agent interactions, LLM calls, and tool usage in real-time.\nThis feature is useful for debugging and understanding how agents interact with users as well as other agents.\n\n\n\n\n\n\n\n\n​\nFeatures\n\n\n\n\nLLM Cost Management and Tracking\n: Track spend with foundation model providers.\n\n\nReplay Analytics\n: Watch step-by-step agent execution graphs.\n\n\nRecursive Thought Detection\n: Identify when agents fall into infinite loops.\n\n\nCustom Reporting\n: Create custom analytics on agent performance.\n\n\nAnalytics Dashboard\n: Monitor high-level statistics about agents in development and production.\n\n\nPublic Model Testing\n: Test your agents against benchmarks and leaderboards.\n\n\nCustom Tests\n: Run your agents against domain-specific tests.\n\n\nTime Travel Debugging\n: Restart your sessions from checkpoints.\n\n\nCompliance and Security\n: Create audit logs and detect potential threats such as profanity and PII leaks.\n\n\nPrompt Injection Detection\n: Identify potential code injection and secret leaks.\n\n\n\n\n​\nUsing AgentOps\n\n\n1\nCreate an API Key\nCreate a user API key here: \nCreate API Key\n2\nConfigure Your Environment\nAdd your API key to your environment variables:\nCopy\nAsk AI\nAGENTOPS_API_KEY\n=<\nYOUR_AGENTOPS_API_KEY\n>\n\n\n3\nInstall AgentOps\nInstall AgentOps with:\nCopy\nAsk AI\npip\n install\n 'crewai[agentops]'\n\n\nor\nCopy\nAsk AI\npip\n install\n agentops\n\n\n4\nInitialize AgentOps\nBefore using \nCrew\n in your script, include these lines:\nCopy\nAsk AI\nimport\n agentops\n\n\nagentops.init()\n\n\nThis will initiate an AgentOps session as well as automatically track Crew agents. For further info on how to outfit more complex agentic systems,\ncheck out the \nAgentOps documentation\n or join the \nDiscord\n.\n\n\n​\nCrew + AgentOps Examples\n\n\nJob Posting\nExample of a Crew agent that generates job posts.\nMarkdown Validator\nExample of a Crew agent that validates Markdown files.\nInstagram Post\nExample of a Crew agent that generates Instagram posts.\n\n\n​\nFurther Information\n\n\nTo get started, create an \nAgentOps account\n.\n\n\nFor feature requests or bug reports, please reach out to the AgentOps team on the \nAgentOps Repo\n.\n\n\n​\nExtra links\n\n\n🐦 Twitter\n\n\n  •  \n\n\n📢 Discord\n\n\n  •  \n\n\n🖇️ AgentOps Dashboard\n\n\n  •  \n\n\n📙 Documentation\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nOverview\nArize Phoenix\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nAgentOps\nOverview\nFeatures\nUsing AgentOps\nCrew + AgentOps Examples\nFurther Information\nExtra links" }, { "source": "https://docs.crewai.com/en/concepts/agents", "title": "Agents - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nAgents\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nAgents\nCopy page\nDetailed guide on creating and managing agents within the CrewAI framework.\n​\nOverview of an Agent\n\n\nIn the CrewAI framework, an \nAgent\n is an autonomous unit that can:\n\n\n\n\nPerform specific tasks\n\n\nMake decisions based on its role and goal\n\n\nUse tools to accomplish objectives\n\n\nCommunicate and collaborate with other agents\n\n\nMaintain memory of interactions\n\n\nDelegate tasks when allowed\n\n\n\n\nThink of an agent as a specialized team member with specific skills, expertise, and responsibilities. For example, a \nResearcher\n agent might excel at gathering and analyzing information, while a \nWriter\n agent might be better at creating content.\n\n\nCrewAI Enterprise includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time.\nThe Visual Agent Builder enables:\n\n\nIntuitive agent configuration with form-based interfaces\n\n\nReal-time testing and validation\n\n\nTemplate library with pre-configured agent types\n\n\nEasy customization of agent attributes and behaviors\n\n\n\n\n​\nAgent Attributes\n\n\nAttribute\nParameter\nType\nDescription\nRole\nrole\nstr\nDefines the agent’s function and expertise within the crew.\nGoal\ngoal\nstr\nThe individual objective that guides the agent’s decision-making.\nBackstory\nbackstory\nstr\nProvides context and personality to the agent, enriching interactions.\nLLM\n \n(optional)\nllm\nUnion[str, LLM, Any]\nLanguage model that powers the agent. Defaults to the model specified in \nOPENAI_MODEL_NAME\n or “gpt-4”.\nTools\n \n(optional)\ntools\nList[BaseTool]\nCapabilities or functions available to the agent. Defaults to an empty list.\nFunction Calling LLM\n \n(optional)\nfunction_calling_llm\nOptional[Any]\nLanguage model for tool calling, overrides crew’s LLM if specified.\nMax Iterations\n \n(optional)\nmax_iter\nint\nMaximum iterations before the agent must provide its best answer. Default is 20.\nMax RPM\n \n(optional)\nmax_rpm\nOptional[int]\nMaximum requests per minute to avoid rate limits.\nMax Execution Time\n \n(optional)\nmax_execution_time\nOptional[int]\nMaximum time (in seconds) for task execution.\nVerbose\n \n(optional)\nverbose\nbool\nEnable detailed execution logs for debugging. Default is False.\nAllow Delegation\n \n(optional)\nallow_delegation\nbool\nAllow the agent to delegate tasks to other agents. Default is False.\nStep Callback\n \n(optional)\nstep_callback\nOptional[Any]\nFunction called after each agent step, overrides crew callback.\nCache\n \n(optional)\ncache\nbool\nEnable caching for tool usage. Default is True.\nSystem Template\n \n(optional)\nsystem_template\nOptional[str]\nCustom system prompt template for the agent.\nPrompt Template\n \n(optional)\nprompt_template\nOptional[str]\nCustom prompt template for the agent.\nResponse Template\n \n(optional)\nresponse_template\nOptional[str]\nCustom response template for the agent.\nAllow Code Execution\n \n(optional)\nallow_code_execution\nOptional[bool]\nEnable code execution for the agent. Default is False.\nMax Retry Limit\n \n(optional)\nmax_retry_limit\nint\nMaximum number of retries when an error occurs. Default is 2.\nRespect Context Window\n \n(optional)\nrespect_context_window\nbool\nKeep messages under context window size by summarizing. Default is True.\nCode Execution Mode\n \n(optional)\ncode_execution_mode\nLiteral[\"safe\", \"unsafe\"]\nMode for code execution: ‘safe’ (using Docker) or ‘unsafe’ (direct). Default is ‘safe’.\nMultimodal\n \n(optional)\nmultimodal\nbool\nWhether the agent supports multimodal capabilities. Default is False.\nInject Date\n \n(optional)\ninject_date\nbool\nWhether to automatically inject the current date into tasks. Default is False.\nDate Format\n \n(optional)\ndate_format\nstr\nFormat string for date when inject_date is enabled. Default is “%Y-%m-%d” (ISO format).\nReasoning\n \n(optional)\nreasoning\nbool\nWhether the agent should reflect and create a plan before executing a task. Default is False.\nMax Reasoning Attempts\n \n(optional)\nmax_reasoning_attempts\nOptional[int]\nMaximum number of reasoning attempts before executing the task. If None, will try until ready.\nEmbedder\n \n(optional)\nembedder\nOptional[Dict[str, Any]]\nConfiguration for the embedder used by the agent.\nKnowledge Sources\n \n(optional)\nknowledge_sources\nOptional[List[BaseKnowledgeSource]]\nKnowledge sources available to the agent.\nUse System Prompt\n \n(optional)\nuse_system_prompt\nOptional[bool]\nWhether to use system prompt (for o1 model support). Default is True.\n\n\n​\nCreating Agents\n\n\nThere are two ways to create agents in CrewAI: using \nYAML configuration (recommended)\n or defining them \ndirectly in code\n.\n\n\n​\nYAML Configuration (Recommended)\n\n\nUsing YAML configuration provides a cleaner, more maintainable way to define agents. We strongly recommend using this approach in your CrewAI projects.\n\n\nAfter creating your CrewAI project as outlined in the \nInstallation\n section, navigate to the \nsrc/latest_ai_development/config/agents.yaml\n file and modify the template to match your requirements.\n\n\nVariables in your YAML files (like \n{topic}\n) will be replaced with values from your inputs when running the crew:\nCode\nCopy\nAsk AI\ncrew.kickoff(\ninputs\n=\n{\n'topic'\n: \n'AI Agents'\n})\n\n\n\n\nHere’s an example of how to configure agents using YAML:\n\n\nagents.yaml\nCopy\nAsk AI\n# src/latest_ai_development/config/agents.yaml\n\n\nresearcher\n:\n\n\n role\n: \n>\n\n\n {topic} Senior Data Researcher\n\n\n goal\n: \n>\n\n\n Uncover cutting-edge developments in {topic}\n\n\n backstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the latest\n\n\n developments in {topic}. Known for your ability to find the most relevant\n\n\n information and present it in a clear and concise manner.\n\n\n\n\nreporting_analyst\n:\n\n\n role\n: \n>\n\n\n {topic} Reporting Analyst\n\n\n goal\n: \n>\n\n\n Create detailed reports based on {topic} data analysis and research findings\n\n\n backstory\n: \n>\n\n\n You're a meticulous analyst with a keen eye for detail. You're known for\n\n\n your ability to turn complex data into clear and concise reports, making\n\n\n it easy for others to understand and act on the information you provide.\n\n\n\n\nTo use this YAML configuration in your code, create a crew class that inherits from \nCrewBase\n:\n\n\nCode\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n agents_config \n=\n \"config/agents.yaml\"\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n reporting_analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'reporting_analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\nThe names you use in your YAML files (\nagents.yaml\n) should match the method names in your Python code.\n\n\n​\nDirect Code Definition\n\n\nYou can create agents directly in code by instantiating the \nAgent\n class. Here’s a comprehensive example showing all available parameters:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Create an agent with all available parameters\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Senior Data Scientist\"\n,\n\n\n goal\n=\n\"Analyze and interpret complex datasets to provide actionable insights\"\n,\n\n\n backstory\n=\n\"With over 10 years of experience in data science and machine learning, \"\n\n\n \"you excel at finding patterns in complex datasets.\"\n,\n\n\n llm\n=\n\"gpt-4\"\n, \n# Default: OPENAI_MODEL_NAME or \"gpt-4\"\n\n\n function_calling_llm\n=\nNone\n, \n# Optional: Separate LLM for tool calling\n\n\n verbose\n=\nFalse\n, \n# Default: False\n\n\n allow_delegation\n=\nFalse\n, \n# Default: False\n\n\n max_iter\n=\n20\n, \n# Default: 20 iterations\n\n\n max_rpm\n=\nNone\n, \n# Optional: Rate limit for API calls\n\n\n max_execution_time\n=\nNone\n, \n# Optional: Maximum execution time in seconds\n\n\n max_retry_limit\n=\n2\n, \n# Default: 2 retries on error\n\n\n allow_code_execution\n=\nFalse\n, \n# Default: False\n\n\n code_execution_mode\n=\n\"safe\"\n, \n# Default: \"safe\" (options: \"safe\", \"unsafe\")\n\n\n respect_context_window\n=\nTrue\n, \n# Default: True\n\n\n use_system_prompt\n=\nTrue\n, \n# Default: True\n\n\n multimodal\n=\nFalse\n, \n# Default: False\n\n\n inject_date\n=\nFalse\n, \n# Default: False\n\n\n date_format\n=\n\"%Y-%m-\n%d\n\"\n, \n# Default: ISO format\n\n\n reasoning\n=\nFalse\n, \n# Default: False\n\n\n max_reasoning_attempts\n=\nNone\n, \n# Default: None\n\n\n tools\n=\n[SerperDevTool()], \n# Optional: List of tools\n\n\n knowledge_sources\n=\nNone\n, \n# Optional: List of knowledge sources\n\n\n embedder\n=\nNone\n, \n# Optional: Custom embedder configuration\n\n\n system_template\n=\nNone\n, \n# Optional: Custom system prompt template\n\n\n prompt_template\n=\nNone\n, \n# Optional: Custom prompt template\n\n\n response_template\n=\nNone\n, \n# Optional: Custom response template\n\n\n step_callback\n=\nNone\n, \n# Optional: Callback function for monitoring\n\n\n)\n\n\n\n\nLet’s break down some key parameter combinations for common use cases:\n\n\n​\nBasic Research Agent\n\n\nCode\nCopy\nAsk AI\nresearch_agent \n=\n Agent(\n\n\n role\n=\n\"Research Analyst\"\n,\n\n\n goal\n=\n\"Find and summarize information about specific topics\"\n,\n\n\n backstory\n=\n\"You are an experienced researcher with attention to detail\"\n,\n\n\n tools\n=\n[SerperDevTool()],\n\n\n verbose\n=\nTrue\n # Enable logging for debugging\n\n\n)\n\n\n\n\n​\nCode Development Agent\n\n\nCode\nCopy\nAsk AI\ndev_agent \n=\n Agent(\n\n\n role\n=\n\"Senior Python Developer\"\n,\n\n\n goal\n=\n\"Write and debug Python code\"\n,\n\n\n backstory\n=\n\"Expert Python developer with 10 years of experience\"\n,\n\n\n allow_code_execution\n=\nTrue\n,\n\n\n code_execution_mode\n=\n\"safe\"\n, \n# Uses Docker for safety\n\n\n max_execution_time\n=\n300\n, \n# 5-minute timeout\n\n\n max_retry_limit\n=\n3\n # More retries for complex code tasks\n\n\n)\n\n\n\n\n​\nLong-Running Analysis Agent\n\n\nCode\nCopy\nAsk AI\nanalysis_agent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Perform deep analysis of large datasets\"\n,\n\n\n backstory\n=\n\"Specialized in big data analysis and pattern recognition\"\n,\n\n\n memory\n=\nTrue\n,\n\n\n respect_context_window\n=\nTrue\n,\n\n\n max_rpm\n=\n10\n, \n# Limit API calls\n\n\n function_calling_llm\n=\n\"gpt-4o-mini\"\n # Cheaper model for tool calls\n\n\n)\n\n\n\n\n​\nCustom Template Agent\n\n\nCode\nCopy\nAsk AI\ncustom_agent \n=\n Agent(\n\n\n role\n=\n\"Customer Service Representative\"\n,\n\n\n goal\n=\n\"Assist customers with their inquiries\"\n,\n\n\n backstory\n=\n\"Experienced in customer support with a focus on satisfaction\"\n,\n\n\n system_template\n=\n\"\"\"<|start_header_id|>system<|end_header_id|>\n\n\n {{\n .System \n}}\n<|eot_id|>\"\"\"\n,\n\n\n prompt_template\n=\n\"\"\"<|start_header_id|>user<|end_header_id|>\n\n\n {{\n .Prompt \n}}\n<|eot_id|>\"\"\"\n,\n\n\n response_template\n=\n\"\"\"<|start_header_id|>assistant<|end_header_id|>\n\n\n {{\n .Response \n}}\n<|eot_id|>\"\"\"\n,\n\n\n)\n\n\n\n\n​\nDate-Aware Agent with Reasoning\n\n\nCode\nCopy\nAsk AI\nstrategic_agent \n=\n Agent(\n\n\n role\n=\n\"Market Analyst\"\n,\n\n\n goal\n=\n\"Track market movements with precise date references and strategic planning\"\n,\n\n\n backstory\n=\n\"Expert in time-sensitive financial analysis and strategic reporting\"\n,\n\n\n inject_date\n=\nTrue\n, \n# Automatically inject current date into tasks\n\n\n date_format\n=\n\"%B \n%d\n, %Y\"\n, \n# Format as \"May 21, 2025\"\n\n\n reasoning\n=\nTrue\n, \n# Enable strategic planning\n\n\n max_reasoning_attempts\n=\n2\n, \n# Limit planning iterations\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nReasoning Agent\n\n\nCode\nCopy\nAsk AI\nreasoning_agent \n=\n Agent(\n\n\n role\n=\n\"Strategic Planner\"\n,\n\n\n goal\n=\n\"Analyze complex problems and create detailed execution plans\"\n,\n\n\n backstory\n=\n\"Expert strategic planner who methodically breaks down complex challenges\"\n,\n\n\n reasoning\n=\nTrue\n, \n# Enable reasoning and planning\n\n\n max_reasoning_attempts\n=\n3\n, \n# Limit reasoning attempts\n\n\n max_iter\n=\n30\n, \n# Allow more iterations for complex planning\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nMultimodal Agent\n\n\nCode\nCopy\nAsk AI\nmultimodal_agent \n=\n Agent(\n\n\n role\n=\n\"Visual Content Analyst\"\n,\n\n\n goal\n=\n\"Analyze and process both text and visual content\"\n,\n\n\n backstory\n=\n\"Specialized in multimodal analysis combining text and image understanding\"\n,\n\n\n multimodal\n=\nTrue\n, \n# Enable multimodal capabilities\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nParameter Details\n\n\n​\nCritical Parameters\n\n\n\n\nrole\n, \ngoal\n, and \nbackstory\n are required and shape the agent’s behavior\n\n\nllm\n determines the language model used (default: OpenAI’s GPT-4)\n\n\n\n\n​\nMemory and Context\n\n\n\n\nmemory\n: Enable to maintain conversation history\n\n\nrespect_context_window\n: Prevents token limit issues\n\n\nknowledge_sources\n: Add domain-specific knowledge bases\n\n\n\n\n​\nExecution Control\n\n\n\n\nmax_iter\n: Maximum attempts before giving best answer\n\n\nmax_execution_time\n: Timeout in seconds\n\n\nmax_rpm\n: Rate limiting for API calls\n\n\nmax_retry_limit\n: Retries on error\n\n\n\n\n​\nCode Execution\n\n\n\n\nallow_code_execution\n: Must be True to run code\n\n\ncode_execution_mode\n:\n\n\n\n\n\"safe\"\n: Uses Docker (recommended for production)\n\n\n\"unsafe\"\n: Direct execution (use only in trusted environments)\n\n\n\n\n\n\n\n\nThis runs a default Docker image. If you want to configure the docker image, the checkout the Code Interpreter Tool in the tools section.\nAdd the code interpreter tool as a tool in the agent as a tool parameter.\n\n\n​\nAdvanced Features\n\n\n\n\nmultimodal\n: Enable multimodal capabilities for processing text and visual content\n\n\nreasoning\n: Enable agent to reflect and create plans before executing tasks\n\n\ninject_date\n: Automatically inject current date into task descriptions\n\n\n\n\n​\nTemplates\n\n\n\n\nsystem_template\n: Defines agent’s core behavior\n\n\nprompt_template\n: Structures input format\n\n\nresponse_template\n: Formats agent responses\n\n\n\n\nWhen using custom templates, ensure that both \nsystem_template\n and \nprompt_template\n are defined. The \nresponse_template\n is optional but recommended for consistent output formatting.\n\n\nWhen using custom templates, you can use variables like \n{role}\n, \n{goal}\n, and \n{backstory}\n in your templates. These will be automatically populated during execution.\n\n\n​\nAgent Tools\n\n\nAgents can be equipped with various tools to enhance their capabilities. CrewAI supports tools from:\n\n\n\n\nCrewAI Toolkit\n\n\nLangChain Tools\n\n\n\n\nHere’s how to add tools to an agent:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool, WikipediaTools\n\n\n\n\n# Create tools\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\nwiki_tool \n=\n WikipediaTools()\n\n\n\n\n# Add tools to agent\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"AI Technology Researcher\"\n,\n\n\n goal\n=\n\"Research the latest AI developments\"\n,\n\n\n tools\n=\n[search_tool, wiki_tool],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nAgent Memory and Context\n\n\nAgents can maintain memory of their interactions and use context from previous tasks. This is particularly useful for complex workflows where information needs to be retained across multiple tasks.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\nanalyst \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze and remember complex data patterns\"\n,\n\n\n memory\n=\nTrue\n, \n# Enable memory\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWhen \nmemory\n is enabled, the agent will maintain context across multiple interactions, improving its ability to handle complex, multi-step tasks.\n\n\n​\nContext Window Management\n\n\nCrewAI includes sophisticated automatic context window management to handle situations where conversations exceed the language model’s token limits. This powerful feature is controlled by the \nrespect_context_window\n parameter.\n\n\n​\nHow Context Window Management Works\n\n\nWhen an agent’s conversation history grows too large for the LLM’s context window, CrewAI automatically detects this situation and can either:\n\n\n\n\nAutomatically summarize content\n (when \nrespect_context_window=True\n)\n\n\nStop execution with an error\n (when \nrespect_context_window=False\n)\n\n\n\n\n​\nAutomatic Context Handling (\nrespect_context_window=True\n)\n\n\nThis is the \ndefault and recommended setting\n for most use cases. When enabled, CrewAI will:\n\n\nCode\nCopy\nAsk AI\n# Agent with automatic context management (default)\n\n\nsmart_agent \n=\n Agent(\n\n\n role\n=\n\"Research Analyst\"\n,\n\n\n goal\n=\n\"Analyze large documents and datasets\"\n,\n\n\n backstory\n=\n\"Expert at processing extensive information\"\n,\n\n\n respect_context_window\n=\nTrue\n, \n# 🔑 Default: auto-handle context limits\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWhat happens when context limits are exceeded:\n\n\n\n\n⚠️ \nWarning message\n: \n\"Context length exceeded. Summarizing content to fit the model context window.\"\n\n\n🔄 \nAutomatic summarization\n: CrewAI intelligently summarizes the conversation history\n\n\n✅ \nContinued execution\n: Task execution continues seamlessly with the summarized context\n\n\n📝 \nPreserved information\n: Key information is retained while reducing token count\n\n\n\n\n​\nStrict Context Limits (\nrespect_context_window=False\n)\n\n\nWhen you need precise control and prefer execution to stop rather than lose any information:\n\n\nCode\nCopy\nAsk AI\n# Agent with strict context limits\n\n\nstrict_agent \n=\n Agent(\n\n\n role\n=\n\"Legal Document Reviewer\"\n,\n\n\n goal\n=\n\"Provide precise legal analysis without information loss\"\n,\n\n\n backstory\n=\n\"Legal expert requiring complete context for accurate analysis\"\n,\n\n\n respect_context_window\n=\nFalse\n, \n# ❌ Stop execution on context limit\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWhat happens when context limits are exceeded:\n\n\n\n\n❌ \nError message\n: \n\"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools.\"\n\n\n🛑 \nExecution stops\n: Task execution halts immediately\n\n\n🔧 \nManual intervention required\n: You need to modify your approach\n\n\n\n\n​\nChoosing the Right Setting\n\n\n​\nUse \nrespect_context_window=True\n (Default) when:\n\n\n\n\nProcessing large documents\n that might exceed context limits\n\n\nLong-running conversations\n where some summarization is acceptable\n\n\nResearch tasks\n where general context is more important than exact details\n\n\nPrototyping and development\n where you want robust execution\n\n\n\n\nCode\nCopy\nAsk AI\n# Perfect for document processing\n\n\ndocument_processor \n=\n Agent(\n\n\n role\n=\n\"Document Analyst\"\n,\n\n\n goal\n=\n\"Extract insights from large research papers\"\n,\n\n\n backstory\n=\n\"Expert at analyzing extensive documentation\"\n,\n\n\n respect_context_window\n=\nTrue\n, \n# Handle large documents gracefully\n\n\n max_iter\n=\n50\n, \n# Allow more iterations for complex analysis\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nUse \nrespect_context_window=False\n when:\n\n\n\n\nPrecision is critical\n and information loss is unacceptable\n\n\nLegal or medical tasks\n requiring complete context\n\n\nCode review\n where missing details could introduce bugs\n\n\nFinancial analysis\n where accuracy is paramount\n\n\n\n\nCode\nCopy\nAsk AI\n# Perfect for precision tasks\n\n\nprecision_agent \n=\n Agent(\n\n\n role\n=\n\"Code Security Auditor\"\n,\n\n\n goal\n=\n\"Identify security vulnerabilities in code\"\n,\n\n\n backstory\n=\n\"Security expert requiring complete code context\"\n,\n\n\n respect_context_window\n=\nFalse\n, \n# Prefer failure over incomplete analysis\n\n\n max_retry_limit\n=\n1\n, \n# Fail fast on context issues\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nAlternative Approaches for Large Data\n\n\nWhen dealing with very large datasets, consider these strategies:\n\n\n​\n1. Use RAG Tools\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai_tools \nimport\n RagTool\n\n\n\n\n# Create RAG tool for large document processing\n\n\nrag_tool \n=\n RagTool()\n\n\n\n\nrag_agent \n=\n Agent(\n\n\n role\n=\n\"Research Assistant\"\n,\n\n\n goal\n=\n\"Query large knowledge bases efficiently\"\n,\n\n\n backstory\n=\n\"Expert at using RAG tools for information retrieval\"\n,\n\n\n tools\n=\n[rag_tool], \n# Use RAG instead of large context windows\n\n\n respect_context_window\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\n2. Use Knowledge Sources\n\n\nCode\nCopy\nAsk AI\n# Use knowledge sources instead of large prompts\n\n\nknowledge_agent \n=\n Agent(\n\n\n role\n=\n\"Knowledge Expert\"\n,\n\n\n goal\n=\n\"Answer questions using curated knowledge\"\n,\n\n\n backstory\n=\n\"Expert at leveraging structured knowledge sources\"\n,\n\n\n knowledge_sources\n=\n[your_knowledge_sources], \n# Pre-processed knowledge\n\n\n respect_context_window\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nContext Window Best Practices\n\n\n\n\nMonitor Context Usage\n: Enable \nverbose=True\n to see context management in action\n\n\nDesign for Efficiency\n: Structure tasks to minimize context accumulation\n\n\nUse Appropriate Models\n: Choose LLMs with context windows suitable for your tasks\n\n\nTest Both Settings\n: Try both \nTrue\n and \nFalse\n to see which works better for your use case\n\n\nCombine with RAG\n: Use RAG tools for very large datasets instead of relying solely on context windows\n\n\n\n\n​\nTroubleshooting Context Issues\n\n\nIf you’re getting context limit errors:\n\n\nCode\nCopy\nAsk AI\n# Quick fix: Enable automatic handling\n\n\nagent.respect_context_window \n=\n True\n\n\n\n\n# Better solution: Use RAG tools for large data\n\n\nfrom\n crewai_tools \nimport\n RagTool\n\n\nagent.tools \n=\n [RagTool()]\n\n\n\n\n# Alternative: Break tasks into smaller pieces\n\n\n# Or use knowledge sources instead of large prompts\n\n\n\n\nIf automatic summarization loses important information:\n\n\nCode\nCopy\nAsk AI\n# Disable auto-summarization and use RAG instead\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Detailed Analyst\"\n,\n\n\n goal\n=\n\"Maintain complete information accuracy\"\n,\n\n\n backstory\n=\n\"Expert requiring full context\"\n,\n\n\n respect_context_window\n=\nFalse\n, \n# No summarization\n\n\n tools\n=\n[RagTool()], \n# Use RAG for large data\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nThe context window management feature works automatically in the background. You don’t need to call any special functions - just set \nrespect_context_window\n to your preferred behavior and CrewAI handles the rest!\n\n\n​\nDirect Agent Interaction with \nkickoff()\n\n\nAgents can be used directly without going through a task or crew workflow using the \nkickoff()\n method. This provides a simpler way to interact with an agent when you don’t need the full crew orchestration capabilities.\n\n\n​\nHow \nkickoff()\n Works\n\n\nThe \nkickoff()\n method allows you to send messages directly to an agent and get a response, similar to how you would interact with an LLM but with all the agent’s capabilities (tools, reasoning, etc.).\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Create an agent\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"AI Technology Researcher\"\n,\n\n\n goal\n=\n\"Research the latest AI developments\"\n,\n\n\n tools\n=\n[SerperDevTool()],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Use kickoff() to interact directly with the agent\n\n\nresult \n=\n researcher.kickoff(\n\"What are the latest developments in language models?\"\n)\n\n\n\n\n# Access the raw response\n\n\nprint\n(result.raw)\n\n\n\n\n​\nParameters and Return Values\n\n\nParameter\nType\nDescription\nmessages\nUnion[str, List[Dict[str, str]]]\nEither a string query or a list of message dictionaries with role/content\nresponse_format\nOptional[Type[Any]]\nOptional Pydantic model for structured output\n\n\nThe method returns a \nLiteAgentOutput\n object with the following properties:\n\n\n\n\nraw\n: String containing the raw output text\n\n\npydantic\n: Parsed Pydantic model (if a \nresponse_format\n was provided)\n\n\nagent_role\n: Role of the agent that produced the output\n\n\nusage_metrics\n: Token usage metrics for the execution\n\n\n\n\n​\nStructured Output\n\n\nYou can get structured output by providing a Pydantic model as the \nresponse_format\n:\n\n\nCode\nCopy\nAsk AI\nfrom\n pydantic \nimport\n BaseModel\n\n\nfrom\n typing \nimport\n List\n\n\n\n\nclass\n ResearchFindings\n(\nBaseModel\n):\n\n\n main_points: List[\nstr\n]\n\n\n key_technologies: List[\nstr\n]\n\n\n future_predictions: \nstr\n\n\n\n\n# Get structured output\n\n\nresult \n=\n researcher.kickoff(\n\n\n \"Summarize the latest developments in AI for 2025\"\n,\n\n\n response_format\n=\nResearchFindings\n\n\n)\n\n\n\n\n# Access structured data\n\n\nprint\n(result.pydantic.main_points)\n\n\nprint\n(result.pydantic.future_predictions)\n\n\n\n\n​\nMultiple Messages\n\n\nYou can also provide a conversation history as a list of message dictionaries:\n\n\nCode\nCopy\nAsk AI\nmessages \n=\n [\n\n\n {\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: \n\"I need information about large language models\"\n},\n\n\n {\n\"role\"\n: \n\"assistant\"\n, \n\"content\"\n: \n\"I'd be happy to help with that! What specifically would you like to know?\"\n},\n\n\n {\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: \n\"What are the latest developments in 2025?\"\n}\n\n\n]\n\n\n\n\nresult \n=\n researcher.kickoff(messages)\n\n\n\n\n​\nAsync Support\n\n\nAn asynchronous version is available via \nkickoff_async()\n with the same parameters:\n\n\nCode\nCopy\nAsk AI\nimport\n asyncio\n\n\n\n\nasync\n def\n main\n():\n\n\n result \n=\n await\n researcher.kickoff_async(\n\"What are the latest developments in AI?\"\n)\n\n\n print\n(result.raw)\n\n\n\n\nasyncio.run(main())\n\n\n\n\nThe \nkickoff()\n method uses a \nLiteAgent\n internally, which provides a simpler execution flow while preserving all of the agent’s configuration (role, goal, backstory, tools, etc.).\n\n\n​\nImportant Considerations and Best Practices\n\n\n​\nSecurity and Code Execution\n\n\n\n\nWhen using \nallow_code_execution\n, be cautious with user input and always validate it\n\n\nUse \ncode_execution_mode: \"safe\"\n (Docker) in production environments\n\n\nConsider setting appropriate \nmax_execution_time\n limits to prevent infinite loops\n\n\n\n\n​\nPerformance Optimization\n\n\n\n\nUse \nrespect_context_window: true\n to prevent token limit issues\n\n\nSet appropriate \nmax_rpm\n to avoid rate limiting\n\n\nEnable \ncache: true\n to improve performance for repetitive tasks\n\n\nAdjust \nmax_iter\n and \nmax_retry_limit\n based on task complexity\n\n\n\n\n​\nMemory and Context Management\n\n\n\n\nLeverage \nknowledge_sources\n for domain-specific information\n\n\nConfigure \nembedder\n when using custom embedding models\n\n\nUse custom templates (\nsystem_template\n, \nprompt_template\n, \nresponse_template\n) for fine-grained control over agent behavior\n\n\n\n\n​\nAdvanced Features\n\n\n\n\nEnable \nreasoning: true\n for agents that need to plan and reflect before executing complex tasks\n\n\nSet appropriate \nmax_reasoning_attempts\n to control planning iterations (None for unlimited attempts)\n\n\nUse \ninject_date: true\n to provide agents with current date awareness for time-sensitive tasks\n\n\nCustomize the date format with \ndate_format\n using standard Python datetime format codes\n\n\nEnable \nmultimodal: true\n for agents that need to process both text and visual content\n\n\n\n\n​\nAgent Collaboration\n\n\n\n\nEnable \nallow_delegation: true\n when agents need to work together\n\n\nUse \nstep_callback\n to monitor and log agent interactions\n\n\nConsider using different LLMs for different purposes:\n\n\n\n\nMain \nllm\n for complex reasoning\n\n\nfunction_calling_llm\n for efficient tool usage\n\n\n\n\n\n\n\n\n​\nDate Awareness and Reasoning\n\n\n\n\nUse \ninject_date: true\n to provide agents with current date awareness for time-sensitive tasks\n\n\nCustomize the date format with \ndate_format\n using standard Python datetime format codes\n\n\nValid format codes include: %Y (year), %m (month), %d (day), %B (full month name), etc.\n\n\nInvalid date formats will be logged as warnings and will not modify the task description\n\n\nEnable \nreasoning: true\n for complex tasks that benefit from upfront planning and reflection\n\n\n\n\n​\nModel Compatibility\n\n\n\n\nSet \nuse_system_prompt: false\n for older models that don’t support system messages\n\n\nEnsure your chosen \nllm\n supports the features you need (like function calling)\n\n\n\n\n​\nTroubleshooting Common Issues\n\n\n\n\n\n\nRate Limiting\n: If you’re hitting API rate limits:\n\n\n\n\nImplement appropriate \nmax_rpm\n\n\nUse caching for repetitive operations\n\n\nConsider batching requests\n\n\n\n\n\n\n\n\nContext Window Errors\n: If you’re exceeding context limits:\n\n\n\n\nEnable \nrespect_context_window\n\n\nUse more efficient prompts\n\n\nClear agent memory periodically\n\n\n\n\n\n\n\n\nCode Execution Issues\n: If code execution fails:\n\n\n\n\nVerify Docker is installed for safe mode\n\n\nCheck execution permissions\n\n\nReview code sandbox settings\n\n\n\n\n\n\n\n\nMemory Issues\n: If agent responses seem inconsistent:\n\n\n\n\nCheck knowledge source configuration\n\n\nReview conversation history management\n\n\n\n\n\n\n\n\nRemember that agents are most effective when configured according to their specific use case. Take time to understand your requirements and adjust these parameters accordingly.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nFingerprinting\nTasks\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview of an Agent\nAgent Attributes\nCreating Agents\nYAML Configuration (Recommended)\nDirect Code Definition\nBasic Research Agent\nCode Development Agent\nLong-Running Analysis Agent\nCustom Template Agent\nDate-Aware Agent with Reasoning\nReasoning Agent\nMultimodal Agent\nParameter Details\nCritical Parameters\nMemory and Context\nExecution Control\nCode Execution\nAdvanced Features\nTemplates\nAgent Tools\nAgent Memory and Context\nContext Window Management\nHow Context Window Management Works\nAutomatic Context Handling (respect_context_window=True)\nStrict Context Limits (respect_context_window=False)\nChoosing the Right Setting\nUse respect_context_window=True (Default) when:\nUse respect_context_window=False when:\nAlternative Approaches for Large Data\n1. Use RAG Tools\n2. Use Knowledge Sources\nContext Window Best Practices\nTroubleshooting Context Issues\nDirect Agent Interaction with kickoff()\nHow kickoff() Works\nParameters and Return Values\nStructured Output\nMultiple Messages\nAsync Support\nImportant Considerations and Best Practices\nSecurity and Code Execution\nPerformance Optimization\nMemory and Context Management\nAdvanced Features\nAgent Collaboration\nDate Awareness and Reasoning\nModel Compatibility\nTroubleshooting Common Issues\nCore Concepts\nAgents\nCopy page\nDetailed guide on creating and managing agents within the CrewAI framework.\n​\nOverview of an Agent\n\n\nIn the CrewAI framework, an \nAgent\n is an autonomous unit that can:\n\n\n\n\nPerform specific tasks\n\n\nMake decisions based on its role and goal\n\n\nUse tools to accomplish objectives\n\n\nCommunicate and collaborate with other agents\n\n\nMaintain memory of interactions\n\n\nDelegate tasks when allowed\n\n\n\n\nThink of an agent as a specialized team member with specific skills, expertise, and responsibilities. For example, a \nResearcher\n agent might excel at gathering and analyzing information, while a \nWriter\n agent might be better at creating content.\n\n\nCrewAI Enterprise includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time.\nThe Visual Agent Builder enables:\n\n\nIntuitive agent configuration with form-based interfaces\n\n\nReal-time testing and validation\n\n\nTemplate library with pre-configured agent types\n\n\nEasy customization of agent attributes and behaviors\n\n\n\n\n​\nAgent Attributes\n\n\nAttribute\nParameter\nType\nDescription\nRole\nrole\nstr\nDefines the agent’s function and expertise within the crew.\nGoal\ngoal\nstr\nThe individual objective that guides the agent’s decision-making.\nBackstory\nbackstory\nstr\nProvides context and personality to the agent, enriching interactions.\nLLM\n \n(optional)\nllm\nUnion[str, LLM, Any]\nLanguage model that powers the agent. Defaults to the model specified in \nOPENAI_MODEL_NAME\n or “gpt-4”.\nTools\n \n(optional)\ntools\nList[BaseTool]\nCapabilities or functions available to the agent. Defaults to an empty list.\nFunction Calling LLM\n \n(optional)\nfunction_calling_llm\nOptional[Any]\nLanguage model for tool calling, overrides crew’s LLM if specified.\nMax Iterations\n \n(optional)\nmax_iter\nint\nMaximum iterations before the agent must provide its best answer. Default is 20.\nMax RPM\n \n(optional)\nmax_rpm\nOptional[int]\nMaximum requests per minute to avoid rate limits.\nMax Execution Time\n \n(optional)\nmax_execution_time\nOptional[int]\nMaximum time (in seconds) for task execution.\nVerbose\n \n(optional)\nverbose\nbool\nEnable detailed execution logs for debugging. Default is False.\nAllow Delegation\n \n(optional)\nallow_delegation\nbool\nAllow the agent to delegate tasks to other agents. Default is False.\nStep Callback\n \n(optional)\nstep_callback\nOptional[Any]\nFunction called after each agent step, overrides crew callback.\nCache\n \n(optional)\ncache\nbool\nEnable caching for tool usage. Default is True.\nSystem Template\n \n(optional)\nsystem_template\nOptional[str]\nCustom system prompt template for the agent.\nPrompt Template\n \n(optional)\nprompt_template\nOptional[str]\nCustom prompt template for the agent.\nResponse Template\n \n(optional)\nresponse_template\nOptional[str]\nCustom response template for the agent.\nAllow Code Execution\n \n(optional)\nallow_code_execution\nOptional[bool]\nEnable code execution for the agent. Default is False.\nMax Retry Limit\n \n(optional)\nmax_retry_limit\nint\nMaximum number of retries when an error occurs. Default is 2.\nRespect Context Window\n \n(optional)\nrespect_context_window\nbool\nKeep messages under context window size by summarizing. Default is True.\nCode Execution Mode\n \n(optional)\ncode_execution_mode\nLiteral[\"safe\", \"unsafe\"]\nMode for code execution: ‘safe’ (using Docker) or ‘unsafe’ (direct). Default is ‘safe’.\nMultimodal\n \n(optional)\nmultimodal\nbool\nWhether the agent supports multimodal capabilities. Default is False.\nInject Date\n \n(optional)\ninject_date\nbool\nWhether to automatically inject the current date into tasks. Default is False.\nDate Format\n \n(optional)\ndate_format\nstr\nFormat string for date when inject_date is enabled. Default is “%Y-%m-%d” (ISO format).\nReasoning\n \n(optional)\nreasoning\nbool\nWhether the agent should reflect and create a plan before executing a task. Default is False.\nMax Reasoning Attempts\n \n(optional)\nmax_reasoning_attempts\nOptional[int]\nMaximum number of reasoning attempts before executing the task. If None, will try until ready.\nEmbedder\n \n(optional)\nembedder\nOptional[Dict[str, Any]]\nConfiguration for the embedder used by the agent.\nKnowledge Sources\n \n(optional)\nknowledge_sources\nOptional[List[BaseKnowledgeSource]]\nKnowledge sources available to the agent.\nUse System Prompt\n \n(optional)\nuse_system_prompt\nOptional[bool]\nWhether to use system prompt (for o1 model support). Default is True.\n\n\n​\nCreating Agents\n\n\nThere are two ways to create agents in CrewAI: using \nYAML configuration (recommended)\n or defining them \ndirectly in code\n.\n\n\n​\nYAML Configuration (Recommended)\n\n\nUsing YAML configuration provides a cleaner, more maintainable way to define agents. We strongly recommend using this approach in your CrewAI projects.\n\n\nAfter creating your CrewAI project as outlined in the \nInstallation\n section, navigate to the \nsrc/latest_ai_development/config/agents.yaml\n file and modify the template to match your requirements.\n\n\nVariables in your YAML files (like \n{topic}\n) will be replaced with values from your inputs when running the crew:\nCode\nCopy\nAsk AI\ncrew.kickoff(\ninputs\n=\n{\n'topic'\n: \n'AI Agents'\n})\n\n\n\n\nHere’s an example of how to configure agents using YAML:\n\n\nagents.yaml\nCopy\nAsk AI\n# src/latest_ai_development/config/agents.yaml\n\n\nresearcher\n:\n\n\n role\n: \n>\n\n\n {topic} Senior Data Researcher\n\n\n goal\n: \n>\n\n\n Uncover cutting-edge developments in {topic}\n\n\n backstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the latest\n\n\n developments in {topic}. Known for your ability to find the most relevant\n\n\n information and present it in a clear and concise manner.\n\n\n\n\nreporting_analyst\n:\n\n\n role\n: \n>\n\n\n {topic} Reporting Analyst\n\n\n goal\n: \n>\n\n\n Create detailed reports based on {topic} data analysis and research findings\n\n\n backstory\n: \n>\n\n\n You're a meticulous analyst with a keen eye for detail. You're known for\n\n\n your ability to turn complex data into clear and concise reports, making\n\n\n it easy for others to understand and act on the information you provide.\n\n\n\n\nTo use this YAML configuration in your code, create a crew class that inherits from \nCrewBase\n:\n\n\nCode\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n agents_config \n=\n \"config/agents.yaml\"\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n reporting_analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'reporting_analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\nThe names you use in your YAML files (\nagents.yaml\n) should match the method names in your Python code.\n\n\n​\nDirect Code Definition\n\n\nYou can create agents directly in code by instantiating the \nAgent\n class. Here’s a comprehensive example showing all available parameters:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Create an agent with all available parameters\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Senior Data Scientist\"\n,\n\n\n goal\n=\n\"Analyze and interpret complex datasets to provide actionable insights\"\n,\n\n\n backstory\n=\n\"With over 10 years of experience in data science and machine learning, \"\n\n\n \"you excel at finding patterns in complex datasets.\"\n,\n\n\n llm\n=\n\"gpt-4\"\n, \n# Default: OPENAI_MODEL_NAME or \"gpt-4\"\n\n\n function_calling_llm\n=\nNone\n, \n# Optional: Separate LLM for tool calling\n\n\n verbose\n=\nFalse\n, \n# Default: False\n\n\n allow_delegation\n=\nFalse\n, \n# Default: False\n\n\n max_iter\n=\n20\n, \n# Default: 20 iterations\n\n\n max_rpm\n=\nNone\n, \n# Optional: Rate limit for API calls\n\n\n max_execution_time\n=\nNone\n, \n# Optional: Maximum execution time in seconds\n\n\n max_retry_limit\n=\n2\n, \n# Default: 2 retries on error\n\n\n allow_code_execution\n=\nFalse\n, \n# Default: False\n\n\n code_execution_mode\n=\n\"safe\"\n, \n# Default: \"safe\" (options: \"safe\", \"unsafe\")\n\n\n respect_context_window\n=\nTrue\n, \n# Default: True\n\n\n use_system_prompt\n=\nTrue\n, \n# Default: True\n\n\n multimodal\n=\nFalse\n, \n# Default: False\n\n\n inject_date\n=\nFalse\n, \n# Default: False\n\n\n date_format\n=\n\"%Y-%m-\n%d\n\"\n, \n# Default: ISO format\n\n\n reasoning\n=\nFalse\n, \n# Default: False\n\n\n max_reasoning_attempts\n=\nNone\n, \n# Default: None\n\n\n tools\n=\n[SerperDevTool()], \n# Optional: List of tools\n\n\n knowledge_sources\n=\nNone\n, \n# Optional: List of knowledge sources\n\n\n embedder\n=\nNone\n, \n# Optional: Custom embedder configuration\n\n\n system_template\n=\nNone\n, \n# Optional: Custom system prompt template\n\n\n prompt_template\n=\nNone\n, \n# Optional: Custom prompt template\n\n\n response_template\n=\nNone\n, \n# Optional: Custom response template\n\n\n step_callback\n=\nNone\n, \n# Optional: Callback function for monitoring\n\n\n)\n\n\n\n\nLet’s break down some key parameter combinations for common use cases:\n\n\n​\nBasic Research Agent\n\n\nCode\nCopy\nAsk AI\nresearch_agent \n=\n Agent(\n\n\n role\n=\n\"Research Analyst\"\n,\n\n\n goal\n=\n\"Find and summarize information about specific topics\"\n,\n\n\n backstory\n=\n\"You are an experienced researcher with attention to detail\"\n,\n\n\n tools\n=\n[SerperDevTool()],\n\n\n verbose\n=\nTrue\n # Enable logging for debugging\n\n\n)\n\n\n\n\n​\nCode Development Agent\n\n\nCode\nCopy\nAsk AI\ndev_agent \n=\n Agent(\n\n\n role\n=\n\"Senior Python Developer\"\n,\n\n\n goal\n=\n\"Write and debug Python code\"\n,\n\n\n backstory\n=\n\"Expert Python developer with 10 years of experience\"\n,\n\n\n allow_code_execution\n=\nTrue\n,\n\n\n code_execution_mode\n=\n\"safe\"\n, \n# Uses Docker for safety\n\n\n max_execution_time\n=\n300\n, \n# 5-minute timeout\n\n\n max_retry_limit\n=\n3\n # More retries for complex code tasks\n\n\n)\n\n\n\n\n​\nLong-Running Analysis Agent\n\n\nCode\nCopy\nAsk AI\nanalysis_agent \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Perform deep analysis of large datasets\"\n,\n\n\n backstory\n=\n\"Specialized in big data analysis and pattern recognition\"\n,\n\n\n memory\n=\nTrue\n,\n\n\n respect_context_window\n=\nTrue\n,\n\n\n max_rpm\n=\n10\n, \n# Limit API calls\n\n\n function_calling_llm\n=\n\"gpt-4o-mini\"\n # Cheaper model for tool calls\n\n\n)\n\n\n\n\n​\nCustom Template Agent\n\n\nCode\nCopy\nAsk AI\ncustom_agent \n=\n Agent(\n\n\n role\n=\n\"Customer Service Representative\"\n,\n\n\n goal\n=\n\"Assist customers with their inquiries\"\n,\n\n\n backstory\n=\n\"Experienced in customer support with a focus on satisfaction\"\n,\n\n\n system_template\n=\n\"\"\"<|start_header_id|>system<|end_header_id|>\n\n\n {{\n .System \n}}\n<|eot_id|>\"\"\"\n,\n\n\n prompt_template\n=\n\"\"\"<|start_header_id|>user<|end_header_id|>\n\n\n {{\n .Prompt \n}}\n<|eot_id|>\"\"\"\n,\n\n\n response_template\n=\n\"\"\"<|start_header_id|>assistant<|end_header_id|>\n\n\n {{\n .Response \n}}\n<|eot_id|>\"\"\"\n,\n\n\n)\n\n\n\n\n​\nDate-Aware Agent with Reasoning\n\n\nCode\nCopy\nAsk AI\nstrategic_agent \n=\n Agent(\n\n\n role\n=\n\"Market Analyst\"\n,\n\n\n goal\n=\n\"Track market movements with precise date references and strategic planning\"\n,\n\n\n backstory\n=\n\"Expert in time-sensitive financial analysis and strategic reporting\"\n,\n\n\n inject_date\n=\nTrue\n, \n# Automatically inject current date into tasks\n\n\n date_format\n=\n\"%B \n%d\n, %Y\"\n, \n# Format as \"May 21, 2025\"\n\n\n reasoning\n=\nTrue\n, \n# Enable strategic planning\n\n\n max_reasoning_attempts\n=\n2\n, \n# Limit planning iterations\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nReasoning Agent\n\n\nCode\nCopy\nAsk AI\nreasoning_agent \n=\n Agent(\n\n\n role\n=\n\"Strategic Planner\"\n,\n\n\n goal\n=\n\"Analyze complex problems and create detailed execution plans\"\n,\n\n\n backstory\n=\n\"Expert strategic planner who methodically breaks down complex challenges\"\n,\n\n\n reasoning\n=\nTrue\n, \n# Enable reasoning and planning\n\n\n max_reasoning_attempts\n=\n3\n, \n# Limit reasoning attempts\n\n\n max_iter\n=\n30\n, \n# Allow more iterations for complex planning\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nMultimodal Agent\n\n\nCode\nCopy\nAsk AI\nmultimodal_agent \n=\n Agent(\n\n\n role\n=\n\"Visual Content Analyst\"\n,\n\n\n goal\n=\n\"Analyze and process both text and visual content\"\n,\n\n\n backstory\n=\n\"Specialized in multimodal analysis combining text and image understanding\"\n,\n\n\n multimodal\n=\nTrue\n, \n# Enable multimodal capabilities\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nParameter Details\n\n\n​\nCritical Parameters\n\n\n\n\nrole\n, \ngoal\n, and \nbackstory\n are required and shape the agent’s behavior\n\n\nllm\n determines the language model used (default: OpenAI’s GPT-4)\n\n\n\n\n​\nMemory and Context\n\n\n\n\nmemory\n: Enable to maintain conversation history\n\n\nrespect_context_window\n: Prevents token limit issues\n\n\nknowledge_sources\n: Add domain-specific knowledge bases\n\n\n\n\n​\nExecution Control\n\n\n\n\nmax_iter\n: Maximum attempts before giving best answer\n\n\nmax_execution_time\n: Timeout in seconds\n\n\nmax_rpm\n: Rate limiting for API calls\n\n\nmax_retry_limit\n: Retries on error\n\n\n\n\n​\nCode Execution\n\n\n\n\nallow_code_execution\n: Must be True to run code\n\n\ncode_execution_mode\n:\n\n\n\n\n\"safe\"\n: Uses Docker (recommended for production)\n\n\n\"unsafe\"\n: Direct execution (use only in trusted environments)\n\n\n\n\n\n\n\n\nThis runs a default Docker image. If you want to configure the docker image, the checkout the Code Interpreter Tool in the tools section.\nAdd the code interpreter tool as a tool in the agent as a tool parameter.\n\n\n​\nAdvanced Features\n\n\n\n\nmultimodal\n: Enable multimodal capabilities for processing text and visual content\n\n\nreasoning\n: Enable agent to reflect and create plans before executing tasks\n\n\ninject_date\n: Automatically inject current date into task descriptions\n\n\n\n\n​\nTemplates\n\n\n\n\nsystem_template\n: Defines agent’s core behavior\n\n\nprompt_template\n: Structures input format\n\n\nresponse_template\n: Formats agent responses\n\n\n\n\nWhen using custom templates, ensure that both \nsystem_template\n and \nprompt_template\n are defined. The \nresponse_template\n is optional but recommended for consistent output formatting.\n\n\nWhen using custom templates, you can use variables like \n{role}\n, \n{goal}\n, and \n{backstory}\n in your templates. These will be automatically populated during execution.\n\n\n​\nAgent Tools\n\n\nAgents can be equipped with various tools to enhance their capabilities. CrewAI supports tools from:\n\n\n\n\nCrewAI Toolkit\n\n\nLangChain Tools\n\n\n\n\nHere’s how to add tools to an agent:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool, WikipediaTools\n\n\n\n\n# Create tools\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\nwiki_tool \n=\n WikipediaTools()\n\n\n\n\n# Add tools to agent\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"AI Technology Researcher\"\n,\n\n\n goal\n=\n\"Research the latest AI developments\"\n,\n\n\n tools\n=\n[search_tool, wiki_tool],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nAgent Memory and Context\n\n\nAgents can maintain memory of their interactions and use context from previous tasks. This is particularly useful for complex workflows where information needs to be retained across multiple tasks.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\nanalyst \n=\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze and remember complex data patterns\"\n,\n\n\n memory\n=\nTrue\n, \n# Enable memory\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWhen \nmemory\n is enabled, the agent will maintain context across multiple interactions, improving its ability to handle complex, multi-step tasks.\n\n\n​\nContext Window Management\n\n\nCrewAI includes sophisticated automatic context window management to handle situations where conversations exceed the language model’s token limits. This powerful feature is controlled by the \nrespect_context_window\n parameter.\n\n\n​\nHow Context Window Management Works\n\n\nWhen an agent’s conversation history grows too large for the LLM’s context window, CrewAI automatically detects this situation and can either:\n\n\n\n\nAutomatically summarize content\n (when \nrespect_context_window=True\n)\n\n\nStop execution with an error\n (when \nrespect_context_window=False\n)\n\n\n\n\n​\nAutomatic Context Handling (\nrespect_context_window=True\n)\n\n\nThis is the \ndefault and recommended setting\n for most use cases. When enabled, CrewAI will:\n\n\nCode\nCopy\nAsk AI\n# Agent with automatic context management (default)\n\n\nsmart_agent \n=\n Agent(\n\n\n role\n=\n\"Research Analyst\"\n,\n\n\n goal\n=\n\"Analyze large documents and datasets\"\n,\n\n\n backstory\n=\n\"Expert at processing extensive information\"\n,\n\n\n respect_context_window\n=\nTrue\n, \n# 🔑 Default: auto-handle context limits\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWhat happens when context limits are exceeded:\n\n\n\n\n⚠️ \nWarning message\n: \n\"Context length exceeded. Summarizing content to fit the model context window.\"\n\n\n🔄 \nAutomatic summarization\n: CrewAI intelligently summarizes the conversation history\n\n\n✅ \nContinued execution\n: Task execution continues seamlessly with the summarized context\n\n\n📝 \nPreserved information\n: Key information is retained while reducing token count\n\n\n\n\n​\nStrict Context Limits (\nrespect_context_window=False\n)\n\n\nWhen you need precise control and prefer execution to stop rather than lose any information:\n\n\nCode\nCopy\nAsk AI\n# Agent with strict context limits\n\n\nstrict_agent \n=\n Agent(\n\n\n role\n=\n\"Legal Document Reviewer\"\n,\n\n\n goal\n=\n\"Provide precise legal analysis without information loss\"\n,\n\n\n backstory\n=\n\"Legal expert requiring complete context for accurate analysis\"\n,\n\n\n respect_context_window\n=\nFalse\n, \n# ❌ Stop execution on context limit\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nWhat happens when context limits are exceeded:\n\n\n\n\n❌ \nError message\n: \n\"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools.\"\n\n\n🛑 \nExecution stops\n: Task execution halts immediately\n\n\n🔧 \nManual intervention required\n: You need to modify your approach\n\n\n\n\n​\nChoosing the Right Setting\n\n\n​\nUse \nrespect_context_window=True\n (Default) when:\n\n\n\n\nProcessing large documents\n that might exceed context limits\n\n\nLong-running conversations\n where some summarization is acceptable\n\n\nResearch tasks\n where general context is more important than exact details\n\n\nPrototyping and development\n where you want robust execution\n\n\n\n\nCode\nCopy\nAsk AI\n# Perfect for document processing\n\n\ndocument_processor \n=\n Agent(\n\n\n role\n=\n\"Document Analyst\"\n,\n\n\n goal\n=\n\"Extract insights from large research papers\"\n,\n\n\n backstory\n=\n\"Expert at analyzing extensive documentation\"\n,\n\n\n respect_context_window\n=\nTrue\n, \n# Handle large documents gracefully\n\n\n max_iter\n=\n50\n, \n# Allow more iterations for complex analysis\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nUse \nrespect_context_window=False\n when:\n\n\n\n\nPrecision is critical\n and information loss is unacceptable\n\n\nLegal or medical tasks\n requiring complete context\n\n\nCode review\n where missing details could introduce bugs\n\n\nFinancial analysis\n where accuracy is paramount\n\n\n\n\nCode\nCopy\nAsk AI\n# Perfect for precision tasks\n\n\nprecision_agent \n=\n Agent(\n\n\n role\n=\n\"Code Security Auditor\"\n,\n\n\n goal\n=\n\"Identify security vulnerabilities in code\"\n,\n\n\n backstory\n=\n\"Security expert requiring complete code context\"\n,\n\n\n respect_context_window\n=\nFalse\n, \n# Prefer failure over incomplete analysis\n\n\n max_retry_limit\n=\n1\n, \n# Fail fast on context issues\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nAlternative Approaches for Large Data\n\n\nWhen dealing with very large datasets, consider these strategies:\n\n\n​\n1. Use RAG Tools\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai_tools \nimport\n RagTool\n\n\n\n\n# Create RAG tool for large document processing\n\n\nrag_tool \n=\n RagTool()\n\n\n\n\nrag_agent \n=\n Agent(\n\n\n role\n=\n\"Research Assistant\"\n,\n\n\n goal\n=\n\"Query large knowledge bases efficiently\"\n,\n\n\n backstory\n=\n\"Expert at using RAG tools for information retrieval\"\n,\n\n\n tools\n=\n[rag_tool], \n# Use RAG instead of large context windows\n\n\n respect_context_window\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\n2. Use Knowledge Sources\n\n\nCode\nCopy\nAsk AI\n# Use knowledge sources instead of large prompts\n\n\nknowledge_agent \n=\n Agent(\n\n\n role\n=\n\"Knowledge Expert\"\n,\n\n\n goal\n=\n\"Answer questions using curated knowledge\"\n,\n\n\n backstory\n=\n\"Expert at leveraging structured knowledge sources\"\n,\n\n\n knowledge_sources\n=\n[your_knowledge_sources], \n# Pre-processed knowledge\n\n\n respect_context_window\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n​\nContext Window Best Practices\n\n\n\n\nMonitor Context Usage\n: Enable \nverbose=True\n to see context management in action\n\n\nDesign for Efficiency\n: Structure tasks to minimize context accumulation\n\n\nUse Appropriate Models\n: Choose LLMs with context windows suitable for your tasks\n\n\nTest Both Settings\n: Try both \nTrue\n and \nFalse\n to see which works better for your use case\n\n\nCombine with RAG\n: Use RAG tools for very large datasets instead of relying solely on context windows\n\n\n\n\n​\nTroubleshooting Context Issues\n\n\nIf you’re getting context limit errors:\n\n\nCode\nCopy\nAsk AI\n# Quick fix: Enable automatic handling\n\n\nagent.respect_context_window \n=\n True\n\n\n\n\n# Better solution: Use RAG tools for large data\n\n\nfrom\n crewai_tools \nimport\n RagTool\n\n\nagent.tools \n=\n [RagTool()]\n\n\n\n\n# Alternative: Break tasks into smaller pieces\n\n\n# Or use knowledge sources instead of large prompts\n\n\n\n\nIf automatic summarization loses important information:\n\n\nCode\nCopy\nAsk AI\n# Disable auto-summarization and use RAG instead\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Detailed Analyst\"\n,\n\n\n goal\n=\n\"Maintain complete information accuracy\"\n,\n\n\n backstory\n=\n\"Expert requiring full context\"\n,\n\n\n respect_context_window\n=\nFalse\n, \n# No summarization\n\n\n tools\n=\n[RagTool()], \n# Use RAG for large data\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nThe context window management feature works automatically in the background. You don’t need to call any special functions - just set \nrespect_context_window\n to your preferred behavior and CrewAI handles the rest!\n\n\n​\nDirect Agent Interaction with \nkickoff()\n\n\nAgents can be used directly without going through a task or crew workflow using the \nkickoff()\n method. This provides a simpler way to interact with an agent when you don’t need the full crew orchestration capabilities.\n\n\n​\nHow \nkickoff()\n Works\n\n\nThe \nkickoff()\n method allows you to send messages directly to an agent and get a response, similar to how you would interact with an LLM but with all the agent’s capabilities (tools, reasoning, etc.).\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Create an agent\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"AI Technology Researcher\"\n,\n\n\n goal\n=\n\"Research the latest AI developments\"\n,\n\n\n tools\n=\n[SerperDevTool()],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Use kickoff() to interact directly with the agent\n\n\nresult \n=\n researcher.kickoff(\n\"What are the latest developments in language models?\"\n)\n\n\n\n\n# Access the raw response\n\n\nprint\n(result.raw)\n\n\n\n\n​\nParameters and Return Values\n\n\nParameter\nType\nDescription\nmessages\nUnion[str, List[Dict[str, str]]]\nEither a string query or a list of message dictionaries with role/content\nresponse_format\nOptional[Type[Any]]\nOptional Pydantic model for structured output\n\n\nThe method returns a \nLiteAgentOutput\n object with the following properties:\n\n\n\n\nraw\n: String containing the raw output text\n\n\npydantic\n: Parsed Pydantic model (if a \nresponse_format\n was provided)\n\n\nagent_role\n: Role of the agent that produced the output\n\n\nusage_metrics\n: Token usage metrics for the execution\n\n\n\n\n​\nStructured Output\n\n\nYou can get structured output by providing a Pydantic model as the \nresponse_format\n:\n\n\nCode\nCopy\nAsk AI\nfrom\n pydantic \nimport\n BaseModel\n\n\nfrom\n typing \nimport\n List\n\n\n\n\nclass\n ResearchFindings\n(\nBaseModel\n):\n\n\n main_points: List[\nstr\n]\n\n\n key_technologies: List[\nstr\n]\n\n\n future_predictions: \nstr\n\n\n\n\n# Get structured output\n\n\nresult \n=\n researcher.kickoff(\n\n\n \"Summarize the latest developments in AI for 2025\"\n,\n\n\n response_format\n=\nResearchFindings\n\n\n)\n\n\n\n\n# Access structured data\n\n\nprint\n(result.pydantic.main_points)\n\n\nprint\n(result.pydantic.future_predictions)\n\n\n\n\n​\nMultiple Messages\n\n\nYou can also provide a conversation history as a list of message dictionaries:\n\n\nCode\nCopy\nAsk AI\nmessages \n=\n [\n\n\n {\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: \n\"I need information about large language models\"\n},\n\n\n {\n\"role\"\n: \n\"assistant\"\n, \n\"content\"\n: \n\"I'd be happy to help with that! What specifically would you like to know?\"\n},\n\n\n {\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: \n\"What are the latest developments in 2025?\"\n}\n\n\n]\n\n\n\n\nresult \n=\n researcher.kickoff(messages)\n\n\n\n\n​\nAsync Support\n\n\nAn asynchronous version is available via \nkickoff_async()\n with the same parameters:\n\n\nCode\nCopy\nAsk AI\nimport\n asyncio\n\n\n\n\nasync\n def\n main\n():\n\n\n result \n=\n await\n researcher.kickoff_async(\n\"What are the latest developments in AI?\"\n)\n\n\n print\n(result.raw)\n\n\n\n\nasyncio.run(main())\n\n\n\n\nThe \nkickoff()\n method uses a \nLiteAgent\n internally, which provides a simpler execution flow while preserving all of the agent’s configuration (role, goal, backstory, tools, etc.).\n\n\n​\nImportant Considerations and Best Practices\n\n\n​\nSecurity and Code Execution\n\n\n\n\nWhen using \nallow_code_execution\n, be cautious with user input and always validate it\n\n\nUse \ncode_execution_mode: \"safe\"\n (Docker) in production environments\n\n\nConsider setting appropriate \nmax_execution_time\n limits to prevent infinite loops\n\n\n\n\n​\nPerformance Optimization\n\n\n\n\nUse \nrespect_context_window: true\n to prevent token limit issues\n\n\nSet appropriate \nmax_rpm\n to avoid rate limiting\n\n\nEnable \ncache: true\n to improve performance for repetitive tasks\n\n\nAdjust \nmax_iter\n and \nmax_retry_limit\n based on task complexity\n\n\n\n\n​\nMemory and Context Management\n\n\n\n\nLeverage \nknowledge_sources\n for domain-specific information\n\n\nConfigure \nembedder\n when using custom embedding models\n\n\nUse custom templates (\nsystem_template\n, \nprompt_template\n, \nresponse_template\n) for fine-grained control over agent behavior\n\n\n\n\n​\nAdvanced Features\n\n\n\n\nEnable \nreasoning: true\n for agents that need to plan and reflect before executing complex tasks\n\n\nSet appropriate \nmax_reasoning_attempts\n to control planning iterations (None for unlimited attempts)\n\n\nUse \ninject_date: true\n to provide agents with current date awareness for time-sensitive tasks\n\n\nCustomize the date format with \ndate_format\n using standard Python datetime format codes\n\n\nEnable \nmultimodal: true\n for agents that need to process both text and visual content\n\n\n\n\n​\nAgent Collaboration\n\n\n\n\nEnable \nallow_delegation: true\n when agents need to work together\n\n\nUse \nstep_callback\n to monitor and log agent interactions\n\n\nConsider using different LLMs for different purposes:\n\n\n\n\nMain \nllm\n for complex reasoning\n\n\nfunction_calling_llm\n for efficient tool usage\n\n\n\n\n\n\n\n\n​\nDate Awareness and Reasoning\n\n\n\n\nUse \ninject_date: true\n to provide agents with current date awareness for time-sensitive tasks\n\n\nCustomize the date format with \ndate_format\n using standard Python datetime format codes\n\n\nValid format codes include: %Y (year), %m (month), %d (day), %B (full month name), etc.\n\n\nInvalid date formats will be logged as warnings and will not modify the task description\n\n\nEnable \nreasoning: true\n for complex tasks that benefit from upfront planning and reflection\n\n\n\n\n​\nModel Compatibility\n\n\n\n\nSet \nuse_system_prompt: false\n for older models that don’t support system messages\n\n\nEnsure your chosen \nllm\n supports the features you need (like function calling)\n\n\n\n\n​\nTroubleshooting Common Issues\n\n\n\n\n\n\nRate Limiting\n: If you’re hitting API rate limits:\n\n\n\n\nImplement appropriate \nmax_rpm\n\n\nUse caching for repetitive operations\n\n\nConsider batching requests\n\n\n\n\n\n\n\n\nContext Window Errors\n: If you’re exceeding context limits:\n\n\n\n\nEnable \nrespect_context_window\n\n\nUse more efficient prompts\n\n\nClear agent memory periodically\n\n\n\n\n\n\n\n\nCode Execution Issues\n: If code execution fails:\n\n\n\n\nVerify Docker is installed for safe mode\n\n\nCheck execution permissions\n\n\nReview code sandbox settings\n\n\n\n\n\n\n\n\nMemory Issues\n: If agent responses seem inconsistent:\n\n\n\n\nCheck knowledge source configuration\n\n\nReview conversation history management\n\n\n\n\n\n\n\n\nRemember that agents are most effective when configured according to their specific use case. Take time to understand your requirements and adjust these parameters accordingly.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nFingerprinting\nTasks\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview of an Agent\nAgent Attributes\nCreating Agents\nYAML Configuration (Recommended)\nDirect Code Definition\nBasic Research Agent\nCode Development Agent\nLong-Running Analysis Agent\nCustom Template Agent\nDate-Aware Agent with Reasoning\nReasoning Agent\nMultimodal Agent\nParameter Details\nCritical Parameters\nMemory and Context\nExecution Control\nCode Execution\nAdvanced Features\nTemplates\nAgent Tools\nAgent Memory and Context\nContext Window Management\nHow Context Window Management Works\nAutomatic Context Handling (respect_context_window=True)\nStrict Context Limits (respect_context_window=False)\nChoosing the Right Setting\nUse respect_context_window=True (Default) when:\nUse respect_context_window=False when:\nAlternative Approaches for Large Data\n1. Use RAG Tools\n2. Use Knowledge Sources\nContext Window Best Practices\nTroubleshooting Context Issues\nDirect Agent Interaction with kickoff()\nHow kickoff() Works\nParameters and Return Values\nStructured Output\nMultiple Messages\nAsync Support\nImportant Considerations and Best Practices\nSecurity and Code Execution\nPerformance Optimization\nMemory and Context Management\nAdvanced Features\nAgent Collaboration\nDate Awareness and Reasoning\nModel Compatibility\nTroubleshooting Common Issues" }, { "source": "https://docs.crewai.com/en/learn/custom-llm", "title": "Custom LLM Implementation - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nCustom LLM Implementation\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nCustom LLM Implementation\nCopy page\nLearn how to create custom LLM implementations in CrewAI.\n​\nOverview\n\n\nCrewAI supports custom LLM implementations through the \nBaseLLM\n abstract base class. This allows you to integrate any LLM provider that doesn’t have built-in support in LiteLLM, or implement custom authentication mechanisms.\n\n\n​\nQuick Start\n\n\nHere’s a minimal custom LLM implementation:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n BaseLLM\n\n\nfrom\n typing \nimport\n Any, Dict, List, Optional, Union\n\n\nimport\n requests\n\n\n\n\nclass\n CustomLLM\n(\nBaseLLM\n):\n\n\n def\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \napi_key\n: \nstr\n, \nendpoint\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n # IMPORTANT: Call super().__init__() with required parameters\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n \n\n\n self\n.api_key \n=\n api_key\n\n\n self\n.endpoint \n=\n endpoint\n\n\n \n\n\n def\n call\n(\n\n\n self\n,\n\n\n messages\n: Union[\nstr\n, List[Dict[\nstr\n, \nstr\n]]],\n\n\n tools\n: Optional[List[\ndict\n]] \n=\n None\n,\n\n\n callbacks\n: Optional[List[Any]] \n=\n None\n,\n\n\n available_functions\n: Optional[Dict[\nstr\n, Any]] \n=\n None\n,\n\n\n ) -> Union[\nstr\n, Any]:\n\n\n \"\"\"Call the LLM with the given messages.\"\"\"\n\n\n # Convert string to message format if needed\n\n\n if\n isinstance\n(messages, \nstr\n):\n\n\n messages \n=\n [{\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: messages}]\n\n\n \n\n\n # Prepare request\n\n\n payload \n=\n {\n\n\n \"model\"\n: \nself\n.model,\n\n\n \"messages\"\n: messages,\n\n\n \"temperature\"\n: \nself\n.temperature,\n\n\n }\n\n\n \n\n\n # Add tools if provided and supported\n\n\n if\n tools \nand\n self\n.supports_function_calling():\n\n\n payload[\n\"tools\"\n] \n=\n tools\n\n\n \n\n\n # Make API call\n\n\n response \n=\n requests.post(\n\n\n self\n.endpoint,\n\n\n headers\n=\n{\n\n\n \"Authorization\"\n: \nf\n\"Bearer \n{\nself\n.api_key\n}\n\"\n,\n\n\n \"Content-Type\"\n: \n\"application/json\"\n\n\n },\n\n\n json\n=\npayload,\n\n\n timeout\n=\n30\n\n\n )\n\n\n response.raise_for_status()\n\n\n \n\n\n result \n=\n response.json()\n\n\n return\n result[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n \n\n\n def\n supports_function_calling\n(\nself\n) -> \nbool\n:\n\n\n \"\"\"Override if your LLM supports function calling.\"\"\"\n\n\n return\n True\n # Change to False if your LLM doesn't support tools\n\n\n \n\n\n def\n get_context_window_size\n(\nself\n) -> \nint\n:\n\n\n \"\"\"Return the context window size of your LLM.\"\"\"\n\n\n return\n 8192\n # Adjust based on your model's actual context window\n\n\n\n\n​\nUsing Your Custom LLM\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Assuming you have the CustomLLM class defined above\n\n\n# Create your custom LLM\n\n\ncustom_llm \n=\n CustomLLM(\n\n\n model\n=\n\"my-custom-model\"\n,\n\n\n api_key\n=\n\"your-api-key\"\n,\n\n\n endpoint\n=\n\"https://api.example.com/v1/chat/completions\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\n\n\n# Use with an agent\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Research Assistant\"\n,\n\n\n goal\n=\n\"Find and analyze information\"\n,\n\n\n backstory\n=\n\"You are a research assistant.\"\n,\n\n\n llm\n=\ncustom_llm\n\n\n)\n\n\n\n\n# Create and execute tasks\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI\"\n,\n\n\n expected_output\n=\n\"A comprehensive summary\"\n,\n\n\n agent\n=\nagent\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nRequired Methods\n\n\n​\nConstructor: \n__init__()\n\n\nCritical\n: You must call \nsuper().__init__(model, temperature)\n with the required parameters:\n\n\nCopy\nAsk AI\ndef\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \napi_key\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n # REQUIRED: Call parent constructor with model and temperature\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n \n\n\n # Your custom initialization\n\n\n self\n.api_key \n=\n api_key\n\n\n\n\n​\nAbstract Method: \ncall()\n\n\nThe \ncall()\n method is the heart of your LLM implementation. It must:\n\n\n\n\nAccept messages (string or list of dicts with ‘role’ and ‘content’)\n\n\nReturn a string response\n\n\nHandle tools and function calling if supported\n\n\nRaise appropriate exceptions for errors\n\n\n\n\n​\nOptional Methods\n\n\nCopy\nAsk AI\ndef\n supports_function_calling\n(\nself\n) -> \nbool\n:\n\n\n \"\"\"Return True if your LLM supports function calling.\"\"\"\n\n\n return\n True\n # Default is True\n\n\n\n\ndef\n supports_stop_words\n(\nself\n) -> \nbool\n:\n\n\n \"\"\"Return True if your LLM supports stop sequences.\"\"\"\n\n\n return\n True\n # Default is True\n\n\n\n\ndef\n get_context_window_size\n(\nself\n) -> \nint\n:\n\n\n \"\"\"Return the context window size.\"\"\"\n\n\n return\n 4096\n # Default is 4096\n\n\n\n\n​\nCommon Patterns\n\n\n​\nError Handling\n\n\nCopy\nAsk AI\nimport\n requests\n\n\n\n\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n try\n:\n\n\n response \n=\n requests.post(\n\n\n self\n.endpoint,\n\n\n headers\n=\n{\n\"Authorization\"\n: \nf\n\"Bearer \n{\nself\n.api_key\n}\n\"\n},\n\n\n json\n=\npayload,\n\n\n timeout\n=\n30\n\n\n )\n\n\n response.raise_for_status()\n\n\n return\n response.json()[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n \n\n\n except\n requests.Timeout:\n\n\n raise\n TimeoutError\n(\n\"LLM request timed out\"\n)\n\n\n except\n requests.RequestException \nas\n e:\n\n\n raise\n RuntimeError\n(\nf\n\"LLM request failed: \n{\nstr\n(e)\n}\n\"\n)\n\n\n except\n (\nKeyError\n, \nIndexError\n) \nas\n e:\n\n\n raise\n ValueError\n(\nf\n\"Invalid response format: \n{\nstr\n(e)\n}\n\"\n)\n\n\n\n\n​\nCustom Authentication\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n BaseLLM\n\n\nfrom\n typing \nimport\n Optional\n\n\n\n\nclass\n CustomAuthLLM\n(\nBaseLLM\n):\n\n\n def\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \nauth_token\n: \nstr\n, \nendpoint\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n self\n.auth_token \n=\n auth_token\n\n\n self\n.endpoint \n=\n endpoint\n\n\n \n\n\n def\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n headers \n=\n {\n\n\n \"Authorization\"\n: \nf\n\"Custom \n{\nself\n.auth_token\n}\n\"\n, \n# Custom auth format\n\n\n \"Content-Type\"\n: \n\"application/json\"\n\n\n }\n\n\n # Rest of implementation...\n\n\n\n\n​\nStop Words Support\n\n\nCrewAI automatically adds \n\"\\nObservation:\"\n as a stop word to control agent behavior. If your LLM supports stop words:\n\n\nCopy\nAsk AI\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n payload \n=\n {\n\n\n \"model\"\n: \nself\n.model,\n\n\n \"messages\"\n: messages,\n\n\n \"stop\"\n: \nself\n.stop \n# Include stop words in API call\n\n\n }\n\n\n # Make API call...\n\n\n\n\ndef\n supports_stop_words\n(\nself\n) -> \nbool\n:\n\n\n return\n True\n # Your LLM supports stop sequences\n\n\n\n\nIf your LLM doesn’t support stop words natively:\n\n\nCopy\nAsk AI\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n response \n=\n self\n._make_api_call(messages, tools)\n\n\n content \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n \n\n\n # Manually truncate at stop words\n\n\n if\n self\n.stop:\n\n\n for\n stop_word \nin\n self\n.stop:\n\n\n if\n stop_word \nin\n content:\n\n\n content \n=\n content.split(stop_word)[\n0\n]\n\n\n break\n\n\n \n\n\n return\n content\n\n\n\n\ndef\n supports_stop_words\n(\nself\n) -> \nbool\n:\n\n\n return\n False\n # Tell CrewAI we handle stop words manually\n\n\n\n\n​\nFunction Calling\n\n\nIf your LLM supports function calling, implement the complete flow:\n\n\nCopy\nAsk AI\nimport\n json\n\n\n\n\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n # Convert string to message format\n\n\n if\n isinstance\n(messages, \nstr\n):\n\n\n messages \n=\n [{\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: messages}]\n\n\n \n\n\n # Make API call\n\n\n response \n=\n self\n._make_api_call(messages, tools)\n\n\n message \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n]\n\n\n \n\n\n # Check for function calls\n\n\n if\n \"tool_calls\"\n in\n message \nand\n available_functions:\n\n\n return\n self\n._handle_function_calls(\n\n\n message[\n\"tool_calls\"\n], messages, tools, available_functions\n\n\n )\n\n\n \n\n\n return\n message[\n\"content\"\n]\n\n\n\n\ndef\n _handle_function_calls\n(\nself\n, \ntool_calls\n, \nmessages\n, \ntools\n, \navailable_functions\n):\n\n\n \"\"\"Handle function calling with proper message flow.\"\"\"\n\n\n for\n tool_call \nin\n tool_calls:\n\n\n function_name \n=\n tool_call[\n\"function\"\n][\n\"name\"\n]\n\n\n \n\n\n if\n function_name \nin\n available_functions:\n\n\n # Parse and execute function\n\n\n function_args \n=\n json.loads(tool_call[\n\"function\"\n][\n\"arguments\"\n])\n\n\n function_result \n=\n available_functions[function_name](\n**\nfunction_args)\n\n\n \n\n\n # Add function call and result to message history\n\n\n messages.append({\n\n\n \"role\"\n: \n\"assistant\"\n,\n\n\n \"content\"\n: \nNone\n,\n\n\n \"tool_calls\"\n: [tool_call]\n\n\n })\n\n\n messages.append({\n\n\n \"role\"\n: \n\"tool\"\n,\n\n\n \"tool_call_id\"\n: tool_call[\n\"id\"\n],\n\n\n \"name\"\n: function_name,\n\n\n \"content\"\n: \nstr\n(function_result)\n\n\n })\n\n\n \n\n\n # Call LLM again with updated context\n\n\n return\n self\n.call(messages, tools, \nNone\n, available_functions)\n\n\n \n\n\n return\n \"Function call failed\"\n\n\n\n\n​\nTroubleshooting\n\n\n​\nCommon Issues\n\n\nConstructor Errors\n\n\nCopy\nAsk AI\n# ❌ Wrong - missing required parameters\n\n\ndef\n __init__\n(\nself\n, \napi_key\n: \nstr\n):\n\n\n super\n().\n__init__\n()\n\n\n\n\n# ✅ Correct\n\n\ndef\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \napi_key\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n\n\nFunction Calling Not Working\n\n\n\n\nEnsure \nsupports_function_calling()\n returns \nTrue\n\n\nCheck that you handle \ntool_calls\n in the response\n\n\nVerify \navailable_functions\n parameter is used correctly\n\n\n\n\nAuthentication Failures\n\n\n\n\nVerify API key format and permissions\n\n\nCheck authentication header format\n\n\nEnsure endpoint URLs are correct\n\n\n\n\nResponse Parsing Errors\n\n\n\n\nValidate response structure before accessing nested fields\n\n\nHandle cases where content might be None\n\n\nAdd proper error handling for malformed responses\n\n\n\n\n​\nTesting Your Custom LLM\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\ndef\n test_custom_llm\n():\n\n\n llm \n=\n CustomLLM(\n\n\n model\n=\n\"test-model\"\n,\n\n\n api_key\n=\n\"test-key\"\n,\n\n\n endpoint\n=\n\"https://api.test.com\"\n\n\n )\n\n\n \n\n\n # Test basic call\n\n\n result \n=\n llm.call(\n\"Hello, world!\"\n)\n\n\n assert\n isinstance\n(result, \nstr\n)\n\n\n assert\n len\n(result) \n>\n 0\n\n\n \n\n\n # Test with CrewAI agent\n\n\n agent \n=\n Agent(\n\n\n role\n=\n\"Test Agent\"\n,\n\n\n goal\n=\n\"Test custom LLM\"\n,\n\n\n backstory\n=\n\"A test agent.\"\n,\n\n\n llm\n=\nllm\n\n\n )\n\n\n \n\n\n task \n=\n Task(\n\n\n description\n=\n\"Say hello\"\n,\n\n\n expected_output\n=\n\"A greeting\"\n,\n\n\n agent\n=\nagent\n\n\n )\n\n\n \n\n\n crew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[task])\n\n\n result \n=\n crew.kickoff()\n\n\n assert\n \"hello\"\n in\n result.raw.lower()\n\n\n\n\nThis guide covers the essentials of implementing custom LLMs in CrewAI.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCreate Custom Tools\nCustom Manager Agent\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nQuick Start\nUsing Your Custom LLM\nRequired Methods\nConstructor: __init__()\nAbstract Method: call()\nOptional Methods\nCommon Patterns\nError Handling\nCustom Authentication\nStop Words Support\nFunction Calling\nTroubleshooting\nCommon Issues\nTesting Your Custom LLM\nLearn\nCustom LLM Implementation\nCopy page\nLearn how to create custom LLM implementations in CrewAI.\n​\nOverview\n\n\nCrewAI supports custom LLM implementations through the \nBaseLLM\n abstract base class. This allows you to integrate any LLM provider that doesn’t have built-in support in LiteLLM, or implement custom authentication mechanisms.\n\n\n​\nQuick Start\n\n\nHere’s a minimal custom LLM implementation:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n BaseLLM\n\n\nfrom\n typing \nimport\n Any, Dict, List, Optional, Union\n\n\nimport\n requests\n\n\n\n\nclass\n CustomLLM\n(\nBaseLLM\n):\n\n\n def\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \napi_key\n: \nstr\n, \nendpoint\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n # IMPORTANT: Call super().__init__() with required parameters\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n \n\n\n self\n.api_key \n=\n api_key\n\n\n self\n.endpoint \n=\n endpoint\n\n\n \n\n\n def\n call\n(\n\n\n self\n,\n\n\n messages\n: Union[\nstr\n, List[Dict[\nstr\n, \nstr\n]]],\n\n\n tools\n: Optional[List[\ndict\n]] \n=\n None\n,\n\n\n callbacks\n: Optional[List[Any]] \n=\n None\n,\n\n\n available_functions\n: Optional[Dict[\nstr\n, Any]] \n=\n None\n,\n\n\n ) -> Union[\nstr\n, Any]:\n\n\n \"\"\"Call the LLM with the given messages.\"\"\"\n\n\n # Convert string to message format if needed\n\n\n if\n isinstance\n(messages, \nstr\n):\n\n\n messages \n=\n [{\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: messages}]\n\n\n \n\n\n # Prepare request\n\n\n payload \n=\n {\n\n\n \"model\"\n: \nself\n.model,\n\n\n \"messages\"\n: messages,\n\n\n \"temperature\"\n: \nself\n.temperature,\n\n\n }\n\n\n \n\n\n # Add tools if provided and supported\n\n\n if\n tools \nand\n self\n.supports_function_calling():\n\n\n payload[\n\"tools\"\n] \n=\n tools\n\n\n \n\n\n # Make API call\n\n\n response \n=\n requests.post(\n\n\n self\n.endpoint,\n\n\n headers\n=\n{\n\n\n \"Authorization\"\n: \nf\n\"Bearer \n{\nself\n.api_key\n}\n\"\n,\n\n\n \"Content-Type\"\n: \n\"application/json\"\n\n\n },\n\n\n json\n=\npayload,\n\n\n timeout\n=\n30\n\n\n )\n\n\n response.raise_for_status()\n\n\n \n\n\n result \n=\n response.json()\n\n\n return\n result[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n \n\n\n def\n supports_function_calling\n(\nself\n) -> \nbool\n:\n\n\n \"\"\"Override if your LLM supports function calling.\"\"\"\n\n\n return\n True\n # Change to False if your LLM doesn't support tools\n\n\n \n\n\n def\n get_context_window_size\n(\nself\n) -> \nint\n:\n\n\n \"\"\"Return the context window size of your LLM.\"\"\"\n\n\n return\n 8192\n # Adjust based on your model's actual context window\n\n\n\n\n​\nUsing Your Custom LLM\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Assuming you have the CustomLLM class defined above\n\n\n# Create your custom LLM\n\n\ncustom_llm \n=\n CustomLLM(\n\n\n model\n=\n\"my-custom-model\"\n,\n\n\n api_key\n=\n\"your-api-key\"\n,\n\n\n endpoint\n=\n\"https://api.example.com/v1/chat/completions\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\n\n\n# Use with an agent\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Research Assistant\"\n,\n\n\n goal\n=\n\"Find and analyze information\"\n,\n\n\n backstory\n=\n\"You are a research assistant.\"\n,\n\n\n llm\n=\ncustom_llm\n\n\n)\n\n\n\n\n# Create and execute tasks\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI\"\n,\n\n\n expected_output\n=\n\"A comprehensive summary\"\n,\n\n\n agent\n=\nagent\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[task])\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nRequired Methods\n\n\n​\nConstructor: \n__init__()\n\n\nCritical\n: You must call \nsuper().__init__(model, temperature)\n with the required parameters:\n\n\nCopy\nAsk AI\ndef\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \napi_key\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n # REQUIRED: Call parent constructor with model and temperature\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n \n\n\n # Your custom initialization\n\n\n self\n.api_key \n=\n api_key\n\n\n\n\n​\nAbstract Method: \ncall()\n\n\nThe \ncall()\n method is the heart of your LLM implementation. It must:\n\n\n\n\nAccept messages (string or list of dicts with ‘role’ and ‘content’)\n\n\nReturn a string response\n\n\nHandle tools and function calling if supported\n\n\nRaise appropriate exceptions for errors\n\n\n\n\n​\nOptional Methods\n\n\nCopy\nAsk AI\ndef\n supports_function_calling\n(\nself\n) -> \nbool\n:\n\n\n \"\"\"Return True if your LLM supports function calling.\"\"\"\n\n\n return\n True\n # Default is True\n\n\n\n\ndef\n supports_stop_words\n(\nself\n) -> \nbool\n:\n\n\n \"\"\"Return True if your LLM supports stop sequences.\"\"\"\n\n\n return\n True\n # Default is True\n\n\n\n\ndef\n get_context_window_size\n(\nself\n) -> \nint\n:\n\n\n \"\"\"Return the context window size.\"\"\"\n\n\n return\n 4096\n # Default is 4096\n\n\n\n\n​\nCommon Patterns\n\n\n​\nError Handling\n\n\nCopy\nAsk AI\nimport\n requests\n\n\n\n\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n try\n:\n\n\n response \n=\n requests.post(\n\n\n self\n.endpoint,\n\n\n headers\n=\n{\n\"Authorization\"\n: \nf\n\"Bearer \n{\nself\n.api_key\n}\n\"\n},\n\n\n json\n=\npayload,\n\n\n timeout\n=\n30\n\n\n )\n\n\n response.raise_for_status()\n\n\n return\n response.json()[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n \n\n\n except\n requests.Timeout:\n\n\n raise\n TimeoutError\n(\n\"LLM request timed out\"\n)\n\n\n except\n requests.RequestException \nas\n e:\n\n\n raise\n RuntimeError\n(\nf\n\"LLM request failed: \n{\nstr\n(e)\n}\n\"\n)\n\n\n except\n (\nKeyError\n, \nIndexError\n) \nas\n e:\n\n\n raise\n ValueError\n(\nf\n\"Invalid response format: \n{\nstr\n(e)\n}\n\"\n)\n\n\n\n\n​\nCustom Authentication\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n BaseLLM\n\n\nfrom\n typing \nimport\n Optional\n\n\n\n\nclass\n CustomAuthLLM\n(\nBaseLLM\n):\n\n\n def\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \nauth_token\n: \nstr\n, \nendpoint\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n self\n.auth_token \n=\n auth_token\n\n\n self\n.endpoint \n=\n endpoint\n\n\n \n\n\n def\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n headers \n=\n {\n\n\n \"Authorization\"\n: \nf\n\"Custom \n{\nself\n.auth_token\n}\n\"\n, \n# Custom auth format\n\n\n \"Content-Type\"\n: \n\"application/json\"\n\n\n }\n\n\n # Rest of implementation...\n\n\n\n\n​\nStop Words Support\n\n\nCrewAI automatically adds \n\"\\nObservation:\"\n as a stop word to control agent behavior. If your LLM supports stop words:\n\n\nCopy\nAsk AI\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n payload \n=\n {\n\n\n \"model\"\n: \nself\n.model,\n\n\n \"messages\"\n: messages,\n\n\n \"stop\"\n: \nself\n.stop \n# Include stop words in API call\n\n\n }\n\n\n # Make API call...\n\n\n\n\ndef\n supports_stop_words\n(\nself\n) -> \nbool\n:\n\n\n return\n True\n # Your LLM supports stop sequences\n\n\n\n\nIf your LLM doesn’t support stop words natively:\n\n\nCopy\nAsk AI\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n response \n=\n self\n._make_api_call(messages, tools)\n\n\n content \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n \n\n\n # Manually truncate at stop words\n\n\n if\n self\n.stop:\n\n\n for\n stop_word \nin\n self\n.stop:\n\n\n if\n stop_word \nin\n content:\n\n\n content \n=\n content.split(stop_word)[\n0\n]\n\n\n break\n\n\n \n\n\n return\n content\n\n\n\n\ndef\n supports_stop_words\n(\nself\n) -> \nbool\n:\n\n\n return\n False\n # Tell CrewAI we handle stop words manually\n\n\n\n\n​\nFunction Calling\n\n\nIf your LLM supports function calling, implement the complete flow:\n\n\nCopy\nAsk AI\nimport\n json\n\n\n\n\ndef\n call\n(\nself\n, \nmessages\n, \ntools\n=\nNone\n, \ncallbacks\n=\nNone\n, \navailable_functions\n=\nNone\n):\n\n\n # Convert string to message format\n\n\n if\n isinstance\n(messages, \nstr\n):\n\n\n messages \n=\n [{\n\"role\"\n: \n\"user\"\n, \n\"content\"\n: messages}]\n\n\n \n\n\n # Make API call\n\n\n response \n=\n self\n._make_api_call(messages, tools)\n\n\n message \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n]\n\n\n \n\n\n # Check for function calls\n\n\n if\n \"tool_calls\"\n in\n message \nand\n available_functions:\n\n\n return\n self\n._handle_function_calls(\n\n\n message[\n\"tool_calls\"\n], messages, tools, available_functions\n\n\n )\n\n\n \n\n\n return\n message[\n\"content\"\n]\n\n\n\n\ndef\n _handle_function_calls\n(\nself\n, \ntool_calls\n, \nmessages\n, \ntools\n, \navailable_functions\n):\n\n\n \"\"\"Handle function calling with proper message flow.\"\"\"\n\n\n for\n tool_call \nin\n tool_calls:\n\n\n function_name \n=\n tool_call[\n\"function\"\n][\n\"name\"\n]\n\n\n \n\n\n if\n function_name \nin\n available_functions:\n\n\n # Parse and execute function\n\n\n function_args \n=\n json.loads(tool_call[\n\"function\"\n][\n\"arguments\"\n])\n\n\n function_result \n=\n available_functions[function_name](\n**\nfunction_args)\n\n\n \n\n\n # Add function call and result to message history\n\n\n messages.append({\n\n\n \"role\"\n: \n\"assistant\"\n,\n\n\n \"content\"\n: \nNone\n,\n\n\n \"tool_calls\"\n: [tool_call]\n\n\n })\n\n\n messages.append({\n\n\n \"role\"\n: \n\"tool\"\n,\n\n\n \"tool_call_id\"\n: tool_call[\n\"id\"\n],\n\n\n \"name\"\n: function_name,\n\n\n \"content\"\n: \nstr\n(function_result)\n\n\n })\n\n\n \n\n\n # Call LLM again with updated context\n\n\n return\n self\n.call(messages, tools, \nNone\n, available_functions)\n\n\n \n\n\n return\n \"Function call failed\"\n\n\n\n\n​\nTroubleshooting\n\n\n​\nCommon Issues\n\n\nConstructor Errors\n\n\nCopy\nAsk AI\n# ❌ Wrong - missing required parameters\n\n\ndef\n __init__\n(\nself\n, \napi_key\n: \nstr\n):\n\n\n super\n().\n__init__\n()\n\n\n\n\n# ✅ Correct\n\n\ndef\n __init__\n(\nself\n, \nmodel\n: \nstr\n, \napi_key\n: \nstr\n, \ntemperature\n: Optional[\nfloat\n] \n=\n None\n):\n\n\n super\n().\n__init__\n(\nmodel\n=\nmodel, \ntemperature\n=\ntemperature)\n\n\n\n\nFunction Calling Not Working\n\n\n\n\nEnsure \nsupports_function_calling()\n returns \nTrue\n\n\nCheck that you handle \ntool_calls\n in the response\n\n\nVerify \navailable_functions\n parameter is used correctly\n\n\n\n\nAuthentication Failures\n\n\n\n\nVerify API key format and permissions\n\n\nCheck authentication header format\n\n\nEnsure endpoint URLs are correct\n\n\n\n\nResponse Parsing Errors\n\n\n\n\nValidate response structure before accessing nested fields\n\n\nHandle cases where content might be None\n\n\nAdd proper error handling for malformed responses\n\n\n\n\n​\nTesting Your Custom LLM\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\ndef\n test_custom_llm\n():\n\n\n llm \n=\n CustomLLM(\n\n\n model\n=\n\"test-model\"\n,\n\n\n api_key\n=\n\"test-key\"\n,\n\n\n endpoint\n=\n\"https://api.test.com\"\n\n\n )\n\n\n \n\n\n # Test basic call\n\n\n result \n=\n llm.call(\n\"Hello, world!\"\n)\n\n\n assert\n isinstance\n(result, \nstr\n)\n\n\n assert\n len\n(result) \n>\n 0\n\n\n \n\n\n # Test with CrewAI agent\n\n\n agent \n=\n Agent(\n\n\n role\n=\n\"Test Agent\"\n,\n\n\n goal\n=\n\"Test custom LLM\"\n,\n\n\n backstory\n=\n\"A test agent.\"\n,\n\n\n llm\n=\nllm\n\n\n )\n\n\n \n\n\n task \n=\n Task(\n\n\n description\n=\n\"Say hello\"\n,\n\n\n expected_output\n=\n\"A greeting\"\n,\n\n\n agent\n=\nagent\n\n\n )\n\n\n \n\n\n crew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[task])\n\n\n result \n=\n crew.kickoff()\n\n\n assert\n \"hello\"\n in\n result.raw.lower()\n\n\n\n\nThis guide covers the essentials of implementing custom LLMs in CrewAI.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCreate Custom Tools\nCustom Manager Agent\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nQuick Start\nUsing Your Custom LLM\nRequired Methods\nConstructor: __init__()\nAbstract Method: call()\nOptional Methods\nCommon Patterns\nError Handling\nCustom Authentication\nStop Words Support\nFunction Calling\nTroubleshooting\nCommon Issues\nTesting Your Custom LLM" }, { "source": "https://docs.crewai.com/en/concepts/training", "title": "Training - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nTraining\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nTraining\nCopy page\nLearn how to train your CrewAI agents by giving them feedback early on and get consistent results.\n​\nOverview\n\n\nThe training feature in CrewAI allows you to train your AI agents using the command-line interface (CLI).\nBy running the command \ncrewai train -n \n, you can specify the number of iterations for the training process.\n\n\nDuring training, CrewAI utilizes techniques to optimize the performance of your agents along with human feedback.\nThis helps the agents improve their understanding, decision-making, and problem-solving abilities.\n\n\n​\nTraining Your Crew Using the CLI\n\n\nTo use the training feature, follow these steps:\n\n\n\n\nOpen your terminal or command prompt.\n\n\nNavigate to the directory where your CrewAI project is located.\n\n\nRun the following command:\n\n\n\n\nCopy\nAsk AI\ncrewai\n train\n -n\n <\nn_iteration\ns\n>\n <\nfilenam\ne\n>\n (optional)\n\n\n\n\nReplace \n\n with the desired number of training iterations and \n\n with the appropriate filename ending with \n.pkl\n.\n\n\n​\nTraining Your Crew Programmatically\n\n\nTo train your crew programmatically, use the following steps:\n\n\n\n\nDefine the number of iterations for training.\n\n\nSpecify the input parameters for the training process.\n\n\nExecute the training command within a try-except block to handle potential errors.\n\n\n\n\nCode\nCopy\nAsk AI\nn_iterations \n=\n 2\n\n\ninputs \n=\n {\n\"topic\"\n: \n\"CrewAI Training\"\n}\n\n\nfilename \n=\n \"your_model.pkl\"\n\n\n\n\ntry\n:\n\n\n YourCrewName_Crew().crew().train(\n\n\n n_iterations\n=\nn_iterations,\n\n\n inputs\n=\ninputs,\n\n\n filename\n=\nfilename\n\n\n )\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n raise\n Exception\n(\nf\n\"An error occurred while training the crew: \n{\ne\n}\n\"\n)\n\n\n\n\n​\nKey Points to Note\n\n\n\n\nPositive Integer Requirement:\n Ensure that the number of iterations (\nn_iterations\n) is a positive integer. The code will raise a \nValueError\n if this condition is not met.\n\n\nFilename Requirement:\n Ensure that the filename ends with \n.pkl\n. The code will raise a \nValueError\n if this condition is not met.\n\n\nError Handling:\n The code handles subprocess errors and unexpected exceptions, providing error messages to the user.\n\n\n\n\nIt is important to note that the training process may take some time, depending on the complexity of your agents and will also require your feedback on each iteration.\n\n\nOnce the training is complete, your agents will be equipped with enhanced capabilities and knowledge, ready to tackle complex tasks and provide more consistent and valuable insights.\n\n\nRemember to regularly update and retrain your agents to ensure they stay up-to-date with the latest information and advancements in the field.\n\n\nHappy training with CrewAI! 🚀\n\n\n​\nSmall Language Model Considerations\n\n\nWhen using smaller language models (≤7B parameters) for training data evaluation, be aware that they may face challenges with generating structured outputs and following complex instructions.\n\n\n​\nLimitations of Small Models in Training Evaluation\n\n\nJSON Output Accuracy\nSmaller models often struggle with producing valid JSON responses needed for structured training evaluations, leading to parsing errors and incomplete data.\nEvaluation Quality\nModels under 7B parameters may provide less nuanced evaluations with limited reasoning depth compared to larger models.\nInstruction Following\nComplex training evaluation criteria may not be fully followed or considered by smaller models.\nConsistency\nEvaluations across multiple training iterations may lack consistency with smaller models.\n\n\n​\nRecommendations for Training\n\n\nBest Practice\nSmall Model Usage\nFor optimal training quality and reliable evaluations, we strongly recommend using models with at least 7B parameters or larger:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, \nLLM\n\n\n\n\n# Recommended minimum for training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"mistral/open-mistral-7b\"\n)\n\n\n\n\n# Better options for reliable training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"anthropic/claude-3-sonnet-20240229-v1:0\"\n)\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n)\n\n\n\n\n# Use this LLM with your agents\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Training Evaluator\"\n,\n\n\n goal\n=\n\"Provide accurate training feedback\"\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\nMore powerful models provide higher quality feedback with better reasoning, leading to more effective training iterations.\nFor optimal training quality and reliable evaluations, we strongly recommend using models with at least 7B parameters or larger:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, \nLLM\n\n\n\n\n# Recommended minimum for training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"mistral/open-mistral-7b\"\n)\n\n\n\n\n# Better options for reliable training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"anthropic/claude-3-sonnet-20240229-v1:0\"\n)\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n)\n\n\n\n\n# Use this LLM with your agents\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Training Evaluator\"\n,\n\n\n goal\n=\n\"Provide accurate training feedback\"\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\nMore powerful models provide higher quality feedback with better reasoning, leading to more effective training iterations.\nIf you must use smaller models for training evaluation, be aware of these constraints:\nCopy\nAsk AI\n# Using a smaller model (expect some limitations)\n\n\nllm \n=\n LLM(\nmodel\n=\n\"huggingface/microsoft/Phi-3-mini-4k-instruct\"\n)\n\n\nWhile CrewAI includes optimizations for small models, expect less reliable and less nuanced evaluation results that may require more human intervention during training.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCollaboration\nMemory\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nTraining Your Crew Using the CLI\nTraining Your Crew Programmatically\nKey Points to Note\nSmall Language Model Considerations\nLimitations of Small Models in Training Evaluation\nRecommendations for Training\nCore Concepts\nTraining\nCopy page\nLearn how to train your CrewAI agents by giving them feedback early on and get consistent results.\n​\nOverview\n\n\nThe training feature in CrewAI allows you to train your AI agents using the command-line interface (CLI).\nBy running the command \ncrewai train -n \n, you can specify the number of iterations for the training process.\n\n\nDuring training, CrewAI utilizes techniques to optimize the performance of your agents along with human feedback.\nThis helps the agents improve their understanding, decision-making, and problem-solving abilities.\n\n\n​\nTraining Your Crew Using the CLI\n\n\nTo use the training feature, follow these steps:\n\n\n\n\nOpen your terminal or command prompt.\n\n\nNavigate to the directory where your CrewAI project is located.\n\n\nRun the following command:\n\n\n\n\nCopy\nAsk AI\ncrewai\n train\n -n\n <\nn_iteration\ns\n>\n <\nfilenam\ne\n>\n (optional)\n\n\n\n\nReplace \n\n with the desired number of training iterations and \n\n with the appropriate filename ending with \n.pkl\n.\n\n\n​\nTraining Your Crew Programmatically\n\n\nTo train your crew programmatically, use the following steps:\n\n\n\n\nDefine the number of iterations for training.\n\n\nSpecify the input parameters for the training process.\n\n\nExecute the training command within a try-except block to handle potential errors.\n\n\n\n\nCode\nCopy\nAsk AI\nn_iterations \n=\n 2\n\n\ninputs \n=\n {\n\"topic\"\n: \n\"CrewAI Training\"\n}\n\n\nfilename \n=\n \"your_model.pkl\"\n\n\n\n\ntry\n:\n\n\n YourCrewName_Crew().crew().train(\n\n\n n_iterations\n=\nn_iterations,\n\n\n inputs\n=\ninputs,\n\n\n filename\n=\nfilename\n\n\n )\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n raise\n Exception\n(\nf\n\"An error occurred while training the crew: \n{\ne\n}\n\"\n)\n\n\n\n\n​\nKey Points to Note\n\n\n\n\nPositive Integer Requirement:\n Ensure that the number of iterations (\nn_iterations\n) is a positive integer. The code will raise a \nValueError\n if this condition is not met.\n\n\nFilename Requirement:\n Ensure that the filename ends with \n.pkl\n. The code will raise a \nValueError\n if this condition is not met.\n\n\nError Handling:\n The code handles subprocess errors and unexpected exceptions, providing error messages to the user.\n\n\n\n\nIt is important to note that the training process may take some time, depending on the complexity of your agents and will also require your feedback on each iteration.\n\n\nOnce the training is complete, your agents will be equipped with enhanced capabilities and knowledge, ready to tackle complex tasks and provide more consistent and valuable insights.\n\n\nRemember to regularly update and retrain your agents to ensure they stay up-to-date with the latest information and advancements in the field.\n\n\nHappy training with CrewAI! 🚀\n\n\n​\nSmall Language Model Considerations\n\n\nWhen using smaller language models (≤7B parameters) for training data evaluation, be aware that they may face challenges with generating structured outputs and following complex instructions.\n\n\n​\nLimitations of Small Models in Training Evaluation\n\n\nJSON Output Accuracy\nSmaller models often struggle with producing valid JSON responses needed for structured training evaluations, leading to parsing errors and incomplete data.\nEvaluation Quality\nModels under 7B parameters may provide less nuanced evaluations with limited reasoning depth compared to larger models.\nInstruction Following\nComplex training evaluation criteria may not be fully followed or considered by smaller models.\nConsistency\nEvaluations across multiple training iterations may lack consistency with smaller models.\n\n\n​\nRecommendations for Training\n\n\nBest Practice\nSmall Model Usage\nFor optimal training quality and reliable evaluations, we strongly recommend using models with at least 7B parameters or larger:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, \nLLM\n\n\n\n\n# Recommended minimum for training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"mistral/open-mistral-7b\"\n)\n\n\n\n\n# Better options for reliable training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"anthropic/claude-3-sonnet-20240229-v1:0\"\n)\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n)\n\n\n\n\n# Use this LLM with your agents\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Training Evaluator\"\n,\n\n\n goal\n=\n\"Provide accurate training feedback\"\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\nMore powerful models provide higher quality feedback with better reasoning, leading to more effective training iterations.\nFor optimal training quality and reliable evaluations, we strongly recommend using models with at least 7B parameters or larger:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, \nLLM\n\n\n\n\n# Recommended minimum for training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"mistral/open-mistral-7b\"\n)\n\n\n\n\n# Better options for reliable training evaluation\n\n\nllm \n=\n LLM(\nmodel\n=\n\"anthropic/claude-3-sonnet-20240229-v1:0\"\n)\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n)\n\n\n\n\n# Use this LLM with your agents\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Training Evaluator\"\n,\n\n\n goal\n=\n\"Provide accurate training feedback\"\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\nMore powerful models provide higher quality feedback with better reasoning, leading to more effective training iterations.\nIf you must use smaller models for training evaluation, be aware of these constraints:\nCopy\nAsk AI\n# Using a smaller model (expect some limitations)\n\n\nllm \n=\n LLM(\nmodel\n=\n\"huggingface/microsoft/Phi-3-mini-4k-instruct\"\n)\n\n\nWhile CrewAI includes optimizations for small models, expect less reliable and less nuanced evaluation results that may require more human intervention during training.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCollaboration\nMemory\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nTraining Your Crew Using the CLI\nTraining Your Crew Programmatically\nKey Points to Note\nSmall Language Model Considerations\nLimitations of Small Models in Training Evaluation\nRecommendations for Training" }, { "source": "https://docs.crewai.com/en/introduction", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/mcp/stdio", "title": "Stdio Transport - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nMCP Integration\nStdio Transport\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nMCP Integration\nStdio Transport\nCopy page\nLearn how to connect CrewAI to local MCP servers using the Stdio (Standard Input/Output) transport mechanism.\n​\nOverview\n\n\nThe Stdio (Standard Input/Output) transport is designed for connecting \nMCPServerAdapter\n to local MCP servers that communicate over their standard input and output streams. This is typically used when the MCP server is a script or executable running on the same machine as your CrewAI application.\n\n\n​\nKey Concepts\n\n\n\n\nLocal Execution\n: Stdio transport manages a locally running process for the MCP server.\n\n\nStdioServerParameters\n: This class from the \nmcp\n library is used to configure the command, arguments, and environment variables for launching the Stdio server.\n\n\n\n\n​\nConnecting via Stdio\n\n\nYou can connect to an Stdio-based MCP server using two main approaches for managing the connection lifecycle:\n\n\n​\n1. Fully Managed Connection (Recommended)\n\n\nUsing a Python context manager (\nwith\n statement) is the recommended approach. It automatically handles starting the MCP server process and stopping it when the context is exited.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters\n\n\nimport\n os\n\n\n\n\n# Create a StdioServerParameters object\n\n\nserver_params\n=\nStdioServerParameters(\n\n\n command\n=\n\"python3\"\n, \n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n)\n\n\n\n\nwith\n MCPServerAdapter(server_params) \nas\n tools:\n\n\n print\n(\nf\n\"Available tools from Stdio MCP server: \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n # Example: Using the tools from the Stdio MCP server in a CrewAI Agent\n\n\n research_agent \n=\n Agent(\n\n\n role\n=\n\"Local Data Processor\"\n,\n\n\n goal\n=\n\"Process data using a local Stdio-based tool.\"\n,\n\n\n backstory\n=\n\"An AI that leverages local scripts via MCP for specialized tasks.\"\n,\n\n\n tools\n=\ntools,\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n \n\n\n processing_task \n=\n Task(\n\n\n description\n=\n\"Process the input data file 'data.txt' and summarize its contents.\"\n,\n\n\n expected_output\n=\n\"A summary of the processed data.\"\n,\n\n\n agent\n=\nresearch_agent,\n\n\n markdown\n=\nTrue\n\n\n )\n\n\n \n\n\n data_crew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[processing_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential \n\n\n )\n\n\n \n\n\n result \n=\n data_crew.kickoff()\n\n\n print\n(\n\"\n\\n\nCrew Task Result (Stdio - Managed):\n\\n\n\"\n, result)\n\n\n\n\n\n\n​\n2. Manual Connection Lifecycle\n\n\nIf you need finer-grained control over when the Stdio MCP server process is started and stopped, you can manage the \nMCPServerAdapter\n lifecycle manually.\n\n\nYou \nMUST\n call \nmcp_server_adapter.stop()\n to ensure the server process is terminated and resources are released. Using a \ntry...finally\n block is highly recommended.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters\n\n\nimport\n os\n\n\n\n\n# Create a StdioServerParameters object\n\n\nstdio_params\n=\nStdioServerParameters(\n\n\n command\n=\n\"python3\"\n, \n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n)\n\n\n\n\nmcp_server_adapter \n=\n MCPServerAdapter(\nserver_params\n=\nstdio_params)\n\n\ntry\n:\n\n\n mcp_server_adapter.start() \n# Manually start the connection and server process\n\n\n tools \n=\n mcp_server_adapter.tools\n\n\n print\n(\nf\n\"Available tools (manual Stdio): \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n # Example: Using the tools with your Agent, Task, Crew setup\n\n\n manual_agent \n=\n Agent(\n\n\n role\n=\n\"Local Task Executor\"\n,\n\n\n goal\n=\n\"Execute a specific local task using a manually managed Stdio tool.\"\n,\n\n\n backstory\n=\n\"An AI proficient in controlling local processes via MCP.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n \n\n\n manual_task \n=\n Task(\n\n\n description\n=\n\"Execute the 'perform_analysis' command via the Stdio tool.\"\n,\n\n\n expected_output\n=\n\"Results of the analysis.\"\n,\n\n\n agent\n=\nmanual_agent\n\n\n )\n\n\n \n\n\n manual_crew \n=\n Crew(\n\n\n agents\n=\n[manual_agent],\n\n\n tasks\n=\n[manual_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n \n\n\n result \n=\n manual_crew.kickoff() \n# Actual inputs depend on your tool\n\n\n print\n(\n\"\n\\n\nCrew Task Result (Stdio - Manual):\n\\n\n\"\n, result)\n\n\n \n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"An error occurred during manual Stdio MCP integration: \n{\ne\n}\n\"\n)\n\n\nfinally\n:\n\n\n if\n mcp_server_adapter \nand\n mcp_server_adapter.is_connected: \n# Check if connected before stopping\n\n\n print\n(\n\"Stopping Stdio MCP server connection (manual)...\"\n)\n\n\n mcp_server_adapter.stop() \n# **Crucial: Ensure stop is called**\n\n\n elif\n mcp_server_adapter: \n# If adapter exists but not connected (e.g. start failed)\n\n\n print\n(\n\"Stdio MCP server adapter was not connected. No stop needed or start failed.\"\n)\n\n\n\n\n\n\nRemember to replace placeholder paths and commands with your actual Stdio server details. The \nenv\n parameter in \nStdioServerParameters\n can\nbe used to set environment variables for the server process, which can be useful for configuring its behavior or providing necessary paths (like \nPYTHONPATH\n).\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMCP Servers as Tools in CrewAI\nSSE Transport\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nKey Concepts\nConnecting via Stdio\n1. Fully Managed Connection (Recommended)\n2. Manual Connection Lifecycle\nMCP Integration\nStdio Transport\nCopy page\nLearn how to connect CrewAI to local MCP servers using the Stdio (Standard Input/Output) transport mechanism.\n​\nOverview\n\n\nThe Stdio (Standard Input/Output) transport is designed for connecting \nMCPServerAdapter\n to local MCP servers that communicate over their standard input and output streams. This is typically used when the MCP server is a script or executable running on the same machine as your CrewAI application.\n\n\n​\nKey Concepts\n\n\n\n\nLocal Execution\n: Stdio transport manages a locally running process for the MCP server.\n\n\nStdioServerParameters\n: This class from the \nmcp\n library is used to configure the command, arguments, and environment variables for launching the Stdio server.\n\n\n\n\n​\nConnecting via Stdio\n\n\nYou can connect to an Stdio-based MCP server using two main approaches for managing the connection lifecycle:\n\n\n​\n1. Fully Managed Connection (Recommended)\n\n\nUsing a Python context manager (\nwith\n statement) is the recommended approach. It automatically handles starting the MCP server process and stopping it when the context is exited.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters\n\n\nimport\n os\n\n\n\n\n# Create a StdioServerParameters object\n\n\nserver_params\n=\nStdioServerParameters(\n\n\n command\n=\n\"python3\"\n, \n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n)\n\n\n\n\nwith\n MCPServerAdapter(server_params) \nas\n tools:\n\n\n print\n(\nf\n\"Available tools from Stdio MCP server: \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n # Example: Using the tools from the Stdio MCP server in a CrewAI Agent\n\n\n research_agent \n=\n Agent(\n\n\n role\n=\n\"Local Data Processor\"\n,\n\n\n goal\n=\n\"Process data using a local Stdio-based tool.\"\n,\n\n\n backstory\n=\n\"An AI that leverages local scripts via MCP for specialized tasks.\"\n,\n\n\n tools\n=\ntools,\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n \n\n\n processing_task \n=\n Task(\n\n\n description\n=\n\"Process the input data file 'data.txt' and summarize its contents.\"\n,\n\n\n expected_output\n=\n\"A summary of the processed data.\"\n,\n\n\n agent\n=\nresearch_agent,\n\n\n markdown\n=\nTrue\n\n\n )\n\n\n \n\n\n data_crew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[processing_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential \n\n\n )\n\n\n \n\n\n result \n=\n data_crew.kickoff()\n\n\n print\n(\n\"\n\\n\nCrew Task Result (Stdio - Managed):\n\\n\n\"\n, result)\n\n\n\n\n\n\n​\n2. Manual Connection Lifecycle\n\n\nIf you need finer-grained control over when the Stdio MCP server process is started and stopped, you can manage the \nMCPServerAdapter\n lifecycle manually.\n\n\nYou \nMUST\n call \nmcp_server_adapter.stop()\n to ensure the server process is terminated and resources are released. Using a \ntry...finally\n block is highly recommended.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters\n\n\nimport\n os\n\n\n\n\n# Create a StdioServerParameters object\n\n\nstdio_params\n=\nStdioServerParameters(\n\n\n command\n=\n\"python3\"\n, \n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n)\n\n\n\n\nmcp_server_adapter \n=\n MCPServerAdapter(\nserver_params\n=\nstdio_params)\n\n\ntry\n:\n\n\n mcp_server_adapter.start() \n# Manually start the connection and server process\n\n\n tools \n=\n mcp_server_adapter.tools\n\n\n print\n(\nf\n\"Available tools (manual Stdio): \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n # Example: Using the tools with your Agent, Task, Crew setup\n\n\n manual_agent \n=\n Agent(\n\n\n role\n=\n\"Local Task Executor\"\n,\n\n\n goal\n=\n\"Execute a specific local task using a manually managed Stdio tool.\"\n,\n\n\n backstory\n=\n\"An AI proficient in controlling local processes via MCP.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n \n\n\n manual_task \n=\n Task(\n\n\n description\n=\n\"Execute the 'perform_analysis' command via the Stdio tool.\"\n,\n\n\n expected_output\n=\n\"Results of the analysis.\"\n,\n\n\n agent\n=\nmanual_agent\n\n\n )\n\n\n \n\n\n manual_crew \n=\n Crew(\n\n\n agents\n=\n[manual_agent],\n\n\n tasks\n=\n[manual_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n \n\n\n result \n=\n manual_crew.kickoff() \n# Actual inputs depend on your tool\n\n\n print\n(\n\"\n\\n\nCrew Task Result (Stdio - Manual):\n\\n\n\"\n, result)\n\n\n \n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"An error occurred during manual Stdio MCP integration: \n{\ne\n}\n\"\n)\n\n\nfinally\n:\n\n\n if\n mcp_server_adapter \nand\n mcp_server_adapter.is_connected: \n# Check if connected before stopping\n\n\n print\n(\n\"Stopping Stdio MCP server connection (manual)...\"\n)\n\n\n mcp_server_adapter.stop() \n# **Crucial: Ensure stop is called**\n\n\n elif\n mcp_server_adapter: \n# If adapter exists but not connected (e.g. start failed)\n\n\n print\n(\n\"Stdio MCP server adapter was not connected. No stop needed or start failed.\"\n)\n\n\n\n\n\n\nRemember to replace placeholder paths and commands with your actual Stdio server details. The \nenv\n parameter in \nStdioServerParameters\n can\nbe used to set environment variables for the server process, which can be useful for configuring its behavior or providing necessary paths (like \nPYTHONPATH\n).\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMCP Servers as Tools in CrewAI\nSSE Transport\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nKey Concepts\nConnecting via Stdio\n1. Fully Managed Connection (Recommended)\n2. Manual Connection Lifecycle" }, { "source": "https://docs.crewai.com/en/learn/kickoff-async", "title": "Kickoff Crew Asynchronously - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nKickoff Crew Asynchronously\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nKickoff Crew Asynchronously\nCopy page\nKickoff a Crew Asynchronously\n​\nIntroduction\n\n\nCrewAI provides the ability to kickoff a crew asynchronously, allowing you to start the crew execution in a non-blocking manner.\nThis feature is particularly useful when you want to run multiple crews concurrently or when you need to perform other tasks while the crew is executing.\n\n\n​\nAsynchronous Crew Execution\n\n\nTo kickoff a crew asynchronously, use the \nkickoff_async()\n method. This method initiates the crew execution in a separate thread, allowing the main thread to continue executing other tasks.\n\n\n​\nMethod Signature\n\n\nCode\nCopy\nAsk AI\ndef\n kickoff_async\n(\nself\n, \ninputs\n: \ndict\n) -> CrewOutput:\n\n\n\n\n​\nParameters\n\n\n\n\ninputs\n (dict): A dictionary containing the input data required for the tasks.\n\n\n\n\n​\nReturns\n\n\n\n\nCrewOutput\n: An object representing the result of the crew execution.\n\n\n\n\n​\nPotential Use Cases\n\n\n\n\n\n\nParallel Content Generation\n: Kickoff multiple independent crews asynchronously, each responsible for generating content on different topics. For example, one crew might research and draft an article on AI trends, while another crew generates social media posts about a new product launch. Each crew operates independently, allowing content production to scale efficiently.\n\n\n\n\n\n\nConcurrent Market Research Tasks\n: Launch multiple crews asynchronously to conduct market research in parallel. One crew might analyze industry trends, while another examines competitor strategies, and yet another evaluates consumer sentiment. Each crew independently completes its task, enabling faster and more comprehensive insights.\n\n\n\n\n\n\nIndependent Travel Planning Modules\n: Execute separate crews to independently plan different aspects of a trip. One crew might handle flight options, another handles accommodation, and a third plans activities. Each crew works asynchronously, allowing various components of the trip to be planned simultaneously and independently for faster results.\n\n\n\n\n\n\n​\nExample: Single Asynchronous Crew Execution\n\n\nHere’s an example of how to kickoff a crew asynchronously using asyncio and awaiting the result:\n\n\nCode\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age of the participants.\"\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task]\n\n\n)\n\n\n\n\n# Async function to kickoff the crew asynchronously\n\n\nasync\n def\n async_crew_execution\n():\n\n\n result \n=\n await\n analysis_crew.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n]})\n\n\n print\n(\n\"Crew Result:\"\n, result)\n\n\n\n\n# Run the async function\n\n\nasyncio.run(async_crew_execution())\n\n\n\n\n​\nExample: Multiple Asynchronous Crew Executions\n\n\nIn this example, we’ll show how to kickoff multiple crews asynchronously and wait for all of them to complete using \nasyncio.gather()\n:\n\n\nCode\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create tasks that require code execution\n\n\ntask_1 \n=\n Task(\n\n\n description\n=\n\"Analyze the first dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age of the participants.\"\n\n\n)\n\n\n\n\ntask_2 \n=\n Task(\n\n\n description\n=\n\"Analyze the second dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age of the participants.\"\n\n\n)\n\n\n\n\n# Create two crews and add tasks\n\n\ncrew_1 \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[task_1])\n\n\ncrew_2 \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[task_2])\n\n\n\n\n# Async function to kickoff multiple crews asynchronously and wait for all to finish\n\n\nasync\n def\n async_multiple_crews\n():\n\n\n # Create coroutines for concurrent execution\n\n\n result_1 \n=\n crew_1.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n]})\n\n\n result_2 \n=\n crew_2.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n20\n, \n22\n, \n24\n, \n28\n, \n30\n]})\n\n\n\n\n # Wait for both crews to finish\n\n\n results \n=\n await\n asyncio.gather(result_1, result_2)\n\n\n\n\n for\n i, result \nin\n enumerate\n(results, \n1\n):\n\n\n print\n(\nf\n\"Crew \n{\ni\n}\n Result:\"\n, result)\n\n\n\n\n# Run the async function\n\n\nasyncio.run(async_multiple_crews())\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nHuman Input on Execution\nKickoff Crew for Each\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nAsynchronous Crew Execution\nMethod Signature\nParameters\nReturns\nPotential Use Cases\nExample: Single Asynchronous Crew Execution\nExample: Multiple Asynchronous Crew Executions\nLearn\nKickoff Crew Asynchronously\nCopy page\nKickoff a Crew Asynchronously\n​\nIntroduction\n\n\nCrewAI provides the ability to kickoff a crew asynchronously, allowing you to start the crew execution in a non-blocking manner.\nThis feature is particularly useful when you want to run multiple crews concurrently or when you need to perform other tasks while the crew is executing.\n\n\n​\nAsynchronous Crew Execution\n\n\nTo kickoff a crew asynchronously, use the \nkickoff_async()\n method. This method initiates the crew execution in a separate thread, allowing the main thread to continue executing other tasks.\n\n\n​\nMethod Signature\n\n\nCode\nCopy\nAsk AI\ndef\n kickoff_async\n(\nself\n, \ninputs\n: \ndict\n) -> CrewOutput:\n\n\n\n\n​\nParameters\n\n\n\n\ninputs\n (dict): A dictionary containing the input data required for the tasks.\n\n\n\n\n​\nReturns\n\n\n\n\nCrewOutput\n: An object representing the result of the crew execution.\n\n\n\n\n​\nPotential Use Cases\n\n\n\n\n\n\nParallel Content Generation\n: Kickoff multiple independent crews asynchronously, each responsible for generating content on different topics. For example, one crew might research and draft an article on AI trends, while another crew generates social media posts about a new product launch. Each crew operates independently, allowing content production to scale efficiently.\n\n\n\n\n\n\nConcurrent Market Research Tasks\n: Launch multiple crews asynchronously to conduct market research in parallel. One crew might analyze industry trends, while another examines competitor strategies, and yet another evaluates consumer sentiment. Each crew independently completes its task, enabling faster and more comprehensive insights.\n\n\n\n\n\n\nIndependent Travel Planning Modules\n: Execute separate crews to independently plan different aspects of a trip. One crew might handle flight options, another handles accommodation, and a third plans activities. Each crew works asynchronously, allowing various components of the trip to be planned simultaneously and independently for faster results.\n\n\n\n\n\n\n​\nExample: Single Asynchronous Crew Execution\n\n\nHere’s an example of how to kickoff a crew asynchronously using asyncio and awaiting the result:\n\n\nCode\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age of the participants.\"\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task]\n\n\n)\n\n\n\n\n# Async function to kickoff the crew asynchronously\n\n\nasync\n def\n async_crew_execution\n():\n\n\n result \n=\n await\n analysis_crew.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n]})\n\n\n print\n(\n\"Crew Result:\"\n, result)\n\n\n\n\n# Run the async function\n\n\nasyncio.run(async_crew_execution())\n\n\n\n\n​\nExample: Multiple Asynchronous Crew Executions\n\n\nIn this example, we’ll show how to kickoff multiple crews asynchronously and wait for all of them to complete using \nasyncio.gather()\n:\n\n\nCode\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create tasks that require code execution\n\n\ntask_1 \n=\n Task(\n\n\n description\n=\n\"Analyze the first dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age of the participants.\"\n\n\n)\n\n\n\n\ntask_2 \n=\n Task(\n\n\n description\n=\n\"Analyze the second dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"The average age of the participants.\"\n\n\n)\n\n\n\n\n# Create two crews and add tasks\n\n\ncrew_1 \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[task_1])\n\n\ncrew_2 \n=\n Crew(\nagents\n=\n[coding_agent], \ntasks\n=\n[task_2])\n\n\n\n\n# Async function to kickoff multiple crews asynchronously and wait for all to finish\n\n\nasync\n def\n async_multiple_crews\n():\n\n\n # Create coroutines for concurrent execution\n\n\n result_1 \n=\n crew_1.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n]})\n\n\n result_2 \n=\n crew_2.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n20\n, \n22\n, \n24\n, \n28\n, \n30\n]})\n\n\n\n\n # Wait for both crews to finish\n\n\n results \n=\n await\n asyncio.gather(result_1, result_2)\n\n\n\n\n for\n i, result \nin\n enumerate\n(results, \n1\n):\n\n\n print\n(\nf\n\"Crew \n{\ni\n}\n Result:\"\n, result)\n\n\n\n\n# Run the async function\n\n\nasyncio.run(async_multiple_crews())\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nHuman Input on Execution\nKickoff Crew for Each\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nAsynchronous Crew Execution\nMethod Signature\nParameters\nReturns\nPotential Use Cases\nExample: Single Asynchronous Crew Execution\nExample: Multiple Asynchronous Crew Executions" }, { "source": "https://docs.crewai.com/en/learn/multimodal-agents", "title": "Using Multimodal Agents - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nUsing Multimodal Agents\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nUsing Multimodal Agents\nCopy page\nLearn how to enable and use multimodal capabilities in your agents for processing images and other non-text content within the CrewAI framework.\n​\nUsing Multimodal Agents\n\n\nCrewAI supports multimodal agents that can process both text and non-text content like images. This guide will show you how to enable and use multimodal capabilities in your agents.\n\n\n​\nEnabling Multimodal Capabilities\n\n\nTo create a multimodal agent, simply set the \nmultimodal\n parameter to \nTrue\n when initializing your agent:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Image Analyst\"\n,\n\n\n goal\n=\n\"Analyze and extract insights from images\"\n,\n\n\n backstory\n=\n\"An expert in visual content interpretation with years of experience in image analysis\"\n,\n\n\n multimodal\n=\nTrue\n # This enables multimodal capabilities\n\n\n)\n\n\n\n\nWhen you set \nmultimodal=True\n, the agent is automatically configured with the necessary tools for handling non-text content, including the \nAddImageTool\n.\n\n\n​\nWorking with Images\n\n\nThe multimodal agent comes pre-configured with the \nAddImageTool\n, which allows it to process images. You don’t need to manually add this tool - it’s automatically included when you enable multimodal capabilities.\n\n\nHere’s a complete example showing how to use a multimodal agent to analyze an image:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create a multimodal agent\n\n\nimage_analyst \n=\n Agent(\n\n\n role\n=\n\"Product Analyst\"\n,\n\n\n goal\n=\n\"Analyze product images and provide detailed descriptions\"\n,\n\n\n backstory\n=\n\"Expert in visual product analysis with deep knowledge of design and features\"\n,\n\n\n multimodal\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task for image analysis\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Analyze the product image at https://example.com/product.jpg and provide a detailed description\"\n,\n\n\n expected_output\n=\n\"A detailed description of the product image\"\n,\n\n\n agent\n=\nimage_analyst\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[image_analyst],\n\n\n tasks\n=\n[task]\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nAdvanced Usage with Context\n\n\nYou can provide additional context or specific questions about the image when creating tasks for multimodal agents. The task description can include specific aspects you want the agent to focus on:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create a multimodal agent for detailed analysis\n\n\nexpert_analyst \n=\n Agent(\n\n\n role\n=\n\"Visual Quality Inspector\"\n,\n\n\n goal\n=\n\"Perform detailed quality analysis of product images\"\n,\n\n\n backstory\n=\n\"Senior quality control expert with expertise in visual inspection\"\n,\n\n\n multimodal\n=\nTrue\n # AddImageTool is automatically included\n\n\n)\n\n\n\n\n# Create a task with specific analysis requirements\n\n\ninspection_task \n=\n Task(\n\n\n description\n=\n\"\"\"\n\n\n Analyze the product image at https://example.com/product.jpg with focus on:\n\n\n 1. Quality of materials\n\n\n 2. Manufacturing defects\n\n\n 3. Compliance with standards\n\n\n Provide a detailed report highlighting any issues found.\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"A detailed report highlighting any issues found\"\n,\n\n\n agent\n=\nexpert_analyst\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[expert_analyst],\n\n\n tasks\n=\n[inspection_task]\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nTool Details\n\n\nWhen working with multimodal agents, the \nAddImageTool\n is automatically configured with the following schema:\n\n\nCopy\nAsk AI\nclass\n AddImageToolSchema\n:\n\n\n image_url: \nstr\n # Required: The URL or path of the image to process\n\n\n action: Optional[\nstr\n] \n=\n None\n # Optional: Additional context or specific questions about the image\n\n\n\n\nThe multimodal agent will automatically handle the image processing through its built-in tools, allowing it to:\n\n\n\n\nAccess images via URLs or local file paths\n\n\nProcess image content with optional context or specific questions\n\n\nProvide analysis and insights based on the visual information and task requirements\n\n\n\n\n​\nBest Practices\n\n\nWhen working with multimodal agents, keep these best practices in mind:\n\n\n\n\n\n\nImage Access\n\n\n\n\nEnsure your images are accessible via URLs that the agent can reach\n\n\nFor local images, consider hosting them temporarily or using absolute file paths\n\n\nVerify that image URLs are valid and accessible before running tasks\n\n\n\n\n\n\n\n\nTask Description\n\n\n\n\nBe specific about what aspects of the image you want the agent to analyze\n\n\nInclude clear questions or requirements in the task description\n\n\nConsider using the optional \naction\n parameter for focused analysis\n\n\n\n\n\n\n\n\nResource Management\n\n\n\n\nImage processing may require more computational resources than text-only tasks\n\n\nSome language models may require base64 encoding for image data\n\n\nConsider batch processing for multiple images to optimize performance\n\n\n\n\n\n\n\n\nEnvironment Setup\n\n\n\n\nVerify that your environment has the necessary dependencies for image processing\n\n\nEnsure your language model supports multimodal capabilities\n\n\nTest with small images first to validate your setup\n\n\n\n\n\n\n\n\nError Handling\n\n\n\n\nImplement proper error handling for image loading failures\n\n\nHave fallback strategies for when image processing fails\n\n\nMonitor and log image processing operations for debugging\n\n\n\n\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nConnect to any LLM\nReplay Tasks from Latest Crew Kickoff\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nUsing Multimodal Agents\nEnabling Multimodal Capabilities\nWorking with Images\nAdvanced Usage with Context\nTool Details\nBest Practices\nLearn\nUsing Multimodal Agents\nCopy page\nLearn how to enable and use multimodal capabilities in your agents for processing images and other non-text content within the CrewAI framework.\n​\nUsing Multimodal Agents\n\n\nCrewAI supports multimodal agents that can process both text and non-text content like images. This guide will show you how to enable and use multimodal capabilities in your agents.\n\n\n​\nEnabling Multimodal Capabilities\n\n\nTo create a multimodal agent, simply set the \nmultimodal\n parameter to \nTrue\n when initializing your agent:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Image Analyst\"\n,\n\n\n goal\n=\n\"Analyze and extract insights from images\"\n,\n\n\n backstory\n=\n\"An expert in visual content interpretation with years of experience in image analysis\"\n,\n\n\n multimodal\n=\nTrue\n # This enables multimodal capabilities\n\n\n)\n\n\n\n\nWhen you set \nmultimodal=True\n, the agent is automatically configured with the necessary tools for handling non-text content, including the \nAddImageTool\n.\n\n\n​\nWorking with Images\n\n\nThe multimodal agent comes pre-configured with the \nAddImageTool\n, which allows it to process images. You don’t need to manually add this tool - it’s automatically included when you enable multimodal capabilities.\n\n\nHere’s a complete example showing how to use a multimodal agent to analyze an image:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create a multimodal agent\n\n\nimage_analyst \n=\n Agent(\n\n\n role\n=\n\"Product Analyst\"\n,\n\n\n goal\n=\n\"Analyze product images and provide detailed descriptions\"\n,\n\n\n backstory\n=\n\"Expert in visual product analysis with deep knowledge of design and features\"\n,\n\n\n multimodal\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task for image analysis\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Analyze the product image at https://example.com/product.jpg and provide a detailed description\"\n,\n\n\n expected_output\n=\n\"A detailed description of the product image\"\n,\n\n\n agent\n=\nimage_analyst\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[image_analyst],\n\n\n tasks\n=\n[task]\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nAdvanced Usage with Context\n\n\nYou can provide additional context or specific questions about the image when creating tasks for multimodal agents. The task description can include specific aspects you want the agent to focus on:\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create a multimodal agent for detailed analysis\n\n\nexpert_analyst \n=\n Agent(\n\n\n role\n=\n\"Visual Quality Inspector\"\n,\n\n\n goal\n=\n\"Perform detailed quality analysis of product images\"\n,\n\n\n backstory\n=\n\"Senior quality control expert with expertise in visual inspection\"\n,\n\n\n multimodal\n=\nTrue\n # AddImageTool is automatically included\n\n\n)\n\n\n\n\n# Create a task with specific analysis requirements\n\n\ninspection_task \n=\n Task(\n\n\n description\n=\n\"\"\"\n\n\n Analyze the product image at https://example.com/product.jpg with focus on:\n\n\n 1. Quality of materials\n\n\n 2. Manufacturing defects\n\n\n 3. Compliance with standards\n\n\n Provide a detailed report highlighting any issues found.\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"A detailed report highlighting any issues found\"\n,\n\n\n agent\n=\nexpert_analyst\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[expert_analyst],\n\n\n tasks\n=\n[inspection_task]\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n​\nTool Details\n\n\nWhen working with multimodal agents, the \nAddImageTool\n is automatically configured with the following schema:\n\n\nCopy\nAsk AI\nclass\n AddImageToolSchema\n:\n\n\n image_url: \nstr\n # Required: The URL or path of the image to process\n\n\n action: Optional[\nstr\n] \n=\n None\n # Optional: Additional context or specific questions about the image\n\n\n\n\nThe multimodal agent will automatically handle the image processing through its built-in tools, allowing it to:\n\n\n\n\nAccess images via URLs or local file paths\n\n\nProcess image content with optional context or specific questions\n\n\nProvide analysis and insights based on the visual information and task requirements\n\n\n\n\n​\nBest Practices\n\n\nWhen working with multimodal agents, keep these best practices in mind:\n\n\n\n\n\n\nImage Access\n\n\n\n\nEnsure your images are accessible via URLs that the agent can reach\n\n\nFor local images, consider hosting them temporarily or using absolute file paths\n\n\nVerify that image URLs are valid and accessible before running tasks\n\n\n\n\n\n\n\n\nTask Description\n\n\n\n\nBe specific about what aspects of the image you want the agent to analyze\n\n\nInclude clear questions or requirements in the task description\n\n\nConsider using the optional \naction\n parameter for focused analysis\n\n\n\n\n\n\n\n\nResource Management\n\n\n\n\nImage processing may require more computational resources than text-only tasks\n\n\nSome language models may require base64 encoding for image data\n\n\nConsider batch processing for multiple images to optimize performance\n\n\n\n\n\n\n\n\nEnvironment Setup\n\n\n\n\nVerify that your environment has the necessary dependencies for image processing\n\n\nEnsure your language model supports multimodal capabilities\n\n\nTest with small images first to validate your setup\n\n\n\n\n\n\n\n\nError Handling\n\n\n\n\nImplement proper error handling for image loading failures\n\n\nHave fallback strategies for when image processing fails\n\n\nMonitor and log image processing operations for debugging\n\n\n\n\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nConnect to any LLM\nReplay Tasks from Latest Crew Kickoff\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nUsing Multimodal Agents\nEnabling Multimodal Capabilities\nWorking with Images\nAdvanced Usage with Context\nTool Details\nBest Practices" }, { "source": "https://docs.crewai.com/#decision-framework", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/#why-choose-crewai%3F", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/quickstart", "title": "Quickstart - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nQuickstart\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nQuickstart\nCopy page\nBuild your first AI agent with CrewAI in under 5 minutes.\n​\nBuild your first CrewAI Agent\n\n\nLet’s create a simple crew that will help us \nresearch\n and \nreport\n on the \nlatest AI developments\n for a given topic or subject.\n\n\nBefore we proceed, make sure you have finished installing CrewAI.\nIf you haven’t installed them yet, you can do so by following the \ninstallation guide\n.\n\n\nFollow the steps below to get Crewing! 🚣‍♂️\n\n\n1\nCreate your crew\nCreate a new crew project by running the following command in your terminal.\nThis will create a new directory called \nlatest-ai-development\n with the basic structure for your crew.\nTerminal\nCopy\nAsk AI\ncrewai\n create\n crew\n latest-ai-development\n\n\n2\nNavigate to your new crew project\nTerminal\nCopy\nAsk AI\ncd\n latest-ai-development\n\n\n3\nModify your `agents.yaml` file\nYou can also modify the agents as needed to fit your use case or copy and paste as is to your project.\nAny variable interpolated in your \nagents.yaml\n and \ntasks.yaml\n files like \n{topic}\n will be replaced by the value of the variable in the \nmain.py\n file.\nagents.yaml\nCopy\nAsk AI\n# src/latest_ai_development/config/agents.yaml\n\n\nresearcher\n:\n\n\n role\n: \n>\n\n\n {topic} Senior Data Researcher\n\n\n goal\n: \n>\n\n\n Uncover cutting-edge developments in {topic}\n\n\n backstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the latest\n\n\n developments in {topic}. Known for your ability to find the most relevant\n\n\n information and present it in a clear and concise manner.\n\n\n\n\nreporting_analyst\n:\n\n\n role\n: \n>\n\n\n {topic} Reporting Analyst\n\n\n goal\n: \n>\n\n\n Create detailed reports based on {topic} data analysis and research findings\n\n\n backstory\n: \n>\n\n\n You're a meticulous analyst with a keen eye for detail. You're known for\n\n\n your ability to turn complex data into clear and concise reports, making\n\n\n it easy for others to understand and act on the information you provide.\n\n\n4\nModify your `tasks.yaml` file\ntasks.yaml\nCopy\nAsk AI\n# src/latest_ai_development/config/tasks.yaml\n\n\nresearch_task\n:\n\n\n description\n: \n>\n\n\n Conduct a thorough research about {topic}\n\n\n Make sure you find any interesting and relevant information given\n\n\n the current year is 2025.\n\n\n expected_output\n: \n>\n\n\n A list with 10 bullet points of the most relevant information about {topic}\n\n\n agent\n: \nresearcher\n\n\n\n\nreporting_task\n:\n\n\n description\n: \n>\n\n\n Review the context you got and expand each topic into a full section for a report.\n\n\n Make sure the report is detailed and contains any and all relevant information.\n\n\n expected_output\n: \n>\n\n\n A fully fledge reports with the mains topics, each with a full section of information.\n\n\n Formatted as markdown without '```'\n\n\n agent\n: \nreporting_analyst\n\n\n output_file\n: \nreport.md\n\n\n5\nModify your `crew.py` file\ncrew.py\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n reporting_analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'reporting_analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_task'\n], \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n reporting_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'reporting_task'\n], \n# type: ignore[index]\n\n\n output_file\n=\n'output/report.md'\n # This is the file that will be contain the final report.\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the LatestAiDevelopment crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents, \n# Automatically created by the @agent decorator\n\n\n tasks\n=\nself\n.tasks, \n# Automatically created by the @task decorator\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n6\n[Optional] Add before and after crew functions\ncrew.py\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task, before_kickoff, after_kickoff\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n @before_kickoff\n\n\n def\n before_kickoff_function\n(\nself\n, \ninputs\n):\n\n\n print\n(\nf\n\"Before kickoff function with inputs: \n{\ninputs\n}\n\"\n)\n\n\n return\n inputs \n# You can return the inputs or modify them as needed\n\n\n\n\n @after_kickoff\n\n\n def\n after_kickoff_function\n(\nself\n, \nresult\n):\n\n\n print\n(\nf\n\"After kickoff function with result: \n{\nresult\n}\n\"\n)\n\n\n return\n result \n# You can return the result or modify it as needed\n\n\n\n\n # ... remaining code\n\n\n7\nFeel free to pass custom inputs to your crew\nFor example, you can pass the \ntopic\n input to your crew to customize the research and reporting.\nmain.py\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\n# src/latest_ai_development/main.py\n\n\nimport\n sys\n\n\nfrom\n latest_ai_development.crew \nimport\n LatestAiDevelopmentCrew\n\n\n\n\ndef\n run\n():\n\n\n \"\"\"\n\n\n Run the crew.\n\n\n \"\"\"\n\n\n inputs \n=\n {\n\n\n 'topic'\n: \n'AI Agents'\n\n\n }\n\n\n LatestAiDevelopmentCrew().crew().kickoff(\ninputs\n=\ninputs)\n\n\n8\nSet your environment variables\nBefore running your crew, make sure you have the following keys set as environment variables in your \n.env\n file:\n\n\nA \nSerper.dev\n API key: \nSERPER_API_KEY=YOUR_KEY_HERE\n\n\nThe configuration for your choice of model, such as an API key. See the\n\nLLM setup guide\n to learn how to configure models from any provider.\n\n\n9\nLock and install the dependencies\n\n\nLock the dependencies and install them by using the CLI command:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\n\n\nIf you have additional packages that you want to install, you can do so by running:\n\n\nTerminal\nCopy\nAsk AI\nuv\n add\n <\npackage-nam\ne\n>\n\n\n\n\n\n\n10\nRun your crew\n\n\nTo run your crew, execute the following command in the root of your project:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\n\n\n11\nEnterprise Alternative: Create in Crew Studio\nFor CrewAI Enterprise users, you can create the same crew without writing code:\n\n\nLog in to your CrewAI Enterprise account (create a free account at \napp.crewai.com\n)\n\n\nOpen Crew Studio\n\n\nType what is the automation you’re trying to build\n\n\nCreate your tasks visually and connect them in sequence\n\n\nConfigure your inputs and click “Download Code” or “Deploy”\n\n\nTry CrewAI Enterprise\nStart your free account at CrewAI Enterprise\n12\nView your final report\nYou should see the output in the console and the \nreport.md\n file should be created in the root of your project with the final report.\nHere’s an example of what the report should look like:\noutput/report.md\nCopy\nAsk AI\n# Comprehensive Report on the Rise and Impact of AI Agents in 2025\n\n\n\n\n## 1. Introduction to AI Agents\n\n\nIn 2025, Artificial Intelligence (AI) agents are at the forefront of innovation across various industries. As intelligent systems that can perform tasks typically requiring human cognition, AI agents are paving the way for significant advancements in operational efficiency, decision-making, and overall productivity within sectors like Human Resources (HR) and Finance. This report aims to detail the rise of AI agents, their frameworks, applications, and potential implications on the workforce.\n\n\n\n\n## 2. Benefits of AI Agents\n\n\nAI agents bring numerous advantages that are transforming traditional work environments. Key benefits include:\n\n\n\n\n-\n **Task Automation**\n: AI agents can carry out repetitive tasks such as data entry, scheduling, and payroll processing without human intervention, greatly reducing the time and resources spent on these activities.\n\n\n-\n **Improved Efficiency**\n: By quickly processing large datasets and performing analyses that would take humans significantly longer, AI agents enhance operational efficiency. This allows teams to focus on strategic tasks that require higher-level thinking.\n\n\n-\n **Enhanced Decision-Making**\n: AI agents can analyze trends and patterns in data, provide insights, and even suggest actions, helping stakeholders make informed decisions based on factual data rather than intuition alone.\n\n\n\n\n## 3. Popular AI Agent Frameworks\n\n\nSeveral frameworks have emerged to facilitate the development of AI agents, each with its own unique features and capabilities. Some of the most popular frameworks include:\n\n\n\n\n-\n **Autogen**\n: A framework designed to streamline the development of AI agents through automation of code generation.\n\n\n-\n **Semantic Kernel**\n: Focuses on natural language processing and understanding, enabling agents to comprehend user intentions better.\n\n\n-\n **Promptflow**\n: Provides tools for developers to create conversational agents that can navigate complex interactions seamlessly.\n\n\n-\n **Langchain**\n: Specializes in leveraging various APIs to ensure agents can access and utilize external data effectively.\n\n\n-\n **CrewAI**\n: Aimed at collaborative environments, CrewAI strengthens teamwork by facilitating communication through AI-driven insights.\n\n\n-\n **MemGPT**\n: Combines memory-optimized architectures with generative capabilities, allowing for more personalized interactions with users.\n\n\n\n\nThese frameworks empower developers to build versatile and intelligent agents that can engage users, perform advanced analytics, and execute various tasks aligned with organizational goals.\n\n\n\n\n## 4. AI Agents in Human Resources\n\n\nAI agents are revolutionizing HR practices by automating and optimizing key functions:\n\n\n\n\n-\n **Recruiting**\n: AI agents can screen resumes, schedule interviews, and even conduct initial assessments, thus accelerating the hiring process while minimizing biases.\n\n\n-\n **Succession Planning**\n: AI systems analyze employee performance data and potential, helping organizations identify future leaders and plan appropriate training.\n\n\n-\n **Employee Engagement**\n: Chatbots powered by AI can facilitate feedback loops between employees and management, promoting an open culture and addressing concerns promptly.\n\n\n\n\nAs AI continues to evolve, HR departments leveraging these agents can realize substantial improvements in both efficiency and employee satisfaction.\n\n\n\n\n## 5. AI Agents in Finance\n\n\nThe finance sector is seeing extensive integration of AI agents that enhance financial practices:\n\n\n\n\n-\n **Expense Tracking**\n: Automated systems manage and monitor expenses, flagging anomalies and offering recommendations based on spending patterns.\n\n\n-\n **Risk Assessment**\n: AI models assess credit risk and uncover potential fraud by analyzing transaction data and behavioral patterns.\n\n\n-\n **Investment Decisions**\n: AI agents provide stock predictions and analytics based on historical data and current market conditions, empowering investors with informative insights.\n\n\n\n\nThe incorporation of AI agents into finance is fostering a more responsive and risk-aware financial landscape.\n\n\n\n\n## 6. Market Trends and Investments\n\n\nThe growth of AI agents has attracted significant investment, especially amidst the rising popularity of chatbots and generative AI technologies. Companies and entrepreneurs are eager to explore the potential of these systems, recognizing their ability to streamline operations and improve customer engagement.\n\n\n\n\nConversely, corporations like Microsoft are taking strides to integrate AI agents into their product offerings, with enhancements to their Copilot 365 applications. This strategic move emphasizes the importance of AI literacy in the modern workplace and indicates the stabilizing of AI agents as essential business tools.\n\n\n\n\n## 7. Future Predictions and Implications\n\n\nExperts predict that AI agents will transform essential aspects of work life. As we look toward the future, several anticipated changes include:\n\n\n\n\n-\n Enhanced integration of AI agents across all business functions, creating interconnected systems that leverage data from various departmental silos for comprehensive decision-making.\n\n\n-\n Continued advancement of AI technologies, resulting in smarter, more adaptable agents capable of learning and evolving from user interactions.\n\n\n-\n Increased regulatory scrutiny to ensure ethical use, especially concerning data privacy and employee surveillance as AI agents become more prevalent.\n\n\n\n\nTo stay competitive and harness the full potential of AI agents, organizations must remain vigilant about latest developments in AI technology and consider continuous learning and adaptation in their strategic planning.\n\n\n\n\n## 8. Conclusion\n\n\nThe emergence of AI agents is undeniably reshaping the workplace landscape in 5. With their ability to automate tasks, enhance efficiency, and improve decision-making, AI agents are critical in driving operational success. Organizations must embrace and adapt to AI developments to thrive in an increasingly digital business environment.\n\n\n\n\nCongratulations!\nYou have successfully set up your crew project and are ready to start building your own agentic workflows!\n\n\n​\nNote on Consistency in Naming\n\n\nThe names you use in your YAML files (\nagents.yaml\n and \ntasks.yaml\n) should match the method names in your Python code.\nFor example, you can reference the agent for specific tasks from \ntasks.yaml\n file.\nThis naming consistency allows CrewAI to automatically link your configurations with your code; otherwise, your task won’t recognize the reference properly.\n\n\n​\nExample References\n\n\nNote how we use the same name for the agent in the \nagents.yaml\n (\nemail_summarizer\n) file as the method name in the \ncrew.py\n (\nemail_summarizer\n) file.\n\n\nagents.yaml\nCopy\nAsk AI\nemail_summarizer\n:\n\n\n role\n: \n>\n\n\n Email Summarizer\n\n\n goal\n: \n>\n\n\n Summarize emails into a concise and clear summary\n\n\n backstory\n: \n>\n\n\n You will create a 5 bullet point summary of the report\n\n\n llm\n: \nprovider/model-id\n # Add your choice of model here\n\n\n\n\nNote how we use the same name for the task in the \ntasks.yaml\n (\nemail_summarizer_task\n) file as the method name in the \ncrew.py\n (\nemail_summarizer_task\n) file.\n\n\ntasks.yaml\nCopy\nAsk AI\nemail_summarizer_task\n:\n\n\n description\n: \n>\n\n\n Summarize the email into a 5 bullet point summary\n\n\n expected_output\n: \n>\n\n\n A 5 bullet point summary of the email\n\n\n agent\n: \nemail_summarizer\n\n\n context\n:\n\n\n - \nreporting_task\n\n\n - \nresearch_task\n\n\n\n\n​\nDeploying Your Crew\n\n\nThe easiest way to deploy your crew to production is through \nCrewAI Enterprise\n.\n\n\nWatch this video tutorial for a step-by-step demonstration of deploying your crew to \nCrewAI Enterprise\n using the CLI.\n\n\n\n\nDeploy on Enterprise\nGet started with CrewAI Enterprise and deploy your crew in a production environment with just a few clicks.\nJoin the Community\nJoin our open source community to discuss ideas, share your projects, and connect with other CrewAI developers.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nEvaluating Use Cases for CrewAI\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nBuild your first CrewAI Agent\nNote on Consistency in Naming\nExample References\nDeploying Your Crew\nGet Started\nQuickstart\nCopy page\nBuild your first AI agent with CrewAI in under 5 minutes.\n​\nBuild your first CrewAI Agent\n\n\nLet’s create a simple crew that will help us \nresearch\n and \nreport\n on the \nlatest AI developments\n for a given topic or subject.\n\n\nBefore we proceed, make sure you have finished installing CrewAI.\nIf you haven’t installed them yet, you can do so by following the \ninstallation guide\n.\n\n\nFollow the steps below to get Crewing! 🚣‍♂️\n\n\n1\nCreate your crew\nCreate a new crew project by running the following command in your terminal.\nThis will create a new directory called \nlatest-ai-development\n with the basic structure for your crew.\nTerminal\nCopy\nAsk AI\ncrewai\n create\n crew\n latest-ai-development\n\n\n2\nNavigate to your new crew project\nTerminal\nCopy\nAsk AI\ncd\n latest-ai-development\n\n\n3\nModify your `agents.yaml` file\nYou can also modify the agents as needed to fit your use case or copy and paste as is to your project.\nAny variable interpolated in your \nagents.yaml\n and \ntasks.yaml\n files like \n{topic}\n will be replaced by the value of the variable in the \nmain.py\n file.\nagents.yaml\nCopy\nAsk AI\n# src/latest_ai_development/config/agents.yaml\n\n\nresearcher\n:\n\n\n role\n: \n>\n\n\n {topic} Senior Data Researcher\n\n\n goal\n: \n>\n\n\n Uncover cutting-edge developments in {topic}\n\n\n backstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the latest\n\n\n developments in {topic}. Known for your ability to find the most relevant\n\n\n information and present it in a clear and concise manner.\n\n\n\n\nreporting_analyst\n:\n\n\n role\n: \n>\n\n\n {topic} Reporting Analyst\n\n\n goal\n: \n>\n\n\n Create detailed reports based on {topic} data analysis and research findings\n\n\n backstory\n: \n>\n\n\n You're a meticulous analyst with a keen eye for detail. You're known for\n\n\n your ability to turn complex data into clear and concise reports, making\n\n\n it easy for others to understand and act on the information you provide.\n\n\n4\nModify your `tasks.yaml` file\ntasks.yaml\nCopy\nAsk AI\n# src/latest_ai_development/config/tasks.yaml\n\n\nresearch_task\n:\n\n\n description\n: \n>\n\n\n Conduct a thorough research about {topic}\n\n\n Make sure you find any interesting and relevant information given\n\n\n the current year is 2025.\n\n\n expected_output\n: \n>\n\n\n A list with 10 bullet points of the most relevant information about {topic}\n\n\n agent\n: \nresearcher\n\n\n\n\nreporting_task\n:\n\n\n description\n: \n>\n\n\n Review the context you got and expand each topic into a full section for a report.\n\n\n Make sure the report is detailed and contains any and all relevant information.\n\n\n expected_output\n: \n>\n\n\n A fully fledge reports with the mains topics, each with a full section of information.\n\n\n Formatted as markdown without '```'\n\n\n agent\n: \nreporting_analyst\n\n\n output_file\n: \nreport.md\n\n\n5\nModify your `crew.py` file\ncrew.py\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n reporting_analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'reporting_analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_task'\n], \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n reporting_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'reporting_task'\n], \n# type: ignore[index]\n\n\n output_file\n=\n'output/report.md'\n # This is the file that will be contain the final report.\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the LatestAiDevelopment crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents, \n# Automatically created by the @agent decorator\n\n\n tasks\n=\nself\n.tasks, \n# Automatically created by the @task decorator\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n6\n[Optional] Add before and after crew functions\ncrew.py\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task, before_kickoff, after_kickoff\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n @before_kickoff\n\n\n def\n before_kickoff_function\n(\nself\n, \ninputs\n):\n\n\n print\n(\nf\n\"Before kickoff function with inputs: \n{\ninputs\n}\n\"\n)\n\n\n return\n inputs \n# You can return the inputs or modify them as needed\n\n\n\n\n @after_kickoff\n\n\n def\n after_kickoff_function\n(\nself\n, \nresult\n):\n\n\n print\n(\nf\n\"After kickoff function with result: \n{\nresult\n}\n\"\n)\n\n\n return\n result \n# You can return the result or modify it as needed\n\n\n\n\n # ... remaining code\n\n\n7\nFeel free to pass custom inputs to your crew\nFor example, you can pass the \ntopic\n input to your crew to customize the research and reporting.\nmain.py\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\n# src/latest_ai_development/main.py\n\n\nimport\n sys\n\n\nfrom\n latest_ai_development.crew \nimport\n LatestAiDevelopmentCrew\n\n\n\n\ndef\n run\n():\n\n\n \"\"\"\n\n\n Run the crew.\n\n\n \"\"\"\n\n\n inputs \n=\n {\n\n\n 'topic'\n: \n'AI Agents'\n\n\n }\n\n\n LatestAiDevelopmentCrew().crew().kickoff(\ninputs\n=\ninputs)\n\n\n8\nSet your environment variables\nBefore running your crew, make sure you have the following keys set as environment variables in your \n.env\n file:\n\n\nA \nSerper.dev\n API key: \nSERPER_API_KEY=YOUR_KEY_HERE\n\n\nThe configuration for your choice of model, such as an API key. See the\n\nLLM setup guide\n to learn how to configure models from any provider.\n\n\n9\nLock and install the dependencies\n\n\nLock the dependencies and install them by using the CLI command:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\n\n\nIf you have additional packages that you want to install, you can do so by running:\n\n\nTerminal\nCopy\nAsk AI\nuv\n add\n <\npackage-nam\ne\n>\n\n\n\n\n\n\n10\nRun your crew\n\n\nTo run your crew, execute the following command in the root of your project:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\n\n\n11\nEnterprise Alternative: Create in Crew Studio\nFor CrewAI Enterprise users, you can create the same crew without writing code:\n\n\nLog in to your CrewAI Enterprise account (create a free account at \napp.crewai.com\n)\n\n\nOpen Crew Studio\n\n\nType what is the automation you’re trying to build\n\n\nCreate your tasks visually and connect them in sequence\n\n\nConfigure your inputs and click “Download Code” or “Deploy”\n\n\nTry CrewAI Enterprise\nStart your free account at CrewAI Enterprise\n12\nView your final report\nYou should see the output in the console and the \nreport.md\n file should be created in the root of your project with the final report.\nHere’s an example of what the report should look like:\noutput/report.md\nCopy\nAsk AI\n# Comprehensive Report on the Rise and Impact of AI Agents in 2025\n\n\n\n\n## 1. Introduction to AI Agents\n\n\nIn 2025, Artificial Intelligence (AI) agents are at the forefront of innovation across various industries. As intelligent systems that can perform tasks typically requiring human cognition, AI agents are paving the way for significant advancements in operational efficiency, decision-making, and overall productivity within sectors like Human Resources (HR) and Finance. This report aims to detail the rise of AI agents, their frameworks, applications, and potential implications on the workforce.\n\n\n\n\n## 2. Benefits of AI Agents\n\n\nAI agents bring numerous advantages that are transforming traditional work environments. Key benefits include:\n\n\n\n\n-\n **Task Automation**\n: AI agents can carry out repetitive tasks such as data entry, scheduling, and payroll processing without human intervention, greatly reducing the time and resources spent on these activities.\n\n\n-\n **Improved Efficiency**\n: By quickly processing large datasets and performing analyses that would take humans significantly longer, AI agents enhance operational efficiency. This allows teams to focus on strategic tasks that require higher-level thinking.\n\n\n-\n **Enhanced Decision-Making**\n: AI agents can analyze trends and patterns in data, provide insights, and even suggest actions, helping stakeholders make informed decisions based on factual data rather than intuition alone.\n\n\n\n\n## 3. Popular AI Agent Frameworks\n\n\nSeveral frameworks have emerged to facilitate the development of AI agents, each with its own unique features and capabilities. Some of the most popular frameworks include:\n\n\n\n\n-\n **Autogen**\n: A framework designed to streamline the development of AI agents through automation of code generation.\n\n\n-\n **Semantic Kernel**\n: Focuses on natural language processing and understanding, enabling agents to comprehend user intentions better.\n\n\n-\n **Promptflow**\n: Provides tools for developers to create conversational agents that can navigate complex interactions seamlessly.\n\n\n-\n **Langchain**\n: Specializes in leveraging various APIs to ensure agents can access and utilize external data effectively.\n\n\n-\n **CrewAI**\n: Aimed at collaborative environments, CrewAI strengthens teamwork by facilitating communication through AI-driven insights.\n\n\n-\n **MemGPT**\n: Combines memory-optimized architectures with generative capabilities, allowing for more personalized interactions with users.\n\n\n\n\nThese frameworks empower developers to build versatile and intelligent agents that can engage users, perform advanced analytics, and execute various tasks aligned with organizational goals.\n\n\n\n\n## 4. AI Agents in Human Resources\n\n\nAI agents are revolutionizing HR practices by automating and optimizing key functions:\n\n\n\n\n-\n **Recruiting**\n: AI agents can screen resumes, schedule interviews, and even conduct initial assessments, thus accelerating the hiring process while minimizing biases.\n\n\n-\n **Succession Planning**\n: AI systems analyze employee performance data and potential, helping organizations identify future leaders and plan appropriate training.\n\n\n-\n **Employee Engagement**\n: Chatbots powered by AI can facilitate feedback loops between employees and management, promoting an open culture and addressing concerns promptly.\n\n\n\n\nAs AI continues to evolve, HR departments leveraging these agents can realize substantial improvements in both efficiency and employee satisfaction.\n\n\n\n\n## 5. AI Agents in Finance\n\n\nThe finance sector is seeing extensive integration of AI agents that enhance financial practices:\n\n\n\n\n-\n **Expense Tracking**\n: Automated systems manage and monitor expenses, flagging anomalies and offering recommendations based on spending patterns.\n\n\n-\n **Risk Assessment**\n: AI models assess credit risk and uncover potential fraud by analyzing transaction data and behavioral patterns.\n\n\n-\n **Investment Decisions**\n: AI agents provide stock predictions and analytics based on historical data and current market conditions, empowering investors with informative insights.\n\n\n\n\nThe incorporation of AI agents into finance is fostering a more responsive and risk-aware financial landscape.\n\n\n\n\n## 6. Market Trends and Investments\n\n\nThe growth of AI agents has attracted significant investment, especially amidst the rising popularity of chatbots and generative AI technologies. Companies and entrepreneurs are eager to explore the potential of these systems, recognizing their ability to streamline operations and improve customer engagement.\n\n\n\n\nConversely, corporations like Microsoft are taking strides to integrate AI agents into their product offerings, with enhancements to their Copilot 365 applications. This strategic move emphasizes the importance of AI literacy in the modern workplace and indicates the stabilizing of AI agents as essential business tools.\n\n\n\n\n## 7. Future Predictions and Implications\n\n\nExperts predict that AI agents will transform essential aspects of work life. As we look toward the future, several anticipated changes include:\n\n\n\n\n-\n Enhanced integration of AI agents across all business functions, creating interconnected systems that leverage data from various departmental silos for comprehensive decision-making.\n\n\n-\n Continued advancement of AI technologies, resulting in smarter, more adaptable agents capable of learning and evolving from user interactions.\n\n\n-\n Increased regulatory scrutiny to ensure ethical use, especially concerning data privacy and employee surveillance as AI agents become more prevalent.\n\n\n\n\nTo stay competitive and harness the full potential of AI agents, organizations must remain vigilant about latest developments in AI technology and consider continuous learning and adaptation in their strategic planning.\n\n\n\n\n## 8. Conclusion\n\n\nThe emergence of AI agents is undeniably reshaping the workplace landscape in 5. With their ability to automate tasks, enhance efficiency, and improve decision-making, AI agents are critical in driving operational success. Organizations must embrace and adapt to AI developments to thrive in an increasingly digital business environment.\n\n\n\n\nCongratulations!\nYou have successfully set up your crew project and are ready to start building your own agentic workflows!\n\n\n​\nNote on Consistency in Naming\n\n\nThe names you use in your YAML files (\nagents.yaml\n and \ntasks.yaml\n) should match the method names in your Python code.\nFor example, you can reference the agent for specific tasks from \ntasks.yaml\n file.\nThis naming consistency allows CrewAI to automatically link your configurations with your code; otherwise, your task won’t recognize the reference properly.\n\n\n​\nExample References\n\n\nNote how we use the same name for the agent in the \nagents.yaml\n (\nemail_summarizer\n) file as the method name in the \ncrew.py\n (\nemail_summarizer\n) file.\n\n\nagents.yaml\nCopy\nAsk AI\nemail_summarizer\n:\n\n\n role\n: \n>\n\n\n Email Summarizer\n\n\n goal\n: \n>\n\n\n Summarize emails into a concise and clear summary\n\n\n backstory\n: \n>\n\n\n You will create a 5 bullet point summary of the report\n\n\n llm\n: \nprovider/model-id\n # Add your choice of model here\n\n\n\n\nNote how we use the same name for the task in the \ntasks.yaml\n (\nemail_summarizer_task\n) file as the method name in the \ncrew.py\n (\nemail_summarizer_task\n) file.\n\n\ntasks.yaml\nCopy\nAsk AI\nemail_summarizer_task\n:\n\n\n description\n: \n>\n\n\n Summarize the email into a 5 bullet point summary\n\n\n expected_output\n: \n>\n\n\n A 5 bullet point summary of the email\n\n\n agent\n: \nemail_summarizer\n\n\n context\n:\n\n\n - \nreporting_task\n\n\n - \nresearch_task\n\n\n\n\n​\nDeploying Your Crew\n\n\nThe easiest way to deploy your crew to production is through \nCrewAI Enterprise\n.\n\n\nWatch this video tutorial for a step-by-step demonstration of deploying your crew to \nCrewAI Enterprise\n using the CLI.\n\n\n\n\nDeploy on Enterprise\nGet started with CrewAI Enterprise and deploy your crew in a production environment with just a few clicks.\nJoin the Community\nJoin our open source community to discuss ideas, share your projects, and connect with other CrewAI developers.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nEvaluating Use Cases for CrewAI\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nBuild your first CrewAI Agent\nNote on Consistency in Naming\nExample References\nDeploying Your Crew" }, { "source": "https://docs.crewai.com/#ready-to-start-building%3F", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/learn/dalle-image-generation", "title": "Image Generation with DALL-E - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nImage Generation with DALL-E\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nImage Generation with DALL-E\nCopy page\nLearn how to use DALL-E for AI-powered image generation in your CrewAI projects\nCrewAI supports integration with OpenAI’s DALL-E, allowing your AI agents to generate images as part of their tasks. This guide will walk you through how to set up and use the DALL-E tool in your CrewAI projects.\n\n\n​\nPrerequisites\n\n\n\n\ncrewAI installed (latest version)\n\n\nOpenAI API key with access to DALL-E\n\n\n\n\n​\nSetting Up the DALL-E Tool\n\n\n1\nImport the DALL-E tool\nCopy\nAsk AI\nfrom\n crewai_tools \nimport\n DallETool\n\n\n2\nAdd the DALL-E tool to your agent configuration\nCopy\nAsk AI\n@agent\n\n\ndef\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n],\n\n\n tools\n=\n[SerperDevTool(), DallETool()], \n# Add DallETool to the list of tools\n\n\n allow_delegation\n=\nFalse\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n​\nUsing the DALL-E Tool\n\n\nOnce you’ve added the DALL-E tool to your agent, it can generate images based on text prompts. The tool will return a URL to the generated image, which can be used in the agent’s output or passed to other agents for further processing.\n\n\n​\nExample Agent Configuration\n\n\nCopy\nAsk AI\nrole\n: \n>\n\n\n LinkedIn Profile Senior Data Researcher\n\n\ngoal\n: \n>\n\n\n Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}\n\n\n Generate a Dall-e image based on domain {domain}\n\n\nbackstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.\n\n\n Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting\n\n\n professional information clearly and concisely.\n\n\n\n\n​\nExpected Output\n\n\nThe agent with the DALL-E tool will be able to generate the image and provide a URL in its response. You can then download the image.\n\n\n\n\n​\nBest Practices\n\n\n\n\nBe specific in your image generation prompts\n to get the best results.\n\n\nConsider generation time\n - Image generation can take some time, so factor this into your task planning.\n\n\nFollow usage policies\n - Always comply with OpenAI’s usage policies when generating images.\n\n\n\n\n​\nTroubleshooting\n\n\n\n\nCheck API access\n - Ensure your OpenAI API key has access to DALL-E.\n\n\nVersion compatibility\n - Check that you’re using the latest version of crewAI and crewai-tools.\n\n\nTool configuration\n - Verify that the DALL-E tool is correctly added to the agent’s tool list.\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCustomize Agents\nForce Tool Output as Result\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nPrerequisites\nSetting Up the DALL-E Tool\nUsing the DALL-E Tool\nExample Agent Configuration\nExpected Output\nBest Practices\nTroubleshooting\nLearn\nImage Generation with DALL-E\nCopy page\nLearn how to use DALL-E for AI-powered image generation in your CrewAI projects\nCrewAI supports integration with OpenAI’s DALL-E, allowing your AI agents to generate images as part of their tasks. This guide will walk you through how to set up and use the DALL-E tool in your CrewAI projects.\n\n\n​\nPrerequisites\n\n\n\n\ncrewAI installed (latest version)\n\n\nOpenAI API key with access to DALL-E\n\n\n\n\n​\nSetting Up the DALL-E Tool\n\n\n1\nImport the DALL-E tool\nCopy\nAsk AI\nfrom\n crewai_tools \nimport\n DallETool\n\n\n2\nAdd the DALL-E tool to your agent configuration\nCopy\nAsk AI\n@agent\n\n\ndef\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n],\n\n\n tools\n=\n[SerperDevTool(), DallETool()], \n# Add DallETool to the list of tools\n\n\n allow_delegation\n=\nFalse\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n​\nUsing the DALL-E Tool\n\n\nOnce you’ve added the DALL-E tool to your agent, it can generate images based on text prompts. The tool will return a URL to the generated image, which can be used in the agent’s output or passed to other agents for further processing.\n\n\n​\nExample Agent Configuration\n\n\nCopy\nAsk AI\nrole\n: \n>\n\n\n LinkedIn Profile Senior Data Researcher\n\n\ngoal\n: \n>\n\n\n Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}\n\n\n Generate a Dall-e image based on domain {domain}\n\n\nbackstory\n: \n>\n\n\n You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.\n\n\n Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting\n\n\n professional information clearly and concisely.\n\n\n\n\n​\nExpected Output\n\n\nThe agent with the DALL-E tool will be able to generate the image and provide a URL in its response. You can then download the image.\n\n\n\n\n​\nBest Practices\n\n\n\n\nBe specific in your image generation prompts\n to get the best results.\n\n\nConsider generation time\n - Image generation can take some time, so factor this into your task planning.\n\n\nFollow usage policies\n - Always comply with OpenAI’s usage policies when generating images.\n\n\n\n\n​\nTroubleshooting\n\n\n\n\nCheck API access\n - Ensure your OpenAI API key has access to DALL-E.\n\n\nVersion compatibility\n - Check that you’re using the latest version of crewAI and crewai-tools.\n\n\nTool configuration\n - Verify that the DALL-E tool is correctly added to the agent’s tool list.\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCustomize Agents\nForce Tool Output as Result\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nPrerequisites\nSetting Up the DALL-E Tool\nUsing the DALL-E Tool\nExample Agent Configuration\nExpected Output\nBest Practices\nTroubleshooting" }, { "source": "https://docs.crewai.com/en/observability/openlit", "title": "OpenLIT Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nOpenLIT Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nOpenLIT Integration\nCopy page\nQuickly start monitoring your Agents in just a single line of code with OpenTelemetry.\n​\nOpenLIT Overview\n\n\nOpenLIT\n is an open-source tool that makes it simple to monitor the performance of AI agents, LLMs, VectorDBs, and GPUs with just \none\n line of code.\n\n\nIt provides OpenTelemetry-native tracing and metrics to track important parameters like cost, latency, interactions and task sequences.\nThis setup enables you to track hyperparameters and monitor for performance issues, helping you find ways to enhance and fine-tune your agents over time.\n\n\nOpenLIT Dashboard\n\n\n​\nFeatures\n\n\n\n\nAnalytics Dashboard\n: Monitor your Agents health and performance with detailed dashboards that track metrics, costs, and user interactions.\n\n\nOpenTelemetry-native Observability SDK\n: Vendor-neutral SDKs to send traces and metrics to your existing observability tools like Grafana, DataDog and more.\n\n\nCost Tracking for Custom and Fine-Tuned Models\n: Tailor cost estimations for specific models using custom pricing files for precise budgeting.\n\n\nExceptions Monitoring Dashboard\n: Quickly spot and resolve issues by tracking common exceptions and errors with a monitoring dashboard.\n\n\nCompliance and Security\n: Detect potential threats such as profanity and PII leaks.\n\n\nPrompt Injection Detection\n: Identify potential code injection and secret leaks.\n\n\nAPI Keys and Secrets Management\n: Securely handle your LLM API keys and secrets centrally, avoiding insecure practices.\n\n\nPrompt Management\n: Manage and version Agent prompts using PromptHub for consistent and easy access across Agents.\n\n\nModel Playground\n Test and compare different models for your CrewAI agents before deployment.\n\n\n\n\n​\nSetup Instructions\n\n\n1\nDeploy OpenLIT\n1\nGit Clone OpenLIT Repository\nCopy\nAsk AI\ngit\n clone\n git@github.com:openlit/openlit.git\n\n\n2\nStart Docker Compose\nFrom the root directory of the \nOpenLIT Repo\n, Run the below command:\nCopy\nAsk AI\ndocker\n compose\n up\n -d\n\n\n2\nInstall OpenLIT SDK\nCopy\nAsk AI\npip\n install\n openlit\n\n\n3\nInitialize OpenLIT in Your Application\nAdd the following two lines to your application code:\nSetup using function arguments\nSetup using Environment Variables\nCopy\nAsk AI\nimport\n openlit\n\n\nopenlit.init(\notlp_endpoint\n=\n\"http://127.0.0.1:4318\"\n)\n\n\nExample Usage for monitoring a CrewAI Agent:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nimport\n openlit\n\n\n\n\nopenlit.init(\ndisable_metrics\n=\nTrue\n)\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Conduct thorough research and analysis on AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n\n\n# Define your task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.\"\n,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Define the manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n# Instantiate your crew with a custom manager\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher],\n\n\n tasks\n=\n[task],\n\n\n manager_agent\n=\nmanager,\n\n\n process\n=\nProcess.hierarchical,\n\n\n)\n\n\n\n\n# Start the crew's work\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\nCopy\nAsk AI\nimport\n openlit\n\n\nopenlit.init(\notlp_endpoint\n=\n\"http://127.0.0.1:4318\"\n)\n\n\nExample Usage for monitoring a CrewAI Agent:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nimport\n openlit\n\n\n\n\nopenlit.init(\ndisable_metrics\n=\nTrue\n)\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Conduct thorough research and analysis on AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n\n\n# Define your task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.\"\n,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Define the manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n# Instantiate your crew with a custom manager\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher],\n\n\n tasks\n=\n[task],\n\n\n manager_agent\n=\nmanager,\n\n\n process\n=\nProcess.hierarchical,\n\n\n)\n\n\n\n\n# Start the crew's work\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\nAdd the following two lines to your application code:\nCopy\nAsk AI\nimport\n openlit\n\n\n\n\nopenlit.init()\n\n\nRun the following command to configure the OTEL export endpoint:\nCopy\nAsk AI\nexport\n OTEL_EXPORTER_OTLP_ENDPOINT\n = \n\"http://127.0.0.1:4318\"\n\n\nExample Usage for monitoring a CrewAI Async Agent:\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\nimport\n openlit\n\n\n\n\nopenlit.init(\notlp_endpoint\n=\n\"http://127.0.0.1:4318\"\n)\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n,\n\n\n llm\n=\n\"command-r\"\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task]\n\n\n)\n\n\n\n\n# Async function to kickoff the crew asynchronously\n\n\nasync\n def\n async_crew_execution\n():\n\n\n result \n=\n await\n analysis_crew.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n]})\n\n\n print\n(\n\"Crew Result:\"\n, result)\n\n\n\n\n# Run the async function\n\n\nasyncio.run(async_crew_execution())\n\n\nRefer to OpenLIT \nPython SDK repository\n for more advanced configurations and use cases.\n4\nVisualize and Analyze\nWith the Agent Observability data now being collected and sent to OpenLIT, the next step is to visualize and analyze this data to get insights into your Agent’s performance, behavior, and identify areas of improvement.\nJust head over to OpenLIT at \n127.0.0.1:3000\n on your browser to start exploring. You can login using the default credentials\n\n\nEmail\n: \nuser@openlit.io\n\n\nPassword\n: \nopenlituser\n\n\nOpenLIT Dashboard\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMLflow Integration\nOpik Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOpenLIT Overview\nFeatures\nSetup Instructions\nObservability\nOpenLIT Integration\nCopy page\nQuickly start monitoring your Agents in just a single line of code with OpenTelemetry.\n​\nOpenLIT Overview\n\n\nOpenLIT\n is an open-source tool that makes it simple to monitor the performance of AI agents, LLMs, VectorDBs, and GPUs with just \none\n line of code.\n\n\nIt provides OpenTelemetry-native tracing and metrics to track important parameters like cost, latency, interactions and task sequences.\nThis setup enables you to track hyperparameters and monitor for performance issues, helping you find ways to enhance and fine-tune your agents over time.\n\n\nOpenLIT Dashboard\n\n\n​\nFeatures\n\n\n\n\nAnalytics Dashboard\n: Monitor your Agents health and performance with detailed dashboards that track metrics, costs, and user interactions.\n\n\nOpenTelemetry-native Observability SDK\n: Vendor-neutral SDKs to send traces and metrics to your existing observability tools like Grafana, DataDog and more.\n\n\nCost Tracking for Custom and Fine-Tuned Models\n: Tailor cost estimations for specific models using custom pricing files for precise budgeting.\n\n\nExceptions Monitoring Dashboard\n: Quickly spot and resolve issues by tracking common exceptions and errors with a monitoring dashboard.\n\n\nCompliance and Security\n: Detect potential threats such as profanity and PII leaks.\n\n\nPrompt Injection Detection\n: Identify potential code injection and secret leaks.\n\n\nAPI Keys and Secrets Management\n: Securely handle your LLM API keys and secrets centrally, avoiding insecure practices.\n\n\nPrompt Management\n: Manage and version Agent prompts using PromptHub for consistent and easy access across Agents.\n\n\nModel Playground\n Test and compare different models for your CrewAI agents before deployment.\n\n\n\n\n​\nSetup Instructions\n\n\n1\nDeploy OpenLIT\n1\nGit Clone OpenLIT Repository\nCopy\nAsk AI\ngit\n clone\n git@github.com:openlit/openlit.git\n\n\n2\nStart Docker Compose\nFrom the root directory of the \nOpenLIT Repo\n, Run the below command:\nCopy\nAsk AI\ndocker\n compose\n up\n -d\n\n\n2\nInstall OpenLIT SDK\nCopy\nAsk AI\npip\n install\n openlit\n\n\n3\nInitialize OpenLIT in Your Application\nAdd the following two lines to your application code:\nSetup using function arguments\nSetup using Environment Variables\nCopy\nAsk AI\nimport\n openlit\n\n\nopenlit.init(\notlp_endpoint\n=\n\"http://127.0.0.1:4318\"\n)\n\n\nExample Usage for monitoring a CrewAI Agent:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nimport\n openlit\n\n\n\n\nopenlit.init(\ndisable_metrics\n=\nTrue\n)\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Conduct thorough research and analysis on AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n\n\n# Define your task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.\"\n,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Define the manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n# Instantiate your crew with a custom manager\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher],\n\n\n tasks\n=\n[task],\n\n\n manager_agent\n=\nmanager,\n\n\n process\n=\nProcess.hierarchical,\n\n\n)\n\n\n\n\n# Start the crew's work\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\nCopy\nAsk AI\nimport\n openlit\n\n\nopenlit.init(\notlp_endpoint\n=\n\"http://127.0.0.1:4318\"\n)\n\n\nExample Usage for monitoring a CrewAI Agent:\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nimport\n openlit\n\n\n\n\nopenlit.init(\ndisable_metrics\n=\nTrue\n)\n\n\n# Define your agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Conduct thorough research and analysis on AI and AI agents\"\n,\n\n\n backstory\n=\n\"You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.\"\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n\n\n# Define your task\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.\"\n,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Define the manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n llm\n=\n'command-r'\n\n\n)\n\n\n\n\n# Instantiate your crew with a custom manager\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher],\n\n\n tasks\n=\n[task],\n\n\n manager_agent\n=\nmanager,\n\n\n process\n=\nProcess.hierarchical,\n\n\n)\n\n\n\n\n# Start the crew's work\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\nAdd the following two lines to your application code:\nCopy\nAsk AI\nimport\n openlit\n\n\n\n\nopenlit.init()\n\n\nRun the following command to configure the OTEL export endpoint:\nCopy\nAsk AI\nexport\n OTEL_EXPORTER_OTLP_ENDPOINT\n = \n\"http://127.0.0.1:4318\"\n\n\nExample Usage for monitoring a CrewAI Async Agent:\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n crewai \nimport\n Crew, Agent, Task\n\n\nimport\n openlit\n\n\n\n\nopenlit.init(\notlp_endpoint\n=\n\"http://127.0.0.1:4318\"\n)\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n,\n\n\n llm\n=\n\"command-r\"\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants. Ages: \n{ages}\n\"\n,\n\n\n agent\n=\ncoding_agent,\n\n\n expected_output\n=\n\"5 bullet points, each with a paragraph and accompanying notes.\"\n,\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task]\n\n\n)\n\n\n\n\n# Async function to kickoff the crew asynchronously\n\n\nasync\n def\n async_crew_execution\n():\n\n\n result \n=\n await\n analysis_crew.kickoff_async(\ninputs\n=\n{\n\"ages\"\n: [\n25\n, \n30\n, \n35\n, \n40\n, \n45\n]})\n\n\n print\n(\n\"Crew Result:\"\n, result)\n\n\n\n\n# Run the async function\n\n\nasyncio.run(async_crew_execution())\n\n\nRefer to OpenLIT \nPython SDK repository\n for more advanced configurations and use cases.\n4\nVisualize and Analyze\nWith the Agent Observability data now being collected and sent to OpenLIT, the next step is to visualize and analyze this data to get insights into your Agent’s performance, behavior, and identify areas of improvement.\nJust head over to OpenLIT at \n127.0.0.1:3000\n on your browser to start exploring. You can login using the default credentials\n\n\nEmail\n: \nuser@openlit.io\n\n\nPassword\n: \nopenlituser\n\n\nOpenLIT Dashboard\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nMLflow Integration\nOpik Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOpenLIT Overview\nFeatures\nSetup Instructions" }, { "source": "https://docs.crewai.com/en/observability/langfuse", "title": "Langfuse Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nLangfuse Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nLangfuse Integration\nCopy page\nLearn how to integrate Langfuse with CrewAI via OpenTelemetry using OpenLit\n​\nIntegrate Langfuse with CrewAI\n\n\nThis notebook demonstrates how to integrate \nLangfuse\n with \nCrewAI\n using OpenTelemetry via the \nOpenLit\n SDK. By the end of this notebook, you will be able to trace your CrewAI applications with Langfuse for improved observability and debugging.\n\n\n\n\nWhat is Langfuse?\n \nLangfuse\n is an open-source LLM engineering platform. It provides tracing and monitoring capabilities for LLM applications, helping developers debug, analyze, and optimize their AI systems. Langfuse integrates with various tools and frameworks via native integrations, OpenTelemetry, and APIs/SDKs.\n\n\n\n\n\n\n​\nGet Started\n\n\nWe’ll walk through a simple example of using CrewAI and integrating it with Langfuse via OpenTelemetry using OpenLit.\n\n\n​\nStep 1: Install Dependencies\n\n\nCopy\nAsk AI\n%\npip install langfuse openlit crewai crewai_tools\n\n\n\n\n​\nStep 2: Set Up Environment Variables\n\n\nSet your Langfuse API keys and configure OpenTelemetry export settings to send traces to Langfuse. Please refer to the \nLangfuse OpenTelemetry Docs\n for more information on the Langfuse OpenTelemetry endpoint \n/api/public/otel\n and authentication.\n\n\nCopy\nAsk AI\nimport\n os\n\n\n \n\n\n# Get keys for your project from the project settings page: https://cloud.langfuse.com\n\n\nos.environ[\n\"LANGFUSE_PUBLIC_KEY\"\n] \n=\n \"pk-lf-...\"\n \n\n\nos.environ[\n\"LANGFUSE_SECRET_KEY\"\n] \n=\n \"sk-lf-...\"\n\n\nos.environ[\n\"LANGFUSE_HOST\"\n] \n=\n \"https://cloud.langfuse.com\"\n # 🇪🇺 EU region\n\n\n# os.environ[\"LANGFUSE_HOST\"] = \"https://us.cloud.langfuse.com\" # 🇺🇸 US region\n\n\n \n\n\n \n\n\n# Your OpenAI key\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"sk-proj-...\"\n\n\n\n\nWith the environment variables set, we can now initialize the Langfuse client. get_client() initializes the Langfuse client using the credentials provided in the environment variables.\n\n\nCopy\nAsk AI\nfrom\n langfuse \nimport\n get_client\n\n\n \n\n\nlangfuse \n=\n get_client()\n\n\n \n\n\n# Verify connection\n\n\nif\n langfuse.auth_check():\n\n\n print\n(\n\"Langfuse client is authenticated and ready!\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"Authentication failed. Please check your credentials and host.\"\n)\n\n\n\n\n​\nStep 3: Initialize OpenLit\n\n\nInitialize the OpenLit OpenTelemetry instrumentation SDK to start capturing OpenTelemetry traces.\n\n\nCopy\nAsk AI\nimport\n openlit\n\n\n\n\nopenlit.init()\n\n\n\n\n​\nStep 4: Create a Simple CrewAI Application\n\n\nWe’ll create a simple CrewAI application where multiple agents collaborate to answer a user’s question.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\nfrom\n crewai_tools \nimport\n (\n\n\n WebsiteSearchTool\n\n\n)\n\n\n\n\nweb_rag_tool \n=\n WebsiteSearchTool()\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Writer\"\n,\n\n\n goal\n=\n\"You make math engaging and understandable for young children through poetry\"\n,\n\n\n backstory\n=\n\"You're an expert in writing haikus but you know nothing of math.\"\n,\n\n\n tools\n=\n[web_rag_tool], \n\n\n )\n\n\n\n\ntask \n=\n Task(\ndescription\n=\n(\n\"What is \n{multiplication}\n?\"\n),\n\n\n expected_output\n=\n(\n\"Compose a haiku that includes the answer.\"\n),\n\n\n agent\n=\nwriter)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[writer],\n\n\n tasks\n=\n[task],\n\n\n share_crew\n=\nFalse\n\n\n)\n\n\n\n\n​\nStep 5: See Traces in Langfuse\n\n\nAfter running the agent, you can view the traces generated by your CrewAI application in \nLangfuse\n. You should see detailed steps of the LLM interactions, which can help you debug and optimize your AI agent.\n\n\n\n\nPublic example trace in Langfuse\n\n\n​\nReferences\n\n\n\n\nLangfuse OpenTelemetry Docs\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nArize Phoenix\nLangtrace Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntegrate Langfuse with CrewAI\nGet Started\nStep 1: Install Dependencies\nStep 2: Set Up Environment Variables\nStep 3: Initialize OpenLit\nStep 4: Create a Simple CrewAI Application\nStep 5: See Traces in Langfuse\nReferences\nObservability\nLangfuse Integration\nCopy page\nLearn how to integrate Langfuse with CrewAI via OpenTelemetry using OpenLit\n​\nIntegrate Langfuse with CrewAI\n\n\nThis notebook demonstrates how to integrate \nLangfuse\n with \nCrewAI\n using OpenTelemetry via the \nOpenLit\n SDK. By the end of this notebook, you will be able to trace your CrewAI applications with Langfuse for improved observability and debugging.\n\n\n\n\nWhat is Langfuse?\n \nLangfuse\n is an open-source LLM engineering platform. It provides tracing and monitoring capabilities for LLM applications, helping developers debug, analyze, and optimize their AI systems. Langfuse integrates with various tools and frameworks via native integrations, OpenTelemetry, and APIs/SDKs.\n\n\n\n\n\n\n​\nGet Started\n\n\nWe’ll walk through a simple example of using CrewAI and integrating it with Langfuse via OpenTelemetry using OpenLit.\n\n\n​\nStep 1: Install Dependencies\n\n\nCopy\nAsk AI\n%\npip install langfuse openlit crewai crewai_tools\n\n\n\n\n​\nStep 2: Set Up Environment Variables\n\n\nSet your Langfuse API keys and configure OpenTelemetry export settings to send traces to Langfuse. Please refer to the \nLangfuse OpenTelemetry Docs\n for more information on the Langfuse OpenTelemetry endpoint \n/api/public/otel\n and authentication.\n\n\nCopy\nAsk AI\nimport\n os\n\n\n \n\n\n# Get keys for your project from the project settings page: https://cloud.langfuse.com\n\n\nos.environ[\n\"LANGFUSE_PUBLIC_KEY\"\n] \n=\n \"pk-lf-...\"\n \n\n\nos.environ[\n\"LANGFUSE_SECRET_KEY\"\n] \n=\n \"sk-lf-...\"\n\n\nos.environ[\n\"LANGFUSE_HOST\"\n] \n=\n \"https://cloud.langfuse.com\"\n # 🇪🇺 EU region\n\n\n# os.environ[\"LANGFUSE_HOST\"] = \"https://us.cloud.langfuse.com\" # 🇺🇸 US region\n\n\n \n\n\n \n\n\n# Your OpenAI key\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"sk-proj-...\"\n\n\n\n\nWith the environment variables set, we can now initialize the Langfuse client. get_client() initializes the Langfuse client using the credentials provided in the environment variables.\n\n\nCopy\nAsk AI\nfrom\n langfuse \nimport\n get_client\n\n\n \n\n\nlangfuse \n=\n get_client()\n\n\n \n\n\n# Verify connection\n\n\nif\n langfuse.auth_check():\n\n\n print\n(\n\"Langfuse client is authenticated and ready!\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"Authentication failed. Please check your credentials and host.\"\n)\n\n\n\n\n​\nStep 3: Initialize OpenLit\n\n\nInitialize the OpenLit OpenTelemetry instrumentation SDK to start capturing OpenTelemetry traces.\n\n\nCopy\nAsk AI\nimport\n openlit\n\n\n\n\nopenlit.init()\n\n\n\n\n​\nStep 4: Create a Simple CrewAI Application\n\n\nWe’ll create a simple CrewAI application where multiple agents collaborate to answer a user’s question.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\nfrom\n crewai_tools \nimport\n (\n\n\n WebsiteSearchTool\n\n\n)\n\n\n\n\nweb_rag_tool \n=\n WebsiteSearchTool()\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n\"Writer\"\n,\n\n\n goal\n=\n\"You make math engaging and understandable for young children through poetry\"\n,\n\n\n backstory\n=\n\"You're an expert in writing haikus but you know nothing of math.\"\n,\n\n\n tools\n=\n[web_rag_tool], \n\n\n )\n\n\n\n\ntask \n=\n Task(\ndescription\n=\n(\n\"What is \n{multiplication}\n?\"\n),\n\n\n expected_output\n=\n(\n\"Compose a haiku that includes the answer.\"\n),\n\n\n agent\n=\nwriter)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[writer],\n\n\n tasks\n=\n[task],\n\n\n share_crew\n=\nFalse\n\n\n)\n\n\n\n\n​\nStep 5: See Traces in Langfuse\n\n\nAfter running the agent, you can view the traces generated by your CrewAI application in \nLangfuse\n. You should see detailed steps of the LLM interactions, which can help you debug and optimize your AI agent.\n\n\n\n\nPublic example trace in Langfuse\n\n\n​\nReferences\n\n\n\n\nLangfuse OpenTelemetry Docs\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nArize Phoenix\nLangtrace Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntegrate Langfuse with CrewAI\nGet Started\nStep 1: Install Dependencies\nStep 2: Set Up Environment Variables\nStep 3: Initialize OpenLit\nStep 4: Create a Simple CrewAI Application\nStep 5: See Traces in Langfuse\nReferences" }, { "source": "https://docs.crewai.com/en/concepts/tasks", "title": "Tasks - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nTasks\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nTasks\nCopy page\nDetailed guide on managing and creating tasks within the CrewAI framework.\n​\nOverview\n\n\nIn the CrewAI framework, a \nTask\n is a specific assignment completed by an \nAgent\n.\n\n\nTasks provide all necessary details for execution, such as a description, the agent responsible, required tools, and more, facilitating a wide range of action complexities.\n\n\nTasks within CrewAI can be collaborative, requiring multiple agents to work together. This is managed through the task properties and orchestrated by the Crew’s process, enhancing teamwork and efficiency.\n\n\nCrewAI Enterprise includes a Visual Task Builder in Crew Studio that simplifies complex task creation and chaining. Design your task flows visually and test them in real-time without writing code.\nThe Visual Task Builder enables:\n\n\nDrag-and-drop task creation\n\n\nVisual task dependencies and flow\n\n\nReal-time testing and validation\n\n\nEasy sharing and collaboration\n\n\n\n\n​\nTask Execution Flow\n\n\nTasks can be executed in two ways:\n\n\n\n\nSequential\n: Tasks are executed in the order they are defined\n\n\nHierarchical\n: Tasks are assigned to agents based on their roles and expertise\n\n\n\n\nThe execution flow is defined when creating the crew:\n\n\nCode\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent1, agent2],\n\n\n tasks\n=\n[task1, task2],\n\n\n process\n=\nProcess.sequential \n# or Process.hierarchical\n\n\n)\n\n\n\n\n​\nTask Attributes\n\n\nAttribute\nParameters\nType\nDescription\nDescription\ndescription\nstr\nA clear, concise statement of what the task entails.\nExpected Output\nexpected_output\nstr\nA detailed description of what the task’s completion looks like.\nName\n \n(optional)\nname\nOptional[str]\nA name identifier for the task.\nAgent\n \n(optional)\nagent\nOptional[BaseAgent]\nThe agent responsible for executing the task.\nTools\n \n(optional)\ntools\nList[BaseTool]\nThe tools/resources the agent is limited to use for this task.\nContext\n \n(optional)\ncontext\nOptional[List[\"Task\"]]\nOther tasks whose outputs will be used as context for this task.\nAsync Execution\n \n(optional)\nasync_execution\nOptional[bool]\nWhether the task should be executed asynchronously. Defaults to False.\nHuman Input\n \n(optional)\nhuman_input\nOptional[bool]\nWhether the task should have a human review the final answer of the agent. Defaults to False.\nMarkdown\n \n(optional)\nmarkdown\nOptional[bool]\nWhether the task should instruct the agent to return the final answer formatted in Markdown. Defaults to False.\nConfig\n \n(optional)\nconfig\nOptional[Dict[str, Any]]\nTask-specific configuration parameters.\nOutput File\n \n(optional)\noutput_file\nOptional[str]\nFile path for storing the task output.\nOutput JSON\n \n(optional)\noutput_json\nOptional[Type[BaseModel]]\nA Pydantic model to structure the JSON output.\nOutput Pydantic\n \n(optional)\noutput_pydantic\nOptional[Type[BaseModel]]\nA Pydantic model for task output.\nCallback\n \n(optional)\ncallback\nOptional[Any]\nFunction/object to be executed after task completion.\n\n\n​\nCreating Tasks\n\n\nThere are two ways to create tasks in CrewAI: using \nYAML configuration (recommended)\n or defining them \ndirectly in code\n.\n\n\n​\nYAML Configuration (Recommended)\n\n\nUsing YAML configuration provides a cleaner, more maintainable way to define tasks. We strongly recommend using this approach to define tasks in your CrewAI projects.\n\n\nAfter creating your CrewAI project as outlined in the \nInstallation\n section, navigate to the \nsrc/latest_ai_development/config/tasks.yaml\n file and modify the template to match your specific task requirements.\n\n\nVariables in your YAML files (like \n{topic}\n) will be replaced with values from your inputs when running the crew:\nCode\nCopy\nAsk AI\ncrew.kickoff(\ninputs\n=\n{\n'topic'\n: \n'AI Agents'\n})\n\n\n\n\nHere’s an example of how to configure tasks using YAML:\n\n\ntasks.yaml\nCopy\nAsk AI\nresearch_task\n:\n\n\n description\n: \n>\n\n\n Conduct a thorough research about {topic}\n\n\n Make sure you find any interesting and relevant information given\n\n\n the current year is 2025.\n\n\n expected_output\n: \n>\n\n\n A list with 10 bullet points of the most relevant information about {topic}\n\n\n agent\n: \nresearcher\n\n\n\n\nreporting_task\n:\n\n\n description\n: \n>\n\n\n Review the context you got and expand each topic into a full section for a report.\n\n\n Make sure the report is detailed and contains any and all relevant information.\n\n\n expected_output\n: \n>\n\n\n A fully fledge reports with the mains topics, each with a full section of information.\n\n\n Formatted as markdown without '```'\n\n\n agent\n: \nreporting_analyst\n\n\n markdown\n: \ntrue\n\n\n output_file\n: \nreport.md\n\n\n\n\nTo use this YAML configuration in your code, create a crew class that inherits from \nCrewBase\n:\n\n\ncrew.py\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n reporting_analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'reporting_analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n reporting_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'reporting_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\n[\n\n\n self\n.researcher(),\n\n\n self\n.reporting_analyst()\n\n\n ],\n\n\n tasks\n=\n[\n\n\n self\n.research_task(),\n\n\n self\n.reporting_task()\n\n\n ],\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n\n\nThe names you use in your YAML files (\nagents.yaml\n and \ntasks.yaml\n) should match the method names in your Python code.\n\n\n​\nDirect Code Definition (Alternative)\n\n\nAlternatively, you can define tasks directly in your code without using YAML configuration:\n\n\ntask.py\nCopy\nAsk AI\nfrom\n crewai \nimport\n Task\n\n\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n\"\"\"\n\n\n Conduct a thorough research about AI Agents.\n\n\n Make sure you find any interesting and relevant information given\n\n\n the current year is 2025.\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"\"\"\n\n\n A list with 10 bullet points of the most relevant information about AI Agents\n\n\n \"\"\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nreporting_task \n=\n Task(\n\n\n description\n=\n\"\"\"\n\n\n Review the context you got and expand each topic into a full section for a report.\n\n\n Make sure the report is detailed and contains any and all relevant information.\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"\"\"\n\n\n A fully fledge reports with the mains topics, each with a full section of information.\n\n\n \"\"\"\n,\n\n\n agent\n=\nreporting_analyst,\n\n\n markdown\n=\nTrue\n, \n# Enable markdown formatting for the final output\n\n\n output_file\n=\n\"report.md\"\n\n\n)\n\n\n\n\nDirectly specify an \nagent\n for assignment or let the \nhierarchical\n CrewAI’s process decide based on roles, availability, etc.\n\n\n​\nTask Output\n\n\nUnderstanding task outputs is crucial for building effective AI workflows. CrewAI provides a structured way to handle task results through the \nTaskOutput\n class, which supports multiple output formats and can be easily passed between tasks.\n\n\nThe output of a task in CrewAI framework is encapsulated within the \nTaskOutput\n class. This class provides a structured way to access results of a task, including various formats such as raw output, JSON, and Pydantic models.\n\n\nBy default, the \nTaskOutput\n will only include the \nraw\n output. A \nTaskOutput\n will only include the \npydantic\n or \njson_dict\n output if the original \nTask\n object was configured with \noutput_pydantic\n or \noutput_json\n, respectively.\n\n\n​\nTask Output Attributes\n\n\nAttribute\nParameters\nType\nDescription\nDescription\ndescription\nstr\nDescription of the task.\nSummary\nsummary\nOptional[str]\nSummary of the task, auto-generated from the first 10 words of the description.\nRaw\nraw\nstr\nThe raw output of the task. This is the default format for the output.\nPydantic\npydantic\nOptional[BaseModel]\nA Pydantic model object representing the structured output of the task.\nJSON Dict\njson_dict\nOptional[Dict[str, Any]]\nA dictionary representing the JSON output of the task.\nAgent\nagent\nstr\nThe agent that executed the task.\nOutput Format\noutput_format\nOutputFormat\nThe format of the task output, with options including RAW, JSON, and Pydantic. The default is RAW.\n\n\n​\nTask Methods and Properties\n\n\nMethod/Property\nDescription\njson\nReturns the JSON string representation of the task output if the output format is JSON.\nto_dict\nConverts the JSON and Pydantic outputs to a dictionary.\nstr\nReturns the string representation of the task output, prioritizing Pydantic, then JSON, then raw.\n\n\n​\nAccessing Task Outputs\n\n\nOnce a task has been executed, its output can be accessed through the \noutput\n attribute of the \nTask\n object. The \nTaskOutput\n class provides various ways to interact with and present this output.\n\n\n​\nExample\n\n\nCode\nCopy\nAsk AI\n# Example task\n\n\ntask \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\n# Execute the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Accessing the task output\n\n\ntask_output \n=\n task.output\n\n\n\n\nprint\n(\nf\n\"Task Description: \n{\ntask_output.description\n}\n\"\n)\n\n\nprint\n(\nf\n\"Task Summary: \n{\ntask_output.summary\n}\n\"\n)\n\n\nprint\n(\nf\n\"Raw Output: \n{\ntask_output.raw\n}\n\"\n)\n\n\nif\n task_output.json_dict:\n\n\n print\n(\nf\n\"JSON Output: \n{\njson.dumps(task_output.json_dict, \nindent\n=\n2\n)\n}\n\"\n)\n\n\nif\n task_output.pydantic:\n\n\n print\n(\nf\n\"Pydantic Output: \n{\ntask_output.pydantic\n}\n\"\n)\n\n\n\n\n​\nMarkdown Output Formatting\n\n\nThe \nmarkdown\n parameter enables automatic markdown formatting for task outputs. When set to \nTrue\n, the task will instruct the agent to format the final answer using proper Markdown syntax.\n\n\n​\nUsing Markdown Formatting\n\n\nCode\nCopy\nAsk AI\n# Example task with markdown formatting enabled\n\n\nformatted_task \n=\n Task(\n\n\n description\n=\n\"Create a comprehensive report on AI trends\"\n,\n\n\n expected_output\n=\n\"A well-structured report with headers, sections, and bullet points\"\n,\n\n\n agent\n=\nreporter_agent,\n\n\n markdown\n=\nTrue\n # Enable automatic markdown formatting\n\n\n)\n\n\n\n\nWhen \nmarkdown=True\n, the agent will receive additional instructions to format the output using:\n\n\n\n\n#\n for headers\n\n\n**text**\n for bold text\n\n\n*text*\n for italic text\n\n\n-\n or \n*\n for bullet points\n\n\n`code`\n for inline code\n\n\n \nlanguage ``` for code blocks\n\n\n\n\n​\nYAML Configuration with Markdown\n\n\ntasks.yaml\nCopy\nAsk AI\nanalysis_task\n:\n\n\n description\n: \n>\n\n\n Analyze the market data and create a detailed report\n\n\n expected_output\n: \n>\n\n\n A comprehensive analysis with charts and key findings\n\n\n agent\n: \nanalyst\n\n\n markdown\n: \ntrue\n # Enable markdown formatting\n\n\n output_file\n: \nanalysis.md\n\n\n\n\n​\nBenefits of Markdown Output\n\n\n\n\nConsistent Formatting\n: Ensures all outputs follow proper markdown conventions\n\n\nBetter Readability\n: Structured content with headers, lists, and emphasis\n\n\nDocumentation Ready\n: Output can be directly used in documentation systems\n\n\nCross-Platform Compatibility\n: Markdown is universally supported\n\n\n\n\nThe markdown formatting instructions are automatically added to the task prompt when \nmarkdown=True\n, so you don’t need to specify formatting requirements in your task description.\n\n\n​\nTask Dependencies and Context\n\n\nTasks can depend on the output of other tasks using the \ncontext\n attribute. For example:\n\n\nCode\nCopy\nAsk AI\nresearch_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI\"\n,\n\n\n expected_output\n=\n\"A list of recent AI developments\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the research findings and identify key trends\"\n,\n\n\n expected_output\n=\n\"Analysis report of AI trends\"\n,\n\n\n agent\n=\nanalyst,\n\n\n context\n=\n[research_task] \n# This task will wait for research_task to complete\n\n\n)\n\n\n\n\n​\nTask Guardrails\n\n\nTask guardrails provide a way to validate and transform task outputs before they\nare passed to the next task. This feature helps ensure data quality and provides\nfeedback to agents when their output doesn’t meet specific criteria.\n\n\n​\nUsing Task Guardrails\n\n\nTo add a guardrail to a task, provide a validation function through the \nguardrail\n parameter:\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Tuple, Union, Dict, Any\n\n\nfrom\n crewai \nimport\n TaskOutput\n\n\n\n\ndef\n validate_blog_content\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n \"\"\"Validate blog content meets requirements.\"\"\"\n\n\n try\n:\n\n\n # Check word count\n\n\n word_count \n=\n len\n(result.split())\n\n\n if\n word_count \n>\n 200\n:\n\n\n return\n (\nFalse\n, \n\"Blog content exceeds 200 words\"\n)\n\n\n\n\n # Additional validation logic here\n\n\n return\n (\nTrue\n, result.strip())\n\n\n except\n Exception\n as\n e:\n\n\n return\n (\nFalse\n, \n\"Unexpected error during validation\"\n)\n\n\n\n\nblog_task \n=\n Task(\n\n\n description\n=\n\"Write a blog post about AI\"\n,\n\n\n expected_output\n=\n\"A blog post under 200 words\"\n,\n\n\n agent\n=\nblog_agent,\n\n\n guardrail\n=\nvalidate_blog_content \n# Add the guardrail function\n\n\n)\n\n\n\n\n​\nGuardrail Function Requirements\n\n\n\n\n\n\nFunction Signature\n:\n\n\n\n\nMust accept exactly one parameter (the task output)\n\n\nShould return a tuple of \n(bool, Any)\n\n\nType hints are recommended but optional\n\n\n\n\n\n\n\n\nReturn Values\n:\n\n\n\n\nOn success: it returns a tuple of \n(bool, Any)\n. For example: \n(True, validated_result)\n\n\nOn Failure: it returns a tuple of \n(bool, str)\n. For example: \n(False, \"Error message explain the failure\")\n\n\n\n\n\n\n\n\n​\nLLMGuardrail\n\n\nThe \nLLMGuardrail\n class offers a robust mechanism for validating task outputs.\n\n\n​\nError Handling Best Practices\n\n\n\n\nStructured Error Responses\n:\n\n\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n TaskOutput, LLMGuardrail\n\n\n\n\ndef\n validate_with_context\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n try\n:\n\n\n # Main validation logic\n\n\n validated_data \n=\n perform_validation(result)\n\n\n return\n (\nTrue\n, validated_data)\n\n\n except\n ValidationError \nas\n e:\n\n\n return\n (\nFalse\n, \nf\n\"VALIDATION_ERROR: \n{\nstr\n(e)\n}\n\"\n)\n\n\n except\n Exception\n as\n e:\n\n\n return\n (\nFalse\n, \nstr\n(e))\n\n\n\n\n\n\n\n\nError Categories\n:\n\n\n\n\nUse specific error codes\n\n\nInclude relevant context\n\n\nProvide actionable feedback\n\n\n\n\n\n\n\n\nValidation Chain\n:\n\n\n\n\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Any, Dict, List, Tuple, Union\n\n\nfrom\n crewai \nimport\n TaskOutput\n\n\n\n\ndef\n complex_validation\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n \"\"\"Chain multiple validation steps.\"\"\"\n\n\n # Step 1: Basic validation\n\n\n if\n not\n result:\n\n\n return\n (\nFalse\n, \n\"Empty result\"\n)\n\n\n\n\n # Step 2: Content validation\n\n\n try\n:\n\n\n validated \n=\n validate_content(result)\n\n\n if\n not\n validated:\n\n\n return\n (\nFalse\n, \n\"Invalid content\"\n)\n\n\n\n\n # Step 3: Format validation\n\n\n formatted \n=\n format_output(validated)\n\n\n return\n (\nTrue\n, formatted)\n\n\n except\n Exception\n as\n e:\n\n\n return\n (\nFalse\n, \nstr\n(e))\n\n\n\n\n​\nHandling Guardrail Results\n\n\nWhen a guardrail returns \n(False, error)\n:\n\n\n\n\nThe error is sent back to the agent\n\n\nThe agent attempts to fix the issue\n\n\nThe process repeats until:\n\n\n\n\nThe guardrail returns \n(True, result)\n\n\nMaximum retries are reached\n\n\n\n\n\n\n\n\nExample with retry handling:\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Optional, Tuple, Union\n\n\nfrom\n crewai \nimport\n TaskOutput, Task\n\n\n\n\ndef\n validate_json_output\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n \"\"\"Validate and parse JSON output.\"\"\"\n\n\n try\n:\n\n\n # Try to parse as JSON\n\n\n data \n=\n json.loads(result)\n\n\n return\n (\nTrue\n, data)\n\n\n except\n json.JSONDecodeError \nas\n e:\n\n\n return\n (\nFalse\n, \n\"Invalid JSON format\"\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a JSON report\"\n,\n\n\n expected_output\n=\n\"A valid JSON object\"\n,\n\n\n agent\n=\nanalyst,\n\n\n guardrail\n=\nvalidate_json_output,\n\n\n max_retries\n=\n3\n # Limit retry attempts\n\n\n)\n\n\n\n\n​\nGetting Structured Consistent Outputs from Tasks\n\n\nIt’s also important to note that the output of the final task of a crew becomes the final output of the actual crew itself.\n\n\n​\nUsing \noutput_pydantic\n\n\nThe \noutput_pydantic\n property allows you to define a Pydantic model that the task output should conform to. This ensures that the output is not only structured but also validated according to the Pydantic model.\n\n\nHere’s an example demonstrating how to use output_pydantic:\n\n\nCode\nCopy\nAsk AI\nimport\n json\n\n\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\n\n\nclass\n Blog\n(\nBaseModel\n):\n\n\n title: \nstr\n\n\n content: \nstr\n\n\n\n\n\n\nblog_agent \n=\n Agent(\n\n\n role\n=\n\"Blog Content Generator Agent\"\n,\n\n\n goal\n=\n\"Generate a blog title and content\"\n,\n\n\n backstory\n=\n\"\"\"You are an expert content creator, skilled in crafting engaging and informative blog posts.\"\"\"\n,\n\n\n verbose\n=\nFalse\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n\"gpt-4o\"\n,\n\n\n)\n\n\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"\"\"Create a blog title and content on a given topic. Make sure the content is under 200 words.\"\"\"\n,\n\n\n expected_output\n=\n\"A compelling blog title and well-written content.\"\n,\n\n\n agent\n=\nblog_agent,\n\n\n output_pydantic\n=\nBlog,\n\n\n)\n\n\n\n\n# Instantiate your crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[blog_agent],\n\n\n tasks\n=\n[task1],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Option 1: Accessing Properties Using Dictionary-Style Indexing\n\n\nprint\n(\n\"Accessing Properties - Option 1\"\n)\n\n\ntitle \n=\n result[\n\"title\"\n]\n\n\ncontent \n=\n result[\n\"content\"\n]\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 2: Accessing Properties Directly from the Pydantic Model\n\n\nprint\n(\n\"Accessing Properties - Option 2\"\n)\n\n\ntitle \n=\n result.pydantic.title\n\n\ncontent \n=\n result.pydantic.content\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 3: Accessing Properties Using the to_dict() Method\n\n\nprint\n(\n\"Accessing Properties - Option 3\"\n)\n\n\noutput_dict \n=\n result.to_dict()\n\n\ntitle \n=\n output_dict[\n\"title\"\n]\n\n\ncontent \n=\n output_dict[\n\"content\"\n]\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 4: Printing the Entire Blog Object\n\n\nprint\n(\n\"Accessing Properties - Option 5\"\n)\n\n\nprint\n(\n\"Blog:\"\n, result)\n\n\n\n\n\n\nIn this example:\n\n\n\n\nA Pydantic model Blog is defined with title and content fields.\n\n\nThe task task1 uses the output_pydantic property to specify that its output should conform to the Blog model.\n\n\nAfter executing the crew, you can access the structured output in multiple ways as shown.\n\n\n\n\n​\nExplanation of Accessing the Output\n\n\n\n\nDictionary-Style Indexing: You can directly access the fields using result[“field_name”]. This works because the CrewOutput class implements the \ngetitem\n method.\n\n\nDirectly from Pydantic Model: Access the attributes directly from the result.pydantic object.\n\n\nUsing to_dict() Method: Convert the output to a dictionary and access the fields.\n\n\nPrinting the Entire Object: Simply print the result object to see the structured output.\n\n\n\n\n​\nUsing \noutput_json\n\n\nThe \noutput_json\n property allows you to define the expected output in JSON format. This ensures that the task’s output is a valid JSON structure that can be easily parsed and used in your application.\n\n\nHere’s an example demonstrating how to use \noutput_json\n:\n\n\nCode\nCopy\nAsk AI\nimport\n json\n\n\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\n\n\n# Define the Pydantic model for the blog\n\n\nclass\n Blog\n(\nBaseModel\n):\n\n\n title: \nstr\n\n\n content: \nstr\n\n\n\n\n\n\n# Define the agent\n\n\nblog_agent \n=\n Agent(\n\n\n role\n=\n\"Blog Content Generator Agent\"\n,\n\n\n goal\n=\n\"Generate a blog title and content\"\n,\n\n\n backstory\n=\n\"\"\"You are an expert content creator, skilled in crafting engaging and informative blog posts.\"\"\"\n,\n\n\n verbose\n=\nFalse\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n\"gpt-4o\"\n,\n\n\n)\n\n\n\n\n# Define the task with output_json set to the Blog model\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"\"\"Create a blog title and content on a given topic. Make sure the content is under 200 words.\"\"\"\n,\n\n\n expected_output\n=\n\"A JSON object with 'title' and 'content' fields.\"\n,\n\n\n agent\n=\nblog_agent,\n\n\n output_json\n=\nBlog,\n\n\n)\n\n\n\n\n# Instantiate the crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[blog_agent],\n\n\n tasks\n=\n[task1],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n)\n\n\n\n\n# Kickoff the crew to execute the task\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Option 1: Accessing Properties Using Dictionary-Style Indexing\n\n\nprint\n(\n\"Accessing Properties - Option 1\"\n)\n\n\ntitle \n=\n result[\n\"title\"\n]\n\n\ncontent \n=\n result[\n\"content\"\n]\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 2: Printing the Entire Blog Object\n\n\nprint\n(\n\"Accessing Properties - Option 2\"\n)\n\n\nprint\n(\n\"Blog:\"\n, result)\n\n\n\n\nIn this example:\n\n\n\n\nA Pydantic model Blog is defined with title and content fields, which is used to specify the structure of the JSON output.\n\n\nThe task task1 uses the output_json property to indicate that it expects a JSON output conforming to the Blog model.\n\n\nAfter executing the crew, you can access the structured JSON output in two ways as shown.\n\n\n\n\n​\nExplanation of Accessing the Output\n\n\n\n\nAccessing Properties Using Dictionary-Style Indexing: You can access the fields directly using result[“field_name”]. This is possible because the CrewOutput class implements the \ngetitem\n method, allowing you to treat the output like a dictionary. In this option, we’re retrieving the title and content from the result.\n\n\nPrinting the Entire Blog Object: By printing result, you get the string representation of the CrewOutput object. Since the \nstr\n method is implemented to return the JSON output, this will display the entire output as a formatted string representing the Blog object.\n\n\n\n\n\n\nBy using output_pydantic or output_json, you ensure that your tasks produce outputs in a consistent and structured format, making it easier to process and utilize the data within your application or across multiple tasks.\n\n\n​\nIntegrating Tools with Tasks\n\n\nLeverage tools from the \nCrewAI Toolkit\n and \nLangChain Tools\n for enhanced task performance and agent interaction.\n\n\n​\nCreating a Task with Tools\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n # serper.dev API key\n\n\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\nresearch_agent \n=\n Agent(\n\n\n role\n=\n'Researcher'\n,\n\n\n goal\n=\n'Find and summarize the latest AI news'\n,\n\n\n backstory\n=\n\"\"\"You're a researcher at a large company.\n\n\n You're responsible for analyzing data and providing insights\n\n\n to the business.\"\"\"\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# to perform a semantic search for a specified query from a text's content across the internet\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\nprint\n(result)\n\n\n\n\nThis demonstrates how tasks with specific tools can override an agent’s default set for tailored task execution.\n\n\n​\nReferring to Other Tasks\n\n\nIn CrewAI, the output of one task is automatically relayed into the next one, but you can specifically define what tasks’ output, including multiple, should be used as context for another task.\n\n\nThis is useful when you have a task that depends on the output of another task that is not performed immediately after it. This is done through the \ncontext\n attribute of the task:\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\n\n\nresearch_ai_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI\"\n,\n\n\n expected_output\n=\n\"A list of recent AI developments\"\n,\n\n\n async_execution\n=\nTrue\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\nresearch_ops_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI Ops\"\n,\n\n\n expected_output\n=\n\"A list of recent AI Ops developments\"\n,\n\n\n async_execution\n=\nTrue\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\nwrite_blog_task \n=\n Task(\n\n\n description\n=\n\"Write a full blog post about the importance of AI and its latest news\"\n,\n\n\n expected_output\n=\n\"Full blog post that is 4 paragraphs long\"\n,\n\n\n agent\n=\nwriter_agent,\n\n\n context\n=\n[research_ai_task, research_ops_task]\n\n\n)\n\n\n\n\n#...\n\n\n\n\n​\nAsynchronous Execution\n\n\nYou can define a task to be executed asynchronously. This means that the crew will not wait for it to be completed to continue with the next task. This is useful for tasks that take a long time to be completed, or that are not crucial for the next tasks to be performed.\n\n\nYou can then use the \ncontext\n attribute to define in a future task that it should wait for the output of the asynchronous task to be completed.\n\n\nCode\nCopy\nAsk AI\n#...\n\n\n\n\nlist_ideas \n=\n Task(\n\n\n description\n=\n\"List of 5 interesting ideas to explore for an article about AI.\"\n,\n\n\n expected_output\n=\n\"Bullet point list of 5 ideas for an article.\"\n,\n\n\n agent\n=\nresearcher,\n\n\n async_execution\n=\nTrue\n # Will be executed asynchronously\n\n\n)\n\n\n\n\nlist_important_history \n=\n Task(\n\n\n description\n=\n\"Research the history of AI and give me the 5 most important events.\"\n,\n\n\n expected_output\n=\n\"Bullet point list of 5 important events.\"\n,\n\n\n agent\n=\nresearcher,\n\n\n async_execution\n=\nTrue\n # Will be executed asynchronously\n\n\n)\n\n\n\n\nwrite_article \n=\n Task(\n\n\n description\n=\n\"Write an article about AI, its history, and interesting ideas.\"\n,\n\n\n expected_output\n=\n\"A 4 paragraph article about AI.\"\n,\n\n\n agent\n=\nwriter,\n\n\n context\n=\n[list_ideas, list_important_history] \n# Will wait for the output of the two tasks to be completed\n\n\n)\n\n\n\n\n#...\n\n\n\n\n​\nCallback Mechanism\n\n\nThe callback function is executed after the task is completed, allowing for actions or notifications to be triggered based on the task’s outcome.\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\n\n\ndef\n callback_function\n(\noutput\n: TaskOutput):\n\n\n # Do something after the task is completed\n\n\n # Example: Send an email to the manager\n\n\n print\n(\nf\n\"\"\"\n\n\n Task completed!\n\n\n Task: \n{\noutput.description\n}\n\n\n Output: \n{\noutput.raw\n}\n\n\n \"\"\"\n)\n\n\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool],\n\n\n callback\n=\ncallback_function\n\n\n)\n\n\n\n\n#...\n\n\n\n\n​\nAccessing a Specific Task Output\n\n\nOnce a crew finishes running, you can access the output of a specific task by using the \noutput\n attribute of the task object:\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\n#...\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[task1, task2, task3],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Returns a TaskOutput object with the description and results of the task\n\n\nprint\n(\nf\n\"\"\"\n\n\n Task completed!\n\n\n Task: \n{\ntask1.output.description\n}\n\n\n Output: \n{\ntask1.output.raw\n}\n\n\n\"\"\"\n)\n\n\n\n\n​\nTool Override Mechanism\n\n\nSpecifying tools in a task allows for dynamic adaptation of agent capabilities, emphasizing CrewAI’s flexibility.\n\n\n​\nError Handling and Validation Mechanisms\n\n\nWhile creating and executing tasks, certain validation mechanisms are in place to ensure the robustness and reliability of task attributes. These include but are not limited to:\n\n\n\n\nEnsuring only one output type is set per task to maintain clear output expectations.\n\n\nPreventing the manual assignment of the \nid\n attribute to uphold the integrity of the unique identifier system.\n\n\n\n\nThese validations help in maintaining the consistency and reliability of task executions within the crewAI framework.\n\n\n​\nTask Guardrails\n\n\nTask guardrails provide a powerful way to validate, transform, or filter task outputs before they are passed to the next task. Guardrails are optional functions that execute before the next task starts, allowing you to ensure that task outputs meet specific requirements or formats.\n\n\n​\nBasic Usage\n\n\n​\nDefine your own logic to validate\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Tuple, Union\n\n\nfrom\n crewai \nimport\n Task\n\n\n\n\ndef\n validate_json_output\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\ndict\n, \nstr\n]]:\n\n\n \"\"\"Validate that the output is valid JSON.\"\"\"\n\n\n try\n:\n\n\n json_data \n=\n json.loads(result)\n\n\n return\n (\nTrue\n, json_data)\n\n\n except\n json.JSONDecodeError:\n\n\n return\n (\nFalse\n, \n\"Output must be valid JSON\"\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate JSON data\"\n,\n\n\n expected_output\n=\n\"Valid JSON object\"\n,\n\n\n guardrail\n=\nvalidate_json_output\n\n\n)\n\n\n\n\n​\nLeverage a no-code approach for validation\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Task\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate JSON data\"\n,\n\n\n expected_output\n=\n\"Valid JSON object\"\n,\n\n\n guardrail\n=\n\"Ensure the response is a valid JSON object\"\n\n\n)\n\n\n\n\n​\nUsing YAML\n\n\nCopy\nAsk AI\nresearch_task\n:\n\n\n ...\n\n\n guardrail\n: \nmake sure each bullet contains a minimum of 100 words\n\n\n ...\n\n\n\n\nCode\nCopy\nAsk AI\n@CrewBase\n\n\nclass\n InternalCrew\n:\n\n\n agents_config \n=\n \"config/agents.yaml\"\n\n\n tasks_config \n=\n \"config/tasks.yaml\"\n\n\n\n\n ...\n\n\n @task\n\n\n def\n research_task\n(\nself\n):\n\n\n return\n Task(\nconfig\n=\nself\n.tasks_config[\n\"research_task\"\n]) \n# type: ignore[index]\n\n\n ...\n\n\n\n\n​\nUse custom models for code generation\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Task\n\n\nfrom\n crewai.llm \nimport\n LLM\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate JSON data\"\n,\n\n\n expected_output\n=\n\"Valid JSON object\"\n,\n\n\n guardrail\n=\nLLMGuardrail(\n\n\n description\n=\n\"Ensure the response is a valid JSON object\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4o-mini\"\n),\n\n\n )\n\n\n)\n\n\n\n\n​\nHow Guardrails Work\n\n\n\n\nOptional Attribute\n: Guardrails are an optional attribute at the task level, allowing you to add validation only where needed.\n\n\nExecution Timing\n: The guardrail function is executed before the next task starts, ensuring valid data flow between tasks.\n\n\nReturn Format\n: Guardrails must return a tuple of \n(success, data)\n:\n\n\n\n\nIf \nsuccess\n is \nTrue\n, \ndata\n is the validated/transformed result\n\n\nIf \nsuccess\n is \nFalse\n, \ndata\n is the error message\n\n\n\n\n\n\nResult Routing\n:\n\n\n\n\nOn success (\nTrue\n), the result is automatically passed to the next task\n\n\nOn failure (\nFalse\n), the error is sent back to the agent to generate a new answer\n\n\n\n\n\n\n\n\n​\nCommon Use Cases\n\n\n​\nData Format Validation\n\n\nCode\nCopy\nAsk AI\ndef\n validate_email_format\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\nstr\n, \nstr\n]]:\n\n\n \"\"\"Ensure the output contains a valid email address.\"\"\"\n\n\n import\n re\n\n\n email_pattern \n=\n r\n'\n^\n[\n\\w\n\\.\n-\n]\n+\n@\n[\n\\w\n\\.\n-\n]\n+\n\\.\n\\w\n+\n$\n'\n\n\n if\n re.match(email_pattern, result.strip()):\n\n\n return\n (\nTrue\n, result.strip())\n\n\n return\n (\nFalse\n, \n\"Output must be a valid email address\"\n)\n\n\n\n\n​\nContent Filtering\n\n\nCode\nCopy\nAsk AI\ndef\n filter_sensitive_info\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\nstr\n, \nstr\n]]:\n\n\n \"\"\"Remove or validate sensitive information.\"\"\"\n\n\n sensitive_patterns \n=\n [\n'SSN:'\n, \n'password:'\n, \n'secret:'\n]\n\n\n for\n pattern \nin\n sensitive_patterns:\n\n\n if\n pattern.lower() \nin\n result.lower():\n\n\n return\n (\nFalse\n, \nf\n\"Output contains sensitive information (\n{\npattern\n}\n)\"\n)\n\n\n return\n (\nTrue\n, result)\n\n\n\n\n​\nData Transformation\n\n\nCode\nCopy\nAsk AI\ndef\n normalize_phone_number\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\nstr\n, \nstr\n]]:\n\n\n \"\"\"Ensure phone numbers are in a consistent format.\"\"\"\n\n\n import\n re\n\n\n digits \n=\n re.sub(\nr\n'\n\\D\n'\n, \n''\n, result)\n\n\n if\n len\n(digits) \n==\n 10\n:\n\n\n formatted \n=\n f\n\"(\n{\ndigits[:\n3\n]\n}\n) \n{\ndigits[\n3\n:\n6\n]\n}\n-\n{\ndigits[\n6\n:]\n}\n\"\n\n\n return\n (\nTrue\n, formatted)\n\n\n return\n (\nFalse\n, \n\"Output must be a 10-digit phone number\"\n)\n\n\n\n\n​\nAdvanced Features\n\n\n​\nChaining Multiple Validations\n\n\nCode\nCopy\nAsk AI\ndef\n chain_validations\n(\n*\nvalidators\n):\n\n\n \"\"\"Chain multiple validators together.\"\"\"\n\n\n def\n combined_validator\n(\nresult\n):\n\n\n for\n validator \nin\n validators:\n\n\n success, data \n=\n validator(result)\n\n\n if\n not\n success:\n\n\n return\n (\nFalse\n, data)\n\n\n result \n=\n data\n\n\n return\n (\nTrue\n, result)\n\n\n return\n combined_validator\n\n\n\n\n# Usage\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Get user contact info\"\n,\n\n\n expected_output\n=\n\"Email and phone\"\n,\n\n\n guardrail\n=\nchain_validations(\n\n\n validate_email_format,\n\n\n filter_sensitive_info\n\n\n )\n\n\n)\n\n\n\n\n​\nCustom Retry Logic\n\n\nCode\nCopy\nAsk AI\ntask \n=\n Task(\n\n\n description\n=\n\"Generate data\"\n,\n\n\n expected_output\n=\n\"Valid data\"\n,\n\n\n guardrail\n=\nvalidate_data,\n\n\n max_retries\n=\n5\n # Override default retry limit\n\n\n)\n\n\n\n\n​\nCreating Directories when Saving Files\n\n\nYou can now specify if a task should create directories when saving its output to a file. This is particularly useful for organizing outputs and ensuring that file paths are correctly structured.\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\n\n\nsave_output_task \n=\n Task(\n\n\n description\n=\n'Save the summarized AI news to a file'\n,\n\n\n expected_output\n=\n'File saved successfully'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[file_save_tool],\n\n\n output_file\n=\n'outputs/ai_news_summary.txt'\n,\n\n\n create_directory\n=\nTrue\n\n\n)\n\n\n\n\n#...\n\n\n\n\nCheck out the video below to see how to use structured outputs in CrewAI:\n\n\n\n\n​\nConclusion\n\n\nTasks are the driving force behind the actions of agents in CrewAI.\nBy properly defining tasks and their outcomes, you set the stage for your AI agents to work effectively, either independently or as a collaborative unit.\nEquipping tasks with appropriate tools, understanding the execution process, and following robust validation practices are crucial for maximizing CrewAI’s potential,\nensuring agents are effectively prepared for their assignments and that tasks are executed as intended.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nAgents\nCrews\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nTask Execution Flow\nTask Attributes\nCreating Tasks\nYAML Configuration (Recommended)\nDirect Code Definition (Alternative)\nTask Output\nTask Output Attributes\nTask Methods and Properties\nAccessing Task Outputs\nExample\nMarkdown Output Formatting\nUsing Markdown Formatting\nYAML Configuration with Markdown\nBenefits of Markdown Output\nTask Dependencies and Context\nTask Guardrails\nUsing Task Guardrails\nGuardrail Function Requirements\nLLMGuardrail\nError Handling Best Practices\nHandling Guardrail Results\nGetting Structured Consistent Outputs from Tasks\nUsing output_pydantic\nExplanation of Accessing the Output\nUsing output_json\nExplanation of Accessing the Output\nIntegrating Tools with Tasks\nCreating a Task with Tools\nReferring to Other Tasks\nAsynchronous Execution\nCallback Mechanism\nAccessing a Specific Task Output\nTool Override Mechanism\nError Handling and Validation Mechanisms\nTask Guardrails\nBasic Usage\nDefine your own logic to validate\nLeverage a no-code approach for validation\nUsing YAML\nUse custom models for code generation\nHow Guardrails Work\nCommon Use Cases\nData Format Validation\nContent Filtering\nData Transformation\nAdvanced Features\nChaining Multiple Validations\nCustom Retry Logic\nCreating Directories when Saving Files\nConclusion\nCore Concepts\nTasks\nCopy page\nDetailed guide on managing and creating tasks within the CrewAI framework.\n​\nOverview\n\n\nIn the CrewAI framework, a \nTask\n is a specific assignment completed by an \nAgent\n.\n\n\nTasks provide all necessary details for execution, such as a description, the agent responsible, required tools, and more, facilitating a wide range of action complexities.\n\n\nTasks within CrewAI can be collaborative, requiring multiple agents to work together. This is managed through the task properties and orchestrated by the Crew’s process, enhancing teamwork and efficiency.\n\n\nCrewAI Enterprise includes a Visual Task Builder in Crew Studio that simplifies complex task creation and chaining. Design your task flows visually and test them in real-time without writing code.\nThe Visual Task Builder enables:\n\n\nDrag-and-drop task creation\n\n\nVisual task dependencies and flow\n\n\nReal-time testing and validation\n\n\nEasy sharing and collaboration\n\n\n\n\n​\nTask Execution Flow\n\n\nTasks can be executed in two ways:\n\n\n\n\nSequential\n: Tasks are executed in the order they are defined\n\n\nHierarchical\n: Tasks are assigned to agents based on their roles and expertise\n\n\n\n\nThe execution flow is defined when creating the crew:\n\n\nCode\nCopy\nAsk AI\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent1, agent2],\n\n\n tasks\n=\n[task1, task2],\n\n\n process\n=\nProcess.sequential \n# or Process.hierarchical\n\n\n)\n\n\n\n\n​\nTask Attributes\n\n\nAttribute\nParameters\nType\nDescription\nDescription\ndescription\nstr\nA clear, concise statement of what the task entails.\nExpected Output\nexpected_output\nstr\nA detailed description of what the task’s completion looks like.\nName\n \n(optional)\nname\nOptional[str]\nA name identifier for the task.\nAgent\n \n(optional)\nagent\nOptional[BaseAgent]\nThe agent responsible for executing the task.\nTools\n \n(optional)\ntools\nList[BaseTool]\nThe tools/resources the agent is limited to use for this task.\nContext\n \n(optional)\ncontext\nOptional[List[\"Task\"]]\nOther tasks whose outputs will be used as context for this task.\nAsync Execution\n \n(optional)\nasync_execution\nOptional[bool]\nWhether the task should be executed asynchronously. Defaults to False.\nHuman Input\n \n(optional)\nhuman_input\nOptional[bool]\nWhether the task should have a human review the final answer of the agent. Defaults to False.\nMarkdown\n \n(optional)\nmarkdown\nOptional[bool]\nWhether the task should instruct the agent to return the final answer formatted in Markdown. Defaults to False.\nConfig\n \n(optional)\nconfig\nOptional[Dict[str, Any]]\nTask-specific configuration parameters.\nOutput File\n \n(optional)\noutput_file\nOptional[str]\nFile path for storing the task output.\nOutput JSON\n \n(optional)\noutput_json\nOptional[Type[BaseModel]]\nA Pydantic model to structure the JSON output.\nOutput Pydantic\n \n(optional)\noutput_pydantic\nOptional[Type[BaseModel]]\nA Pydantic model for task output.\nCallback\n \n(optional)\ncallback\nOptional[Any]\nFunction/object to be executed after task completion.\n\n\n​\nCreating Tasks\n\n\nThere are two ways to create tasks in CrewAI: using \nYAML configuration (recommended)\n or defining them \ndirectly in code\n.\n\n\n​\nYAML Configuration (Recommended)\n\n\nUsing YAML configuration provides a cleaner, more maintainable way to define tasks. We strongly recommend using this approach to define tasks in your CrewAI projects.\n\n\nAfter creating your CrewAI project as outlined in the \nInstallation\n section, navigate to the \nsrc/latest_ai_development/config/tasks.yaml\n file and modify the template to match your specific task requirements.\n\n\nVariables in your YAML files (like \n{topic}\n) will be replaced with values from your inputs when running the crew:\nCode\nCopy\nAsk AI\ncrew.kickoff(\ninputs\n=\n{\n'topic'\n: \n'AI Agents'\n})\n\n\n\n\nHere’s an example of how to configure tasks using YAML:\n\n\ntasks.yaml\nCopy\nAsk AI\nresearch_task\n:\n\n\n description\n: \n>\n\n\n Conduct a thorough research about {topic}\n\n\n Make sure you find any interesting and relevant information given\n\n\n the current year is 2025.\n\n\n expected_output\n: \n>\n\n\n A list with 10 bullet points of the most relevant information about {topic}\n\n\n agent\n: \nresearcher\n\n\n\n\nreporting_task\n:\n\n\n description\n: \n>\n\n\n Review the context you got and expand each topic into a full section for a report.\n\n\n Make sure the report is detailed and contains any and all relevant information.\n\n\n expected_output\n: \n>\n\n\n A fully fledge reports with the mains topics, each with a full section of information.\n\n\n Formatted as markdown without '```'\n\n\n agent\n: \nreporting_analyst\n\n\n markdown\n: \ntrue\n\n\n output_file\n: \nreport.md\n\n\n\n\nTo use this YAML configuration in your code, create a crew class that inherits from \nCrewBase\n:\n\n\ncrew.py\nCopy\nAsk AI\n# src/latest_ai_development/crew.py\n\n\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n@CrewBase\n\n\nclass\n LatestAiDevelopmentCrew\n():\n\n\n \"\"\"LatestAiDevelopment crew\"\"\"\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n reporting_analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'reporting_analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n reporting_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'reporting_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\n[\n\n\n self\n.researcher(),\n\n\n self\n.reporting_analyst()\n\n\n ],\n\n\n tasks\n=\n[\n\n\n self\n.research_task(),\n\n\n self\n.reporting_task()\n\n\n ],\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n\n\nThe names you use in your YAML files (\nagents.yaml\n and \ntasks.yaml\n) should match the method names in your Python code.\n\n\n​\nDirect Code Definition (Alternative)\n\n\nAlternatively, you can define tasks directly in your code without using YAML configuration:\n\n\ntask.py\nCopy\nAsk AI\nfrom\n crewai \nimport\n Task\n\n\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n\"\"\"\n\n\n Conduct a thorough research about AI Agents.\n\n\n Make sure you find any interesting and relevant information given\n\n\n the current year is 2025.\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"\"\"\n\n\n A list with 10 bullet points of the most relevant information about AI Agents\n\n\n \"\"\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nreporting_task \n=\n Task(\n\n\n description\n=\n\"\"\"\n\n\n Review the context you got and expand each topic into a full section for a report.\n\n\n Make sure the report is detailed and contains any and all relevant information.\n\n\n \"\"\"\n,\n\n\n expected_output\n=\n\"\"\"\n\n\n A fully fledge reports with the mains topics, each with a full section of information.\n\n\n \"\"\"\n,\n\n\n agent\n=\nreporting_analyst,\n\n\n markdown\n=\nTrue\n, \n# Enable markdown formatting for the final output\n\n\n output_file\n=\n\"report.md\"\n\n\n)\n\n\n\n\nDirectly specify an \nagent\n for assignment or let the \nhierarchical\n CrewAI’s process decide based on roles, availability, etc.\n\n\n​\nTask Output\n\n\nUnderstanding task outputs is crucial for building effective AI workflows. CrewAI provides a structured way to handle task results through the \nTaskOutput\n class, which supports multiple output formats and can be easily passed between tasks.\n\n\nThe output of a task in CrewAI framework is encapsulated within the \nTaskOutput\n class. This class provides a structured way to access results of a task, including various formats such as raw output, JSON, and Pydantic models.\n\n\nBy default, the \nTaskOutput\n will only include the \nraw\n output. A \nTaskOutput\n will only include the \npydantic\n or \njson_dict\n output if the original \nTask\n object was configured with \noutput_pydantic\n or \noutput_json\n, respectively.\n\n\n​\nTask Output Attributes\n\n\nAttribute\nParameters\nType\nDescription\nDescription\ndescription\nstr\nDescription of the task.\nSummary\nsummary\nOptional[str]\nSummary of the task, auto-generated from the first 10 words of the description.\nRaw\nraw\nstr\nThe raw output of the task. This is the default format for the output.\nPydantic\npydantic\nOptional[BaseModel]\nA Pydantic model object representing the structured output of the task.\nJSON Dict\njson_dict\nOptional[Dict[str, Any]]\nA dictionary representing the JSON output of the task.\nAgent\nagent\nstr\nThe agent that executed the task.\nOutput Format\noutput_format\nOutputFormat\nThe format of the task output, with options including RAW, JSON, and Pydantic. The default is RAW.\n\n\n​\nTask Methods and Properties\n\n\nMethod/Property\nDescription\njson\nReturns the JSON string representation of the task output if the output format is JSON.\nto_dict\nConverts the JSON and Pydantic outputs to a dictionary.\nstr\nReturns the string representation of the task output, prioritizing Pydantic, then JSON, then raw.\n\n\n​\nAccessing Task Outputs\n\n\nOnce a task has been executed, its output can be accessed through the \noutput\n attribute of the \nTask\n object. The \nTaskOutput\n class provides various ways to interact with and present this output.\n\n\n​\nExample\n\n\nCode\nCopy\nAsk AI\n# Example task\n\n\ntask \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\n# Execute the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Accessing the task output\n\n\ntask_output \n=\n task.output\n\n\n\n\nprint\n(\nf\n\"Task Description: \n{\ntask_output.description\n}\n\"\n)\n\n\nprint\n(\nf\n\"Task Summary: \n{\ntask_output.summary\n}\n\"\n)\n\n\nprint\n(\nf\n\"Raw Output: \n{\ntask_output.raw\n}\n\"\n)\n\n\nif\n task_output.json_dict:\n\n\n print\n(\nf\n\"JSON Output: \n{\njson.dumps(task_output.json_dict, \nindent\n=\n2\n)\n}\n\"\n)\n\n\nif\n task_output.pydantic:\n\n\n print\n(\nf\n\"Pydantic Output: \n{\ntask_output.pydantic\n}\n\"\n)\n\n\n\n\n​\nMarkdown Output Formatting\n\n\nThe \nmarkdown\n parameter enables automatic markdown formatting for task outputs. When set to \nTrue\n, the task will instruct the agent to format the final answer using proper Markdown syntax.\n\n\n​\nUsing Markdown Formatting\n\n\nCode\nCopy\nAsk AI\n# Example task with markdown formatting enabled\n\n\nformatted_task \n=\n Task(\n\n\n description\n=\n\"Create a comprehensive report on AI trends\"\n,\n\n\n expected_output\n=\n\"A well-structured report with headers, sections, and bullet points\"\n,\n\n\n agent\n=\nreporter_agent,\n\n\n markdown\n=\nTrue\n # Enable automatic markdown formatting\n\n\n)\n\n\n\n\nWhen \nmarkdown=True\n, the agent will receive additional instructions to format the output using:\n\n\n\n\n#\n for headers\n\n\n**text**\n for bold text\n\n\n*text*\n for italic text\n\n\n-\n or \n*\n for bullet points\n\n\n`code`\n for inline code\n\n\n \nlanguage ``` for code blocks\n\n\n\n\n​\nYAML Configuration with Markdown\n\n\ntasks.yaml\nCopy\nAsk AI\nanalysis_task\n:\n\n\n description\n: \n>\n\n\n Analyze the market data and create a detailed report\n\n\n expected_output\n: \n>\n\n\n A comprehensive analysis with charts and key findings\n\n\n agent\n: \nanalyst\n\n\n markdown\n: \ntrue\n # Enable markdown formatting\n\n\n output_file\n: \nanalysis.md\n\n\n\n\n​\nBenefits of Markdown Output\n\n\n\n\nConsistent Formatting\n: Ensures all outputs follow proper markdown conventions\n\n\nBetter Readability\n: Structured content with headers, lists, and emphasis\n\n\nDocumentation Ready\n: Output can be directly used in documentation systems\n\n\nCross-Platform Compatibility\n: Markdown is universally supported\n\n\n\n\nThe markdown formatting instructions are automatically added to the task prompt when \nmarkdown=True\n, so you don’t need to specify formatting requirements in your task description.\n\n\n​\nTask Dependencies and Context\n\n\nTasks can depend on the output of other tasks using the \ncontext\n attribute. For example:\n\n\nCode\nCopy\nAsk AI\nresearch_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI\"\n,\n\n\n expected_output\n=\n\"A list of recent AI developments\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the research findings and identify key trends\"\n,\n\n\n expected_output\n=\n\"Analysis report of AI trends\"\n,\n\n\n agent\n=\nanalyst,\n\n\n context\n=\n[research_task] \n# This task will wait for research_task to complete\n\n\n)\n\n\n\n\n​\nTask Guardrails\n\n\nTask guardrails provide a way to validate and transform task outputs before they\nare passed to the next task. This feature helps ensure data quality and provides\nfeedback to agents when their output doesn’t meet specific criteria.\n\n\n​\nUsing Task Guardrails\n\n\nTo add a guardrail to a task, provide a validation function through the \nguardrail\n parameter:\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Tuple, Union, Dict, Any\n\n\nfrom\n crewai \nimport\n TaskOutput\n\n\n\n\ndef\n validate_blog_content\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n \"\"\"Validate blog content meets requirements.\"\"\"\n\n\n try\n:\n\n\n # Check word count\n\n\n word_count \n=\n len\n(result.split())\n\n\n if\n word_count \n>\n 200\n:\n\n\n return\n (\nFalse\n, \n\"Blog content exceeds 200 words\"\n)\n\n\n\n\n # Additional validation logic here\n\n\n return\n (\nTrue\n, result.strip())\n\n\n except\n Exception\n as\n e:\n\n\n return\n (\nFalse\n, \n\"Unexpected error during validation\"\n)\n\n\n\n\nblog_task \n=\n Task(\n\n\n description\n=\n\"Write a blog post about AI\"\n,\n\n\n expected_output\n=\n\"A blog post under 200 words\"\n,\n\n\n agent\n=\nblog_agent,\n\n\n guardrail\n=\nvalidate_blog_content \n# Add the guardrail function\n\n\n)\n\n\n\n\n​\nGuardrail Function Requirements\n\n\n\n\n\n\nFunction Signature\n:\n\n\n\n\nMust accept exactly one parameter (the task output)\n\n\nShould return a tuple of \n(bool, Any)\n\n\nType hints are recommended but optional\n\n\n\n\n\n\n\n\nReturn Values\n:\n\n\n\n\nOn success: it returns a tuple of \n(bool, Any)\n. For example: \n(True, validated_result)\n\n\nOn Failure: it returns a tuple of \n(bool, str)\n. For example: \n(False, \"Error message explain the failure\")\n\n\n\n\n\n\n\n\n​\nLLMGuardrail\n\n\nThe \nLLMGuardrail\n class offers a robust mechanism for validating task outputs.\n\n\n​\nError Handling Best Practices\n\n\n\n\nStructured Error Responses\n:\n\n\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n TaskOutput, LLMGuardrail\n\n\n\n\ndef\n validate_with_context\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n try\n:\n\n\n # Main validation logic\n\n\n validated_data \n=\n perform_validation(result)\n\n\n return\n (\nTrue\n, validated_data)\n\n\n except\n ValidationError \nas\n e:\n\n\n return\n (\nFalse\n, \nf\n\"VALIDATION_ERROR: \n{\nstr\n(e)\n}\n\"\n)\n\n\n except\n Exception\n as\n e:\n\n\n return\n (\nFalse\n, \nstr\n(e))\n\n\n\n\n\n\n\n\nError Categories\n:\n\n\n\n\nUse specific error codes\n\n\nInclude relevant context\n\n\nProvide actionable feedback\n\n\n\n\n\n\n\n\nValidation Chain\n:\n\n\n\n\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Any, Dict, List, Tuple, Union\n\n\nfrom\n crewai \nimport\n TaskOutput\n\n\n\n\ndef\n complex_validation\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n \"\"\"Chain multiple validation steps.\"\"\"\n\n\n # Step 1: Basic validation\n\n\n if\n not\n result:\n\n\n return\n (\nFalse\n, \n\"Empty result\"\n)\n\n\n\n\n # Step 2: Content validation\n\n\n try\n:\n\n\n validated \n=\n validate_content(result)\n\n\n if\n not\n validated:\n\n\n return\n (\nFalse\n, \n\"Invalid content\"\n)\n\n\n\n\n # Step 3: Format validation\n\n\n formatted \n=\n format_output(validated)\n\n\n return\n (\nTrue\n, formatted)\n\n\n except\n Exception\n as\n e:\n\n\n return\n (\nFalse\n, \nstr\n(e))\n\n\n\n\n​\nHandling Guardrail Results\n\n\nWhen a guardrail returns \n(False, error)\n:\n\n\n\n\nThe error is sent back to the agent\n\n\nThe agent attempts to fix the issue\n\n\nThe process repeats until:\n\n\n\n\nThe guardrail returns \n(True, result)\n\n\nMaximum retries are reached\n\n\n\n\n\n\n\n\nExample with retry handling:\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Optional, Tuple, Union\n\n\nfrom\n crewai \nimport\n TaskOutput, Task\n\n\n\n\ndef\n validate_json_output\n(\nresult\n: TaskOutput) -> Tuple[\nbool\n, Any]:\n\n\n \"\"\"Validate and parse JSON output.\"\"\"\n\n\n try\n:\n\n\n # Try to parse as JSON\n\n\n data \n=\n json.loads(result)\n\n\n return\n (\nTrue\n, data)\n\n\n except\n json.JSONDecodeError \nas\n e:\n\n\n return\n (\nFalse\n, \n\"Invalid JSON format\"\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate a JSON report\"\n,\n\n\n expected_output\n=\n\"A valid JSON object\"\n,\n\n\n agent\n=\nanalyst,\n\n\n guardrail\n=\nvalidate_json_output,\n\n\n max_retries\n=\n3\n # Limit retry attempts\n\n\n)\n\n\n\n\n​\nGetting Structured Consistent Outputs from Tasks\n\n\nIt’s also important to note that the output of the final task of a crew becomes the final output of the actual crew itself.\n\n\n​\nUsing \noutput_pydantic\n\n\nThe \noutput_pydantic\n property allows you to define a Pydantic model that the task output should conform to. This ensures that the output is not only structured but also validated according to the Pydantic model.\n\n\nHere’s an example demonstrating how to use output_pydantic:\n\n\nCode\nCopy\nAsk AI\nimport\n json\n\n\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\n\n\nclass\n Blog\n(\nBaseModel\n):\n\n\n title: \nstr\n\n\n content: \nstr\n\n\n\n\n\n\nblog_agent \n=\n Agent(\n\n\n role\n=\n\"Blog Content Generator Agent\"\n,\n\n\n goal\n=\n\"Generate a blog title and content\"\n,\n\n\n backstory\n=\n\"\"\"You are an expert content creator, skilled in crafting engaging and informative blog posts.\"\"\"\n,\n\n\n verbose\n=\nFalse\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n\"gpt-4o\"\n,\n\n\n)\n\n\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"\"\"Create a blog title and content on a given topic. Make sure the content is under 200 words.\"\"\"\n,\n\n\n expected_output\n=\n\"A compelling blog title and well-written content.\"\n,\n\n\n agent\n=\nblog_agent,\n\n\n output_pydantic\n=\nBlog,\n\n\n)\n\n\n\n\n# Instantiate your crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[blog_agent],\n\n\n tasks\n=\n[task1],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Option 1: Accessing Properties Using Dictionary-Style Indexing\n\n\nprint\n(\n\"Accessing Properties - Option 1\"\n)\n\n\ntitle \n=\n result[\n\"title\"\n]\n\n\ncontent \n=\n result[\n\"content\"\n]\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 2: Accessing Properties Directly from the Pydantic Model\n\n\nprint\n(\n\"Accessing Properties - Option 2\"\n)\n\n\ntitle \n=\n result.pydantic.title\n\n\ncontent \n=\n result.pydantic.content\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 3: Accessing Properties Using the to_dict() Method\n\n\nprint\n(\n\"Accessing Properties - Option 3\"\n)\n\n\noutput_dict \n=\n result.to_dict()\n\n\ntitle \n=\n output_dict[\n\"title\"\n]\n\n\ncontent \n=\n output_dict[\n\"content\"\n]\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 4: Printing the Entire Blog Object\n\n\nprint\n(\n\"Accessing Properties - Option 5\"\n)\n\n\nprint\n(\n\"Blog:\"\n, result)\n\n\n\n\n\n\nIn this example:\n\n\n\n\nA Pydantic model Blog is defined with title and content fields.\n\n\nThe task task1 uses the output_pydantic property to specify that its output should conform to the Blog model.\n\n\nAfter executing the crew, you can access the structured output in multiple ways as shown.\n\n\n\n\n​\nExplanation of Accessing the Output\n\n\n\n\nDictionary-Style Indexing: You can directly access the fields using result[“field_name”]. This works because the CrewOutput class implements the \ngetitem\n method.\n\n\nDirectly from Pydantic Model: Access the attributes directly from the result.pydantic object.\n\n\nUsing to_dict() Method: Convert the output to a dictionary and access the fields.\n\n\nPrinting the Entire Object: Simply print the result object to see the structured output.\n\n\n\n\n​\nUsing \noutput_json\n\n\nThe \noutput_json\n property allows you to define the expected output in JSON format. This ensures that the task’s output is a valid JSON structure that can be easily parsed and used in your application.\n\n\nHere’s an example demonstrating how to use \noutput_json\n:\n\n\nCode\nCopy\nAsk AI\nimport\n json\n\n\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\n\n\n# Define the Pydantic model for the blog\n\n\nclass\n Blog\n(\nBaseModel\n):\n\n\n title: \nstr\n\n\n content: \nstr\n\n\n\n\n\n\n# Define the agent\n\n\nblog_agent \n=\n Agent(\n\n\n role\n=\n\"Blog Content Generator Agent\"\n,\n\n\n goal\n=\n\"Generate a blog title and content\"\n,\n\n\n backstory\n=\n\"\"\"You are an expert content creator, skilled in crafting engaging and informative blog posts.\"\"\"\n,\n\n\n verbose\n=\nFalse\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\n\"gpt-4o\"\n,\n\n\n)\n\n\n\n\n# Define the task with output_json set to the Blog model\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n\"\"\"Create a blog title and content on a given topic. Make sure the content is under 200 words.\"\"\"\n,\n\n\n expected_output\n=\n\"A JSON object with 'title' and 'content' fields.\"\n,\n\n\n agent\n=\nblog_agent,\n\n\n output_json\n=\nBlog,\n\n\n)\n\n\n\n\n# Instantiate the crew with a sequential process\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[blog_agent],\n\n\n tasks\n=\n[task1],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n)\n\n\n\n\n# Kickoff the crew to execute the task\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Option 1: Accessing Properties Using Dictionary-Style Indexing\n\n\nprint\n(\n\"Accessing Properties - Option 1\"\n)\n\n\ntitle \n=\n result[\n\"title\"\n]\n\n\ncontent \n=\n result[\n\"content\"\n]\n\n\nprint\n(\n\"Title:\"\n, title)\n\n\nprint\n(\n\"Content:\"\n, content)\n\n\n\n\n# Option 2: Printing the Entire Blog Object\n\n\nprint\n(\n\"Accessing Properties - Option 2\"\n)\n\n\nprint\n(\n\"Blog:\"\n, result)\n\n\n\n\nIn this example:\n\n\n\n\nA Pydantic model Blog is defined with title and content fields, which is used to specify the structure of the JSON output.\n\n\nThe task task1 uses the output_json property to indicate that it expects a JSON output conforming to the Blog model.\n\n\nAfter executing the crew, you can access the structured JSON output in two ways as shown.\n\n\n\n\n​\nExplanation of Accessing the Output\n\n\n\n\nAccessing Properties Using Dictionary-Style Indexing: You can access the fields directly using result[“field_name”]. This is possible because the CrewOutput class implements the \ngetitem\n method, allowing you to treat the output like a dictionary. In this option, we’re retrieving the title and content from the result.\n\n\nPrinting the Entire Blog Object: By printing result, you get the string representation of the CrewOutput object. Since the \nstr\n method is implemented to return the JSON output, this will display the entire output as a formatted string representing the Blog object.\n\n\n\n\n\n\nBy using output_pydantic or output_json, you ensure that your tasks produce outputs in a consistent and structured format, making it easier to process and utilize the data within your application or across multiple tasks.\n\n\n​\nIntegrating Tools with Tasks\n\n\nLeverage tools from the \nCrewAI Toolkit\n and \nLangChain Tools\n for enhanced task performance and agent interaction.\n\n\n​\nCreating a Task with Tools\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n # serper.dev API key\n\n\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\nresearch_agent \n=\n Agent(\n\n\n role\n=\n'Researcher'\n,\n\n\n goal\n=\n'Find and summarize the latest AI news'\n,\n\n\n backstory\n=\n\"\"\"You're a researcher at a large company.\n\n\n You're responsible for analyzing data and providing insights\n\n\n to the business.\"\"\"\n,\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# to perform a semantic search for a specified query from a text's content across the internet\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\nprint\n(result)\n\n\n\n\nThis demonstrates how tasks with specific tools can override an agent’s default set for tailored task execution.\n\n\n​\nReferring to Other Tasks\n\n\nIn CrewAI, the output of one task is automatically relayed into the next one, but you can specifically define what tasks’ output, including multiple, should be used as context for another task.\n\n\nThis is useful when you have a task that depends on the output of another task that is not performed immediately after it. This is done through the \ncontext\n attribute of the task:\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\n\n\nresearch_ai_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI\"\n,\n\n\n expected_output\n=\n\"A list of recent AI developments\"\n,\n\n\n async_execution\n=\nTrue\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\nresearch_ops_task \n=\n Task(\n\n\n description\n=\n\"Research the latest developments in AI Ops\"\n,\n\n\n expected_output\n=\n\"A list of recent AI Ops developments\"\n,\n\n\n async_execution\n=\nTrue\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\nwrite_blog_task \n=\n Task(\n\n\n description\n=\n\"Write a full blog post about the importance of AI and its latest news\"\n,\n\n\n expected_output\n=\n\"Full blog post that is 4 paragraphs long\"\n,\n\n\n agent\n=\nwriter_agent,\n\n\n context\n=\n[research_ai_task, research_ops_task]\n\n\n)\n\n\n\n\n#...\n\n\n\n\n​\nAsynchronous Execution\n\n\nYou can define a task to be executed asynchronously. This means that the crew will not wait for it to be completed to continue with the next task. This is useful for tasks that take a long time to be completed, or that are not crucial for the next tasks to be performed.\n\n\nYou can then use the \ncontext\n attribute to define in a future task that it should wait for the output of the asynchronous task to be completed.\n\n\nCode\nCopy\nAsk AI\n#...\n\n\n\n\nlist_ideas \n=\n Task(\n\n\n description\n=\n\"List of 5 interesting ideas to explore for an article about AI.\"\n,\n\n\n expected_output\n=\n\"Bullet point list of 5 ideas for an article.\"\n,\n\n\n agent\n=\nresearcher,\n\n\n async_execution\n=\nTrue\n # Will be executed asynchronously\n\n\n)\n\n\n\n\nlist_important_history \n=\n Task(\n\n\n description\n=\n\"Research the history of AI and give me the 5 most important events.\"\n,\n\n\n expected_output\n=\n\"Bullet point list of 5 important events.\"\n,\n\n\n agent\n=\nresearcher,\n\n\n async_execution\n=\nTrue\n # Will be executed asynchronously\n\n\n)\n\n\n\n\nwrite_article \n=\n Task(\n\n\n description\n=\n\"Write an article about AI, its history, and interesting ideas.\"\n,\n\n\n expected_output\n=\n\"A 4 paragraph article about AI.\"\n,\n\n\n agent\n=\nwriter,\n\n\n context\n=\n[list_ideas, list_important_history] \n# Will wait for the output of the two tasks to be completed\n\n\n)\n\n\n\n\n#...\n\n\n\n\n​\nCallback Mechanism\n\n\nThe callback function is executed after the task is completed, allowing for actions or notifications to be triggered based on the task’s outcome.\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\n\n\ndef\n callback_function\n(\noutput\n: TaskOutput):\n\n\n # Do something after the task is completed\n\n\n # Example: Send an email to the manager\n\n\n print\n(\nf\n\"\"\"\n\n\n Task completed!\n\n\n Task: \n{\noutput.description\n}\n\n\n Output: \n{\noutput.raw\n}\n\n\n \"\"\"\n)\n\n\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool],\n\n\n callback\n=\ncallback_function\n\n\n)\n\n\n\n\n#...\n\n\n\n\n​\nAccessing a Specific Task Output\n\n\nOnce a crew finishes running, you can access the output of a specific task by using the \noutput\n attribute of the task object:\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\ntask1 \n=\n Task(\n\n\n description\n=\n'Find and summarize the latest AI news'\n,\n\n\n expected_output\n=\n'A bullet list summary of the top 5 most important AI news'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[search_tool]\n\n\n)\n\n\n\n\n#...\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent],\n\n\n tasks\n=\n[task1, task2, task3],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff()\n\n\n\n\n# Returns a TaskOutput object with the description and results of the task\n\n\nprint\n(\nf\n\"\"\"\n\n\n Task completed!\n\n\n Task: \n{\ntask1.output.description\n}\n\n\n Output: \n{\ntask1.output.raw\n}\n\n\n\"\"\"\n)\n\n\n\n\n​\nTool Override Mechanism\n\n\nSpecifying tools in a task allows for dynamic adaptation of agent capabilities, emphasizing CrewAI’s flexibility.\n\n\n​\nError Handling and Validation Mechanisms\n\n\nWhile creating and executing tasks, certain validation mechanisms are in place to ensure the robustness and reliability of task attributes. These include but are not limited to:\n\n\n\n\nEnsuring only one output type is set per task to maintain clear output expectations.\n\n\nPreventing the manual assignment of the \nid\n attribute to uphold the integrity of the unique identifier system.\n\n\n\n\nThese validations help in maintaining the consistency and reliability of task executions within the crewAI framework.\n\n\n​\nTask Guardrails\n\n\nTask guardrails provide a powerful way to validate, transform, or filter task outputs before they are passed to the next task. Guardrails are optional functions that execute before the next task starts, allowing you to ensure that task outputs meet specific requirements or formats.\n\n\n​\nBasic Usage\n\n\n​\nDefine your own logic to validate\n\n\nCode\nCopy\nAsk AI\nfrom\n typing \nimport\n Tuple, Union\n\n\nfrom\n crewai \nimport\n Task\n\n\n\n\ndef\n validate_json_output\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\ndict\n, \nstr\n]]:\n\n\n \"\"\"Validate that the output is valid JSON.\"\"\"\n\n\n try\n:\n\n\n json_data \n=\n json.loads(result)\n\n\n return\n (\nTrue\n, json_data)\n\n\n except\n json.JSONDecodeError:\n\n\n return\n (\nFalse\n, \n\"Output must be valid JSON\"\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate JSON data\"\n,\n\n\n expected_output\n=\n\"Valid JSON object\"\n,\n\n\n guardrail\n=\nvalidate_json_output\n\n\n)\n\n\n\n\n​\nLeverage a no-code approach for validation\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Task\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate JSON data\"\n,\n\n\n expected_output\n=\n\"Valid JSON object\"\n,\n\n\n guardrail\n=\n\"Ensure the response is a valid JSON object\"\n\n\n)\n\n\n\n\n​\nUsing YAML\n\n\nCopy\nAsk AI\nresearch_task\n:\n\n\n ...\n\n\n guardrail\n: \nmake sure each bullet contains a minimum of 100 words\n\n\n ...\n\n\n\n\nCode\nCopy\nAsk AI\n@CrewBase\n\n\nclass\n InternalCrew\n:\n\n\n agents_config \n=\n \"config/agents.yaml\"\n\n\n tasks_config \n=\n \"config/tasks.yaml\"\n\n\n\n\n ...\n\n\n @task\n\n\n def\n research_task\n(\nself\n):\n\n\n return\n Task(\nconfig\n=\nself\n.tasks_config[\n\"research_task\"\n]) \n# type: ignore[index]\n\n\n ...\n\n\n\n\n​\nUse custom models for code generation\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Task\n\n\nfrom\n crewai.llm \nimport\n LLM\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Generate JSON data\"\n,\n\n\n expected_output\n=\n\"Valid JSON object\"\n,\n\n\n guardrail\n=\nLLMGuardrail(\n\n\n description\n=\n\"Ensure the response is a valid JSON object\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4o-mini\"\n),\n\n\n )\n\n\n)\n\n\n\n\n​\nHow Guardrails Work\n\n\n\n\nOptional Attribute\n: Guardrails are an optional attribute at the task level, allowing you to add validation only where needed.\n\n\nExecution Timing\n: The guardrail function is executed before the next task starts, ensuring valid data flow between tasks.\n\n\nReturn Format\n: Guardrails must return a tuple of \n(success, data)\n:\n\n\n\n\nIf \nsuccess\n is \nTrue\n, \ndata\n is the validated/transformed result\n\n\nIf \nsuccess\n is \nFalse\n, \ndata\n is the error message\n\n\n\n\n\n\nResult Routing\n:\n\n\n\n\nOn success (\nTrue\n), the result is automatically passed to the next task\n\n\nOn failure (\nFalse\n), the error is sent back to the agent to generate a new answer\n\n\n\n\n\n\n\n\n​\nCommon Use Cases\n\n\n​\nData Format Validation\n\n\nCode\nCopy\nAsk AI\ndef\n validate_email_format\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\nstr\n, \nstr\n]]:\n\n\n \"\"\"Ensure the output contains a valid email address.\"\"\"\n\n\n import\n re\n\n\n email_pattern \n=\n r\n'\n^\n[\n\\w\n\\.\n-\n]\n+\n@\n[\n\\w\n\\.\n-\n]\n+\n\\.\n\\w\n+\n$\n'\n\n\n if\n re.match(email_pattern, result.strip()):\n\n\n return\n (\nTrue\n, result.strip())\n\n\n return\n (\nFalse\n, \n\"Output must be a valid email address\"\n)\n\n\n\n\n​\nContent Filtering\n\n\nCode\nCopy\nAsk AI\ndef\n filter_sensitive_info\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\nstr\n, \nstr\n]]:\n\n\n \"\"\"Remove or validate sensitive information.\"\"\"\n\n\n sensitive_patterns \n=\n [\n'SSN:'\n, \n'password:'\n, \n'secret:'\n]\n\n\n for\n pattern \nin\n sensitive_patterns:\n\n\n if\n pattern.lower() \nin\n result.lower():\n\n\n return\n (\nFalse\n, \nf\n\"Output contains sensitive information (\n{\npattern\n}\n)\"\n)\n\n\n return\n (\nTrue\n, result)\n\n\n\n\n​\nData Transformation\n\n\nCode\nCopy\nAsk AI\ndef\n normalize_phone_number\n(\nresult\n: \nstr\n) -> Tuple[\nbool\n, Union[\nstr\n, \nstr\n]]:\n\n\n \"\"\"Ensure phone numbers are in a consistent format.\"\"\"\n\n\n import\n re\n\n\n digits \n=\n re.sub(\nr\n'\n\\D\n'\n, \n''\n, result)\n\n\n if\n len\n(digits) \n==\n 10\n:\n\n\n formatted \n=\n f\n\"(\n{\ndigits[:\n3\n]\n}\n) \n{\ndigits[\n3\n:\n6\n]\n}\n-\n{\ndigits[\n6\n:]\n}\n\"\n\n\n return\n (\nTrue\n, formatted)\n\n\n return\n (\nFalse\n, \n\"Output must be a 10-digit phone number\"\n)\n\n\n\n\n​\nAdvanced Features\n\n\n​\nChaining Multiple Validations\n\n\nCode\nCopy\nAsk AI\ndef\n chain_validations\n(\n*\nvalidators\n):\n\n\n \"\"\"Chain multiple validators together.\"\"\"\n\n\n def\n combined_validator\n(\nresult\n):\n\n\n for\n validator \nin\n validators:\n\n\n success, data \n=\n validator(result)\n\n\n if\n not\n success:\n\n\n return\n (\nFalse\n, data)\n\n\n result \n=\n data\n\n\n return\n (\nTrue\n, result)\n\n\n return\n combined_validator\n\n\n\n\n# Usage\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Get user contact info\"\n,\n\n\n expected_output\n=\n\"Email and phone\"\n,\n\n\n guardrail\n=\nchain_validations(\n\n\n validate_email_format,\n\n\n filter_sensitive_info\n\n\n )\n\n\n)\n\n\n\n\n​\nCustom Retry Logic\n\n\nCode\nCopy\nAsk AI\ntask \n=\n Task(\n\n\n description\n=\n\"Generate data\"\n,\n\n\n expected_output\n=\n\"Valid data\"\n,\n\n\n guardrail\n=\nvalidate_data,\n\n\n max_retries\n=\n5\n # Override default retry limit\n\n\n)\n\n\n\n\n​\nCreating Directories when Saving Files\n\n\nYou can now specify if a task should create directories when saving its output to a file. This is particularly useful for organizing outputs and ensuring that file paths are correctly structured.\n\n\nCode\nCopy\nAsk AI\n# ...\n\n\n\n\nsave_output_task \n=\n Task(\n\n\n description\n=\n'Save the summarized AI news to a file'\n,\n\n\n expected_output\n=\n'File saved successfully'\n,\n\n\n agent\n=\nresearch_agent,\n\n\n tools\n=\n[file_save_tool],\n\n\n output_file\n=\n'outputs/ai_news_summary.txt'\n,\n\n\n create_directory\n=\nTrue\n\n\n)\n\n\n\n\n#...\n\n\n\n\nCheck out the video below to see how to use structured outputs in CrewAI:\n\n\n\n\n​\nConclusion\n\n\nTasks are the driving force behind the actions of agents in CrewAI.\nBy properly defining tasks and their outcomes, you set the stage for your AI agents to work effectively, either independently or as a collaborative unit.\nEquipping tasks with appropriate tools, understanding the execution process, and following robust validation practices are crucial for maximizing CrewAI’s potential,\nensuring agents are effectively prepared for their assignments and that tasks are executed as intended.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nAgents\nCrews\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nTask Execution Flow\nTask Attributes\nCreating Tasks\nYAML Configuration (Recommended)\nDirect Code Definition (Alternative)\nTask Output\nTask Output Attributes\nTask Methods and Properties\nAccessing Task Outputs\nExample\nMarkdown Output Formatting\nUsing Markdown Formatting\nYAML Configuration with Markdown\nBenefits of Markdown Output\nTask Dependencies and Context\nTask Guardrails\nUsing Task Guardrails\nGuardrail Function Requirements\nLLMGuardrail\nError Handling Best Practices\nHandling Guardrail Results\nGetting Structured Consistent Outputs from Tasks\nUsing output_pydantic\nExplanation of Accessing the Output\nUsing output_json\nExplanation of Accessing the Output\nIntegrating Tools with Tasks\nCreating a Task with Tools\nReferring to Other Tasks\nAsynchronous Execution\nCallback Mechanism\nAccessing a Specific Task Output\nTool Override Mechanism\nError Handling and Validation Mechanisms\nTask Guardrails\nBasic Usage\nDefine your own logic to validate\nLeverage a no-code approach for validation\nUsing YAML\nUse custom models for code generation\nHow Guardrails Work\nCommon Use Cases\nData Format Validation\nContent Filtering\nData Transformation\nAdvanced Features\nChaining Multiple Validations\nCustom Retry Logic\nCreating Directories when Saving Files\nConclusion" }, { "source": "https://docs.crewai.com/en/learn/replay-tasks-from-latest-crew-kickoff", "title": "Replay Tasks from Latest Crew Kickoff - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nReplay Tasks from Latest Crew Kickoff\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nReplay Tasks from Latest Crew Kickoff\nCopy page\nReplay tasks from the latest crew.kickoff(…)\n​\nIntroduction\n\n\nCrewAI provides the ability to replay from a task specified from the latest crew kickoff. This feature is particularly useful when you’ve finished a kickoff and may want to retry certain tasks or don’t need to refetch data over and your agents already have the context saved from the kickoff execution so you just need to replay the tasks you want to.\n\n\nYou must run \ncrew.kickoff()\n before you can replay a task.\nCurrently, only the latest kickoff is supported, so if you use \nkickoff_for_each\n, it will only allow you to replay from the most recent crew run.\n\n\nHere’s an example of how to replay from a task:\n\n\n​\nReplaying from Specific Task Using the CLI\n\n\nTo use the replay feature, follow these steps:\n\n\n1\nOpen your terminal or command prompt.\n2\nNavigate to the directory where your CrewAI project is located.\n3\nRun the following commands:\nTo view the latest kickoff task_ids use:\nCopy\nAsk AI\ncrewai\n log-tasks-outputs\n\n\nOnce you have your \ntask_id\n to replay, use:\nCopy\nAsk AI\ncrewai\n replay\n -t\n <\ntask_i\nd\n>\n\n\n\n\nEnsure \ncrewai\n is installed and configured correctly in your development environment.\n\n\n​\nReplaying from a Task Programmatically\n\n\nTo replay from a task programmatically, use the following steps:\n\n\n1\nSpecify the `task_id` and input parameters for the replay process.\nSpecify the \ntask_id\n and input parameters for the replay process.\n2\nExecute the replay command within a try-except block to handle potential errors.\nExecute the replay command within a try-except block to handle potential errors.\nCode\nCopy\nAsk AI\n def\n replay\n():\n\n\n \"\"\"\n\n\n Replay the crew execution from a specific task.\n\n\n \"\"\"\n\n\n task_id \n=\n ''\n\n\n inputs \n=\n {\n\"topic\"\n: \n\"CrewAI Training\"\n} \n# This is optional; you can pass in the inputs you want to replay; otherwise, it uses the previous kickoff's inputs.\n\n\n try\n:\n\n\n YourCrewName_Crew().crew().replay(\ntask_id\n=\ntask_id, \ninputs\n=\ninputs)\n\n\n\n\n except\n subprocess.CalledProcessError \nas\n e:\n\n\n raise\n Exception\n(\nf\n\"An error occurred while replaying the crew: \n{\ne\n}\n\"\n)\n\n\n\n\n except\n Exception\n as\n e:\n\n\n raise\n Exception\n(\nf\n\"An unexpected error occurred: \n{\ne\n}\n\"\n)\n\n\n\n\n​\nConclusion\n\n\nWith the above enhancements and detailed functionality, replaying specific tasks in CrewAI has been made more efficient and robust.\nEnsure you follow the commands and steps precisely to make the most of these features.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nUsing Multimodal Agents\nSequential Processes\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nReplaying from Specific Task Using the CLI\nReplaying from a Task Programmatically\nConclusion\nLearn\nReplay Tasks from Latest Crew Kickoff\nCopy page\nReplay tasks from the latest crew.kickoff(…)\n​\nIntroduction\n\n\nCrewAI provides the ability to replay from a task specified from the latest crew kickoff. This feature is particularly useful when you’ve finished a kickoff and may want to retry certain tasks or don’t need to refetch data over and your agents already have the context saved from the kickoff execution so you just need to replay the tasks you want to.\n\n\nYou must run \ncrew.kickoff()\n before you can replay a task.\nCurrently, only the latest kickoff is supported, so if you use \nkickoff_for_each\n, it will only allow you to replay from the most recent crew run.\n\n\nHere’s an example of how to replay from a task:\n\n\n​\nReplaying from Specific Task Using the CLI\n\n\nTo use the replay feature, follow these steps:\n\n\n1\nOpen your terminal or command prompt.\n2\nNavigate to the directory where your CrewAI project is located.\n3\nRun the following commands:\nTo view the latest kickoff task_ids use:\nCopy\nAsk AI\ncrewai\n log-tasks-outputs\n\n\nOnce you have your \ntask_id\n to replay, use:\nCopy\nAsk AI\ncrewai\n replay\n -t\n <\ntask_i\nd\n>\n\n\n\n\nEnsure \ncrewai\n is installed and configured correctly in your development environment.\n\n\n​\nReplaying from a Task Programmatically\n\n\nTo replay from a task programmatically, use the following steps:\n\n\n1\nSpecify the `task_id` and input parameters for the replay process.\nSpecify the \ntask_id\n and input parameters for the replay process.\n2\nExecute the replay command within a try-except block to handle potential errors.\nExecute the replay command within a try-except block to handle potential errors.\nCode\nCopy\nAsk AI\n def\n replay\n():\n\n\n \"\"\"\n\n\n Replay the crew execution from a specific task.\n\n\n \"\"\"\n\n\n task_id \n=\n ''\n\n\n inputs \n=\n {\n\"topic\"\n: \n\"CrewAI Training\"\n} \n# This is optional; you can pass in the inputs you want to replay; otherwise, it uses the previous kickoff's inputs.\n\n\n try\n:\n\n\n YourCrewName_Crew().crew().replay(\ntask_id\n=\ntask_id, \ninputs\n=\ninputs)\n\n\n\n\n except\n subprocess.CalledProcessError \nas\n e:\n\n\n raise\n Exception\n(\nf\n\"An error occurred while replaying the crew: \n{\ne\n}\n\"\n)\n\n\n\n\n except\n Exception\n as\n e:\n\n\n raise\n Exception\n(\nf\n\"An unexpected error occurred: \n{\ne\n}\n\"\n)\n\n\n\n\n​\nConclusion\n\n\nWith the above enhancements and detailed functionality, replaying specific tasks in CrewAI has been made more efficient and robust.\nEnsure you follow the commands and steps precisely to make the most of these features.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nUsing Multimodal Agents\nSequential Processes\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nReplaying from Specific Task Using the CLI\nReplaying from a Task Programmatically\nConclusion" }, { "source": "https://docs.crewai.com/en/mcp/sse", "title": "SSE Transport - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nMCP Integration\nSSE Transport\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nMCP Integration\nSSE Transport\nCopy page\nLearn how to connect CrewAI to remote MCP servers using Server-Sent Events (SSE) for real-time communication.\n​\nOverview\n\n\nServer-Sent Events (SSE) provide a standard way for a web server to send updates to a client over a single, long-lived HTTP connection. In the context of MCP, SSE is used for remote servers to stream data (like tool responses) to your CrewAI application in real-time.\n\n\n​\nKey Concepts\n\n\n\n\nRemote Servers\n: SSE is suitable for MCP servers hosted remotely.\n\n\nUnidirectional Stream\n: Typically, SSE is a one-way communication channel from server to client.\n\n\nMCPServerAdapter\n Configuration\n: For SSE, you’ll provide the server’s URL and specify the transport type.\n\n\n\n\n​\nConnecting via SSE\n\n\nYou can connect to an SSE-based MCP server using two main approaches for managing the connection lifecycle:\n\n\n​\n1. Fully Managed Connection (Recommended)\n\n\nUsing a Python context manager (\nwith\n statement) is the recommended approach. It automatically handles establishing and closing the connection to the SSE MCP server.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n, \n# Replace with your actual SSE server URL\n\n\n \"transport\"\n: \n\"sse\"\n \n\n\n}\n\n\n\n\n# Using MCPServerAdapter with a context manager\n\n\ntry\n:\n\n\n with\n MCPServerAdapter(server_params) \nas\n tools:\n\n\n print\n(\nf\n\"Available tools from SSE MCP server: \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n # Example: Using a tool from the SSE MCP server\n\n\n sse_agent \n=\n Agent(\n\n\n role\n=\n\"Remote Service User\"\n,\n\n\n goal\n=\n\"Utilize a tool provided by a remote SSE MCP server.\"\n,\n\n\n backstory\n=\n\"An AI agent that connects to external services via SSE.\"\n,\n\n\n tools\n=\ntools,\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n sse_task \n=\n Task(\n\n\n description\n=\n\"Fetch real-time stock updates for 'AAPL' using an SSE tool.\"\n,\n\n\n expected_output\n=\n\"The latest stock price for AAPL.\"\n,\n\n\n agent\n=\nsse_agent,\n\n\n markdown\n=\nTrue\n\n\n )\n\n\n\n\n sse_crew \n=\n Crew(\n\n\n agents\n=\n[sse_agent],\n\n\n tasks\n=\n[sse_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n if\n tools: \n# Only kickoff if tools were loaded\n\n\n result \n=\n sse_crew.kickoff() \n# Add inputs={'stock_symbol': 'AAPL'} if tool requires it\n\n\n print\n(\n\"\n\\n\nCrew Task Result (SSE - Managed):\n\\n\n\"\n, result)\n\n\n else\n:\n\n\n print\n(\n\"Skipping crew kickoff as tools were not loaded (check server connection).\"\n)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Error connecting to or using SSE MCP server (Managed): \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the SSE MCP server is running and accessible at the specified URL.\"\n)\n\n\n\n\n\n\nReplace \n\"http://localhost:8000/sse\"\n with the actual URL of your SSE MCP server.\n\n\n​\n2. Manual Connection Lifecycle\n\n\nIf you need finer-grained control, you can manage the \nMCPServerAdapter\n connection lifecycle manually.\n\n\nYou \nMUST\n call \nmcp_server_adapter.stop()\n to ensure the connection is closed and resources are released. Using a \ntry...finally\n block is highly recommended.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n, \n# Replace with your actual SSE server URL\n\n\n \"transport\"\n: \n\"sse\"\n\n\n}\n\n\n\n\nmcp_server_adapter \n=\n None\n \n\n\ntry\n:\n\n\n mcp_server_adapter \n=\n MCPServerAdapter(server_params)\n\n\n mcp_server_adapter.start()\n\n\n tools \n=\n mcp_server_adapter.tools\n\n\n print\n(\nf\n\"Available tools (manual SSE): \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n manual_sse_agent \n=\n Agent(\n\n\n role\n=\n\"Remote Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data fetched from a remote SSE MCP server using manual connection management.\"\n,\n\n\n backstory\n=\n\"An AI skilled in handling SSE connections explicitly.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n \n\n\n analysis_task \n=\n Task(\n\n\n description\n=\n\"Fetch and analyze the latest user activity trends from the SSE server.\"\n,\n\n\n expected_output\n=\n\"A summary report of user activity trends.\"\n,\n\n\n agent\n=\nmanual_sse_agent\n\n\n )\n\n\n \n\n\n analysis_crew \n=\n Crew(\n\n\n agents\n=\n[manual_sse_agent],\n\n\n tasks\n=\n[analysis_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n result \n=\n analysis_crew.kickoff()\n\n\n print\n(\n\"\n\\n\nCrew Task Result (SSE - Manual):\n\\n\n\"\n, result)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"An error occurred during manual SSE MCP integration: \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the SSE MCP server is running and accessible.\"\n)\n\n\nfinally\n:\n\n\n if\n mcp_server_adapter \nand\n mcp_server_adapter.is_connected:\n\n\n print\n(\n\"Stopping SSE MCP server connection (manual)...\"\n)\n\n\n mcp_server_adapter.stop() \n# **Crucial: Ensure stop is called**\n\n\n elif\n mcp_server_adapter:\n\n\n print\n(\n\"SSE MCP server adapter was not connected. No stop needed or start failed.\"\n)\n\n\n\n\n\n\n​\nSecurity Considerations for SSE\n\n\nDNS Rebinding Attacks\n: SSE transports can be vulnerable to DNS rebinding attacks if the MCP server is not properly secured. This could allow malicious websites to interact with local or intranet-based MCP servers.\n\n\nTo mitigate this risk:\n\n\n\n\nMCP server implementations should \nvalidate \nOrigin\n headers\n on incoming SSE connections.\n\n\nWhen running local SSE MCP servers for development, \nbind only to \nlocalhost\n (\n127.0.0.1\n)\n rather than all network interfaces (\n0.0.0.0\n).\n\n\nImplement \nproper authentication\n for all SSE connections if they expose sensitive tools or data.\n\n\n\n\nFor a comprehensive overview of security best practices, please refer to our \nSecurity Considerations\n page and the official \nMCP Transport Security documentation\n.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nStdio Transport\nStreamable HTTP Transport\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nKey Concepts\nConnecting via SSE\n1. Fully Managed Connection (Recommended)\n2. Manual Connection Lifecycle\nSecurity Considerations for SSE\nMCP Integration\nSSE Transport\nCopy page\nLearn how to connect CrewAI to remote MCP servers using Server-Sent Events (SSE) for real-time communication.\n​\nOverview\n\n\nServer-Sent Events (SSE) provide a standard way for a web server to send updates to a client over a single, long-lived HTTP connection. In the context of MCP, SSE is used for remote servers to stream data (like tool responses) to your CrewAI application in real-time.\n\n\n​\nKey Concepts\n\n\n\n\nRemote Servers\n: SSE is suitable for MCP servers hosted remotely.\n\n\nUnidirectional Stream\n: Typically, SSE is a one-way communication channel from server to client.\n\n\nMCPServerAdapter\n Configuration\n: For SSE, you’ll provide the server’s URL and specify the transport type.\n\n\n\n\n​\nConnecting via SSE\n\n\nYou can connect to an SSE-based MCP server using two main approaches for managing the connection lifecycle:\n\n\n​\n1. Fully Managed Connection (Recommended)\n\n\nUsing a Python context manager (\nwith\n statement) is the recommended approach. It automatically handles establishing and closing the connection to the SSE MCP server.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n, \n# Replace with your actual SSE server URL\n\n\n \"transport\"\n: \n\"sse\"\n \n\n\n}\n\n\n\n\n# Using MCPServerAdapter with a context manager\n\n\ntry\n:\n\n\n with\n MCPServerAdapter(server_params) \nas\n tools:\n\n\n print\n(\nf\n\"Available tools from SSE MCP server: \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n # Example: Using a tool from the SSE MCP server\n\n\n sse_agent \n=\n Agent(\n\n\n role\n=\n\"Remote Service User\"\n,\n\n\n goal\n=\n\"Utilize a tool provided by a remote SSE MCP server.\"\n,\n\n\n backstory\n=\n\"An AI agent that connects to external services via SSE.\"\n,\n\n\n tools\n=\ntools,\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n sse_task \n=\n Task(\n\n\n description\n=\n\"Fetch real-time stock updates for 'AAPL' using an SSE tool.\"\n,\n\n\n expected_output\n=\n\"The latest stock price for AAPL.\"\n,\n\n\n agent\n=\nsse_agent,\n\n\n markdown\n=\nTrue\n\n\n )\n\n\n\n\n sse_crew \n=\n Crew(\n\n\n agents\n=\n[sse_agent],\n\n\n tasks\n=\n[sse_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n if\n tools: \n# Only kickoff if tools were loaded\n\n\n result \n=\n sse_crew.kickoff() \n# Add inputs={'stock_symbol': 'AAPL'} if tool requires it\n\n\n print\n(\n\"\n\\n\nCrew Task Result (SSE - Managed):\n\\n\n\"\n, result)\n\n\n else\n:\n\n\n print\n(\n\"Skipping crew kickoff as tools were not loaded (check server connection).\"\n)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"Error connecting to or using SSE MCP server (Managed): \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the SSE MCP server is running and accessible at the specified URL.\"\n)\n\n\n\n\n\n\nReplace \n\"http://localhost:8000/sse\"\n with the actual URL of your SSE MCP server.\n\n\n​\n2. Manual Connection Lifecycle\n\n\nIf you need finer-grained control, you can manage the \nMCPServerAdapter\n connection lifecycle manually.\n\n\nYou \nMUST\n call \nmcp_server_adapter.stop()\n to ensure the connection is closed and resources are released. Using a \ntry...finally\n block is highly recommended.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n, \n# Replace with your actual SSE server URL\n\n\n \"transport\"\n: \n\"sse\"\n\n\n}\n\n\n\n\nmcp_server_adapter \n=\n None\n \n\n\ntry\n:\n\n\n mcp_server_adapter \n=\n MCPServerAdapter(server_params)\n\n\n mcp_server_adapter.start()\n\n\n tools \n=\n mcp_server_adapter.tools\n\n\n print\n(\nf\n\"Available tools (manual SSE): \n{\n[tool.name \nfor\n tool \nin\n tools]\n}\n\"\n)\n\n\n\n\n manual_sse_agent \n=\n Agent(\n\n\n role\n=\n\"Remote Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data fetched from a remote SSE MCP server using manual connection management.\"\n,\n\n\n backstory\n=\n\"An AI skilled in handling SSE connections explicitly.\"\n,\n\n\n tools\n=\ntools,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n \n\n\n analysis_task \n=\n Task(\n\n\n description\n=\n\"Fetch and analyze the latest user activity trends from the SSE server.\"\n,\n\n\n expected_output\n=\n\"A summary report of user activity trends.\"\n,\n\n\n agent\n=\nmanual_sse_agent\n\n\n )\n\n\n \n\n\n analysis_crew \n=\n Crew(\n\n\n agents\n=\n[manual_sse_agent],\n\n\n tasks\n=\n[analysis_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n )\n\n\n \n\n\n result \n=\n analysis_crew.kickoff()\n\n\n print\n(\n\"\n\\n\nCrew Task Result (SSE - Manual):\n\\n\n\"\n, result)\n\n\n\n\nexcept\n Exception\n as\n e:\n\n\n print\n(\nf\n\"An error occurred during manual SSE MCP integration: \n{\ne\n}\n\"\n)\n\n\n print\n(\n\"Ensure the SSE MCP server is running and accessible.\"\n)\n\n\nfinally\n:\n\n\n if\n mcp_server_adapter \nand\n mcp_server_adapter.is_connected:\n\n\n print\n(\n\"Stopping SSE MCP server connection (manual)...\"\n)\n\n\n mcp_server_adapter.stop() \n# **Crucial: Ensure stop is called**\n\n\n elif\n mcp_server_adapter:\n\n\n print\n(\n\"SSE MCP server adapter was not connected. No stop needed or start failed.\"\n)\n\n\n\n\n\n\n​\nSecurity Considerations for SSE\n\n\nDNS Rebinding Attacks\n: SSE transports can be vulnerable to DNS rebinding attacks if the MCP server is not properly secured. This could allow malicious websites to interact with local or intranet-based MCP servers.\n\n\nTo mitigate this risk:\n\n\n\n\nMCP server implementations should \nvalidate \nOrigin\n headers\n on incoming SSE connections.\n\n\nWhen running local SSE MCP servers for development, \nbind only to \nlocalhost\n (\n127.0.0.1\n)\n rather than all network interfaces (\n0.0.0.0\n).\n\n\nImplement \nproper authentication\n for all SSE connections if they expose sensitive tools or data.\n\n\n\n\nFor a comprehensive overview of security best practices, please refer to our \nSecurity Considerations\n page and the official \nMCP Transport Security documentation\n.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nStdio Transport\nStreamable HTTP Transport\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nKey Concepts\nConnecting via SSE\n1. Fully Managed Connection (Recommended)\n2. Manual Connection Lifecycle\nSecurity Considerations for SSE" }, { "source": "https://docs.crewai.com/en/learn/llm-connections", "title": "Connect to any LLM - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nConnect to any LLM\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nConnect to any LLM\nCopy page\nComprehensive guide on integrating CrewAI with various Large Language Models (LLMs) using LiteLLM, including supported providers and configuration options.\n​\nConnect CrewAI to LLMs\n\n\nCrewAI uses LiteLLM to connect to a wide variety of Language Models (LLMs). This integration provides extensive versatility, allowing you to use models from numerous providers with a simple, unified interface.\n\n\nBy default, CrewAI uses the \ngpt-4o-mini\n model. This is determined by the \nOPENAI_MODEL_NAME\n environment variable, which defaults to “gpt-4o-mini” if not set.\nYou can easily configure your agents to use a different model or provider as described in this guide.\n\n\n​\nSupported Providers\n\n\nLiteLLM supports a wide range of providers, including but not limited to:\n\n\n\n\nOpenAI\n\n\nAnthropic\n\n\nGoogle (Vertex AI, Gemini)\n\n\nAzure OpenAI\n\n\nAWS (Bedrock, SageMaker)\n\n\nCohere\n\n\nVoyageAI\n\n\nHugging Face\n\n\nOllama\n\n\nMistral AI\n\n\nReplicate\n\n\nTogether AI\n\n\nAI21\n\n\nCloudflare Workers AI\n\n\nDeepInfra\n\n\nGroq\n\n\nSambaNova\n\n\nNebius AI Studio\n\n\nNVIDIA NIMs\n\n\nAnd many more!\n\n\n\n\nFor a complete and up-to-date list of supported providers, please refer to the \nLiteLLM Providers documentation\n.\n\n\n​\nChanging the LLM\n\n\nTo use a different LLM with your CrewAI agents, you have several options:\n\n\nUsing a String Identifier\nUsing the LLM Class\nPass the model name as a string when initializing the agent:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\n# Using OpenAI's GPT-4\n\n\nopenai_agent \n=\n Agent(\n\n\n role\n=\n'OpenAI Expert'\n,\n\n\n goal\n=\n'Provide insights using GPT-4'\n,\n\n\n backstory\n=\n\"An AI assistant powered by OpenAI's latest model.\"\n,\n\n\n llm\n=\n'gpt-4'\n\n\n)\n\n\n\n\n# Using Anthropic's Claude\n\n\nclaude_agent \n=\n Agent(\n\n\n role\n=\n'Anthropic Expert'\n,\n\n\n goal\n=\n'Analyze data using Claude'\n,\n\n\n backstory\n=\n\"An AI assistant leveraging Anthropic's language model.\"\n,\n\n\n llm\n=\n'claude-2'\n\n\n)\n\n\nPass the model name as a string when initializing the agent:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\n# Using OpenAI's GPT-4\n\n\nopenai_agent \n=\n Agent(\n\n\n role\n=\n'OpenAI Expert'\n,\n\n\n goal\n=\n'Provide insights using GPT-4'\n,\n\n\n backstory\n=\n\"An AI assistant powered by OpenAI's latest model.\"\n,\n\n\n llm\n=\n'gpt-4'\n\n\n)\n\n\n\n\n# Using Anthropic's Claude\n\n\nclaude_agent \n=\n Agent(\n\n\n role\n=\n'Anthropic Expert'\n,\n\n\n goal\n=\n'Analyze data using Claude'\n,\n\n\n backstory\n=\n\"An AI assistant leveraging Anthropic's language model.\"\n,\n\n\n llm\n=\n'claude-2'\n\n\n)\n\n\nFor more detailed configuration, use the LLM class:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gpt-4\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n base_url\n=\n\"https://api.openai.com/v1\"\n,\n\n\n api_key\n=\n\"your-api-key-here\"\n\n\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n'Customized LLM Expert'\n,\n\n\n goal\n=\n'Provide tailored responses'\n,\n\n\n backstory\n=\n\"An AI assistant with custom LLM settings.\"\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\n\n\n​\nConfiguration Options\n\n\nWhen configuring an LLM for your agent, you have access to a wide range of parameters:\n\n\nParameter\nType\nDescription\nmodel\nstr\nThe name of the model to use (e.g., “gpt-4”, “claude-2”)\ntemperature\nfloat\nControls randomness in output (0.0 to 1.0)\nmax_tokens\nint\nMaximum number of tokens to generate\ntop_p\nfloat\nControls diversity of output (0.0 to 1.0)\nfrequency_penalty\nfloat\nPenalizes new tokens based on their frequency in the text so far\npresence_penalty\nfloat\nPenalizes new tokens based on their presence in the text so far\nstop\nstr\n, \nList[str]\nSequence(s) to stop generation\nbase_url\nstr\nThe base URL for the API endpoint\napi_key\nstr\nYour API key for authentication\n\n\nFor a complete list of parameters and their descriptions, refer to the LLM class documentation.\n\n\n​\nConnecting to OpenAI-Compatible LLMs\n\n\nYou can connect to OpenAI-compatible LLMs using either environment variables or by setting specific attributes on the LLM class:\n\n\nUsing Environment Variables\nUsing LLM Class Attributes\nGeneric\nGoogle\nCopy\nAsk AI\nimport\n os\n\n\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"your-api-key\"\n\n\nos.environ[\n\"OPENAI_API_BASE\"\n] \n=\n \"https://api.your-provider.com/v1\"\n\n\nos.environ[\n\"OPENAI_MODEL_NAME\"\n] \n=\n \"your-model-name\"\n\n\nGeneric\nGoogle\nCopy\nAsk AI\nimport\n os\n\n\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"your-api-key\"\n\n\nos.environ[\n\"OPENAI_API_BASE\"\n] \n=\n \"https://api.your-provider.com/v1\"\n\n\nos.environ[\n\"OPENAI_MODEL_NAME\"\n] \n=\n \"your-model-name\"\n\n\nGeneric\nGoogle\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"custom-model-name\"\n,\n\n\n api_key\n=\n\"your-api-key\"\n,\n\n\n base_url\n=\n\"https://api.your-provider.com/v1\"\n\n\n)\n\n\nagent \n=\n Agent(\nllm\n=\nllm, \n...\n)\n\n\n\n\n​\nUsing Local Models with Ollama\n\n\nFor local models like those provided by Ollama:\n\n\n1\nDownload and install Ollama\nClick here to download and install Ollama\n2\nPull the desired model\nFor example, run \nollama pull llama3.2\n to download the model.\n3\nConfigure your agent\nCode\nCopy\nAsk AI\n agent \n=\n Agent(\n\n\n role\n=\n'Local AI Expert'\n,\n\n\n goal\n=\n'Process information using a local model'\n,\n\n\n backstory\n=\n\"An AI assistant running on local hardware.\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"ollama/llama3.2\"\n, \nbase_url\n=\n\"http://localhost:11434\"\n)\n\n\n )\n\n\n\n\n​\nChanging the Base API URL\n\n\nYou can change the base API URL for any LLM provider by setting the \nbase_url\n parameter:\n\n\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"custom-model-name\"\n,\n\n\n base_url\n=\n\"https://api.your-provider.com/v1\"\n,\n\n\n api_key\n=\n\"your-api-key\"\n\n\n)\n\n\nagent \n=\n Agent(\nllm\n=\nllm, \n...\n)\n\n\n\n\nThis is particularly useful when working with OpenAI-compatible APIs or when you need to specify a different endpoint for your chosen provider.\n\n\n​\nConclusion\n\n\nBy leveraging LiteLLM, CrewAI offers seamless integration with a vast array of LLMs. This flexibility allows you to choose the most suitable model for your specific needs, whether you prioritize performance, cost-efficiency, or local deployment. Remember to consult the \nLiteLLM documentation\n for the most up-to-date information on supported models and configuration options.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nKickoff Crew for Each\nUsing Multimodal Agents\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nConnect CrewAI to LLMs\nSupported Providers\nChanging the LLM\nConfiguration Options\nConnecting to OpenAI-Compatible LLMs\nUsing Local Models with Ollama\nChanging the Base API URL\nConclusion\nLearn\nConnect to any LLM\nCopy page\nComprehensive guide on integrating CrewAI with various Large Language Models (LLMs) using LiteLLM, including supported providers and configuration options.\n​\nConnect CrewAI to LLMs\n\n\nCrewAI uses LiteLLM to connect to a wide variety of Language Models (LLMs). This integration provides extensive versatility, allowing you to use models from numerous providers with a simple, unified interface.\n\n\nBy default, CrewAI uses the \ngpt-4o-mini\n model. This is determined by the \nOPENAI_MODEL_NAME\n environment variable, which defaults to “gpt-4o-mini” if not set.\nYou can easily configure your agents to use a different model or provider as described in this guide.\n\n\n​\nSupported Providers\n\n\nLiteLLM supports a wide range of providers, including but not limited to:\n\n\n\n\nOpenAI\n\n\nAnthropic\n\n\nGoogle (Vertex AI, Gemini)\n\n\nAzure OpenAI\n\n\nAWS (Bedrock, SageMaker)\n\n\nCohere\n\n\nVoyageAI\n\n\nHugging Face\n\n\nOllama\n\n\nMistral AI\n\n\nReplicate\n\n\nTogether AI\n\n\nAI21\n\n\nCloudflare Workers AI\n\n\nDeepInfra\n\n\nGroq\n\n\nSambaNova\n\n\nNebius AI Studio\n\n\nNVIDIA NIMs\n\n\nAnd many more!\n\n\n\n\nFor a complete and up-to-date list of supported providers, please refer to the \nLiteLLM Providers documentation\n.\n\n\n​\nChanging the LLM\n\n\nTo use a different LLM with your CrewAI agents, you have several options:\n\n\nUsing a String Identifier\nUsing the LLM Class\nPass the model name as a string when initializing the agent:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\n# Using OpenAI's GPT-4\n\n\nopenai_agent \n=\n Agent(\n\n\n role\n=\n'OpenAI Expert'\n,\n\n\n goal\n=\n'Provide insights using GPT-4'\n,\n\n\n backstory\n=\n\"An AI assistant powered by OpenAI's latest model.\"\n,\n\n\n llm\n=\n'gpt-4'\n\n\n)\n\n\n\n\n# Using Anthropic's Claude\n\n\nclaude_agent \n=\n Agent(\n\n\n role\n=\n'Anthropic Expert'\n,\n\n\n goal\n=\n'Analyze data using Claude'\n,\n\n\n backstory\n=\n\"An AI assistant leveraging Anthropic's language model.\"\n,\n\n\n llm\n=\n'claude-2'\n\n\n)\n\n\nPass the model name as a string when initializing the agent:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\n# Using OpenAI's GPT-4\n\n\nopenai_agent \n=\n Agent(\n\n\n role\n=\n'OpenAI Expert'\n,\n\n\n goal\n=\n'Provide insights using GPT-4'\n,\n\n\n backstory\n=\n\"An AI assistant powered by OpenAI's latest model.\"\n,\n\n\n llm\n=\n'gpt-4'\n\n\n)\n\n\n\n\n# Using Anthropic's Claude\n\n\nclaude_agent \n=\n Agent(\n\n\n role\n=\n'Anthropic Expert'\n,\n\n\n goal\n=\n'Analyze data using Claude'\n,\n\n\n backstory\n=\n\"An AI assistant leveraging Anthropic's language model.\"\n,\n\n\n llm\n=\n'claude-2'\n\n\n)\n\n\nFor more detailed configuration, use the LLM class:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, \nLLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gpt-4\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n base_url\n=\n\"https://api.openai.com/v1\"\n,\n\n\n api_key\n=\n\"your-api-key-here\"\n\n\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n'Customized LLM Expert'\n,\n\n\n goal\n=\n'Provide tailored responses'\n,\n\n\n backstory\n=\n\"An AI assistant with custom LLM settings.\"\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\n\n\n​\nConfiguration Options\n\n\nWhen configuring an LLM for your agent, you have access to a wide range of parameters:\n\n\nParameter\nType\nDescription\nmodel\nstr\nThe name of the model to use (e.g., “gpt-4”, “claude-2”)\ntemperature\nfloat\nControls randomness in output (0.0 to 1.0)\nmax_tokens\nint\nMaximum number of tokens to generate\ntop_p\nfloat\nControls diversity of output (0.0 to 1.0)\nfrequency_penalty\nfloat\nPenalizes new tokens based on their frequency in the text so far\npresence_penalty\nfloat\nPenalizes new tokens based on their presence in the text so far\nstop\nstr\n, \nList[str]\nSequence(s) to stop generation\nbase_url\nstr\nThe base URL for the API endpoint\napi_key\nstr\nYour API key for authentication\n\n\nFor a complete list of parameters and their descriptions, refer to the LLM class documentation.\n\n\n​\nConnecting to OpenAI-Compatible LLMs\n\n\nYou can connect to OpenAI-compatible LLMs using either environment variables or by setting specific attributes on the LLM class:\n\n\nUsing Environment Variables\nUsing LLM Class Attributes\nGeneric\nGoogle\nCopy\nAsk AI\nimport\n os\n\n\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"your-api-key\"\n\n\nos.environ[\n\"OPENAI_API_BASE\"\n] \n=\n \"https://api.your-provider.com/v1\"\n\n\nos.environ[\n\"OPENAI_MODEL_NAME\"\n] \n=\n \"your-model-name\"\n\n\nGeneric\nGoogle\nCopy\nAsk AI\nimport\n os\n\n\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"your-api-key\"\n\n\nos.environ[\n\"OPENAI_API_BASE\"\n] \n=\n \"https://api.your-provider.com/v1\"\n\n\nos.environ[\n\"OPENAI_MODEL_NAME\"\n] \n=\n \"your-model-name\"\n\n\nGeneric\nGoogle\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"custom-model-name\"\n,\n\n\n api_key\n=\n\"your-api-key\"\n,\n\n\n base_url\n=\n\"https://api.your-provider.com/v1\"\n\n\n)\n\n\nagent \n=\n Agent(\nllm\n=\nllm, \n...\n)\n\n\n\n\n​\nUsing Local Models with Ollama\n\n\nFor local models like those provided by Ollama:\n\n\n1\nDownload and install Ollama\nClick here to download and install Ollama\n2\nPull the desired model\nFor example, run \nollama pull llama3.2\n to download the model.\n3\nConfigure your agent\nCode\nCopy\nAsk AI\n agent \n=\n Agent(\n\n\n role\n=\n'Local AI Expert'\n,\n\n\n goal\n=\n'Process information using a local model'\n,\n\n\n backstory\n=\n\"An AI assistant running on local hardware.\"\n,\n\n\n llm\n=\nLLM(\nmodel\n=\n\"ollama/llama3.2\"\n, \nbase_url\n=\n\"http://localhost:11434\"\n)\n\n\n )\n\n\n\n\n​\nChanging the Base API URL\n\n\nYou can change the base API URL for any LLM provider by setting the \nbase_url\n parameter:\n\n\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"custom-model-name\"\n,\n\n\n base_url\n=\n\"https://api.your-provider.com/v1\"\n,\n\n\n api_key\n=\n\"your-api-key\"\n\n\n)\n\n\nagent \n=\n Agent(\nllm\n=\nllm, \n...\n)\n\n\n\n\nThis is particularly useful when working with OpenAI-compatible APIs or when you need to specify a different endpoint for your chosen provider.\n\n\n​\nConclusion\n\n\nBy leveraging LiteLLM, CrewAI offers seamless integration with a vast array of LLMs. This flexibility allows you to choose the most suitable model for your specific needs, whether you prioritize performance, cost-efficiency, or local deployment. Remember to consult the \nLiteLLM documentation\n for the most up-to-date information on supported models and configuration options.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nKickoff Crew for Each\nUsing Multimodal Agents\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nConnect CrewAI to LLMs\nSupported Providers\nChanging the LLM\nConfiguration Options\nConnecting to OpenAI-Compatible LLMs\nUsing Local Models with Ollama\nChanging the Base API URL\nConclusion" }, { "source": "https://docs.crewai.com/#key-capabilities", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/concepts/tools", "title": "Tools - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nTools\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nTools\nCopy page\nUnderstanding and leveraging tools within the CrewAI framework for agent collaboration and task execution.\n​\nOverview\n\n\nCrewAI tools empower agents with capabilities ranging from web searching and data analysis to collaboration and delegating tasks among coworkers.\nThis documentation outlines how to create, integrate, and leverage these tools within the CrewAI framework, including a new focus on collaboration tools.\n\n\n​\nWhat is a Tool?\n\n\nA tool in CrewAI is a skill or function that agents can utilize to perform various actions.\nThis includes tools from the \nCrewAI Toolkit\n and \nLangChain Tools\n,\nenabling everything from simple searches to complex interactions and effective teamwork among agents.\n\n\nCrewAI Enterprise provides a comprehensive Tools Repository with pre-built integrations for common business systems and APIs. Deploy agents with enterprise tools in minutes instead of days.\nThe Enterprise Tools Repository includes:\n\n\nPre-built connectors for popular enterprise systems\n\n\nCustom tool creation interface\n\n\nVersion control and sharing capabilities\n\n\nSecurity and compliance features\n\n\n\n\n​\nKey Characteristics of Tools\n\n\n\n\nUtility\n: Crafted for tasks such as web searching, data analysis, content generation, and agent collaboration.\n\n\nIntegration\n: Boosts agent capabilities by seamlessly integrating tools into their workflow.\n\n\nCustomizability\n: Provides the flexibility to develop custom tools or utilize existing ones, catering to the specific needs of agents.\n\n\nError Handling\n: Incorporates robust error handling mechanisms to ensure smooth operation.\n\n\nCaching Mechanism\n: Features intelligent caching to optimize performance and reduce redundant operations.\n\n\nAsynchronous Support\n: Handles both synchronous and asynchronous tools, enabling non-blocking operations.\n\n\n\n\n​\nUsing CrewAI Tools\n\n\nTo enhance your agents’ capabilities with crewAI tools, begin by installing our extra tools package:\n\n\nCopy\nAsk AI\npip\n install\n 'crewai[tools]'\n\n\n\n\nHere’s an example demonstrating their use:\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n# Importing crewAI tools\n\n\nfrom\n crewai_tools \nimport\n (\n\n\n DirectoryReadTool,\n\n\n FileReadTool,\n\n\n SerperDevTool,\n\n\n WebsiteSearchTool\n\n\n)\n\n\n\n\n# Set up API keys\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n # serper.dev API key\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\n\n\n# Instantiate tools\n\n\ndocs_tool \n=\n DirectoryReadTool(\ndirectory\n=\n'./blog-posts'\n)\n\n\nfile_tool \n=\n FileReadTool()\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\nweb_rag_tool \n=\n WebsiteSearchTool()\n\n\n\n\n# Create agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Market Research Analyst'\n,\n\n\n goal\n=\n'Provide up-to-date market analysis of the AI industry'\n,\n\n\n backstory\n=\n'An expert analyst with a keen eye for market trends.'\n,\n\n\n tools\n=\n[search_tool, web_rag_tool],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Content Writer'\n,\n\n\n goal\n=\n'Craft engaging blog posts about the AI industry'\n,\n\n\n backstory\n=\n'A skilled writer with a passion for technology.'\n,\n\n\n tools\n=\n[docs_tool, file_tool],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Define tasks\n\n\nresearch \n=\n Task(\n\n\n description\n=\n'Research the latest trends in the AI industry and provide a summary.'\n,\n\n\n expected_output\n=\n'A summary of the top 3 trending developments in the AI industry with a unique perspective on their significance.'\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nwrite \n=\n Task(\n\n\n description\n=\n'Write an engaging blog post about the AI industry, based on the research analyst'\ns summary. Draw inspiration \nfrom\n the latest blog posts \nin\n the directory.\n',\n\n\n expected_output\n=\n'A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.'\n,\n\n\n agent\n=\nwriter,\n\n\n output_file\n=\n'blog-posts/new_post.md'\n # The final blog post will be saved here\n\n\n)\n\n\n\n\n# Assemble a crew with planning enabled\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[research, write],\n\n\n verbose\n=\nTrue\n,\n\n\n planning\n=\nTrue\n, \n# Enable planning feature\n\n\n)\n\n\n\n\n# Execute tasks\n\n\ncrew.kickoff()\n\n\n\n\n​\nAvailable CrewAI Tools\n\n\n\n\nError Handling\n: All tools are built with error handling capabilities, allowing agents to gracefully manage exceptions and continue their tasks.\n\n\nCaching Mechanism\n: All tools support caching, enabling agents to efficiently reuse previously obtained results, reducing the load on external resources and speeding up the execution time. You can also define finer control over the caching mechanism using the \ncache_function\n attribute on the tool.\n\n\n\n\nHere is a list of the available tools and their descriptions:\n\n\nTool\nDescription\nApifyActorsTool\nA tool that integrates Apify Actors with your workflows for web scraping and automation tasks.\nBrowserbaseLoadTool\nA tool for interacting with and extracting data from web browsers.\nCodeDocsSearchTool\nA RAG tool optimized for searching through code documentation and related technical documents.\nCodeInterpreterTool\nA tool for interpreting python code.\nComposioTool\nEnables use of Composio tools.\nCSVSearchTool\nA RAG tool designed for searching within CSV files, tailored to handle structured data.\nDALL-E Tool\nA tool for generating images using the DALL-E API.\nDirectorySearchTool\nA RAG tool for searching within directories, useful for navigating through file systems.\nDOCXSearchTool\nA RAG tool aimed at searching within DOCX documents, ideal for processing Word files.\nDirectoryReadTool\nFacilitates reading and processing of directory structures and their contents.\nEXASearchTool\nA tool designed for performing exhaustive searches across various data sources.\nFileReadTool\nEnables reading and extracting data from files, supporting various file formats.\nFirecrawlSearchTool\nA tool to search webpages using Firecrawl and return the results.\nFirecrawlCrawlWebsiteTool\nA tool for crawling webpages using Firecrawl.\nFirecrawlScrapeWebsiteTool\nA tool for scraping webpages URL using Firecrawl and returning its contents.\nGithubSearchTool\nA RAG tool for searching within GitHub repositories, useful for code and documentation search.\nSerperDevTool\nA specialized tool for development purposes, with specific functionalities under development.\nTXTSearchTool\nA RAG tool focused on searching within text (.txt) files, suitable for unstructured data.\nJSONSearchTool\nA RAG tool designed for searching within JSON files, catering to structured data handling.\nLlamaIndexTool\nEnables the use of LlamaIndex tools.\nMDXSearchTool\nA RAG tool tailored for searching within Markdown (MDX) files, useful for documentation.\nPDFSearchTool\nA RAG tool aimed at searching within PDF documents, ideal for processing scanned documents.\nPGSearchTool\nA RAG tool optimized for searching within PostgreSQL databases, suitable for database queries.\nVision Tool\nA tool for generating images using the DALL-E API.\nRagTool\nA general-purpose RAG tool capable of handling various data sources and types.\nScrapeElementFromWebsiteTool\nEnables scraping specific elements from websites, useful for targeted data extraction.\nScrapeWebsiteTool\nFacilitates scraping entire websites, ideal for comprehensive data collection.\nWebsiteSearchTool\nA RAG tool for searching website content, optimized for web data extraction.\nXMLSearchTool\nA RAG tool designed for searching within XML files, suitable for structured data formats.\nYoutubeChannelSearchTool\nA RAG tool for searching within YouTube channels, useful for video content analysis.\nYoutubeVideoSearchTool\nA RAG tool aimed at searching within YouTube videos, ideal for video data extraction.\n\n\n​\nCreating your own Tools\n\n\nDevelopers can craft \ncustom tools\n tailored for their agent’s needs or\nutilize pre-built options.\n\n\nThere are two main ways for one to create a CrewAI tool:\n\n\n​\nSubclassing \nBaseTool\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n BaseTool\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nclass\n MyToolInput\n(\nBaseModel\n):\n\n\n \"\"\"Input schema for MyCustomTool.\"\"\"\n\n\n argument: \nstr\n =\n Field(\n...\n, \ndescription\n=\n\"Description of the argument.\"\n)\n\n\n\n\nclass\n MyCustomTool\n(\nBaseTool\n):\n\n\n name: \nstr\n =\n \"Name of my tool\"\n\n\n description: \nstr\n =\n \"What this tool does. It's vital for effective utilization.\"\n\n\n args_schema: Type[BaseModel] \n=\n MyToolInput\n\n\n\n\n def\n _run\n(\nself\n, \nargument\n: \nstr\n) -> \nstr\n:\n\n\n # Your tool's logic here\n\n\n return\n \"Tool's result\"\n\n\n\n\n​\nAsynchronous Tool Support\n\n\nCrewAI supports asynchronous tools, allowing you to implement tools that perform non-blocking operations like network requests, file I/O, or other async operations without blocking the main execution thread.\n\n\n​\nCreating Async Tools\n\n\nYou can create async tools in two ways:\n\n\n​\n1. Using the \ntool\n Decorator with Async Functions\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n\n\n@tool\n(\n\"fetch_data_async\"\n)\n\n\nasync\n def\n fetch_data_async\n(\nquery\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Asynchronously fetch data based on the query.\"\"\"\n\n\n # Simulate async operation\n\n\n await\n asyncio.sleep(\n1\n)\n\n\n return\n f\n\"Data retrieved for \n{\nquery\n}\n\"\n\n\n\n\n​\n2. Implementing Async Methods in Custom Tool Classes\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n BaseTool\n\n\n\n\nclass\n AsyncCustomTool\n(\nBaseTool\n):\n\n\n name: \nstr\n =\n \"async_custom_tool\"\n\n\n description: \nstr\n =\n \"An asynchronous custom tool\"\n\n\n \n\n\n async\n def\n _run\n(\nself\n, \nquery\n: \nstr\n =\n \"\"\n) -> \nstr\n:\n\n\n \"\"\"Asynchronously run the tool\"\"\"\n\n\n # Your async implementation here\n\n\n await\n asyncio.sleep(\n1\n)\n\n\n return\n f\n\"Processed \n{\nquery\n}\n asynchronously\"\n\n\n\n\n​\nUsing Async Tools\n\n\nAsync tools work seamlessly in both standard Crew workflows and Flow-based workflows:\n\n\nCode\nCopy\nAsk AI\n# In standard Crew\n\n\nagent \n=\n Agent(\nrole\n=\n\"researcher\"\n, \ntools\n=\n[async_custom_tool])\n\n\n\n\n# In Flow\n\n\nclass\n MyFlow\n(\nFlow\n):\n\n\n @start\n()\n\n\n async\n def\n begin\n(\nself\n):\n\n\n crew \n=\n Crew(\nagents\n=\n[agent])\n\n\n result \n=\n await\n crew.kickoff_async()\n\n\n return\n result\n\n\n\n\nThe CrewAI framework automatically handles the execution of both synchronous and asynchronous tools, so you don’t need to worry about how to call them differently.\n\n\n​\nUtilizing the \ntool\n Decorator\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n@tool\n(\n\"Name of my tool\"\n)\n\n\ndef\n my_tool\n(\nquestion\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Clear description for what this tool is useful for, your agent will need this information to use it.\"\"\"\n\n\n # Function logic here\n\n\n return\n \"Result from your custom tool\"\n\n\n\n\n​\nCustom Caching Mechanism\n\n\nTools can optionally implement a \ncache_function\n to fine-tune caching\nbehavior. This function determines when to cache results based on specific\nconditions, offering granular control over caching logic.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n\n\n@tool\n\n\ndef\n multiplication_tool\n(\nfirst_number\n: \nint\n, \nsecond_number\n: \nint\n) -> \nstr\n:\n\n\n \"\"\"Useful for when you need to multiply two numbers together.\"\"\"\n\n\n return\n first_number \n*\n second_number\n\n\n\n\ndef\n cache_func\n(\nargs\n, \nresult\n):\n\n\n # In this case, we only cache the result if it's a multiple of 2\n\n\n cache \n=\n result \n%\n 2\n ==\n 0\n\n\n return\n cache\n\n\n\n\nmultiplication_tool.cache_function \n=\n cache_func\n\n\n\n\nwriter1 \n=\n Agent(\n\n\n role\n=\n\"Writer\"\n,\n\n\n goal\n=\n\"You write lessons of math for kids.\"\n,\n\n\n backstory\n=\n\"You're an expert in writing and you love to teach kids but you know nothing of math.\"\n,\n\n\n tools\n=\n[multiplication_tool],\n\n\n allow_delegation\n=\nFalse\n,\n\n\n )\n\n\n #...\n\n\n\n\n​\nConclusion\n\n\nTools are pivotal in extending the capabilities of CrewAI agents, enabling them to undertake a broad spectrum of tasks and collaborate effectively.\nWhen building solutions with CrewAI, leverage both custom and existing tools to empower your agents and enhance the AI ecosystem. Consider utilizing error handling,\ncaching mechanisms, and the flexibility of tool arguments to optimize your agents’ performance and capabilities.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCLI\nEvent Listeners\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nWhat is a Tool?\nKey Characteristics of Tools\nUsing CrewAI Tools\nAvailable CrewAI Tools\nCreating your own Tools\nSubclassing BaseTool\nAsynchronous Tool Support\nCreating Async Tools\n1. Using the tool Decorator with Async Functions\n2. Implementing Async Methods in Custom Tool Classes\nUsing Async Tools\nUtilizing the tool Decorator\nCustom Caching Mechanism\nConclusion\nCore Concepts\nTools\nCopy page\nUnderstanding and leveraging tools within the CrewAI framework for agent collaboration and task execution.\n​\nOverview\n\n\nCrewAI tools empower agents with capabilities ranging from web searching and data analysis to collaboration and delegating tasks among coworkers.\nThis documentation outlines how to create, integrate, and leverage these tools within the CrewAI framework, including a new focus on collaboration tools.\n\n\n​\nWhat is a Tool?\n\n\nA tool in CrewAI is a skill or function that agents can utilize to perform various actions.\nThis includes tools from the \nCrewAI Toolkit\n and \nLangChain Tools\n,\nenabling everything from simple searches to complex interactions and effective teamwork among agents.\n\n\nCrewAI Enterprise provides a comprehensive Tools Repository with pre-built integrations for common business systems and APIs. Deploy agents with enterprise tools in minutes instead of days.\nThe Enterprise Tools Repository includes:\n\n\nPre-built connectors for popular enterprise systems\n\n\nCustom tool creation interface\n\n\nVersion control and sharing capabilities\n\n\nSecurity and compliance features\n\n\n\n\n​\nKey Characteristics of Tools\n\n\n\n\nUtility\n: Crafted for tasks such as web searching, data analysis, content generation, and agent collaboration.\n\n\nIntegration\n: Boosts agent capabilities by seamlessly integrating tools into their workflow.\n\n\nCustomizability\n: Provides the flexibility to develop custom tools or utilize existing ones, catering to the specific needs of agents.\n\n\nError Handling\n: Incorporates robust error handling mechanisms to ensure smooth operation.\n\n\nCaching Mechanism\n: Features intelligent caching to optimize performance and reduce redundant operations.\n\n\nAsynchronous Support\n: Handles both synchronous and asynchronous tools, enabling non-blocking operations.\n\n\n\n\n​\nUsing CrewAI Tools\n\n\nTo enhance your agents’ capabilities with crewAI tools, begin by installing our extra tools package:\n\n\nCopy\nAsk AI\npip\n install\n 'crewai[tools]'\n\n\n\n\nHere’s an example demonstrating their use:\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n# Importing crewAI tools\n\n\nfrom\n crewai_tools \nimport\n (\n\n\n DirectoryReadTool,\n\n\n FileReadTool,\n\n\n SerperDevTool,\n\n\n WebsiteSearchTool\n\n\n)\n\n\n\n\n# Set up API keys\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n # serper.dev API key\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\n\n\n# Instantiate tools\n\n\ndocs_tool \n=\n DirectoryReadTool(\ndirectory\n=\n'./blog-posts'\n)\n\n\nfile_tool \n=\n FileReadTool()\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\nweb_rag_tool \n=\n WebsiteSearchTool()\n\n\n\n\n# Create agents\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Market Research Analyst'\n,\n\n\n goal\n=\n'Provide up-to-date market analysis of the AI industry'\n,\n\n\n backstory\n=\n'An expert analyst with a keen eye for market trends.'\n,\n\n\n tools\n=\n[search_tool, web_rag_tool],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Content Writer'\n,\n\n\n goal\n=\n'Craft engaging blog posts about the AI industry'\n,\n\n\n backstory\n=\n'A skilled writer with a passion for technology.'\n,\n\n\n tools\n=\n[docs_tool, file_tool],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\n# Define tasks\n\n\nresearch \n=\n Task(\n\n\n description\n=\n'Research the latest trends in the AI industry and provide a summary.'\n,\n\n\n expected_output\n=\n'A summary of the top 3 trending developments in the AI industry with a unique perspective on their significance.'\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\nwrite \n=\n Task(\n\n\n description\n=\n'Write an engaging blog post about the AI industry, based on the research analyst'\ns summary. Draw inspiration \nfrom\n the latest blog posts \nin\n the directory.\n',\n\n\n expected_output\n=\n'A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.'\n,\n\n\n agent\n=\nwriter,\n\n\n output_file\n=\n'blog-posts/new_post.md'\n # The final blog post will be saved here\n\n\n)\n\n\n\n\n# Assemble a crew with planning enabled\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher, writer],\n\n\n tasks\n=\n[research, write],\n\n\n verbose\n=\nTrue\n,\n\n\n planning\n=\nTrue\n, \n# Enable planning feature\n\n\n)\n\n\n\n\n# Execute tasks\n\n\ncrew.kickoff()\n\n\n\n\n​\nAvailable CrewAI Tools\n\n\n\n\nError Handling\n: All tools are built with error handling capabilities, allowing agents to gracefully manage exceptions and continue their tasks.\n\n\nCaching Mechanism\n: All tools support caching, enabling agents to efficiently reuse previously obtained results, reducing the load on external resources and speeding up the execution time. You can also define finer control over the caching mechanism using the \ncache_function\n attribute on the tool.\n\n\n\n\nHere is a list of the available tools and their descriptions:\n\n\nTool\nDescription\nApifyActorsTool\nA tool that integrates Apify Actors with your workflows for web scraping and automation tasks.\nBrowserbaseLoadTool\nA tool for interacting with and extracting data from web browsers.\nCodeDocsSearchTool\nA RAG tool optimized for searching through code documentation and related technical documents.\nCodeInterpreterTool\nA tool for interpreting python code.\nComposioTool\nEnables use of Composio tools.\nCSVSearchTool\nA RAG tool designed for searching within CSV files, tailored to handle structured data.\nDALL-E Tool\nA tool for generating images using the DALL-E API.\nDirectorySearchTool\nA RAG tool for searching within directories, useful for navigating through file systems.\nDOCXSearchTool\nA RAG tool aimed at searching within DOCX documents, ideal for processing Word files.\nDirectoryReadTool\nFacilitates reading and processing of directory structures and their contents.\nEXASearchTool\nA tool designed for performing exhaustive searches across various data sources.\nFileReadTool\nEnables reading and extracting data from files, supporting various file formats.\nFirecrawlSearchTool\nA tool to search webpages using Firecrawl and return the results.\nFirecrawlCrawlWebsiteTool\nA tool for crawling webpages using Firecrawl.\nFirecrawlScrapeWebsiteTool\nA tool for scraping webpages URL using Firecrawl and returning its contents.\nGithubSearchTool\nA RAG tool for searching within GitHub repositories, useful for code and documentation search.\nSerperDevTool\nA specialized tool for development purposes, with specific functionalities under development.\nTXTSearchTool\nA RAG tool focused on searching within text (.txt) files, suitable for unstructured data.\nJSONSearchTool\nA RAG tool designed for searching within JSON files, catering to structured data handling.\nLlamaIndexTool\nEnables the use of LlamaIndex tools.\nMDXSearchTool\nA RAG tool tailored for searching within Markdown (MDX) files, useful for documentation.\nPDFSearchTool\nA RAG tool aimed at searching within PDF documents, ideal for processing scanned documents.\nPGSearchTool\nA RAG tool optimized for searching within PostgreSQL databases, suitable for database queries.\nVision Tool\nA tool for generating images using the DALL-E API.\nRagTool\nA general-purpose RAG tool capable of handling various data sources and types.\nScrapeElementFromWebsiteTool\nEnables scraping specific elements from websites, useful for targeted data extraction.\nScrapeWebsiteTool\nFacilitates scraping entire websites, ideal for comprehensive data collection.\nWebsiteSearchTool\nA RAG tool for searching website content, optimized for web data extraction.\nXMLSearchTool\nA RAG tool designed for searching within XML files, suitable for structured data formats.\nYoutubeChannelSearchTool\nA RAG tool for searching within YouTube channels, useful for video content analysis.\nYoutubeVideoSearchTool\nA RAG tool aimed at searching within YouTube videos, ideal for video data extraction.\n\n\n​\nCreating your own Tools\n\n\nDevelopers can craft \ncustom tools\n tailored for their agent’s needs or\nutilize pre-built options.\n\n\nThere are two main ways for one to create a CrewAI tool:\n\n\n​\nSubclassing \nBaseTool\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n BaseTool\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nclass\n MyToolInput\n(\nBaseModel\n):\n\n\n \"\"\"Input schema for MyCustomTool.\"\"\"\n\n\n argument: \nstr\n =\n Field(\n...\n, \ndescription\n=\n\"Description of the argument.\"\n)\n\n\n\n\nclass\n MyCustomTool\n(\nBaseTool\n):\n\n\n name: \nstr\n =\n \"Name of my tool\"\n\n\n description: \nstr\n =\n \"What this tool does. It's vital for effective utilization.\"\n\n\n args_schema: Type[BaseModel] \n=\n MyToolInput\n\n\n\n\n def\n _run\n(\nself\n, \nargument\n: \nstr\n) -> \nstr\n:\n\n\n # Your tool's logic here\n\n\n return\n \"Tool's result\"\n\n\n\n\n​\nAsynchronous Tool Support\n\n\nCrewAI supports asynchronous tools, allowing you to implement tools that perform non-blocking operations like network requests, file I/O, or other async operations without blocking the main execution thread.\n\n\n​\nCreating Async Tools\n\n\nYou can create async tools in two ways:\n\n\n​\n1. Using the \ntool\n Decorator with Async Functions\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n\n\n@tool\n(\n\"fetch_data_async\"\n)\n\n\nasync\n def\n fetch_data_async\n(\nquery\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Asynchronously fetch data based on the query.\"\"\"\n\n\n # Simulate async operation\n\n\n await\n asyncio.sleep(\n1\n)\n\n\n return\n f\n\"Data retrieved for \n{\nquery\n}\n\"\n\n\n\n\n​\n2. Implementing Async Methods in Custom Tool Classes\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n BaseTool\n\n\n\n\nclass\n AsyncCustomTool\n(\nBaseTool\n):\n\n\n name: \nstr\n =\n \"async_custom_tool\"\n\n\n description: \nstr\n =\n \"An asynchronous custom tool\"\n\n\n \n\n\n async\n def\n _run\n(\nself\n, \nquery\n: \nstr\n =\n \"\"\n) -> \nstr\n:\n\n\n \"\"\"Asynchronously run the tool\"\"\"\n\n\n # Your async implementation here\n\n\n await\n asyncio.sleep(\n1\n)\n\n\n return\n f\n\"Processed \n{\nquery\n}\n asynchronously\"\n\n\n\n\n​\nUsing Async Tools\n\n\nAsync tools work seamlessly in both standard Crew workflows and Flow-based workflows:\n\n\nCode\nCopy\nAsk AI\n# In standard Crew\n\n\nagent \n=\n Agent(\nrole\n=\n\"researcher\"\n, \ntools\n=\n[async_custom_tool])\n\n\n\n\n# In Flow\n\n\nclass\n MyFlow\n(\nFlow\n):\n\n\n @start\n()\n\n\n async\n def\n begin\n(\nself\n):\n\n\n crew \n=\n Crew(\nagents\n=\n[agent])\n\n\n result \n=\n await\n crew.kickoff_async()\n\n\n return\n result\n\n\n\n\nThe CrewAI framework automatically handles the execution of both synchronous and asynchronous tools, so you don’t need to worry about how to call them differently.\n\n\n​\nUtilizing the \ntool\n Decorator\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n@tool\n(\n\"Name of my tool\"\n)\n\n\ndef\n my_tool\n(\nquestion\n: \nstr\n) -> \nstr\n:\n\n\n \"\"\"Clear description for what this tool is useful for, your agent will need this information to use it.\"\"\"\n\n\n # Function logic here\n\n\n return\n \"Result from your custom tool\"\n\n\n\n\n​\nCustom Caching Mechanism\n\n\nTools can optionally implement a \ncache_function\n to fine-tune caching\nbehavior. This function determines when to cache results based on specific\nconditions, offering granular control over caching logic.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.tools \nimport\n tool\n\n\n\n\n@tool\n\n\ndef\n multiplication_tool\n(\nfirst_number\n: \nint\n, \nsecond_number\n: \nint\n) -> \nstr\n:\n\n\n \"\"\"Useful for when you need to multiply two numbers together.\"\"\"\n\n\n return\n first_number \n*\n second_number\n\n\n\n\ndef\n cache_func\n(\nargs\n, \nresult\n):\n\n\n # In this case, we only cache the result if it's a multiple of 2\n\n\n cache \n=\n result \n%\n 2\n ==\n 0\n\n\n return\n cache\n\n\n\n\nmultiplication_tool.cache_function \n=\n cache_func\n\n\n\n\nwriter1 \n=\n Agent(\n\n\n role\n=\n\"Writer\"\n,\n\n\n goal\n=\n\"You write lessons of math for kids.\"\n,\n\n\n backstory\n=\n\"You're an expert in writing and you love to teach kids but you know nothing of math.\"\n,\n\n\n tools\n=\n[multiplication_tool],\n\n\n allow_delegation\n=\nFalse\n,\n\n\n )\n\n\n #...\n\n\n\n\n​\nConclusion\n\n\nTools are pivotal in extending the capabilities of CrewAI agents, enabling them to undertake a broad spectrum of tasks and collaborate effectively.\nWhen building solutions with CrewAI, leverage both custom and existing tools to empower your agents and enhance the AI ecosystem. Consider utilizing error handling,\ncaching mechanisms, and the flexibility of tool arguments to optimize your agents’ performance and capabilities.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCLI\nEvent Listeners\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nWhat is a Tool?\nKey Characteristics of Tools\nUsing CrewAI Tools\nAvailable CrewAI Tools\nCreating your own Tools\nSubclassing BaseTool\nAsynchronous Tool Support\nCreating Async Tools\n1. Using the tool Decorator with Async Functions\n2. Implementing Async Methods in Custom Tool Classes\nUsing Async Tools\nUtilizing the tool Decorator\nCustom Caching Mechanism\nConclusion" }, { "source": "https://docs.crewai.com/en/mcp/overview", "title": "MCP Servers as Tools in CrewAI - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nMCP Integration\nMCP Servers as Tools in CrewAI\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nMCP Integration\nMCP Servers as Tools in CrewAI\nCopy page\nLearn how to integrate MCP servers as tools in your CrewAI agents using the \ncrewai-tools\n library.\n​\nOverview\n\n\nThe \nModel Context Protocol\n (MCP) provides a standardized way for AI agents to provide context to LLMs by communicating with external services, known as MCP Servers.\nThe \ncrewai-tools\n library extends CrewAI’s capabilities by allowing you to seamlessly integrate tools from these MCP servers into your agents.\nThis gives your crews access to a vast ecosystem of functionalities.\n\n\nWe currently support the following transport mechanisms:\n\n\n\n\nStdio\n: for local servers (communication via standard input/output between processes on the same machine)\n\n\nServer-Sent Events (SSE)\n: for remote servers (unidirectional, real-time data streaming from server to client over HTTP)\n\n\nStreamable HTTP\n: for remote servers (flexible, potentially bi-directional communication over HTTP, often utilizing SSE for server-to-client streams)\n\n\n\n\n​\nVideo Tutorial\n\n\nWatch this video tutorial for a comprehensive guide on MCP integration with CrewAI:\n\n\n\n\n​\nInstallation\n\n\nBefore you start using MCP with \ncrewai-tools\n, you need to install the \nmcp\n extra \ncrewai-tools\n dependency with the following command:\n\n\nCopy\nAsk AI\nuv\n pip\n install\n 'crewai-tools[mcp]'\n\n\n\n\n​\nKey Concepts & Getting Started\n\n\nThe \nMCPServerAdapter\n class from \ncrewai-tools\n is the primary way to connect to an MCP server and make its tools available to your CrewAI agents. It supports different transport mechanisms and simplifies connection management.\n\n\nUsing a Python context manager (\nwith\n statement) is the \nrecommended approach\n for \nMCPServerAdapter\n. It automatically handles starting and stopping the connection to the MCP server.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters \n# For Stdio Server\n\n\n\n\n# Example server_params (choose one based on your server type):\n\n\n# 1. Stdio Server:\n\n\nserver_params\n=\nStdioServerParameters(\n\n\n command\n=\n\"python3\"\n,\n\n\n args\n=\n[\n\"servers/your_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n)\n\n\n\n\n# 2. SSE Server:\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n,\n\n\n \"transport\"\n: \n\"sse\"\n\n\n}\n\n\n\n\n# 3. Streamable HTTP Server:\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n,\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n}\n\n\n\n\n# Example usage (uncomment and adapt once server_params is set):\n\n\nwith\n MCPServerAdapter(server_params) \nas\n mcp_tools:\n\n\n print\n(\nf\n\"Available tools: \n{\n[tool.name \nfor\n tool \nin\n mcp_tools]\n}\n\"\n)\n\n\n\n\n my_agent \n=\n Agent(\n\n\n role\n=\n\"MCP Tool User\"\n,\n\n\n goal\n=\n\"Utilize tools from an MCP server.\"\n,\n\n\n backstory\n=\n\"I can connect to MCP servers and use their tools.\"\n,\n\n\n tools\n=\nmcp_tools, \n# Pass the loaded tools to your agent\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n # ... rest of your crew setup ...\n\n\n\n\nThis general pattern shows how to integrate tools. For specific examples tailored to each transport, refer to the detailed guides below.\n\n\n​\nFiltering Tools\n\n\nThere are two ways to filter tools:\n\n\n\n\nAccessing a specific tool using dictionary-style indexing.\n\n\nPass a list of tool names to the \nMCPServerAdapter\n constructor.\n\n\n\n\n​\nAccessing a specific tool using dictionary-style indexing.\n\n\nCopy\nAsk AI\nwith\n MCPServerAdapter(server_params) \nas\n mcp_tools:\n\n\n print\n(\nf\n\"Available tools: \n{\n[tool.name \nfor\n tool \nin\n mcp_tools]\n}\n\"\n)\n\n\n\n\n my_agent \n=\n Agent(\n\n\n role\n=\n\"MCP Tool User\"\n,\n\n\n goal\n=\n\"Utilize tools from an MCP server.\"\n,\n\n\n backstory\n=\n\"I can connect to MCP servers and use their tools.\"\n,\n\n\n tools\n=\n[mcp_tools[\n\"tool_name\"\n]], \n# Pass the loaded tools to your agent\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n # ... rest of your crew setup ...\n\n\n\n\n​\nPass a list of tool names to the \nMCPServerAdapter\n constructor.\n\n\nCopy\nAsk AI\nwith\n MCPServerAdapter(server_params, \n\"tool_name\"\n) \nas\n mcp_tools:\n\n\n print\n(\nf\n\"Available tools: \n{\n[tool.name \nfor\n tool \nin\n mcp_tools]\n}\n\"\n)\n\n\n\n\n my_agent \n=\n Agent(\n\n\n role\n=\n\"MCP Tool User\"\n,\n\n\n goal\n=\n\"Utilize tools from an MCP server.\"\n,\n\n\n backstory\n=\n\"I can connect to MCP servers and use their tools.\"\n,\n\n\n tools\n=\nmcp_tools, \n# Pass the loaded tools to your agent\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n # ... rest of your crew setup ...\n\n\n\n\n​\nUsing with CrewBase\n\n\nTo use MCPServer tools within a CrewBase class, use the \nmcp_tools\n method. Server configurations should be provided via the mcp_server_params attribute. You can pass either a single configuration or a list of multiple server configurations.\n\n\nCopy\nAsk AI\n@CrewBase\n\n\nclass\n CrewWithMCP\n:\n\n\n # ... define your agents and tasks config file ...\n\n\n\n\n mcp_server_params \n=\n [\n\n\n # Streamable HTTP Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n,\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n },\n\n\n # SSE Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n,\n\n\n \"transport\"\n: \n\"sse\"\n\n\n },\n\n\n # StdIO Server\n\n\n StdioServerParameters(\n\n\n command\n=\n\"python3\"\n,\n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n )\n\n\n ]\n\n\n\n\n @agent\n\n\n def\n your_agent\n(\nself\n):\n\n\n return\n Agent(\nconfig\n=\nself\n.agents_config[\n\"your_agent\"\n], \ntools\n=\nself\n.get_mcp_tools()) \n# get all available tools\n\n\n\n\n # ... rest of your crew setup ...\n\n\n\n\nYou can filter which tools are available to your agent by passing a list of tool names to the \nget_mcp_tools\n method.\n\n\nCopy\nAsk AI\n@agent\n\n\ndef\n another_agent\n(\nself\n):\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n\"your_agent\"\n],\n\n\n tools\n=\nself\n.get_mcp_tools(\n\"tool_1\"\n, \n\"tool_2\"\n) \n# get specific tools\n\n\n )\n\n\n\n\n​\nExplore MCP Integrations\n\n\nStdio Transport\nConnect to local MCP servers via standard input/output. Ideal for scripts and local executables.\nSSE Transport\nIntegrate with remote MCP servers using Server-Sent Events for real-time data streaming.\nStreamable HTTP Transport\nUtilize flexible Streamable HTTP for robust communication with remote MCP servers.\nConnecting to Multiple Servers\nAggregate tools from several MCP servers simultaneously using a single adapter.\nSecurity Considerations\nReview important security best practices for MCP integration to keep your agents safe.\n\n\nCheckout this repository for full demos and examples of MCP integration with CrewAI! 👇\n\n\nGitHub Repository\nCrewAI MCP Demo\n\n\n​\nStaying Safe with MCP\n\n\nAlways ensure that you trust an MCP Server before using it.\n\n\n​\nSecurity Warning: DNS Rebinding Attacks\n\n\nSSE transports can be vulnerable to DNS rebinding attacks if not properly secured.\nTo prevent this:\n\n\n\n\nAlways validate Origin headers\n on incoming SSE connections to ensure they come from expected sources\n\n\nAvoid binding servers to all network interfaces\n (0.0.0.0) when running locally - bind only to localhost (127.0.0.1) instead\n\n\nImplement proper authentication\n for all SSE connections\n\n\n\n\nWithout these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites.\n\n\nFor more details, see the \nAnthropic’s MCP Transport Security docs\n.\n\n\n​\nLimitations\n\n\n\n\nSupported Primitives\n: Currently, \nMCPServerAdapter\n primarily supports adapting MCP \ntools\n.\nOther MCP primitives like \nprompts\n or \nresources\n are not directly integrated as CrewAI components through this adapter at this time.\n\n\nOutput Handling\n: The adapter typically processes the primary text output from an MCP tool (e.g., \n.content[0].text\n). Complex or multi-modal outputs might require custom handling if not fitting this pattern.\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nEvent Listeners\nStdio Transport\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nVideo Tutorial\nInstallation\nKey Concepts & Getting Started\nFiltering Tools\nAccessing a specific tool using dictionary-style indexing.\nPass a list of tool names to the MCPServerAdapter constructor.\nUsing with CrewBase\nExplore MCP Integrations\nStaying Safe with MCP\nSecurity Warning: DNS Rebinding Attacks\nLimitations\nMCP Integration\nMCP Servers as Tools in CrewAI\nCopy page\nLearn how to integrate MCP servers as tools in your CrewAI agents using the \ncrewai-tools\n library.\n​\nOverview\n\n\nThe \nModel Context Protocol\n (MCP) provides a standardized way for AI agents to provide context to LLMs by communicating with external services, known as MCP Servers.\nThe \ncrewai-tools\n library extends CrewAI’s capabilities by allowing you to seamlessly integrate tools from these MCP servers into your agents.\nThis gives your crews access to a vast ecosystem of functionalities.\n\n\nWe currently support the following transport mechanisms:\n\n\n\n\nStdio\n: for local servers (communication via standard input/output between processes on the same machine)\n\n\nServer-Sent Events (SSE)\n: for remote servers (unidirectional, real-time data streaming from server to client over HTTP)\n\n\nStreamable HTTP\n: for remote servers (flexible, potentially bi-directional communication over HTTP, often utilizing SSE for server-to-client streams)\n\n\n\n\n​\nVideo Tutorial\n\n\nWatch this video tutorial for a comprehensive guide on MCP integration with CrewAI:\n\n\n\n\n​\nInstallation\n\n\nBefore you start using MCP with \ncrewai-tools\n, you need to install the \nmcp\n extra \ncrewai-tools\n dependency with the following command:\n\n\nCopy\nAsk AI\nuv\n pip\n install\n 'crewai-tools[mcp]'\n\n\n\n\n​\nKey Concepts & Getting Started\n\n\nThe \nMCPServerAdapter\n class from \ncrewai-tools\n is the primary way to connect to an MCP server and make its tools available to your CrewAI agents. It supports different transport mechanisms and simplifies connection management.\n\n\nUsing a Python context manager (\nwith\n statement) is the \nrecommended approach\n for \nMCPServerAdapter\n. It automatically handles starting and stopping the connection to the MCP server.\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n MCPServerAdapter\n\n\nfrom\n mcp \nimport\n StdioServerParameters \n# For Stdio Server\n\n\n\n\n# Example server_params (choose one based on your server type):\n\n\n# 1. Stdio Server:\n\n\nserver_params\n=\nStdioServerParameters(\n\n\n command\n=\n\"python3\"\n,\n\n\n args\n=\n[\n\"servers/your_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n)\n\n\n\n\n# 2. SSE Server:\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n,\n\n\n \"transport\"\n: \n\"sse\"\n\n\n}\n\n\n\n\n# 3. Streamable HTTP Server:\n\n\nserver_params \n=\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n,\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n}\n\n\n\n\n# Example usage (uncomment and adapt once server_params is set):\n\n\nwith\n MCPServerAdapter(server_params) \nas\n mcp_tools:\n\n\n print\n(\nf\n\"Available tools: \n{\n[tool.name \nfor\n tool \nin\n mcp_tools]\n}\n\"\n)\n\n\n\n\n my_agent \n=\n Agent(\n\n\n role\n=\n\"MCP Tool User\"\n,\n\n\n goal\n=\n\"Utilize tools from an MCP server.\"\n,\n\n\n backstory\n=\n\"I can connect to MCP servers and use their tools.\"\n,\n\n\n tools\n=\nmcp_tools, \n# Pass the loaded tools to your agent\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n # ... rest of your crew setup ...\n\n\n\n\nThis general pattern shows how to integrate tools. For specific examples tailored to each transport, refer to the detailed guides below.\n\n\n​\nFiltering Tools\n\n\nThere are two ways to filter tools:\n\n\n\n\nAccessing a specific tool using dictionary-style indexing.\n\n\nPass a list of tool names to the \nMCPServerAdapter\n constructor.\n\n\n\n\n​\nAccessing a specific tool using dictionary-style indexing.\n\n\nCopy\nAsk AI\nwith\n MCPServerAdapter(server_params) \nas\n mcp_tools:\n\n\n print\n(\nf\n\"Available tools: \n{\n[tool.name \nfor\n tool \nin\n mcp_tools]\n}\n\"\n)\n\n\n\n\n my_agent \n=\n Agent(\n\n\n role\n=\n\"MCP Tool User\"\n,\n\n\n goal\n=\n\"Utilize tools from an MCP server.\"\n,\n\n\n backstory\n=\n\"I can connect to MCP servers and use their tools.\"\n,\n\n\n tools\n=\n[mcp_tools[\n\"tool_name\"\n]], \n# Pass the loaded tools to your agent\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n # ... rest of your crew setup ...\n\n\n\n\n​\nPass a list of tool names to the \nMCPServerAdapter\n constructor.\n\n\nCopy\nAsk AI\nwith\n MCPServerAdapter(server_params, \n\"tool_name\"\n) \nas\n mcp_tools:\n\n\n print\n(\nf\n\"Available tools: \n{\n[tool.name \nfor\n tool \nin\n mcp_tools]\n}\n\"\n)\n\n\n\n\n my_agent \n=\n Agent(\n\n\n role\n=\n\"MCP Tool User\"\n,\n\n\n goal\n=\n\"Utilize tools from an MCP server.\"\n,\n\n\n backstory\n=\n\"I can connect to MCP servers and use their tools.\"\n,\n\n\n tools\n=\nmcp_tools, \n# Pass the loaded tools to your agent\n\n\n reasoning\n=\nTrue\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n # ... rest of your crew setup ...\n\n\n\n\n​\nUsing with CrewBase\n\n\nTo use MCPServer tools within a CrewBase class, use the \nmcp_tools\n method. Server configurations should be provided via the mcp_server_params attribute. You can pass either a single configuration or a list of multiple server configurations.\n\n\nCopy\nAsk AI\n@CrewBase\n\n\nclass\n CrewWithMCP\n:\n\n\n # ... define your agents and tasks config file ...\n\n\n\n\n mcp_server_params \n=\n [\n\n\n # Streamable HTTP Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8001/mcp\"\n,\n\n\n \"transport\"\n: \n\"streamable-http\"\n\n\n },\n\n\n # SSE Server\n\n\n {\n\n\n \"url\"\n: \n\"http://localhost:8000/sse\"\n,\n\n\n \"transport\"\n: \n\"sse\"\n\n\n },\n\n\n # StdIO Server\n\n\n StdioServerParameters(\n\n\n command\n=\n\"python3\"\n,\n\n\n args\n=\n[\n\"servers/your_stdio_server.py\"\n],\n\n\n env\n=\n{\n\"UV_PYTHON\"\n: \n\"3.12\"\n, \n**\nos.environ},\n\n\n )\n\n\n ]\n\n\n\n\n @agent\n\n\n def\n your_agent\n(\nself\n):\n\n\n return\n Agent(\nconfig\n=\nself\n.agents_config[\n\"your_agent\"\n], \ntools\n=\nself\n.get_mcp_tools()) \n# get all available tools\n\n\n\n\n # ... rest of your crew setup ...\n\n\n\n\nYou can filter which tools are available to your agent by passing a list of tool names to the \nget_mcp_tools\n method.\n\n\nCopy\nAsk AI\n@agent\n\n\ndef\n another_agent\n(\nself\n):\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n\"your_agent\"\n],\n\n\n tools\n=\nself\n.get_mcp_tools(\n\"tool_1\"\n, \n\"tool_2\"\n) \n# get specific tools\n\n\n )\n\n\n\n\n​\nExplore MCP Integrations\n\n\nStdio Transport\nConnect to local MCP servers via standard input/output. Ideal for scripts and local executables.\nSSE Transport\nIntegrate with remote MCP servers using Server-Sent Events for real-time data streaming.\nStreamable HTTP Transport\nUtilize flexible Streamable HTTP for robust communication with remote MCP servers.\nConnecting to Multiple Servers\nAggregate tools from several MCP servers simultaneously using a single adapter.\nSecurity Considerations\nReview important security best practices for MCP integration to keep your agents safe.\n\n\nCheckout this repository for full demos and examples of MCP integration with CrewAI! 👇\n\n\nGitHub Repository\nCrewAI MCP Demo\n\n\n​\nStaying Safe with MCP\n\n\nAlways ensure that you trust an MCP Server before using it.\n\n\n​\nSecurity Warning: DNS Rebinding Attacks\n\n\nSSE transports can be vulnerable to DNS rebinding attacks if not properly secured.\nTo prevent this:\n\n\n\n\nAlways validate Origin headers\n on incoming SSE connections to ensure they come from expected sources\n\n\nAvoid binding servers to all network interfaces\n (0.0.0.0) when running locally - bind only to localhost (127.0.0.1) instead\n\n\nImplement proper authentication\n for all SSE connections\n\n\n\n\nWithout these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites.\n\n\nFor more details, see the \nAnthropic’s MCP Transport Security docs\n.\n\n\n​\nLimitations\n\n\n\n\nSupported Primitives\n: Currently, \nMCPServerAdapter\n primarily supports adapting MCP \ntools\n.\nOther MCP primitives like \nprompts\n or \nresources\n are not directly integrated as CrewAI components through this adapter at this time.\n\n\nOutput Handling\n: The adapter typically processes the primary text output from an MCP tool (e.g., \n.content[0].text\n). Complex or multi-modal outputs might require custom handling if not fitting this pattern.\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nEvent Listeners\nStdio Transport\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nVideo Tutorial\nInstallation\nKey Concepts & Getting Started\nFiltering Tools\nAccessing a specific tool using dictionary-style indexing.\nPass a list of tool names to the MCPServerAdapter constructor.\nUsing with CrewBase\nExplore MCP Integrations\nStaying Safe with MCP\nSecurity Warning: DNS Rebinding Attacks\nLimitations" }, { "source": "https://docs.crewai.com/en/concepts/llms", "title": "LLMs - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nLLMs\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nLLMs\nCopy page\nA comprehensive guide to configuring and using Large Language Models (LLMs) in your CrewAI projects\n​\nOverview\n\n\nCrewAI integrates with multiple LLM providers through LiteLLM, giving you the flexibility to choose the right model for your specific use case. This guide will help you understand how to configure and use different LLM providers in your CrewAI projects.\n\n\n​\nWhat are LLMs?\n\n\nLarge Language Models (LLMs) are the core intelligence behind CrewAI agents. They enable agents to understand context, make decisions, and generate human-like responses. Here’s what you need to know:\n\n\nLLM Basics\nLarge Language Models are AI systems trained on vast amounts of text data. They power the intelligence of your CrewAI agents, enabling them to understand and generate human-like text.\nContext Window\nThe context window determines how much text an LLM can process at once. Larger windows (e.g., 128K tokens) allow for more context but may be more expensive and slower.\nTemperature\nTemperature (0.0 to 1.0) controls response randomness. Lower values (e.g., 0.2) produce more focused, deterministic outputs, while higher values (e.g., 0.8) increase creativity and variability.\nProvider Selection\nEach LLM provider (e.g., OpenAI, Anthropic, Google) offers different models with varying capabilities, pricing, and features. Choose based on your needs for accuracy, speed, and cost.\n\n\n​\nSetting up your LLM\n\n\nThere are different places in CrewAI code where you can specify the model to use. Once you specify the model you are using, you will need to provide the configuration (like an API key) for each of the model providers you use. See the \nprovider configuration examples\n section for your provider.\n\n\n1. Environment Variables\n2. YAML Configuration\n3. Direct Code\nThe simplest way to get started. Set the model in your environment directly, through an \n.env\n file or in your app code. If you used \ncrewai create\n to bootstrap your project, it will be set already.\n.env\nCopy\nAsk AI\nMODEL\n=\nmodel-id\n # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...\n\n\n\n\n# Be sure to set your API keys here too. See the Provider\n\n\n# section below.\n\n\nNever commit API keys to version control. Use environment files (.env) or your system’s secret management.\nThe simplest way to get started. Set the model in your environment directly, through an \n.env\n file or in your app code. If you used \ncrewai create\n to bootstrap your project, it will be set already.\n.env\nCopy\nAsk AI\nMODEL\n=\nmodel-id\n # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...\n\n\n\n\n# Be sure to set your API keys here too. See the Provider\n\n\n# section below.\n\n\nNever commit API keys to version control. Use environment files (.env) or your system’s secret management.\nCreate a YAML file to define your agent configurations. This method is great for version control and team collaboration:\nagents.yaml\nCopy\nAsk AI\nresearcher\n:\n\n\n role\n: \nResearch Specialist\n\n\n goal\n: \nConduct comprehensive research and analysis\n\n\n backstory\n: \nA dedicated research professional with years of experience\n\n\n verbose\n: \ntrue\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n # (see provider configuration examples below for more)\n\n\nThe YAML configuration allows you to:\n\n\nVersion control your agent settings\n\n\nEasily switch between different models\n\n\nShare configurations across team members\n\n\nDocument model choices and their purposes\n\n\nFor maximum flexibility, configure LLMs directly in your Python code:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Basic configuration\n\n\nllm \n=\n LLM(\nmodel\n=\n\"model-id-here\"\n) \n# gpt-4o, gemini-2.0-flash, anthropic/claude...\n\n\n\n\n# Advanced configuration with detailed parameters\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"model-id-here\"\n, \n# gpt-4o, gemini-2.0-flash, anthropic/claude...\n\n\n temperature\n=\n0.7\n, \n# Higher for more creative outputs\n\n\n timeout\n=\n120\n, \n# Seconds to wait for response\n\n\n max_tokens\n=\n4000\n, \n# Maximum length of response\n\n\n top_p\n=\n0.9\n, \n# Nucleus sampling parameter\n\n\n frequency_penalty\n=\n0.1\n , \n# Reduce repetition\n\n\n presence_penalty\n=\n0.1\n, \n# Encourage topic diversity\n\n\n response_format\n=\n{\n\"type\"\n: \n\"json\"\n}, \n# For structured outputs\n\n\n seed\n=\n42\n # For reproducible results\n\n\n)\n\n\nParameter explanations:\n\n\ntemperature\n: Controls randomness (0.0-1.0)\n\n\ntimeout\n: Maximum wait time for response\n\n\nmax_tokens\n: Limits response length\n\n\ntop_p\n: Alternative to temperature for sampling\n\n\nfrequency_penalty\n: Reduces word repetition\n\n\npresence_penalty\n: Encourages new topics\n\n\nresponse_format\n: Specifies output structure\n\n\nseed\n: Ensures consistent outputs\n\n\n\n\n​\nProvider Configuration Examples\n\n\nCrewAI supports a multitude of LLM providers, each offering unique features, authentication methods, and model capabilities.\nIn this section, you’ll find detailed examples that help you select, configure, and optimize the LLM that best fits your project’s needs.\n\n\nOpenAI\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Required\n\n\nOPENAI_API_KEY\n=s\nk-...\n\n\n\n\n# Optional\n\n\nOPENAI_API_BASE\n=<\ncustom-base-url>\n\n\nOPENAI_ORGANIZATION\n=<\nyour-org-id>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4\"\n, \n# call model by provider/model_name\n\n\n temperature\n=\n0.8\n,\n\n\n max_tokens\n=\n150\n,\n\n\n top_p\n=\n0.9\n,\n\n\n frequency_penalty\n=\n0.1\n,\n\n\n presence_penalty\n=\n0.1\n,\n\n\n stop\n=\n[\n\"END\"\n],\n\n\n seed\n=\n42\n\n\n)\n\n\nOpenAI is one of the leading providers of LLMs with a wide range of models and features.\nModel\nContext Window\nBest For\nGPT-4\n8,192 tokens\nHigh-accuracy tasks, complex reasoning\nGPT-4 Turbo\n128,000 tokens\nLong-form content, document analysis\nGPT-4o & GPT-4o-mini\n128,000 tokens\nCost-effective large context processing\no3-mini\n200,000 tokens\nFast reasoning, complex reasoning\no1-mini\n128,000 tokens\nFast reasoning, complex reasoning\no1-preview\n128,000 tokens\nFast reasoning, complex reasoning\no1\n200,000 tokens\nFast reasoning, complex reasoning\nMeta-Llama\nMeta’s Llama API provides access to Meta’s family of large language models.\nThe API is available through the \nMeta Llama API\n.\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Meta Llama API Key Configuration\n\n\nLLAMA_API_KEY\n=L\nLM|your_api_key_here\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Initialize Meta Llama LLM\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8\"\n,\n\n\n temperature\n=\n0.8\n,\n\n\n stop\n=\n[\n\"END\"\n],\n\n\n seed\n=\n42\n\n\n)\n\n\nAll models listed here \nhttps://llama.developer.meta.com/docs/models/\n are supported.\nModel ID\nInput context length\nOutput context length\nInput Modalities\nOutput Modalities\nmeta_llama/Llama-4-Scout-17B-16E-Instruct-FP8\n128k\n4028\nText, Image\nText\nmeta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8\n128k\n4028\nText, Image\nText\nmeta_llama/Llama-3.3-70B-Instruct\n128k\n4028\nText\nText\nmeta_llama/Llama-3.3-8B-Instruct\n128k\n4028\nText\nText\nAnthropic\nCode\nCopy\nAsk AI\n# Required\n\n\nANTHROPIC_API_KEY\n=s\nk-ant-...\n\n\n\n\n# Optional\n\n\nANTHROPIC_API_BASE\n=<\ncustom-base-url>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"anthropic/claude-3-sonnet-20240229-v1:0\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nGoogle (Gemini API)\nSet your API key in your \n.env\n file. If you need a key, or need to find an\nexisting key, check \nAI Studio\n.\n.env\nCopy\nAsk AI\n# https://ai.google.dev/gemini-api/docs/api-key\n\n\nGEMINI_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gemini/gemini-2.0-flash\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n)\n\n\n​\nGemini models\nGoogle offers a range of powerful models optimized for different use cases.\nModel\nContext Window\nBest For\ngemini-2.5-flash-preview-04-17\n1M tokens\nAdaptive thinking, cost efficiency\ngemini-2.5-pro-preview-05-06\n1M tokens\nEnhanced thinking and reasoning, multimodal understanding, advanced coding, and more\ngemini-2.0-flash\n1M tokens\nNext generation features, speed, thinking, and realtime streaming\ngemini-2.0-flash-lite\n1M tokens\nCost efficiency and low latency\ngemini-1.5-flash\n1M tokens\nBalanced multimodal model, good for most tasks\ngemini-1.5-flash-8B\n1M tokens\nFastest, most cost-efficient, good for high-frequency tasks\ngemini-1.5-pro\n2M tokens\nBest performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration\nThe full list of models is available in the \nGemini model docs\n.\n​\nGemma\nThe Gemini API also allows you to use your API key to access \nGemma models\n hosted on Google infrastructure.\nModel\nContext Window\ngemma-3-1b-it\n32k tokens\ngemma-3-4b-it\n32k tokens\ngemma-3-12b-it\n32k tokens\ngemma-3-27b-it\n128k tokens\nGoogle (Vertex AI)\nGet credentials from your Google Cloud Console and save it to a JSON file, then load it with the following code:\nCode\nCopy\nAsk AI\nimport\n json\n\n\n\n\nfile_path \n=\n 'path/to/vertex_ai_service_account.json'\n\n\n\n\n# Load the JSON file\n\n\nwith\n open\n(file_path, \n'r'\n) \nas\n file\n:\n\n\n vertex_credentials \n=\n json.load(\nfile\n)\n\n\n\n\n# Convert the credentials to a JSON string\n\n\nvertex_credentials_json \n=\n json.dumps(vertex_credentials)\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gemini/gemini-1.5-pro-latest\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n vertex_credentials\n=\nvertex_credentials_json\n\n\n)\n\n\nGoogle offers a range of powerful models optimized for different use cases:\nModel\nContext Window\nBest For\ngemini-2.5-flash-preview-04-17\n1M tokens\nAdaptive thinking, cost efficiency\ngemini-2.5-pro-preview-05-06\n1M tokens\nEnhanced thinking and reasoning, multimodal understanding, advanced coding, and more\ngemini-2.0-flash\n1M tokens\nNext generation features, speed, thinking, and realtime streaming\ngemini-2.0-flash-lite\n1M tokens\nCost efficiency and low latency\ngemini-1.5-flash\n1M tokens\nBalanced multimodal model, good for most tasks\ngemini-1.5-flash-8B\n1M tokens\nFastest, most cost-efficient, good for high-frequency tasks\ngemini-1.5-pro\n2M tokens\nBest performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration\nAzure\nCode\nCopy\nAsk AI\n# Required\n\n\nAZURE_API_KEY\n=<\nyour-api-key>\n\n\nAZURE_API_BASE\n=<\nyour-resource-url>\n\n\nAZURE_API_VERSION\n=<\napi-version>\n\n\n\n\n# Optional\n\n\nAZURE_AD_TOKEN\n=<\nyour-azure-ad-token>\n\n\nAZURE_API_TYPE\n=<\nyour-azure-api-type>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"azure/gpt-4\"\n,\n\n\n api_version\n=\n\"2023-05-15\"\n\n\n)\n\n\nAWS Bedrock\nCode\nCopy\nAsk AI\nAWS_ACCESS_KEY_ID\n=<\nyour-access-key>\n\n\nAWS_SECRET_ACCESS_KEY\n=<\nyour-secret-key>\n\n\nAWS_DEFAULT_REGION\n=<\nyour-region>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"bedrock/anthropic.claude-3-sonnet-20240229-v1:0\"\n\n\n)\n\n\nBefore using Amazon Bedrock, make sure you have boto3 installed in your environment\nAmazon Bedrock\n is a managed service that provides access to multiple foundation models from top AI companies through a unified API, enabling secure and responsible AI application development.\nModel\nContext Window\nBest For\nAmazon Nova Pro\nUp to 300k tokens\nHigh-performance, model balancing accuracy, speed, and cost-effectiveness across diverse tasks.\nAmazon Nova Micro\nUp to 128k tokens\nHigh-performance, cost-effective text-only model optimized for lowest latency responses.\nAmazon Nova Lite\nUp to 300k tokens\nHigh-performance, affordable multimodal processing for images, video, and text with real-time capabilities.\nClaude 3.7 Sonnet\nUp to 128k tokens\nHigh-performance, best for complex reasoning, coding & AI agents\nClaude 3.5 Sonnet v2\nUp to 200k tokens\nState-of-the-art model specialized in software engineering, agentic capabilities, and computer interaction at optimized cost.\nClaude 3.5 Sonnet\nUp to 200k tokens\nHigh-performance model delivering superior intelligence and reasoning across diverse tasks with optimal speed-cost balance.\nClaude 3.5 Haiku\nUp to 200k tokens\nFast, compact multimodal model optimized for quick responses and seamless human-like interactions\nClaude 3 Sonnet\nUp to 200k tokens\nMultimodal model balancing intelligence and speed for high-volume deployments.\nClaude 3 Haiku\nUp to 200k tokens\nCompact, high-speed multimodal model optimized for quick responses and natural conversational interactions\nClaude 3 Opus\nUp to 200k tokens\nMost advanced multimodal model exceling at complex tasks with human-like reasoning and superior contextual understanding.\nClaude 2.1\nUp to 200k tokens\nEnhanced version with expanded context window, improved reliability, and reduced hallucinations for long-form and RAG applications\nClaude\nUp to 100k tokens\nVersatile model excelling in sophisticated dialogue, creative content, and precise instruction following.\nClaude Instant\nUp to 100k tokens\nFast, cost-effective model for everyday tasks like dialogue, analysis, summarization, and document Q&A\nLlama 3.1 405B Instruct\nUp to 128k tokens\nAdvanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks.\nLlama 3.1 70B Instruct\nUp to 128k tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nLlama 3.1 8B Instruct\nUp to 128k tokens\nAdvanced state-of-the-art model with language understanding, superior reasoning, and text generation.\nLlama 3 70B Instruct\nUp to 8k tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nLlama 3 8B Instruct\nUp to 8k tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nTitan Text G1 - Lite\nUp to 4k tokens\nLightweight, cost-effective model optimized for English tasks and fine-tuning with focus on summarization and content generation.\nTitan Text G1 - Express\nUp to 8k tokens\nVersatile model for general language tasks, chat, and RAG applications with support for English and 100+ languages.\nCohere Command\nUp to 4k tokens\nModel specialized in following user commands and delivering practical enterprise solutions.\nJurassic-2 Mid\nUp to 8,191 tokens\nCost-effective model balancing quality and affordability for diverse language tasks like Q&A, summarization, and content generation.\nJurassic-2 Ultra\nUp to 8,191 tokens\nModel for advanced text generation and comprehension, excelling in complex tasks like analysis and content creation.\nJamba-Instruct\nUp to 256k tokens\nModel with extended context window optimized for cost-effective text generation, summarization, and Q&A.\nMistral 7B Instruct\nUp to 32k tokens\nThis LLM follows instructions, completes requests, and generates creative text.\nMistral 8x7B Instruct\nUp to 32k tokens\nAn MOE LLM that follows instructions, completes requests, and generates creative text.\nAmazon SageMaker\nCode\nCopy\nAsk AI\nAWS_ACCESS_KEY_ID\n=<\nyour-access-key>\n\n\nAWS_SECRET_ACCESS_KEY\n=<\nyour-secret-key>\n\n\nAWS_DEFAULT_REGION\n=<\nyour-region>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"sagemaker/\"\n\n\n)\n\n\nMistral\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nMISTRAL_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"mistral/mistral-large-latest\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nNvidia NIM\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nNVIDIA_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"nvidia_nim/meta/llama3-70b-instruct\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nNvidia NIM provides a comprehensive suite of models for various use cases, from general-purpose tasks to specialized applications.\nModel\nContext Window\nBest For\nnvidia/mistral-nemo-minitron-8b-8k-instruct\n8,192 tokens\nState-of-the-art small language model delivering superior accuracy for chatbot, virtual assistants, and content generation.\nnvidia/nemotron-4-mini-hindi-4b-instruct\n4,096 tokens\nA bilingual Hindi-English SLM for on-device inference, tailored specifically for Hindi Language.\nnvidia/llama-3.1-nemotron-70b-instruct\n128k tokens\nCustomized for enhanced helpfulness in responses\nnvidia/llama3-chatqa-1.5-8b\n128k tokens\nAdvanced LLM to generate high-quality, context-aware responses for chatbots and search engines.\nnvidia/llama3-chatqa-1.5-70b\n128k tokens\nAdvanced LLM to generate high-quality, context-aware responses for chatbots and search engines.\nnvidia/vila\n128k tokens\nMulti-modal vision-language model that understands text/img/video and creates informative responses\nnvidia/neva-22\n4,096 tokens\nMulti-modal vision-language model that understands text/images and generates informative responses\nnvidia/nemotron-mini-4b-instruct\n8,192 tokens\nGeneral-purpose tasks\nnvidia/usdcode-llama3-70b-instruct\n128k tokens\nState-of-the-art LLM that answers OpenUSD knowledge queries and generates USD-Python code.\nnvidia/nemotron-4-340b-instruct\n4,096 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nmeta/codellama-70b\n100k tokens\nLLM capable of generating code from natural language and vice versa.\nmeta/llama2-70b\n4,096 tokens\nCutting-edge large language AI model capable of generating text and code in response to prompts.\nmeta/llama3-8b-instruct\n8,192 tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nmeta/llama3-70b-instruct\n8,192 tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nmeta/llama-3.1-8b-instruct\n128k tokens\nAdvanced state-of-the-art model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.1-70b-instruct\n128k tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nmeta/llama-3.1-405b-instruct\n128k tokens\nAdvanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks.\nmeta/llama-3.2-1b-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.2-3b-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.2-11b-vision-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.2-90b-vision-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\ngoogle/gemma-7b\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/gemma-2b\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/codegemma-7b\n8,192 tokens\nCutting-edge model built on Google’s Gemma-7B specialized for code generation and code completion.\ngoogle/codegemma-1.1-7b\n8,192 tokens\nAdvanced programming model for code generation, completion, reasoning, and instruction following.\ngoogle/recurrentgemma-2b\n8,192 tokens\nNovel recurrent architecture based language model for faster inference when generating long sequences.\ngoogle/gemma-2-9b-it\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/gemma-2-27b-it\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/gemma-2-2b-it\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/deplot\n512 tokens\nOne-shot visual language understanding model that translates images of plots into tables.\ngoogle/paligemma\n8,192 tokens\nVision language model adept at comprehending text and visual inputs to produce informative responses.\nmistralai/mistral-7b-instruct-v0.2\n32k tokens\nThis LLM follows instructions, completes requests, and generates creative text.\nmistralai/mixtral-8x7b-instruct-v0.1\n8,192 tokens\nAn MOE LLM that follows instructions, completes requests, and generates creative text.\nmistralai/mistral-large\n4,096 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nmistralai/mixtral-8x22b-instruct-v0.1\n8,192 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nmistralai/mistral-7b-instruct-v0.3\n32k tokens\nThis LLM follows instructions, completes requests, and generates creative text.\nnv-mistralai/mistral-nemo-12b-instruct\n128k tokens\nMost advanced language model for reasoning, code, multilingual tasks; runs on a single GPU.\nmistralai/mamba-codestral-7b-v0.1\n256k tokens\nModel for writing and interacting with code across a wide range of programming languages and tasks.\nmicrosoft/phi-3-mini-128k-instruct\n128K tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-mini-4k-instruct\n4,096 tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-small-8k-instruct\n8,192 tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-small-128k-instruct\n128K tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-medium-4k-instruct\n4,096 tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-medium-128k-instruct\n128K tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3.5-mini-instruct\n128K tokens\nLightweight multilingual LLM powering AI applications in latency bound, memory/compute constrained environments\nmicrosoft/phi-3.5-moe-instruct\n128K tokens\nAdvanced LLM based on Mixture of Experts architecture to deliver compute efficient content generation\nmicrosoft/kosmos-2\n1,024 tokens\nGroundbreaking multimodal model designed to understand and reason about visual elements in images.\nmicrosoft/phi-3-vision-128k-instruct\n128k tokens\nCutting-edge open multimodal model exceling in high-quality reasoning from images.\nmicrosoft/phi-3.5-vision-instruct\n128k tokens\nCutting-edge open multimodal model exceling in high-quality reasoning from images.\ndatabricks/dbrx-instruct\n12k tokens\nA general-purpose LLM with state-of-the-art performance in language understanding, coding, and RAG.\nsnowflake/arctic\n1,024 tokens\nDelivers high efficiency inference for enterprise applications focused on SQL generation and coding.\naisingapore/sea-lion-7b-instruct\n4,096 tokens\nLLM to represent and serve the linguistic and cultural diversity of Southeast Asia\nibm/granite-8b-code-instruct\n4,096 tokens\nSoftware programming LLM for code generation, completion, explanation, and multi-turn conversion.\nibm/granite-34b-code-instruct\n8,192 tokens\nSoftware programming LLM for code generation, completion, explanation, and multi-turn conversion.\nibm/granite-3.0-8b-instruct\n4,096 tokens\nAdvanced Small Language Model supporting RAG, summarization, classification, code, and agentic AI\nibm/granite-3.0-3b-a800m-instruct\n4,096 tokens\nHighly efficient Mixture of Experts model for RAG, summarization, entity extraction, and classification\nmediatek/breeze-7b-instruct\n4,096 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nupstage/solar-10.7b-instruct\n4,096 tokens\nExcels in NLP tasks, particularly in instruction-following, reasoning, and mathematics.\nwriter/palmyra-med-70b-32k\n32k tokens\nLeading LLM for accurate, contextually relevant responses in the medical domain.\nwriter/palmyra-med-70b\n32k tokens\nLeading LLM for accurate, contextually relevant responses in the medical domain.\nwriter/palmyra-fin-70b-32k\n32k tokens\nSpecialized LLM for financial analysis, reporting, and data processing\n01-ai/yi-large\n32k tokens\nPowerful model trained on English and Chinese for diverse tasks including chatbot and creative writing.\ndeepseek-ai/deepseek-coder-6.7b-instruct\n2k tokens\nPowerful coding model offering advanced capabilities in code generation, completion, and infilling\nrakuten/rakutenai-7b-instruct\n1,024 tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nrakuten/rakutenai-7b-chat\n1,024 tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nbaichuan-inc/baichuan2-13b-chat\n4,096 tokens\nSupport Chinese and English chat, coding, math, instruction following, solving quizzes\nLocal NVIDIA NIM Deployed using WSL2\nNVIDIA NIM enables you to run powerful LLMs locally on your Windows machine using WSL2 (Windows Subsystem for Linux).\nThis approach allows you to leverage your NVIDIA GPU for private, secure, and cost-effective AI inference without relying on cloud services.\nPerfect for development, testing, or production scenarios where data privacy or offline capabilities are required.\nHere is a step-by-step guide to setting up a local NVIDIA NIM model:\n\n\n\n\nFollow installation instructions from \nNVIDIA Website\n\n\n\n\n\n\nInstall the local model. For Llama 3.1-8b follow \ninstructions\n\n\n\n\n\n\nConfigure your crewai local models:\n\n\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.llm \nimport\n LLM\n\n\n\n\nlocal_nvidia_nim_llm \n=\n LLM(\n\n\n model\n=\n\"openai/meta/llama-3.1-8b-instruct\"\n, \n# it's an openai-api compatible model\n\n\n base_url\n=\n\"http://localhost:8000/v1\"\n,\n\n\n api_key\n=\n\"\"\n, \n# api_key is required, but you can use any text\n\n\n)\n\n\n\n\n# Then you can use it in your crew:\n\n\n\n\n@CrewBase\n\n\nclass\n MyCrew\n():\n\n\n # ...\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n llm\n=\nlocal_nvidia_nim_llm\n\n\n )\n\n\n\n\n # ...\n\n\nGroq\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nGROQ_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"groq/llama-3.2-90b-text-preview\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nModel\nContext Window\nBest For\nLlama 3.1 70B/8B\n131,072 tokens\nHigh-performance, large context tasks\nLlama 3.2 Series\n8,192 tokens\nGeneral-purpose tasks\nMixtral 8x7B\n32,768 tokens\nBalanced performance and context\nIBM watsonx.ai\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Required\n\n\nWATSONX_URL\n=<\nyour-url>\n\n\nWATSONX_APIKEY\n=<\nyour-apikey>\n\n\nWATSONX_PROJECT_ID\n=<\nyour-project-id>\n\n\n\n\n# Optional\n\n\nWATSONX_TOKEN\n=<\nyour-token>\n\n\nWATSONX_DEPLOYMENT_SPACE_ID\n=<\nyour-space-id>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"watsonx/meta-llama/llama-3-1-70b-instruct\"\n,\n\n\n base_url\n=\n\"https://api.watsonx.ai/v1\"\n\n\n)\n\n\nOllama (Local LLMs)\n\n\nInstall Ollama: \nollama.ai\n\n\nRun a model: \nollama run llama3\n\n\nConfigure:\n\n\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"ollama/llama3:70b\"\n,\n\n\n base_url\n=\n\"http://localhost:11434\"\n\n\n)\n\n\nFireworks AI\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nFIREWORKS_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nPerplexity AI\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nPERPLEXITY_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"llama-3.1-sonar-large-128k-online\"\n,\n\n\n base_url\n=\n\"https://api.perplexity.ai/\"\n\n\n)\n\n\nHugging Face\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nHF_TOKEN\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"huggingface/meta-llama/Meta-Llama-3.1-8B-Instruct\"\n\n\n)\n\n\nSambaNova\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nSAMBANOVA_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"sambanova/Meta-Llama-3.1-8B-Instruct\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nModel\nContext Window\nBest For\nLlama 3.1 70B/8B\nUp to 131,072 tokens\nHigh-performance, large context tasks\nLlama 3.1 405B\n8,192 tokens\nHigh-performance and output quality\nLlama 3.2 Series\n8,192 tokens\nGeneral-purpose, multimodal tasks\nLlama 3.3 70B\nUp to 131,072 tokens\nHigh-performance and output quality\nQwen2 familly\n8,192 tokens\nHigh-performance and output quality\nCerebras\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Required\n\n\nCEREBRAS_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"cerebras/llama3.1-70b\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n max_tokens\n=\n8192\n\n\n)\n\n\nCerebras features:\n\n\nFast inference speeds\n\n\nCompetitive pricing\n\n\nGood balance of speed and quality\n\n\nSupport for long context windows\n\n\nOpen Router\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nOPENROUTER_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"openrouter/deepseek/deepseek-r1\"\n,\n\n\n base_url\n=\n\"https://openrouter.ai/api/v1\"\n,\n\n\n api_key\n=\nOPENROUTER_API_KEY\n\n\n)\n\n\nOpen Router models:\n\n\nopenrouter/deepseek/deepseek-r1\n\n\nopenrouter/deepseek/deepseek-chat\n\n\nNebius AI Studio\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nNEBIUS_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"nebius/Qwen/Qwen3-30B-A3B\"\n\n\n)\n\n\nNebius AI Studio features:\n\n\nLarge collection of open source models\n\n\nHigher rate limits\n\n\nCompetitive pricing\n\n\nGood balance of speed and quality\n\n\n\n\n​\nStreaming Responses\n\n\nCrewAI supports streaming responses from LLMs, allowing your application to receive and process outputs in real-time as they’re generated.\n\n\nBasic Setup\nEvent Handling\nAgent & Task Tracking\nEnable streaming by setting the \nstream\n parameter to \nTrue\n when initializing your LLM:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Create an LLM with streaming enabled\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4o\"\n,\n\n\n stream\n=\nTrue\n # Enable streaming\n\n\n)\n\n\nWhen streaming is enabled, responses are delivered in chunks as they’re generated, creating a more responsive user experience.\nEnable streaming by setting the \nstream\n parameter to \nTrue\n when initializing your LLM:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Create an LLM with streaming enabled\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4o\"\n,\n\n\n stream\n=\nTrue\n # Enable streaming\n\n\n)\n\n\nWhen streaming is enabled, responses are delivered in chunks as they’re generated, creating a more responsive user experience.\nCrewAI emits events for each chunk received during streaming:\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n (\n\n\n LLMStreamChunkEvent\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(LLMStreamChunkEvent)\n\n\n def\n on_llm_stream_chunk\n(\nself\n, \nevent\n: LLMStreamChunkEvent):\n\n\n # Process each chunk as it arrives\n\n\n print\n(\nf\n\"Received chunk: \n{\nevent.chunk\n}\n\"\n)\n\n\n\n\nmy_listener \n=\n MyCustomListener()\n\n\nClick here\n for more details\nAll LLM events in CrewAI include agent and task information, allowing you to track and filter LLM interactions by specific agents or tasks:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n, Agent, Task, Crew\n\n\nfrom\n crewai.utilities.events \nimport\n LLMStreamChunkEvent\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(LLMStreamChunkEvent)\n\n\n def\n on_llm_stream_chunk\n(\nsource\n, \nevent\n):\n\n\n if\n researcher.id \n==\n event.agent_id:\n\n\n print\n(\n\"\n\\n\n==============\n\\n\n Got event:\"\n, event, \n\"\n\\n\n==============\n\\n\n\"\n)\n\n\n\n\n\n\nmy_listener \n=\n MyCustomListener()\n\n\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n, \nstream\n=\nTrue\n)\n\n\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"About User\"\n,\n\n\n goal\n=\n\"You know everything about the user.\"\n,\n\n\n backstory\n=\n\"\"\"You are a master at understanding people and their preferences.\"\"\"\n,\n\n\n llm\n=\nllm,\n\n\n)\n\n\n\n\nsearch \n=\n Task(\n\n\n description\n=\n\"Answer the following questions about the user: \n{question}\n\"\n,\n\n\n expected_output\n=\n\"An answer to the question.\"\n,\n\n\n agent\n=\nresearcher,\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\nagents\n=\n[researcher], \ntasks\n=\n[search])\n\n\n\n\nresult \n=\n crew.kickoff(\n\n\n inputs\n=\n{\n\"question\"\n: \n\"...\"\n}\n\n\n)\n\n\nThis feature is particularly useful for:\n\n\nDebugging specific agent behaviors\n\n\nLogging LLM usage by task type\n\n\nAuditing which agents are making what types of LLM calls\n\n\nPerformance monitoring of specific tasks\n\n\n\n\n​\nStructured LLM Calls\n\n\nCrewAI supports structured responses from LLM calls by allowing you to define a \nresponse_format\n using a Pydantic model. This enables the framework to automatically parse and validate the output, making it easier to integrate the response into your application without manual post-processing.\n\n\nFor example, you can define a Pydantic model to represent the expected response structure and pass it as the \nresponse_format\n when instantiating the LLM. The model will then be used to convert the LLM output into a structured Python object.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nclass\n Dog\n(\nBaseModel\n):\n\n\n name: \nstr\n\n\n age: \nint\n\n\n breed: \nstr\n\n\n\n\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n, \nresponse_format\n=\nDog)\n\n\n\n\nresponse \n=\n llm.call(\n\n\n \"Analyze the following messages and return the name, age, and breed. \"\n\n\n \"Meet Kona! She is 3 years old and is a black german shepherd.\"\n\n\n)\n\n\nprint\n(response)\n\n\n\n\n# Output:\n\n\n# Dog(name='Kona', age=3, breed='black german shepherd')\n\n\n\n\n​\nAdvanced Features and Optimization\n\n\nLearn how to get the most out of your LLM configuration:\n\n\nContext Window Management\nCrewAI includes smart context management features:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# CrewAI automatically handles:\n\n\n# 1. Token counting and tracking\n\n\n# 2. Content summarization when needed\n\n\n# 3. Task splitting for large contexts\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gpt-4\"\n,\n\n\n max_tokens\n=\n4000\n, \n# Limit response length\n\n\n)\n\n\nBest practices for context management:\n\n\nChoose models with appropriate context windows\n\n\nPre-process long inputs when possible\n\n\nUse chunking for large documents\n\n\nMonitor token usage to optimize costs\n\n\nPerformance Optimization\n1\nToken Usage Optimization\nChoose the right context window for your task:\n\n\nSmall tasks (up to 4K tokens): Standard models\n\n\nMedium tasks (between 4K-32K): Enhanced models\n\n\nLarge tasks (over 32K): Large context models\n\n\nCopy\nAsk AI\n# Configure model with appropriate settings\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4-turbo-preview\"\n,\n\n\n temperature\n=\n0.7\n, \n# Adjust based on task\n\n\n max_tokens\n=\n4096\n, \n# Set based on output needs\n\n\n timeout\n=\n300\n # Longer timeout for complex tasks\n\n\n)\n\n\n\n\nLower temperature (0.1 to 0.3) for factual responses\n\n\nHigher temperature (0.7 to 0.9) for creative tasks\n\n\n2\nBest Practices\n\n\nMonitor token usage\n\n\nImplement rate limiting\n\n\nUse caching when possible\n\n\nSet appropriate max_tokens limits\n\n\nRemember to regularly monitor your token usage and adjust your configuration as needed to optimize costs and performance.\nDrop Additional Parameters\nCrewAI internally uses Litellm for LLM calls, which allows you to drop additional parameters that are not needed for your specific use case. This can help simplify your code and reduce the complexity of your LLM configuration.\nFor example, if you don’t need to send the \nstop\n parameter, you can simply omit it from your LLM call:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\nimport\n os\n\n\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"\"\n\n\n\n\no3_llm \n=\n LLM(\n\n\n model\n=\n\"o3\"\n,\n\n\n drop_params\n=\nTrue\n,\n\n\n additional_drop_params\n=\n[\n\"stop\"\n]\n\n\n)\n\n\n\n\n​\nCommon Issues and Solutions\n\n\nAuthentication\nModel Names\nContext Length\nMost authentication issues can be resolved by checking API key format and environment variable names.\nCopy\nAsk AI\n# OpenAI\n\n\nOPENAI_API_KEY\n=\nsk-...\n\n\n\n\n# Anthropic\n\n\nANTHROPIC_API_KEY\n=\nsk-ant-...\n\n\nMost authentication issues can be resolved by checking API key format and environment variable names.\nCopy\nAsk AI\n# OpenAI\n\n\nOPENAI_API_KEY\n=\nsk-...\n\n\n\n\n# Anthropic\n\n\nANTHROPIC_API_KEY\n=\nsk-ant-...\n\n\nAlways include the provider prefix in model names\nCopy\nAsk AI\n# Correct\n\n\nllm \n=\n LLM(\nmodel\n=\n\"openai/gpt-4\"\n)\n\n\n\n\n# Incorrect\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4\"\n)\n\n\nUse larger context models for extensive tasks\nCopy\nAsk AI\n# Large context model\n\n\nllm \n=\n LLM(\nmodel\n=\n\"openai/gpt-4o\"\n) \n# 128K tokens\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nKnowledge\nProcesses\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nWhat are LLMs?\nSetting up your LLM\nProvider Configuration Examples\nStreaming Responses\nStructured LLM Calls\nAdvanced Features and Optimization\nCommon Issues and Solutions\nCore Concepts\nLLMs\nCopy page\nA comprehensive guide to configuring and using Large Language Models (LLMs) in your CrewAI projects\n​\nOverview\n\n\nCrewAI integrates with multiple LLM providers through LiteLLM, giving you the flexibility to choose the right model for your specific use case. This guide will help you understand how to configure and use different LLM providers in your CrewAI projects.\n\n\n​\nWhat are LLMs?\n\n\nLarge Language Models (LLMs) are the core intelligence behind CrewAI agents. They enable agents to understand context, make decisions, and generate human-like responses. Here’s what you need to know:\n\n\nLLM Basics\nLarge Language Models are AI systems trained on vast amounts of text data. They power the intelligence of your CrewAI agents, enabling them to understand and generate human-like text.\nContext Window\nThe context window determines how much text an LLM can process at once. Larger windows (e.g., 128K tokens) allow for more context but may be more expensive and slower.\nTemperature\nTemperature (0.0 to 1.0) controls response randomness. Lower values (e.g., 0.2) produce more focused, deterministic outputs, while higher values (e.g., 0.8) increase creativity and variability.\nProvider Selection\nEach LLM provider (e.g., OpenAI, Anthropic, Google) offers different models with varying capabilities, pricing, and features. Choose based on your needs for accuracy, speed, and cost.\n\n\n​\nSetting up your LLM\n\n\nThere are different places in CrewAI code where you can specify the model to use. Once you specify the model you are using, you will need to provide the configuration (like an API key) for each of the model providers you use. See the \nprovider configuration examples\n section for your provider.\n\n\n1. Environment Variables\n2. YAML Configuration\n3. Direct Code\nThe simplest way to get started. Set the model in your environment directly, through an \n.env\n file or in your app code. If you used \ncrewai create\n to bootstrap your project, it will be set already.\n.env\nCopy\nAsk AI\nMODEL\n=\nmodel-id\n # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...\n\n\n\n\n# Be sure to set your API keys here too. See the Provider\n\n\n# section below.\n\n\nNever commit API keys to version control. Use environment files (.env) or your system’s secret management.\nThe simplest way to get started. Set the model in your environment directly, through an \n.env\n file or in your app code. If you used \ncrewai create\n to bootstrap your project, it will be set already.\n.env\nCopy\nAsk AI\nMODEL\n=\nmodel-id\n # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...\n\n\n\n\n# Be sure to set your API keys here too. See the Provider\n\n\n# section below.\n\n\nNever commit API keys to version control. Use environment files (.env) or your system’s secret management.\nCreate a YAML file to define your agent configurations. This method is great for version control and team collaboration:\nagents.yaml\nCopy\nAsk AI\nresearcher\n:\n\n\n role\n: \nResearch Specialist\n\n\n goal\n: \nConduct comprehensive research and analysis\n\n\n backstory\n: \nA dedicated research professional with years of experience\n\n\n verbose\n: \ntrue\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n # (see provider configuration examples below for more)\n\n\nThe YAML configuration allows you to:\n\n\nVersion control your agent settings\n\n\nEasily switch between different models\n\n\nShare configurations across team members\n\n\nDocument model choices and their purposes\n\n\nFor maximum flexibility, configure LLMs directly in your Python code:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Basic configuration\n\n\nllm \n=\n LLM(\nmodel\n=\n\"model-id-here\"\n) \n# gpt-4o, gemini-2.0-flash, anthropic/claude...\n\n\n\n\n# Advanced configuration with detailed parameters\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"model-id-here\"\n, \n# gpt-4o, gemini-2.0-flash, anthropic/claude...\n\n\n temperature\n=\n0.7\n, \n# Higher for more creative outputs\n\n\n timeout\n=\n120\n, \n# Seconds to wait for response\n\n\n max_tokens\n=\n4000\n, \n# Maximum length of response\n\n\n top_p\n=\n0.9\n, \n# Nucleus sampling parameter\n\n\n frequency_penalty\n=\n0.1\n , \n# Reduce repetition\n\n\n presence_penalty\n=\n0.1\n, \n# Encourage topic diversity\n\n\n response_format\n=\n{\n\"type\"\n: \n\"json\"\n}, \n# For structured outputs\n\n\n seed\n=\n42\n # For reproducible results\n\n\n)\n\n\nParameter explanations:\n\n\ntemperature\n: Controls randomness (0.0-1.0)\n\n\ntimeout\n: Maximum wait time for response\n\n\nmax_tokens\n: Limits response length\n\n\ntop_p\n: Alternative to temperature for sampling\n\n\nfrequency_penalty\n: Reduces word repetition\n\n\npresence_penalty\n: Encourages new topics\n\n\nresponse_format\n: Specifies output structure\n\n\nseed\n: Ensures consistent outputs\n\n\n\n\n​\nProvider Configuration Examples\n\n\nCrewAI supports a multitude of LLM providers, each offering unique features, authentication methods, and model capabilities.\nIn this section, you’ll find detailed examples that help you select, configure, and optimize the LLM that best fits your project’s needs.\n\n\nOpenAI\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Required\n\n\nOPENAI_API_KEY\n=s\nk-...\n\n\n\n\n# Optional\n\n\nOPENAI_API_BASE\n=<\ncustom-base-url>\n\n\nOPENAI_ORGANIZATION\n=<\nyour-org-id>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4\"\n, \n# call model by provider/model_name\n\n\n temperature\n=\n0.8\n,\n\n\n max_tokens\n=\n150\n,\n\n\n top_p\n=\n0.9\n,\n\n\n frequency_penalty\n=\n0.1\n,\n\n\n presence_penalty\n=\n0.1\n,\n\n\n stop\n=\n[\n\"END\"\n],\n\n\n seed\n=\n42\n\n\n)\n\n\nOpenAI is one of the leading providers of LLMs with a wide range of models and features.\nModel\nContext Window\nBest For\nGPT-4\n8,192 tokens\nHigh-accuracy tasks, complex reasoning\nGPT-4 Turbo\n128,000 tokens\nLong-form content, document analysis\nGPT-4o & GPT-4o-mini\n128,000 tokens\nCost-effective large context processing\no3-mini\n200,000 tokens\nFast reasoning, complex reasoning\no1-mini\n128,000 tokens\nFast reasoning, complex reasoning\no1-preview\n128,000 tokens\nFast reasoning, complex reasoning\no1\n200,000 tokens\nFast reasoning, complex reasoning\nMeta-Llama\nMeta’s Llama API provides access to Meta’s family of large language models.\nThe API is available through the \nMeta Llama API\n.\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Meta Llama API Key Configuration\n\n\nLLAMA_API_KEY\n=L\nLM|your_api_key_here\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Initialize Meta Llama LLM\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8\"\n,\n\n\n temperature\n=\n0.8\n,\n\n\n stop\n=\n[\n\"END\"\n],\n\n\n seed\n=\n42\n\n\n)\n\n\nAll models listed here \nhttps://llama.developer.meta.com/docs/models/\n are supported.\nModel ID\nInput context length\nOutput context length\nInput Modalities\nOutput Modalities\nmeta_llama/Llama-4-Scout-17B-16E-Instruct-FP8\n128k\n4028\nText, Image\nText\nmeta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8\n128k\n4028\nText, Image\nText\nmeta_llama/Llama-3.3-70B-Instruct\n128k\n4028\nText\nText\nmeta_llama/Llama-3.3-8B-Instruct\n128k\n4028\nText\nText\nAnthropic\nCode\nCopy\nAsk AI\n# Required\n\n\nANTHROPIC_API_KEY\n=s\nk-ant-...\n\n\n\n\n# Optional\n\n\nANTHROPIC_API_BASE\n=<\ncustom-base-url>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"anthropic/claude-3-sonnet-20240229-v1:0\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nGoogle (Gemini API)\nSet your API key in your \n.env\n file. If you need a key, or need to find an\nexisting key, check \nAI Studio\n.\n.env\nCopy\nAsk AI\n# https://ai.google.dev/gemini-api/docs/api-key\n\n\nGEMINI_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gemini/gemini-2.0-flash\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n)\n\n\n​\nGemini models\nGoogle offers a range of powerful models optimized for different use cases.\nModel\nContext Window\nBest For\ngemini-2.5-flash-preview-04-17\n1M tokens\nAdaptive thinking, cost efficiency\ngemini-2.5-pro-preview-05-06\n1M tokens\nEnhanced thinking and reasoning, multimodal understanding, advanced coding, and more\ngemini-2.0-flash\n1M tokens\nNext generation features, speed, thinking, and realtime streaming\ngemini-2.0-flash-lite\n1M tokens\nCost efficiency and low latency\ngemini-1.5-flash\n1M tokens\nBalanced multimodal model, good for most tasks\ngemini-1.5-flash-8B\n1M tokens\nFastest, most cost-efficient, good for high-frequency tasks\ngemini-1.5-pro\n2M tokens\nBest performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration\nThe full list of models is available in the \nGemini model docs\n.\n​\nGemma\nThe Gemini API also allows you to use your API key to access \nGemma models\n hosted on Google infrastructure.\nModel\nContext Window\ngemma-3-1b-it\n32k tokens\ngemma-3-4b-it\n32k tokens\ngemma-3-12b-it\n32k tokens\ngemma-3-27b-it\n128k tokens\nGoogle (Vertex AI)\nGet credentials from your Google Cloud Console and save it to a JSON file, then load it with the following code:\nCode\nCopy\nAsk AI\nimport\n json\n\n\n\n\nfile_path \n=\n 'path/to/vertex_ai_service_account.json'\n\n\n\n\n# Load the JSON file\n\n\nwith\n open\n(file_path, \n'r'\n) \nas\n file\n:\n\n\n vertex_credentials \n=\n json.load(\nfile\n)\n\n\n\n\n# Convert the credentials to a JSON string\n\n\nvertex_credentials_json \n=\n json.dumps(vertex_credentials)\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gemini/gemini-1.5-pro-latest\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n vertex_credentials\n=\nvertex_credentials_json\n\n\n)\n\n\nGoogle offers a range of powerful models optimized for different use cases:\nModel\nContext Window\nBest For\ngemini-2.5-flash-preview-04-17\n1M tokens\nAdaptive thinking, cost efficiency\ngemini-2.5-pro-preview-05-06\n1M tokens\nEnhanced thinking and reasoning, multimodal understanding, advanced coding, and more\ngemini-2.0-flash\n1M tokens\nNext generation features, speed, thinking, and realtime streaming\ngemini-2.0-flash-lite\n1M tokens\nCost efficiency and low latency\ngemini-1.5-flash\n1M tokens\nBalanced multimodal model, good for most tasks\ngemini-1.5-flash-8B\n1M tokens\nFastest, most cost-efficient, good for high-frequency tasks\ngemini-1.5-pro\n2M tokens\nBest performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration\nAzure\nCode\nCopy\nAsk AI\n# Required\n\n\nAZURE_API_KEY\n=<\nyour-api-key>\n\n\nAZURE_API_BASE\n=<\nyour-resource-url>\n\n\nAZURE_API_VERSION\n=<\napi-version>\n\n\n\n\n# Optional\n\n\nAZURE_AD_TOKEN\n=<\nyour-azure-ad-token>\n\n\nAZURE_API_TYPE\n=<\nyour-azure-api-type>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"azure/gpt-4\"\n,\n\n\n api_version\n=\n\"2023-05-15\"\n\n\n)\n\n\nAWS Bedrock\nCode\nCopy\nAsk AI\nAWS_ACCESS_KEY_ID\n=<\nyour-access-key>\n\n\nAWS_SECRET_ACCESS_KEY\n=<\nyour-secret-key>\n\n\nAWS_DEFAULT_REGION\n=<\nyour-region>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"bedrock/anthropic.claude-3-sonnet-20240229-v1:0\"\n\n\n)\n\n\nBefore using Amazon Bedrock, make sure you have boto3 installed in your environment\nAmazon Bedrock\n is a managed service that provides access to multiple foundation models from top AI companies through a unified API, enabling secure and responsible AI application development.\nModel\nContext Window\nBest For\nAmazon Nova Pro\nUp to 300k tokens\nHigh-performance, model balancing accuracy, speed, and cost-effectiveness across diverse tasks.\nAmazon Nova Micro\nUp to 128k tokens\nHigh-performance, cost-effective text-only model optimized for lowest latency responses.\nAmazon Nova Lite\nUp to 300k tokens\nHigh-performance, affordable multimodal processing for images, video, and text with real-time capabilities.\nClaude 3.7 Sonnet\nUp to 128k tokens\nHigh-performance, best for complex reasoning, coding & AI agents\nClaude 3.5 Sonnet v2\nUp to 200k tokens\nState-of-the-art model specialized in software engineering, agentic capabilities, and computer interaction at optimized cost.\nClaude 3.5 Sonnet\nUp to 200k tokens\nHigh-performance model delivering superior intelligence and reasoning across diverse tasks with optimal speed-cost balance.\nClaude 3.5 Haiku\nUp to 200k tokens\nFast, compact multimodal model optimized for quick responses and seamless human-like interactions\nClaude 3 Sonnet\nUp to 200k tokens\nMultimodal model balancing intelligence and speed for high-volume deployments.\nClaude 3 Haiku\nUp to 200k tokens\nCompact, high-speed multimodal model optimized for quick responses and natural conversational interactions\nClaude 3 Opus\nUp to 200k tokens\nMost advanced multimodal model exceling at complex tasks with human-like reasoning and superior contextual understanding.\nClaude 2.1\nUp to 200k tokens\nEnhanced version with expanded context window, improved reliability, and reduced hallucinations for long-form and RAG applications\nClaude\nUp to 100k tokens\nVersatile model excelling in sophisticated dialogue, creative content, and precise instruction following.\nClaude Instant\nUp to 100k tokens\nFast, cost-effective model for everyday tasks like dialogue, analysis, summarization, and document Q&A\nLlama 3.1 405B Instruct\nUp to 128k tokens\nAdvanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks.\nLlama 3.1 70B Instruct\nUp to 128k tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nLlama 3.1 8B Instruct\nUp to 128k tokens\nAdvanced state-of-the-art model with language understanding, superior reasoning, and text generation.\nLlama 3 70B Instruct\nUp to 8k tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nLlama 3 8B Instruct\nUp to 8k tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nTitan Text G1 - Lite\nUp to 4k tokens\nLightweight, cost-effective model optimized for English tasks and fine-tuning with focus on summarization and content generation.\nTitan Text G1 - Express\nUp to 8k tokens\nVersatile model for general language tasks, chat, and RAG applications with support for English and 100+ languages.\nCohere Command\nUp to 4k tokens\nModel specialized in following user commands and delivering practical enterprise solutions.\nJurassic-2 Mid\nUp to 8,191 tokens\nCost-effective model balancing quality and affordability for diverse language tasks like Q&A, summarization, and content generation.\nJurassic-2 Ultra\nUp to 8,191 tokens\nModel for advanced text generation and comprehension, excelling in complex tasks like analysis and content creation.\nJamba-Instruct\nUp to 256k tokens\nModel with extended context window optimized for cost-effective text generation, summarization, and Q&A.\nMistral 7B Instruct\nUp to 32k tokens\nThis LLM follows instructions, completes requests, and generates creative text.\nMistral 8x7B Instruct\nUp to 32k tokens\nAn MOE LLM that follows instructions, completes requests, and generates creative text.\nAmazon SageMaker\nCode\nCopy\nAsk AI\nAWS_ACCESS_KEY_ID\n=<\nyour-access-key>\n\n\nAWS_SECRET_ACCESS_KEY\n=<\nyour-secret-key>\n\n\nAWS_DEFAULT_REGION\n=<\nyour-region>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"sagemaker/\"\n\n\n)\n\n\nMistral\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nMISTRAL_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"mistral/mistral-large-latest\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nNvidia NIM\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nNVIDIA_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"nvidia_nim/meta/llama3-70b-instruct\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nNvidia NIM provides a comprehensive suite of models for various use cases, from general-purpose tasks to specialized applications.\nModel\nContext Window\nBest For\nnvidia/mistral-nemo-minitron-8b-8k-instruct\n8,192 tokens\nState-of-the-art small language model delivering superior accuracy for chatbot, virtual assistants, and content generation.\nnvidia/nemotron-4-mini-hindi-4b-instruct\n4,096 tokens\nA bilingual Hindi-English SLM for on-device inference, tailored specifically for Hindi Language.\nnvidia/llama-3.1-nemotron-70b-instruct\n128k tokens\nCustomized for enhanced helpfulness in responses\nnvidia/llama3-chatqa-1.5-8b\n128k tokens\nAdvanced LLM to generate high-quality, context-aware responses for chatbots and search engines.\nnvidia/llama3-chatqa-1.5-70b\n128k tokens\nAdvanced LLM to generate high-quality, context-aware responses for chatbots and search engines.\nnvidia/vila\n128k tokens\nMulti-modal vision-language model that understands text/img/video and creates informative responses\nnvidia/neva-22\n4,096 tokens\nMulti-modal vision-language model that understands text/images and generates informative responses\nnvidia/nemotron-mini-4b-instruct\n8,192 tokens\nGeneral-purpose tasks\nnvidia/usdcode-llama3-70b-instruct\n128k tokens\nState-of-the-art LLM that answers OpenUSD knowledge queries and generates USD-Python code.\nnvidia/nemotron-4-340b-instruct\n4,096 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nmeta/codellama-70b\n100k tokens\nLLM capable of generating code from natural language and vice versa.\nmeta/llama2-70b\n4,096 tokens\nCutting-edge large language AI model capable of generating text and code in response to prompts.\nmeta/llama3-8b-instruct\n8,192 tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nmeta/llama3-70b-instruct\n8,192 tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nmeta/llama-3.1-8b-instruct\n128k tokens\nAdvanced state-of-the-art model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.1-70b-instruct\n128k tokens\nPowers complex conversations with superior contextual understanding, reasoning and text generation.\nmeta/llama-3.1-405b-instruct\n128k tokens\nAdvanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks.\nmeta/llama-3.2-1b-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.2-3b-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.2-11b-vision-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\nmeta/llama-3.2-90b-vision-instruct\n128k tokens\nAdvanced state-of-the-art small language model with language understanding, superior reasoning, and text generation.\ngoogle/gemma-7b\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/gemma-2b\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/codegemma-7b\n8,192 tokens\nCutting-edge model built on Google’s Gemma-7B specialized for code generation and code completion.\ngoogle/codegemma-1.1-7b\n8,192 tokens\nAdvanced programming model for code generation, completion, reasoning, and instruction following.\ngoogle/recurrentgemma-2b\n8,192 tokens\nNovel recurrent architecture based language model for faster inference when generating long sequences.\ngoogle/gemma-2-9b-it\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/gemma-2-27b-it\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/gemma-2-2b-it\n8,192 tokens\nCutting-edge text generation model text understanding, transformation, and code generation.\ngoogle/deplot\n512 tokens\nOne-shot visual language understanding model that translates images of plots into tables.\ngoogle/paligemma\n8,192 tokens\nVision language model adept at comprehending text and visual inputs to produce informative responses.\nmistralai/mistral-7b-instruct-v0.2\n32k tokens\nThis LLM follows instructions, completes requests, and generates creative text.\nmistralai/mixtral-8x7b-instruct-v0.1\n8,192 tokens\nAn MOE LLM that follows instructions, completes requests, and generates creative text.\nmistralai/mistral-large\n4,096 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nmistralai/mixtral-8x22b-instruct-v0.1\n8,192 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nmistralai/mistral-7b-instruct-v0.3\n32k tokens\nThis LLM follows instructions, completes requests, and generates creative text.\nnv-mistralai/mistral-nemo-12b-instruct\n128k tokens\nMost advanced language model for reasoning, code, multilingual tasks; runs on a single GPU.\nmistralai/mamba-codestral-7b-v0.1\n256k tokens\nModel for writing and interacting with code across a wide range of programming languages and tasks.\nmicrosoft/phi-3-mini-128k-instruct\n128K tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-mini-4k-instruct\n4,096 tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-small-8k-instruct\n8,192 tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-small-128k-instruct\n128K tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-medium-4k-instruct\n4,096 tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3-medium-128k-instruct\n128K tokens\nLightweight, state-of-the-art open LLM with strong math and logical reasoning skills.\nmicrosoft/phi-3.5-mini-instruct\n128K tokens\nLightweight multilingual LLM powering AI applications in latency bound, memory/compute constrained environments\nmicrosoft/phi-3.5-moe-instruct\n128K tokens\nAdvanced LLM based on Mixture of Experts architecture to deliver compute efficient content generation\nmicrosoft/kosmos-2\n1,024 tokens\nGroundbreaking multimodal model designed to understand and reason about visual elements in images.\nmicrosoft/phi-3-vision-128k-instruct\n128k tokens\nCutting-edge open multimodal model exceling in high-quality reasoning from images.\nmicrosoft/phi-3.5-vision-instruct\n128k tokens\nCutting-edge open multimodal model exceling in high-quality reasoning from images.\ndatabricks/dbrx-instruct\n12k tokens\nA general-purpose LLM with state-of-the-art performance in language understanding, coding, and RAG.\nsnowflake/arctic\n1,024 tokens\nDelivers high efficiency inference for enterprise applications focused on SQL generation and coding.\naisingapore/sea-lion-7b-instruct\n4,096 tokens\nLLM to represent and serve the linguistic and cultural diversity of Southeast Asia\nibm/granite-8b-code-instruct\n4,096 tokens\nSoftware programming LLM for code generation, completion, explanation, and multi-turn conversion.\nibm/granite-34b-code-instruct\n8,192 tokens\nSoftware programming LLM for code generation, completion, explanation, and multi-turn conversion.\nibm/granite-3.0-8b-instruct\n4,096 tokens\nAdvanced Small Language Model supporting RAG, summarization, classification, code, and agentic AI\nibm/granite-3.0-3b-a800m-instruct\n4,096 tokens\nHighly efficient Mixture of Experts model for RAG, summarization, entity extraction, and classification\nmediatek/breeze-7b-instruct\n4,096 tokens\nCreates diverse synthetic data that mimics the characteristics of real-world data.\nupstage/solar-10.7b-instruct\n4,096 tokens\nExcels in NLP tasks, particularly in instruction-following, reasoning, and mathematics.\nwriter/palmyra-med-70b-32k\n32k tokens\nLeading LLM for accurate, contextually relevant responses in the medical domain.\nwriter/palmyra-med-70b\n32k tokens\nLeading LLM for accurate, contextually relevant responses in the medical domain.\nwriter/palmyra-fin-70b-32k\n32k tokens\nSpecialized LLM for financial analysis, reporting, and data processing\n01-ai/yi-large\n32k tokens\nPowerful model trained on English and Chinese for diverse tasks including chatbot and creative writing.\ndeepseek-ai/deepseek-coder-6.7b-instruct\n2k tokens\nPowerful coding model offering advanced capabilities in code generation, completion, and infilling\nrakuten/rakutenai-7b-instruct\n1,024 tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nrakuten/rakutenai-7b-chat\n1,024 tokens\nAdvanced state-of-the-art LLM with language understanding, superior reasoning, and text generation.\nbaichuan-inc/baichuan2-13b-chat\n4,096 tokens\nSupport Chinese and English chat, coding, math, instruction following, solving quizzes\nLocal NVIDIA NIM Deployed using WSL2\nNVIDIA NIM enables you to run powerful LLMs locally on your Windows machine using WSL2 (Windows Subsystem for Linux).\nThis approach allows you to leverage your NVIDIA GPU for private, secure, and cost-effective AI inference without relying on cloud services.\nPerfect for development, testing, or production scenarios where data privacy or offline capabilities are required.\nHere is a step-by-step guide to setting up a local NVIDIA NIM model:\n\n\n\n\nFollow installation instructions from \nNVIDIA Website\n\n\n\n\n\n\nInstall the local model. For Llama 3.1-8b follow \ninstructions\n\n\n\n\n\n\nConfigure your crewai local models:\n\n\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.llm \nimport\n LLM\n\n\n\n\nlocal_nvidia_nim_llm \n=\n LLM(\n\n\n model\n=\n\"openai/meta/llama-3.1-8b-instruct\"\n, \n# it's an openai-api compatible model\n\n\n base_url\n=\n\"http://localhost:8000/v1\"\n,\n\n\n api_key\n=\n\"\"\n, \n# api_key is required, but you can use any text\n\n\n)\n\n\n\n\n# Then you can use it in your crew:\n\n\n\n\n@CrewBase\n\n\nclass\n MyCrew\n():\n\n\n # ...\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n llm\n=\nlocal_nvidia_nim_llm\n\n\n )\n\n\n\n\n # ...\n\n\nGroq\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nGROQ_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"groq/llama-3.2-90b-text-preview\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nModel\nContext Window\nBest For\nLlama 3.1 70B/8B\n131,072 tokens\nHigh-performance, large context tasks\nLlama 3.2 Series\n8,192 tokens\nGeneral-purpose tasks\nMixtral 8x7B\n32,768 tokens\nBalanced performance and context\nIBM watsonx.ai\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Required\n\n\nWATSONX_URL\n=<\nyour-url>\n\n\nWATSONX_APIKEY\n=<\nyour-apikey>\n\n\nWATSONX_PROJECT_ID\n=<\nyour-project-id>\n\n\n\n\n# Optional\n\n\nWATSONX_TOKEN\n=<\nyour-token>\n\n\nWATSONX_DEPLOYMENT_SPACE_ID\n=<\nyour-space-id>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"watsonx/meta-llama/llama-3-1-70b-instruct\"\n,\n\n\n base_url\n=\n\"https://api.watsonx.ai/v1\"\n\n\n)\n\n\nOllama (Local LLMs)\n\n\nInstall Ollama: \nollama.ai\n\n\nRun a model: \nollama run llama3\n\n\nConfigure:\n\n\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"ollama/llama3:70b\"\n,\n\n\n base_url\n=\n\"http://localhost:11434\"\n\n\n)\n\n\nFireworks AI\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nFIREWORKS_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nPerplexity AI\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nPERPLEXITY_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"llama-3.1-sonar-large-128k-online\"\n,\n\n\n base_url\n=\n\"https://api.perplexity.ai/\"\n\n\n)\n\n\nHugging Face\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nHF_TOKEN\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"huggingface/meta-llama/Meta-Llama-3.1-8B-Instruct\"\n\n\n)\n\n\nSambaNova\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nSAMBANOVA_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"sambanova/Meta-Llama-3.1-8B-Instruct\"\n,\n\n\n temperature\n=\n0.7\n\n\n)\n\n\nModel\nContext Window\nBest For\nLlama 3.1 70B/8B\nUp to 131,072 tokens\nHigh-performance, large context tasks\nLlama 3.1 405B\n8,192 tokens\nHigh-performance and output quality\nLlama 3.2 Series\n8,192 tokens\nGeneral-purpose, multimodal tasks\nLlama 3.3 70B\nUp to 131,072 tokens\nHigh-performance and output quality\nQwen2 familly\n8,192 tokens\nHigh-performance and output quality\nCerebras\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\n# Required\n\n\nCEREBRAS_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"cerebras/llama3.1-70b\"\n,\n\n\n temperature\n=\n0.7\n,\n\n\n max_tokens\n=\n8192\n\n\n)\n\n\nCerebras features:\n\n\nFast inference speeds\n\n\nCompetitive pricing\n\n\nGood balance of speed and quality\n\n\nSupport for long context windows\n\n\nOpen Router\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nOPENROUTER_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"openrouter/deepseek/deepseek-r1\"\n,\n\n\n base_url\n=\n\"https://openrouter.ai/api/v1\"\n,\n\n\n api_key\n=\nOPENROUTER_API_KEY\n\n\n)\n\n\nOpen Router models:\n\n\nopenrouter/deepseek/deepseek-r1\n\n\nopenrouter/deepseek/deepseek-chat\n\n\nNebius AI Studio\nSet the following environment variables in your \n.env\n file:\nCode\nCopy\nAsk AI\nNEBIUS_API_KEY\n=<\nyour-api-key>\n\n\nExample usage in your CrewAI project:\nCode\nCopy\nAsk AI\nllm \n=\n LLM(\n\n\n model\n=\n\"nebius/Qwen/Qwen3-30B-A3B\"\n\n\n)\n\n\nNebius AI Studio features:\n\n\nLarge collection of open source models\n\n\nHigher rate limits\n\n\nCompetitive pricing\n\n\nGood balance of speed and quality\n\n\n\n\n​\nStreaming Responses\n\n\nCrewAI supports streaming responses from LLMs, allowing your application to receive and process outputs in real-time as they’re generated.\n\n\nBasic Setup\nEvent Handling\nAgent & Task Tracking\nEnable streaming by setting the \nstream\n parameter to \nTrue\n when initializing your LLM:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Create an LLM with streaming enabled\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4o\"\n,\n\n\n stream\n=\nTrue\n # Enable streaming\n\n\n)\n\n\nWhen streaming is enabled, responses are delivered in chunks as they’re generated, creating a more responsive user experience.\nEnable streaming by setting the \nstream\n parameter to \nTrue\n when initializing your LLM:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# Create an LLM with streaming enabled\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4o\"\n,\n\n\n stream\n=\nTrue\n # Enable streaming\n\n\n)\n\n\nWhen streaming is enabled, responses are delivered in chunks as they’re generated, creating a more responsive user experience.\nCrewAI emits events for each chunk received during streaming:\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n (\n\n\n LLMStreamChunkEvent\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(LLMStreamChunkEvent)\n\n\n def\n on_llm_stream_chunk\n(\nself\n, \nevent\n: LLMStreamChunkEvent):\n\n\n # Process each chunk as it arrives\n\n\n print\n(\nf\n\"Received chunk: \n{\nevent.chunk\n}\n\"\n)\n\n\n\n\nmy_listener \n=\n MyCustomListener()\n\n\nClick here\n for more details\nAll LLM events in CrewAI include agent and task information, allowing you to track and filter LLM interactions by specific agents or tasks:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n, Agent, Task, Crew\n\n\nfrom\n crewai.utilities.events \nimport\n LLMStreamChunkEvent\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n MyCustomListener\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(LLMStreamChunkEvent)\n\n\n def\n on_llm_stream_chunk\n(\nsource\n, \nevent\n):\n\n\n if\n researcher.id \n==\n event.agent_id:\n\n\n print\n(\n\"\n\\n\n==============\n\\n\n Got event:\"\n, event, \n\"\n\\n\n==============\n\\n\n\"\n)\n\n\n\n\n\n\nmy_listener \n=\n MyCustomListener()\n\n\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n, \nstream\n=\nTrue\n)\n\n\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n\"About User\"\n,\n\n\n goal\n=\n\"You know everything about the user.\"\n,\n\n\n backstory\n=\n\"\"\"You are a master at understanding people and their preferences.\"\"\"\n,\n\n\n llm\n=\nllm,\n\n\n)\n\n\n\n\nsearch \n=\n Task(\n\n\n description\n=\n\"Answer the following questions about the user: \n{question}\n\"\n,\n\n\n expected_output\n=\n\"An answer to the question.\"\n,\n\n\n agent\n=\nresearcher,\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\nagents\n=\n[researcher], \ntasks\n=\n[search])\n\n\n\n\nresult \n=\n crew.kickoff(\n\n\n inputs\n=\n{\n\"question\"\n: \n\"...\"\n}\n\n\n)\n\n\nThis feature is particularly useful for:\n\n\nDebugging specific agent behaviors\n\n\nLogging LLM usage by task type\n\n\nAuditing which agents are making what types of LLM calls\n\n\nPerformance monitoring of specific tasks\n\n\n\n\n​\nStructured LLM Calls\n\n\nCrewAI supports structured responses from LLM calls by allowing you to define a \nresponse_format\n using a Pydantic model. This enables the framework to automatically parse and validate the output, making it easier to integrate the response into your application without manual post-processing.\n\n\nFor example, you can define a Pydantic model to represent the expected response structure and pass it as the \nresponse_format\n when instantiating the LLM. The model will then be used to convert the LLM output into a structured Python object.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\nclass\n Dog\n(\nBaseModel\n):\n\n\n name: \nstr\n\n\n age: \nint\n\n\n breed: \nstr\n\n\n\n\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o\"\n, \nresponse_format\n=\nDog)\n\n\n\n\nresponse \n=\n llm.call(\n\n\n \"Analyze the following messages and return the name, age, and breed. \"\n\n\n \"Meet Kona! She is 3 years old and is a black german shepherd.\"\n\n\n)\n\n\nprint\n(response)\n\n\n\n\n# Output:\n\n\n# Dog(name='Kona', age=3, breed='black german shepherd')\n\n\n\n\n​\nAdvanced Features and Optimization\n\n\nLearn how to get the most out of your LLM configuration:\n\n\nContext Window Management\nCrewAI includes smart context management features:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\n\n\n# CrewAI automatically handles:\n\n\n# 1. Token counting and tracking\n\n\n# 2. Content summarization when needed\n\n\n# 3. Task splitting for large contexts\n\n\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"gpt-4\"\n,\n\n\n max_tokens\n=\n4000\n, \n# Limit response length\n\n\n)\n\n\nBest practices for context management:\n\n\nChoose models with appropriate context windows\n\n\nPre-process long inputs when possible\n\n\nUse chunking for large documents\n\n\nMonitor token usage to optimize costs\n\n\nPerformance Optimization\n1\nToken Usage Optimization\nChoose the right context window for your task:\n\n\nSmall tasks (up to 4K tokens): Standard models\n\n\nMedium tasks (between 4K-32K): Enhanced models\n\n\nLarge tasks (over 32K): Large context models\n\n\nCopy\nAsk AI\n# Configure model with appropriate settings\n\n\nllm \n=\n LLM(\n\n\n model\n=\n\"openai/gpt-4-turbo-preview\"\n,\n\n\n temperature\n=\n0.7\n, \n# Adjust based on task\n\n\n max_tokens\n=\n4096\n, \n# Set based on output needs\n\n\n timeout\n=\n300\n # Longer timeout for complex tasks\n\n\n)\n\n\n\n\nLower temperature (0.1 to 0.3) for factual responses\n\n\nHigher temperature (0.7 to 0.9) for creative tasks\n\n\n2\nBest Practices\n\n\nMonitor token usage\n\n\nImplement rate limiting\n\n\nUse caching when possible\n\n\nSet appropriate max_tokens limits\n\n\nRemember to regularly monitor your token usage and adjust your configuration as needed to optimize costs and performance.\nDrop Additional Parameters\nCrewAI internally uses Litellm for LLM calls, which allows you to drop additional parameters that are not needed for your specific use case. This can help simplify your code and reduce the complexity of your LLM configuration.\nFor example, if you don’t need to send the \nstop\n parameter, you can simply omit it from your LLM call:\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n\n\nimport\n os\n\n\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"\"\n\n\n\n\no3_llm \n=\n LLM(\n\n\n model\n=\n\"o3\"\n,\n\n\n drop_params\n=\nTrue\n,\n\n\n additional_drop_params\n=\n[\n\"stop\"\n]\n\n\n)\n\n\n\n\n​\nCommon Issues and Solutions\n\n\nAuthentication\nModel Names\nContext Length\nMost authentication issues can be resolved by checking API key format and environment variable names.\nCopy\nAsk AI\n# OpenAI\n\n\nOPENAI_API_KEY\n=\nsk-...\n\n\n\n\n# Anthropic\n\n\nANTHROPIC_API_KEY\n=\nsk-ant-...\n\n\nMost authentication issues can be resolved by checking API key format and environment variable names.\nCopy\nAsk AI\n# OpenAI\n\n\nOPENAI_API_KEY\n=\nsk-...\n\n\n\n\n# Anthropic\n\n\nANTHROPIC_API_KEY\n=\nsk-ant-...\n\n\nAlways include the provider prefix in model names\nCopy\nAsk AI\n# Correct\n\n\nllm \n=\n LLM(\nmodel\n=\n\"openai/gpt-4\"\n)\n\n\n\n\n# Incorrect\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4\"\n)\n\n\nUse larger context models for extensive tasks\nCopy\nAsk AI\n# Large context model\n\n\nllm \n=\n LLM(\nmodel\n=\n\"openai/gpt-4o\"\n) \n# 128K tokens\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nKnowledge\nProcesses\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nWhat are LLMs?\nSetting up your LLM\nProvider Configuration Examples\nStreaming Responses\nStructured LLM Calls\nAdvanced Features and Optimization\nCommon Issues and Solutions" }, { "source": "https://docs.crewai.com/en/learn/customizing-agents", "title": "Customize Agents - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nCustomize Agents\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nCustomize Agents\nCopy page\nA comprehensive guide to tailoring agents for specific roles, tasks, and advanced customizations within the CrewAI framework.\n​\nCustomizable Attributes\n\n\nCrafting an efficient CrewAI team hinges on the ability to dynamically tailor your AI agents to meet the unique requirements of any project. This section covers the foundational attributes you can customize.\n\n\n​\nKey Attributes for Customization\n\n\nAttribute\nDescription\nRole\nSpecifies the agent’s job within the crew, such as ‘Analyst’ or ‘Customer Service Rep’.\nGoal\nDefines the agent’s objectives, aligned with its role and the crew’s overarching mission.\nBackstory\nProvides depth to the agent’s persona, enhancing motivations and engagements within the crew.\nTools\n \n(Optional)\nRepresents the capabilities or methods the agent uses for tasks, from simple functions to complex integrations.\nCache\n \n(Optional)\nDetermines if the agent should use a cache for tool usage.\nMax RPM\nSets the maximum requests per minute (\nmax_rpm\n). Can be set to \nNone\n for unlimited requests to external services.\nVerbose\n \n(Optional)\nEnables detailed logging for debugging and optimization, providing insights into execution processes.\nAllow Delegation\n \n(Optional)\nControls task delegation to other agents, default is \nFalse\n.\nMax Iter\n \n(Optional)\nLimits the maximum number of iterations (\nmax_iter\n) for a task to prevent infinite loops, with a default of 25.\nMax Execution Time\n \n(Optional)\nSets the maximum time allowed for an agent to complete a task.\nSystem Template\n \n(Optional)\nDefines the system format for the agent.\nPrompt Template\n \n(Optional)\nDefines the prompt format for the agent.\nResponse Template\n \n(Optional)\nDefines the response format for the agent.\nUse System Prompt\n \n(Optional)\nControls whether the agent will use a system prompt during task execution.\nRespect Context Window\nEnables a sliding context window by default, maintaining context size.\nMax Retry Limit\nSets the maximum number of retries (\nmax_retry_limit\n) for an agent in case of errors.\n\n\n​\nAdvanced Customization Options\n\n\nBeyond the basic attributes, CrewAI allows for deeper customization to enhance an agent’s behavior and capabilities significantly.\n\n\n​\nLanguage Model Customization\n\n\nAgents can be customized with specific language models (\nllm\n) and function-calling language models (\nfunction_calling_llm\n), offering advanced control over their processing and decision-making abilities.\nIt’s important to note that setting the \nfunction_calling_llm\n allows for overriding the default crew function-calling language model, providing a greater degree of customization.\n\n\n​\nPerformance and Debugging Settings\n\n\nAdjusting an agent’s performance and monitoring its operations are crucial for efficient task execution.\n\n\n​\nVerbose Mode and RPM Limit\n\n\n\n\nVerbose Mode\n: Enables detailed logging of an agent’s actions, useful for debugging and optimization. Specifically, it provides insights into agent execution processes, aiding in the optimization of performance.\n\n\nRPM Limit\n: Sets the maximum number of requests per minute (\nmax_rpm\n). This attribute is optional and can be set to \nNone\n for no limit, allowing for unlimited queries to external services if needed.\n\n\n\n\n​\nMaximum Iterations for Task Execution\n\n\nThe \nmax_iter\n attribute allows users to define the maximum number of iterations an agent can perform for a single task, preventing infinite loops or excessively long executions.\nThe default value is set to 25, providing a balance between thoroughness and efficiency. Once the agent approaches this number, it will try its best to give a good answer.\n\n\n​\nCustomizing Agents and Tools\n\n\nAgents are customized by defining their attributes and tools during initialization. Tools are critical for an agent’s functionality, enabling them to perform specialized tasks.\nThe \ntools\n attribute should be an array of tools the agent can utilize, and it’s initialized as an empty list by default. Tools can be added or modified post-agent initialization to adapt to new requirements.\n\n\nCopy\nAsk AI\npip\n install\n 'crewai[tools]'\n\n\n\n\n​\nExample: Assigning Tools to an Agent\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Set API keys for tool initialization\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n\n\n\n\n# Initialize a search tool\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\n# Initialize the agent with advanced options\n\n\nagent \n=\n Agent(\n\n\n role\n=\n'Research Analyst'\n,\n\n\n goal\n=\n'Provide up-to-date market analysis'\n,\n\n\n backstory\n=\n'An expert analyst with a keen eye for market trends.'\n,\n\n\n tools\n=\n[search_tool],\n\n\n memory\n=\nTrue\n, \n# Enable memory\n\n\n verbose\n=\nTrue\n,\n\n\n max_rpm\n=\nNone\n, \n# No limit on requests per minute\n\n\n max_iter\n=\n25\n, \n# Default value for maximum iterations\n\n\n)\n\n\n\n\n​\nDelegation and Autonomy\n\n\nControlling an agent’s ability to delegate tasks or ask questions is vital for tailoring its autonomy and collaborative dynamics within the CrewAI framework. By default,\nthe \nallow_delegation\n attribute is now set to \nFalse\n, disabling agents to seek assistance or delegate tasks as needed. This default behavior can be changed to promote collaborative problem-solving and\nefficiency within the CrewAI ecosystem. If needed, delegation can be enabled to suit specific operational requirements.\n\n\n​\nExample: Disabling Delegation for an Agent\n\n\nCode\nCopy\nAsk AI\nagent \n=\n Agent(\n\n\n role\n=\n'Content Writer'\n,\n\n\n goal\n=\n'Write engaging content on market trends'\n,\n\n\n backstory\n=\n'A seasoned writer with expertise in market analysis.'\n,\n\n\n allow_delegation\n=\nTrue\n # Enabling delegation\n\n\n)\n\n\n\n\n​\nConclusion\n\n\nCustomizing agents in CrewAI by setting their roles, goals, backstories, and tools, alongside advanced options like language model customization, memory, performance settings, and delegation preferences,\nequips a nuanced and capable AI team ready for complex challenges.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCustom Manager Agent\nImage Generation with DALL-E\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nCustomizable Attributes\nKey Attributes for Customization\nAdvanced Customization Options\nLanguage Model Customization\nPerformance and Debugging Settings\nVerbose Mode and RPM Limit\nMaximum Iterations for Task Execution\nCustomizing Agents and Tools\nExample: Assigning Tools to an Agent\nDelegation and Autonomy\nExample: Disabling Delegation for an Agent\nConclusion\nLearn\nCustomize Agents\nCopy page\nA comprehensive guide to tailoring agents for specific roles, tasks, and advanced customizations within the CrewAI framework.\n​\nCustomizable Attributes\n\n\nCrafting an efficient CrewAI team hinges on the ability to dynamically tailor your AI agents to meet the unique requirements of any project. This section covers the foundational attributes you can customize.\n\n\n​\nKey Attributes for Customization\n\n\nAttribute\nDescription\nRole\nSpecifies the agent’s job within the crew, such as ‘Analyst’ or ‘Customer Service Rep’.\nGoal\nDefines the agent’s objectives, aligned with its role and the crew’s overarching mission.\nBackstory\nProvides depth to the agent’s persona, enhancing motivations and engagements within the crew.\nTools\n \n(Optional)\nRepresents the capabilities or methods the agent uses for tasks, from simple functions to complex integrations.\nCache\n \n(Optional)\nDetermines if the agent should use a cache for tool usage.\nMax RPM\nSets the maximum requests per minute (\nmax_rpm\n). Can be set to \nNone\n for unlimited requests to external services.\nVerbose\n \n(Optional)\nEnables detailed logging for debugging and optimization, providing insights into execution processes.\nAllow Delegation\n \n(Optional)\nControls task delegation to other agents, default is \nFalse\n.\nMax Iter\n \n(Optional)\nLimits the maximum number of iterations (\nmax_iter\n) for a task to prevent infinite loops, with a default of 25.\nMax Execution Time\n \n(Optional)\nSets the maximum time allowed for an agent to complete a task.\nSystem Template\n \n(Optional)\nDefines the system format for the agent.\nPrompt Template\n \n(Optional)\nDefines the prompt format for the agent.\nResponse Template\n \n(Optional)\nDefines the response format for the agent.\nUse System Prompt\n \n(Optional)\nControls whether the agent will use a system prompt during task execution.\nRespect Context Window\nEnables a sliding context window by default, maintaining context size.\nMax Retry Limit\nSets the maximum number of retries (\nmax_retry_limit\n) for an agent in case of errors.\n\n\n​\nAdvanced Customization Options\n\n\nBeyond the basic attributes, CrewAI allows for deeper customization to enhance an agent’s behavior and capabilities significantly.\n\n\n​\nLanguage Model Customization\n\n\nAgents can be customized with specific language models (\nllm\n) and function-calling language models (\nfunction_calling_llm\n), offering advanced control over their processing and decision-making abilities.\nIt’s important to note that setting the \nfunction_calling_llm\n allows for overriding the default crew function-calling language model, providing a greater degree of customization.\n\n\n​\nPerformance and Debugging Settings\n\n\nAdjusting an agent’s performance and monitoring its operations are crucial for efficient task execution.\n\n\n​\nVerbose Mode and RPM Limit\n\n\n\n\nVerbose Mode\n: Enables detailed logging of an agent’s actions, useful for debugging and optimization. Specifically, it provides insights into agent execution processes, aiding in the optimization of performance.\n\n\nRPM Limit\n: Sets the maximum number of requests per minute (\nmax_rpm\n). This attribute is optional and can be set to \nNone\n for no limit, allowing for unlimited queries to external services if needed.\n\n\n\n\n​\nMaximum Iterations for Task Execution\n\n\nThe \nmax_iter\n attribute allows users to define the maximum number of iterations an agent can perform for a single task, preventing infinite loops or excessively long executions.\nThe default value is set to 25, providing a balance between thoroughness and efficiency. Once the agent approaches this number, it will try its best to give a good answer.\n\n\n​\nCustomizing Agents and Tools\n\n\nAgents are customized by defining their attributes and tools during initialization. Tools are critical for an agent’s functionality, enabling them to perform specialized tasks.\nThe \ntools\n attribute should be an array of tools the agent can utilize, and it’s initialized as an empty list by default. Tools can be added or modified post-agent initialization to adapt to new requirements.\n\n\nCopy\nAsk AI\npip\n install\n 'crewai[tools]'\n\n\n\n\n​\nExample: Assigning Tools to an Agent\n\n\nCode\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Agent\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\n\n\n# Set API keys for tool initialization\n\n\nos.environ[\n\"OPENAI_API_KEY\"\n] \n=\n \"Your Key\"\n\n\nos.environ[\n\"SERPER_API_KEY\"\n] \n=\n \"Your Key\"\n\n\n\n\n# Initialize a search tool\n\n\nsearch_tool \n=\n SerperDevTool()\n\n\n\n\n# Initialize the agent with advanced options\n\n\nagent \n=\n Agent(\n\n\n role\n=\n'Research Analyst'\n,\n\n\n goal\n=\n'Provide up-to-date market analysis'\n,\n\n\n backstory\n=\n'An expert analyst with a keen eye for market trends.'\n,\n\n\n tools\n=\n[search_tool],\n\n\n memory\n=\nTrue\n, \n# Enable memory\n\n\n verbose\n=\nTrue\n,\n\n\n max_rpm\n=\nNone\n, \n# No limit on requests per minute\n\n\n max_iter\n=\n25\n, \n# Default value for maximum iterations\n\n\n)\n\n\n\n\n​\nDelegation and Autonomy\n\n\nControlling an agent’s ability to delegate tasks or ask questions is vital for tailoring its autonomy and collaborative dynamics within the CrewAI framework. By default,\nthe \nallow_delegation\n attribute is now set to \nFalse\n, disabling agents to seek assistance or delegate tasks as needed. This default behavior can be changed to promote collaborative problem-solving and\nefficiency within the CrewAI ecosystem. If needed, delegation can be enabled to suit specific operational requirements.\n\n\n​\nExample: Disabling Delegation for an Agent\n\n\nCode\nCopy\nAsk AI\nagent \n=\n Agent(\n\n\n role\n=\n'Content Writer'\n,\n\n\n goal\n=\n'Write engaging content on market trends'\n,\n\n\n backstory\n=\n'A seasoned writer with expertise in market analysis.'\n,\n\n\n allow_delegation\n=\nTrue\n # Enabling delegation\n\n\n)\n\n\n\n\n​\nConclusion\n\n\nCustomizing agents in CrewAI by setting their roles, goals, backstories, and tools, alongside advanced options like language model customization, memory, performance settings, and delegation preferences,\nequips a nuanced and capable AI team ready for complex challenges.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCustom Manager Agent\nImage Generation with DALL-E\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nCustomizable Attributes\nKey Attributes for Customization\nAdvanced Customization Options\nLanguage Model Customization\nPerformance and Debugging Settings\nVerbose Mode and RPM Limit\nMaximum Iterations for Task Execution\nCustomizing Agents and Tools\nExample: Assigning Tools to an Agent\nDelegation and Autonomy\nExample: Disabling Delegation for an Agent\nConclusion" }, { "source": "https://docs.crewai.com/en/learn/overview", "title": "Overview - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nOverview\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nOverview\nCopy page\nLearn how to build, customize, and optimize your CrewAI applications with comprehensive guides and tutorials\n​\nLearn CrewAI\n\n\nThis section provides comprehensive guides and tutorials to help you master CrewAI, from basic concepts to advanced techniques. Whether you’re just getting started or looking to optimize your existing implementations, these resources will guide you through every aspect of building powerful AI agent workflows.\n\n\n​\nGetting Started Guides\n\n\n​\nCore Concepts\n\n\nSequential Process\nLearn how to execute tasks in a sequential order for structured workflows.\nHierarchical Process\nImplement hierarchical task execution with manager agents overseeing workflows.\nConditional Tasks\nCreate dynamic workflows with conditional task execution based on outcomes.\nAsync Kickoff\nExecute crews asynchronously for improved performance and concurrency.\n\n\n​\nAgent Development\n\n\nCustomizing Agents\nLearn how to customize agent behavior, roles, and capabilities.\nCoding Agents\nBuild agents that can write, execute, and debug code automatically.\nMultimodal Agents\nCreate agents that can process text, images, and other media types.\nCustom Manager Agent\nImplement custom manager agents for complex hierarchical workflows.\n\n\n​\nAdvanced Features\n\n\n​\nWorkflow Control\n\n\nHuman in the Loop\nIntegrate human oversight and intervention into agent workflows.\nHuman Input on Execution\nAllow human input during task execution for dynamic decision making.\nReplay Tasks\nReplay and resume tasks from previous crew executions.\nKickoff for Each\nExecute crews multiple times with different inputs efficiently.\n\n\n​\nCustomization & Integration\n\n\nCustom LLM\nIntegrate custom language models and providers with CrewAI.\nLLM Connections\nConfigure and manage connections to various LLM providers.\nCreate Custom Tools\nBuild custom tools to extend agent capabilities.\nUsing Annotations\nUse Python annotations for cleaner, more maintainable code.\n\n\n​\nSpecialized Applications\n\n\n​\nContent & Media\n\n\nDALL-E Image Generation\nGenerate images using DALL-E integration with your agents.\nBring Your Own Agent\nIntegrate existing agents and models into CrewAI workflows.\n\n\n​\nTool Management\n\n\nForce Tool Output as Result\nConfigure tools to return their output directly as task results.\n\n\n​\nLearning Path Recommendations\n\n\n​\nFor Beginners\n\n\n\n\nStart with \nSequential Process\n to understand basic workflow execution\n\n\nLearn \nCustomizing Agents\n to create effective agent configurations\n\n\nExplore \nCreate Custom Tools\n to extend functionality\n\n\nTry \nHuman in the Loop\n for interactive workflows\n\n\n\n\n​\nFor Intermediate Users\n\n\n\n\nMaster \nHierarchical Process\n for complex multi-agent systems\n\n\nImplement \nConditional Tasks\n for dynamic workflows\n\n\nUse \nAsync Kickoff\n for performance optimization\n\n\nIntegrate \nCustom LLM\n for specialized models\n\n\n\n\n​\nFor Advanced Users\n\n\n\n\nBuild \nMultimodal Agents\n for complex media processing\n\n\nCreate \nCustom Manager Agents\n for sophisticated orchestration\n\n\nImplement \nBring Your Own Agent\n for hybrid systems\n\n\nUse \nReplay Tasks\n for robust error recovery\n\n\n\n\n​\nBest Practices\n\n\n​\nDevelopment\n\n\n\n\nStart Simple\n: Begin with basic sequential workflows before adding complexity\n\n\nTest Incrementally\n: Test each component before integrating into larger systems\n\n\nUse Annotations\n: Leverage Python annotations for cleaner, more maintainable code\n\n\nCustom Tools\n: Build reusable tools that can be shared across different agents\n\n\n\n\n​\nProduction\n\n\n\n\nError Handling\n: Implement robust error handling and recovery mechanisms\n\n\nPerformance\n: Use async execution and optimize LLM calls for better performance\n\n\nMonitoring\n: Integrate observability tools to track agent performance\n\n\nHuman Oversight\n: Include human checkpoints for critical decisions\n\n\n\n\n​\nOptimization\n\n\n\n\nResource Management\n: Monitor and optimize token usage and API costs\n\n\nWorkflow Design\n: Design workflows that minimize unnecessary LLM calls\n\n\nTool Efficiency\n: Create efficient tools that provide maximum value with minimal overhead\n\n\nIterative Improvement\n: Use feedback and metrics to continuously improve agent performance\n\n\n\n\n​\nGetting Help\n\n\n\n\nDocumentation\n: Each guide includes detailed examples and explanations\n\n\nCommunity\n: Join the \nCrewAI Forum\n for discussions and support\n\n\nExamples\n: Check the Examples section for complete working implementations\n\n\nSupport\n: Contact \nsupport@crewai.com\n for technical assistance\n\n\n\n\nStart with the guides that match your current needs and gradually explore more advanced topics as you become comfortable with the fundamentals.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nWeave Integration\nStrategic LLM Selection Guide\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nLearn CrewAI\nGetting Started Guides\nCore Concepts\nAgent Development\nAdvanced Features\nWorkflow Control\nCustomization & Integration\nSpecialized Applications\nContent & Media\nTool Management\nLearning Path Recommendations\nFor Beginners\nFor Intermediate Users\nFor Advanced Users\nBest Practices\nDevelopment\nProduction\nOptimization\nGetting Help\nLearn\nOverview\nCopy page\nLearn how to build, customize, and optimize your CrewAI applications with comprehensive guides and tutorials\n​\nLearn CrewAI\n\n\nThis section provides comprehensive guides and tutorials to help you master CrewAI, from basic concepts to advanced techniques. Whether you’re just getting started or looking to optimize your existing implementations, these resources will guide you through every aspect of building powerful AI agent workflows.\n\n\n​\nGetting Started Guides\n\n\n​\nCore Concepts\n\n\nSequential Process\nLearn how to execute tasks in a sequential order for structured workflows.\nHierarchical Process\nImplement hierarchical task execution with manager agents overseeing workflows.\nConditional Tasks\nCreate dynamic workflows with conditional task execution based on outcomes.\nAsync Kickoff\nExecute crews asynchronously for improved performance and concurrency.\n\n\n​\nAgent Development\n\n\nCustomizing Agents\nLearn how to customize agent behavior, roles, and capabilities.\nCoding Agents\nBuild agents that can write, execute, and debug code automatically.\nMultimodal Agents\nCreate agents that can process text, images, and other media types.\nCustom Manager Agent\nImplement custom manager agents for complex hierarchical workflows.\n\n\n​\nAdvanced Features\n\n\n​\nWorkflow Control\n\n\nHuman in the Loop\nIntegrate human oversight and intervention into agent workflows.\nHuman Input on Execution\nAllow human input during task execution for dynamic decision making.\nReplay Tasks\nReplay and resume tasks from previous crew executions.\nKickoff for Each\nExecute crews multiple times with different inputs efficiently.\n\n\n​\nCustomization & Integration\n\n\nCustom LLM\nIntegrate custom language models and providers with CrewAI.\nLLM Connections\nConfigure and manage connections to various LLM providers.\nCreate Custom Tools\nBuild custom tools to extend agent capabilities.\nUsing Annotations\nUse Python annotations for cleaner, more maintainable code.\n\n\n​\nSpecialized Applications\n\n\n​\nContent & Media\n\n\nDALL-E Image Generation\nGenerate images using DALL-E integration with your agents.\nBring Your Own Agent\nIntegrate existing agents and models into CrewAI workflows.\n\n\n​\nTool Management\n\n\nForce Tool Output as Result\nConfigure tools to return their output directly as task results.\n\n\n​\nLearning Path Recommendations\n\n\n​\nFor Beginners\n\n\n\n\nStart with \nSequential Process\n to understand basic workflow execution\n\n\nLearn \nCustomizing Agents\n to create effective agent configurations\n\n\nExplore \nCreate Custom Tools\n to extend functionality\n\n\nTry \nHuman in the Loop\n for interactive workflows\n\n\n\n\n​\nFor Intermediate Users\n\n\n\n\nMaster \nHierarchical Process\n for complex multi-agent systems\n\n\nImplement \nConditional Tasks\n for dynamic workflows\n\n\nUse \nAsync Kickoff\n for performance optimization\n\n\nIntegrate \nCustom LLM\n for specialized models\n\n\n\n\n​\nFor Advanced Users\n\n\n\n\nBuild \nMultimodal Agents\n for complex media processing\n\n\nCreate \nCustom Manager Agents\n for sophisticated orchestration\n\n\nImplement \nBring Your Own Agent\n for hybrid systems\n\n\nUse \nReplay Tasks\n for robust error recovery\n\n\n\n\n​\nBest Practices\n\n\n​\nDevelopment\n\n\n\n\nStart Simple\n: Begin with basic sequential workflows before adding complexity\n\n\nTest Incrementally\n: Test each component before integrating into larger systems\n\n\nUse Annotations\n: Leverage Python annotations for cleaner, more maintainable code\n\n\nCustom Tools\n: Build reusable tools that can be shared across different agents\n\n\n\n\n​\nProduction\n\n\n\n\nError Handling\n: Implement robust error handling and recovery mechanisms\n\n\nPerformance\n: Use async execution and optimize LLM calls for better performance\n\n\nMonitoring\n: Integrate observability tools to track agent performance\n\n\nHuman Oversight\n: Include human checkpoints for critical decisions\n\n\n\n\n​\nOptimization\n\n\n\n\nResource Management\n: Monitor and optimize token usage and API costs\n\n\nWorkflow Design\n: Design workflows that minimize unnecessary LLM calls\n\n\nTool Efficiency\n: Create efficient tools that provide maximum value with minimal overhead\n\n\nIterative Improvement\n: Use feedback and metrics to continuously improve agent performance\n\n\n\n\n​\nGetting Help\n\n\n\n\nDocumentation\n: Each guide includes detailed examples and explanations\n\n\nCommunity\n: Join the \nCrewAI Forum\n for discussions and support\n\n\nExamples\n: Check the Examples section for complete working implementations\n\n\nSupport\n: Contact \nsupport@crewai.com\n for technical assistance\n\n\n\n\nStart with the guides that match your current needs and gradually explore more advanced topics as you become comfortable with the fundamentals.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nWeave Integration\nStrategic LLM Selection Guide\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nLearn CrewAI\nGetting Started Guides\nCore Concepts\nAgent Development\nAdvanced Features\nWorkflow Control\nCustomization & Integration\nSpecialized Applications\nContent & Media\nTool Management\nLearning Path Recommendations\nFor Beginners\nFor Intermediate Users\nFor Advanced Users\nBest Practices\nDevelopment\nProduction\nOptimization\nGetting Help" }, { "source": "https://docs.crewai.com/en/concepts/flows", "title": "Flows - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nFlows\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nFlows\nCopy page\nLearn how to create and manage AI workflows using CrewAI Flows.\n​\nOverview\n\n\nCrewAI Flows is a powerful feature designed to streamline the creation and management of AI workflows. Flows allow developers to combine and coordinate coding tasks and Crews efficiently, providing a robust framework for building sophisticated AI automations.\n\n\nFlows allow you to create structured, event-driven workflows. They provide a seamless way to connect multiple tasks, manage state, and control the flow of execution in your AI applications. With Flows, you can easily design and implement multi-step processes that leverage the full potential of CrewAI’s capabilities.\n\n\n\n\n\n\nSimplified Workflow Creation\n: Easily chain together multiple Crews and tasks to create complex AI workflows.\n\n\n\n\n\n\nState Management\n: Flows make it super easy to manage and share state between different tasks in your workflow.\n\n\n\n\n\n\nEvent-Driven Architecture\n: Built on an event-driven model, allowing for dynamic and responsive workflows.\n\n\n\n\n\n\nFlexible Control Flow\n: Implement conditional logic, loops, and branching within your workflows.\n\n\n\n\n\n\n​\nGetting Started\n\n\nLet’s create a simple Flow where you will use OpenAI to generate a random city in one task and then use that city to generate a fun fact in another task.\n\n\nCode\nCopy\nAsk AI\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n dotenv \nimport\n load_dotenv\n\n\nfrom\n litellm \nimport\n completion\n\n\n\n\n\n\nclass\n ExampleFlow\n(\nFlow\n):\n\n\n model \n=\n \"gpt-4o-mini\"\n\n\n\n\n @start\n()\n\n\n def\n generate_city\n(\nself\n):\n\n\n print\n(\n\"Starting flow\"\n)\n\n\n # Each flow state automatically gets a unique ID\n\n\n print\n(\nf\n\"Flow State ID: \n{\nself\n.state[\n'id'\n]\n}\n\"\n)\n\n\n\n\n response \n=\n completion(\n\n\n model\n=\nself\n.model,\n\n\n messages\n=\n[\n\n\n {\n\n\n \"role\"\n: \n\"user\"\n,\n\n\n \"content\"\n: \n\"Return the name of a random city in the world.\"\n,\n\n\n },\n\n\n ],\n\n\n )\n\n\n\n\n random_city \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n # Store the city in our state\n\n\n self\n.state[\n\"city\"\n] \n=\n random_city\n\n\n print\n(\nf\n\"Random City: \n{\nrandom_city\n}\n\"\n)\n\n\n\n\n return\n random_city\n\n\n\n\n @listen\n(generate_city)\n\n\n def\n generate_fun_fact\n(\nself\n, \nrandom_city\n):\n\n\n response \n=\n completion(\n\n\n model\n=\nself\n.model,\n\n\n messages\n=\n[\n\n\n {\n\n\n \"role\"\n: \n\"user\"\n,\n\n\n \"content\"\n: \nf\n\"Tell me a fun fact about \n{\nrandom_city\n}\n\"\n,\n\n\n },\n\n\n ],\n\n\n )\n\n\n\n\n fun_fact \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n # Store the fun fact in our state\n\n\n self\n.state[\n\"fun_fact\"\n] \n=\n fun_fact\n\n\n return\n fun_fact\n\n\n\n\n\n\n\n\nflow \n=\n ExampleFlow()\n\n\nflow.plot()\n\n\nresult \n=\n flow.kickoff()\n\n\n\n\nprint\n(\nf\n\"Generated fun fact: \n{\nresult\n}\n\"\n)\n\n\n\n\n\nIn the above example, we have created a simple Flow that generates a random city using OpenAI and then generates a fun fact about that city. The Flow consists of two tasks: \ngenerate_city\n and \ngenerate_fun_fact\n. The \ngenerate_city\n task is the starting point of the Flow, and the \ngenerate_fun_fact\n task listens for the output of the \ngenerate_city\n task.\n\n\nEach Flow instance automatically receives a unique identifier (UUID) in its state, which helps track and manage flow executions. The state can also store additional data (like the generated city and fun fact) that persists throughout the flow’s execution.\n\n\nWhen you run the Flow, it will:\n\n\n\n\nGenerate a unique ID for the flow state\n\n\nGenerate a random city and store it in the state\n\n\nGenerate a fun fact about that city and store it in the state\n\n\nPrint the results to the console\n\n\n\n\nThe state’s unique ID and stored data can be useful for tracking flow executions and maintaining context between tasks.\n\n\nNote:\n Ensure you have set up your \n.env\n file to store your \nOPENAI_API_KEY\n. This key is necessary for authenticating requests to the OpenAI API.\n\n\n​\n@start()\n\n\nThe \n@start()\n decorator is used to mark a method as the starting point of a Flow. When a Flow is started, all the methods decorated with \n@start()\n are executed in parallel. You can have multiple start methods in a Flow, and they will all be executed when the Flow is started.\n\n\n​\n@listen()\n\n\nThe \n@listen()\n decorator is used to mark a method as a listener for the output of another task in the Flow. The method decorated with \n@listen()\n will be executed when the specified task emits an output. The method can access the output of the task it is listening to as an argument.\n\n\n​\nUsage\n\n\nThe \n@listen()\n decorator can be used in several ways:\n\n\n\n\n\n\nListening to a Method by Name\n: You can pass the name of the method you want to listen to as a string. When that method completes, the listener method will be triggered.\n\n\nCode\nCopy\nAsk AI\n@listen\n(\n\"generate_city\"\n)\n\n\ndef\n generate_fun_fact\n(\nself\n, \nrandom_city\n):\n\n\n # Implementation\n\n\n\n\n\n\n\n\nListening to a Method Directly\n: You can pass the method itself. When that method completes, the listener method will be triggered.\n\n\nCode\nCopy\nAsk AI\n@listen\n(generate_city)\n\n\ndef\n generate_fun_fact\n(\nself\n, \nrandom_city\n):\n\n\n # Implementation\n\n\n\n\n\n\n\n\n​\nFlow Output\n\n\nAccessing and handling the output of a Flow is essential for integrating your AI workflows into larger applications or systems. CrewAI Flows provide straightforward mechanisms to retrieve the final output, access intermediate results, and manage the overall state of your Flow.\n\n\n​\nRetrieving the Final Output\n\n\nWhen you run a Flow, the final output is determined by the last method that completes. The \nkickoff()\n method returns the output of this final method.\n\n\nHere’s how you can access the final output:\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\n\n\nclass\n OutputExampleFlow\n(\nFlow\n):\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n return\n \"Output from first_method\"\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n, \nfirst_output\n):\n\n\n return\n f\n\"Second method received: \n{\nfirst_output\n}\n\"\n\n\n\n\n\n\nflow \n=\n OutputExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nfinal_output \n=\n flow.kickoff()\n\n\n\n\nprint\n(\n\"---- Final Output ----\"\n)\n\n\nprint\n(final_output)\n\n\n\n\n\n\nIn this example, the \nsecond_method\n is the last method to complete, so its output will be the final output of the Flow.\nThe \nkickoff()\n method will return the final output, which is then printed to the console. The \nplot()\n method will generate the HTML file, which will help you understand the flow.\n\n\n​\nAccessing and Updating State\n\n\nIn addition to retrieving the final output, you can also access and update the state within your Flow. The state can be used to store and share data between different methods in the Flow. After the Flow has run, you can access the state to retrieve any information that was added or updated during the execution.\n\n\nHere’s an example of how to update and access the state:\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\nclass\n ExampleState\n(\nBaseModel\n):\n\n\n counter: \nint\n =\n 0\n\n\n message: \nstr\n =\n \"\"\n\n\n\n\nclass\n StateExampleFlow\n(Flow[ExampleState]):\n\n\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n self\n.state.message \n=\n \"Hello from first_method\"\n\n\n self\n.state.counter \n+=\n 1\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state.message \n+=\n \" - updated by second_method\"\n\n\n self\n.state.counter \n+=\n 1\n\n\n return\n self\n.state.message\n\n\n\n\nflow \n=\n StateExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nfinal_output \n=\n flow.kickoff()\n\n\nprint\n(\nf\n\"Final Output: \n{\nfinal_output\n}\n\"\n)\n\n\nprint\n(\n\"Final State:\"\n)\n\n\nprint\n(flow.state)\n\n\n\n\n\n\nIn this example, the state is updated by both \nfirst_method\n and \nsecond_method\n.\nAfter the Flow has run, you can access the final state to see the updates made by these methods.\n\n\nBy ensuring that the final method’s output is returned and providing access to the state, CrewAI Flows make it easy to integrate the results of your AI workflows into larger applications or systems,\nwhile also maintaining and accessing the state throughout the Flow’s execution.\n\n\n​\nFlow State Management\n\n\nManaging state effectively is crucial for building reliable and maintainable AI workflows. CrewAI Flows provides robust mechanisms for both unstructured and structured state management,\nallowing developers to choose the approach that best fits their application’s needs.\n\n\n​\nUnstructured State Management\n\n\nIn unstructured state management, all state is stored in the \nstate\n attribute of the \nFlow\n class.\nThis approach offers flexibility, enabling developers to add or modify state attributes on the fly without defining a strict schema.\nEven with unstructured states, CrewAI Flows automatically generates and maintains a unique identifier (UUID) for each state instance.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\n\n\nclass\n UnstructuredExampleFlow\n(\nFlow\n):\n\n\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n # The state automatically includes an 'id' field\n\n\n print\n(\nf\n\"State ID: \n{\nself\n.state[\n'id'\n]\n}\n\"\n)\n\n\n self\n.state[\n'counter'\n] \n=\n 0\n\n\n self\n.state[\n'message'\n] \n=\n \"Hello from structured flow\"\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state[\n'counter'\n] \n+=\n 1\n\n\n self\n.state[\n'message'\n] \n+=\n \" - updated\"\n\n\n\n\n @listen\n(second_method)\n\n\n def\n third_method\n(\nself\n):\n\n\n self\n.state[\n'counter'\n] \n+=\n 1\n\n\n self\n.state[\n'message'\n] \n+=\n \" - updated again\"\n\n\n\n\n print\n(\nf\n\"State after third_method: \n{\nself\n.state\n}\n\"\n)\n\n\n\n\n\n\nflow \n=\n UnstructuredExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nflow.kickoff()\n\n\n\n\n\n\nNote:\n The \nid\n field is automatically generated and preserved throughout the flow’s execution. You don’t need to manage or set it manually, and it will be maintained even when updating the state with new data.\n\n\nKey Points:\n\n\n\n\nFlexibility:\n You can dynamically add attributes to \nself.state\n without predefined constraints.\n\n\nSimplicity:\n Ideal for straightforward workflows where state structure is minimal or varies significantly.\n\n\n\n\n​\nStructured State Management\n\n\nStructured state management leverages predefined schemas to ensure consistency and type safety across the workflow.\nBy using models like Pydantic’s \nBaseModel\n, developers can define the exact shape of the state, enabling better validation and auto-completion in development environments.\n\n\nEach state in CrewAI Flows automatically receives a unique identifier (UUID) to help track and manage state instances. This ID is automatically generated and managed by the Flow system.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\n\n\nclass\n ExampleState\n(\nBaseModel\n):\n\n\n # Note: 'id' field is automatically added to all states\n\n\n counter: \nint\n =\n 0\n\n\n message: \nstr\n =\n \"\"\n\n\n\n\n\n\nclass\n StructuredExampleFlow\n(Flow[ExampleState]):\n\n\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n # Access the auto-generated ID if needed\n\n\n print\n(\nf\n\"State ID: \n{\nself\n.state.id\n}\n\"\n)\n\n\n self\n.state.message \n=\n \"Hello from structured flow\"\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state.counter \n+=\n 1\n\n\n self\n.state.message \n+=\n \" - updated\"\n\n\n\n\n @listen\n(second_method)\n\n\n def\n third_method\n(\nself\n):\n\n\n self\n.state.counter \n+=\n 1\n\n\n self\n.state.message \n+=\n \" - updated again\"\n\n\n\n\n print\n(\nf\n\"State after third_method: \n{\nself\n.state\n}\n\"\n)\n\n\n\n\n\n\nflow \n=\n StructuredExampleFlow()\n\n\nflow.kickoff()\n\n\n\n\n\n\nKey Points:\n\n\n\n\nDefined Schema:\n \nExampleState\n clearly outlines the state structure, enhancing code readability and maintainability.\n\n\nType Safety:\n Leveraging Pydantic ensures that state attributes adhere to the specified types, reducing runtime errors.\n\n\nAuto-Completion:\n IDEs can provide better auto-completion and error checking based on the defined state model.\n\n\n\n\n​\nChoosing Between Unstructured and Structured State Management\n\n\n\n\n\n\nUse Unstructured State Management when:\n\n\n\n\nThe workflow’s state is simple or highly dynamic.\n\n\nFlexibility is prioritized over strict state definitions.\n\n\nRapid prototyping is required without the overhead of defining schemas.\n\n\n\n\n\n\n\n\nUse Structured State Management when:\n\n\n\n\nThe workflow requires a well-defined and consistent state structure.\n\n\nType safety and validation are important for your application’s reliability.\n\n\nYou want to leverage IDE features like auto-completion and type checking for better developer experience.\n\n\n\n\n\n\n\n\nBy providing both unstructured and structured state management options, CrewAI Flows empowers developers to build AI workflows that are both flexible and robust, catering to a wide range of application requirements.\n\n\n​\nFlow Persistence\n\n\nThe @persist decorator enables automatic state persistence in CrewAI Flows, allowing you to maintain flow state across restarts or different workflow executions. This decorator can be applied at either the class level or method level, providing flexibility in how you manage state persistence.\n\n\n​\nClass-Level Persistence\n\n\nWhen applied at the class level, the @persist decorator automatically persists all flow method states:\n\n\nCopy\nAsk AI\n@persist\n # Using SQLiteFlowPersistence by default\n\n\nclass\n MyFlow\n(Flow[MyState]):\n\n\n @start\n()\n\n\n def\n initialize_flow\n(\nself\n):\n\n\n # This method will automatically have its state persisted\n\n\n self\n.state.counter \n=\n 1\n\n\n print\n(\n\"Initialized flow. State ID:\"\n, \nself\n.state.id)\n\n\n\n\n @listen\n(initialize_flow)\n\n\n def\n next_step\n(\nself\n):\n\n\n # The state (including self.state.id) is automatically reloaded\n\n\n self\n.state.counter \n+=\n 1\n\n\n print\n(\n\"Flow state is persisted. Counter:\"\n, \nself\n.state.counter)\n\n\n\n\n​\nMethod-Level Persistence\n\n\nFor more granular control, you can apply @persist to specific methods:\n\n\nCopy\nAsk AI\nclass\n AnotherFlow\n(Flow[\ndict\n]):\n\n\n @persist\n # Persists only this method's state\n\n\n @start\n()\n\n\n def\n begin\n(\nself\n):\n\n\n if\n \"runs\"\n not\n in\n self\n.state:\n\n\n self\n.state[\n\"runs\"\n] \n=\n 0\n\n\n self\n.state[\n\"runs\"\n] \n+=\n 1\n\n\n print\n(\n\"Method-level persisted runs:\"\n, \nself\n.state[\n\"runs\"\n])\n\n\n\n\n​\nHow It Works\n\n\n\n\n\n\nUnique State Identification\n\n\n\n\nEach flow state automatically receives a unique UUID\n\n\nThe ID is preserved across state updates and method calls\n\n\nSupports both structured (Pydantic BaseModel) and unstructured (dictionary) states\n\n\n\n\n\n\n\n\nDefault SQLite Backend\n\n\n\n\nSQLiteFlowPersistence is the default storage backend\n\n\nStates are automatically saved to a local SQLite database\n\n\nRobust error handling ensures clear messages if database operations fail\n\n\n\n\n\n\n\n\nError Handling\n\n\n\n\nComprehensive error messages for database operations\n\n\nAutomatic state validation during save and load\n\n\nClear feedback when persistence operations encounter issues\n\n\n\n\n\n\n\n\n​\nImportant Considerations\n\n\n\n\nState Types\n: Both structured (Pydantic BaseModel) and unstructured (dictionary) states are supported\n\n\nAutomatic ID\n: The \nid\n field is automatically added if not present\n\n\nState Recovery\n: Failed or restarted flows can automatically reload their previous state\n\n\nCustom Implementation\n: You can provide your own FlowPersistence implementation for specialized storage needs\n\n\n\n\n​\nTechnical Advantages\n\n\n\n\n\n\nPrecise Control Through Low-Level Access\n\n\n\n\nDirect access to persistence operations for advanced use cases\n\n\nFine-grained control via method-level persistence decorators\n\n\nBuilt-in state inspection and debugging capabilities\n\n\nFull visibility into state changes and persistence operations\n\n\n\n\n\n\n\n\nEnhanced Reliability\n\n\n\n\nAutomatic state recovery after system failures or restarts\n\n\nTransaction-based state updates for data integrity\n\n\nComprehensive error handling with clear error messages\n\n\nRobust validation during state save and load operations\n\n\n\n\n\n\n\n\nExtensible Architecture\n\n\n\n\nCustomizable persistence backend through FlowPersistence interface\n\n\nSupport for specialized storage solutions beyond SQLite\n\n\nCompatible with both structured (Pydantic) and unstructured (dict) states\n\n\nSeamless integration with existing CrewAI flow patterns\n\n\n\n\n\n\n\n\nThe persistence system’s architecture emphasizes technical precision and customization options, allowing developers to maintain full control over state management while benefiting from built-in reliability features.\n\n\n​\nFlow Control\n\n\n​\nConditional Logic: \nor\n\n\nThe \nor_\n function in Flows allows you to listen to multiple methods and trigger the listener method when any of the specified methods emit an output.\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, or_, start\n\n\n\n\nclass\n OrExampleFlow\n(\nFlow\n):\n\n\n\n\n @start\n()\n\n\n def\n start_method\n(\nself\n):\n\n\n return\n \"Hello from the start method\"\n\n\n\n\n @listen\n(start_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n return\n \"Hello from the second method\"\n\n\n\n\n @listen\n(or_(start_method, second_method))\n\n\n def\n logger\n(\nself\n, \nresult\n):\n\n\n print\n(\nf\n\"Logger: \n{\nresult\n}\n\"\n)\n\n\n\n\n\n\n\n\nflow \n=\n OrExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nflow.kickoff()\n\n\n\n\n\n\nWhen you run this Flow, the \nlogger\n method will be triggered by the output of either the \nstart_method\n or the \nsecond_method\n.\nThe \nor_\n function is used to listen to multiple methods and trigger the listener method when any of the specified methods emit an output.\n\n\n​\nConditional Logic: \nand\n\n\nThe \nand_\n function in Flows allows you to listen to multiple methods and trigger the listener method only when all the specified methods emit an output.\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, and_, listen, start\n\n\n\n\nclass\n AndExampleFlow\n(\nFlow\n):\n\n\n\n\n @start\n()\n\n\n def\n start_method\n(\nself\n):\n\n\n self\n.state[\n\"greeting\"\n] \n=\n \"Hello from the start method\"\n\n\n\n\n @listen\n(start_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state[\n\"joke\"\n] \n=\n \"What do computers eat? Microchips.\"\n\n\n\n\n @listen\n(and_(start_method, second_method))\n\n\n def\n logger\n(\nself\n):\n\n\n print\n(\n\"---- Logger ----\"\n)\n\n\n print\n(\nself\n.state)\n\n\n\n\nflow \n=\n AndExampleFlow()\n\n\nflow.plot()\n\n\nflow.kickoff()\n\n\n\n\n\n\nWhen you run this Flow, the \nlogger\n method will be triggered only when both the \nstart_method\n and the \nsecond_method\n emit an output.\nThe \nand_\n function is used to listen to multiple methods and trigger the listener method only when all the specified methods emit an output.\n\n\n​\nRouter\n\n\nThe \n@router()\n decorator in Flows allows you to define conditional routing logic based on the output of a method.\nYou can specify different routes based on the output of the method, allowing you to control the flow of execution dynamically.\n\n\nCode\nOutput\nCopy\nAsk AI\nimport\n random\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, router, start\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\nclass\n ExampleState\n(\nBaseModel\n):\n\n\n success_flag: \nbool\n =\n False\n\n\n\n\nclass\n RouterFlow\n(Flow[ExampleState]):\n\n\n\n\n @start\n()\n\n\n def\n start_method\n(\nself\n):\n\n\n print\n(\n\"Starting the structured flow\"\n)\n\n\n random_boolean \n=\n random.choice([\nTrue\n, \nFalse\n])\n\n\n self\n.state.success_flag \n=\n random_boolean\n\n\n\n\n @router\n(start_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n if\n self\n.state.success_flag:\n\n\n return\n \"success\"\n\n\n else\n:\n\n\n return\n \"failed\"\n\n\n\n\n @listen\n(\n\"success\"\n)\n\n\n def\n third_method\n(\nself\n):\n\n\n print\n(\n\"Third method running\"\n)\n\n\n\n\n @listen\n(\n\"failed\"\n)\n\n\n def\n fourth_method\n(\nself\n):\n\n\n print\n(\n\"Fourth method running\"\n)\n\n\n\n\n\n\nflow \n=\n RouterFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nflow.kickoff()\n\n\n\n\n\n\nIn the above example, the \nstart_method\n generates a random boolean value and sets it in the state.\nThe \nsecond_method\n uses the \n@router()\n decorator to define conditional routing logic based on the value of the boolean.\nIf the boolean is \nTrue\n, the method returns \n\"success\"\n, and if it is \nFalse\n, the method returns \n\"failed\"\n.\nThe \nthird_method\n and \nfourth_method\n listen to the output of the \nsecond_method\n and execute based on the returned value.\n\n\nWhen you run this Flow, the output will change based on the random boolean value generated by the \nstart_method\n.\n\n\n​\nAdding Agents to Flows\n\n\nAgents can be seamlessly integrated into your flows, providing a lightweight alternative to full Crews when you need simpler, focused task execution. Here’s an example of how to use an Agent within a flow to perform market research:\n\n\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n typing \nimport\n Any, Dict, List\n\n\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nfrom\n crewai.agent \nimport\n Agent\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\n\n\n\n\n# Define a structured output format\n\n\nclass\n MarketAnalysis\n(\nBaseModel\n):\n\n\n key_trends: List[\nstr\n] \n=\n Field(\ndescription\n=\n\"List of identified market trends\"\n)\n\n\n market_size: \nstr\n =\n Field(\ndescription\n=\n\"Estimated market size\"\n)\n\n\n competitors: List[\nstr\n] \n=\n Field(\ndescription\n=\n\"Major competitors in the space\"\n)\n\n\n\n\n\n\n# Define flow state\n\n\nclass\n MarketResearchState\n(\nBaseModel\n):\n\n\n product: \nstr\n =\n \"\"\n\n\n analysis: MarketAnalysis \n|\n None\n =\n None\n\n\n\n\n\n\n# Create a flow class\n\n\nclass\n MarketResearchFlow\n(Flow[MarketResearchState]):\n\n\n @start\n()\n\n\n def\n initialize_research\n(\nself\n) -> Dict[\nstr\n, Any]:\n\n\n print\n(\nf\n\"Starting market research for \n{\nself\n.state.product\n}\n\"\n)\n\n\n return\n {\n\"product\"\n: \nself\n.state.product}\n\n\n\n\n @listen\n(initialize_research)\n\n\n async\n def\n analyze_market\n(\nself\n) -> Dict[\nstr\n, Any]:\n\n\n # Create an Agent for market research\n\n\n analyst \n=\n Agent(\n\n\n role\n=\n\"Market Research Analyst\"\n,\n\n\n goal\n=\nf\n\"Analyze the market for \n{\nself\n.state.product\n}\n\"\n,\n\n\n backstory\n=\n\"You are an experienced market analyst with expertise in \"\n\n\n \"identifying market trends and opportunities.\"\n,\n\n\n tools\n=\n[SerperDevTool()],\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n # Define the research query\n\n\n query \n=\n f\n\"\"\"\n\n\n Research the market for \n{\nself\n.state.product\n}\n. Include:\n\n\n 1. Key market trends\n\n\n 2. Market size\n\n\n 3. Major competitors\n\n\n\n\n Format your response according to the specified structure.\n\n\n \"\"\"\n\n\n\n\n # Execute the analysis with structured output format\n\n\n result \n=\n await\n analyst.kickoff_async(query, \nresponse_format\n=\nMarketAnalysis)\n\n\n if\n result.pydantic:\n\n\n print\n(\n\"result\"\n, result.pydantic)\n\n\n else\n:\n\n\n print\n(\n\"result\"\n, result)\n\n\n\n\n # Return the analysis to update the state\n\n\n return\n {\n\"analysis\"\n: result.pydantic}\n\n\n\n\n @listen\n(analyze_market)\n\n\n def\n present_results\n(\nself\n, \nanalysis\n) -> \nNone\n:\n\n\n print\n(\n\"\n\\n\nMarket Analysis Results\"\n)\n\n\n print\n(\n\"=====================\"\n)\n\n\n\n\n if\n isinstance\n(analysis, \ndict\n):\n\n\n # If we got a dict with 'analysis' key, extract the actual analysis object\n\n\n market_analysis \n=\n analysis.get(\n\"analysis\"\n)\n\n\n else\n:\n\n\n market_analysis \n=\n analysis\n\n\n\n\n if\n market_analysis \nand\n isinstance\n(market_analysis, MarketAnalysis):\n\n\n print\n(\n\"\n\\n\nKey Market Trends:\"\n)\n\n\n for\n trend \nin\n market_analysis.key_trends:\n\n\n print\n(\nf\n\"- \n{\ntrend\n}\n\"\n)\n\n\n\n\n print\n(\nf\n\"\n\\n\nMarket Size: \n{\nmarket_analysis.market_size\n}\n\"\n)\n\n\n\n\n print\n(\n\"\n\\n\nMajor Competitors:\"\n)\n\n\n for\n competitor \nin\n market_analysis.competitors:\n\n\n print\n(\nf\n\"- \n{\ncompetitor\n}\n\"\n)\n\n\n else\n:\n\n\n print\n(\n\"No structured analysis data available.\"\n)\n\n\n print\n(\n\"Raw analysis:\"\n, analysis)\n\n\n\n\n\n\n# Usage example\n\n\nasync\n def\n run_flow\n():\n\n\n flow \n=\n MarketResearchFlow()\n\n\n flow.plot(\n\"MarketResearchFlowPlot\"\n)\n\n\n result \n=\n await\n flow.kickoff_async(\ninputs\n=\n{\n\"product\"\n: \n\"AI-powered chatbots\"\n})\n\n\n return\n result\n\n\n\n\n\n\n# Run the flow\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n asyncio.run(run_flow())\n\n\n\n\n\n\nThis example demonstrates several key features of using Agents in flows:\n\n\n\n\n\n\nStructured Output\n: Using Pydantic models to define the expected output format (\nMarketAnalysis\n) ensures type safety and structured data throughout the flow.\n\n\n\n\n\n\nState Management\n: The flow state (\nMarketResearchState\n) maintains context between steps and stores both inputs and outputs.\n\n\n\n\n\n\nTool Integration\n: Agents can use tools (like \nWebsiteSearchTool\n) to enhance their capabilities.\n\n\n\n\n\n\n​\nAdding Crews to Flows\n\n\nCreating a flow with multiple crews in CrewAI is straightforward.\n\n\nYou can generate a new CrewAI project that includes all the scaffolding needed to create a flow with multiple crews by running the following command:\n\n\nCopy\nAsk AI\ncrewai\n create\n flow\n name_of_flow\n\n\n\n\nThis command will generate a new CrewAI project with the necessary folder structure. The generated project includes a prebuilt crew called \npoem_crew\n that is already working. You can use this crew as a template by copying, pasting, and editing it to create other crews.\n\n\n​\nFolder Structure\n\n\nAfter running the \ncrewai create flow name_of_flow\n command, you will see a folder structure similar to the following:\n\n\nDirectory/File\nDescription\nname_of_flow/\nRoot directory for the flow.\n├── \ncrews/\nContains directories for specific crews.\n│ └── \npoem_crew/\nDirectory for the “poem_crew” with its configurations and scripts.\n│ ├── \nconfig/\nConfiguration files directory for the “poem_crew”.\n│ │ ├── \nagents.yaml\nYAML file defining the agents for “poem_crew”.\n│ │ └── \ntasks.yaml\nYAML file defining the tasks for “poem_crew”.\n│ ├── \npoem_crew.py\nScript for “poem_crew” functionality.\n├── \ntools/\nDirectory for additional tools used in the flow.\n│ └── \ncustom_tool.py\nCustom tool implementation.\n├── \nmain.py\nMain script for running the flow.\n├── \nREADME.md\nProject description and instructions.\n├── \npyproject.toml\nConfiguration file for project dependencies and settings.\n└── \n.gitignore\nSpecifies files and directories to ignore in version control.\n\n\n​\nBuilding Your Crews\n\n\nIn the \ncrews\n folder, you can define multiple crews. Each crew will have its own folder containing configuration files and the crew definition file. For example, the \npoem_crew\n folder contains:\n\n\n\n\nconfig/agents.yaml\n: Defines the agents for the crew.\n\n\nconfig/tasks.yaml\n: Defines the tasks for the crew.\n\n\npoem_crew.py\n: Contains the crew definition, including agents, tasks, and the crew itself.\n\n\n\n\nYou can copy, paste, and edit the \npoem_crew\n to create other crews.\n\n\n​\nConnecting Crews in \nmain.py\n\n\nThe \nmain.py\n file is where you create your flow and connect the crews together. You can define your flow by using the \nFlow\n class and the decorators \n@start\n and \n@listen\n to specify the flow of execution.\n\n\nHere’s an example of how you can connect the \npoem_crew\n in the \nmain.py\n file:\n\n\nCode\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\nfrom\n random \nimport\n randint\n\n\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n .crews.poem_crew.poem_crew \nimport\n PoemCrew\n\n\n\n\nclass\n PoemState\n(\nBaseModel\n):\n\n\n sentence_count: \nint\n =\n 1\n\n\n poem: \nstr\n =\n \"\"\n\n\n\n\nclass\n PoemFlow\n(Flow[PoemState]):\n\n\n\n\n @start\n()\n\n\n def\n generate_sentence_count\n(\nself\n):\n\n\n print\n(\n\"Generating sentence count\"\n)\n\n\n self\n.state.sentence_count \n=\n randint(\n1\n, \n5\n)\n\n\n\n\n @listen\n(generate_sentence_count)\n\n\n def\n generate_poem\n(\nself\n):\n\n\n print\n(\n\"Generating poem\"\n)\n\n\n result \n=\n PoemCrew().crew().kickoff(\ninputs\n=\n{\n\"sentence_count\"\n: \nself\n.state.sentence_count})\n\n\n\n\n print\n(\n\"Poem generated\"\n, result.raw)\n\n\n self\n.state.poem \n=\n result.raw\n\n\n\n\n @listen\n(generate_poem)\n\n\n def\n save_poem\n(\nself\n):\n\n\n print\n(\n\"Saving poem\"\n)\n\n\n with\n open\n(\n\"poem.txt\"\n, \n\"w\"\n) \nas\n f:\n\n\n f.write(\nself\n.state.poem)\n\n\n\n\ndef\n kickoff\n():\n\n\n poem_flow \n=\n PoemFlow()\n\n\n poem_flow.kickoff()\n\n\n\n\n\n\ndef\n plot\n():\n\n\n poem_flow \n=\n PoemFlow()\n\n\n poem_flow.plot(\n\"PoemFlowPlot\"\n)\n\n\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n kickoff()\n\n\n plot()\n\n\n\n\nIn this example, the \nPoemFlow\n class defines a flow that generates a sentence count, uses the \nPoemCrew\n to generate a poem, and then saves the poem to a file. The flow is kicked off by calling the \nkickoff()\n method. The PoemFlowPlot will be generated by \nplot()\n method.\n\n\n\n\n​\nRunning the Flow\n\n\n(Optional) Before running the flow, you can install the dependencies by running:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\nOnce all of the dependencies are installed, you need to activate the virtual environment by running:\n\n\nCopy\nAsk AI\nsource\n .venv/bin/activate\n\n\n\n\nAfter activating the virtual environment, you can run the flow by executing one of the following commands:\n\n\nCopy\nAsk AI\ncrewai\n flow\n kickoff\n\n\n\n\nor\n\n\nCopy\nAsk AI\nuv\n run\n kickoff\n\n\n\n\nThe flow will execute, and you should see the output in the console.\n\n\n​\nPlot Flows\n\n\nVisualizing your AI workflows can provide valuable insights into the structure and execution paths of your flows. CrewAI offers a powerful visualization tool that allows you to generate interactive plots of your flows, making it easier to understand and optimize your AI workflows.\n\n\n​\nWhat are Plots?\n\n\nPlots in CrewAI are graphical representations of your AI workflows. They display the various tasks, their connections, and the flow of data between them. This visualization helps in understanding the sequence of operations, identifying bottlenecks, and ensuring that the workflow logic aligns with your expectations.\n\n\n​\nHow to Generate a Plot\n\n\nCrewAI provides two convenient methods to generate plots of your flows:\n\n\n​\nOption 1: Using the \nplot()\n Method\n\n\nIf you are working directly with a flow instance, you can generate a plot by calling the \nplot()\n method on your flow object. This method will create an HTML file containing the interactive plot of your flow.\n\n\nCode\nCopy\nAsk AI\n# Assuming you have a flow instance\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\n\n\nThis will generate a file named \nmy_flow_plot.html\n in your current directory. You can open this file in a web browser to view the interactive plot.\n\n\n​\nOption 2: Using the Command Line\n\n\nIf you are working within a structured CrewAI project, you can generate a plot using the command line. This is particularly useful for larger projects where you want to visualize the entire flow setup.\n\n\nCopy\nAsk AI\ncrewai\n flow\n plot\n\n\n\n\nThis command will generate an HTML file with the plot of your flow, similar to the \nplot()\n method. The file will be saved in your project directory, and you can open it in a web browser to explore the flow.\n\n\n​\nUnderstanding the Plot\n\n\nThe generated plot will display nodes representing the tasks in your flow, with directed edges indicating the flow of execution. The plot is interactive, allowing you to zoom in and out, and hover over nodes to see additional details.\n\n\nBy visualizing your flows, you can gain a clearer understanding of the workflow’s structure, making it easier to debug, optimize, and communicate your AI processes to others.\n\n\n​\nConclusion\n\n\nPlotting your flows is a powerful feature of CrewAI that enhances your ability to design and manage complex AI workflows. Whether you choose to use the \nplot()\n method or the command line, generating plots will provide you with a visual representation of your workflows, aiding in both development and presentation.\n\n\n​\nNext Steps\n\n\nIf you’re interested in exploring additional examples of flows, we have a variety of recommendations in our examples repository. Here are four specific flow examples, each showcasing unique use cases to help you match your current problem type to a specific example:\n\n\n\n\n\n\nEmail Auto Responder Flow\n: This example demonstrates an infinite loop where a background job continually runs to automate email responses. It’s a great use case for tasks that need to be performed repeatedly without manual intervention. \nView Example\n\n\n\n\n\n\nLead Score Flow\n: This flow showcases adding human-in-the-loop feedback and handling different conditional branches using the router. It’s an excellent example of how to incorporate dynamic decision-making and human oversight into your workflows. \nView Example\n\n\n\n\n\n\nWrite a Book Flow\n: This example excels at chaining multiple crews together, where the output of one crew is used by another. Specifically, one crew outlines an entire book, and another crew generates chapters based on the outline. Eventually, everything is connected to produce a complete book. This flow is perfect for complex, multi-step processes that require coordination between different tasks. \nView Example\n\n\n\n\n\n\nMeeting Assistant Flow\n: This flow demonstrates how to broadcast one event to trigger multiple follow-up actions. For instance, after a meeting is completed, the flow can update a Trello board, send a Slack message, and save the results. It’s a great example of handling multiple outcomes from a single event, making it ideal for comprehensive task management and notification systems. \nView Example\n\n\n\n\n\n\nBy exploring these examples, you can gain insights into how to leverage CrewAI Flows for various use cases, from automating repetitive tasks to managing complex, multi-step processes with dynamic decision-making and human feedback.\n\n\nAlso, check out our YouTube video on how to use flows in CrewAI below!\n\n\n\n\n​\nRunning Flows\n\n\nThere are two ways to run a flow:\n\n\n​\nUsing the Flow API\n\n\nYou can run a flow programmatically by creating an instance of your flow class and calling the \nkickoff()\n method:\n\n\nCopy\nAsk AI\nflow \n=\n ExampleFlow()\n\n\nresult \n=\n flow.kickoff()\n\n\n\n\n​\nUsing the CLI\n\n\nStarting from version 0.103.0, you can run flows using the \ncrewai run\n command:\n\n\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\nThis command automatically detects if your project is a flow (based on the \ntype = \"flow\"\n setting in your pyproject.toml) and runs it accordingly. This is the recommended way to run flows from the command line.\n\n\nFor backward compatibility, you can also use:\n\n\nCopy\nAsk AI\ncrewai\n flow\n kickoff\n\n\n\n\nHowever, the \ncrewai run\n command is now the preferred method as it works for both crews and flows.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCrews\nKnowledge\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nGetting Started\n@start()\n@listen()\nUsage\nFlow Output\nRetrieving the Final Output\nAccessing and Updating State\nFlow State Management\nUnstructured State Management\nStructured State Management\nChoosing Between Unstructured and Structured State Management\nFlow Persistence\nClass-Level Persistence\nMethod-Level Persistence\nHow It Works\nImportant Considerations\nTechnical Advantages\nFlow Control\nConditional Logic: or\nConditional Logic: and\nRouter\nAdding Agents to Flows\nAdding Crews to Flows\nFolder Structure\nBuilding Your Crews\nConnecting Crews in main.py\nRunning the Flow\nPlot Flows\nWhat are Plots?\nHow to Generate a Plot\nOption 1: Using the plot() Method\nOption 2: Using the Command Line\nUnderstanding the Plot\nConclusion\nNext Steps\nRunning Flows\nUsing the Flow API\nUsing the CLI\nCore Concepts\nFlows\nCopy page\nLearn how to create and manage AI workflows using CrewAI Flows.\n​\nOverview\n\n\nCrewAI Flows is a powerful feature designed to streamline the creation and management of AI workflows. Flows allow developers to combine and coordinate coding tasks and Crews efficiently, providing a robust framework for building sophisticated AI automations.\n\n\nFlows allow you to create structured, event-driven workflows. They provide a seamless way to connect multiple tasks, manage state, and control the flow of execution in your AI applications. With Flows, you can easily design and implement multi-step processes that leverage the full potential of CrewAI’s capabilities.\n\n\n\n\n\n\nSimplified Workflow Creation\n: Easily chain together multiple Crews and tasks to create complex AI workflows.\n\n\n\n\n\n\nState Management\n: Flows make it super easy to manage and share state between different tasks in your workflow.\n\n\n\n\n\n\nEvent-Driven Architecture\n: Built on an event-driven model, allowing for dynamic and responsive workflows.\n\n\n\n\n\n\nFlexible Control Flow\n: Implement conditional logic, loops, and branching within your workflows.\n\n\n\n\n\n\n​\nGetting Started\n\n\nLet’s create a simple Flow where you will use OpenAI to generate a random city in one task and then use that city to generate a fun fact in another task.\n\n\nCode\nCopy\nAsk AI\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n dotenv \nimport\n load_dotenv\n\n\nfrom\n litellm \nimport\n completion\n\n\n\n\n\n\nclass\n ExampleFlow\n(\nFlow\n):\n\n\n model \n=\n \"gpt-4o-mini\"\n\n\n\n\n @start\n()\n\n\n def\n generate_city\n(\nself\n):\n\n\n print\n(\n\"Starting flow\"\n)\n\n\n # Each flow state automatically gets a unique ID\n\n\n print\n(\nf\n\"Flow State ID: \n{\nself\n.state[\n'id'\n]\n}\n\"\n)\n\n\n\n\n response \n=\n completion(\n\n\n model\n=\nself\n.model,\n\n\n messages\n=\n[\n\n\n {\n\n\n \"role\"\n: \n\"user\"\n,\n\n\n \"content\"\n: \n\"Return the name of a random city in the world.\"\n,\n\n\n },\n\n\n ],\n\n\n )\n\n\n\n\n random_city \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n # Store the city in our state\n\n\n self\n.state[\n\"city\"\n] \n=\n random_city\n\n\n print\n(\nf\n\"Random City: \n{\nrandom_city\n}\n\"\n)\n\n\n\n\n return\n random_city\n\n\n\n\n @listen\n(generate_city)\n\n\n def\n generate_fun_fact\n(\nself\n, \nrandom_city\n):\n\n\n response \n=\n completion(\n\n\n model\n=\nself\n.model,\n\n\n messages\n=\n[\n\n\n {\n\n\n \"role\"\n: \n\"user\"\n,\n\n\n \"content\"\n: \nf\n\"Tell me a fun fact about \n{\nrandom_city\n}\n\"\n,\n\n\n },\n\n\n ],\n\n\n )\n\n\n\n\n fun_fact \n=\n response[\n\"choices\"\n][\n0\n][\n\"message\"\n][\n\"content\"\n]\n\n\n # Store the fun fact in our state\n\n\n self\n.state[\n\"fun_fact\"\n] \n=\n fun_fact\n\n\n return\n fun_fact\n\n\n\n\n\n\n\n\nflow \n=\n ExampleFlow()\n\n\nflow.plot()\n\n\nresult \n=\n flow.kickoff()\n\n\n\n\nprint\n(\nf\n\"Generated fun fact: \n{\nresult\n}\n\"\n)\n\n\n\n\n\nIn the above example, we have created a simple Flow that generates a random city using OpenAI and then generates a fun fact about that city. The Flow consists of two tasks: \ngenerate_city\n and \ngenerate_fun_fact\n. The \ngenerate_city\n task is the starting point of the Flow, and the \ngenerate_fun_fact\n task listens for the output of the \ngenerate_city\n task.\n\n\nEach Flow instance automatically receives a unique identifier (UUID) in its state, which helps track and manage flow executions. The state can also store additional data (like the generated city and fun fact) that persists throughout the flow’s execution.\n\n\nWhen you run the Flow, it will:\n\n\n\n\nGenerate a unique ID for the flow state\n\n\nGenerate a random city and store it in the state\n\n\nGenerate a fun fact about that city and store it in the state\n\n\nPrint the results to the console\n\n\n\n\nThe state’s unique ID and stored data can be useful for tracking flow executions and maintaining context between tasks.\n\n\nNote:\n Ensure you have set up your \n.env\n file to store your \nOPENAI_API_KEY\n. This key is necessary for authenticating requests to the OpenAI API.\n\n\n​\n@start()\n\n\nThe \n@start()\n decorator is used to mark a method as the starting point of a Flow. When a Flow is started, all the methods decorated with \n@start()\n are executed in parallel. You can have multiple start methods in a Flow, and they will all be executed when the Flow is started.\n\n\n​\n@listen()\n\n\nThe \n@listen()\n decorator is used to mark a method as a listener for the output of another task in the Flow. The method decorated with \n@listen()\n will be executed when the specified task emits an output. The method can access the output of the task it is listening to as an argument.\n\n\n​\nUsage\n\n\nThe \n@listen()\n decorator can be used in several ways:\n\n\n\n\n\n\nListening to a Method by Name\n: You can pass the name of the method you want to listen to as a string. When that method completes, the listener method will be triggered.\n\n\nCode\nCopy\nAsk AI\n@listen\n(\n\"generate_city\"\n)\n\n\ndef\n generate_fun_fact\n(\nself\n, \nrandom_city\n):\n\n\n # Implementation\n\n\n\n\n\n\n\n\nListening to a Method Directly\n: You can pass the method itself. When that method completes, the listener method will be triggered.\n\n\nCode\nCopy\nAsk AI\n@listen\n(generate_city)\n\n\ndef\n generate_fun_fact\n(\nself\n, \nrandom_city\n):\n\n\n # Implementation\n\n\n\n\n\n\n\n\n​\nFlow Output\n\n\nAccessing and handling the output of a Flow is essential for integrating your AI workflows into larger applications or systems. CrewAI Flows provide straightforward mechanisms to retrieve the final output, access intermediate results, and manage the overall state of your Flow.\n\n\n​\nRetrieving the Final Output\n\n\nWhen you run a Flow, the final output is determined by the last method that completes. The \nkickoff()\n method returns the output of this final method.\n\n\nHere’s how you can access the final output:\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\n\n\nclass\n OutputExampleFlow\n(\nFlow\n):\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n return\n \"Output from first_method\"\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n, \nfirst_output\n):\n\n\n return\n f\n\"Second method received: \n{\nfirst_output\n}\n\"\n\n\n\n\n\n\nflow \n=\n OutputExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nfinal_output \n=\n flow.kickoff()\n\n\n\n\nprint\n(\n\"---- Final Output ----\"\n)\n\n\nprint\n(final_output)\n\n\n\n\n\n\nIn this example, the \nsecond_method\n is the last method to complete, so its output will be the final output of the Flow.\nThe \nkickoff()\n method will return the final output, which is then printed to the console. The \nplot()\n method will generate the HTML file, which will help you understand the flow.\n\n\n​\nAccessing and Updating State\n\n\nIn addition to retrieving the final output, you can also access and update the state within your Flow. The state can be used to store and share data between different methods in the Flow. After the Flow has run, you can access the state to retrieve any information that was added or updated during the execution.\n\n\nHere’s an example of how to update and access the state:\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\nclass\n ExampleState\n(\nBaseModel\n):\n\n\n counter: \nint\n =\n 0\n\n\n message: \nstr\n =\n \"\"\n\n\n\n\nclass\n StateExampleFlow\n(Flow[ExampleState]):\n\n\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n self\n.state.message \n=\n \"Hello from first_method\"\n\n\n self\n.state.counter \n+=\n 1\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state.message \n+=\n \" - updated by second_method\"\n\n\n self\n.state.counter \n+=\n 1\n\n\n return\n self\n.state.message\n\n\n\n\nflow \n=\n StateExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nfinal_output \n=\n flow.kickoff()\n\n\nprint\n(\nf\n\"Final Output: \n{\nfinal_output\n}\n\"\n)\n\n\nprint\n(\n\"Final State:\"\n)\n\n\nprint\n(flow.state)\n\n\n\n\n\n\nIn this example, the state is updated by both \nfirst_method\n and \nsecond_method\n.\nAfter the Flow has run, you can access the final state to see the updates made by these methods.\n\n\nBy ensuring that the final method’s output is returned and providing access to the state, CrewAI Flows make it easy to integrate the results of your AI workflows into larger applications or systems,\nwhile also maintaining and accessing the state throughout the Flow’s execution.\n\n\n​\nFlow State Management\n\n\nManaging state effectively is crucial for building reliable and maintainable AI workflows. CrewAI Flows provides robust mechanisms for both unstructured and structured state management,\nallowing developers to choose the approach that best fits their application’s needs.\n\n\n​\nUnstructured State Management\n\n\nIn unstructured state management, all state is stored in the \nstate\n attribute of the \nFlow\n class.\nThis approach offers flexibility, enabling developers to add or modify state attributes on the fly without defining a strict schema.\nEven with unstructured states, CrewAI Flows automatically generates and maintains a unique identifier (UUID) for each state instance.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\n\n\nclass\n UnstructuredExampleFlow\n(\nFlow\n):\n\n\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n # The state automatically includes an 'id' field\n\n\n print\n(\nf\n\"State ID: \n{\nself\n.state[\n'id'\n]\n}\n\"\n)\n\n\n self\n.state[\n'counter'\n] \n=\n 0\n\n\n self\n.state[\n'message'\n] \n=\n \"Hello from structured flow\"\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state[\n'counter'\n] \n+=\n 1\n\n\n self\n.state[\n'message'\n] \n+=\n \" - updated\"\n\n\n\n\n @listen\n(second_method)\n\n\n def\n third_method\n(\nself\n):\n\n\n self\n.state[\n'counter'\n] \n+=\n 1\n\n\n self\n.state[\n'message'\n] \n+=\n \" - updated again\"\n\n\n\n\n print\n(\nf\n\"State after third_method: \n{\nself\n.state\n}\n\"\n)\n\n\n\n\n\n\nflow \n=\n UnstructuredExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nflow.kickoff()\n\n\n\n\n\n\nNote:\n The \nid\n field is automatically generated and preserved throughout the flow’s execution. You don’t need to manage or set it manually, and it will be maintained even when updating the state with new data.\n\n\nKey Points:\n\n\n\n\nFlexibility:\n You can dynamically add attributes to \nself.state\n without predefined constraints.\n\n\nSimplicity:\n Ideal for straightforward workflows where state structure is minimal or varies significantly.\n\n\n\n\n​\nStructured State Management\n\n\nStructured state management leverages predefined schemas to ensure consistency and type safety across the workflow.\nBy using models like Pydantic’s \nBaseModel\n, developers can define the exact shape of the state, enabling better validation and auto-completion in development environments.\n\n\nEach state in CrewAI Flows automatically receives a unique identifier (UUID) to help track and manage state instances. This ID is automatically generated and managed by the Flow system.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\n\n\nclass\n ExampleState\n(\nBaseModel\n):\n\n\n # Note: 'id' field is automatically added to all states\n\n\n counter: \nint\n =\n 0\n\n\n message: \nstr\n =\n \"\"\n\n\n\n\n\n\nclass\n StructuredExampleFlow\n(Flow[ExampleState]):\n\n\n\n\n @start\n()\n\n\n def\n first_method\n(\nself\n):\n\n\n # Access the auto-generated ID if needed\n\n\n print\n(\nf\n\"State ID: \n{\nself\n.state.id\n}\n\"\n)\n\n\n self\n.state.message \n=\n \"Hello from structured flow\"\n\n\n\n\n @listen\n(first_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state.counter \n+=\n 1\n\n\n self\n.state.message \n+=\n \" - updated\"\n\n\n\n\n @listen\n(second_method)\n\n\n def\n third_method\n(\nself\n):\n\n\n self\n.state.counter \n+=\n 1\n\n\n self\n.state.message \n+=\n \" - updated again\"\n\n\n\n\n print\n(\nf\n\"State after third_method: \n{\nself\n.state\n}\n\"\n)\n\n\n\n\n\n\nflow \n=\n StructuredExampleFlow()\n\n\nflow.kickoff()\n\n\n\n\n\n\nKey Points:\n\n\n\n\nDefined Schema:\n \nExampleState\n clearly outlines the state structure, enhancing code readability and maintainability.\n\n\nType Safety:\n Leveraging Pydantic ensures that state attributes adhere to the specified types, reducing runtime errors.\n\n\nAuto-Completion:\n IDEs can provide better auto-completion and error checking based on the defined state model.\n\n\n\n\n​\nChoosing Between Unstructured and Structured State Management\n\n\n\n\n\n\nUse Unstructured State Management when:\n\n\n\n\nThe workflow’s state is simple or highly dynamic.\n\n\nFlexibility is prioritized over strict state definitions.\n\n\nRapid prototyping is required without the overhead of defining schemas.\n\n\n\n\n\n\n\n\nUse Structured State Management when:\n\n\n\n\nThe workflow requires a well-defined and consistent state structure.\n\n\nType safety and validation are important for your application’s reliability.\n\n\nYou want to leverage IDE features like auto-completion and type checking for better developer experience.\n\n\n\n\n\n\n\n\nBy providing both unstructured and structured state management options, CrewAI Flows empowers developers to build AI workflows that are both flexible and robust, catering to a wide range of application requirements.\n\n\n​\nFlow Persistence\n\n\nThe @persist decorator enables automatic state persistence in CrewAI Flows, allowing you to maintain flow state across restarts or different workflow executions. This decorator can be applied at either the class level or method level, providing flexibility in how you manage state persistence.\n\n\n​\nClass-Level Persistence\n\n\nWhen applied at the class level, the @persist decorator automatically persists all flow method states:\n\n\nCopy\nAsk AI\n@persist\n # Using SQLiteFlowPersistence by default\n\n\nclass\n MyFlow\n(Flow[MyState]):\n\n\n @start\n()\n\n\n def\n initialize_flow\n(\nself\n):\n\n\n # This method will automatically have its state persisted\n\n\n self\n.state.counter \n=\n 1\n\n\n print\n(\n\"Initialized flow. State ID:\"\n, \nself\n.state.id)\n\n\n\n\n @listen\n(initialize_flow)\n\n\n def\n next_step\n(\nself\n):\n\n\n # The state (including self.state.id) is automatically reloaded\n\n\n self\n.state.counter \n+=\n 1\n\n\n print\n(\n\"Flow state is persisted. Counter:\"\n, \nself\n.state.counter)\n\n\n\n\n​\nMethod-Level Persistence\n\n\nFor more granular control, you can apply @persist to specific methods:\n\n\nCopy\nAsk AI\nclass\n AnotherFlow\n(Flow[\ndict\n]):\n\n\n @persist\n # Persists only this method's state\n\n\n @start\n()\n\n\n def\n begin\n(\nself\n):\n\n\n if\n \"runs\"\n not\n in\n self\n.state:\n\n\n self\n.state[\n\"runs\"\n] \n=\n 0\n\n\n self\n.state[\n\"runs\"\n] \n+=\n 1\n\n\n print\n(\n\"Method-level persisted runs:\"\n, \nself\n.state[\n\"runs\"\n])\n\n\n\n\n​\nHow It Works\n\n\n\n\n\n\nUnique State Identification\n\n\n\n\nEach flow state automatically receives a unique UUID\n\n\nThe ID is preserved across state updates and method calls\n\n\nSupports both structured (Pydantic BaseModel) and unstructured (dictionary) states\n\n\n\n\n\n\n\n\nDefault SQLite Backend\n\n\n\n\nSQLiteFlowPersistence is the default storage backend\n\n\nStates are automatically saved to a local SQLite database\n\n\nRobust error handling ensures clear messages if database operations fail\n\n\n\n\n\n\n\n\nError Handling\n\n\n\n\nComprehensive error messages for database operations\n\n\nAutomatic state validation during save and load\n\n\nClear feedback when persistence operations encounter issues\n\n\n\n\n\n\n\n\n​\nImportant Considerations\n\n\n\n\nState Types\n: Both structured (Pydantic BaseModel) and unstructured (dictionary) states are supported\n\n\nAutomatic ID\n: The \nid\n field is automatically added if not present\n\n\nState Recovery\n: Failed or restarted flows can automatically reload their previous state\n\n\nCustom Implementation\n: You can provide your own FlowPersistence implementation for specialized storage needs\n\n\n\n\n​\nTechnical Advantages\n\n\n\n\n\n\nPrecise Control Through Low-Level Access\n\n\n\n\nDirect access to persistence operations for advanced use cases\n\n\nFine-grained control via method-level persistence decorators\n\n\nBuilt-in state inspection and debugging capabilities\n\n\nFull visibility into state changes and persistence operations\n\n\n\n\n\n\n\n\nEnhanced Reliability\n\n\n\n\nAutomatic state recovery after system failures or restarts\n\n\nTransaction-based state updates for data integrity\n\n\nComprehensive error handling with clear error messages\n\n\nRobust validation during state save and load operations\n\n\n\n\n\n\n\n\nExtensible Architecture\n\n\n\n\nCustomizable persistence backend through FlowPersistence interface\n\n\nSupport for specialized storage solutions beyond SQLite\n\n\nCompatible with both structured (Pydantic) and unstructured (dict) states\n\n\nSeamless integration with existing CrewAI flow patterns\n\n\n\n\n\n\n\n\nThe persistence system’s architecture emphasizes technical precision and customization options, allowing developers to maintain full control over state management while benefiting from built-in reliability features.\n\n\n​\nFlow Control\n\n\n​\nConditional Logic: \nor\n\n\nThe \nor_\n function in Flows allows you to listen to multiple methods and trigger the listener method when any of the specified methods emit an output.\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, listen, or_, start\n\n\n\n\nclass\n OrExampleFlow\n(\nFlow\n):\n\n\n\n\n @start\n()\n\n\n def\n start_method\n(\nself\n):\n\n\n return\n \"Hello from the start method\"\n\n\n\n\n @listen\n(start_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n return\n \"Hello from the second method\"\n\n\n\n\n @listen\n(or_(start_method, second_method))\n\n\n def\n logger\n(\nself\n, \nresult\n):\n\n\n print\n(\nf\n\"Logger: \n{\nresult\n}\n\"\n)\n\n\n\n\n\n\n\n\nflow \n=\n OrExampleFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nflow.kickoff()\n\n\n\n\n\n\nWhen you run this Flow, the \nlogger\n method will be triggered by the output of either the \nstart_method\n or the \nsecond_method\n.\nThe \nor_\n function is used to listen to multiple methods and trigger the listener method when any of the specified methods emit an output.\n\n\n​\nConditional Logic: \nand\n\n\nThe \nand_\n function in Flows allows you to listen to multiple methods and trigger the listener method only when all the specified methods emit an output.\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai.flow.flow \nimport\n Flow, and_, listen, start\n\n\n\n\nclass\n AndExampleFlow\n(\nFlow\n):\n\n\n\n\n @start\n()\n\n\n def\n start_method\n(\nself\n):\n\n\n self\n.state[\n\"greeting\"\n] \n=\n \"Hello from the start method\"\n\n\n\n\n @listen\n(start_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n self\n.state[\n\"joke\"\n] \n=\n \"What do computers eat? Microchips.\"\n\n\n\n\n @listen\n(and_(start_method, second_method))\n\n\n def\n logger\n(\nself\n):\n\n\n print\n(\n\"---- Logger ----\"\n)\n\n\n print\n(\nself\n.state)\n\n\n\n\nflow \n=\n AndExampleFlow()\n\n\nflow.plot()\n\n\nflow.kickoff()\n\n\n\n\n\n\nWhen you run this Flow, the \nlogger\n method will be triggered only when both the \nstart_method\n and the \nsecond_method\n emit an output.\nThe \nand_\n function is used to listen to multiple methods and trigger the listener method only when all the specified methods emit an output.\n\n\n​\nRouter\n\n\nThe \n@router()\n decorator in Flows allows you to define conditional routing logic based on the output of a method.\nYou can specify different routes based on the output of the method, allowing you to control the flow of execution dynamically.\n\n\nCode\nOutput\nCopy\nAsk AI\nimport\n random\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, router, start\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\n\n\nclass\n ExampleState\n(\nBaseModel\n):\n\n\n success_flag: \nbool\n =\n False\n\n\n\n\nclass\n RouterFlow\n(Flow[ExampleState]):\n\n\n\n\n @start\n()\n\n\n def\n start_method\n(\nself\n):\n\n\n print\n(\n\"Starting the structured flow\"\n)\n\n\n random_boolean \n=\n random.choice([\nTrue\n, \nFalse\n])\n\n\n self\n.state.success_flag \n=\n random_boolean\n\n\n\n\n @router\n(start_method)\n\n\n def\n second_method\n(\nself\n):\n\n\n if\n self\n.state.success_flag:\n\n\n return\n \"success\"\n\n\n else\n:\n\n\n return\n \"failed\"\n\n\n\n\n @listen\n(\n\"success\"\n)\n\n\n def\n third_method\n(\nself\n):\n\n\n print\n(\n\"Third method running\"\n)\n\n\n\n\n @listen\n(\n\"failed\"\n)\n\n\n def\n fourth_method\n(\nself\n):\n\n\n print\n(\n\"Fourth method running\"\n)\n\n\n\n\n\n\nflow \n=\n RouterFlow()\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\nflow.kickoff()\n\n\n\n\n\n\nIn the above example, the \nstart_method\n generates a random boolean value and sets it in the state.\nThe \nsecond_method\n uses the \n@router()\n decorator to define conditional routing logic based on the value of the boolean.\nIf the boolean is \nTrue\n, the method returns \n\"success\"\n, and if it is \nFalse\n, the method returns \n\"failed\"\n.\nThe \nthird_method\n and \nfourth_method\n listen to the output of the \nsecond_method\n and execute based on the returned value.\n\n\nWhen you run this Flow, the output will change based on the random boolean value generated by the \nstart_method\n.\n\n\n​\nAdding Agents to Flows\n\n\nAgents can be seamlessly integrated into your flows, providing a lightweight alternative to full Crews when you need simpler, focused task execution. Here’s an example of how to use an Agent within a flow to perform market research:\n\n\nCopy\nAsk AI\nimport\n asyncio\n\n\nfrom\n typing \nimport\n Any, Dict, List\n\n\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nfrom\n crewai.agent \nimport\n Agent\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\n\n\n\n\n# Define a structured output format\n\n\nclass\n MarketAnalysis\n(\nBaseModel\n):\n\n\n key_trends: List[\nstr\n] \n=\n Field(\ndescription\n=\n\"List of identified market trends\"\n)\n\n\n market_size: \nstr\n =\n Field(\ndescription\n=\n\"Estimated market size\"\n)\n\n\n competitors: List[\nstr\n] \n=\n Field(\ndescription\n=\n\"Major competitors in the space\"\n)\n\n\n\n\n\n\n# Define flow state\n\n\nclass\n MarketResearchState\n(\nBaseModel\n):\n\n\n product: \nstr\n =\n \"\"\n\n\n analysis: MarketAnalysis \n|\n None\n =\n None\n\n\n\n\n\n\n# Create a flow class\n\n\nclass\n MarketResearchFlow\n(Flow[MarketResearchState]):\n\n\n @start\n()\n\n\n def\n initialize_research\n(\nself\n) -> Dict[\nstr\n, Any]:\n\n\n print\n(\nf\n\"Starting market research for \n{\nself\n.state.product\n}\n\"\n)\n\n\n return\n {\n\"product\"\n: \nself\n.state.product}\n\n\n\n\n @listen\n(initialize_research)\n\n\n async\n def\n analyze_market\n(\nself\n) -> Dict[\nstr\n, Any]:\n\n\n # Create an Agent for market research\n\n\n analyst \n=\n Agent(\n\n\n role\n=\n\"Market Research Analyst\"\n,\n\n\n goal\n=\nf\n\"Analyze the market for \n{\nself\n.state.product\n}\n\"\n,\n\n\n backstory\n=\n\"You are an experienced market analyst with expertise in \"\n\n\n \"identifying market trends and opportunities.\"\n,\n\n\n tools\n=\n[SerperDevTool()],\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\n # Define the research query\n\n\n query \n=\n f\n\"\"\"\n\n\n Research the market for \n{\nself\n.state.product\n}\n. Include:\n\n\n 1. Key market trends\n\n\n 2. Market size\n\n\n 3. Major competitors\n\n\n\n\n Format your response according to the specified structure.\n\n\n \"\"\"\n\n\n\n\n # Execute the analysis with structured output format\n\n\n result \n=\n await\n analyst.kickoff_async(query, \nresponse_format\n=\nMarketAnalysis)\n\n\n if\n result.pydantic:\n\n\n print\n(\n\"result\"\n, result.pydantic)\n\n\n else\n:\n\n\n print\n(\n\"result\"\n, result)\n\n\n\n\n # Return the analysis to update the state\n\n\n return\n {\n\"analysis\"\n: result.pydantic}\n\n\n\n\n @listen\n(analyze_market)\n\n\n def\n present_results\n(\nself\n, \nanalysis\n) -> \nNone\n:\n\n\n print\n(\n\"\n\\n\nMarket Analysis Results\"\n)\n\n\n print\n(\n\"=====================\"\n)\n\n\n\n\n if\n isinstance\n(analysis, \ndict\n):\n\n\n # If we got a dict with 'analysis' key, extract the actual analysis object\n\n\n market_analysis \n=\n analysis.get(\n\"analysis\"\n)\n\n\n else\n:\n\n\n market_analysis \n=\n analysis\n\n\n\n\n if\n market_analysis \nand\n isinstance\n(market_analysis, MarketAnalysis):\n\n\n print\n(\n\"\n\\n\nKey Market Trends:\"\n)\n\n\n for\n trend \nin\n market_analysis.key_trends:\n\n\n print\n(\nf\n\"- \n{\ntrend\n}\n\"\n)\n\n\n\n\n print\n(\nf\n\"\n\\n\nMarket Size: \n{\nmarket_analysis.market_size\n}\n\"\n)\n\n\n\n\n print\n(\n\"\n\\n\nMajor Competitors:\"\n)\n\n\n for\n competitor \nin\n market_analysis.competitors:\n\n\n print\n(\nf\n\"- \n{\ncompetitor\n}\n\"\n)\n\n\n else\n:\n\n\n print\n(\n\"No structured analysis data available.\"\n)\n\n\n print\n(\n\"Raw analysis:\"\n, analysis)\n\n\n\n\n\n\n# Usage example\n\n\nasync\n def\n run_flow\n():\n\n\n flow \n=\n MarketResearchFlow()\n\n\n flow.plot(\n\"MarketResearchFlowPlot\"\n)\n\n\n result \n=\n await\n flow.kickoff_async(\ninputs\n=\n{\n\"product\"\n: \n\"AI-powered chatbots\"\n})\n\n\n return\n result\n\n\n\n\n\n\n# Run the flow\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n asyncio.run(run_flow())\n\n\n\n\n\n\nThis example demonstrates several key features of using Agents in flows:\n\n\n\n\n\n\nStructured Output\n: Using Pydantic models to define the expected output format (\nMarketAnalysis\n) ensures type safety and structured data throughout the flow.\n\n\n\n\n\n\nState Management\n: The flow state (\nMarketResearchState\n) maintains context between steps and stores both inputs and outputs.\n\n\n\n\n\n\nTool Integration\n: Agents can use tools (like \nWebsiteSearchTool\n) to enhance their capabilities.\n\n\n\n\n\n\n​\nAdding Crews to Flows\n\n\nCreating a flow with multiple crews in CrewAI is straightforward.\n\n\nYou can generate a new CrewAI project that includes all the scaffolding needed to create a flow with multiple crews by running the following command:\n\n\nCopy\nAsk AI\ncrewai\n create\n flow\n name_of_flow\n\n\n\n\nThis command will generate a new CrewAI project with the necessary folder structure. The generated project includes a prebuilt crew called \npoem_crew\n that is already working. You can use this crew as a template by copying, pasting, and editing it to create other crews.\n\n\n​\nFolder Structure\n\n\nAfter running the \ncrewai create flow name_of_flow\n command, you will see a folder structure similar to the following:\n\n\nDirectory/File\nDescription\nname_of_flow/\nRoot directory for the flow.\n├── \ncrews/\nContains directories for specific crews.\n│ └── \npoem_crew/\nDirectory for the “poem_crew” with its configurations and scripts.\n│ ├── \nconfig/\nConfiguration files directory for the “poem_crew”.\n│ │ ├── \nagents.yaml\nYAML file defining the agents for “poem_crew”.\n│ │ └── \ntasks.yaml\nYAML file defining the tasks for “poem_crew”.\n│ ├── \npoem_crew.py\nScript for “poem_crew” functionality.\n├── \ntools/\nDirectory for additional tools used in the flow.\n│ └── \ncustom_tool.py\nCustom tool implementation.\n├── \nmain.py\nMain script for running the flow.\n├── \nREADME.md\nProject description and instructions.\n├── \npyproject.toml\nConfiguration file for project dependencies and settings.\n└── \n.gitignore\nSpecifies files and directories to ignore in version control.\n\n\n​\nBuilding Your Crews\n\n\nIn the \ncrews\n folder, you can define multiple crews. Each crew will have its own folder containing configuration files and the crew definition file. For example, the \npoem_crew\n folder contains:\n\n\n\n\nconfig/agents.yaml\n: Defines the agents for the crew.\n\n\nconfig/tasks.yaml\n: Defines the tasks for the crew.\n\n\npoem_crew.py\n: Contains the crew definition, including agents, tasks, and the crew itself.\n\n\n\n\nYou can copy, paste, and edit the \npoem_crew\n to create other crews.\n\n\n​\nConnecting Crews in \nmain.py\n\n\nThe \nmain.py\n file is where you create your flow and connect the crews together. You can define your flow by using the \nFlow\n class and the decorators \n@start\n and \n@listen\n to specify the flow of execution.\n\n\nHere’s an example of how you can connect the \npoem_crew\n in the \nmain.py\n file:\n\n\nCode\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\nfrom\n random \nimport\n randint\n\n\n\n\nfrom\n pydantic \nimport\n BaseModel\n\n\nfrom\n crewai.flow.flow \nimport\n Flow, listen, start\n\n\nfrom\n .crews.poem_crew.poem_crew \nimport\n PoemCrew\n\n\n\n\nclass\n PoemState\n(\nBaseModel\n):\n\n\n sentence_count: \nint\n =\n 1\n\n\n poem: \nstr\n =\n \"\"\n\n\n\n\nclass\n PoemFlow\n(Flow[PoemState]):\n\n\n\n\n @start\n()\n\n\n def\n generate_sentence_count\n(\nself\n):\n\n\n print\n(\n\"Generating sentence count\"\n)\n\n\n self\n.state.sentence_count \n=\n randint(\n1\n, \n5\n)\n\n\n\n\n @listen\n(generate_sentence_count)\n\n\n def\n generate_poem\n(\nself\n):\n\n\n print\n(\n\"Generating poem\"\n)\n\n\n result \n=\n PoemCrew().crew().kickoff(\ninputs\n=\n{\n\"sentence_count\"\n: \nself\n.state.sentence_count})\n\n\n\n\n print\n(\n\"Poem generated\"\n, result.raw)\n\n\n self\n.state.poem \n=\n result.raw\n\n\n\n\n @listen\n(generate_poem)\n\n\n def\n save_poem\n(\nself\n):\n\n\n print\n(\n\"Saving poem\"\n)\n\n\n with\n open\n(\n\"poem.txt\"\n, \n\"w\"\n) \nas\n f:\n\n\n f.write(\nself\n.state.poem)\n\n\n\n\ndef\n kickoff\n():\n\n\n poem_flow \n=\n PoemFlow()\n\n\n poem_flow.kickoff()\n\n\n\n\n\n\ndef\n plot\n():\n\n\n poem_flow \n=\n PoemFlow()\n\n\n poem_flow.plot(\n\"PoemFlowPlot\"\n)\n\n\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n kickoff()\n\n\n plot()\n\n\n\n\nIn this example, the \nPoemFlow\n class defines a flow that generates a sentence count, uses the \nPoemCrew\n to generate a poem, and then saves the poem to a file. The flow is kicked off by calling the \nkickoff()\n method. The PoemFlowPlot will be generated by \nplot()\n method.\n\n\n\n\n​\nRunning the Flow\n\n\n(Optional) Before running the flow, you can install the dependencies by running:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\nOnce all of the dependencies are installed, you need to activate the virtual environment by running:\n\n\nCopy\nAsk AI\nsource\n .venv/bin/activate\n\n\n\n\nAfter activating the virtual environment, you can run the flow by executing one of the following commands:\n\n\nCopy\nAsk AI\ncrewai\n flow\n kickoff\n\n\n\n\nor\n\n\nCopy\nAsk AI\nuv\n run\n kickoff\n\n\n\n\nThe flow will execute, and you should see the output in the console.\n\n\n​\nPlot Flows\n\n\nVisualizing your AI workflows can provide valuable insights into the structure and execution paths of your flows. CrewAI offers a powerful visualization tool that allows you to generate interactive plots of your flows, making it easier to understand and optimize your AI workflows.\n\n\n​\nWhat are Plots?\n\n\nPlots in CrewAI are graphical representations of your AI workflows. They display the various tasks, their connections, and the flow of data between them. This visualization helps in understanding the sequence of operations, identifying bottlenecks, and ensuring that the workflow logic aligns with your expectations.\n\n\n​\nHow to Generate a Plot\n\n\nCrewAI provides two convenient methods to generate plots of your flows:\n\n\n​\nOption 1: Using the \nplot()\n Method\n\n\nIf you are working directly with a flow instance, you can generate a plot by calling the \nplot()\n method on your flow object. This method will create an HTML file containing the interactive plot of your flow.\n\n\nCode\nCopy\nAsk AI\n# Assuming you have a flow instance\n\n\nflow.plot(\n\"my_flow_plot\"\n)\n\n\n\n\nThis will generate a file named \nmy_flow_plot.html\n in your current directory. You can open this file in a web browser to view the interactive plot.\n\n\n​\nOption 2: Using the Command Line\n\n\nIf you are working within a structured CrewAI project, you can generate a plot using the command line. This is particularly useful for larger projects where you want to visualize the entire flow setup.\n\n\nCopy\nAsk AI\ncrewai\n flow\n plot\n\n\n\n\nThis command will generate an HTML file with the plot of your flow, similar to the \nplot()\n method. The file will be saved in your project directory, and you can open it in a web browser to explore the flow.\n\n\n​\nUnderstanding the Plot\n\n\nThe generated plot will display nodes representing the tasks in your flow, with directed edges indicating the flow of execution. The plot is interactive, allowing you to zoom in and out, and hover over nodes to see additional details.\n\n\nBy visualizing your flows, you can gain a clearer understanding of the workflow’s structure, making it easier to debug, optimize, and communicate your AI processes to others.\n\n\n​\nConclusion\n\n\nPlotting your flows is a powerful feature of CrewAI that enhances your ability to design and manage complex AI workflows. Whether you choose to use the \nplot()\n method or the command line, generating plots will provide you with a visual representation of your workflows, aiding in both development and presentation.\n\n\n​\nNext Steps\n\n\nIf you’re interested in exploring additional examples of flows, we have a variety of recommendations in our examples repository. Here are four specific flow examples, each showcasing unique use cases to help you match your current problem type to a specific example:\n\n\n\n\n\n\nEmail Auto Responder Flow\n: This example demonstrates an infinite loop where a background job continually runs to automate email responses. It’s a great use case for tasks that need to be performed repeatedly without manual intervention. \nView Example\n\n\n\n\n\n\nLead Score Flow\n: This flow showcases adding human-in-the-loop feedback and handling different conditional branches using the router. It’s an excellent example of how to incorporate dynamic decision-making and human oversight into your workflows. \nView Example\n\n\n\n\n\n\nWrite a Book Flow\n: This example excels at chaining multiple crews together, where the output of one crew is used by another. Specifically, one crew outlines an entire book, and another crew generates chapters based on the outline. Eventually, everything is connected to produce a complete book. This flow is perfect for complex, multi-step processes that require coordination between different tasks. \nView Example\n\n\n\n\n\n\nMeeting Assistant Flow\n: This flow demonstrates how to broadcast one event to trigger multiple follow-up actions. For instance, after a meeting is completed, the flow can update a Trello board, send a Slack message, and save the results. It’s a great example of handling multiple outcomes from a single event, making it ideal for comprehensive task management and notification systems. \nView Example\n\n\n\n\n\n\nBy exploring these examples, you can gain insights into how to leverage CrewAI Flows for various use cases, from automating repetitive tasks to managing complex, multi-step processes with dynamic decision-making and human feedback.\n\n\nAlso, check out our YouTube video on how to use flows in CrewAI below!\n\n\n\n\n​\nRunning Flows\n\n\nThere are two ways to run a flow:\n\n\n​\nUsing the Flow API\n\n\nYou can run a flow programmatically by creating an instance of your flow class and calling the \nkickoff()\n method:\n\n\nCopy\nAsk AI\nflow \n=\n ExampleFlow()\n\n\nresult \n=\n flow.kickoff()\n\n\n\n\n​\nUsing the CLI\n\n\nStarting from version 0.103.0, you can run flows using the \ncrewai run\n command:\n\n\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\nThis command automatically detects if your project is a flow (based on the \ntype = \"flow\"\n setting in your pyproject.toml) and runs it accordingly. This is the recommended way to run flows from the command line.\n\n\nFor backward compatibility, you can also use:\n\n\nCopy\nAsk AI\ncrewai\n flow\n kickoff\n\n\n\n\nHowever, the \ncrewai run\n command is now the preferred method as it works for both crews and flows.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCrews\nKnowledge\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nGetting Started\n@start()\n@listen()\nUsage\nFlow Output\nRetrieving the Final Output\nAccessing and Updating State\nFlow State Management\nUnstructured State Management\nStructured State Management\nChoosing Between Unstructured and Structured State Management\nFlow Persistence\nClass-Level Persistence\nMethod-Level Persistence\nHow It Works\nImportant Considerations\nTechnical Advantages\nFlow Control\nConditional Logic: or\nConditional Logic: and\nRouter\nAdding Agents to Flows\nAdding Crews to Flows\nFolder Structure\nBuilding Your Crews\nConnecting Crews in main.py\nRunning the Flow\nPlot Flows\nWhat are Plots?\nHow to Generate a Plot\nOption 1: Using the plot() Method\nOption 2: Using the Command Line\nUnderstanding the Plot\nConclusion\nNext Steps\nRunning Flows\nUsing the Flow API\nUsing the CLI" }, { "source": "https://docs.crewai.com/#what-is-crewai%3F", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/learn/coding-agents", "title": "Coding Agents - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nCoding Agents\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nCoding Agents\nCopy page\nLearn how to enable your CrewAI Agents to write and execute code, and explore advanced features for enhanced functionality.\n​\nIntroduction\n\n\nCrewAI Agents now have the powerful ability to write and execute code, significantly enhancing their problem-solving capabilities. This feature is particularly useful for tasks that require computational or programmatic solutions.\n\n\n​\nEnabling Code Execution\n\n\nTo enable code execution for an agent, set the \nallow_code_execution\n parameter to \nTrue\n when creating the agent.\n\n\nHere’s an example:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Senior Python Developer\"\n,\n\n\n goal\n=\n\"Craft well-designed and thought-out code\"\n,\n\n\n backstory\n=\n\"You are a senior Python developer with extensive experience in software architecture and best practices.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\nNote that \nallow_code_execution\n parameter defaults to \nFalse\n.\n\n\n​\nImportant Considerations\n\n\n\n\n\n\nModel Selection\n: It is strongly recommended to use more capable models like Claude 3.5 Sonnet and GPT-4 when enabling code execution.\nThese models have a better understanding of programming concepts and are more likely to generate correct and efficient code.\n\n\n\n\n\n\nError Handling\n: The code execution feature includes error handling. If executed code raises an exception, the agent will receive the error message and can attempt to correct the code or\nprovide alternative solutions. The \nmax_retry_limit\n parameter, which defaults to 2, controls the maximum number of retries for a task.\n\n\n\n\n\n\nDependencies\n: To use the code execution feature, you need to install the \ncrewai_tools\n package. If not installed, the agent will log an info message:\n“Coding tools not available. Install crewai_tools.”\n\n\n\n\n\n\n​\nCode Execution Process\n\n\nWhen an agent with code execution enabled encounters a task requiring programming:\n\n\n1\nTask Analysis\nThe agent analyzes the task and determines that code execution is necessary.\n2\nCode Formulation\nIt formulates the Python code needed to solve the problem.\n3\nCode Execution\nThe code is sent to the internal code execution tool (\nCodeInterpreterTool\n).\n4\nResult Interpretation\nThe agent interprets the result and incorporates it into its response or uses it for further problem-solving.\n\n\n​\nExample Usage\n\n\nHere’s a detailed example of creating an agent with code execution capabilities and using it in a task:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants.\"\n,\n\n\n agent\n=\ncoding_agent\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task]\n\n\n)\n\n\n\n\n# Execute the crew\n\n\nresult \n=\n analysis_crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\n\n\nIn this example, the \ncoding_agent\n can write and execute Python code to perform data analysis tasks.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nConditional Tasks\nCreate Custom Tools\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nEnabling Code Execution\nImportant Considerations\nCode Execution Process\nExample Usage\nLearn\nCoding Agents\nCopy page\nLearn how to enable your CrewAI Agents to write and execute code, and explore advanced features for enhanced functionality.\n​\nIntroduction\n\n\nCrewAI Agents now have the powerful ability to write and execute code, significantly enhancing their problem-solving capabilities. This feature is particularly useful for tasks that require computational or programmatic solutions.\n\n\n​\nEnabling Code Execution\n\n\nTo enable code execution for an agent, set the \nallow_code_execution\n parameter to \nTrue\n when creating the agent.\n\n\nHere’s an example:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent\n\n\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Senior Python Developer\"\n,\n\n\n goal\n=\n\"Craft well-designed and thought-out code\"\n,\n\n\n backstory\n=\n\"You are a senior Python developer with extensive experience in software architecture and best practices.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\nNote that \nallow_code_execution\n parameter defaults to \nFalse\n.\n\n\n​\nImportant Considerations\n\n\n\n\n\n\nModel Selection\n: It is strongly recommended to use more capable models like Claude 3.5 Sonnet and GPT-4 when enabling code execution.\nThese models have a better understanding of programming concepts and are more likely to generate correct and efficient code.\n\n\n\n\n\n\nError Handling\n: The code execution feature includes error handling. If executed code raises an exception, the agent will receive the error message and can attempt to correct the code or\nprovide alternative solutions. The \nmax_retry_limit\n parameter, which defaults to 2, controls the maximum number of retries for a task.\n\n\n\n\n\n\nDependencies\n: To use the code execution feature, you need to install the \ncrewai_tools\n package. If not installed, the agent will log an info message:\n“Coding tools not available. Install crewai_tools.”\n\n\n\n\n\n\n​\nCode Execution Process\n\n\nWhen an agent with code execution enabled encounters a task requiring programming:\n\n\n1\nTask Analysis\nThe agent analyzes the task and determines that code execution is necessary.\n2\nCode Formulation\nIt formulates the Python code needed to solve the problem.\n3\nCode Execution\nThe code is sent to the internal code execution tool (\nCodeInterpreterTool\n).\n4\nResult Interpretation\nThe agent interprets the result and incorporates it into its response or uses it for further problem-solving.\n\n\n​\nExample Usage\n\n\nHere’s a detailed example of creating an agent with code execution capabilities and using it in a task:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n# Create an agent with code execution enabled\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Python Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data and provide insights using Python\"\n,\n\n\n backstory\n=\n\"You are an experienced data analyst with strong Python skills.\"\n,\n\n\n allow_code_execution\n=\nTrue\n\n\n)\n\n\n\n\n# Create a task that requires code execution\n\n\ndata_analysis_task \n=\n Task(\n\n\n description\n=\n\"Analyze the given dataset and calculate the average age of participants.\"\n,\n\n\n agent\n=\ncoding_agent\n\n\n)\n\n\n\n\n# Create a crew and add the task\n\n\nanalysis_crew \n=\n Crew(\n\n\n agents\n=\n[coding_agent],\n\n\n tasks\n=\n[data_analysis_task]\n\n\n)\n\n\n\n\n# Execute the crew\n\n\nresult \n=\n analysis_crew.kickoff()\n\n\n\n\nprint\n(result)\n\n\n\n\nIn this example, the \ncoding_agent\n can write and execute Python code to perform data analysis tasks.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nConditional Tasks\nCreate Custom Tools\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nEnabling Code Execution\nImportant Considerations\nCode Execution Process\nExample Usage" }, { "source": "https://docs.crewai.com/#how-it-all-works-together", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGet Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?\nGet Started\nIntroduction\nCopy page\nBuild AI agent teams that work together to tackle complex tasks\n​\nWhat is CrewAI?\n\n\nCrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.\n\n\nCrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:\n\n\n\n\nCrewAI Crews\n: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.\n\n\nCrewAI Flows\n: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.\n\n\n\n\nWith over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.\n\n\n​\nHow Crews Work\n\n\nJust like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nCrew\nThe top-level organization\n• Manages AI agent teams\n• Oversees workflows\n• Ensures collaboration\n• Delivers outcomes\nAI Agents\nSpecialized team members\n• Have specific roles (researcher, writer)\n• Use designated tools\n• Can delegate tasks\n• Make autonomous decisions\nProcess\nWorkflow management system\n• Defines collaboration patterns\n• Controls task assignments\n• Manages interactions\n• Ensures efficient execution\nTasks\nIndividual assignments\n• Have clear objectives\n• Use specific tools\n• Feed into larger process\n• Produce actionable results\n\n\n​\nHow It All Works Together\n\n\n\n\nThe \nCrew\n organizes the overall operation\n\n\nAI Agents\n work on their specialized tasks\n\n\nThe \nProcess\n ensures smooth collaboration\n\n\nTasks\n get completed to achieve the goal\n\n\n\n\n​\nKey Features\n\n\nRole-Based Agents\nCreate specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers\nFlexible Tools\nEquip agents with custom tools and APIs to interact with external services and data sources\nIntelligent Collaboration\nAgents work together, sharing insights and coordinating tasks to achieve complex objectives\nTask Management\nDefine sequential or parallel workflows, with agents automatically handling task dependencies\n\n\n​\nHow Flows Work\n\n\nWhile Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.\n\n\nCrewAI Framework Overview\n\n\nComponent\nDescription\nKey Features\nFlow\nStructured workflow orchestration\n• Manages execution paths\n• Handles state transitions\n• Controls task sequencing\n• Ensures reliable execution\nEvents\nTriggers for workflow actions\n• Initiate specific processes\n• Enable dynamic responses\n• Support conditional branching\n• Allow for real-time adaptation\nStates\nWorkflow execution contexts\n• Maintain execution data\n• Enable persistence\n• Support resumability\n• Ensure execution integrity\nCrew Support\nEnhances workflow automation\n• Injects pockets of agency when needed\n• Complements structured workflows\n• Balances automation with intelligence\n• Enables adaptive decision-making\n\n\n​\nKey Capabilities\n\n\nEvent-Driven Orchestration\nDefine precise execution paths responding dynamically to events\nFine-Grained Control\nManage workflow states and conditional execution securely and efficiently\nNative Crew Integration\nEffortlessly combine with Crews for enhanced autonomy and intelligence\nDeterministic Execution\nEnsure predictable outcomes with explicit control flow and error handling\n\n\n​\nWhen to Use Crews vs. Flows\n\n\nUnderstanding when to use \nCrews\n versus \nFlows\n is key to maximizing the potential of CrewAI in your applications.\n\n\nUse Case\nRecommended Approach\nWhy?\nOpen-ended research\nCrews\nWhen tasks require creative thinking, exploration, and adaptation\nContent generation\nCrews\nFor collaborative creation of articles, reports, or marketing materials\nDecision workflows\nFlows\nWhen you need predictable, auditable decision paths with precise control\nAPI orchestration\nFlows\nFor reliable integration with multiple external services in a specific sequence\nHybrid applications\nCombined approach\nUse \nFlows\n to orchestrate overall process with \nCrews\n handling complex subtasks\n\n\n​\nDecision Framework\n\n\n\n\nChoose \nCrews\n when:\n You need autonomous problem-solving, creative collaboration, or exploratory tasks\n\n\nChoose \nFlows\n when:\n You require deterministic outcomes, auditability, or precise control over execution\n\n\nCombine both when:\n Your application needs both structured processes and pockets of autonomous intelligence\n\n\n\n\n​\nWhy Choose CrewAI?\n\n\n\n\n🧠 \nAutonomous Operation\n: Agents make intelligent decisions based on their roles and available tools\n\n\n📝 \nNatural Interaction\n: Agents communicate and collaborate like human team members\n\n\n🛠️ \nExtensible Design\n: Easy to add new tools, roles, and capabilities\n\n\n🚀 \nProduction Ready\n: Built for reliability and scalability in real-world applications\n\n\n🔒 \nSecurity-Focused\n: Designed with enterprise security requirements in mind\n\n\n💰 \nCost-Efficient\n: Optimized to minimize token usage and API calls\n\n\n\n\n​\nReady to Start Building?\n\n\nBuild Your First Crew\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\nBuild Your First Flow\nLearn how to create structured, event-driven workflows with precise control over execution.\n\n\nInstall CrewAI\nGet started with CrewAI in your development environment.\nQuick Start\nFollow our quickstart guide to create your first CrewAI agent and get hands-on experience.\nJoin the Community\nConnect with other developers, get help, and share your CrewAI experiences.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nInstallation\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nWhat is CrewAI?\nHow Crews Work\nHow It All Works Together\nKey Features\nHow Flows Work\nKey Capabilities\nWhen to Use Crews vs. Flows\nDecision Framework\nWhy Choose CrewAI?\nReady to Start Building?" }, { "source": "https://docs.crewai.com/en/guides/crews/first-crew", "title": "Build Your First Crew - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCrews\nBuild Your First Crew\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nBuild Your First Crew\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCrews\nBuild Your First Crew\nCopy page\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\n​\nUnleashing the Power of Collaborative AI\n\n\nImagine having a team of specialized AI agents working together seamlessly to solve complex problems, each contributing their unique skills to achieve a common goal. This is the power of CrewAI - a framework that enables you to create collaborative AI systems that can accomplish tasks far beyond what a single AI could achieve alone.\n\n\nIn this guide, we’ll walk through creating a research crew that will help us research and analyze a topic, then create a comprehensive report. This practical example demonstrates how AI agents can collaborate to accomplish complex tasks, but it’s just the beginning of what’s possible with CrewAI.\n\n\n​\nWhat You’ll Build and Learn\n\n\nBy the end of this guide, you’ll have:\n\n\n\n\nCreated a specialized AI research team\n with distinct roles and responsibilities\n\n\nOrchestrated collaboration\n between multiple AI agents\n\n\nAutomated a complex workflow\n that involves gathering information, analysis, and report generation\n\n\nBuilt foundational skills\n that you can apply to more ambitious projects\n\n\n\n\nWhile we’re building a simple research crew in this guide, the same patterns and techniques can be applied to create much more sophisticated teams for tasks like:\n\n\n\n\nMulti-stage content creation with specialized writers, editors, and fact-checkers\n\n\nComplex customer service systems with tiered support agents\n\n\nAutonomous business analysts that gather data, create visualizations, and generate insights\n\n\nProduct development teams that ideate, design, and plan implementation\n\n\n\n\nLet’s get started building your first crew!\n\n\n​\nPrerequisites\n\n\nBefore starting, make sure you have:\n\n\n\n\nInstalled CrewAI following the \ninstallation guide\n\n\nSet up your LLM API key in your environment, following the \nLLM setup\nguide\n\n\nBasic understanding of Python\n\n\n\n\n​\nStep 1: Create a New CrewAI Project\n\n\nFirst, let’s create a new CrewAI project using the CLI. This command will set up a complete project structure with all the necessary files, allowing you to focus on defining your agents and their tasks rather than setting up boilerplate code.\n\n\nCopy\nAsk AI\ncrewai\n create\n crew\n research_crew\n\n\ncd\n research_crew\n\n\n\n\nThis will generate a project with the basic structure needed for your crew. The CLI automatically creates:\n\n\n\n\nA project directory with the necessary files\n\n\nConfiguration files for agents and tasks\n\n\nA basic crew implementation\n\n\nA main script to run the crew\n\n\n\n\nCrewAI Framework Overview\n\n\n​\nStep 2: Explore the Project Structure\n\n\nLet’s take a moment to understand the project structure created by the CLI. CrewAI follows best practices for Python projects, making it easy to maintain and extend your code as your crews become more complex.\n\n\nCopy\nAsk AI\nresearch_crew/\n\n\n├── .gitignore\n\n\n├── pyproject.toml\n\n\n├── README.md\n\n\n├── .env\n\n\n└── src/\n\n\n └── research_crew/\n\n\n ├── __init__.py\n\n\n ├── main.py\n\n\n ├── crew.py\n\n\n ├── tools/\n\n\n │ ├── custom_tool.py\n\n\n │ └── __init__.py\n\n\n └── config/\n\n\n ├── agents.yaml\n\n\n └── tasks.yaml\n\n\n\n\nThis structure follows best practices for Python projects and makes it easy to organize your code. The separation of configuration files (in YAML) from implementation code (in Python) makes it easy to modify your crew’s behavior without changing the underlying code.\n\n\n​\nStep 3: Configure Your Agents\n\n\nNow comes the fun part - defining your AI agents! In CrewAI, agents are specialized entities with specific roles, goals, and backstories that shape their behavior. Think of them as characters in a play, each with their own personality and purpose.\n\n\nFor our research crew, we’ll create two agents:\n\n\n\n\nA \nresearcher\n who excels at finding and organizing information\n\n\nAn \nanalyst\n who can interpret research findings and create insightful reports\n\n\n\n\nLet’s modify the \nagents.yaml\n file to define these specialized agents. Be sure\nto set \nllm\n to the provider you are using.\n\n\nCopy\nAsk AI\n# src/research_crew/config/agents.yaml\n\n\nresearcher\n:\n\n\n role\n: \n>\n\n\n Senior Research Specialist for {topic}\n\n\n goal\n: \n>\n\n\n Find comprehensive and accurate information about {topic}\n\n\n with a focus on recent developments and key insights\n\n\n backstory\n: \n>\n\n\n You are an experienced research specialist with a talent for\n\n\n finding relevant information from various sources. You excel at\n\n\n organizing information in a clear and structured manner, making\n\n\n complex topics accessible to others.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\nanalyst\n:\n\n\n role\n: \n>\n\n\n Data Analyst and Report Writer for {topic}\n\n\n goal\n: \n>\n\n\n Analyze research findings and create a comprehensive, well-structured\n\n\n report that presents insights in a clear and engaging way\n\n\n backstory\n: \n>\n\n\n You are a skilled analyst with a background in data interpretation\n\n\n and technical writing. You have a talent for identifying patterns\n\n\n and extracting meaningful insights from research data, then\n\n\n communicating those insights effectively through well-crafted reports.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\nNotice how each agent has a distinct role, goal, and backstory. These elements aren’t just descriptive - they actively shape how the agent approaches its tasks. By crafting these carefully, you can create agents with specialized skills and perspectives that complement each other.\n\n\n​\nStep 4: Define Your Tasks\n\n\nWith our agents defined, we now need to give them specific tasks to perform. Tasks in CrewAI represent the concrete work that agents will perform, with detailed instructions and expected outputs.\n\n\nFor our research crew, we’ll define two main tasks:\n\n\n\n\nA \nresearch task\n for gathering comprehensive information\n\n\nAn \nanalysis task\n for creating an insightful report\n\n\n\n\nLet’s modify the \ntasks.yaml\n file:\n\n\nCopy\nAsk AI\n# src/research_crew/config/tasks.yaml\n\n\nresearch_task\n:\n\n\n description\n: \n>\n\n\n Conduct thorough research on {topic}. Focus on:\n\n\n 1. Key concepts and definitions\n\n\n 2. Historical development and recent trends\n\n\n 3. Major challenges and opportunities\n\n\n 4. Notable applications or case studies\n\n\n 5. Future outlook and potential developments\n\n\n\n\n Make sure to organize your findings in a structured format with clear sections.\n\n\n expected_output\n: \n>\n\n\n A comprehensive research document with well-organized sections covering\n\n\n all the requested aspects of {topic}. Include specific facts, figures,\n\n\n and examples where relevant.\n\n\n agent\n: \nresearcher\n\n\n\n\nanalysis_task\n:\n\n\n description\n: \n>\n\n\n Analyze the research findings and create a comprehensive report on {topic}.\n\n\n Your report should:\n\n\n 1. Begin with an executive summary\n\n\n 2. Include all key information from the research\n\n\n 3. Provide insightful analysis of trends and patterns\n\n\n 4. Offer recommendations or future considerations\n\n\n 5. Be formatted in a professional, easy-to-read style with clear headings\n\n\n expected_output\n: \n>\n\n\n A polished, professional report on {topic} that presents the research\n\n\n findings with added analysis and insights. The report should be well-structured\n\n\n with an executive summary, main sections, and conclusion.\n\n\n agent\n: \nanalyst\n\n\n context\n:\n\n\n - \nresearch_task\n\n\n output_file\n: \noutput/report.md\n\n\n\n\nNote the \ncontext\n field in the analysis task - this is a powerful feature that allows the analyst to access the output of the research task. This creates a workflow where information flows naturally between agents, just as it would in a human team.\n\n\n​\nStep 5: Configure Your Crew\n\n\nNow it’s time to bring everything together by configuring our crew. The crew is the container that orchestrates how agents work together to complete tasks.\n\n\nLet’s modify the \ncrew.py\n file:\n\n\nCopy\nAsk AI\n# src/research_crew/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n ResearchCrew\n():\n\n\n \"\"\"Research crew for comprehensive topic analysis and reporting\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n analysis_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'analysis_task'\n], \n# type: ignore[index]\n\n\n output_file\n=\n'output/report.md'\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the research crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nIn this code, we’re:\n\n\n\n\nCreating the researcher agent and equipping it with the SerperDevTool to search the web\n\n\nCreating the analyst agent\n\n\nSetting up the research and analysis tasks\n\n\nConfiguring the crew to run tasks sequentially (the analyst will wait for the researcher to finish)\n\n\n\n\nThis is where the magic happens - with just a few lines of code, we’ve defined a collaborative AI system where specialized agents work together in a coordinated process.\n\n\n​\nStep 6: Set Up Your Main Script\n\n\nNow, let’s set up the main script that will run our crew. This is where we provide the specific topic we want our crew to research.\n\n\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\n# src/research_crew/main.py\n\n\nimport\n os\n\n\nfrom\n research_crew.crew \nimport\n ResearchCrew\n\n\n\n\n# Create output directory if it doesn't exist\n\n\nos.makedirs(\n'output'\n, \nexist_ok\n=\nTrue\n)\n\n\n\n\ndef\n run\n():\n\n\n \"\"\"\n\n\n Run the research crew.\n\n\n \"\"\"\n\n\n inputs \n=\n {\n\n\n 'topic'\n: \n'Artificial Intelligence in Healthcare'\n\n\n }\n\n\n\n\n # Create and run the crew\n\n\n result \n=\n ResearchCrew().crew().kickoff(\ninputs\n=\ninputs)\n\n\n\n\n # Print the result\n\n\n print\n(\n\"\n\\n\\n\n=== FINAL REPORT ===\n\\n\\n\n\"\n)\n\n\n print\n(result.raw)\n\n\n\n\n print\n(\n\"\n\\n\\n\nReport has been saved to output/report.md\"\n)\n\n\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n run()\n\n\n\n\nThis script prepares the environment, specifies our research topic, and kicks off the crew’s work. The power of CrewAI is evident in how simple this code is - all the complexity of managing multiple AI agents is handled by the framework.\n\n\n​\nStep 7: Set Up Your Environment Variables\n\n\nCreate a \n.env\n file in your project root with your API keys:\n\n\nCopy\nAsk AI\nSERPER_API_KEY\n=\nyour_serper_api_key\n\n\n# Add your provider's API key here too.\n\n\n\n\nSee the \nLLM Setup guide\n for details on configuring your provider of choice. You can get a Serper API key from \nSerper.dev\n.\n\n\n​\nStep 8: Install Dependencies\n\n\nInstall the required dependencies using the CrewAI CLI:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\nThis command will:\n\n\n\n\nRead the dependencies from your project configuration\n\n\nCreate a virtual environment if needed\n\n\nInstall all required packages\n\n\n\n\n​\nStep 9: Run Your Crew\n\n\nNow for the exciting moment - it’s time to run your crew and see AI collaboration in action!\n\n\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\nWhen you run this command, you’ll see your crew spring to life. The researcher will gather information about the specified topic, and the analyst will then create a comprehensive report based on that research. You’ll see the agents’ thought processes, actions, and outputs in real-time as they work together to complete their tasks.\n\n\n​\nStep 10: Review the Output\n\n\nOnce the crew completes its work, you’ll find the final report in the \noutput/report.md\n file. The report will include:\n\n\n\n\nAn executive summary\n\n\nDetailed information about the topic\n\n\nAnalysis and insights\n\n\nRecommendations or future considerations\n\n\n\n\nTake a moment to appreciate what you’ve accomplished - you’ve created a system where multiple AI agents collaborated on a complex task, each contributing their specialized skills to produce a result that’s greater than what any single agent could achieve alone.\n\n\n​\nExploring Other CLI Commands\n\n\nCrewAI offers several other useful CLI commands for working with crews:\n\n\nCopy\nAsk AI\n# View all available commands\n\n\ncrewai\n --help\n\n\n\n\n# Run the crew\n\n\ncrewai\n run\n\n\n\n\n# Test the crew\n\n\ncrewai\n test\n\n\n\n\n# Reset crew memories\n\n\ncrewai\n reset-memories\n\n\n\n\n# Replay from a specific task\n\n\ncrewai\n replay\n -t\n <\ntask_i\nd\n>\n\n\n\n\n​\nThe Art of the Possible: Beyond Your First Crew\n\n\nWhat you’ve built in this guide is just the beginning. The skills and patterns you’ve learned can be applied to create increasingly sophisticated AI systems. Here are some ways you could extend this basic research crew:\n\n\n​\nExpanding Your Crew\n\n\nYou could add more specialized agents to your crew:\n\n\n\n\nA \nfact-checker\n to verify research findings\n\n\nA \ndata visualizer\n to create charts and graphs\n\n\nA \ndomain expert\n with specialized knowledge in a particular area\n\n\nA \ncritic\n to identify weaknesses in the analysis\n\n\n\n\n​\nAdding Tools and Capabilities\n\n\nYou could enhance your agents with additional tools:\n\n\n\n\nWeb browsing tools for real-time research\n\n\nCSV/database tools for data analysis\n\n\nCode execution tools for data processing\n\n\nAPI connections to external services\n\n\n\n\n​\nCreating More Complex Workflows\n\n\nYou could implement more sophisticated processes:\n\n\n\n\nHierarchical processes where manager agents delegate to worker agents\n\n\nIterative processes with feedback loops for refinement\n\n\nParallel processes where multiple agents work simultaneously\n\n\nDynamic processes that adapt based on intermediate results\n\n\n\n\n​\nApplying to Different Domains\n\n\nThe same patterns can be applied to create crews for:\n\n\n\n\nContent creation\n: Writers, editors, fact-checkers, and designers working together\n\n\nCustomer service\n: Triage agents, specialists, and quality control working together\n\n\nProduct development\n: Researchers, designers, and planners collaborating\n\n\nData analysis\n: Data collectors, analysts, and visualization specialists\n\n\n\n\n​\nNext Steps\n\n\nNow that you’ve built your first crew, you can:\n\n\n\n\nExperiment with different agent configurations and personalities\n\n\nTry more complex task structures and workflows\n\n\nImplement custom tools to give your agents new capabilities\n\n\nApply your crew to different topics or problem domains\n\n\nExplore \nCrewAI Flows\n for more advanced workflows with procedural programming\n\n\n\n\nCongratulations! You’ve successfully built your first CrewAI crew that can research and analyze any topic you provide. This foundational experience has equipped you with the skills to create increasingly sophisticated AI systems that can tackle complex, multi-stage problems through collaborative intelligence.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCrafting Effective Agents\nBuild Your First Flow\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nUnleashing the Power of Collaborative AI\nWhat You’ll Build and Learn\nPrerequisites\nStep 1: Create a New CrewAI Project\nStep 2: Explore the Project Structure\nStep 3: Configure Your Agents\nStep 4: Define Your Tasks\nStep 5: Configure Your Crew\nStep 6: Set Up Your Main Script\nStep 7: Set Up Your Environment Variables\nStep 8: Install Dependencies\nStep 9: Run Your Crew\nStep 10: Review the Output\nExploring Other CLI Commands\nThe Art of the Possible: Beyond Your First Crew\nExpanding Your Crew\nAdding Tools and Capabilities\nCreating More Complex Workflows\nApplying to Different Domains\nNext Steps\nCrews\nBuild Your First Crew\nCopy page\nStep-by-step tutorial to create a collaborative AI team that works together to solve complex problems.\n​\nUnleashing the Power of Collaborative AI\n\n\nImagine having a team of specialized AI agents working together seamlessly to solve complex problems, each contributing their unique skills to achieve a common goal. This is the power of CrewAI - a framework that enables you to create collaborative AI systems that can accomplish tasks far beyond what a single AI could achieve alone.\n\n\nIn this guide, we’ll walk through creating a research crew that will help us research and analyze a topic, then create a comprehensive report. This practical example demonstrates how AI agents can collaborate to accomplish complex tasks, but it’s just the beginning of what’s possible with CrewAI.\n\n\n​\nWhat You’ll Build and Learn\n\n\nBy the end of this guide, you’ll have:\n\n\n\n\nCreated a specialized AI research team\n with distinct roles and responsibilities\n\n\nOrchestrated collaboration\n between multiple AI agents\n\n\nAutomated a complex workflow\n that involves gathering information, analysis, and report generation\n\n\nBuilt foundational skills\n that you can apply to more ambitious projects\n\n\n\n\nWhile we’re building a simple research crew in this guide, the same patterns and techniques can be applied to create much more sophisticated teams for tasks like:\n\n\n\n\nMulti-stage content creation with specialized writers, editors, and fact-checkers\n\n\nComplex customer service systems with tiered support agents\n\n\nAutonomous business analysts that gather data, create visualizations, and generate insights\n\n\nProduct development teams that ideate, design, and plan implementation\n\n\n\n\nLet’s get started building your first crew!\n\n\n​\nPrerequisites\n\n\nBefore starting, make sure you have:\n\n\n\n\nInstalled CrewAI following the \ninstallation guide\n\n\nSet up your LLM API key in your environment, following the \nLLM setup\nguide\n\n\nBasic understanding of Python\n\n\n\n\n​\nStep 1: Create a New CrewAI Project\n\n\nFirst, let’s create a new CrewAI project using the CLI. This command will set up a complete project structure with all the necessary files, allowing you to focus on defining your agents and their tasks rather than setting up boilerplate code.\n\n\nCopy\nAsk AI\ncrewai\n create\n crew\n research_crew\n\n\ncd\n research_crew\n\n\n\n\nThis will generate a project with the basic structure needed for your crew. The CLI automatically creates:\n\n\n\n\nA project directory with the necessary files\n\n\nConfiguration files for agents and tasks\n\n\nA basic crew implementation\n\n\nA main script to run the crew\n\n\n\n\nCrewAI Framework Overview\n\n\n​\nStep 2: Explore the Project Structure\n\n\nLet’s take a moment to understand the project structure created by the CLI. CrewAI follows best practices for Python projects, making it easy to maintain and extend your code as your crews become more complex.\n\n\nCopy\nAsk AI\nresearch_crew/\n\n\n├── .gitignore\n\n\n├── pyproject.toml\n\n\n├── README.md\n\n\n├── .env\n\n\n└── src/\n\n\n └── research_crew/\n\n\n ├── __init__.py\n\n\n ├── main.py\n\n\n ├── crew.py\n\n\n ├── tools/\n\n\n │ ├── custom_tool.py\n\n\n │ └── __init__.py\n\n\n └── config/\n\n\n ├── agents.yaml\n\n\n └── tasks.yaml\n\n\n\n\nThis structure follows best practices for Python projects and makes it easy to organize your code. The separation of configuration files (in YAML) from implementation code (in Python) makes it easy to modify your crew’s behavior without changing the underlying code.\n\n\n​\nStep 3: Configure Your Agents\n\n\nNow comes the fun part - defining your AI agents! In CrewAI, agents are specialized entities with specific roles, goals, and backstories that shape their behavior. Think of them as characters in a play, each with their own personality and purpose.\n\n\nFor our research crew, we’ll create two agents:\n\n\n\n\nA \nresearcher\n who excels at finding and organizing information\n\n\nAn \nanalyst\n who can interpret research findings and create insightful reports\n\n\n\n\nLet’s modify the \nagents.yaml\n file to define these specialized agents. Be sure\nto set \nllm\n to the provider you are using.\n\n\nCopy\nAsk AI\n# src/research_crew/config/agents.yaml\n\n\nresearcher\n:\n\n\n role\n: \n>\n\n\n Senior Research Specialist for {topic}\n\n\n goal\n: \n>\n\n\n Find comprehensive and accurate information about {topic}\n\n\n with a focus on recent developments and key insights\n\n\n backstory\n: \n>\n\n\n You are an experienced research specialist with a talent for\n\n\n finding relevant information from various sources. You excel at\n\n\n organizing information in a clear and structured manner, making\n\n\n complex topics accessible to others.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\nanalyst\n:\n\n\n role\n: \n>\n\n\n Data Analyst and Report Writer for {topic}\n\n\n goal\n: \n>\n\n\n Analyze research findings and create a comprehensive, well-structured\n\n\n report that presents insights in a clear and engaging way\n\n\n backstory\n: \n>\n\n\n You are a skilled analyst with a background in data interpretation\n\n\n and technical writing. You have a talent for identifying patterns\n\n\n and extracting meaningful insights from research data, then\n\n\n communicating those insights effectively through well-crafted reports.\n\n\n llm\n: \nprovider/model-id\n # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...\n\n\n\n\nNotice how each agent has a distinct role, goal, and backstory. These elements aren’t just descriptive - they actively shape how the agent approaches its tasks. By crafting these carefully, you can create agents with specialized skills and perspectives that complement each other.\n\n\n​\nStep 4: Define Your Tasks\n\n\nWith our agents defined, we now need to give them specific tasks to perform. Tasks in CrewAI represent the concrete work that agents will perform, with detailed instructions and expected outputs.\n\n\nFor our research crew, we’ll define two main tasks:\n\n\n\n\nA \nresearch task\n for gathering comprehensive information\n\n\nAn \nanalysis task\n for creating an insightful report\n\n\n\n\nLet’s modify the \ntasks.yaml\n file:\n\n\nCopy\nAsk AI\n# src/research_crew/config/tasks.yaml\n\n\nresearch_task\n:\n\n\n description\n: \n>\n\n\n Conduct thorough research on {topic}. Focus on:\n\n\n 1. Key concepts and definitions\n\n\n 2. Historical development and recent trends\n\n\n 3. Major challenges and opportunities\n\n\n 4. Notable applications or case studies\n\n\n 5. Future outlook and potential developments\n\n\n\n\n Make sure to organize your findings in a structured format with clear sections.\n\n\n expected_output\n: \n>\n\n\n A comprehensive research document with well-organized sections covering\n\n\n all the requested aspects of {topic}. Include specific facts, figures,\n\n\n and examples where relevant.\n\n\n agent\n: \nresearcher\n\n\n\n\nanalysis_task\n:\n\n\n description\n: \n>\n\n\n Analyze the research findings and create a comprehensive report on {topic}.\n\n\n Your report should:\n\n\n 1. Begin with an executive summary\n\n\n 2. Include all key information from the research\n\n\n 3. Provide insightful analysis of trends and patterns\n\n\n 4. Offer recommendations or future considerations\n\n\n 5. Be formatted in a professional, easy-to-read style with clear headings\n\n\n expected_output\n: \n>\n\n\n A polished, professional report on {topic} that presents the research\n\n\n findings with added analysis and insights. The report should be well-structured\n\n\n with an executive summary, main sections, and conclusion.\n\n\n agent\n: \nanalyst\n\n\n context\n:\n\n\n - \nresearch_task\n\n\n output_file\n: \noutput/report.md\n\n\n\n\nNote the \ncontext\n field in the analysis task - this is a powerful feature that allows the analyst to access the output of the research task. This creates a workflow where information flows naturally between agents, just as it would in a human team.\n\n\n​\nStep 5: Configure Your Crew\n\n\nNow it’s time to bring everything together by configuring our crew. The crew is the container that orchestrates how agents work together to complete tasks.\n\n\nLet’s modify the \ncrew.py\n file:\n\n\nCopy\nAsk AI\n# src/research_crew/crew.py\n\n\nfrom\n crewai \nimport\n Agent, Crew, Process, Task\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, crew, task\n\n\nfrom\n crewai_tools \nimport\n SerperDevTool\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n ResearchCrew\n():\n\n\n \"\"\"Research crew for comprehensive topic analysis and reporting\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n @agent\n\n\n def\n researcher\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'researcher'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[SerperDevTool()]\n\n\n )\n\n\n\n\n @agent\n\n\n def\n analyst\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'analyst'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n research_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'research_task'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n analysis_task\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'analysis_task'\n], \n# type: ignore[index]\n\n\n output_file\n=\n'output/report.md'\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n \"\"\"Creates the research crew\"\"\"\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nIn this code, we’re:\n\n\n\n\nCreating the researcher agent and equipping it with the SerperDevTool to search the web\n\n\nCreating the analyst agent\n\n\nSetting up the research and analysis tasks\n\n\nConfiguring the crew to run tasks sequentially (the analyst will wait for the researcher to finish)\n\n\n\n\nThis is where the magic happens - with just a few lines of code, we’ve defined a collaborative AI system where specialized agents work together in a coordinated process.\n\n\n​\nStep 6: Set Up Your Main Script\n\n\nNow, let’s set up the main script that will run our crew. This is where we provide the specific topic we want our crew to research.\n\n\nCopy\nAsk AI\n#!/usr/bin/env python\n\n\n# src/research_crew/main.py\n\n\nimport\n os\n\n\nfrom\n research_crew.crew \nimport\n ResearchCrew\n\n\n\n\n# Create output directory if it doesn't exist\n\n\nos.makedirs(\n'output'\n, \nexist_ok\n=\nTrue\n)\n\n\n\n\ndef\n run\n():\n\n\n \"\"\"\n\n\n Run the research crew.\n\n\n \"\"\"\n\n\n inputs \n=\n {\n\n\n 'topic'\n: \n'Artificial Intelligence in Healthcare'\n\n\n }\n\n\n\n\n # Create and run the crew\n\n\n result \n=\n ResearchCrew().crew().kickoff(\ninputs\n=\ninputs)\n\n\n\n\n # Print the result\n\n\n print\n(\n\"\n\\n\\n\n=== FINAL REPORT ===\n\\n\\n\n\"\n)\n\n\n print\n(result.raw)\n\n\n\n\n print\n(\n\"\n\\n\\n\nReport has been saved to output/report.md\"\n)\n\n\n\n\nif\n __name__\n ==\n \"__main__\"\n:\n\n\n run()\n\n\n\n\nThis script prepares the environment, specifies our research topic, and kicks off the crew’s work. The power of CrewAI is evident in how simple this code is - all the complexity of managing multiple AI agents is handled by the framework.\n\n\n​\nStep 7: Set Up Your Environment Variables\n\n\nCreate a \n.env\n file in your project root with your API keys:\n\n\nCopy\nAsk AI\nSERPER_API_KEY\n=\nyour_serper_api_key\n\n\n# Add your provider's API key here too.\n\n\n\n\nSee the \nLLM Setup guide\n for details on configuring your provider of choice. You can get a Serper API key from \nSerper.dev\n.\n\n\n​\nStep 8: Install Dependencies\n\n\nInstall the required dependencies using the CrewAI CLI:\n\n\nCopy\nAsk AI\ncrewai\n install\n\n\n\n\nThis command will:\n\n\n\n\nRead the dependencies from your project configuration\n\n\nCreate a virtual environment if needed\n\n\nInstall all required packages\n\n\n\n\n​\nStep 9: Run Your Crew\n\n\nNow for the exciting moment - it’s time to run your crew and see AI collaboration in action!\n\n\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\nWhen you run this command, you’ll see your crew spring to life. The researcher will gather information about the specified topic, and the analyst will then create a comprehensive report based on that research. You’ll see the agents’ thought processes, actions, and outputs in real-time as they work together to complete their tasks.\n\n\n​\nStep 10: Review the Output\n\n\nOnce the crew completes its work, you’ll find the final report in the \noutput/report.md\n file. The report will include:\n\n\n\n\nAn executive summary\n\n\nDetailed information about the topic\n\n\nAnalysis and insights\n\n\nRecommendations or future considerations\n\n\n\n\nTake a moment to appreciate what you’ve accomplished - you’ve created a system where multiple AI agents collaborated on a complex task, each contributing their specialized skills to produce a result that’s greater than what any single agent could achieve alone.\n\n\n​\nExploring Other CLI Commands\n\n\nCrewAI offers several other useful CLI commands for working with crews:\n\n\nCopy\nAsk AI\n# View all available commands\n\n\ncrewai\n --help\n\n\n\n\n# Run the crew\n\n\ncrewai\n run\n\n\n\n\n# Test the crew\n\n\ncrewai\n test\n\n\n\n\n# Reset crew memories\n\n\ncrewai\n reset-memories\n\n\n\n\n# Replay from a specific task\n\n\ncrewai\n replay\n -t\n <\ntask_i\nd\n>\n\n\n\n\n​\nThe Art of the Possible: Beyond Your First Crew\n\n\nWhat you’ve built in this guide is just the beginning. The skills and patterns you’ve learned can be applied to create increasingly sophisticated AI systems. Here are some ways you could extend this basic research crew:\n\n\n​\nExpanding Your Crew\n\n\nYou could add more specialized agents to your crew:\n\n\n\n\nA \nfact-checker\n to verify research findings\n\n\nA \ndata visualizer\n to create charts and graphs\n\n\nA \ndomain expert\n with specialized knowledge in a particular area\n\n\nA \ncritic\n to identify weaknesses in the analysis\n\n\n\n\n​\nAdding Tools and Capabilities\n\n\nYou could enhance your agents with additional tools:\n\n\n\n\nWeb browsing tools for real-time research\n\n\nCSV/database tools for data analysis\n\n\nCode execution tools for data processing\n\n\nAPI connections to external services\n\n\n\n\n​\nCreating More Complex Workflows\n\n\nYou could implement more sophisticated processes:\n\n\n\n\nHierarchical processes where manager agents delegate to worker agents\n\n\nIterative processes with feedback loops for refinement\n\n\nParallel processes where multiple agents work simultaneously\n\n\nDynamic processes that adapt based on intermediate results\n\n\n\n\n​\nApplying to Different Domains\n\n\nThe same patterns can be applied to create crews for:\n\n\n\n\nContent creation\n: Writers, editors, fact-checkers, and designers working together\n\n\nCustomer service\n: Triage agents, specialists, and quality control working together\n\n\nProduct development\n: Researchers, designers, and planners collaborating\n\n\nData analysis\n: Data collectors, analysts, and visualization specialists\n\n\n\n\n​\nNext Steps\n\n\nNow that you’ve built your first crew, you can:\n\n\n\n\nExperiment with different agent configurations and personalities\n\n\nTry more complex task structures and workflows\n\n\nImplement custom tools to give your agents new capabilities\n\n\nApply your crew to different topics or problem domains\n\n\nExplore \nCrewAI Flows\n for more advanced workflows with procedural programming\n\n\n\n\nCongratulations! You’ve successfully built your first CrewAI crew that can research and analyze any topic you provide. This foundational experience has equipped you with the skills to create increasingly sophisticated AI systems that can tackle complex, multi-stage problems through collaborative intelligence.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nCrafting Effective Agents\nBuild Your First Flow\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nUnleashing the Power of Collaborative AI\nWhat You’ll Build and Learn\nPrerequisites\nStep 1: Create a New CrewAI Project\nStep 2: Explore the Project Structure\nStep 3: Configure Your Agents\nStep 4: Define Your Tasks\nStep 5: Configure Your Crew\nStep 6: Set Up Your Main Script\nStep 7: Set Up Your Environment Variables\nStep 8: Install Dependencies\nStep 9: Run Your Crew\nStep 10: Review the Output\nExploring Other CLI Commands\nThe Art of the Possible: Beyond Your First Crew\nExpanding Your Crew\nAdding Tools and Capabilities\nCreating More Complex Workflows\nApplying to Different Domains\nNext Steps" }, { "source": "https://docs.crewai.com/en/api-reference/introduction", "title": "Introduction - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nGetting Started\nIntroduction\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGetting Started\nIntroduction\nEndpoints\nAPI Reference\nGetting Started\nIntroduction\nCopy page\nComplete reference for the CrewAI Enterprise REST API\n​\nCrewAI Enterprise API\n\n\nWelcome to the CrewAI Enterprise API reference. This API allows you to programmatically interact with your deployed crews, enabling integration with your applications, workflows, and services.\n\n\n​\nQuick Start\n\n\n1\nGet Your API Credentials\nNavigate to your crew’s detail page in the CrewAI Enterprise dashboard and copy your Bearer Token from the Status tab.\n2\nDiscover Required Inputs\nUse the \nGET /inputs\n endpoint to see what parameters your crew expects.\n3\nStart a Crew Execution\nCall \nPOST /kickoff\n with your inputs to start the crew execution and receive a \nkickoff_id\n.\n4\nMonitor Progress\nUse \nGET /status/{kickoff_id}\n to check execution status and retrieve results.\n\n\n​\nAuthentication\n\n\nAll API requests require authentication using a Bearer token. Include your token in the \nAuthorization\n header:\n\n\nCopy\nAsk AI\ncurl\n -H\n \"Authorization: Bearer YOUR_CREW_TOKEN\"\n \\\n\n\n https://your-crew-url.crewai.com/inputs\n\n\n\n\n​\nToken Types\n\n\nToken Type\nScope\nUse Case\nBearer Token\nOrganization-level access\nFull crew operations, ideal for server-to-server integration\nUser Bearer Token\nUser-scoped access\nLimited permissions, suitable for user-specific operations\n\n\nYou can find both token types in the Status tab of your crew’s detail page in the CrewAI Enterprise dashboard.\n\n\n​\nBase URL\n\n\nEach deployed crew has its own unique API endpoint:\n\n\nCopy\nAsk AI\nhttps://your-crew-name.crewai.com\n\n\n\n\nReplace \nyour-crew-name\n with your actual crew’s URL from the dashboard.\n\n\n​\nTypical Workflow\n\n\n\n\nDiscovery\n: Call \nGET /inputs\n to understand what your crew needs\n\n\nExecution\n: Submit inputs via \nPOST /kickoff\n to start processing\n\n\nMonitoring\n: Poll \nGET /status/{kickoff_id}\n until completion\n\n\nResults\n: Extract the final output from the completed response\n\n\n\n\n​\nError Handling\n\n\nThe API uses standard HTTP status codes:\n\n\nCode\nMeaning\n200\nSuccess\n400\nBad Request - Invalid input format\n401\nUnauthorized - Invalid bearer token\n404\nNot Found - Resource doesn’t exist\n422\nValidation Error - Missing required inputs\n500\nServer Error - Contact support\n\n\n​\nInteractive Testing\n\n\nWhy no “Send” button?\n Since each CrewAI Enterprise user has their own unique crew URL, we use \nreference mode\n instead of an interactive playground to avoid confusion. This shows you exactly what the requests should look like without non-functional send buttons.\n\n\nEach endpoint page shows you:\n\n\n\n\n✅ \nExact request format\n with all parameters\n\n\n✅ \nResponse examples\n for success and error cases\n\n\n✅ \nCode samples\n in multiple languages (cURL, Python, JavaScript, etc.)\n\n\n✅ \nAuthentication examples\n with proper Bearer token format\n\n\n\n\n​\nTo Test Your Actual API:\n\n\nCopy cURL Examples\nCopy the cURL examples and replace the URL + token with your real values\nUse Postman/Insomnia\nImport the examples into your preferred API testing tool\n\n\nExample workflow:\n\n\n\n\nCopy this cURL example\n from any endpoint page\n\n\nReplace \nyour-actual-crew-name.crewai.com\n with your real crew URL\n\n\nReplace the Bearer token\n with your real token from the dashboard\n\n\nRun the request\n in your terminal or API client\n\n\n\n\n​\nNeed Help?\n\n\nEnterprise Support\nGet help with API integration and troubleshooting\nEnterprise Dashboard\nManage your crews and view execution logs\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nGet Required Inputs\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nCrewAI Enterprise API\nQuick Start\nAuthentication\nToken Types\nBase URL\nTypical Workflow\nError Handling\nInteractive Testing\nTo Test Your Actual API:\nNeed Help?\nGetting Started\nIntroduction\nCopy page\nComplete reference for the CrewAI Enterprise REST API\n​\nCrewAI Enterprise API\n\n\nWelcome to the CrewAI Enterprise API reference. This API allows you to programmatically interact with your deployed crews, enabling integration with your applications, workflows, and services.\n\n\n​\nQuick Start\n\n\n1\nGet Your API Credentials\nNavigate to your crew’s detail page in the CrewAI Enterprise dashboard and copy your Bearer Token from the Status tab.\n2\nDiscover Required Inputs\nUse the \nGET /inputs\n endpoint to see what parameters your crew expects.\n3\nStart a Crew Execution\nCall \nPOST /kickoff\n with your inputs to start the crew execution and receive a \nkickoff_id\n.\n4\nMonitor Progress\nUse \nGET /status/{kickoff_id}\n to check execution status and retrieve results.\n\n\n​\nAuthentication\n\n\nAll API requests require authentication using a Bearer token. Include your token in the \nAuthorization\n header:\n\n\nCopy\nAsk AI\ncurl\n -H\n \"Authorization: Bearer YOUR_CREW_TOKEN\"\n \\\n\n\n https://your-crew-url.crewai.com/inputs\n\n\n\n\n​\nToken Types\n\n\nToken Type\nScope\nUse Case\nBearer Token\nOrganization-level access\nFull crew operations, ideal for server-to-server integration\nUser Bearer Token\nUser-scoped access\nLimited permissions, suitable for user-specific operations\n\n\nYou can find both token types in the Status tab of your crew’s detail page in the CrewAI Enterprise dashboard.\n\n\n​\nBase URL\n\n\nEach deployed crew has its own unique API endpoint:\n\n\nCopy\nAsk AI\nhttps://your-crew-name.crewai.com\n\n\n\n\nReplace \nyour-crew-name\n with your actual crew’s URL from the dashboard.\n\n\n​\nTypical Workflow\n\n\n\n\nDiscovery\n: Call \nGET /inputs\n to understand what your crew needs\n\n\nExecution\n: Submit inputs via \nPOST /kickoff\n to start processing\n\n\nMonitoring\n: Poll \nGET /status/{kickoff_id}\n until completion\n\n\nResults\n: Extract the final output from the completed response\n\n\n\n\n​\nError Handling\n\n\nThe API uses standard HTTP status codes:\n\n\nCode\nMeaning\n200\nSuccess\n400\nBad Request - Invalid input format\n401\nUnauthorized - Invalid bearer token\n404\nNot Found - Resource doesn’t exist\n422\nValidation Error - Missing required inputs\n500\nServer Error - Contact support\n\n\n​\nInteractive Testing\n\n\nWhy no “Send” button?\n Since each CrewAI Enterprise user has their own unique crew URL, we use \nreference mode\n instead of an interactive playground to avoid confusion. This shows you exactly what the requests should look like without non-functional send buttons.\n\n\nEach endpoint page shows you:\n\n\n\n\n✅ \nExact request format\n with all parameters\n\n\n✅ \nResponse examples\n for success and error cases\n\n\n✅ \nCode samples\n in multiple languages (cURL, Python, JavaScript, etc.)\n\n\n✅ \nAuthentication examples\n with proper Bearer token format\n\n\n\n\n​\nTo Test Your Actual API:\n\n\nCopy cURL Examples\nCopy the cURL examples and replace the URL + token with your real values\nUse Postman/Insomnia\nImport the examples into your preferred API testing tool\n\n\nExample workflow:\n\n\n\n\nCopy this cURL example\n from any endpoint page\n\n\nReplace \nyour-actual-crew-name.crewai.com\n with your real crew URL\n\n\nReplace the Bearer token\n with your real token from the dashboard\n\n\nRun the request\n in your terminal or API client\n\n\n\n\n​\nNeed Help?\n\n\nEnterprise Support\nGet help with API integration and troubleshooting\nEnterprise Dashboard\nManage your crews and view execution logs\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nGet Required Inputs\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nCrewAI Enterprise API\nQuick Start\nAuthentication\nToken Types\nBase URL\nTypical Workflow\nError Handling\nInteractive Testing\nTo Test Your Actual API:\nNeed Help?" }, { "source": "https://docs.crewai.com/en/observability/langtrace", "title": "Langtrace Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nLangtrace Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nLangtrace Integration\nCopy page\nHow to monitor cost, latency, and performance of CrewAI Agents using Langtrace, an external observability tool.\n​\nLangtrace Overview\n\n\nLangtrace is an open-source, external tool that helps you set up observability and evaluations for Large Language Models (LLMs), LLM frameworks, and Vector Databases.\nWhile not built directly into CrewAI, Langtrace can be used alongside CrewAI to gain deep visibility into the cost, latency, and performance of your CrewAI Agents.\nThis integration allows you to log hyperparameters, monitor performance regressions, and establish a process for continuous improvement of your Agents.\n\n\n\n\n\n\n\n\n​\nSetup Instructions\n\n\n1\nSign up for Langtrace\nSign up by visiting \nhttps://langtrace.ai/signup\n.\n2\nCreate a project\nSet the project type to \nCrewAI\n and generate an API key.\n3\nInstall Langtrace in your CrewAI project\nUse the following command:\nCopy\nAsk AI\npip\n install\n langtrace-python-sdk\n\n\n4\nImport Langtrace\nImport and initialize Langtrace at the beginning of your script, before any CrewAI imports:\nCopy\nAsk AI\nfrom\n langtrace_python_sdk \nimport\n langtrace\n\n\nlangtrace.init(\napi_key\n=\n''\n)\n\n\n\n\n# Now import CrewAI modules\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n​\nFeatures and Their Application to CrewAI\n\n\n\n\n\n\nLLM Token and Cost Tracking\n\n\n\n\nMonitor the token usage and associated costs for each CrewAI agent interaction.\n\n\n\n\n\n\n\n\nTrace Graph for Execution Steps\n\n\n\n\nVisualize the execution flow of your CrewAI tasks, including latency and logs.\n\n\nUseful for identifying bottlenecks in your agent workflows.\n\n\n\n\n\n\n\n\nDataset Curation with Manual Annotation\n\n\n\n\nCreate datasets from your CrewAI task outputs for future training or evaluation.\n\n\n\n\n\n\n\n\nPrompt Versioning and Management\n\n\n\n\nKeep track of different versions of prompts used in your CrewAI agents.\n\n\nUseful for A/B testing and optimizing agent performance.\n\n\n\n\n\n\n\n\nPrompt Playground with Model Comparisons\n\n\n\n\nTest and compare different prompts and models for your CrewAI agents before deployment.\n\n\n\n\n\n\n\n\nTesting and Evaluations\n\n\n\n\nSet up automated tests for your CrewAI agents and tasks.\n\n\n\n\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nLangfuse Integration\nMaxim Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nLangtrace Overview\nSetup Instructions\nFeatures and Their Application to CrewAI\nObservability\nLangtrace Integration\nCopy page\nHow to monitor cost, latency, and performance of CrewAI Agents using Langtrace, an external observability tool.\n​\nLangtrace Overview\n\n\nLangtrace is an open-source, external tool that helps you set up observability and evaluations for Large Language Models (LLMs), LLM frameworks, and Vector Databases.\nWhile not built directly into CrewAI, Langtrace can be used alongside CrewAI to gain deep visibility into the cost, latency, and performance of your CrewAI Agents.\nThis integration allows you to log hyperparameters, monitor performance regressions, and establish a process for continuous improvement of your Agents.\n\n\n\n\n\n\n\n\n​\nSetup Instructions\n\n\n1\nSign up for Langtrace\nSign up by visiting \nhttps://langtrace.ai/signup\n.\n2\nCreate a project\nSet the project type to \nCrewAI\n and generate an API key.\n3\nInstall Langtrace in your CrewAI project\nUse the following command:\nCopy\nAsk AI\npip\n install\n langtrace-python-sdk\n\n\n4\nImport Langtrace\nImport and initialize Langtrace at the beginning of your script, before any CrewAI imports:\nCopy\nAsk AI\nfrom\n langtrace_python_sdk \nimport\n langtrace\n\n\nlangtrace.init(\napi_key\n=\n''\n)\n\n\n\n\n# Now import CrewAI modules\n\n\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\n\n\n​\nFeatures and Their Application to CrewAI\n\n\n\n\n\n\nLLM Token and Cost Tracking\n\n\n\n\nMonitor the token usage and associated costs for each CrewAI agent interaction.\n\n\n\n\n\n\n\n\nTrace Graph for Execution Steps\n\n\n\n\nVisualize the execution flow of your CrewAI tasks, including latency and logs.\n\n\nUseful for identifying bottlenecks in your agent workflows.\n\n\n\n\n\n\n\n\nDataset Curation with Manual Annotation\n\n\n\n\nCreate datasets from your CrewAI task outputs for future training or evaluation.\n\n\n\n\n\n\n\n\nPrompt Versioning and Management\n\n\n\n\nKeep track of different versions of prompts used in your CrewAI agents.\n\n\nUseful for A/B testing and optimizing agent performance.\n\n\n\n\n\n\n\n\nPrompt Playground with Model Comparisons\n\n\n\n\nTest and compare different prompts and models for your CrewAI agents before deployment.\n\n\n\n\n\n\n\n\nTesting and Evaluations\n\n\n\n\nSet up automated tests for your CrewAI agents and tasks.\n\n\n\n\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nLangfuse Integration\nMaxim Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nLangtrace Overview\nSetup Instructions\nFeatures and Their Application to CrewAI" }, { "source": "https://docs.crewai.com/en/observability/maxim", "title": "Maxim Integration - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nObservability\nMaxim Integration\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nObservability\nMaxim Integration\nCopy page\nStart Agent monitoring, evaluation, and observability\n​\nMaxim Overview\n\n\nMaxim AI provides comprehensive agent monitoring, evaluation, and observability for your CrewAI applications. With Maxim’s one-line integration, you can easily trace and analyse agent interactions, performance metrics, and more.\n\n\n​\nFeatures\n\n\n​\nPrompt Management\n\n\nMaxim’s Prompt Management capabilities enable you to create, organize, and optimize prompts for your CrewAI agents. Rather than hardcoding instructions, leverage Maxim’s SDK to dynamically retrieve and apply version-controlled prompts.\n\n\nPrompt Playground\nPrompt Versions\nPrompt Comparisons\nCreate, refine, experiment and deploy your prompts via the playground. Organize of your prompts using folders and versions, experimenting with the real world cases by linking tools and context, and deploying based on custom logic.\nEasily experiment across models by \nconfiguring models\n and selecting the relevant model from the dropdown at the top of the prompt playground.\nCreate, refine, experiment and deploy your prompts via the playground. Organize of your prompts using folders and versions, experimenting with the real world cases by linking tools and context, and deploying based on custom logic.\nEasily experiment across models by \nconfiguring models\n and selecting the relevant model from the dropdown at the top of the prompt playground.\nAs teams build their AI applications, a big part of experimentation is iterating on the prompt structure. In order to collaborate effectively and organize your changes clearly, Maxim allows prompt versioning and comparison runs across versions.\nIterating on Prompts as you evolve your AI application would need experiments across models, prompt structures, etc. In order to compare versions and make informed decisions about changes, the comparison playground allows a side by side view of results.\n​\nWhy use Prompt comparison?\nPrompt comparison combines multiple single Prompts into one view, enabling a streamlined approach for various workflows:\n\n\nModel comparison\n: Evaluate the performance of different models on the same Prompt.\n\n\nPrompt optimization\n: Compare different versions of a Prompt to identify the most effective formulation.\n\n\nCross-Model consistency\n: Ensure consistent outputs across various models for the same Prompt.\n\n\nPerformance benchmarking\n: Analyze metrics like latency, cost, and token count across different models and Prompts.\n\n\n\n\n​\nObservability & Evals\n\n\nMaxim AI provides comprehensive observability & evaluation for your CrewAI agents, helping you understand exactly what’s happening during each execution.\n\n\nAgent Tracing\nAnalytics + Evals\nAlerting\nDashboards\nTrack your agent’s complete lifecycle, including tool calls, agent trajectories, and decision flows effortlessly.\nTrack your agent’s complete lifecycle, including tool calls, agent trajectories, and decision flows effortlessly.\nRun detailed evaluations on full traces or individual nodes with support for:\n\n\nMulti-step interactions and granular trace analysis\n\n\nSession Level Evaluations\n\n\nSimulations for real-world testing\n\n\nAuto Evals on Logs\nEvaluate captured logs automatically from the UI based on filters and sampling\nHuman Evals on Logs\nUse human evaluation or rating to assess the quality of your logs and evaluate them.\nNode Level Evals\nEvaluate any component of your trace or log to gain insights into your agent’s behavior.\nSet thresholds on \nerror\n, \ncost, token usage, user feedback, latency\n and get real-time alerts via Slack or PagerDuty.\nVisualize Traces over time, usage metrics, latency & error rates with ease.\n\n\n​\nGetting Started\n\n\n​\nPrerequisites\n\n\n\n\nPython version >=3.10\n\n\nA Maxim account (\nsign up here\n)\n\n\nGenerate Maxim API Key\n\n\nA CrewAI project\n\n\n\n\n​\nInstallation\n\n\nInstall the Maxim SDK via pip:\n\n\nCopy\nAsk AI\npip install maxim\n-\npy\n\n\n\n\nOr add it to your \nrequirements.txt\n:\n\n\nCopy\nAsk AI\nmaxim-py\n\n\n\n\n​\nBasic Setup\n\n\n​\n1. Set up environment variables\n\n\nCopy\nAsk AI\n### Environment Variables Setup\n\n\n\n\n# Create a `.env` file in your project root:\n\n\n\n\n# Maxim API Configuration\n\n\nMAXIM_API_KEY\n=\nyour_api_key_here\n\n\nMAXIM_LOG_REPO_ID\n=\nyour_repo_id_here\n\n\n\n\n​\n2. Import the required packages\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n maxim \nimport\n Maxim\n\n\nfrom\n maxim.logger.crewai \nimport\n instrument_crewai\n\n\n\n\n​\n3. Initialise Maxim with your API key\n\n\nCopy\nAsk AI\n# Instrument CrewAI with just one line\n\n\ninstrument_crewai(Maxim().logger())\n\n\n\n\n​\n4. Create and run your CrewAI application as usual\n\n\nCopy\nAsk AI\n# Create your agent\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Senior Research Analyst'\n,\n\n\n goal\n=\n'Uncover cutting-edge developments in AI'\n,\n\n\n backstory\n=\n\"You are an expert researcher at a tech think tank...\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\n\n\n# Define the task\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n\"Research the latest AI advancements...\"\n,\n\n\n expected_output\n=\n\"\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\n# Configure and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher],\n\n\n tasks\n=\n[research_task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ntry\n:\n\n\n result \n=\n crew.kickoff()\n\n\nfinally\n:\n\n\n maxim.cleanup() \n# Ensure cleanup happens even if errors occur\n\n\n\n\nThat’s it! All your CrewAI agent interactions will now be logged and available in your Maxim dashboard.\n\n\nCheck this Google Colab Notebook for a quick reference - \nNotebook\n\n\n​\nViewing Your Traces\n\n\nAfter running your CrewAI application:\n\n\n\n\n\n\nLog in to your \nMaxim Dashboard\n\n\n\n\n\n\nNavigate to your repository\n\n\n\n\n\n\nView detailed agent traces, including:\n\n\n\n\nAgent conversations\n\n\nTool usage patterns\n\n\nPerformance metrics\n\n\nCost analytics\n\n\n\n\n\n\n\n\n\n\n​\nTroubleshooting\n\n\n​\nCommon Issues\n\n\n\n\n\n\nNo traces appearing\n: Ensure your API key and repository ID are correct\n\n\n\n\n\n\nEnsure you’ve \ncalled instrument_crewai()\n \nbefore\n running your crew. This initializes logging hooks correctly.\n\n\n\n\n\n\nSet \ndebug=True\n in your \ninstrument_crewai()\n call to surface any internal errors:\n\n\nCopy\nAsk AI\ninstrument_crewai(logger, \ndebug\n=\nTrue\n)\n\n\n\n\n\n\n\n\nConfigure your agents with \nverbose=True\n to capture detailed logs:\n\n\nCopy\nAsk AI\nagent \n=\n CrewAgent(\n...\n, \nverbose\n=\nTrue\n)\n\n\n\n\n\n\n\n\nDouble-check that \ninstrument_crewai()\n is called \nbefore\n creating or executing agents. This might be obvious, but it’s a common oversight.\n\n\n\n\n\n\n​\nResources\n\n\nCrewAI Docs\nOfficial CrewAI documentation\nMaxim Docs\nOfficial Maxim documentation\nMaxim Github\nMaxim Github\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nLangtrace Integration\nMLflow Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nMaxim Overview\nFeatures\nPrompt Management\nObservability & Evals\nGetting Started\nPrerequisites\nInstallation\nBasic Setup\n1. Set up environment variables\n2. Import the required packages\n3. Initialise Maxim with your API key\n4. Create and run your CrewAI application as usual\nViewing Your Traces\nTroubleshooting\nCommon Issues\nResources\nObservability\nMaxim Integration\nCopy page\nStart Agent monitoring, evaluation, and observability\n​\nMaxim Overview\n\n\nMaxim AI provides comprehensive agent monitoring, evaluation, and observability for your CrewAI applications. With Maxim’s one-line integration, you can easily trace and analyse agent interactions, performance metrics, and more.\n\n\n​\nFeatures\n\n\n​\nPrompt Management\n\n\nMaxim’s Prompt Management capabilities enable you to create, organize, and optimize prompts for your CrewAI agents. Rather than hardcoding instructions, leverage Maxim’s SDK to dynamically retrieve and apply version-controlled prompts.\n\n\nPrompt Playground\nPrompt Versions\nPrompt Comparisons\nCreate, refine, experiment and deploy your prompts via the playground. Organize of your prompts using folders and versions, experimenting with the real world cases by linking tools and context, and deploying based on custom logic.\nEasily experiment across models by \nconfiguring models\n and selecting the relevant model from the dropdown at the top of the prompt playground.\nCreate, refine, experiment and deploy your prompts via the playground. Organize of your prompts using folders and versions, experimenting with the real world cases by linking tools and context, and deploying based on custom logic.\nEasily experiment across models by \nconfiguring models\n and selecting the relevant model from the dropdown at the top of the prompt playground.\nAs teams build their AI applications, a big part of experimentation is iterating on the prompt structure. In order to collaborate effectively and organize your changes clearly, Maxim allows prompt versioning and comparison runs across versions.\nIterating on Prompts as you evolve your AI application would need experiments across models, prompt structures, etc. In order to compare versions and make informed decisions about changes, the comparison playground allows a side by side view of results.\n​\nWhy use Prompt comparison?\nPrompt comparison combines multiple single Prompts into one view, enabling a streamlined approach for various workflows:\n\n\nModel comparison\n: Evaluate the performance of different models on the same Prompt.\n\n\nPrompt optimization\n: Compare different versions of a Prompt to identify the most effective formulation.\n\n\nCross-Model consistency\n: Ensure consistent outputs across various models for the same Prompt.\n\n\nPerformance benchmarking\n: Analyze metrics like latency, cost, and token count across different models and Prompts.\n\n\n\n\n​\nObservability & Evals\n\n\nMaxim AI provides comprehensive observability & evaluation for your CrewAI agents, helping you understand exactly what’s happening during each execution.\n\n\nAgent Tracing\nAnalytics + Evals\nAlerting\nDashboards\nTrack your agent’s complete lifecycle, including tool calls, agent trajectories, and decision flows effortlessly.\nTrack your agent’s complete lifecycle, including tool calls, agent trajectories, and decision flows effortlessly.\nRun detailed evaluations on full traces or individual nodes with support for:\n\n\nMulti-step interactions and granular trace analysis\n\n\nSession Level Evaluations\n\n\nSimulations for real-world testing\n\n\nAuto Evals on Logs\nEvaluate captured logs automatically from the UI based on filters and sampling\nHuman Evals on Logs\nUse human evaluation or rating to assess the quality of your logs and evaluate them.\nNode Level Evals\nEvaluate any component of your trace or log to gain insights into your agent’s behavior.\nSet thresholds on \nerror\n, \ncost, token usage, user feedback, latency\n and get real-time alerts via Slack or PagerDuty.\nVisualize Traces over time, usage metrics, latency & error rates with ease.\n\n\n​\nGetting Started\n\n\n​\nPrerequisites\n\n\n\n\nPython version >=3.10\n\n\nA Maxim account (\nsign up here\n)\n\n\nGenerate Maxim API Key\n\n\nA CrewAI project\n\n\n\n\n​\nInstallation\n\n\nInstall the Maxim SDK via pip:\n\n\nCopy\nAsk AI\npip install maxim\n-\npy\n\n\n\n\nOr add it to your \nrequirements.txt\n:\n\n\nCopy\nAsk AI\nmaxim-py\n\n\n\n\n​\nBasic Setup\n\n\n​\n1. Set up environment variables\n\n\nCopy\nAsk AI\n### Environment Variables Setup\n\n\n\n\n# Create a `.env` file in your project root:\n\n\n\n\n# Maxim API Configuration\n\n\nMAXIM_API_KEY\n=\nyour_api_key_here\n\n\nMAXIM_LOG_REPO_ID\n=\nyour_repo_id_here\n\n\n\n\n​\n2. Import the required packages\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process\n\n\nfrom\n maxim \nimport\n Maxim\n\n\nfrom\n maxim.logger.crewai \nimport\n instrument_crewai\n\n\n\n\n​\n3. Initialise Maxim with your API key\n\n\nCopy\nAsk AI\n# Instrument CrewAI with just one line\n\n\ninstrument_crewai(Maxim().logger())\n\n\n\n\n​\n4. Create and run your CrewAI application as usual\n\n\nCopy\nAsk AI\n# Create your agent\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Senior Research Analyst'\n,\n\n\n goal\n=\n'Uncover cutting-edge developments in AI'\n,\n\n\n backstory\n=\n\"You are an expert researcher at a tech think tank...\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n llm\n=\nllm\n\n\n)\n\n\n\n\n# Define the task\n\n\nresearch_task \n=\n Task(\n\n\n description\n=\n\"Research the latest AI advancements...\"\n,\n\n\n expected_output\n=\n\"\"\n,\n\n\n agent\n=\nresearcher\n\n\n)\n\n\n\n\n# Configure and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[researcher],\n\n\n tasks\n=\n[research_task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ntry\n:\n\n\n result \n=\n crew.kickoff()\n\n\nfinally\n:\n\n\n maxim.cleanup() \n# Ensure cleanup happens even if errors occur\n\n\n\n\nThat’s it! All your CrewAI agent interactions will now be logged and available in your Maxim dashboard.\n\n\nCheck this Google Colab Notebook for a quick reference - \nNotebook\n\n\n​\nViewing Your Traces\n\n\nAfter running your CrewAI application:\n\n\n\n\n\n\nLog in to your \nMaxim Dashboard\n\n\n\n\n\n\nNavigate to your repository\n\n\n\n\n\n\nView detailed agent traces, including:\n\n\n\n\nAgent conversations\n\n\nTool usage patterns\n\n\nPerformance metrics\n\n\nCost analytics\n\n\n\n\n\n\n\n\n\n\n​\nTroubleshooting\n\n\n​\nCommon Issues\n\n\n\n\n\n\nNo traces appearing\n: Ensure your API key and repository ID are correct\n\n\n\n\n\n\nEnsure you’ve \ncalled instrument_crewai()\n \nbefore\n running your crew. This initializes logging hooks correctly.\n\n\n\n\n\n\nSet \ndebug=True\n in your \ninstrument_crewai()\n call to surface any internal errors:\n\n\nCopy\nAsk AI\ninstrument_crewai(logger, \ndebug\n=\nTrue\n)\n\n\n\n\n\n\n\n\nConfigure your agents with \nverbose=True\n to capture detailed logs:\n\n\nCopy\nAsk AI\nagent \n=\n CrewAgent(\n...\n, \nverbose\n=\nTrue\n)\n\n\n\n\n\n\n\n\nDouble-check that \ninstrument_crewai()\n is called \nbefore\n creating or executing agents. This might be obvious, but it’s a common oversight.\n\n\n\n\n\n\n​\nResources\n\n\nCrewAI Docs\nOfficial CrewAI documentation\nMaxim Docs\nOfficial Maxim documentation\nMaxim Github\nMaxim Github\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nLangtrace Integration\nMLflow Integration\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nMaxim Overview\nFeatures\nPrompt Management\nObservability & Evals\nGetting Started\nPrerequisites\nInstallation\nBasic Setup\n1. Set up environment variables\n2. Import the required packages\n3. Initialise Maxim with your API key\n4. Create and run your CrewAI application as usual\nViewing Your Traces\nTroubleshooting\nCommon Issues\nResources" }, { "source": "https://docs.crewai.com/en/concepts/crews", "title": "Crews - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nCrews\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nCrews\nCopy page\nUnderstanding and utilizing crews in the crewAI framework with comprehensive attributes and functionalities.\n​\nOverview\n\n\nA crew in crewAI represents a collaborative group of agents working together to achieve a set of tasks. Each crew defines the strategy for task execution, agent collaboration, and the overall workflow.\n\n\n​\nCrew Attributes\n\n\nAttribute\nParameters\nDescription\nTasks\ntasks\nA list of tasks assigned to the crew.\nAgents\nagents\nA list of agents that are part of the crew.\nProcess\n \n(optional)\nprocess\nThe process flow (e.g., sequential, hierarchical) the crew follows. Default is \nsequential\n.\nVerbose\n \n(optional)\nverbose\nThe verbosity level for logging during execution. Defaults to \nFalse\n.\nManager LLM\n \n(optional)\nmanager_llm\nThe language model used by the manager agent in a hierarchical process. \nRequired when using a hierarchical process.\nFunction Calling LLM\n \n(optional)\nfunction_calling_llm\nIf passed, the crew will use this LLM to do function calling for tools for all agents in the crew. Each agent can have its own LLM, which overrides the crew’s LLM for function calling.\nConfig\n \n(optional)\nconfig\nOptional configuration settings for the crew, in \nJson\n or \nDict[str, Any]\n format.\nMax RPM\n \n(optional)\nmax_rpm\nMaximum requests per minute the crew adheres to during execution. Defaults to \nNone\n.\nMemory\n \n(optional)\nmemory\nUtilized for storing execution memories (short-term, long-term, entity memory).\nMemory Config\n \n(optional)\nmemory_config\nConfiguration for the memory provider to be used by the crew.\nCache\n \n(optional)\ncache\nSpecifies whether to use a cache for storing the results of tools’ execution. Defaults to \nTrue\n.\nEmbedder\n \n(optional)\nembedder\nConfiguration for the embedder to be used by the crew. Mostly used by memory for now. Default is \n{\"provider\": \"openai\"}\n.\nStep Callback\n \n(optional)\nstep_callback\nA function that is called after each step of every agent. This can be used to log the agent’s actions or to perform other operations; it won’t override the agent-specific \nstep_callback\n.\nTask Callback\n \n(optional)\ntask_callback\nA function that is called after the completion of each task. Useful for monitoring or additional operations post-task execution.\nShare Crew\n \n(optional)\nshare_crew\nWhether you want to share the complete crew information and execution with the crewAI team to make the library better, and allow us to train models.\nOutput Log File\n \n(optional)\noutput_log_file\nSet to True to save logs as logs.txt in the current directory or provide a file path. Logs will be in JSON format if the filename ends in .json, otherwise .txt. Defaults to \nNone\n.\nManager Agent\n \n(optional)\nmanager_agent\nmanager\n sets a custom agent that will be used as a manager.\nPrompt File\n \n(optional)\nprompt_file\nPath to the prompt JSON file to be used for the crew.\nPlanning\n \n(optional)\nplanning\nAdds planning ability to the Crew. When activated before each Crew iteration, all Crew data is sent to an AgentPlanner that will plan the tasks and this plan will be added to each task description.\nPlanning LLM\n \n(optional)\nplanning_llm\nThe language model used by the AgentPlanner in a planning process.\n\n\nCrew Max RPM\n: The \nmax_rpm\n attribute sets the maximum number of requests per minute the crew can perform to avoid rate limits and will override individual agents’ \nmax_rpm\n settings if you set it.\n\n\n​\nCreating Crews\n\n\nThere are two ways to create crews in CrewAI: using \nYAML configuration (recommended)\n or defining them \ndirectly in code\n.\n\n\n​\nYAML Configuration (Recommended)\n\n\nUsing YAML configuration provides a cleaner, more maintainable way to define crews and is consistent with how agents and tasks are defined in CrewAI projects.\n\n\nAfter creating your CrewAI project as outlined in the \nInstallation\n section, you can define your crew in a class that inherits from \nCrewBase\n and uses decorators to define agents, tasks, and the crew itself.\n\n\n​\nExample Crew Class with Decorators\n\n\ncode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, task, crew, before_kickoff, after_kickoff\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n YourCrewName\n:\n\n\n \"\"\"Description of your crew\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n # Paths to your YAML configuration files\n\n\n # To see an example agent and task defined in YAML, checkout the following:\n\n\n # - Task: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommended\n\n\n # - Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended\n\n\n agents_config \n=\n 'config/agents.yaml'\n\n\n tasks_config \n=\n 'config/tasks.yaml'\n\n\n\n\n @before_kickoff\n\n\n def\n prepare_inputs\n(\nself\n, \ninputs\n):\n\n\n # Modify inputs before the crew starts\n\n\n inputs[\n'additional_data'\n] \n=\n \"Some extra information\"\n\n\n return\n inputs\n\n\n\n\n @after_kickoff\n\n\n def\n process_output\n(\nself\n, \noutput\n):\n\n\n # Modify output after the crew finishes\n\n\n output.raw \n+=\n \"\n\\n\nProcessed after kickoff.\"\n\n\n return\n output\n\n\n\n\n @agent\n\n\n def\n agent_one\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'agent_one'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @agent\n\n\n def\n agent_two\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'agent_two'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n task_one\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'task_one'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n task_two\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'task_two'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents, \n# Automatically collected by the @agent decorator\n\n\n tasks\n=\nself\n.tasks, \n# Automatically collected by the @task decorator.\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nHow to run the above code:\n\n\ncode\nCopy\nAsk AI\nYourCrewName().crew().kickoff(\ninputs\n=\n{\n\"any\"\n: \n\"input here\"\n})\n\n\n\n\nTasks will be executed in the order they are defined.\n\n\nThe \nCrewBase\n class, along with these decorators, automates the collection of agents and tasks, reducing the need for manual management.\n\n\n​\nDecorators overview from \nannotations.py\n\n\nCrewAI provides several decorators in the \nannotations.py\n file that are used to mark methods within your crew class for special handling:\n\n\n\n\n@CrewBase\n: Marks the class as a crew base class.\n\n\n@agent\n: Denotes a method that returns an \nAgent\n object.\n\n\n@task\n: Denotes a method that returns a \nTask\n object.\n\n\n@crew\n: Denotes the method that returns the \nCrew\n object.\n\n\n@before_kickoff\n: (Optional) Marks a method to be executed before the crew starts.\n\n\n@after_kickoff\n: (Optional) Marks a method to be executed after the crew finishes.\n\n\n\n\nThese decorators help in organizing your crew’s structure and automatically collecting agents and tasks without manually listing them.\n\n\n​\nDirect Code Definition (Alternative)\n\n\nAlternatively, you can define the crew directly in code without using YAML configuration files.\n\n\ncode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\nfrom\n crewai_tools \nimport\n YourCustomTool\n\n\n\n\nclass\n YourCrewName\n:\n\n\n def\n agent_one\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data trends in the market\"\n,\n\n\n backstory\n=\n\"An experienced data analyst with a background in economics\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[YourCustomTool()]\n\n\n )\n\n\n\n\n def\n agent_two\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Market Researcher\"\n,\n\n\n goal\n=\n\"Gather information on market dynamics\"\n,\n\n\n backstory\n=\n\"A diligent researcher with a keen eye for detail\"\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n def\n task_one\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n description\n=\n\"Collect recent market data and identify trends.\"\n,\n\n\n expected_output\n=\n\"A report summarizing key trends in the market.\"\n,\n\n\n agent\n=\nself\n.agent_one()\n\n\n )\n\n\n\n\n def\n task_two\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n description\n=\n\"Research factors affecting market dynamics.\"\n,\n\n\n expected_output\n=\n\"An analysis of factors influencing the market.\"\n,\n\n\n agent\n=\nself\n.agent_two()\n\n\n )\n\n\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\n[\nself\n.agent_one(), \nself\n.agent_two()],\n\n\n tasks\n=\n[\nself\n.task_one(), \nself\n.task_two()],\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\nHow to run the above code:\n\n\ncode\nCopy\nAsk AI\nYourCrewName().crew().kickoff(\ninputs\n=\n{})\n\n\n\n\nIn this example:\n\n\n\n\nAgents and tasks are defined directly within the class without decorators.\n\n\nWe manually create and manage the list of agents and tasks.\n\n\nThis approach provides more control but can be less maintainable for larger projects.\n\n\n\n\n​\nCrew Output\n\n\nThe output of a crew in the CrewAI framework is encapsulated within the \nCrewOutput\n class.\nThis class provides a structured way to access results of the crew’s execution, including various formats such as raw strings, JSON, and Pydantic models.\nThe \nCrewOutput\n includes the results from the final task output, token usage, and individual task outputs.\n\n\n​\nCrew Output Attributes\n\n\nAttribute\nParameters\nType\nDescription\nRaw\nraw\nstr\nThe raw output of the crew. This is the default format for the output.\nPydantic\npydantic\nOptional[BaseModel]\nA Pydantic model object representing the structured output of the crew.\nJSON Dict\njson_dict\nOptional[Dict[str, Any]]\nA dictionary representing the JSON output of the crew.\nTasks Output\ntasks_output\nList[TaskOutput]\nA list of \nTaskOutput\n objects, each representing the output of a task in the crew.\nToken Usage\ntoken_usage\nDict[str, Any]\nA summary of token usage, providing insights into the language model’s performance during execution.\n\n\n​\nCrew Output Methods and Properties\n\n\nMethod/Property\nDescription\njson\nReturns the JSON string representation of the crew output if the output format is JSON.\nto_dict\nConverts the JSON and Pydantic outputs to a dictionary.\n*\n*str**\nReturns the string representation of the crew output, prioritizing Pydantic, then JSON, then raw.\n\n\n​\nAccessing Crew Outputs\n\n\nOnce a crew has been executed, its output can be accessed through the \noutput\n attribute of the \nCrew\n object. The \nCrewOutput\n class provides various ways to interact with and present this output.\n\n\n​\nExample\n\n\nCode\nCopy\nAsk AI\n# Example crew execution\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent, writer_agent],\n\n\n tasks\n=\n[research_task, write_article_task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ncrew_output \n=\n crew.kickoff()\n\n\n\n\n# Accessing the crew output\n\n\nprint\n(\nf\n\"Raw Output: \n{\ncrew_output.raw\n}\n\"\n)\n\n\nif\n crew_output.json_dict:\n\n\n print\n(\nf\n\"JSON Output: \n{\njson.dumps(crew_output.json_dict, \nindent\n=\n2\n)\n}\n\"\n)\n\n\nif\n crew_output.pydantic:\n\n\n print\n(\nf\n\"Pydantic Output: \n{\ncrew_output.pydantic\n}\n\"\n)\n\n\nprint\n(\nf\n\"Tasks Output: \n{\ncrew_output.tasks_output\n}\n\"\n)\n\n\nprint\n(\nf\n\"Token Usage: \n{\ncrew_output.token_usage\n}\n\"\n)\n\n\n\n\n​\nAccessing Crew Logs\n\n\nYou can see real time log of the crew execution, by setting \noutput_log_file\n as a \nTrue(Boolean)\n or a \nfile_name(str)\n. Supports logging of events as both \nfile_name.txt\n and \nfile_name.json\n.\nIn case of \nTrue(Boolean)\n will save as \nlogs.txt\n.\n\n\nIn case of \noutput_log_file\n is set as \nFalse(Boolean)\n or \nNone\n, the logs will not be populated.\n\n\nCode\nCopy\nAsk AI\n# Save crew logs\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n True\n) \n# Logs will be saved as logs.txt\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n file_name) \n# Logs will be saved as file_name.txt\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n file_name.txt) \n# Logs will be saved as file_name.txt\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n file_name.json) \n# Logs will be saved as file_name.json\n\n\n\n\n​\nMemory Utilization\n\n\nCrews can utilize memory (short-term, long-term, and entity memory) to enhance their execution and learning over time. This feature allows crews to store and recall execution memories, aiding in decision-making and task execution strategies.\n\n\n​\nCache Utilization\n\n\nCaches can be employed to store the results of tools’ execution, making the process more efficient by reducing the need to re-execute identical tasks.\n\n\n​\nCrew Usage Metrics\n\n\nAfter the crew execution, you can access the \nusage_metrics\n attribute to view the language model (LLM) usage metrics for all tasks executed by the crew. This provides insights into operational efficiency and areas for improvement.\n\n\nCode\nCopy\nAsk AI\n# Access the crew's usage metrics\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent1, agent2], \ntasks\n=\n[task1, task2])\n\n\ncrew.kickoff()\n\n\nprint\n(crew.usage_metrics)\n\n\n\n\n​\nCrew Execution Process\n\n\n\n\nSequential Process\n: Tasks are executed one after another, allowing for a linear flow of work.\n\n\nHierarchical Process\n: A manager agent coordinates the crew, delegating tasks and validating outcomes before proceeding. \nNote\n: A \nmanager_llm\n or \nmanager_agent\n is required for this process and it’s essential for validating the process flow.\n\n\n\n\n​\nKicking Off a Crew\n\n\nOnce your crew is assembled, initiate the workflow with the \nkickoff()\n method. This starts the execution process according to the defined process flow.\n\n\nCode\nCopy\nAsk AI\n# Start the crew's task execution\n\n\nresult \n=\n my_crew.kickoff()\n\n\nprint\n(result)\n\n\n\n\n​\nDifferent Ways to Kick Off a Crew\n\n\nOnce your crew is assembled, initiate the workflow with the appropriate kickoff method. CrewAI provides several methods for better control over the kickoff process: \nkickoff()\n, \nkickoff_for_each()\n, \nkickoff_async()\n, and \nkickoff_for_each_async()\n.\n\n\n\n\nkickoff()\n: Starts the execution process according to the defined process flow.\n\n\nkickoff_for_each()\n: Executes tasks sequentially for each provided input event or item in the collection.\n\n\nkickoff_async()\n: Initiates the workflow asynchronously.\n\n\nkickoff_for_each_async()\n: Executes tasks concurrently for each provided input event or item, leveraging asynchronous processing.\n\n\n\n\nCode\nCopy\nAsk AI\n# Start the crew's task execution\n\n\nresult \n=\n my_crew.kickoff()\n\n\nprint\n(result)\n\n\n\n\n# Example of using kickoff_for_each\n\n\ninputs_array \n=\n [{\n'topic'\n: \n'AI in healthcare'\n}, {\n'topic'\n: \n'AI in finance'\n}]\n\n\nresults \n=\n my_crew.kickoff_for_each(\ninputs\n=\ninputs_array)\n\n\nfor\n result \nin\n results:\n\n\n print\n(result)\n\n\n\n\n# Example of using kickoff_async\n\n\ninputs \n=\n {\n'topic'\n: \n'AI in healthcare'\n}\n\n\nasync_result \n=\n await\n my_crew.kickoff_async(\ninputs\n=\ninputs)\n\n\nprint\n(async_result)\n\n\n\n\n# Example of using kickoff_for_each_async\n\n\ninputs_array \n=\n [{\n'topic'\n: \n'AI in healthcare'\n}, {\n'topic'\n: \n'AI in finance'\n}]\n\n\nasync_results \n=\n await\n my_crew.kickoff_for_each_async(\ninputs\n=\ninputs_array)\n\n\nfor\n async_result \nin\n async_results:\n\n\n print\n(async_result)\n\n\n\n\nThese methods provide flexibility in how you manage and execute tasks within your crew, allowing for both synchronous and asynchronous workflows tailored to your needs.\n\n\n​\nReplaying from a Specific Task\n\n\nYou can now replay from a specific task using our CLI command \nreplay\n.\n\n\nThe replay feature in CrewAI allows you to replay from a specific task using the command-line interface (CLI). By running the command \ncrewai replay -t \n, you can specify the \ntask_id\n for the replay process.\n\n\nKickoffs will now save the latest kickoffs returned task outputs locally for you to be able to replay from.\n\n\n​\nReplaying from a Specific Task Using the CLI\n\n\nTo use the replay feature, follow these steps:\n\n\n\n\nOpen your terminal or command prompt.\n\n\nNavigate to the directory where your CrewAI project is located.\n\n\nRun the following command:\n\n\n\n\nTo view the latest kickoff task IDs, use:\n\n\nCopy\nAsk AI\ncrewai\n log-tasks-outputs\n\n\n\n\nThen, to replay from a specific task, use:\n\n\nCopy\nAsk AI\ncrewai\n replay\n -t\n <\ntask_i\nd\n>\n\n\n\n\nThese commands let you replay from your latest kickoff tasks, still retaining context from previously executed tasks.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTasks\nFlows\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nCrew Attributes\nCreating Crews\nYAML Configuration (Recommended)\nExample Crew Class with Decorators\nDecorators overview from annotations.py\nDirect Code Definition (Alternative)\nCrew Output\nCrew Output Attributes\nCrew Output Methods and Properties\nAccessing Crew Outputs\nExample\nAccessing Crew Logs\nMemory Utilization\nCache Utilization\nCrew Usage Metrics\nCrew Execution Process\nKicking Off a Crew\nDifferent Ways to Kick Off a Crew\nReplaying from a Specific Task\nReplaying from a Specific Task Using the CLI\nCore Concepts\nCrews\nCopy page\nUnderstanding and utilizing crews in the crewAI framework with comprehensive attributes and functionalities.\n​\nOverview\n\n\nA crew in crewAI represents a collaborative group of agents working together to achieve a set of tasks. Each crew defines the strategy for task execution, agent collaboration, and the overall workflow.\n\n\n​\nCrew Attributes\n\n\nAttribute\nParameters\nDescription\nTasks\ntasks\nA list of tasks assigned to the crew.\nAgents\nagents\nA list of agents that are part of the crew.\nProcess\n \n(optional)\nprocess\nThe process flow (e.g., sequential, hierarchical) the crew follows. Default is \nsequential\n.\nVerbose\n \n(optional)\nverbose\nThe verbosity level for logging during execution. Defaults to \nFalse\n.\nManager LLM\n \n(optional)\nmanager_llm\nThe language model used by the manager agent in a hierarchical process. \nRequired when using a hierarchical process.\nFunction Calling LLM\n \n(optional)\nfunction_calling_llm\nIf passed, the crew will use this LLM to do function calling for tools for all agents in the crew. Each agent can have its own LLM, which overrides the crew’s LLM for function calling.\nConfig\n \n(optional)\nconfig\nOptional configuration settings for the crew, in \nJson\n or \nDict[str, Any]\n format.\nMax RPM\n \n(optional)\nmax_rpm\nMaximum requests per minute the crew adheres to during execution. Defaults to \nNone\n.\nMemory\n \n(optional)\nmemory\nUtilized for storing execution memories (short-term, long-term, entity memory).\nMemory Config\n \n(optional)\nmemory_config\nConfiguration for the memory provider to be used by the crew.\nCache\n \n(optional)\ncache\nSpecifies whether to use a cache for storing the results of tools’ execution. Defaults to \nTrue\n.\nEmbedder\n \n(optional)\nembedder\nConfiguration for the embedder to be used by the crew. Mostly used by memory for now. Default is \n{\"provider\": \"openai\"}\n.\nStep Callback\n \n(optional)\nstep_callback\nA function that is called after each step of every agent. This can be used to log the agent’s actions or to perform other operations; it won’t override the agent-specific \nstep_callback\n.\nTask Callback\n \n(optional)\ntask_callback\nA function that is called after the completion of each task. Useful for monitoring or additional operations post-task execution.\nShare Crew\n \n(optional)\nshare_crew\nWhether you want to share the complete crew information and execution with the crewAI team to make the library better, and allow us to train models.\nOutput Log File\n \n(optional)\noutput_log_file\nSet to True to save logs as logs.txt in the current directory or provide a file path. Logs will be in JSON format if the filename ends in .json, otherwise .txt. Defaults to \nNone\n.\nManager Agent\n \n(optional)\nmanager_agent\nmanager\n sets a custom agent that will be used as a manager.\nPrompt File\n \n(optional)\nprompt_file\nPath to the prompt JSON file to be used for the crew.\nPlanning\n \n(optional)\nplanning\nAdds planning ability to the Crew. When activated before each Crew iteration, all Crew data is sent to an AgentPlanner that will plan the tasks and this plan will be added to each task description.\nPlanning LLM\n \n(optional)\nplanning_llm\nThe language model used by the AgentPlanner in a planning process.\n\n\nCrew Max RPM\n: The \nmax_rpm\n attribute sets the maximum number of requests per minute the crew can perform to avoid rate limits and will override individual agents’ \nmax_rpm\n settings if you set it.\n\n\n​\nCreating Crews\n\n\nThere are two ways to create crews in CrewAI: using \nYAML configuration (recommended)\n or defining them \ndirectly in code\n.\n\n\n​\nYAML Configuration (Recommended)\n\n\nUsing YAML configuration provides a cleaner, more maintainable way to define crews and is consistent with how agents and tasks are defined in CrewAI projects.\n\n\nAfter creating your CrewAI project as outlined in the \nInstallation\n section, you can define your crew in a class that inherits from \nCrewBase\n and uses decorators to define agents, tasks, and the crew itself.\n\n\n​\nExample Crew Class with Decorators\n\n\ncode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\nfrom\n crewai.project \nimport\n CrewBase, agent, task, crew, before_kickoff, after_kickoff\n\n\nfrom\n crewai.agents.agent_builder.base_agent \nimport\n BaseAgent\n\n\nfrom\n typing \nimport\n List\n\n\n\n\n@CrewBase\n\n\nclass\n YourCrewName\n:\n\n\n \"\"\"Description of your crew\"\"\"\n\n\n\n\n agents: List[BaseAgent]\n\n\n tasks: List[Task]\n\n\n\n\n # Paths to your YAML configuration files\n\n\n # To see an example agent and task defined in YAML, checkout the following:\n\n\n # - Task: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommended\n\n\n # - Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended\n\n\n agents_config \n=\n 'config/agents.yaml'\n\n\n tasks_config \n=\n 'config/tasks.yaml'\n\n\n\n\n @before_kickoff\n\n\n def\n prepare_inputs\n(\nself\n, \ninputs\n):\n\n\n # Modify inputs before the crew starts\n\n\n inputs[\n'additional_data'\n] \n=\n \"Some extra information\"\n\n\n return\n inputs\n\n\n\n\n @after_kickoff\n\n\n def\n process_output\n(\nself\n, \noutput\n):\n\n\n # Modify output after the crew finishes\n\n\n output.raw \n+=\n \"\n\\n\nProcessed after kickoff.\"\n\n\n return\n output\n\n\n\n\n @agent\n\n\n def\n agent_one\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'agent_one'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @agent\n\n\n def\n agent_two\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n config\n=\nself\n.agents_config[\n'agent_two'\n], \n# type: ignore[index]\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n @task\n\n\n def\n task_one\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'task_one'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @task\n\n\n def\n task_two\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n config\n=\nself\n.tasks_config[\n'task_two'\n] \n# type: ignore[index]\n\n\n )\n\n\n\n\n @crew\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents, \n# Automatically collected by the @agent decorator\n\n\n tasks\n=\nself\n.tasks, \n# Automatically collected by the @task decorator.\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n )\n\n\n\n\nHow to run the above code:\n\n\ncode\nCopy\nAsk AI\nYourCrewName().crew().kickoff(\ninputs\n=\n{\n\"any\"\n: \n\"input here\"\n})\n\n\n\n\nTasks will be executed in the order they are defined.\n\n\nThe \nCrewBase\n class, along with these decorators, automates the collection of agents and tasks, reducing the need for manual management.\n\n\n​\nDecorators overview from \nannotations.py\n\n\nCrewAI provides several decorators in the \nannotations.py\n file that are used to mark methods within your crew class for special handling:\n\n\n\n\n@CrewBase\n: Marks the class as a crew base class.\n\n\n@agent\n: Denotes a method that returns an \nAgent\n object.\n\n\n@task\n: Denotes a method that returns a \nTask\n object.\n\n\n@crew\n: Denotes the method that returns the \nCrew\n object.\n\n\n@before_kickoff\n: (Optional) Marks a method to be executed before the crew starts.\n\n\n@after_kickoff\n: (Optional) Marks a method to be executed after the crew finishes.\n\n\n\n\nThese decorators help in organizing your crew’s structure and automatically collecting agents and tasks without manually listing them.\n\n\n​\nDirect Code Definition (Alternative)\n\n\nAlternatively, you can define the crew directly in code without using YAML configuration files.\n\n\ncode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task, Process\n\n\nfrom\n crewai_tools \nimport\n YourCustomTool\n\n\n\n\nclass\n YourCrewName\n:\n\n\n def\n agent_one\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Data Analyst\"\n,\n\n\n goal\n=\n\"Analyze data trends in the market\"\n,\n\n\n backstory\n=\n\"An experienced data analyst with a background in economics\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n tools\n=\n[YourCustomTool()]\n\n\n )\n\n\n\n\n def\n agent_two\n(\nself\n) -> Agent:\n\n\n return\n Agent(\n\n\n role\n=\n\"Market Researcher\"\n,\n\n\n goal\n=\n\"Gather information on market dynamics\"\n,\n\n\n backstory\n=\n\"A diligent researcher with a keen eye for detail\"\n,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\n def\n task_one\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n description\n=\n\"Collect recent market data and identify trends.\"\n,\n\n\n expected_output\n=\n\"A report summarizing key trends in the market.\"\n,\n\n\n agent\n=\nself\n.agent_one()\n\n\n )\n\n\n\n\n def\n task_two\n(\nself\n) -> Task:\n\n\n return\n Task(\n\n\n description\n=\n\"Research factors affecting market dynamics.\"\n,\n\n\n expected_output\n=\n\"An analysis of factors influencing the market.\"\n,\n\n\n agent\n=\nself\n.agent_two()\n\n\n )\n\n\n\n\n def\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\n[\nself\n.agent_one(), \nself\n.agent_two()],\n\n\n tasks\n=\n[\nself\n.task_one(), \nself\n.task_two()],\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n\n\n )\n\n\n\n\nHow to run the above code:\n\n\ncode\nCopy\nAsk AI\nYourCrewName().crew().kickoff(\ninputs\n=\n{})\n\n\n\n\nIn this example:\n\n\n\n\nAgents and tasks are defined directly within the class without decorators.\n\n\nWe manually create and manage the list of agents and tasks.\n\n\nThis approach provides more control but can be less maintainable for larger projects.\n\n\n\n\n​\nCrew Output\n\n\nThe output of a crew in the CrewAI framework is encapsulated within the \nCrewOutput\n class.\nThis class provides a structured way to access results of the crew’s execution, including various formats such as raw strings, JSON, and Pydantic models.\nThe \nCrewOutput\n includes the results from the final task output, token usage, and individual task outputs.\n\n\n​\nCrew Output Attributes\n\n\nAttribute\nParameters\nType\nDescription\nRaw\nraw\nstr\nThe raw output of the crew. This is the default format for the output.\nPydantic\npydantic\nOptional[BaseModel]\nA Pydantic model object representing the structured output of the crew.\nJSON Dict\njson_dict\nOptional[Dict[str, Any]]\nA dictionary representing the JSON output of the crew.\nTasks Output\ntasks_output\nList[TaskOutput]\nA list of \nTaskOutput\n objects, each representing the output of a task in the crew.\nToken Usage\ntoken_usage\nDict[str, Any]\nA summary of token usage, providing insights into the language model’s performance during execution.\n\n\n​\nCrew Output Methods and Properties\n\n\nMethod/Property\nDescription\njson\nReturns the JSON string representation of the crew output if the output format is JSON.\nto_dict\nConverts the JSON and Pydantic outputs to a dictionary.\n*\n*str**\nReturns the string representation of the crew output, prioritizing Pydantic, then JSON, then raw.\n\n\n​\nAccessing Crew Outputs\n\n\nOnce a crew has been executed, its output can be accessed through the \noutput\n attribute of the \nCrew\n object. The \nCrewOutput\n class provides various ways to interact with and present this output.\n\n\n​\nExample\n\n\nCode\nCopy\nAsk AI\n# Example crew execution\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[research_agent, writer_agent],\n\n\n tasks\n=\n[research_task, write_article_task],\n\n\n verbose\n=\nTrue\n\n\n)\n\n\n\n\ncrew_output \n=\n crew.kickoff()\n\n\n\n\n# Accessing the crew output\n\n\nprint\n(\nf\n\"Raw Output: \n{\ncrew_output.raw\n}\n\"\n)\n\n\nif\n crew_output.json_dict:\n\n\n print\n(\nf\n\"JSON Output: \n{\njson.dumps(crew_output.json_dict, \nindent\n=\n2\n)\n}\n\"\n)\n\n\nif\n crew_output.pydantic:\n\n\n print\n(\nf\n\"Pydantic Output: \n{\ncrew_output.pydantic\n}\n\"\n)\n\n\nprint\n(\nf\n\"Tasks Output: \n{\ncrew_output.tasks_output\n}\n\"\n)\n\n\nprint\n(\nf\n\"Token Usage: \n{\ncrew_output.token_usage\n}\n\"\n)\n\n\n\n\n​\nAccessing Crew Logs\n\n\nYou can see real time log of the crew execution, by setting \noutput_log_file\n as a \nTrue(Boolean)\n or a \nfile_name(str)\n. Supports logging of events as both \nfile_name.txt\n and \nfile_name.json\n.\nIn case of \nTrue(Boolean)\n will save as \nlogs.txt\n.\n\n\nIn case of \noutput_log_file\n is set as \nFalse(Boolean)\n or \nNone\n, the logs will not be populated.\n\n\nCode\nCopy\nAsk AI\n# Save crew logs\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n True\n) \n# Logs will be saved as logs.txt\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n file_name) \n# Logs will be saved as file_name.txt\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n file_name.txt) \n# Logs will be saved as file_name.txt\n\n\ncrew \n=\n Crew(\noutput_log_file\n =\n file_name.json) \n# Logs will be saved as file_name.json\n\n\n\n\n​\nMemory Utilization\n\n\nCrews can utilize memory (short-term, long-term, and entity memory) to enhance their execution and learning over time. This feature allows crews to store and recall execution memories, aiding in decision-making and task execution strategies.\n\n\n​\nCache Utilization\n\n\nCaches can be employed to store the results of tools’ execution, making the process more efficient by reducing the need to re-execute identical tasks.\n\n\n​\nCrew Usage Metrics\n\n\nAfter the crew execution, you can access the \nusage_metrics\n attribute to view the language model (LLM) usage metrics for all tasks executed by the crew. This provides insights into operational efficiency and areas for improvement.\n\n\nCode\nCopy\nAsk AI\n# Access the crew's usage metrics\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent1, agent2], \ntasks\n=\n[task1, task2])\n\n\ncrew.kickoff()\n\n\nprint\n(crew.usage_metrics)\n\n\n\n\n​\nCrew Execution Process\n\n\n\n\nSequential Process\n: Tasks are executed one after another, allowing for a linear flow of work.\n\n\nHierarchical Process\n: A manager agent coordinates the crew, delegating tasks and validating outcomes before proceeding. \nNote\n: A \nmanager_llm\n or \nmanager_agent\n is required for this process and it’s essential for validating the process flow.\n\n\n\n\n​\nKicking Off a Crew\n\n\nOnce your crew is assembled, initiate the workflow with the \nkickoff()\n method. This starts the execution process according to the defined process flow.\n\n\nCode\nCopy\nAsk AI\n# Start the crew's task execution\n\n\nresult \n=\n my_crew.kickoff()\n\n\nprint\n(result)\n\n\n\n\n​\nDifferent Ways to Kick Off a Crew\n\n\nOnce your crew is assembled, initiate the workflow with the appropriate kickoff method. CrewAI provides several methods for better control over the kickoff process: \nkickoff()\n, \nkickoff_for_each()\n, \nkickoff_async()\n, and \nkickoff_for_each_async()\n.\n\n\n\n\nkickoff()\n: Starts the execution process according to the defined process flow.\n\n\nkickoff_for_each()\n: Executes tasks sequentially for each provided input event or item in the collection.\n\n\nkickoff_async()\n: Initiates the workflow asynchronously.\n\n\nkickoff_for_each_async()\n: Executes tasks concurrently for each provided input event or item, leveraging asynchronous processing.\n\n\n\n\nCode\nCopy\nAsk AI\n# Start the crew's task execution\n\n\nresult \n=\n my_crew.kickoff()\n\n\nprint\n(result)\n\n\n\n\n# Example of using kickoff_for_each\n\n\ninputs_array \n=\n [{\n'topic'\n: \n'AI in healthcare'\n}, {\n'topic'\n: \n'AI in finance'\n}]\n\n\nresults \n=\n my_crew.kickoff_for_each(\ninputs\n=\ninputs_array)\n\n\nfor\n result \nin\n results:\n\n\n print\n(result)\n\n\n\n\n# Example of using kickoff_async\n\n\ninputs \n=\n {\n'topic'\n: \n'AI in healthcare'\n}\n\n\nasync_result \n=\n await\n my_crew.kickoff_async(\ninputs\n=\ninputs)\n\n\nprint\n(async_result)\n\n\n\n\n# Example of using kickoff_for_each_async\n\n\ninputs_array \n=\n [{\n'topic'\n: \n'AI in healthcare'\n}, {\n'topic'\n: \n'AI in finance'\n}]\n\n\nasync_results \n=\n await\n my_crew.kickoff_for_each_async(\ninputs\n=\ninputs_array)\n\n\nfor\n async_result \nin\n async_results:\n\n\n print\n(async_result)\n\n\n\n\nThese methods provide flexibility in how you manage and execute tasks within your crew, allowing for both synchronous and asynchronous workflows tailored to your needs.\n\n\n​\nReplaying from a Specific Task\n\n\nYou can now replay from a specific task using our CLI command \nreplay\n.\n\n\nThe replay feature in CrewAI allows you to replay from a specific task using the command-line interface (CLI). By running the command \ncrewai replay -t \n, you can specify the \ntask_id\n for the replay process.\n\n\nKickoffs will now save the latest kickoffs returned task outputs locally for you to be able to replay from.\n\n\n​\nReplaying from a Specific Task Using the CLI\n\n\nTo use the replay feature, follow these steps:\n\n\n\n\nOpen your terminal or command prompt.\n\n\nNavigate to the directory where your CrewAI project is located.\n\n\nRun the following command:\n\n\n\n\nTo view the latest kickoff task IDs, use:\n\n\nCopy\nAsk AI\ncrewai\n log-tasks-outputs\n\n\n\n\nThen, to replay from a specific task, use:\n\n\nCopy\nAsk AI\ncrewai\n replay\n -t\n <\ntask_i\nd\n>\n\n\n\n\nThese commands let you replay from your latest kickoff tasks, still retaining context from previously executed tasks.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTasks\nFlows\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nCrew Attributes\nCreating Crews\nYAML Configuration (Recommended)\nExample Crew Class with Decorators\nDecorators overview from annotations.py\nDirect Code Definition (Alternative)\nCrew Output\nCrew Output Attributes\nCrew Output Methods and Properties\nAccessing Crew Outputs\nExample\nAccessing Crew Logs\nMemory Utilization\nCache Utilization\nCrew Usage Metrics\nCrew Execution Process\nKicking Off a Crew\nDifferent Ways to Kick Off a Crew\nReplaying from a Specific Task\nReplaying from a Specific Task Using the CLI" }, { "source": "https://docs.crewai.com/en/learn/hierarchical-process", "title": "Hierarchical Process - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nHierarchical Process\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nHierarchical Process\nCopy page\nA comprehensive guide to understanding and applying the hierarchical process within your CrewAI projects, updated to reflect the latest coding practices and functionalities.\n​\nIntroduction\n\n\nThe hierarchical process in CrewAI introduces a structured approach to task management, simulating traditional organizational hierarchies for efficient task delegation and execution.\nThis systematic workflow enhances project outcomes by ensuring tasks are handled with optimal efficiency and accuracy.\n\n\nThe hierarchical process is designed to leverage advanced models like GPT-4, optimizing token usage while handling complex tasks with greater efficiency.\n\n\n​\nHierarchical Process Overview\n\n\nBy default, tasks in CrewAI are managed through a sequential process. However, adopting a hierarchical approach allows for a clear hierarchy in task management,\nwhere a ‘manager’ agent coordinates the workflow, delegates tasks, and validates outcomes for streamlined and effective execution. This manager agent can now be either\nautomatically created by CrewAI or explicitly set by the user.\n\n\n​\nKey Features\n\n\n\n\nTask Delegation\n: A manager agent allocates tasks among crew members based on their roles and capabilities.\n\n\nResult Validation\n: The manager evaluates outcomes to ensure they meet the required standards.\n\n\nEfficient Workflow\n: Emulates corporate structures, providing an organized approach to task management.\n\n\nSystem Prompt Handling\n: Optionally specify whether the system should use predefined prompts.\n\n\nStop Words Control\n: Optionally specify whether stop words should be used, supporting various models including the o1 models.\n\n\nContext Window Respect\n: Prioritize important context by enabling respect of the context window, which is now the default behavior.\n\n\nDelegation Control\n: Delegation is now disabled by default to give users explicit control.\n\n\nMax Requests Per Minute\n: Configurable option to set the maximum number of requests per minute.\n\n\nMax Iterations\n: Limit the maximum number of iterations for obtaining a final answer.\n\n\n\n\n​\nImplementing the Hierarchical Process\n\n\nTo utilize the hierarchical process, it’s essential to explicitly set the process attribute to \nProcess.hierarchical\n, as the default behavior is \nProcess.sequential\n.\nDefine a crew with a designated manager and establish a clear chain of command.\n\n\nAssign tools at the agent level to facilitate task delegation and execution by the designated agents under the manager’s guidance.\nTools can also be specified at the task level for precise control over tool availability during task execution.\n\n\nConfiguring the \nmanager_llm\n parameter is crucial for the hierarchical process.\nThe system requires a manager LLM to be set up for proper function, ensuring tailored decision-making.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Process, Agent\n\n\n\n\n# Agents are defined with attributes for backstory, cache, and verbose mode\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Researcher'\n,\n\n\n goal\n=\n'Conduct in-depth analysis'\n,\n\n\n backstory\n=\n'Experienced data analyst with a knack for uncovering hidden trends.'\n,\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Writer'\n,\n\n\n goal\n=\n'Create engaging content'\n,\n\n\n backstory\n=\n'Creative writer passionate about storytelling in technical domains.'\n,\n\n\n)\n\n\n\n\n# Establishing the crew with a hierarchical process and additional configurations\n\n\nproject_crew \n=\n Crew(\n\n\n tasks\n=\n[\n...\n], \n# Tasks to be delegated and executed under the manager's supervision\n\n\n agents\n=\n[researcher, writer],\n\n\n manager_llm\n=\n\"gpt-4o\"\n, \n# Specify which LLM the manager should use\n\n\n process\n=\nProcess.hierarchical, \n\n\n planning\n=\nTrue\n, \n\n\n)\n\n\n\n\n​\nUsing a Custom Manager Agent\n\n\nAlternatively, you can create a custom manager agent with specific attributes tailored to your project’s management needs. This gives you more control over the manager’s behavior and capabilities.\n\n\nCopy\nAsk AI\n# Define a custom manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Use the custom manager in your crew\n\n\nproject_crew \n=\n Crew(\n\n\n tasks\n=\n[\n...\n],\n\n\n agents\n=\n[researcher, writer],\n\n\n manager_agent\n=\nmanager, \n# Use your custom manager agent\n\n\n process\n=\nProcess.hierarchical,\n\n\n planning\n=\nTrue\n,\n\n\n)\n\n\n\n\nFor more details on creating and customizing a manager agent, check out the \nCustom Manager Agent documentation\n.\n\n\n​\nWorkflow in Action\n\n\n\n\nTask Assignment\n: The manager assigns tasks strategically, considering each agent’s capabilities and available tools.\n\n\nExecution and Review\n: Agents complete their tasks with the option for asynchronous execution and callback functions for streamlined workflows.\n\n\nSequential Task Progression\n: Despite being a hierarchical process, tasks follow a logical order for smooth progression, facilitated by the manager’s oversight.\n\n\n\n\n​\nConclusion\n\n\nAdopting the hierarchical process in CrewAI, with the correct configurations and understanding of the system’s capabilities, facilitates an organized and efficient approach to project management.\nUtilize the advanced features and customizations to tailor the workflow to your specific needs, ensuring optimal task execution and project success.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nForce Tool Output as Result\nHuman Input on Execution\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nHierarchical Process Overview\nKey Features\nImplementing the Hierarchical Process\nUsing a Custom Manager Agent\nWorkflow in Action\nConclusion\nLearn\nHierarchical Process\nCopy page\nA comprehensive guide to understanding and applying the hierarchical process within your CrewAI projects, updated to reflect the latest coding practices and functionalities.\n​\nIntroduction\n\n\nThe hierarchical process in CrewAI introduces a structured approach to task management, simulating traditional organizational hierarchies for efficient task delegation and execution.\nThis systematic workflow enhances project outcomes by ensuring tasks are handled with optimal efficiency and accuracy.\n\n\nThe hierarchical process is designed to leverage advanced models like GPT-4, optimizing token usage while handling complex tasks with greater efficiency.\n\n\n​\nHierarchical Process Overview\n\n\nBy default, tasks in CrewAI are managed through a sequential process. However, adopting a hierarchical approach allows for a clear hierarchy in task management,\nwhere a ‘manager’ agent coordinates the workflow, delegates tasks, and validates outcomes for streamlined and effective execution. This manager agent can now be either\nautomatically created by CrewAI or explicitly set by the user.\n\n\n​\nKey Features\n\n\n\n\nTask Delegation\n: A manager agent allocates tasks among crew members based on their roles and capabilities.\n\n\nResult Validation\n: The manager evaluates outcomes to ensure they meet the required standards.\n\n\nEfficient Workflow\n: Emulates corporate structures, providing an organized approach to task management.\n\n\nSystem Prompt Handling\n: Optionally specify whether the system should use predefined prompts.\n\n\nStop Words Control\n: Optionally specify whether stop words should be used, supporting various models including the o1 models.\n\n\nContext Window Respect\n: Prioritize important context by enabling respect of the context window, which is now the default behavior.\n\n\nDelegation Control\n: Delegation is now disabled by default to give users explicit control.\n\n\nMax Requests Per Minute\n: Configurable option to set the maximum number of requests per minute.\n\n\nMax Iterations\n: Limit the maximum number of iterations for obtaining a final answer.\n\n\n\n\n​\nImplementing the Hierarchical Process\n\n\nTo utilize the hierarchical process, it’s essential to explicitly set the process attribute to \nProcess.hierarchical\n, as the default behavior is \nProcess.sequential\n.\nDefine a crew with a designated manager and establish a clear chain of command.\n\n\nAssign tools at the agent level to facilitate task delegation and execution by the designated agents under the manager’s guidance.\nTools can also be specified at the task level for precise control over tool availability during task execution.\n\n\nConfiguring the \nmanager_llm\n parameter is crucial for the hierarchical process.\nThe system requires a manager LLM to be set up for proper function, ensuring tailored decision-making.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Crew, Process, Agent\n\n\n\n\n# Agents are defined with attributes for backstory, cache, and verbose mode\n\n\nresearcher \n=\n Agent(\n\n\n role\n=\n'Researcher'\n,\n\n\n goal\n=\n'Conduct in-depth analysis'\n,\n\n\n backstory\n=\n'Experienced data analyst with a knack for uncovering hidden trends.'\n,\n\n\n)\n\n\nwriter \n=\n Agent(\n\n\n role\n=\n'Writer'\n,\n\n\n goal\n=\n'Create engaging content'\n,\n\n\n backstory\n=\n'Creative writer passionate about storytelling in technical domains.'\n,\n\n\n)\n\n\n\n\n# Establishing the crew with a hierarchical process and additional configurations\n\n\nproject_crew \n=\n Crew(\n\n\n tasks\n=\n[\n...\n], \n# Tasks to be delegated and executed under the manager's supervision\n\n\n agents\n=\n[researcher, writer],\n\n\n manager_llm\n=\n\"gpt-4o\"\n, \n# Specify which LLM the manager should use\n\n\n process\n=\nProcess.hierarchical, \n\n\n planning\n=\nTrue\n, \n\n\n)\n\n\n\n\n​\nUsing a Custom Manager Agent\n\n\nAlternatively, you can create a custom manager agent with specific attributes tailored to your project’s management needs. This gives you more control over the manager’s behavior and capabilities.\n\n\nCopy\nAsk AI\n# Define a custom manager agent\n\n\nmanager \n=\n Agent(\n\n\n role\n=\n\"Project Manager\"\n,\n\n\n goal\n=\n\"Efficiently manage the crew and ensure high-quality task completion\"\n,\n\n\n backstory\n=\n\"You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success.\"\n,\n\n\n allow_delegation\n=\nTrue\n,\n\n\n)\n\n\n\n\n# Use the custom manager in your crew\n\n\nproject_crew \n=\n Crew(\n\n\n tasks\n=\n[\n...\n],\n\n\n agents\n=\n[researcher, writer],\n\n\n manager_agent\n=\nmanager, \n# Use your custom manager agent\n\n\n process\n=\nProcess.hierarchical,\n\n\n planning\n=\nTrue\n,\n\n\n)\n\n\n\n\nFor more details on creating and customizing a manager agent, check out the \nCustom Manager Agent documentation\n.\n\n\n​\nWorkflow in Action\n\n\n\n\nTask Assignment\n: The manager assigns tasks strategically, considering each agent’s capabilities and available tools.\n\n\nExecution and Review\n: Agents complete their tasks with the option for asynchronous execution and callback functions for streamlined workflows.\n\n\nSequential Task Progression\n: Despite being a hierarchical process, tasks follow a logical order for smooth progression, facilitated by the manager’s oversight.\n\n\n\n\n​\nConclusion\n\n\nAdopting the hierarchical process in CrewAI, with the correct configurations and understanding of the system’s capabilities, facilitates an organized and efficient approach to project management.\nUtilize the advanced features and customizations to tailor the workflow to your specific needs, ensuring optimal task execution and project success.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nForce Tool Output as Result\nHuman Input on Execution\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nHierarchical Process Overview\nKey Features\nImplementing the Hierarchical Process\nUsing a Custom Manager Agent\nWorkflow in Action\nConclusion" }, { "source": "https://docs.crewai.com/en/mcp/security", "title": "MCP Security Considerations - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nMCP Integration\nMCP Security Considerations\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nMCP Integration\nMCP Security Considerations\nCopy page\nLearn about important security best practices when integrating MCP servers with your CrewAI agents.\n​\nOverview\n\n\nThe most critical aspect of MCP security is \ntrust\n. You should \nonly\n connect your CrewAI agents to MCP servers that you fully trust.\n\n\nWhen integrating external services like MCP (Model Context Protocol) servers into your CrewAI agents, security is paramount.\nMCP servers can execute code, access data, or interact with other systems based on the tools they expose.\nIt’s crucial to understand the implications and follow best practices to protect your applications and data.\n\n\n​\nRisks\n\n\n\n\nExecute arbitrary code on the machine where the agent is running (especially with \nStdio\n transport if the server can control the command executed).\n\n\nExpose sensitive data from your agent or its environment.\n\n\nManipulate your agent’s behavior in unintended ways, including making unauthorized API calls on your behalf.\n\n\nHijack your agent’s reasoning process through sophisticated prompt injection techniques (see below).\n\n\n\n\n​\n1. Trusting MCP Servers\n\n\nOnly connect to MCP servers that you trust.\n\n\nBefore configuring \nMCPServerAdapter\n to connect to an MCP server, ensure you know:\n\n\n\n\nWho operates the server?\n Is it a known, reputable service, or an internal server under your control?\n\n\nWhat tools does it expose?\n Understand the capabilities of the tools. Could they be misused if an attacker gained control or if the server itself is malicious?\n\n\nWhat data does it access or process?\n Be aware of any sensitive information that might be sent to or handled by the MCP server.\n\n\n\n\nAvoid connecting to unknown or unverified MCP servers, especially if your agents handle sensitive tasks or data.\n\n\n​\n2. Secure Prompt Injection via Tool Metadata: The “Model Control Protocol” Risk\n\n\nA significant and subtle risk is the potential for prompt injection through tool metadata. Here’s how it works:\n\n\n\n\nWhen your CrewAI agent connects to an MCP server, it typically requests a list of available tools.\n\n\nThe MCP server responds with metadata for each tool, including its name, description, and parameter descriptions.\n\n\nYour agent’s underlying Language Model (LLM) uses this metadata to understand how and when to use the tools. This metadata is often incorporated into the LLM’s system prompt or context.\n\n\nA malicious MCP server can craft its tool metadata (names, descriptions) to include hidden or overt instructions. These instructions can act as a prompt injection, effectively telling your LLM to behave in a certain way, reveal sensitive information, or perform malicious actions.\n\n\n\n\nCrucially, this attack can occur simply by connecting to a malicious server and listing its tools, even if your agent never explicitly decides to \nuse\n any of those tools.\n The mere exposure to the malicious metadata can be enough to compromise the agent’s behavior.\n\n\nMitigation:\n\n\n\n\nExtreme Caution with Untrusted Servers:\n Reiterate: \nDo not connect to MCP servers you do not fully trust.\n The risk of metadata injection makes this paramount.\n\n\n\n\n​\nStdio Transport Security\n\n\nStdio (Standard Input/Output) transport is typically used for local MCP servers running on the same machine as your CrewAI application.\n\n\n\n\nProcess Isolation\n: While generally safer as it doesn’t involve network exposure by default, ensure the script or command run by \nStdioServerParameters\n is from a trusted source and has appropriate file system permissions. A malicious Stdio server script could still harm your local system.\n\n\nInput Sanitization\n: If your Stdio server script takes complex inputs derived from agent interactions, ensure the script itself sanitizes these inputs to prevent command injection or other vulnerabilities within the script’s logic.\n\n\nResource Limits\n: Be mindful that a local Stdio server process consumes local resources (CPU, memory). Ensure it’s well-behaved and won’t exhaust system resources.\n\n\n\n\n​\nConfused Deputy Attacks\n\n\nThe \nConfused Deputy Problem\n is a classic security vulnerability that can manifest in MCP integrations, especially when an MCP server acts as a proxy to other third-party services (e.g., Google Calendar, GitHub) that use OAuth 2.0 for authorization.\n\n\nScenario:\n\n\n\n\nAn MCP server (let’s call it \nMCP-Proxy\n) allows your agent to interact with \nThirdPartyAPI\n.\n\n\nMCP-Proxy\n uses its own single, static \nclient_id\n when talking to \nThirdPartyAPI\n’s authorization server.\n\n\nYou, as the user, legitimately authorize \nMCP-Proxy\n to access \nThirdPartyAPI\n on your behalf. During this, \nThirdPartyAPI\n’s auth server might set a cookie in your browser indicating your consent for \nMCP-Proxy\n’s \nclient_id\n.\n\n\nAn attacker crafts a malicious link. This link initiates an OAuth flow with \nMCP-Proxy\n, but is designed to trick \nThirdPartyAPI\n’s auth server.\n\n\nIf you click this link, and \nThirdPartyAPI\n’s auth server sees your existing consent cookie for \nMCP-Proxy\n’s \nclient_id\n, it might \nskip\n asking for your consent again.\n\n\nMCP-Proxy\n might then be tricked into forwarding an authorization code (for \nThirdPartyAPI\n) to the attacker, or an MCP authorization code that the attacker can use to impersonate you to \nMCP-Proxy\n.\n\n\n\n\nMitigation (Primarily for MCP Server Developers):\n\n\n\n\nMCP proxy servers using static client IDs for downstream services \nmust\n obtain explicit user consent for \neach client application or agent\n connecting to them \nbefore\n initiating an OAuth flow with the third-party service. This means \nMCP-Proxy\n itself should show a consent screen.\n\n\n\n\nCrewAI User Implication:\n\n\n\n\nBe cautious if an MCP server redirects you for multiple OAuth authentications, especially if it seems unexpected or if the permissions requested are overly broad.\n\n\nPrefer MCP servers that clearly delineate their own identity versus the third-party services they might proxy.\n\n\n\n\n​\nRemote Transport Security (SSE & Streamable HTTP)\n\n\nWhen connecting to remote MCP servers via Server-Sent Events (SSE) or Streamable HTTP, standard web security practices are essential.\n\n\n​\nSSE Security Considerations\n\n\n​\na. DNS Rebinding Attacks (Especially for SSE)\n\n\n\n\nDNS rebinding allows an attacker-controlled website to bypass the same-origin policy and make requests to servers on the user’s local network (e.g., \nlocalhost\n) or intranet. This is particularly risky if you run an MCP server locally (e.g., for development) and an agent in a browser-like environment (though less common for typical CrewAI backend setups) or if the MCP server is on an internal network.\n\n\nMitigation Strategies for MCP Server Implementers:\n\n\n\n\nValidate \nOrigin\n and \nHost\n Headers\n: MCP servers (especially SSE ones) should validate the \nOrigin\n and/or \nHost\n HTTP headers to ensure requests are coming from expected domains/clients.\n\n\nBind to \nlocalhost\n (127.0.0.1)\n: When running MCP servers locally for development, bind them to \n127.0.0.1\n instead of \n0.0.0.0\n. This prevents them from being accessible from other machines on the network.\n\n\nAuthentication\n: Require authentication for all connections to your MCP server if it’s not intended for public anonymous access.\n\n\n\n\n​\nb. Use HTTPS\n\n\n\n\nEncrypt Data in Transit\n: Always use HTTPS (HTTP Secure) for the URLs of remote MCP servers. This encrypts the communication between your CrewAI application and the MCP server, protecting against eavesdropping and man-in-the-middle attacks. \nMCPServerAdapter\n will respect the scheme (\nhttp\n or \nhttps\n) provided in the URL.\n\n\n\n\n​\nc. Token Passthrough (Anti-Pattern)\n\n\nThis is primarily a concern for MCP server developers but understanding it helps in choosing secure servers.\n\n\n“Token passthrough” is when an MCP server accepts an access token from your CrewAI agent (which might be a token for a \ndifferent\n service, say \nServiceA\n) and simply passes it through to another downstream API (\nServiceB\n) without proper validation. Specifically, \nServiceB\n (or the MCP server itself) should only accept tokens that were explicitly issued \nfor them\n (i.e., the ‘audience’ claim in the token matches the server/service).\n\n\nRisks:\n\n\n\n\nBypasses security controls (like rate limiting or fine-grained permissions) on the MCP server or the downstream API.\n\n\nBreaks audit trails and accountability.\n\n\nAllows misuse of stolen tokens.\n\n\n\n\nMitigation (For MCP Server Developers):\n\n\n\n\nMCP servers \nMUST NOT\n accept tokens that were not explicitly issued for them. They must validate the token’s audience claim.\n\n\n\n\nCrewAI User Implication:\n\n\n\n\nWhile not directly controllable by the user, this highlights the importance of connecting to well-designed MCP servers that adhere to security best practices.\n\n\n\n\n​\nAuthentication and Authorization\n\n\n\n\nVerify Identity\n: If the MCP server provides sensitive tools or access to private data, it MUST implement strong authentication mechanisms to verify the identity of the client (your CrewAI application). This could involve API keys, OAuth tokens, or other standard methods.\n\n\nPrinciple of Least Privilege\n: Ensure the credentials used by \nMCPServerAdapter\n (if any) have only the necessary permissions to access the required tools.\n\n\n\n\n​\nd. Input Validation and Sanitization\n\n\n\n\nInput Validation is Critical\n: MCP servers \nmust\n rigorously validate all inputs received from agents \nbefore\n processing them or passing them to tools. This is a primary defense against many common vulnerabilities:\n\n\n\n\nCommand Injection:\n If a tool constructs shell commands, SQL queries, or other interpreted language statements based on input, the server must meticulously sanitize this input to prevent malicious commands from being injected and executed.\n\n\nPath Traversal:\n If a tool accesses files based on input parameters, the server must validate and sanitize these paths to prevent access to unauthorized files or directories (e.g., by blocking \n../\n sequences).\n\n\nData Type & Range Checks:\n Servers must ensure that input data conforms to the expected data types (e.g., string, number, boolean) and falls within acceptable ranges or adheres to defined formats (e.g., regex for URLs).\n\n\nJSON Schema Validation:\n All tool parameters should be strictly validated against their defined JSON schema. This helps catch malformed requests early.\n\n\n\n\n\n\nClient-Side Awareness\n: While server-side validation is paramount, as a CrewAI user, be mindful of the data your agents are constructed to send to MCP tools, especially if interacting with less-trusted or new MCP servers.\n\n\n\n\n​\ne. Rate Limiting and Resource Management\n\n\n\n\nPrevent Abuse\n: MCP servers should implement rate limiting to prevent abuse, whether intentional (Denial of Service attacks) or unintentional (e.g., a misconfigured agent making too many requests).\n\n\nClient-Side Retries\n: Implement sensible retry logic in your CrewAI tasks if transient network issues or server rate limits are expected, but avoid aggressive retries that could exacerbate server load.\n\n\n\n\n​\n4. Secure MCP Server Implementation Advice (For Developers)\n\n\nIf you are developing an MCP server that CrewAI agents might connect to, consider these best practices in addition to the points above:\n\n\n\n\nFollow Secure Coding Practices\n: Adhere to standard secure coding principles for your chosen language and framework (e.g., OWASP Top 10).\n\n\nPrinciple of Least Privilege\n: Ensure the process running the MCP server (especially for \nStdio\n) has only the minimum necessary permissions. Tools themselves should also operate with the least privilege required to perform their function.\n\n\nDependency Management\n: Keep all server-side dependencies, including operating system packages, language runtimes, and third-party libraries, up-to-date to patch known vulnerabilities. Use tools to scan for vulnerable dependencies.\n\n\nSecure Defaults\n: Design your server and its tools to be secure by default. For example, features that could be risky should be off by default or require explicit opt-in with clear warnings.\n\n\nAccess Control for Tools\n: Implement robust mechanisms to control which authenticated and authorized agents or users can access specific tools, especially those that are powerful, sensitive, or incur costs.\n\n\nSecure Error Handling\n: Servers should not expose detailed internal error messages, stack traces, or debugging information to the client, as these can reveal internal workings or potential vulnerabilities. Log errors comprehensively on the server-side for diagnostics.\n\n\nComprehensive Logging and Monitoring\n: Implement detailed logging of security-relevant events (e.g., authentication attempts, tool invocations, errors, authorization changes). Monitor these logs for suspicious activity or abuse patterns.\n\n\nAdherence to MCP Authorization Spec\n: If implementing authentication and authorization, strictly follow the \nMCP Authorization specification\n and relevant \nOAuth 2.0 security best practices\n.\n\n\nRegular Security Audits\n: If your MCP server handles sensitive data, performs critical operations, or is publicly exposed, consider periodic security audits by qualified professionals.\n\n\n\n\n​\n5. Further Reading\n\n\nFor more detailed information on MCP security, refer to the official documentation:\n\n\n\n\nMCP Transport Security\n\n\n\n\nBy understanding these security considerations and implementing best practices, you can safely leverage the power of MCP servers in your CrewAI projects.\nThese are by no means exhaustive, but they cover the most common and critical security concerns.\nThe threats will continue to evolve, so it’s important to stay informed and adapt your security measures accordingly.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nConnecting to Multiple MCP Servers\nTools Overview\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nRisks\n1. Trusting MCP Servers\n2. Secure Prompt Injection via Tool Metadata: The “Model Control Protocol” Risk\nStdio Transport Security\nConfused Deputy Attacks\nRemote Transport Security (SSE & Streamable HTTP)\nSSE Security Considerations\na. DNS Rebinding Attacks (Especially for SSE)\nb. Use HTTPS\nc. Token Passthrough (Anti-Pattern)\nAuthentication and Authorization\nd. Input Validation and Sanitization\ne. Rate Limiting and Resource Management\n4. Secure MCP Server Implementation Advice (For Developers)\n5. Further Reading\nMCP Integration\nMCP Security Considerations\nCopy page\nLearn about important security best practices when integrating MCP servers with your CrewAI agents.\n​\nOverview\n\n\nThe most critical aspect of MCP security is \ntrust\n. You should \nonly\n connect your CrewAI agents to MCP servers that you fully trust.\n\n\nWhen integrating external services like MCP (Model Context Protocol) servers into your CrewAI agents, security is paramount.\nMCP servers can execute code, access data, or interact with other systems based on the tools they expose.\nIt’s crucial to understand the implications and follow best practices to protect your applications and data.\n\n\n​\nRisks\n\n\n\n\nExecute arbitrary code on the machine where the agent is running (especially with \nStdio\n transport if the server can control the command executed).\n\n\nExpose sensitive data from your agent or its environment.\n\n\nManipulate your agent’s behavior in unintended ways, including making unauthorized API calls on your behalf.\n\n\nHijack your agent’s reasoning process through sophisticated prompt injection techniques (see below).\n\n\n\n\n​\n1. Trusting MCP Servers\n\n\nOnly connect to MCP servers that you trust.\n\n\nBefore configuring \nMCPServerAdapter\n to connect to an MCP server, ensure you know:\n\n\n\n\nWho operates the server?\n Is it a known, reputable service, or an internal server under your control?\n\n\nWhat tools does it expose?\n Understand the capabilities of the tools. Could they be misused if an attacker gained control or if the server itself is malicious?\n\n\nWhat data does it access or process?\n Be aware of any sensitive information that might be sent to or handled by the MCP server.\n\n\n\n\nAvoid connecting to unknown or unverified MCP servers, especially if your agents handle sensitive tasks or data.\n\n\n​\n2. Secure Prompt Injection via Tool Metadata: The “Model Control Protocol” Risk\n\n\nA significant and subtle risk is the potential for prompt injection through tool metadata. Here’s how it works:\n\n\n\n\nWhen your CrewAI agent connects to an MCP server, it typically requests a list of available tools.\n\n\nThe MCP server responds with metadata for each tool, including its name, description, and parameter descriptions.\n\n\nYour agent’s underlying Language Model (LLM) uses this metadata to understand how and when to use the tools. This metadata is often incorporated into the LLM’s system prompt or context.\n\n\nA malicious MCP server can craft its tool metadata (names, descriptions) to include hidden or overt instructions. These instructions can act as a prompt injection, effectively telling your LLM to behave in a certain way, reveal sensitive information, or perform malicious actions.\n\n\n\n\nCrucially, this attack can occur simply by connecting to a malicious server and listing its tools, even if your agent never explicitly decides to \nuse\n any of those tools.\n The mere exposure to the malicious metadata can be enough to compromise the agent’s behavior.\n\n\nMitigation:\n\n\n\n\nExtreme Caution with Untrusted Servers:\n Reiterate: \nDo not connect to MCP servers you do not fully trust.\n The risk of metadata injection makes this paramount.\n\n\n\n\n​\nStdio Transport Security\n\n\nStdio (Standard Input/Output) transport is typically used for local MCP servers running on the same machine as your CrewAI application.\n\n\n\n\nProcess Isolation\n: While generally safer as it doesn’t involve network exposure by default, ensure the script or command run by \nStdioServerParameters\n is from a trusted source and has appropriate file system permissions. A malicious Stdio server script could still harm your local system.\n\n\nInput Sanitization\n: If your Stdio server script takes complex inputs derived from agent interactions, ensure the script itself sanitizes these inputs to prevent command injection or other vulnerabilities within the script’s logic.\n\n\nResource Limits\n: Be mindful that a local Stdio server process consumes local resources (CPU, memory). Ensure it’s well-behaved and won’t exhaust system resources.\n\n\n\n\n​\nConfused Deputy Attacks\n\n\nThe \nConfused Deputy Problem\n is a classic security vulnerability that can manifest in MCP integrations, especially when an MCP server acts as a proxy to other third-party services (e.g., Google Calendar, GitHub) that use OAuth 2.0 for authorization.\n\n\nScenario:\n\n\n\n\nAn MCP server (let’s call it \nMCP-Proxy\n) allows your agent to interact with \nThirdPartyAPI\n.\n\n\nMCP-Proxy\n uses its own single, static \nclient_id\n when talking to \nThirdPartyAPI\n’s authorization server.\n\n\nYou, as the user, legitimately authorize \nMCP-Proxy\n to access \nThirdPartyAPI\n on your behalf. During this, \nThirdPartyAPI\n’s auth server might set a cookie in your browser indicating your consent for \nMCP-Proxy\n’s \nclient_id\n.\n\n\nAn attacker crafts a malicious link. This link initiates an OAuth flow with \nMCP-Proxy\n, but is designed to trick \nThirdPartyAPI\n’s auth server.\n\n\nIf you click this link, and \nThirdPartyAPI\n’s auth server sees your existing consent cookie for \nMCP-Proxy\n’s \nclient_id\n, it might \nskip\n asking for your consent again.\n\n\nMCP-Proxy\n might then be tricked into forwarding an authorization code (for \nThirdPartyAPI\n) to the attacker, or an MCP authorization code that the attacker can use to impersonate you to \nMCP-Proxy\n.\n\n\n\n\nMitigation (Primarily for MCP Server Developers):\n\n\n\n\nMCP proxy servers using static client IDs for downstream services \nmust\n obtain explicit user consent for \neach client application or agent\n connecting to them \nbefore\n initiating an OAuth flow with the third-party service. This means \nMCP-Proxy\n itself should show a consent screen.\n\n\n\n\nCrewAI User Implication:\n\n\n\n\nBe cautious if an MCP server redirects you for multiple OAuth authentications, especially if it seems unexpected or if the permissions requested are overly broad.\n\n\nPrefer MCP servers that clearly delineate their own identity versus the third-party services they might proxy.\n\n\n\n\n​\nRemote Transport Security (SSE & Streamable HTTP)\n\n\nWhen connecting to remote MCP servers via Server-Sent Events (SSE) or Streamable HTTP, standard web security practices are essential.\n\n\n​\nSSE Security Considerations\n\n\n​\na. DNS Rebinding Attacks (Especially for SSE)\n\n\n\n\nDNS rebinding allows an attacker-controlled website to bypass the same-origin policy and make requests to servers on the user’s local network (e.g., \nlocalhost\n) or intranet. This is particularly risky if you run an MCP server locally (e.g., for development) and an agent in a browser-like environment (though less common for typical CrewAI backend setups) or if the MCP server is on an internal network.\n\n\nMitigation Strategies for MCP Server Implementers:\n\n\n\n\nValidate \nOrigin\n and \nHost\n Headers\n: MCP servers (especially SSE ones) should validate the \nOrigin\n and/or \nHost\n HTTP headers to ensure requests are coming from expected domains/clients.\n\n\nBind to \nlocalhost\n (127.0.0.1)\n: When running MCP servers locally for development, bind them to \n127.0.0.1\n instead of \n0.0.0.0\n. This prevents them from being accessible from other machines on the network.\n\n\nAuthentication\n: Require authentication for all connections to your MCP server if it’s not intended for public anonymous access.\n\n\n\n\n​\nb. Use HTTPS\n\n\n\n\nEncrypt Data in Transit\n: Always use HTTPS (HTTP Secure) for the URLs of remote MCP servers. This encrypts the communication between your CrewAI application and the MCP server, protecting against eavesdropping and man-in-the-middle attacks. \nMCPServerAdapter\n will respect the scheme (\nhttp\n or \nhttps\n) provided in the URL.\n\n\n\n\n​\nc. Token Passthrough (Anti-Pattern)\n\n\nThis is primarily a concern for MCP server developers but understanding it helps in choosing secure servers.\n\n\n“Token passthrough” is when an MCP server accepts an access token from your CrewAI agent (which might be a token for a \ndifferent\n service, say \nServiceA\n) and simply passes it through to another downstream API (\nServiceB\n) without proper validation. Specifically, \nServiceB\n (or the MCP server itself) should only accept tokens that were explicitly issued \nfor them\n (i.e., the ‘audience’ claim in the token matches the server/service).\n\n\nRisks:\n\n\n\n\nBypasses security controls (like rate limiting or fine-grained permissions) on the MCP server or the downstream API.\n\n\nBreaks audit trails and accountability.\n\n\nAllows misuse of stolen tokens.\n\n\n\n\nMitigation (For MCP Server Developers):\n\n\n\n\nMCP servers \nMUST NOT\n accept tokens that were not explicitly issued for them. They must validate the token’s audience claim.\n\n\n\n\nCrewAI User Implication:\n\n\n\n\nWhile not directly controllable by the user, this highlights the importance of connecting to well-designed MCP servers that adhere to security best practices.\n\n\n\n\n​\nAuthentication and Authorization\n\n\n\n\nVerify Identity\n: If the MCP server provides sensitive tools or access to private data, it MUST implement strong authentication mechanisms to verify the identity of the client (your CrewAI application). This could involve API keys, OAuth tokens, or other standard methods.\n\n\nPrinciple of Least Privilege\n: Ensure the credentials used by \nMCPServerAdapter\n (if any) have only the necessary permissions to access the required tools.\n\n\n\n\n​\nd. Input Validation and Sanitization\n\n\n\n\nInput Validation is Critical\n: MCP servers \nmust\n rigorously validate all inputs received from agents \nbefore\n processing them or passing them to tools. This is a primary defense against many common vulnerabilities:\n\n\n\n\nCommand Injection:\n If a tool constructs shell commands, SQL queries, or other interpreted language statements based on input, the server must meticulously sanitize this input to prevent malicious commands from being injected and executed.\n\n\nPath Traversal:\n If a tool accesses files based on input parameters, the server must validate and sanitize these paths to prevent access to unauthorized files or directories (e.g., by blocking \n../\n sequences).\n\n\nData Type & Range Checks:\n Servers must ensure that input data conforms to the expected data types (e.g., string, number, boolean) and falls within acceptable ranges or adheres to defined formats (e.g., regex for URLs).\n\n\nJSON Schema Validation:\n All tool parameters should be strictly validated against their defined JSON schema. This helps catch malformed requests early.\n\n\n\n\n\n\nClient-Side Awareness\n: While server-side validation is paramount, as a CrewAI user, be mindful of the data your agents are constructed to send to MCP tools, especially if interacting with less-trusted or new MCP servers.\n\n\n\n\n​\ne. Rate Limiting and Resource Management\n\n\n\n\nPrevent Abuse\n: MCP servers should implement rate limiting to prevent abuse, whether intentional (Denial of Service attacks) or unintentional (e.g., a misconfigured agent making too many requests).\n\n\nClient-Side Retries\n: Implement sensible retry logic in your CrewAI tasks if transient network issues or server rate limits are expected, but avoid aggressive retries that could exacerbate server load.\n\n\n\n\n​\n4. Secure MCP Server Implementation Advice (For Developers)\n\n\nIf you are developing an MCP server that CrewAI agents might connect to, consider these best practices in addition to the points above:\n\n\n\n\nFollow Secure Coding Practices\n: Adhere to standard secure coding principles for your chosen language and framework (e.g., OWASP Top 10).\n\n\nPrinciple of Least Privilege\n: Ensure the process running the MCP server (especially for \nStdio\n) has only the minimum necessary permissions. Tools themselves should also operate with the least privilege required to perform their function.\n\n\nDependency Management\n: Keep all server-side dependencies, including operating system packages, language runtimes, and third-party libraries, up-to-date to patch known vulnerabilities. Use tools to scan for vulnerable dependencies.\n\n\nSecure Defaults\n: Design your server and its tools to be secure by default. For example, features that could be risky should be off by default or require explicit opt-in with clear warnings.\n\n\nAccess Control for Tools\n: Implement robust mechanisms to control which authenticated and authorized agents or users can access specific tools, especially those that are powerful, sensitive, or incur costs.\n\n\nSecure Error Handling\n: Servers should not expose detailed internal error messages, stack traces, or debugging information to the client, as these can reveal internal workings or potential vulnerabilities. Log errors comprehensively on the server-side for diagnostics.\n\n\nComprehensive Logging and Monitoring\n: Implement detailed logging of security-relevant events (e.g., authentication attempts, tool invocations, errors, authorization changes). Monitor these logs for suspicious activity or abuse patterns.\n\n\nAdherence to MCP Authorization Spec\n: If implementing authentication and authorization, strictly follow the \nMCP Authorization specification\n and relevant \nOAuth 2.0 security best practices\n.\n\n\nRegular Security Audits\n: If your MCP server handles sensitive data, performs critical operations, or is publicly exposed, consider periodic security audits by qualified professionals.\n\n\n\n\n​\n5. Further Reading\n\n\nFor more detailed information on MCP security, refer to the official documentation:\n\n\n\n\nMCP Transport Security\n\n\n\n\nBy understanding these security considerations and implementing best practices, you can safely leverage the power of MCP servers in your CrewAI projects.\nThese are by no means exhaustive, but they cover the most common and critical security concerns.\nThe threats will continue to evolve, so it’s important to stay informed and adapt your security measures accordingly.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nConnecting to Multiple MCP Servers\nTools Overview\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nRisks\n1. Trusting MCP Servers\n2. Secure Prompt Injection via Tool Metadata: The “Model Control Protocol” Risk\nStdio Transport Security\nConfused Deputy Attacks\nRemote Transport Security (SSE & Streamable HTTP)\nSSE Security Considerations\na. DNS Rebinding Attacks (Especially for SSE)\nb. Use HTTPS\nc. Token Passthrough (Anti-Pattern)\nAuthentication and Authorization\nd. Input Validation and Sanitization\ne. Rate Limiting and Resource Management\n4. Secure MCP Server Implementation Advice (For Developers)\n5. Further Reading" }, { "source": "https://docs.crewai.com/en/concepts/cli", "title": "CLI - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nCLI\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nCLI\nCopy page\nLearn how to use the CrewAI CLI to interact with CrewAI.\nSince release 0.140.0, CrewAI Enterprise started a process of migrating their login provider. As such, the authentication flow via CLI was updated. Users that use Google to login, or that created their account after July 3rd, 2025 will be unable to log in with older versions of the \ncrewai\n library.\n\n\n​\nOverview\n\n\nThe CrewAI CLI provides a set of commands to interact with CrewAI, allowing you to create, train, run, and manage crews & flows.\n\n\n​\nInstallation\n\n\nTo use the CrewAI CLI, make sure you have CrewAI installed:\n\n\nTerminal\nCopy\nAsk AI\npip\n install\n crewai\n\n\n\n\n​\nBasic Usage\n\n\nThe basic structure of a CrewAI CLI command is:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n [COMMAND] [OPTIONS] [ARGUMENTS]\n\n\n\n\n​\nAvailable Commands\n\n\n​\n1. Create\n\n\nCreate a new crew or flow.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n create\n [OPTIONS] TYPE NAME\n\n\n\n\n\n\nTYPE\n: Choose between “crew” or “flow”\n\n\nNAME\n: Name of the crew or flow\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n create\n crew\n my_new_crew\n\n\ncrewai\n create\n flow\n my_new_flow\n\n\n\n\n​\n2. Version\n\n\nShow the installed version of CrewAI.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n version\n [OPTIONS]\n\n\n\n\n\n\n--tools\n: (Optional) Show the installed version of CrewAI tools\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n version\n\n\ncrewai\n version\n --tools\n\n\n\n\n​\n3. Train\n\n\nTrain the crew for a specified number of iterations.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n train\n [OPTIONS]\n\n\n\n\n\n\n-n, --n_iterations INTEGER\n: Number of iterations to train the crew (default: 5)\n\n\n-f, --filename TEXT\n: Path to a custom file for training (default: “trained_agents_data.pkl”)\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n train\n -n\n 10\n -f\n my_training_data.pkl\n\n\n\n\n​\n4. Replay\n\n\nReplay the crew execution from a specific task.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n replay\n [OPTIONS]\n\n\n\n\n\n\n-t, --task_id TEXT\n: Replay the crew from this task ID, including all subsequent tasks\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n replay\n -t\n task_123456\n\n\n\n\n​\n5. Log-tasks-outputs\n\n\nRetrieve your latest crew.kickoff() task outputs.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n log-tasks-outputs\n\n\n\n\n​\n6. Reset-memories\n\n\nReset the crew memories (long, short, entity, latest_crew_kickoff_outputs).\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n reset-memories\n [OPTIONS]\n\n\n\n\n\n\n-l, --long\n: Reset LONG TERM memory\n\n\n-s, --short\n: Reset SHORT TERM memory\n\n\n-e, --entities\n: Reset ENTITIES memory\n\n\n-k, --kickoff-outputs\n: Reset LATEST KICKOFF TASK OUTPUTS\n\n\n-kn, --knowledge\n: Reset KNOWLEDGE storage\n\n\n-akn, --agent-knowledge\n: Reset AGENT KNOWLEDGE storage\n\n\n-a, --all\n: Reset ALL memories\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n reset-memories\n --long\n --short\n\n\ncrewai\n reset-memories\n --all\n\n\n\n\n​\n7. Test\n\n\nTest the crew and evaluate the results.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n test\n [OPTIONS]\n\n\n\n\n\n\n-n, --n_iterations INTEGER\n: Number of iterations to test the crew (default: 3)\n\n\n-m, --model TEXT\n: LLM Model to run the tests on the Crew (default: “gpt-4o-mini”)\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n test\n -n\n 5\n -m\n gpt-3.5-turbo\n\n\n\n\n​\n8. Run\n\n\nRun the crew or flow.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\nStarting from version 0.103.0, the \ncrewai run\n command can be used to run both standard crews and flows. For flows, it automatically detects the type from pyproject.toml and runs the appropriate command. This is now the recommended way to run both crews and flows.\n\n\nMake sure to run these commands from the directory where your CrewAI project is set up.\nSome commands may require additional configuration or setup within your project structure.\n\n\n​\n9. Chat\n\n\nStarting in version \n0.98.0\n, when you run the \ncrewai chat\n command, you start an interactive session with your crew. The AI assistant will guide you by asking for necessary inputs to execute the crew. Once all inputs are provided, the crew will execute its tasks.\n\n\nAfter receiving the results, you can continue interacting with the assistant for further instructions or questions.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n chat\n\n\n\n\nEnsure you execute these commands from your CrewAI project’s root directory.\n\n\nIMPORTANT: Set the \nchat_llm\n property in your \ncrew.py\n file to enable this command.\nCopy\nAsk AI\n@crew\n\n\ndef\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n chat_llm\n=\n\"gpt-4o\"\n, \n# LLM for chat orchestration\n\n\n )\n\n\n\n\n​\n10. Deploy\n\n\nDeploy the crew or flow to \nCrewAI Enterprise\n.\n\n\n\n\n\n\nAuthentication\n: You need to be authenticated to deploy to CrewAI Enterprise.\nYou can login or create an account with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n login\n\n\n\n\n\n\n\n\nCreate a deployment\n: Once you are authenticated, you can create a deployment for your crew or flow from the root of your localproject.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n create\n\n\n\n\n\n\nReads your local project configuration.\n\n\nPrompts you to confirm the environment variables (like \nOPENAI_API_KEY\n, \nSERPER_API_KEY\n) found locally. These will be securely stored with the deployment on the Enterprise platform. Ensure your sensitive keys are correctly configured locally (e.g., in a \n.env\n file) before running this.\n\n\n\n\n\n\n\n\n​\n11. Organization Management\n\n\nManage your CrewAI Enterprise organizations.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n [COMMAND] [OPTIONS]\n\n\n\n\n​\nCommands:\n\n\n\n\nlist\n: List all organizations you belong to\n\n\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n list\n\n\n\n\n\n\ncurrent\n: Display your currently active organization\n\n\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n current\n\n\n\n\n\n\nswitch\n: Switch to a specific organization\n\n\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n switch\n <\norganization_i\nd\n>\n\n\n\n\nYou must be authenticated to CrewAI Enterprise to use these organization management commands.\n\n\n\n\n\n\nCreate a deployment\n (continued):\n\n\n\n\nLinks the deployment to the corresponding remote GitHub repository (it usually detects this automatically).\n\n\n\n\n\n\n\n\nDeploy the Crew\n: Once you are authenticated, you can deploy your crew or flow to CrewAI Enterprise.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n push\n\n\n\n\n\n\nInitiates the deployment process on the CrewAI Enterprise platform.\n\n\nUpon successful initiation, it will output the Deployment created successfully! message along with the Deployment Name and a unique Deployment ID (UUID).\n\n\n\n\n\n\n\n\nDeployment Status\n: You can check the status of your deployment with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n status\n\n\n\n\nThis fetches the latest deployment status of your most recent deployment attempt (e.g., \nBuilding Images for Crew\n, \nDeploy Enqueued\n, \nOnline\n).\n\n\n\n\n\n\nDeployment Logs\n: You can check the logs of your deployment with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n logs\n\n\n\n\nThis streams the deployment logs to your terminal.\n\n\n\n\n\n\nList deployments\n: You can list all your deployments with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n list\n\n\n\n\nThis lists all your deployments.\n\n\n\n\n\n\nDelete a deployment\n: You can delete a deployment with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n remove\n\n\n\n\nThis deletes the deployment from the CrewAI Enterprise platform.\n\n\n\n\n\n\nHelp Command\n: You can get help with the CLI with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n --help\n\n\n\n\nThis shows the help message for the CrewAI Deploy CLI.\n\n\n\n\n\n\nWatch this video tutorial for a step-by-step demonstration of deploying your crew to \nCrewAI Enterprise\n using the CLI.\n\n\n\n\n​\n11. API Keys\n\n\nWhen running \ncrewai create crew\n command, the CLI will show you a list of available LLM providers to choose from, followed by model selection for your chosen provider.\n\n\nOnce you’ve selected an LLM provider and model, you will be prompted for API keys.\n\n\n​\nAvailable LLM Providers\n\n\nHere’s a list of the most popular LLM providers suggested by the CLI:\n\n\n\n\nOpenAI\n\n\nGroq\n\n\nAnthropic\n\n\nGoogle Gemini\n\n\nSambaNova\n\n\n\n\nWhen you select a provider, the CLI will then show you available models for that provider and prompt you to enter your API key.\n\n\n​\nOther Options\n\n\nIf you select “other”, you will be able to select from a list of LiteLLM supported providers.\n\n\nWhen you select a provider, the CLI will prompt you to enter the Key name and the API key.\n\n\nSee the following link for each provider’s key name:\n\n\n\n\nLiteLLM Providers\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTesting\nTools\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nInstallation\nBasic Usage\nAvailable Commands\n1. Create\n2. Version\n3. Train\n4. Replay\n5. Log-tasks-outputs\n6. Reset-memories\n7. Test\n8. Run\n9. Chat\n10. Deploy\n11. Organization Management\nCommands:\n11. API Keys\nAvailable LLM Providers\nOther Options\nCore Concepts\nCLI\nCopy page\nLearn how to use the CrewAI CLI to interact with CrewAI.\nSince release 0.140.0, CrewAI Enterprise started a process of migrating their login provider. As such, the authentication flow via CLI was updated. Users that use Google to login, or that created their account after July 3rd, 2025 will be unable to log in with older versions of the \ncrewai\n library.\n\n\n​\nOverview\n\n\nThe CrewAI CLI provides a set of commands to interact with CrewAI, allowing you to create, train, run, and manage crews & flows.\n\n\n​\nInstallation\n\n\nTo use the CrewAI CLI, make sure you have CrewAI installed:\n\n\nTerminal\nCopy\nAsk AI\npip\n install\n crewai\n\n\n\n\n​\nBasic Usage\n\n\nThe basic structure of a CrewAI CLI command is:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n [COMMAND] [OPTIONS] [ARGUMENTS]\n\n\n\n\n​\nAvailable Commands\n\n\n​\n1. Create\n\n\nCreate a new crew or flow.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n create\n [OPTIONS] TYPE NAME\n\n\n\n\n\n\nTYPE\n: Choose between “crew” or “flow”\n\n\nNAME\n: Name of the crew or flow\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n create\n crew\n my_new_crew\n\n\ncrewai\n create\n flow\n my_new_flow\n\n\n\n\n​\n2. Version\n\n\nShow the installed version of CrewAI.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n version\n [OPTIONS]\n\n\n\n\n\n\n--tools\n: (Optional) Show the installed version of CrewAI tools\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n version\n\n\ncrewai\n version\n --tools\n\n\n\n\n​\n3. Train\n\n\nTrain the crew for a specified number of iterations.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n train\n [OPTIONS]\n\n\n\n\n\n\n-n, --n_iterations INTEGER\n: Number of iterations to train the crew (default: 5)\n\n\n-f, --filename TEXT\n: Path to a custom file for training (default: “trained_agents_data.pkl”)\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n train\n -n\n 10\n -f\n my_training_data.pkl\n\n\n\n\n​\n4. Replay\n\n\nReplay the crew execution from a specific task.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n replay\n [OPTIONS]\n\n\n\n\n\n\n-t, --task_id TEXT\n: Replay the crew from this task ID, including all subsequent tasks\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n replay\n -t\n task_123456\n\n\n\n\n​\n5. Log-tasks-outputs\n\n\nRetrieve your latest crew.kickoff() task outputs.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n log-tasks-outputs\n\n\n\n\n​\n6. Reset-memories\n\n\nReset the crew memories (long, short, entity, latest_crew_kickoff_outputs).\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n reset-memories\n [OPTIONS]\n\n\n\n\n\n\n-l, --long\n: Reset LONG TERM memory\n\n\n-s, --short\n: Reset SHORT TERM memory\n\n\n-e, --entities\n: Reset ENTITIES memory\n\n\n-k, --kickoff-outputs\n: Reset LATEST KICKOFF TASK OUTPUTS\n\n\n-kn, --knowledge\n: Reset KNOWLEDGE storage\n\n\n-akn, --agent-knowledge\n: Reset AGENT KNOWLEDGE storage\n\n\n-a, --all\n: Reset ALL memories\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n reset-memories\n --long\n --short\n\n\ncrewai\n reset-memories\n --all\n\n\n\n\n​\n7. Test\n\n\nTest the crew and evaluate the results.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n test\n [OPTIONS]\n\n\n\n\n\n\n-n, --n_iterations INTEGER\n: Number of iterations to test the crew (default: 3)\n\n\n-m, --model TEXT\n: LLM Model to run the tests on the Crew (default: “gpt-4o-mini”)\n\n\n\n\nExample:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n test\n -n\n 5\n -m\n gpt-3.5-turbo\n\n\n\n\n​\n8. Run\n\n\nRun the crew or flow.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n run\n\n\n\n\nStarting from version 0.103.0, the \ncrewai run\n command can be used to run both standard crews and flows. For flows, it automatically detects the type from pyproject.toml and runs the appropriate command. This is now the recommended way to run both crews and flows.\n\n\nMake sure to run these commands from the directory where your CrewAI project is set up.\nSome commands may require additional configuration or setup within your project structure.\n\n\n​\n9. Chat\n\n\nStarting in version \n0.98.0\n, when you run the \ncrewai chat\n command, you start an interactive session with your crew. The AI assistant will guide you by asking for necessary inputs to execute the crew. Once all inputs are provided, the crew will execute its tasks.\n\n\nAfter receiving the results, you can continue interacting with the assistant for further instructions or questions.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n chat\n\n\n\n\nEnsure you execute these commands from your CrewAI project’s root directory.\n\n\nIMPORTANT: Set the \nchat_llm\n property in your \ncrew.py\n file to enable this command.\nCopy\nAsk AI\n@crew\n\n\ndef\n crew\n(\nself\n) -> Crew:\n\n\n return\n Crew(\n\n\n agents\n=\nself\n.agents,\n\n\n tasks\n=\nself\n.tasks,\n\n\n process\n=\nProcess.sequential,\n\n\n verbose\n=\nTrue\n,\n\n\n chat_llm\n=\n\"gpt-4o\"\n, \n# LLM for chat orchestration\n\n\n )\n\n\n\n\n​\n10. Deploy\n\n\nDeploy the crew or flow to \nCrewAI Enterprise\n.\n\n\n\n\n\n\nAuthentication\n: You need to be authenticated to deploy to CrewAI Enterprise.\nYou can login or create an account with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n login\n\n\n\n\n\n\n\n\nCreate a deployment\n: Once you are authenticated, you can create a deployment for your crew or flow from the root of your localproject.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n create\n\n\n\n\n\n\nReads your local project configuration.\n\n\nPrompts you to confirm the environment variables (like \nOPENAI_API_KEY\n, \nSERPER_API_KEY\n) found locally. These will be securely stored with the deployment on the Enterprise platform. Ensure your sensitive keys are correctly configured locally (e.g., in a \n.env\n file) before running this.\n\n\n\n\n\n\n\n\n​\n11. Organization Management\n\n\nManage your CrewAI Enterprise organizations.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n [COMMAND] [OPTIONS]\n\n\n\n\n​\nCommands:\n\n\n\n\nlist\n: List all organizations you belong to\n\n\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n list\n\n\n\n\n\n\ncurrent\n: Display your currently active organization\n\n\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n current\n\n\n\n\n\n\nswitch\n: Switch to a specific organization\n\n\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n org\n switch\n <\norganization_i\nd\n>\n\n\n\n\nYou must be authenticated to CrewAI Enterprise to use these organization management commands.\n\n\n\n\n\n\nCreate a deployment\n (continued):\n\n\n\n\nLinks the deployment to the corresponding remote GitHub repository (it usually detects this automatically).\n\n\n\n\n\n\n\n\nDeploy the Crew\n: Once you are authenticated, you can deploy your crew or flow to CrewAI Enterprise.\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n push\n\n\n\n\n\n\nInitiates the deployment process on the CrewAI Enterprise platform.\n\n\nUpon successful initiation, it will output the Deployment created successfully! message along with the Deployment Name and a unique Deployment ID (UUID).\n\n\n\n\n\n\n\n\nDeployment Status\n: You can check the status of your deployment with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n status\n\n\n\n\nThis fetches the latest deployment status of your most recent deployment attempt (e.g., \nBuilding Images for Crew\n, \nDeploy Enqueued\n, \nOnline\n).\n\n\n\n\n\n\nDeployment Logs\n: You can check the logs of your deployment with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n logs\n\n\n\n\nThis streams the deployment logs to your terminal.\n\n\n\n\n\n\nList deployments\n: You can list all your deployments with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n list\n\n\n\n\nThis lists all your deployments.\n\n\n\n\n\n\nDelete a deployment\n: You can delete a deployment with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n remove\n\n\n\n\nThis deletes the deployment from the CrewAI Enterprise platform.\n\n\n\n\n\n\nHelp Command\n: You can get help with the CLI with:\n\n\nTerminal\nCopy\nAsk AI\ncrewai\n deploy\n --help\n\n\n\n\nThis shows the help message for the CrewAI Deploy CLI.\n\n\n\n\n\n\nWatch this video tutorial for a step-by-step demonstration of deploying your crew to \nCrewAI Enterprise\n using the CLI.\n\n\n\n\n​\n11. API Keys\n\n\nWhen running \ncrewai create crew\n command, the CLI will show you a list of available LLM providers to choose from, followed by model selection for your chosen provider.\n\n\nOnce you’ve selected an LLM provider and model, you will be prompted for API keys.\n\n\n​\nAvailable LLM Providers\n\n\nHere’s a list of the most popular LLM providers suggested by the CLI:\n\n\n\n\nOpenAI\n\n\nGroq\n\n\nAnthropic\n\n\nGoogle Gemini\n\n\nSambaNova\n\n\n\n\nWhen you select a provider, the CLI will then show you available models for that provider and prompt you to enter your API key.\n\n\n​\nOther Options\n\n\nIf you select “other”, you will be able to select from a list of LiteLLM supported providers.\n\n\nWhen you select a provider, the CLI will prompt you to enter the Key name and the API key.\n\n\nSee the following link for each provider’s key name:\n\n\n\n\nLiteLLM Providers\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nTesting\nTools\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nInstallation\nBasic Usage\nAvailable Commands\n1. Create\n2. Version\n3. Train\n4. Replay\n5. Log-tasks-outputs\n6. Reset-memories\n7. Test\n8. Run\n9. Chat\n10. Deploy\n11. Organization Management\nCommands:\n11. API Keys\nAvailable LLM Providers\nOther Options" }, { "source": "https://docs.crewai.com/en/concepts/knowledge", "title": "Knowledge - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nCore Concepts\nKnowledge\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nCore Concepts\nKnowledge\nCopy page\nWhat is knowledge in CrewAI and how to use it.\n​\nOverview\n\n\nKnowledge in CrewAI is a powerful system that allows AI agents to access and utilize external information sources during their tasks.\nThink of it as giving your agents a reference library they can consult while working.\n\n\nKey benefits of using Knowledge:\n\n\nEnhance agents with domain-specific information\n\n\nSupport decisions with real-world data\n\n\nMaintain context across conversations\n\n\nGround responses in factual information\n\n\n\n\n​\nQuickstart Examples\n\n\nFor file-based Knowledge Sources, make sure to place your files in a \nknowledge\n directory at the root of your project.\nAlso, use relative paths from the \nknowledge\n directory when creating the source.\n\n\n​\nBasic String Knowledge Example\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process, \nLLM\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Create a knowledge source\n\n\ncontent \n=\n \"Users name is John. He is 30 years old and lives in San Francisco.\"\n\n\nstring_source \n=\n StringKnowledgeSource(\ncontent\n=\ncontent)\n\n\n\n\n# Create an LLM with a temperature of 0 to ensure deterministic outputs\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n)\n\n\n\n\n# Create an agent with the knowledge store\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"About User\"\n,\n\n\n goal\n=\n\"You know everything about the user.\"\n,\n\n\n backstory\n=\n\"You are a master at understanding people and their preferences.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\nllm,\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer the following questions about the user: \n{question}\n\"\n,\n\n\n expected_output\n=\n\"An answer to the question.\"\n,\n\n\n agent\n=\nagent,\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n knowledge_sources\n=\n[string_source], \n# Enable knowledge by adding the sources here\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff(\ninputs\n=\n{\n\"question\"\n: \n\"What city does John live in and how old is he?\"\n})\n\n\n\n\n​\nWeb Content Knowledge Example\n\n\nYou need to install \ndocling\n for the following example to work: \nuv add docling\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n, Agent, Crew, Process, Task\n\n\nfrom\n crewai.knowledge.source.crew_docling_source \nimport\n CrewDoclingSource\n\n\n\n\n# Create a knowledge source from web content\n\n\ncontent_source \n=\n CrewDoclingSource(\n\n\n file_paths\n=\n[\n\n\n \"https://lilianweng.github.io/posts/2024-11-28-reward-hacking\"\n,\n\n\n \"https://lilianweng.github.io/posts/2024-07-07-hallucination\"\n,\n\n\n ],\n\n\n)\n\n\n\n\n# Create an LLM with a temperature of 0 to ensure deterministic outputs\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n)\n\n\n\n\n# Create an agent with the knowledge store\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"About papers\"\n,\n\n\n goal\n=\n\"You know everything about the papers.\"\n,\n\n\n backstory\n=\n\"You are a master at understanding papers and their content.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\nllm,\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer the following questions about the papers: \n{question}\n\"\n,\n\n\n expected_output\n=\n\"An answer to the question.\"\n,\n\n\n agent\n=\nagent,\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n knowledge_sources\n=\n[content_source],\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff(\n\n\n inputs\n=\n{\n\"question\"\n: \n\"What is the reward hacking paper about? Be sure to provide sources.\"\n}\n\n\n)\n\n\n\n\n​\nSupported Knowledge Sources\n\n\nCrewAI supports various types of knowledge sources out of the box:\n\n\nText Sources\n\n\nRaw strings\n\n\nText files (.txt)\n\n\nPDF documents\n\n\nStructured Data\n\n\nCSV files\n\n\nExcel spreadsheets\n\n\nJSON documents\n\n\n\n\n​\nText File Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.text_file_knowledge_source \nimport\n TextFileKnowledgeSource\n\n\n\n\ntext_source \n=\n TextFileKnowledgeSource(\n\n\n file_paths\n=\n[\n\"document.txt\"\n, \n\"another.txt\"\n]\n\n\n)\n\n\n\n\n​\nPDF Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.pdf_knowledge_source \nimport\n PDFKnowledgeSource\n\n\n\n\npdf_source \n=\n PDFKnowledgeSource(\n\n\n file_paths\n=\n[\n\"document.pdf\"\n, \n\"another.pdf\"\n]\n\n\n)\n\n\n\n\n​\nCSV Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.csv_knowledge_source \nimport\n CSVKnowledgeSource\n\n\n\n\ncsv_source \n=\n CSVKnowledgeSource(\n\n\n file_paths\n=\n[\n\"data.csv\"\n]\n\n\n)\n\n\n\n\n​\nExcel Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.excel_knowledge_source \nimport\n ExcelKnowledgeSource\n\n\n\n\nexcel_source \n=\n ExcelKnowledgeSource(\n\n\n file_paths\n=\n[\n\"spreadsheet.xlsx\"\n]\n\n\n)\n\n\n\n\n​\nJSON Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.json_knowledge_source \nimport\n JSONKnowledgeSource\n\n\n\n\njson_source \n=\n JSONKnowledgeSource(\n\n\n file_paths\n=\n[\n\"data.json\"\n]\n\n\n)\n\n\n\n\nPlease ensure that you create the ./knowledge folder. All source files (e.g., .txt, .pdf, .xlsx, .json) should be placed in this folder for centralized management.\n\n\n​\nAgent vs Crew Knowledge: Complete Guide\n\n\nUnderstanding Knowledge Levels\n: CrewAI supports knowledge at both agent and crew levels. This section clarifies exactly how each works, when they’re initialized, and addresses common misconceptions about dependencies.\n\n\n​\nHow Knowledge Initialization Actually Works\n\n\nHere’s exactly what happens when you use knowledge:\n\n\n​\nAgent-Level Knowledge (Independent)\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Agent with its own knowledge - NO crew knowledge needed\n\n\nspecialist_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Specialized technical information for this agent only\"\n\n\n)\n\n\n\n\nspecialist_agent \n=\n Agent(\n\n\n role\n=\n\"Technical Specialist\"\n,\n\n\n goal\n=\n\"Provide technical expertise\"\n,\n\n\n backstory\n=\n\"Expert in specialized technical domains\"\n,\n\n\n knowledge_sources\n=\n[specialist_knowledge] \n# Agent-specific knowledge\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer technical questions\"\n,\n\n\n agent\n=\nspecialist_agent,\n\n\n expected_output\n=\n\"Technical answer\"\n\n\n)\n\n\n\n\n# No crew-level knowledge required\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[specialist_agent],\n\n\n tasks\n=\n[task]\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff() \n# Agent knowledge works independently\n\n\n\n\n​\nWhat Happens During \ncrew.kickoff()\n\n\nWhen you call \ncrew.kickoff()\n, here’s the exact sequence:\n\n\nCopy\nAsk AI\n# During kickoff\n\n\nfor\n agent \nin\n self\n.agents:\n\n\n agent.crew \n=\n self\n # Agent gets reference to crew\n\n\n agent.set_knowledge(\ncrew_embedder\n=\nself\n.embedder) \n# Agent knowledge initialized\n\n\n agent.create_agent_executor()\n\n\n\n\n​\nStorage Independence\n\n\nEach knowledge level uses independent storage collections:\n\n\nCopy\nAsk AI\n# Agent knowledge storage\n\n\nagent_collection_name \n=\n agent.role \n# e.g., \"Technical Specialist\"\n\n\n\n\n# Crew knowledge storage \n\n\ncrew_collection_name \n=\n \"crew\"\n\n\n\n\n# Both stored in same ChromaDB instance but different collections\n\n\n# Path: ~/.local/share/CrewAI/{project}/knowledge/\n\n\n# ├── crew/ # Crew knowledge collection\n\n\n# ├── Technical Specialist/ # Agent knowledge collection\n\n\n# └── Another Agent Role/ # Another agent's collection\n\n\n\n\n​\nComplete Working Examples\n\n\n​\nExample 1: Agent-Only Knowledge\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Agent-specific knowledge\n\n\nagent_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Agent-specific information that only this agent needs\"\n\n\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Specialist\"\n,\n\n\n goal\n=\n\"Use specialized knowledge\"\n,\n\n\n backstory\n=\n\"Expert with specific knowledge\"\n,\n\n\n knowledge_sources\n=\n[agent_knowledge],\n\n\n embedder\n=\n{ \n# Agent can have its own embedder\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer using your specialized knowledge\"\n,\n\n\n agent\n=\nagent,\n\n\n expected_output\n=\n\"Answer based on agent knowledge\"\n\n\n)\n\n\n\n\n# No crew knowledge needed\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[task])\n\n\nresult \n=\n crew.kickoff() \n# Works perfectly\n\n\n\n\n​\nExample 2: Both Agent and Crew Knowledge\n\n\nCopy\nAsk AI\n# Crew-wide knowledge (shared by all agents)\n\n\ncrew_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Company policies and general information for all agents\"\n\n\n)\n\n\n\n\n# Agent-specific knowledge\n\n\nspecialist_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Technical specifications only the specialist needs\"\n\n\n)\n\n\n\n\nspecialist \n=\n Agent(\n\n\n role\n=\n\"Technical Specialist\"\n,\n\n\n goal\n=\n\"Provide technical expertise\"\n,\n\n\n backstory\n=\n\"Technical expert\"\n,\n\n\n knowledge_sources\n=\n[specialist_knowledge] \n# Agent-specific\n\n\n)\n\n\n\n\ngeneralist \n=\n Agent(\n\n\n role\n=\n\"General Assistant\"\n, \n\n\n goal\n=\n\"Provide general assistance\"\n,\n\n\n backstory\n=\n\"General helper\"\n\n\n # No agent-specific knowledge\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[specialist, generalist],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[crew_knowledge] \n# Crew-wide knowledge\n\n\n)\n\n\n\n\n# Result:\n\n\n# - specialist gets: crew_knowledge + specialist_knowledge\n\n\n# - generalist gets: crew_knowledge only\n\n\n\n\n​\nExample 3: Multiple Agents with Different Knowledge\n\n\nCopy\nAsk AI\n# Different knowledge for different agents\n\n\nsales_knowledge \n=\n StringKnowledgeSource(\ncontent\n=\n\"Sales procedures and pricing\"\n)\n\n\ntech_knowledge \n=\n StringKnowledgeSource(\ncontent\n=\n\"Technical documentation\"\n)\n\n\nsupport_knowledge \n=\n StringKnowledgeSource(\ncontent\n=\n\"Support procedures\"\n)\n\n\n\n\nsales_agent \n=\n Agent(\n\n\n role\n=\n\"Sales Representative\"\n,\n\n\n knowledge_sources\n=\n[sales_knowledge],\n\n\n embedder\n=\n{\n\"provider\"\n: \n\"openai\"\n, \n\"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}}\n\n\n)\n\n\n\n\ntech_agent \n=\n Agent(\n\n\n role\n=\n\"Technical Expert\"\n, \n\n\n knowledge_sources\n=\n[tech_knowledge],\n\n\n embedder\n=\n{\n\"provider\"\n: \n\"ollama\"\n, \n\"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}}\n\n\n)\n\n\n\n\nsupport_agent \n=\n Agent(\n\n\n role\n=\n\"Support Specialist\"\n,\n\n\n knowledge_sources\n=\n[support_knowledge]\n\n\n # Will use crew embedder as fallback\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[sales_agent, tech_agent, support_agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n embedder\n=\n{ \n# Fallback embedder for agents without their own\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-004\"\n}\n\n\n }\n\n\n)\n\n\n\n\n# Each agent gets only their specific knowledge\n\n\n# Each can use different embedding providers\n\n\n\n\nUnlike retrieval from a vector database using a tool, agents preloaded with knowledge will not need a retrieval persona or task.\nSimply add the relevant knowledge sources your agent or crew needs to function.\nKnowledge sources can be added at the agent or crew level.\nCrew level knowledge sources will be used by \nall agents\n in the crew.\nAgent level knowledge sources will be used by the \nspecific agent\n that is preloaded with the knowledge.\n\n\n​\nKnowledge Configuration\n\n\nYou can configure the knowledge configuration for the crew or agent.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.knowledge.knowledge_config \nimport\n KnowledgeConfig\n\n\n\n\nknowledge_config \n=\n KnowledgeConfig(\nresults_limit\n=\n10\n, \nscore_threshold\n=\n0.5\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n ...\n\n\n knowledge_config\n=\nknowledge_config\n\n\n)\n\n\n\n\nresults_limit\n: is the number of relevant documents to return. Default is 3.\n\nscore_threshold\n: is the minimum score for a document to be considered relevant. Default is 0.35.\n\n\n​\nSupported Knowledge Parameters\n\n\n​\nsources\nList[BaseKnowledgeSource]\nrequired\nList of knowledge sources that provide content to be stored and queried. Can include PDF, CSV, Excel, JSON, text files, or string content.\n\n\n​\ncollection_name\nstr\nName of the collection where the knowledge will be stored. Used to identify different sets of knowledge. Defaults to “knowledge” if not provided.\n\n\n​\nstorage\nOptional[KnowledgeStorage]\nCustom storage configuration for managing how the knowledge is stored and retrieved. If not provided, a default storage will be created.\n\n\n​\nKnowledge Storage Transparency\n\n\nUnderstanding Knowledge Storage\n: CrewAI automatically stores knowledge sources in platform-specific directories using ChromaDB for vector storage. Understanding these locations and defaults helps with production deployments, debugging, and storage management.\n\n\n​\nWhere CrewAI Stores Knowledge Files\n\n\nBy default, CrewAI uses the same storage system as memory, storing knowledge in platform-specific directories:\n\n\n​\nDefault Storage Locations by Platform\n\n\nmacOS:\n\n\nCopy\nAsk AI\n~/Library/Application Support/CrewAI/{project_name}/\n\n\n└── knowledge/ # Knowledge ChromaDB files\n\n\n ├── chroma.sqlite3 # ChromaDB metadata\n\n\n ├── {collection_id}/ # Vector embeddings\n\n\n └── knowledge_{collection}/ # Named collections\n\n\n\n\nLinux:\n\n\nCopy\nAsk AI\n~/.local/share/CrewAI/{project_name}/\n\n\n└── knowledge/\n\n\n ├── chroma.sqlite3\n\n\n ├── {collection_id}/\n\n\n └── knowledge_{collection}/\n\n\n\n\nWindows:\n\n\nCopy\nAsk AI\nC:\\Users\\{username}\\AppData\\Local\\CrewAI\\{project_name}\\\n\n\n└── knowledge\\\n\n\n ├── chroma.sqlite3\n\n\n ├── {collection_id}\\\n\n\n └── knowledge_{collection}\\\n\n\n\n\n​\nFinding Your Knowledge Storage Location\n\n\nTo see exactly where CrewAI is storing your knowledge files:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\nimport\n os\n\n\n\n\n# Get the knowledge storage path\n\n\nknowledge_path \n=\n os.path.join(db_storage_path(), \n\"knowledge\"\n)\n\n\nprint\n(\nf\n\"Knowledge storage location: \n{\nknowledge_path\n}\n\"\n)\n\n\n\n\n# List knowledge collections and files\n\n\nif\n os.path.exists(knowledge_path):\n\n\n print\n(\n\"\n\\n\nKnowledge storage contents:\"\n)\n\n\n for\n item \nin\n os.listdir(knowledge_path):\n\n\n item_path \n=\n os.path.join(knowledge_path, item)\n\n\n if\n os.path.isdir(item_path):\n\n\n print\n(\nf\n\"📁 Collection: \n{\nitem\n}\n/\"\n)\n\n\n # Show collection contents\n\n\n try\n:\n\n\n for\n subitem \nin\n os.listdir(item_path):\n\n\n print\n(\nf\n\" └── \n{\nsubitem\n}\n\"\n)\n\n\n except\n PermissionError\n:\n\n\n print\n(\nf\n\" └── (permission denied)\"\n)\n\n\n else\n:\n\n\n print\n(\nf\n\"📄 \n{\nitem\n}\n\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No knowledge storage found yet.\"\n)\n\n\n\n\n​\nControlling Knowledge Storage Locations\n\n\n​\nOption 1: Environment Variable (Recommended)\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Set custom storage location for all CrewAI data\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n \"./my_project_storage\"\n\n\n\n\n# All knowledge will now be stored in ./my_project_storage/knowledge/\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[\n...\n]\n\n\n)\n\n\n\n\n​\nOption 2: Custom Knowledge Storage\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.storage.knowledge_storage \nimport\n KnowledgeStorage\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Create custom storage with specific embedder\n\n\ncustom_storage \n=\n KnowledgeStorage(\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n },\n\n\n collection_name\n=\n\"my_custom_knowledge\"\n\n\n)\n\n\n\n\n# Use with knowledge sources\n\n\nknowledge_source \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Your knowledge content here\"\n\n\n)\n\n\nknowledge_source.storage \n=\n custom_storage\n\n\n\n\n​\nOption 3: Project-Specific Knowledge Storage\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n pathlib \nimport\n Path\n\n\n\n\n# Store knowledge in project directory\n\n\nproject_root \n=\n Path(\n__file__\n).parent\n\n\nknowledge_dir \n=\n project_root \n/\n \"knowledge_storage\"\n\n\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n str\n(knowledge_dir)\n\n\n\n\n# Now all knowledge will be stored in your project directory\n\n\n\n\n​\nDefault Embedding Provider Behavior\n\n\nDefault Embedding Provider\n: CrewAI defaults to OpenAI embeddings (\ntext-embedding-3-small\n) for knowledge storage, even when using different LLM providers. You can easily customize this to match your setup.\n\n\n​\nUnderstanding Default Behavior\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, \nLLM\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# When using Claude as your LLM...\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Research topics\"\n,\n\n\n backstory\n=\n\"Expert researcher\"\n,\n\n\n llm\n=\nLLM(\nprovider\n=\n\"anthropic\"\n, \nmodel\n=\n\"claude-3-sonnet\"\n) \n# Using Claude\n\n\n)\n\n\n\n\n# CrewAI will still use OpenAI embeddings by default for knowledge\n\n\n# This ensures consistency but may not match your LLM provider preference\n\n\nknowledge_source \n=\n StringKnowledgeSource(\ncontent\n=\n\"Research data...\"\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[knowledge_source]\n\n\n # Default: Uses OpenAI embeddings even with Claude LLM\n\n\n)\n\n\n\n\n​\nCustomizing Knowledge Embedding Providers\n\n\nCopy\nAsk AI\n# Option 1: Use Voyage AI (recommended by Anthropic for Claude users)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"voyageai\"\n, \n# Recommended for Claude users\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-voyage-api-key\"\n,\n\n\n \"model\"\n: \n\"voyage-3\"\n # or \"voyage-3-large\" for best quality\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Option 2: Use local embeddings (no external API calls)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"mxbai-embed-large\"\n,\n\n\n \"url\"\n: \n\"http://localhost:11434/api/embeddings\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Option 3: Agent-level embedding customization\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Research topics\"\n,\n\n\n backstory\n=\n\"Expert researcher\"\n,\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"models/text-embedding-004\"\n,\n\n\n \"api_key\"\n: \n\"your-google-key\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nConfiguring Azure OpenAI Embeddings\n\n\nWhen using Azure OpenAI embeddings:\n\n\n\n\nMake sure you deploy the embedding model in Azure platform first\n\n\nThen you need to use the following configuration:\n\n\n\n\nCopy\nAsk AI\nagent \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Research topics\"\n,\n\n\n backstory\n=\n\"Expert researcher\"\n,\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"azure\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-azure-api-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-ada-002\"\n, \n# change to the model you are using and is deployed in Azure\n\n\n \"api_base\"\n: \n\"https://your-azure-endpoint.openai.azure.com/\"\n,\n\n\n \"api_version\"\n: \n\"2024-02-01\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAdvanced Features\n\n\n​\nQuery Rewriting\n\n\nCrewAI implements an intelligent query rewriting mechanism to optimize knowledge retrieval. When an agent needs to search through knowledge sources, the raw task prompt is automatically transformed into a more effective search query.\n\n\n​\nHow Query Rewriting Works\n\n\n\n\nWhen an agent executes a task with knowledge sources available, the \n_get_knowledge_search_query\n method is triggered\n\n\nThe agent’s LLM is used to transform the original task prompt into an optimized search query\n\n\nThis optimized query is then used to retrieve relevant information from knowledge sources\n\n\n\n\n​\nBenefits of Query Rewriting\n\n\nImproved Retrieval Accuracy\nBy focusing on key concepts and removing irrelevant content, query rewriting helps retrieve more relevant information.\nContext Awareness\nThe rewritten queries are designed to be more specific and context-aware for vector database retrieval.\n\n\n​\nExample\n\n\nCopy\nAsk AI\n# Original task prompt\n\n\ntask_prompt \n=\n \"Answer the following questions about the user's favorite movies: What movie did John watch last week? Format your answer in JSON.\"\n\n\n\n\n# Behind the scenes, this might be rewritten as:\n\n\nrewritten_query \n=\n \"What movies did John watch last week?\"\n\n\n\n\nThe rewritten query is more focused on the core information need and removes irrelevant instructions about output formatting.\n\n\nThis mechanism is fully automatic and requires no configuration from users. The agent’s LLM is used to perform the query rewriting, so using a more capable LLM can improve the quality of rewritten queries.\n\n\n​\nKnowledge Events\n\n\nCrewAI emits events during the knowledge retrieval process that you can listen for using the event system. These events allow you to monitor, debug, and analyze how knowledge is being retrieved and used by your agents.\n\n\n​\nAvailable Knowledge Events\n\n\n\n\nKnowledgeRetrievalStartedEvent\n: Emitted when an agent starts retrieving knowledge from sources\n\n\nKnowledgeRetrievalCompletedEvent\n: Emitted when knowledge retrieval is completed, including the query used and the retrieved content\n\n\nKnowledgeQueryStartedEvent\n: Emitted when a query to knowledge sources begins\n\n\nKnowledgeQueryCompletedEvent\n: Emitted when a query completes successfully\n\n\nKnowledgeQueryFailedEvent\n: Emitted when a query to knowledge sources fails\n\n\nKnowledgeSearchQueryFailedEvent\n: Emitted when a search query fails\n\n\n\n\n​\nExample: Monitoring Knowledge Retrieval\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n (\n\n\n KnowledgeRetrievalStartedEvent,\n\n\n KnowledgeRetrievalCompletedEvent,\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n KnowledgeMonitorListener\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(KnowledgeRetrievalStartedEvent)\n\n\n def\n on_knowledge_retrieval_started\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Agent '\n{\nevent.agent.role\n}\n' started retrieving knowledge\"\n)\n\n\n \n\n\n @crewai_event_bus.on\n(KnowledgeRetrievalCompletedEvent)\n\n\n def\n on_knowledge_retrieval_completed\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Agent '\n{\nevent.agent.role\n}\n' completed knowledge retrieval\"\n)\n\n\n print\n(\nf\n\"Query: \n{\nevent.query\n}\n\"\n)\n\n\n print\n(\nf\n\"Retrieved \n{\nlen\n(event.retrieved_knowledge)\n}\n knowledge chunks\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nknowledge_monitor \n=\n KnowledgeMonitorListener()\n\n\n\n\nFor more information on using events, see the \nEvent Listeners\n documentation.\n\n\n​\nCustom Knowledge Sources\n\n\nCrewAI allows you to create custom knowledge sources for any type of data by extending the \nBaseKnowledgeSource\n class. Let’s create a practical example that fetches and processes space news articles.\n\n\n​\nSpace News Knowledge Source Example\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process, \nLLM\n\n\nfrom\n crewai.knowledge.source.base_knowledge_source \nimport\n BaseKnowledgeSource\n\n\nimport\n requests\n\n\nfrom\n datetime \nimport\n datetime\n\n\nfrom\n typing \nimport\n Dict, Any\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nclass\n SpaceNewsKnowledgeSource\n(\nBaseKnowledgeSource\n):\n\n\n \"\"\"Knowledge source that fetches data from Space News API.\"\"\"\n\n\n\n\n api_endpoint: \nstr\n =\n Field(\ndescription\n=\n\"API endpoint URL\"\n)\n\n\n limit: \nint\n =\n Field(\ndefault\n=\n10\n, \ndescription\n=\n\"Number of articles to fetch\"\n)\n\n\n\n\n def\n load_content\n(\nself\n) -> Dict[Any, \nstr\n]:\n\n\n \"\"\"Fetch and format space news articles.\"\"\"\n\n\n try\n:\n\n\n response \n=\n requests.get(\n\n\n f\n\"\n{\nself\n.api_endpoint\n}\n?limit=\n{\nself\n.limit\n}\n\"\n\n\n )\n\n\n response.raise_for_status()\n\n\n\n\n data \n=\n response.json()\n\n\n articles \n=\n data.get(\n'results'\n, [])\n\n\n\n\n formatted_data \n=\n self\n.validate_content(articles)\n\n\n return\n {\nself\n.api_endpoint: formatted_data}\n\n\n except\n Exception\n as\n e:\n\n\n raise\n ValueError\n(\nf\n\"Failed to fetch space news: \n{\nstr\n(e)\n}\n\"\n)\n\n\n\n\n def\n validate_content\n(\nself\n, \narticles\n: \nlist\n) -> \nstr\n:\n\n\n \"\"\"Format articles into readable text.\"\"\"\n\n\n formatted \n=\n \"Space News Articles:\n\\n\\n\n\"\n\n\n for\n article \nin\n articles:\n\n\n formatted \n+=\n f\n\"\"\"\n\n\n Title: \n{\narticle[\n'title'\n]\n}\n\n\n Published: \n{\narticle[\n'published_at'\n]\n}\n\n\n Summary: \n{\narticle[\n'summary'\n]\n}\n\n\n News Site: \n{\narticle[\n'news_site'\n]\n}\n\n\n URL: \n{\narticle[\n'url'\n]\n}\n\n\n -------------------\"\"\"\n\n\n return\n formatted\n\n\n\n\n def\n add\n(\nself\n) -> \nNone\n:\n\n\n \"\"\"Process and store the articles.\"\"\"\n\n\n content \n=\n self\n.load_content()\n\n\n for\n _, text \nin\n content.items():\n\n\n chunks \n=\n self\n._chunk_text(text)\n\n\n self\n.chunks.extend(chunks)\n\n\n\n\n self\n._save_documents()\n\n\n\n\n# Create knowledge source\n\n\nrecent_news \n=\n SpaceNewsKnowledgeSource(\n\n\n api_endpoint\n=\n\"https://api.spaceflightnewsapi.net/v4/articles\"\n,\n\n\n limit\n=\n10\n,\n\n\n)\n\n\n\n\n# Create specialized agent\n\n\nspace_analyst \n=\n Agent(\n\n\n role\n=\n\"Space News Analyst\"\n,\n\n\n goal\n=\n\"Answer questions about space news accurately and comprehensively\"\n,\n\n\n backstory\n=\n\"\"\"You are a space industry analyst with expertise in space exploration,\n\n\n satellite technology, and space industry trends. You excel at answering questions\n\n\n about space news and providing detailed, accurate information.\"\"\"\n,\n\n\n knowledge_sources\n=\n[recent_news],\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4\"\n, \ntemperature\n=\n0.0\n)\n\n\n)\n\n\n\n\n# Create task that handles user questions\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n\"Answer this question about space news: \n{user_question}\n\"\n,\n\n\n expected_output\n=\n\"A detailed answer based on the recent space news articles\"\n,\n\n\n agent\n=\nspace_analyst\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[space_analyst],\n\n\n tasks\n=\n[analysis_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Example usage\n\n\nresult \n=\n crew.kickoff(\n\n\n inputs\n=\n{\n\"user_question\"\n: \n\"What are the latest developments in space exploration?\"\n}\n\n\n)\n\n\n\n\n​\nDebugging and Troubleshooting\n\n\n​\nDebugging Knowledge Issues\n\n\n​\nCheck Agent Knowledge Initialization\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\nknowledge_source \n=\n StringKnowledgeSource(\ncontent\n=\n\"Test knowledge\"\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Test Agent\"\n,\n\n\n goal\n=\n\"Test knowledge\"\n,\n\n\n backstory\n=\n\"Testing\"\n,\n\n\n knowledge_sources\n=\n[knowledge_source]\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[Task(\n...\n)])\n\n\n\n\n# Before kickoff - knowledge not initialized\n\n\nprint\n(\nf\n\"Before kickoff - Agent knowledge: \n{\ngetattr\n(agent, \n'knowledge'\n, \nNone\n)\n}\n\"\n)\n\n\n\n\ncrew.kickoff()\n\n\n\n\n# After kickoff - knowledge initialized\n\n\nprint\n(\nf\n\"After kickoff - Agent knowledge: \n{\nagent.knowledge\n}\n\"\n)\n\n\nprint\n(\nf\n\"Agent knowledge collection: \n{\nagent.knowledge.storage.collection_name\n}\n\"\n)\n\n\nprint\n(\nf\n\"Number of sources: \n{\nlen\n(agent.knowledge.sources)\n}\n\"\n)\n\n\n\n\n​\nVerify Knowledge Storage Locations\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\n# Check storage structure\n\n\nstorage_path \n=\n db_storage_path()\n\n\nknowledge_path \n=\n os.path.join(storage_path, \n\"knowledge\"\n)\n\n\n\n\nif\n os.path.exists(knowledge_path):\n\n\n print\n(\n\"Knowledge collections found:\"\n)\n\n\n for\n collection \nin\n os.listdir(knowledge_path):\n\n\n collection_path \n=\n os.path.join(knowledge_path, collection)\n\n\n if\n os.path.isdir(collection_path):\n\n\n print\n(\nf\n\" - \n{\ncollection\n}\n/\"\n)\n\n\n # Show collection contents\n\n\n for\n item \nin\n os.listdir(collection_path):\n\n\n print\n(\nf\n\" └── \n{\nitem\n}\n\"\n)\n\n\n\n\n​\nTest Knowledge Retrieval\n\n\nCopy\nAsk AI\n# Test agent knowledge retrieval\n\n\nif\n hasattr\n(agent, \n'knowledge'\n) \nand\n agent.knowledge:\n\n\n test_query \n=\n [\n\"test query\"\n]\n\n\n results \n=\n agent.knowledge.query(test_query)\n\n\n print\n(\nf\n\"Agent knowledge results: \n{\nlen\n(results)\n}\n documents found\"\n)\n\n\n \n\n\n # Test crew knowledge retrieval (if exists)\n\n\n if\n hasattr\n(crew, \n'knowledge'\n) \nand\n crew.knowledge:\n\n\n crew_results \n=\n crew.query_knowledge(test_query)\n\n\n print\n(\nf\n\"Crew knowledge results: \n{\nlen\n(crew_results)\n}\n documents found\"\n)\n\n\n\n\n​\nInspect Knowledge Collections\n\n\nCopy\nAsk AI\nimport\n chromadb\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\nimport\n os\n\n\n\n\n# Connect to CrewAI's knowledge ChromaDB\n\n\nknowledge_path \n=\n os.path.join(db_storage_path(), \n\"knowledge\"\n)\n\n\n\n\nif\n os.path.exists(knowledge_path):\n\n\n client \n=\n chromadb.PersistentClient(\npath\n=\nknowledge_path)\n\n\n collections \n=\n client.list_collections()\n\n\n \n\n\n print\n(\n\"Knowledge Collections:\"\n)\n\n\n for\n collection \nin\n collections:\n\n\n print\n(\nf\n\" - \n{\ncollection.name\n}\n: \n{\ncollection.count()\n}\n documents\"\n)\n\n\n \n\n\n # Sample a few documents to verify content\n\n\n if\n collection.count() \n>\n 0\n:\n\n\n sample \n=\n collection.peek(\nlimit\n=\n2\n)\n\n\n print\n(\nf\n\" Sample content: \n{\nsample[\n'documents'\n][\n0\n][:\n100\n]\n}\n...\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No knowledge storage found\"\n)\n\n\n\n\n​\nCheck Knowledge Processing\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Create a test knowledge source\n\n\ntest_source \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Test knowledge content for debugging\"\n,\n\n\n chunk_size\n=\n100\n, \n# Small chunks for testing\n\n\n chunk_overlap\n=\n20\n\n\n)\n\n\n\n\n# Check chunking behavior\n\n\nprint\n(\nf\n\"Original content length: \n{\nlen\n(test_source.content)\n}\n\"\n)\n\n\nprint\n(\nf\n\"Chunk size: \n{\ntest_source.chunk_size\n}\n\"\n)\n\n\nprint\n(\nf\n\"Chunk overlap: \n{\ntest_source.chunk_overlap\n}\n\"\n)\n\n\n\n\n# Process and inspect chunks\n\n\ntest_source.add()\n\n\nprint\n(\nf\n\"Number of chunks created: \n{\nlen\n(test_source.chunks)\n}\n\"\n)\n\n\nfor\n i, chunk \nin\n enumerate\n(test_source.chunks[:\n3\n]): \n# Show first 3 chunks\n\n\n print\n(\nf\n\"Chunk \n{\ni\n+\n1\n}\n: \n{\nchunk[:\n50\n]\n}\n...\"\n)\n\n\n\n\n​\nCommon Knowledge Storage Issues\n\n\n“File not found” errors:\n\n\nCopy\nAsk AI\n# Ensure files are in the correct location\n\n\nfrom\n crewai.utilities.constants \nimport\n KNOWLEDGE_DIRECTORY\n\n\nimport\n os\n\n\n\n\nknowledge_dir \n=\n KNOWLEDGE_DIRECTORY\n # Usually \"knowledge\"\n\n\nfile_path \n=\n os.path.join(knowledge_dir, \n\"your_file.pdf\"\n)\n\n\n\n\nif\n not\n os.path.exists(file_path):\n\n\n print\n(\nf\n\"File not found: \n{\nfile_path\n}\n\"\n)\n\n\n print\n(\nf\n\"Current working directory: \n{\nos.getcwd()\n}\n\"\n)\n\n\n print\n(\nf\n\"Expected knowledge directory: \n{\nos.path.abspath(knowledge_dir)\n}\n\"\n)\n\n\n\n\n“Embedding dimension mismatch” errors:\n\n\nCopy\nAsk AI\n# This happens when switching embedding providers\n\n\n# Reset knowledge storage to clear old embeddings\n\n\ncrew.reset_memories(\ncommand_type\n=\n'knowledge'\n)\n\n\n\n\n# Or use consistent embedding providers\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[\n...\n],\n\n\n embedder\n=\n{\n\"provider\"\n: \n\"openai\"\n, \n\"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}}\n\n\n)\n\n\n\n\n“ChromaDB permission denied” errors:\n\n\nCopy\nAsk AI\n# Fix storage permissions\n\n\nchmod\n -R\n 755\n ~/.local/share/CrewAI/\n\n\n\n\nKnowledge not persisting between runs:\n\n\nCopy\nAsk AI\n# Verify storage location consistency\n\n\nimport\n os\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\nprint\n(\n\"CREWAI_STORAGE_DIR:\"\n, os.getenv(\n\"CREWAI_STORAGE_DIR\"\n))\n\n\nprint\n(\n\"Computed storage path:\"\n, db_storage_path())\n\n\nprint\n(\n\"Knowledge path:\"\n, os.path.join(db_storage_path(), \n\"knowledge\"\n))\n\n\n\n\n​\nKnowledge Reset Commands\n\n\nCopy\nAsk AI\n# Reset only agent-specific knowledge\n\n\ncrew.reset_memories(\ncommand_type\n=\n'agent_knowledge'\n)\n\n\n\n\n# Reset both crew and agent knowledge \n\n\ncrew.reset_memories(\ncommand_type\n=\n'knowledge'\n)\n\n\n\n\n# CLI commands\n\n\n# crewai reset-memories --agent-knowledge # Agent knowledge only\n\n\n# crewai reset-memories --knowledge # All knowledge\n\n\n\n\n​\nClearing Knowledge\n\n\nIf you need to clear the knowledge stored in CrewAI, you can use the \ncrewai reset-memories\n command with the \n--knowledge\n option.\n\n\nCommand\nCopy\nAsk AI\ncrewai\n reset-memories\n --knowledge\n\n\n\n\nThis is useful when you’ve updated your knowledge sources and want to ensure that the agents are using the most recent information.\n\n\n​\nBest Practices\n\n\nContent Organization\n\n\nKeep chunk sizes appropriate for your content type\n\n\nConsider content overlap for context preservation\n\n\nOrganize related information into separate knowledge sources\n\n\nPerformance Tips\n\n\nAdjust chunk sizes based on content complexity\n\n\nConfigure appropriate embedding models\n\n\nConsider using local embedding providers for faster processing\n\n\nOne Time Knowledge\n\n\nWith the typical file structure provided by CrewAI, knowledge sources are embedded every time the kickoff is triggered.\n\n\nIf the knowledge sources are large, this leads to inefficiency and increased latency, as the same data is embedded each time.\n\n\nTo resolve this, directly initialize the knowledge parameter instead of the knowledge_sources parameter.\n\n\nLink to the issue to get complete idea \nGithub Issue\n\n\nKnowledge Management\n\n\nUse agent-level knowledge for role-specific information\n\n\nUse crew-level knowledge for shared information all agents need\n\n\nSet embedders at agent level if you need different embedding strategies\n\n\nUse consistent collection naming by keeping agent roles descriptive\n\n\nTest knowledge initialization by checking agent.knowledge after kickoff\n\n\nMonitor storage locations to understand where knowledge is stored\n\n\nReset knowledge appropriately using the correct command types\n\n\nProduction Best Practices\n\n\nSet \nCREWAI_STORAGE_DIR\n to a known location in production\n\n\nChoose explicit embedding providers to match your LLM setup and avoid API key conflicts\n\n\nMonitor knowledge storage size as it grows with document additions\n\n\nOrganize knowledge sources by domain or purpose using collection names\n\n\nInclude knowledge directories in your backup and deployment strategies\n\n\nSet appropriate file permissions for knowledge files and storage directories\n\n\nUse environment variables for API keys and sensitive configuration\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nFlows\nLLMs\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nQuickstart Examples\nBasic String Knowledge Example\nWeb Content Knowledge Example\nSupported Knowledge Sources\nText File Knowledge Source\nPDF Knowledge Source\nCSV Knowledge Source\nExcel Knowledge Source\nJSON Knowledge Source\nAgent vs Crew Knowledge: Complete Guide\nHow Knowledge Initialization Actually Works\nAgent-Level Knowledge (Independent)\nWhat Happens During crew.kickoff()\nStorage Independence\nComplete Working Examples\nExample 1: Agent-Only Knowledge\nExample 2: Both Agent and Crew Knowledge\nExample 3: Multiple Agents with Different Knowledge\nKnowledge Configuration\nSupported Knowledge Parameters\nKnowledge Storage Transparency\nWhere CrewAI Stores Knowledge Files\nDefault Storage Locations by Platform\nFinding Your Knowledge Storage Location\nControlling Knowledge Storage Locations\nOption 1: Environment Variable (Recommended)\nOption 2: Custom Knowledge Storage\nOption 3: Project-Specific Knowledge Storage\nDefault Embedding Provider Behavior\nUnderstanding Default Behavior\nCustomizing Knowledge Embedding Providers\nConfiguring Azure OpenAI Embeddings\nAdvanced Features\nQuery Rewriting\nHow Query Rewriting Works\nBenefits of Query Rewriting\nExample\nKnowledge Events\nAvailable Knowledge Events\nExample: Monitoring Knowledge Retrieval\nCustom Knowledge Sources\nSpace News Knowledge Source Example\nDebugging and Troubleshooting\nDebugging Knowledge Issues\nCheck Agent Knowledge Initialization\nVerify Knowledge Storage Locations\nTest Knowledge Retrieval\nInspect Knowledge Collections\nCheck Knowledge Processing\nCommon Knowledge Storage Issues\nKnowledge Reset Commands\nClearing Knowledge\nBest Practices\nCore Concepts\nKnowledge\nCopy page\nWhat is knowledge in CrewAI and how to use it.\n​\nOverview\n\n\nKnowledge in CrewAI is a powerful system that allows AI agents to access and utilize external information sources during their tasks.\nThink of it as giving your agents a reference library they can consult while working.\n\n\nKey benefits of using Knowledge:\n\n\nEnhance agents with domain-specific information\n\n\nSupport decisions with real-world data\n\n\nMaintain context across conversations\n\n\nGround responses in factual information\n\n\n\n\n​\nQuickstart Examples\n\n\nFor file-based Knowledge Sources, make sure to place your files in a \nknowledge\n directory at the root of your project.\nAlso, use relative paths from the \nknowledge\n directory when creating the source.\n\n\n​\nBasic String Knowledge Example\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process, \nLLM\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Create a knowledge source\n\n\ncontent \n=\n \"Users name is John. He is 30 years old and lives in San Francisco.\"\n\n\nstring_source \n=\n StringKnowledgeSource(\ncontent\n=\ncontent)\n\n\n\n\n# Create an LLM with a temperature of 0 to ensure deterministic outputs\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n)\n\n\n\n\n# Create an agent with the knowledge store\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"About User\"\n,\n\n\n goal\n=\n\"You know everything about the user.\"\n,\n\n\n backstory\n=\n\"You are a master at understanding people and their preferences.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\nllm,\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer the following questions about the user: \n{question}\n\"\n,\n\n\n expected_output\n=\n\"An answer to the question.\"\n,\n\n\n agent\n=\nagent,\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n knowledge_sources\n=\n[string_source], \n# Enable knowledge by adding the sources here\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff(\ninputs\n=\n{\n\"question\"\n: \n\"What city does John live in and how old is he?\"\n})\n\n\n\n\n​\nWeb Content Knowledge Example\n\n\nYou need to install \ndocling\n for the following example to work: \nuv add docling\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai \nimport\n LLM\n, Agent, Crew, Process, Task\n\n\nfrom\n crewai.knowledge.source.crew_docling_source \nimport\n CrewDoclingSource\n\n\n\n\n# Create a knowledge source from web content\n\n\ncontent_source \n=\n CrewDoclingSource(\n\n\n file_paths\n=\n[\n\n\n \"https://lilianweng.github.io/posts/2024-11-28-reward-hacking\"\n,\n\n\n \"https://lilianweng.github.io/posts/2024-07-07-hallucination\"\n,\n\n\n ],\n\n\n)\n\n\n\n\n# Create an LLM with a temperature of 0 to ensure deterministic outputs\n\n\nllm \n=\n LLM(\nmodel\n=\n\"gpt-4o-mini\"\n, \ntemperature\n=\n0\n)\n\n\n\n\n# Create an agent with the knowledge store\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"About papers\"\n,\n\n\n goal\n=\n\"You know everything about the papers.\"\n,\n\n\n backstory\n=\n\"You are a master at understanding papers and their content.\"\n,\n\n\n verbose\n=\nTrue\n,\n\n\n allow_delegation\n=\nFalse\n,\n\n\n llm\n=\nllm,\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer the following questions about the papers: \n{question}\n\"\n,\n\n\n expected_output\n=\n\"An answer to the question.\"\n,\n\n\n agent\n=\nagent,\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential,\n\n\n knowledge_sources\n=\n[content_source],\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff(\n\n\n inputs\n=\n{\n\"question\"\n: \n\"What is the reward hacking paper about? Be sure to provide sources.\"\n}\n\n\n)\n\n\n\n\n​\nSupported Knowledge Sources\n\n\nCrewAI supports various types of knowledge sources out of the box:\n\n\nText Sources\n\n\nRaw strings\n\n\nText files (.txt)\n\n\nPDF documents\n\n\nStructured Data\n\n\nCSV files\n\n\nExcel spreadsheets\n\n\nJSON documents\n\n\n\n\n​\nText File Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.text_file_knowledge_source \nimport\n TextFileKnowledgeSource\n\n\n\n\ntext_source \n=\n TextFileKnowledgeSource(\n\n\n file_paths\n=\n[\n\"document.txt\"\n, \n\"another.txt\"\n]\n\n\n)\n\n\n\n\n​\nPDF Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.pdf_knowledge_source \nimport\n PDFKnowledgeSource\n\n\n\n\npdf_source \n=\n PDFKnowledgeSource(\n\n\n file_paths\n=\n[\n\"document.pdf\"\n, \n\"another.pdf\"\n]\n\n\n)\n\n\n\n\n​\nCSV Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.csv_knowledge_source \nimport\n CSVKnowledgeSource\n\n\n\n\ncsv_source \n=\n CSVKnowledgeSource(\n\n\n file_paths\n=\n[\n\"data.csv\"\n]\n\n\n)\n\n\n\n\n​\nExcel Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.excel_knowledge_source \nimport\n ExcelKnowledgeSource\n\n\n\n\nexcel_source \n=\n ExcelKnowledgeSource(\n\n\n file_paths\n=\n[\n\"spreadsheet.xlsx\"\n]\n\n\n)\n\n\n\n\n​\nJSON Knowledge Source\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.json_knowledge_source \nimport\n JSONKnowledgeSource\n\n\n\n\njson_source \n=\n JSONKnowledgeSource(\n\n\n file_paths\n=\n[\n\"data.json\"\n]\n\n\n)\n\n\n\n\nPlease ensure that you create the ./knowledge folder. All source files (e.g., .txt, .pdf, .xlsx, .json) should be placed in this folder for centralized management.\n\n\n​\nAgent vs Crew Knowledge: Complete Guide\n\n\nUnderstanding Knowledge Levels\n: CrewAI supports knowledge at both agent and crew levels. This section clarifies exactly how each works, when they’re initialized, and addresses common misconceptions about dependencies.\n\n\n​\nHow Knowledge Initialization Actually Works\n\n\nHere’s exactly what happens when you use knowledge:\n\n\n​\nAgent-Level Knowledge (Independent)\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Agent with its own knowledge - NO crew knowledge needed\n\n\nspecialist_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Specialized technical information for this agent only\"\n\n\n)\n\n\n\n\nspecialist_agent \n=\n Agent(\n\n\n role\n=\n\"Technical Specialist\"\n,\n\n\n goal\n=\n\"Provide technical expertise\"\n,\n\n\n backstory\n=\n\"Expert in specialized technical domains\"\n,\n\n\n knowledge_sources\n=\n[specialist_knowledge] \n# Agent-specific knowledge\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer technical questions\"\n,\n\n\n agent\n=\nspecialist_agent,\n\n\n expected_output\n=\n\"Technical answer\"\n\n\n)\n\n\n\n\n# No crew-level knowledge required\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[specialist_agent],\n\n\n tasks\n=\n[task]\n\n\n)\n\n\n\n\nresult \n=\n crew.kickoff() \n# Agent knowledge works independently\n\n\n\n\n​\nWhat Happens During \ncrew.kickoff()\n\n\nWhen you call \ncrew.kickoff()\n, here’s the exact sequence:\n\n\nCopy\nAsk AI\n# During kickoff\n\n\nfor\n agent \nin\n self\n.agents:\n\n\n agent.crew \n=\n self\n # Agent gets reference to crew\n\n\n agent.set_knowledge(\ncrew_embedder\n=\nself\n.embedder) \n# Agent knowledge initialized\n\n\n agent.create_agent_executor()\n\n\n\n\n​\nStorage Independence\n\n\nEach knowledge level uses independent storage collections:\n\n\nCopy\nAsk AI\n# Agent knowledge storage\n\n\nagent_collection_name \n=\n agent.role \n# e.g., \"Technical Specialist\"\n\n\n\n\n# Crew knowledge storage \n\n\ncrew_collection_name \n=\n \"crew\"\n\n\n\n\n# Both stored in same ChromaDB instance but different collections\n\n\n# Path: ~/.local/share/CrewAI/{project}/knowledge/\n\n\n# ├── crew/ # Crew knowledge collection\n\n\n# ├── Technical Specialist/ # Agent knowledge collection\n\n\n# └── Another Agent Role/ # Another agent's collection\n\n\n\n\n​\nComplete Working Examples\n\n\n​\nExample 1: Agent-Only Knowledge\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Agent-specific knowledge\n\n\nagent_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Agent-specific information that only this agent needs\"\n\n\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Specialist\"\n,\n\n\n goal\n=\n\"Use specialized knowledge\"\n,\n\n\n backstory\n=\n\"Expert with specific knowledge\"\n,\n\n\n knowledge_sources\n=\n[agent_knowledge],\n\n\n embedder\n=\n{ \n# Agent can have its own embedder\n\n\n \"provider\"\n: \n\"openai\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}\n\n\n }\n\n\n)\n\n\n\n\ntask \n=\n Task(\n\n\n description\n=\n\"Answer using your specialized knowledge\"\n,\n\n\n agent\n=\nagent,\n\n\n expected_output\n=\n\"Answer based on agent knowledge\"\n\n\n)\n\n\n\n\n# No crew knowledge needed\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[task])\n\n\nresult \n=\n crew.kickoff() \n# Works perfectly\n\n\n\n\n​\nExample 2: Both Agent and Crew Knowledge\n\n\nCopy\nAsk AI\n# Crew-wide knowledge (shared by all agents)\n\n\ncrew_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Company policies and general information for all agents\"\n\n\n)\n\n\n\n\n# Agent-specific knowledge\n\n\nspecialist_knowledge \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Technical specifications only the specialist needs\"\n\n\n)\n\n\n\n\nspecialist \n=\n Agent(\n\n\n role\n=\n\"Technical Specialist\"\n,\n\n\n goal\n=\n\"Provide technical expertise\"\n,\n\n\n backstory\n=\n\"Technical expert\"\n,\n\n\n knowledge_sources\n=\n[specialist_knowledge] \n# Agent-specific\n\n\n)\n\n\n\n\ngeneralist \n=\n Agent(\n\n\n role\n=\n\"General Assistant\"\n, \n\n\n goal\n=\n\"Provide general assistance\"\n,\n\n\n backstory\n=\n\"General helper\"\n\n\n # No agent-specific knowledge\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[specialist, generalist],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[crew_knowledge] \n# Crew-wide knowledge\n\n\n)\n\n\n\n\n# Result:\n\n\n# - specialist gets: crew_knowledge + specialist_knowledge\n\n\n# - generalist gets: crew_knowledge only\n\n\n\n\n​\nExample 3: Multiple Agents with Different Knowledge\n\n\nCopy\nAsk AI\n# Different knowledge for different agents\n\n\nsales_knowledge \n=\n StringKnowledgeSource(\ncontent\n=\n\"Sales procedures and pricing\"\n)\n\n\ntech_knowledge \n=\n StringKnowledgeSource(\ncontent\n=\n\"Technical documentation\"\n)\n\n\nsupport_knowledge \n=\n StringKnowledgeSource(\ncontent\n=\n\"Support procedures\"\n)\n\n\n\n\nsales_agent \n=\n Agent(\n\n\n role\n=\n\"Sales Representative\"\n,\n\n\n knowledge_sources\n=\n[sales_knowledge],\n\n\n embedder\n=\n{\n\"provider\"\n: \n\"openai\"\n, \n\"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}}\n\n\n)\n\n\n\n\ntech_agent \n=\n Agent(\n\n\n role\n=\n\"Technical Expert\"\n, \n\n\n knowledge_sources\n=\n[tech_knowledge],\n\n\n embedder\n=\n{\n\"provider\"\n: \n\"ollama\"\n, \n\"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}}\n\n\n)\n\n\n\n\nsupport_agent \n=\n Agent(\n\n\n role\n=\n\"Support Specialist\"\n,\n\n\n knowledge_sources\n=\n[support_knowledge]\n\n\n # Will use crew embedder as fallback\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[sales_agent, tech_agent, support_agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n embedder\n=\n{ \n# Fallback embedder for agents without their own\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"text-embedding-004\"\n}\n\n\n }\n\n\n)\n\n\n\n\n# Each agent gets only their specific knowledge\n\n\n# Each can use different embedding providers\n\n\n\n\nUnlike retrieval from a vector database using a tool, agents preloaded with knowledge will not need a retrieval persona or task.\nSimply add the relevant knowledge sources your agent or crew needs to function.\nKnowledge sources can be added at the agent or crew level.\nCrew level knowledge sources will be used by \nall agents\n in the crew.\nAgent level knowledge sources will be used by the \nspecific agent\n that is preloaded with the knowledge.\n\n\n​\nKnowledge Configuration\n\n\nYou can configure the knowledge configuration for the crew or agent.\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.knowledge.knowledge_config \nimport\n KnowledgeConfig\n\n\n\n\nknowledge_config \n=\n KnowledgeConfig(\nresults_limit\n=\n10\n, \nscore_threshold\n=\n0.5\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n ...\n\n\n knowledge_config\n=\nknowledge_config\n\n\n)\n\n\n\n\nresults_limit\n: is the number of relevant documents to return. Default is 3.\n\nscore_threshold\n: is the minimum score for a document to be considered relevant. Default is 0.35.\n\n\n​\nSupported Knowledge Parameters\n\n\n​\nsources\nList[BaseKnowledgeSource]\nrequired\nList of knowledge sources that provide content to be stored and queried. Can include PDF, CSV, Excel, JSON, text files, or string content.\n\n\n​\ncollection_name\nstr\nName of the collection where the knowledge will be stored. Used to identify different sets of knowledge. Defaults to “knowledge” if not provided.\n\n\n​\nstorage\nOptional[KnowledgeStorage]\nCustom storage configuration for managing how the knowledge is stored and retrieved. If not provided, a default storage will be created.\n\n\n​\nKnowledge Storage Transparency\n\n\nUnderstanding Knowledge Storage\n: CrewAI automatically stores knowledge sources in platform-specific directories using ChromaDB for vector storage. Understanding these locations and defaults helps with production deployments, debugging, and storage management.\n\n\n​\nWhere CrewAI Stores Knowledge Files\n\n\nBy default, CrewAI uses the same storage system as memory, storing knowledge in platform-specific directories:\n\n\n​\nDefault Storage Locations by Platform\n\n\nmacOS:\n\n\nCopy\nAsk AI\n~/Library/Application Support/CrewAI/{project_name}/\n\n\n└── knowledge/ # Knowledge ChromaDB files\n\n\n ├── chroma.sqlite3 # ChromaDB metadata\n\n\n ├── {collection_id}/ # Vector embeddings\n\n\n └── knowledge_{collection}/ # Named collections\n\n\n\n\nLinux:\n\n\nCopy\nAsk AI\n~/.local/share/CrewAI/{project_name}/\n\n\n└── knowledge/\n\n\n ├── chroma.sqlite3\n\n\n ├── {collection_id}/\n\n\n └── knowledge_{collection}/\n\n\n\n\nWindows:\n\n\nCopy\nAsk AI\nC:\\Users\\{username}\\AppData\\Local\\CrewAI\\{project_name}\\\n\n\n└── knowledge\\\n\n\n ├── chroma.sqlite3\n\n\n ├── {collection_id}\\\n\n\n └── knowledge_{collection}\\\n\n\n\n\n​\nFinding Your Knowledge Storage Location\n\n\nTo see exactly where CrewAI is storing your knowledge files:\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\nimport\n os\n\n\n\n\n# Get the knowledge storage path\n\n\nknowledge_path \n=\n os.path.join(db_storage_path(), \n\"knowledge\"\n)\n\n\nprint\n(\nf\n\"Knowledge storage location: \n{\nknowledge_path\n}\n\"\n)\n\n\n\n\n# List knowledge collections and files\n\n\nif\n os.path.exists(knowledge_path):\n\n\n print\n(\n\"\n\\n\nKnowledge storage contents:\"\n)\n\n\n for\n item \nin\n os.listdir(knowledge_path):\n\n\n item_path \n=\n os.path.join(knowledge_path, item)\n\n\n if\n os.path.isdir(item_path):\n\n\n print\n(\nf\n\"📁 Collection: \n{\nitem\n}\n/\"\n)\n\n\n # Show collection contents\n\n\n try\n:\n\n\n for\n subitem \nin\n os.listdir(item_path):\n\n\n print\n(\nf\n\" └── \n{\nsubitem\n}\n\"\n)\n\n\n except\n PermissionError\n:\n\n\n print\n(\nf\n\" └── (permission denied)\"\n)\n\n\n else\n:\n\n\n print\n(\nf\n\"📄 \n{\nitem\n}\n\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No knowledge storage found yet.\"\n)\n\n\n\n\n​\nControlling Knowledge Storage Locations\n\n\n​\nOption 1: Environment Variable (Recommended)\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai \nimport\n Crew\n\n\n\n\n# Set custom storage location for all CrewAI data\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n \"./my_project_storage\"\n\n\n\n\n# All knowledge will now be stored in ./my_project_storage/knowledge/\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[\n...\n]\n\n\n)\n\n\n\n\n​\nOption 2: Custom Knowledge Storage\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.storage.knowledge_storage \nimport\n KnowledgeStorage\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Create custom storage with specific embedder\n\n\ncustom_storage \n=\n KnowledgeStorage(\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\"model\"\n: \n\"mxbai-embed-large\"\n}\n\n\n },\n\n\n collection_name\n=\n\"my_custom_knowledge\"\n\n\n)\n\n\n\n\n# Use with knowledge sources\n\n\nknowledge_source \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Your knowledge content here\"\n\n\n)\n\n\nknowledge_source.storage \n=\n custom_storage\n\n\n\n\n​\nOption 3: Project-Specific Knowledge Storage\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n pathlib \nimport\n Path\n\n\n\n\n# Store knowledge in project directory\n\n\nproject_root \n=\n Path(\n__file__\n).parent\n\n\nknowledge_dir \n=\n project_root \n/\n \"knowledge_storage\"\n\n\n\n\nos.environ[\n\"CREWAI_STORAGE_DIR\"\n] \n=\n str\n(knowledge_dir)\n\n\n\n\n# Now all knowledge will be stored in your project directory\n\n\n\n\n​\nDefault Embedding Provider Behavior\n\n\nDefault Embedding Provider\n: CrewAI defaults to OpenAI embeddings (\ntext-embedding-3-small\n) for knowledge storage, even when using different LLM providers. You can easily customize this to match your setup.\n\n\n​\nUnderstanding Default Behavior\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, \nLLM\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# When using Claude as your LLM...\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Research topics\"\n,\n\n\n backstory\n=\n\"Expert researcher\"\n,\n\n\n llm\n=\nLLM(\nprovider\n=\n\"anthropic\"\n, \nmodel\n=\n\"claude-3-sonnet\"\n) \n# Using Claude\n\n\n)\n\n\n\n\n# CrewAI will still use OpenAI embeddings by default for knowledge\n\n\n# This ensures consistency but may not match your LLM provider preference\n\n\nknowledge_source \n=\n StringKnowledgeSource(\ncontent\n=\n\"Research data...\"\n)\n\n\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[knowledge_source]\n\n\n # Default: Uses OpenAI embeddings even with Claude LLM\n\n\n)\n\n\n\n\n​\nCustomizing Knowledge Embedding Providers\n\n\nCopy\nAsk AI\n# Option 1: Use Voyage AI (recommended by Anthropic for Claude users)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"voyageai\"\n, \n# Recommended for Claude users\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-voyage-api-key\"\n,\n\n\n \"model\"\n: \n\"voyage-3\"\n # or \"voyage-3-large\" for best quality\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Option 2: Use local embeddings (no external API calls)\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[agent],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"ollama\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"mxbai-embed-large\"\n,\n\n\n \"url\"\n: \n\"http://localhost:11434/api/embeddings\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n# Option 3: Agent-level embedding customization\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Research topics\"\n,\n\n\n backstory\n=\n\"Expert researcher\"\n,\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"google\"\n,\n\n\n \"config\"\n: {\n\n\n \"model\"\n: \n\"models/text-embedding-004\"\n,\n\n\n \"api_key\"\n: \n\"your-google-key\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nConfiguring Azure OpenAI Embeddings\n\n\nWhen using Azure OpenAI embeddings:\n\n\n\n\nMake sure you deploy the embedding model in Azure platform first\n\n\nThen you need to use the following configuration:\n\n\n\n\nCopy\nAsk AI\nagent \n=\n Agent(\n\n\n role\n=\n\"Researcher\"\n,\n\n\n goal\n=\n\"Research topics\"\n,\n\n\n backstory\n=\n\"Expert researcher\"\n,\n\n\n knowledge_sources\n=\n[knowledge_source],\n\n\n embedder\n=\n{\n\n\n \"provider\"\n: \n\"azure\"\n,\n\n\n \"config\"\n: {\n\n\n \"api_key\"\n: \n\"your-azure-api-key\"\n,\n\n\n \"model\"\n: \n\"text-embedding-ada-002\"\n, \n# change to the model you are using and is deployed in Azure\n\n\n \"api_base\"\n: \n\"https://your-azure-endpoint.openai.azure.com/\"\n,\n\n\n \"api_version\"\n: \n\"2024-02-01\"\n\n\n }\n\n\n }\n\n\n)\n\n\n\n\n​\nAdvanced Features\n\n\n​\nQuery Rewriting\n\n\nCrewAI implements an intelligent query rewriting mechanism to optimize knowledge retrieval. When an agent needs to search through knowledge sources, the raw task prompt is automatically transformed into a more effective search query.\n\n\n​\nHow Query Rewriting Works\n\n\n\n\nWhen an agent executes a task with knowledge sources available, the \n_get_knowledge_search_query\n method is triggered\n\n\nThe agent’s LLM is used to transform the original task prompt into an optimized search query\n\n\nThis optimized query is then used to retrieve relevant information from knowledge sources\n\n\n\n\n​\nBenefits of Query Rewriting\n\n\nImproved Retrieval Accuracy\nBy focusing on key concepts and removing irrelevant content, query rewriting helps retrieve more relevant information.\nContext Awareness\nThe rewritten queries are designed to be more specific and context-aware for vector database retrieval.\n\n\n​\nExample\n\n\nCopy\nAsk AI\n# Original task prompt\n\n\ntask_prompt \n=\n \"Answer the following questions about the user's favorite movies: What movie did John watch last week? Format your answer in JSON.\"\n\n\n\n\n# Behind the scenes, this might be rewritten as:\n\n\nrewritten_query \n=\n \"What movies did John watch last week?\"\n\n\n\n\nThe rewritten query is more focused on the core information need and removes irrelevant instructions about output formatting.\n\n\nThis mechanism is fully automatic and requires no configuration from users. The agent’s LLM is used to perform the query rewriting, so using a more capable LLM can improve the quality of rewritten queries.\n\n\n​\nKnowledge Events\n\n\nCrewAI emits events during the knowledge retrieval process that you can listen for using the event system. These events allow you to monitor, debug, and analyze how knowledge is being retrieved and used by your agents.\n\n\n​\nAvailable Knowledge Events\n\n\n\n\nKnowledgeRetrievalStartedEvent\n: Emitted when an agent starts retrieving knowledge from sources\n\n\nKnowledgeRetrievalCompletedEvent\n: Emitted when knowledge retrieval is completed, including the query used and the retrieved content\n\n\nKnowledgeQueryStartedEvent\n: Emitted when a query to knowledge sources begins\n\n\nKnowledgeQueryCompletedEvent\n: Emitted when a query completes successfully\n\n\nKnowledgeQueryFailedEvent\n: Emitted when a query to knowledge sources fails\n\n\nKnowledgeSearchQueryFailedEvent\n: Emitted when a search query fails\n\n\n\n\n​\nExample: Monitoring Knowledge Retrieval\n\n\nCopy\nAsk AI\nfrom\n crewai.utilities.events \nimport\n (\n\n\n KnowledgeRetrievalStartedEvent,\n\n\n KnowledgeRetrievalCompletedEvent,\n\n\n)\n\n\nfrom\n crewai.utilities.events.base_event_listener \nimport\n BaseEventListener\n\n\n\n\nclass\n KnowledgeMonitorListener\n(\nBaseEventListener\n):\n\n\n def\n setup_listeners\n(\nself\n, \ncrewai_event_bus\n):\n\n\n @crewai_event_bus.on\n(KnowledgeRetrievalStartedEvent)\n\n\n def\n on_knowledge_retrieval_started\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Agent '\n{\nevent.agent.role\n}\n' started retrieving knowledge\"\n)\n\n\n \n\n\n @crewai_event_bus.on\n(KnowledgeRetrievalCompletedEvent)\n\n\n def\n on_knowledge_retrieval_completed\n(\nsource\n, \nevent\n):\n\n\n print\n(\nf\n\"Agent '\n{\nevent.agent.role\n}\n' completed knowledge retrieval\"\n)\n\n\n print\n(\nf\n\"Query: \n{\nevent.query\n}\n\"\n)\n\n\n print\n(\nf\n\"Retrieved \n{\nlen\n(event.retrieved_knowledge)\n}\n knowledge chunks\"\n)\n\n\n\n\n# Create an instance of your listener\n\n\nknowledge_monitor \n=\n KnowledgeMonitorListener()\n\n\n\n\nFor more information on using events, see the \nEvent Listeners\n documentation.\n\n\n​\nCustom Knowledge Sources\n\n\nCrewAI allows you to create custom knowledge sources for any type of data by extending the \nBaseKnowledgeSource\n class. Let’s create a practical example that fetches and processes space news articles.\n\n\n​\nSpace News Knowledge Source Example\n\n\nCode\nOutput\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Task, Crew, Process, \nLLM\n\n\nfrom\n crewai.knowledge.source.base_knowledge_source \nimport\n BaseKnowledgeSource\n\n\nimport\n requests\n\n\nfrom\n datetime \nimport\n datetime\n\n\nfrom\n typing \nimport\n Dict, Any\n\n\nfrom\n pydantic \nimport\n BaseModel, Field\n\n\n\n\nclass\n SpaceNewsKnowledgeSource\n(\nBaseKnowledgeSource\n):\n\n\n \"\"\"Knowledge source that fetches data from Space News API.\"\"\"\n\n\n\n\n api_endpoint: \nstr\n =\n Field(\ndescription\n=\n\"API endpoint URL\"\n)\n\n\n limit: \nint\n =\n Field(\ndefault\n=\n10\n, \ndescription\n=\n\"Number of articles to fetch\"\n)\n\n\n\n\n def\n load_content\n(\nself\n) -> Dict[Any, \nstr\n]:\n\n\n \"\"\"Fetch and format space news articles.\"\"\"\n\n\n try\n:\n\n\n response \n=\n requests.get(\n\n\n f\n\"\n{\nself\n.api_endpoint\n}\n?limit=\n{\nself\n.limit\n}\n\"\n\n\n )\n\n\n response.raise_for_status()\n\n\n\n\n data \n=\n response.json()\n\n\n articles \n=\n data.get(\n'results'\n, [])\n\n\n\n\n formatted_data \n=\n self\n.validate_content(articles)\n\n\n return\n {\nself\n.api_endpoint: formatted_data}\n\n\n except\n Exception\n as\n e:\n\n\n raise\n ValueError\n(\nf\n\"Failed to fetch space news: \n{\nstr\n(e)\n}\n\"\n)\n\n\n\n\n def\n validate_content\n(\nself\n, \narticles\n: \nlist\n) -> \nstr\n:\n\n\n \"\"\"Format articles into readable text.\"\"\"\n\n\n formatted \n=\n \"Space News Articles:\n\\n\\n\n\"\n\n\n for\n article \nin\n articles:\n\n\n formatted \n+=\n f\n\"\"\"\n\n\n Title: \n{\narticle[\n'title'\n]\n}\n\n\n Published: \n{\narticle[\n'published_at'\n]\n}\n\n\n Summary: \n{\narticle[\n'summary'\n]\n}\n\n\n News Site: \n{\narticle[\n'news_site'\n]\n}\n\n\n URL: \n{\narticle[\n'url'\n]\n}\n\n\n -------------------\"\"\"\n\n\n return\n formatted\n\n\n\n\n def\n add\n(\nself\n) -> \nNone\n:\n\n\n \"\"\"Process and store the articles.\"\"\"\n\n\n content \n=\n self\n.load_content()\n\n\n for\n _, text \nin\n content.items():\n\n\n chunks \n=\n self\n._chunk_text(text)\n\n\n self\n.chunks.extend(chunks)\n\n\n\n\n self\n._save_documents()\n\n\n\n\n# Create knowledge source\n\n\nrecent_news \n=\n SpaceNewsKnowledgeSource(\n\n\n api_endpoint\n=\n\"https://api.spaceflightnewsapi.net/v4/articles\"\n,\n\n\n limit\n=\n10\n,\n\n\n)\n\n\n\n\n# Create specialized agent\n\n\nspace_analyst \n=\n Agent(\n\n\n role\n=\n\"Space News Analyst\"\n,\n\n\n goal\n=\n\"Answer questions about space news accurately and comprehensively\"\n,\n\n\n backstory\n=\n\"\"\"You are a space industry analyst with expertise in space exploration,\n\n\n satellite technology, and space industry trends. You excel at answering questions\n\n\n about space news and providing detailed, accurate information.\"\"\"\n,\n\n\n knowledge_sources\n=\n[recent_news],\n\n\n llm\n=\nLLM(\nmodel\n=\n\"gpt-4\"\n, \ntemperature\n=\n0.0\n)\n\n\n)\n\n\n\n\n# Create task that handles user questions\n\n\nanalysis_task \n=\n Task(\n\n\n description\n=\n\"Answer this question about space news: \n{user_question}\n\"\n,\n\n\n expected_output\n=\n\"A detailed answer based on the recent space news articles\"\n,\n\n\n agent\n=\nspace_analyst\n\n\n)\n\n\n\n\n# Create and run the crew\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[space_analyst],\n\n\n tasks\n=\n[analysis_task],\n\n\n verbose\n=\nTrue\n,\n\n\n process\n=\nProcess.sequential\n\n\n)\n\n\n\n\n# Example usage\n\n\nresult \n=\n crew.kickoff(\n\n\n inputs\n=\n{\n\"user_question\"\n: \n\"What are the latest developments in space exploration?\"\n}\n\n\n)\n\n\n\n\n​\nDebugging and Troubleshooting\n\n\n​\nDebugging Knowledge Issues\n\n\n​\nCheck Agent Knowledge Initialization\n\n\nCopy\nAsk AI\nfrom\n crewai \nimport\n Agent, Crew, Task\n\n\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\nknowledge_source \n=\n StringKnowledgeSource(\ncontent\n=\n\"Test knowledge\"\n)\n\n\n\n\nagent \n=\n Agent(\n\n\n role\n=\n\"Test Agent\"\n,\n\n\n goal\n=\n\"Test knowledge\"\n,\n\n\n backstory\n=\n\"Testing\"\n,\n\n\n knowledge_sources\n=\n[knowledge_source]\n\n\n)\n\n\n\n\ncrew \n=\n Crew(\nagents\n=\n[agent], \ntasks\n=\n[Task(\n...\n)])\n\n\n\n\n# Before kickoff - knowledge not initialized\n\n\nprint\n(\nf\n\"Before kickoff - Agent knowledge: \n{\ngetattr\n(agent, \n'knowledge'\n, \nNone\n)\n}\n\"\n)\n\n\n\n\ncrew.kickoff()\n\n\n\n\n# After kickoff - knowledge initialized\n\n\nprint\n(\nf\n\"After kickoff - Agent knowledge: \n{\nagent.knowledge\n}\n\"\n)\n\n\nprint\n(\nf\n\"Agent knowledge collection: \n{\nagent.knowledge.storage.collection_name\n}\n\"\n)\n\n\nprint\n(\nf\n\"Number of sources: \n{\nlen\n(agent.knowledge.sources)\n}\n\"\n)\n\n\n\n\n​\nVerify Knowledge Storage Locations\n\n\nCopy\nAsk AI\nimport\n os\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\n# Check storage structure\n\n\nstorage_path \n=\n db_storage_path()\n\n\nknowledge_path \n=\n os.path.join(storage_path, \n\"knowledge\"\n)\n\n\n\n\nif\n os.path.exists(knowledge_path):\n\n\n print\n(\n\"Knowledge collections found:\"\n)\n\n\n for\n collection \nin\n os.listdir(knowledge_path):\n\n\n collection_path \n=\n os.path.join(knowledge_path, collection)\n\n\n if\n os.path.isdir(collection_path):\n\n\n print\n(\nf\n\" - \n{\ncollection\n}\n/\"\n)\n\n\n # Show collection contents\n\n\n for\n item \nin\n os.listdir(collection_path):\n\n\n print\n(\nf\n\" └── \n{\nitem\n}\n\"\n)\n\n\n\n\n​\nTest Knowledge Retrieval\n\n\nCopy\nAsk AI\n# Test agent knowledge retrieval\n\n\nif\n hasattr\n(agent, \n'knowledge'\n) \nand\n agent.knowledge:\n\n\n test_query \n=\n [\n\"test query\"\n]\n\n\n results \n=\n agent.knowledge.query(test_query)\n\n\n print\n(\nf\n\"Agent knowledge results: \n{\nlen\n(results)\n}\n documents found\"\n)\n\n\n \n\n\n # Test crew knowledge retrieval (if exists)\n\n\n if\n hasattr\n(crew, \n'knowledge'\n) \nand\n crew.knowledge:\n\n\n crew_results \n=\n crew.query_knowledge(test_query)\n\n\n print\n(\nf\n\"Crew knowledge results: \n{\nlen\n(crew_results)\n}\n documents found\"\n)\n\n\n\n\n​\nInspect Knowledge Collections\n\n\nCopy\nAsk AI\nimport\n chromadb\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\nimport\n os\n\n\n\n\n# Connect to CrewAI's knowledge ChromaDB\n\n\nknowledge_path \n=\n os.path.join(db_storage_path(), \n\"knowledge\"\n)\n\n\n\n\nif\n os.path.exists(knowledge_path):\n\n\n client \n=\n chromadb.PersistentClient(\npath\n=\nknowledge_path)\n\n\n collections \n=\n client.list_collections()\n\n\n \n\n\n print\n(\n\"Knowledge Collections:\"\n)\n\n\n for\n collection \nin\n collections:\n\n\n print\n(\nf\n\" - \n{\ncollection.name\n}\n: \n{\ncollection.count()\n}\n documents\"\n)\n\n\n \n\n\n # Sample a few documents to verify content\n\n\n if\n collection.count() \n>\n 0\n:\n\n\n sample \n=\n collection.peek(\nlimit\n=\n2\n)\n\n\n print\n(\nf\n\" Sample content: \n{\nsample[\n'documents'\n][\n0\n][:\n100\n]\n}\n...\"\n)\n\n\nelse\n:\n\n\n print\n(\n\"No knowledge storage found\"\n)\n\n\n\n\n​\nCheck Knowledge Processing\n\n\nCopy\nAsk AI\nfrom\n crewai.knowledge.source.string_knowledge_source \nimport\n StringKnowledgeSource\n\n\n\n\n# Create a test knowledge source\n\n\ntest_source \n=\n StringKnowledgeSource(\n\n\n content\n=\n\"Test knowledge content for debugging\"\n,\n\n\n chunk_size\n=\n100\n, \n# Small chunks for testing\n\n\n chunk_overlap\n=\n20\n\n\n)\n\n\n\n\n# Check chunking behavior\n\n\nprint\n(\nf\n\"Original content length: \n{\nlen\n(test_source.content)\n}\n\"\n)\n\n\nprint\n(\nf\n\"Chunk size: \n{\ntest_source.chunk_size\n}\n\"\n)\n\n\nprint\n(\nf\n\"Chunk overlap: \n{\ntest_source.chunk_overlap\n}\n\"\n)\n\n\n\n\n# Process and inspect chunks\n\n\ntest_source.add()\n\n\nprint\n(\nf\n\"Number of chunks created: \n{\nlen\n(test_source.chunks)\n}\n\"\n)\n\n\nfor\n i, chunk \nin\n enumerate\n(test_source.chunks[:\n3\n]): \n# Show first 3 chunks\n\n\n print\n(\nf\n\"Chunk \n{\ni\n+\n1\n}\n: \n{\nchunk[:\n50\n]\n}\n...\"\n)\n\n\n\n\n​\nCommon Knowledge Storage Issues\n\n\n“File not found” errors:\n\n\nCopy\nAsk AI\n# Ensure files are in the correct location\n\n\nfrom\n crewai.utilities.constants \nimport\n KNOWLEDGE_DIRECTORY\n\n\nimport\n os\n\n\n\n\nknowledge_dir \n=\n KNOWLEDGE_DIRECTORY\n # Usually \"knowledge\"\n\n\nfile_path \n=\n os.path.join(knowledge_dir, \n\"your_file.pdf\"\n)\n\n\n\n\nif\n not\n os.path.exists(file_path):\n\n\n print\n(\nf\n\"File not found: \n{\nfile_path\n}\n\"\n)\n\n\n print\n(\nf\n\"Current working directory: \n{\nos.getcwd()\n}\n\"\n)\n\n\n print\n(\nf\n\"Expected knowledge directory: \n{\nos.path.abspath(knowledge_dir)\n}\n\"\n)\n\n\n\n\n“Embedding dimension mismatch” errors:\n\n\nCopy\nAsk AI\n# This happens when switching embedding providers\n\n\n# Reset knowledge storage to clear old embeddings\n\n\ncrew.reset_memories(\ncommand_type\n=\n'knowledge'\n)\n\n\n\n\n# Or use consistent embedding providers\n\n\ncrew \n=\n Crew(\n\n\n agents\n=\n[\n...\n],\n\n\n tasks\n=\n[\n...\n],\n\n\n knowledge_sources\n=\n[\n...\n],\n\n\n embedder\n=\n{\n\"provider\"\n: \n\"openai\"\n, \n\"config\"\n: {\n\"model\"\n: \n\"text-embedding-3-small\"\n}}\n\n\n)\n\n\n\n\n“ChromaDB permission denied” errors:\n\n\nCopy\nAsk AI\n# Fix storage permissions\n\n\nchmod\n -R\n 755\n ~/.local/share/CrewAI/\n\n\n\n\nKnowledge not persisting between runs:\n\n\nCopy\nAsk AI\n# Verify storage location consistency\n\n\nimport\n os\n\n\nfrom\n crewai.utilities.paths \nimport\n db_storage_path\n\n\n\n\nprint\n(\n\"CREWAI_STORAGE_DIR:\"\n, os.getenv(\n\"CREWAI_STORAGE_DIR\"\n))\n\n\nprint\n(\n\"Computed storage path:\"\n, db_storage_path())\n\n\nprint\n(\n\"Knowledge path:\"\n, os.path.join(db_storage_path(), \n\"knowledge\"\n))\n\n\n\n\n​\nKnowledge Reset Commands\n\n\nCopy\nAsk AI\n# Reset only agent-specific knowledge\n\n\ncrew.reset_memories(\ncommand_type\n=\n'agent_knowledge'\n)\n\n\n\n\n# Reset both crew and agent knowledge \n\n\ncrew.reset_memories(\ncommand_type\n=\n'knowledge'\n)\n\n\n\n\n# CLI commands\n\n\n# crewai reset-memories --agent-knowledge # Agent knowledge only\n\n\n# crewai reset-memories --knowledge # All knowledge\n\n\n\n\n​\nClearing Knowledge\n\n\nIf you need to clear the knowledge stored in CrewAI, you can use the \ncrewai reset-memories\n command with the \n--knowledge\n option.\n\n\nCommand\nCopy\nAsk AI\ncrewai\n reset-memories\n --knowledge\n\n\n\n\nThis is useful when you’ve updated your knowledge sources and want to ensure that the agents are using the most recent information.\n\n\n​\nBest Practices\n\n\nContent Organization\n\n\nKeep chunk sizes appropriate for your content type\n\n\nConsider content overlap for context preservation\n\n\nOrganize related information into separate knowledge sources\n\n\nPerformance Tips\n\n\nAdjust chunk sizes based on content complexity\n\n\nConfigure appropriate embedding models\n\n\nConsider using local embedding providers for faster processing\n\n\nOne Time Knowledge\n\n\nWith the typical file structure provided by CrewAI, knowledge sources are embedded every time the kickoff is triggered.\n\n\nIf the knowledge sources are large, this leads to inefficiency and increased latency, as the same data is embedded each time.\n\n\nTo resolve this, directly initialize the knowledge parameter instead of the knowledge_sources parameter.\n\n\nLink to the issue to get complete idea \nGithub Issue\n\n\nKnowledge Management\n\n\nUse agent-level knowledge for role-specific information\n\n\nUse crew-level knowledge for shared information all agents need\n\n\nSet embedders at agent level if you need different embedding strategies\n\n\nUse consistent collection naming by keeping agent roles descriptive\n\n\nTest knowledge initialization by checking agent.knowledge after kickoff\n\n\nMonitor storage locations to understand where knowledge is stored\n\n\nReset knowledge appropriately using the correct command types\n\n\nProduction Best Practices\n\n\nSet \nCREWAI_STORAGE_DIR\n to a known location in production\n\n\nChoose explicit embedding providers to match your LLM setup and avoid API key conflicts\n\n\nMonitor knowledge storage size as it grows with document additions\n\n\nOrganize knowledge sources by domain or purpose using collection names\n\n\nInclude knowledge directories in your backup and deployment strategies\n\n\nSet appropriate file permissions for knowledge files and storage directories\n\n\nUse environment variables for API keys and sensitive configuration\n\n\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nFlows\nLLMs\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nOverview\nQuickstart Examples\nBasic String Knowledge Example\nWeb Content Knowledge Example\nSupported Knowledge Sources\nText File Knowledge Source\nPDF Knowledge Source\nCSV Knowledge Source\nExcel Knowledge Source\nJSON Knowledge Source\nAgent vs Crew Knowledge: Complete Guide\nHow Knowledge Initialization Actually Works\nAgent-Level Knowledge (Independent)\nWhat Happens During crew.kickoff()\nStorage Independence\nComplete Working Examples\nExample 1: Agent-Only Knowledge\nExample 2: Both Agent and Crew Knowledge\nExample 3: Multiple Agents with Different Knowledge\nKnowledge Configuration\nSupported Knowledge Parameters\nKnowledge Storage Transparency\nWhere CrewAI Stores Knowledge Files\nDefault Storage Locations by Platform\nFinding Your Knowledge Storage Location\nControlling Knowledge Storage Locations\nOption 1: Environment Variable (Recommended)\nOption 2: Custom Knowledge Storage\nOption 3: Project-Specific Knowledge Storage\nDefault Embedding Provider Behavior\nUnderstanding Default Behavior\nCustomizing Knowledge Embedding Providers\nConfiguring Azure OpenAI Embeddings\nAdvanced Features\nQuery Rewriting\nHow Query Rewriting Works\nBenefits of Query Rewriting\nExample\nKnowledge Events\nAvailable Knowledge Events\nExample: Monitoring Knowledge Retrieval\nCustom Knowledge Sources\nSpace News Knowledge Source Example\nDebugging and Troubleshooting\nDebugging Knowledge Issues\nCheck Agent Knowledge Initialization\nVerify Knowledge Storage Locations\nTest Knowledge Retrieval\nInspect Knowledge Collections\nCheck Knowledge Processing\nCommon Knowledge Storage Issues\nKnowledge Reset Commands\nClearing Knowledge\nBest Practices" }, { "source": "https://docs.crewai.com/en/examples/example", "title": "CrewAI Examples - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nExamples\nCrewAI Examples\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nExamples\nCrewAI Examples\nExamples\nCrewAI Examples\nCopy page\nA collection of examples that show how to use CrewAI framework to automate workflows.\nMarketing Strategy\nAutomate marketing strategy creation with CrewAI.\nSurprise Trip\nCreate a surprise trip itinerary with CrewAI.\nMatch Profile to Positions\nMatch a profile to jobpositions with CrewAI.\nCreate Job Posting\nCreate a job posting with CrewAI.\nGame Generator\nCreate a game with CrewAI.\nFind Job Candidates\nFind job candidates with CrewAI.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nExamples\nCrewAI Examples\nCopy page\nA collection of examples that show how to use CrewAI framework to automate workflows.\nMarketing Strategy\nAutomate marketing strategy creation with CrewAI.\nSurprise Trip\nCreate a surprise trip itinerary with CrewAI.\nMatch Profile to Positions\nMatch a profile to jobpositions with CrewAI.\nCreate Job Posting\nCreate a job posting with CrewAI.\nGame Generator\nCreate a game with CrewAI.\nFind Job Candidates\nFind job candidates with CrewAI.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify" }, { "source": "https://docs.crewai.com/en/learn/force-tool-output-as-result", "title": "Force Tool Output as Result - CrewAI", "content": "CrewAI\n home page\nEnglish\nSearch...\n⌘\nK\nAsk AI\nStart Cloud Trial\ncrewAIInc\n/\ncrewAI\ncrewAIInc\n/\ncrewAI\nSearch...\nNavigation\nLearn\nForce Tool Output as Result\nDocumentation\nEnterprise\nAPI Reference\nExamples\nWebsite\nForum\nCrew GPT\nGet Help\nReleases\nGet Started\nIntroduction\nInstallation\nQuickstart\nGuides\nStrategy\nAgents\nCrews\nFlows\nAdvanced\nCore Concepts\nAgents\nTasks\nCrews\nFlows\nKnowledge\nLLMs\nProcesses\nCollaboration\nTraining\nMemory\nReasoning\nPlanning\nTesting\nCLI\nTools\nEvent Listeners\nMCP Integration\nMCP Servers as Tools in CrewAI\nStdio Transport\nSSE Transport\nStreamable HTTP Transport\nConnecting to Multiple MCP Servers\nMCP Security Considerations\nTools\nTools Overview\nFile & Document\nWeb Scraping & Browsing\nSearch & Research\nDatabase & Data\nAI & Machine Learning\nCloud & Storage\nAutomation & Integration\nObservability\nOverview\nAgentOps Integration\nArize Phoenix\nLangfuse Integration\nLangtrace Integration\nMaxim Integration\nMLflow Integration\nOpenLIT Integration\nOpik Integration\nPatronus AI Evaluation\nPortkey Integration\nWeave Integration\nLearn\nOverview\nStrategic LLM Selection Guide\nConditional Tasks\nCoding Agents\nCreate Custom Tools\nCustom LLM Implementation\nCustom Manager Agent\nCustomize Agents\nImage Generation with DALL-E\nForce Tool Output as Result\nHierarchical Process\nHuman Input on Execution\nKickoff Crew Asynchronously\nKickoff Crew for Each\nConnect to any LLM\nUsing Multimodal Agents\nReplay Tasks from Latest Crew Kickoff\nSequential Processes\nUsing Annotations in crew.py\nTelemetry\nTelemetry\nLearn\nForce Tool Output as Result\nCopy page\nLearn how to force tool output as the result in an Agent’s task in CrewAI.\n​\nIntroduction\n\n\nIn CrewAI, you can force the output of a tool as the result of an agent’s task.\nThis feature is useful when you want to ensure that the tool output is captured and returned as the task result, avoiding any agent modification during the task execution.\n\n\n​\nForcing Tool Output as Result\n\n\nTo force the tool output as the result of an agent’s task, you need to set the \nresult_as_answer\n parameter to \nTrue\n when adding a tool to the agent.\nThis parameter ensures that the tool output is captured and returned as the task result, without any modifications by the agent.\n\n\nHere’s an example of how to force the tool output as the result of an agent’s task:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.agent \nimport\n Agent\n\n\nfrom\n my_tool \nimport\n MyCustomTool\n\n\n\n\n# Create a coding agent with the custom tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Data Scientist\"\n,\n\n\n goal\n=\n\"Produce amazing reports on AI\"\n,\n\n\n backstory\n=\n\"You work with data and AI\"\n,\n\n\n tools\n=\n[MyCustomTool(\nresult_as_answer\n=\nTrue\n)],\n\n\n )\n\n\n\n\n# Assuming the tool's execution and result population occurs within the system\n\n\ntask_result \n=\n coding_agent.execute_task(task)\n\n\n\n\n​\nWorkflow in Action\n\n\n1\nTask Execution\nThe agent executes the task using the tool provided.\n2\nTool Output\nThe tool generates the output, which is captured as the task result.\n3\nAgent Interaction\nThe agent may reflect and take learnings from the tool but the output is not modified.\n4\nResult Return\nThe tool output is returned as the task result without any modifications.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nImage Generation with DALL-E\nHierarchical Process\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nForcing Tool Output as Result\nWorkflow in Action\nLearn\nForce Tool Output as Result\nCopy page\nLearn how to force tool output as the result in an Agent’s task in CrewAI.\n​\nIntroduction\n\n\nIn CrewAI, you can force the output of a tool as the result of an agent’s task.\nThis feature is useful when you want to ensure that the tool output is captured and returned as the task result, avoiding any agent modification during the task execution.\n\n\n​\nForcing Tool Output as Result\n\n\nTo force the tool output as the result of an agent’s task, you need to set the \nresult_as_answer\n parameter to \nTrue\n when adding a tool to the agent.\nThis parameter ensures that the tool output is captured and returned as the task result, without any modifications by the agent.\n\n\nHere’s an example of how to force the tool output as the result of an agent’s task:\n\n\nCode\nCopy\nAsk AI\nfrom\n crewai.agent \nimport\n Agent\n\n\nfrom\n my_tool \nimport\n MyCustomTool\n\n\n\n\n# Create a coding agent with the custom tool\n\n\ncoding_agent \n=\n Agent(\n\n\n role\n=\n\"Data Scientist\"\n,\n\n\n goal\n=\n\"Produce amazing reports on AI\"\n,\n\n\n backstory\n=\n\"You work with data and AI\"\n,\n\n\n tools\n=\n[MyCustomTool(\nresult_as_answer\n=\nTrue\n)],\n\n\n )\n\n\n\n\n# Assuming the tool's execution and result population occurs within the system\n\n\ntask_result \n=\n coding_agent.execute_task(task)\n\n\n\n\n​\nWorkflow in Action\n\n\n1\nTask Execution\nThe agent executes the task using the tool provided.\n2\nTool Output\nThe tool generates the output, which is captured as the task result.\n3\nAgent Interaction\nThe agent may reflect and take learnings from the tool but the output is not modified.\n4\nResult Return\nThe tool output is returned as the task result without any modifications.\nAssistant\nResponses are generated using AI and may contain mistakes.\nWas this page helpful?\nYes\nNo\nImage Generation with DALL-E\nHierarchical Process\nwebsite\nx\ngithub\nlinkedin\nyoutube\nreddit\nPowered by Mintlify\nOn this page\nIntroduction\nForcing Tool Output as Result\nWorkflow in Action" } ]