CrewAI是一个专注于多智能体协作的开源框架,提供从开发部署到监控的全流程解决方案。当前38.6k star,还是挺受欢迎的,据说很多创业团队都用它!

官网:https://github.com/crewAIInc/crewAI

gitcode镜像:https://gitcode.com/GitHub_Trending/cr/crewAI

官方文档:https://docs.crewai.com/

中文文档:Introduction - CrewAI

一、CrewAI核心概念

  1. 代理(Agent)

    • 具有特定角色、目标和背景故事的AI实体,如研究员、作家等^^1^^2^^

    • 关键属性:role(角色)、goal(目标)、backstory(背景故事)、llm(语言模型)^^3^^4^^

  2. 任务(Task)

    • 分配给代理的具体工作,包含描述和预期输出^^1^^5^^

    • 示例:研究{topic}领域最新趋势撰写技术文章^^2^^3^^

  3. 团队(Crew)

    • 协调多个代理协作的容器,支持动态任务分配^^1^^6^^

    • 流程模式:sequential(顺序执行)或hierarchical(层级协作)^^4^^6^^

  4. 工具(Tool)

    • 扩展代理能力的实用程序,如搜索引擎、数据库连接^^1^^7^^

    • 支持@tool装饰器或子类继承两种实现方式^^7^^

二、环境配置

  1. 安装要求

    • Python ≥3.8(推荐3.10+)^^8^^9^^

    • 安装命令:pip install crewaiuv tool install crewai^^8^^9^^

  2. 项目初始化

    crewai create crew my_project # 创建项目 cd my_project # 进入目录 crewai install # 安装依赖 ^^8^^10^^

  3. 模型配置

    • .env文件中设置API密钥(如OpenAI、Serper.dev)^^9^^11^^

    • 本地模型需通过LLM类指定模型路径(如Ollama)^^3^^12^^

三、基础实践:构建研究团队

  1. 定义代理(agents.yaml

    researcher: role: "AI领域研究员" goal: "收集{topic}最新技术动态" backstory: "专注前沿技术追踪,擅长信息整合" llm: "openai/gpt-4" tools: [search_tool] writer: role: "科技作家" goal: "将研究结果转化为通俗文章" backstory: "擅长技术内容通俗化表达" llm: "ollama_chat/qwen2.5" ^^2^^3^^

  2. 创建任务(tasks.yaml

    research_task: description: "分析{topic}领域2025年技术突破" expected_output: "包含技术名称、应用场景的列表" agent: researcher article_task: description: "基于研究结果撰写1500字科普文" expected_output: "Markdown格式文章" agent: writer ^^10^^11^^

  3. 启动团队执行

    from crewai import Crew, Process crew = Crew(agents=[researcher, writer], tasks=[research_task, article_task], process=Process.sequential) result = crew.kickoff(topic="量子计算") print(result) ^^2^^3^^

四、进阶功能

  1. 知识系统

    • 支持文本/结构化数据源(如PDF、CSV),通过StringKnowledgeSource集成^^13^^

  2. 记忆机制

    • 为代理配置短期记忆,提升上下文理解能力^^5^^14^^

  3. 工具扩展

    • 自定义工具需实现validate_inputrun方法^^7^^

五、常见问题

  • 代理协作失败:检查任务依赖关系是否合理^^4^^

  • 工具调用错误:验证输入参数格式及API权限^^7^^

  • 性能优化:启用verbose=False减少日志输出^^3^^
    (AI生成)

实践

安装

pip install crewai[tools]

验证安装

pip freeze | grep crewai

创建项目

crewai create crew crewaidemo

创建项目会自动下载文件

项目将包含这些基本文件:

文件 用途
agents.yaml 定义你的AI代理及其角色
tasks.yaml 设置代理任务和工作流程
.env 存储API密钥和环境变量
main.py 项目入口点和执行流程
crew.py 船员编排和协调
tools/ 自定义代理工具的目录

创建目录时会询问使用什么ai 大模型的服务,比如可以选openai

API keys and model saved to .env file
Selected model: gpt-4o
  - Created crewaidemo\.gitignore
  - Created crewaidemo\pyproject.toml
  - Created crewaidemo\README.md
  - Created crewaidemo\knowledge\user_preference.txt
  - Created crewaidemo\src\crewaidemo\__init__.py
  - Created crewaidemo\src\crewaidemo\main.py
  - Created crewaidemo\src\crewaidemo\crew.py
  - Created crewaidemo\src\crewaidemo\tools\custom_tool.py
  - Created crewaidemo\src\crewaidemo\tools\__init__.py
  - Created crewaidemo\src\crewaidemo\config\agents.yaml
  - Created crewaidemo\src\crewaidemo\config\tasks.yaml
Crew crewaidemo created successfully!

修改.env文件

MODEL=gpt-4o
OPENAI_API_KEY=hello
OPENAI_BASE_URL="http://127.0.0.1:1337/v1"
OPENAI_API_KEY="your_key"  # 若使用兼容API
OPENAI_API_BASE="http://127.0.0.1:1337/v1"  # 本地模型地址
OPENAI_MODEL_NAME="default"  # 模型名称 

运行

进入目录,先install再run,执行

crewai install
crewai run

但还是有报错,应该是我的大模型配置有问题。

OpenAIException - MissingAuthError: Response 401: Authentication failed.
 

调试

启动后报错

Traceback (most recent call last):
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\main.py", line 1966, in completion
    raise e
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\main.py", line 1939, in completion
    response = openai_chat_completions.completion(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\llms\openai\openai.py", line 736, in completion
    raise OpenAIError(
litellm.llms.openai.common_utils.OpenAIError: Error code: 401 - {'error': {'message': 'MissingAuthError: Response 401: Authentication failed.'}, 'model': 'gpt-4o'}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\work\crewaidemo\src\crewaidemo\main.py", line 26, in run
    Crewaidemo().crew().kickoff(inputs=inputs)
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\crew.py", line 698, in kickoff
    result = self._run_sequential_process()
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\crew.py", line 812, in _run_sequential_process
    return self._execute_tasks(self.tasks)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\crew.py", line 918, in _execute_tasks
    task_output = task.execute_sync(
                  ^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\task.py", line 377, in execute_sync
    return self._execute_core(agent, context, tools)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\task.py", line 526, in _execute_core
    raise e  # Re-raise the exception after emitting the event
    ^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\task.py", line 441, in _execute_core
    result = agent.execute_task(
             ^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\agent.py", line 467, in execute_task
    raise e
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\agent.py", line 443, in execute_task
    result = self._execute_without_timeout(task_prompt, task)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\agent.py", line 539, in _execute_without_timeout
    return self.agent_executor.invoke(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\agents\crew_agent_executor.py", line 149, in invoke
    formatted_answer = self._invoke_loop()
                       ^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\agents\crew_agent_executor.py", line 243, in _invoke_loop
    raise e
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\agents\crew_agent_executor.py", line 189, in _invoke_loop
    answer = get_llm_response(
             ^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\utilities\agent_utils.py", line 252, in get_llm_response
    raise e
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\utilities\agent_utils.py", line 245, in get_llm_response
    answer = llm.call(
             ^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\llm.py", line 1024, in call
    return self._handle_non_streaming_response(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\crewai\llm.py", line 799, in _handle_non_streaming_response
    response = litellm.completion(**params)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\utils.py", line 1330, in wrapper
    raise e
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\utils.py", line 1205, in wrapper
    result = original_function(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\main.py", line 3427, in completion
    raise exception_type(
          ^^^^^^^^^^^^^^^
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\litellm_core_utils\exception_mapping_utils.py", line 2301, in exception_type
    raise e
  File "E:\work\crewaidemo\.venv\Lib\site-packages\litellm\litellm_core_utils\exception_mapping_utils.py", line 456, in exception_type
    raise AuthenticationError(
litellm.exceptions.AuthenticationError: litellm.AuthenticationError: AuthenticationError: OpenAIException - MissingAuthError: Response 401: Authentication failed.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "e:\work\crewaidemo\.venv\Scripts\run_crew.exe\__main__.py", line 10, in <module>
  File "E:\work\crewaidemo\src\crewaidemo\main.py", line 28, in run
    raise Exception(f"An error occurred while running the crew: {e}")
Exception: An error occurred while running the crew: litellm.AuthenticationError: AuthenticationError: OpenAIException - MissingAuthError: Response 401: Authentication failed.
An error occurred while running the crew: Command '['uv', 'run', 'run_crew']' returned non-zero exit status 1.

问题未解决

Logo

更多推荐