游乐游手机版
首页/AI热点日报/热点详情

基于CrewAI的多智能体大模型实践解析

类型:热点整理2026-06-23
这篇实践文章基于CrewAI框架,借助大模型的Multi-Agent能力打造了一款旅行规划工具,并深入探讨了这种多智能体模式在实际场景中的落地可能性。先说结论:想法值得肯定,但踩坑也不少,让我们一步步拆解。 Part 1 核心概念解析 在进入代码细节之前,有必要先理清CrewAI中的几个核心概念,它

这篇实践文章基于CrewAI框架,借助大模型的Multi-Agent能力打造了一款旅行规划工具,并深入探讨了这种多智能体模式在实际场景中的落地可能性。先说结论:想法值得肯定,但踩坑也不少,让我们一步步拆解。

基于CrewAI的大模型Multi-Agent实践及分析

Part 1 核心概念解析

在进入代码细节之前,有必要先理清CrewAI中的几个核心概念,它们是理解后续所有操作的基础。

组件定义属性
Agents

Agent是自主执行单元,负责完成任务、制定决策,并与其他Agent通信。可以类比为一家公司里各司其职的工程师——比如产品、开发、测试,大家朝着一个共同目标努力。

  • 角色定义

  • 目标

  • 上下文背景

Tasks提供执行所需的具体细节,比如任务描述、由哪个Agent负责、需要用到什么工具等。
  • 任务描述

  • 负责的Agent

  • 预期输出

ToolsAgent完成任务所需的技能,来自CrewAI ToolKit或LangChain的工具集。比如SerperDevTool就是专门用于网络搜索的。
Process团队协作的方式。
  • 顺序执行

  • 层次执行:一个Manager Agent做调度,其他Agent可以并行或顺序完成子任务。

Crew代表一个完整的团队,多个Agent按照工作流调用多种工具来完成特定任务。
  • Tasks

  • Agents

  • Process

接下来,我们就用CrewAI官方提供的旅行规划Demo来拆解,看看这些组件在实际运行时是如何协同工作的。

Part 2 落地实践

1. 环境安装

首先安装必要的依赖包:

pip install crewai crewai_tools langchain_community

本篇文章测试版本为:
crewai==0.30.8
crewai-tools==0.2.6
langchain==0.1.20
langchain-community==0.0.38

2. 创建CrewAI Tools

以搜索工具为例,以下代码实现了一个基础的网络搜索能力:

search_tool.py

import json
import requests
from langchain.tools import tool
import os

# 在https://serper.dev/上注册后可免费获取key
os.environ["SERPER_API_KEY"] = 'your_api_key'

class SearchTools():

  @tool("Search the internet")
  def search_internet(query):
    """Useful to search the internet
    about a a given topic and return relevant results"""
    top_result_to_return = 4
    url = "https://google.serper.dev/search"
    payload = json.dumps({"q": query})
    headers = {
        'X-API-KEY': os.environ['SERPER_API_KEY'],
        'content-type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    if 'organic' not in response.json():
      return "Sorry, I couldn't find anything about that, there could be an error with you serper api key."
    else:
      results = response.json()['organic']
      string = []
      for result in results[:top_result_to_return]:
        try:
          string.append('n'.join([
              f"Title: {result['title']}", f"Link: {result['link']}",
              f"Snippet: {result['snippet']}", "n-----------------"
          ]))
        except KeyError:
          next
      return 'n'.join(string)

3. 创建Agents

一共设计了三个Agent,分别对应旅行规划中的不同角色:城市选择专家、本地达人、旅行管家。它们各自承担不同的目标,共享搜索工具,但分工各有侧重。

agents.py

from crewai import Agent
from search_tools import SearchTools

# LLM配置部分(此处使用Azure OpenAI,实际可按需替换)
# ...

class TripAgents():

  def city_selection_agent(self):
    return Agent(
        role='City Selection Expert',
        goal='Select the best city based on weather, season, and prices',
        backstory=
        'An expert in analyzing tra vel data to pick ideal destinations。Reply In Chinese!',
        tools=[
            SearchTools.search_internet,
        ],
        verbose=True)

  def local_expert(self):
    return Agent(
        role='Local Expert at this city',
        goal='Provide the BEST insights about the selected city',
        backstory="""A knowledgeable local guide with extensive information
        about the city, it's attractions and customs。Reply In Chinese!""",
        tools=[
            SearchTools.search_internet,
        ],
        verbose=True)

  def tra vel_concierge(self):
    return Agent(
        role='Amazing Tra vel Concierge',
        goal="""Create the most amazing tra vel itineraries with budget and
        packing suggestions for the city""",
        backstory="""Specialist in tra vel planning and logistics with
        decades of experience。Reply In Chinese!""",
        tools=[
            SearchTools.search_internet,
        ],
        verbose=True)

4. 创建Tasks

每个Agent对应一个任务。从“识别城市”到“信息收集”,再到“行程规划”,层层递进,任务之间天然存在依赖关系。

task.py

from crewai import Task
from textwrap import dedent

class TripTasks():

    def identify_task(self, agent, origin, cities, interests, range):
        return Task(description=dedent(f"""
        Analyze and select the best city for the trip based
        on specific criteria such as weather patterns, seasonal
        events, and tra vel costs. This task involves comparing
        multiple cities, considering factors like current weather
        conditions, upcoming cultural or seasonal events, and
        overall tra vel expenses.

        Tra veling from: {origin}
        City Options: {cities}
        Trip Date: {range}
        Tra veler Interests: {interests}
      """),
                    expected_output=dedent("""
        Your final answer must be a detailed
        report on the chosen city, and everything you found out
        about it, including the actual flight costs, weather
         forecast and attractions.Reply In Chinese!
      """),
                    agent=agent)

    def gather_task(self, agent, origin, interests, range):
        return Task(description=dedent(f"""
        As a local expert on this city you must compile an
        in-depth guide for someone tra veling there and wanting
        to ha ve THE BEST trip ever!
        Gather information about  key attractions, local customs,
        special events, and daily activity recommendations.
        Find the best spots to go to, the kind of place only a
        local would know.

        Trip Date: {range}
        Tra veling from: {origin}
        Tra veler Interests: {interests}
      """),
                    expected_output=dedent("""
        The final answer must be a comprehensive city guide,
        rich in cultural insights and practical tips,
        tailored to enhance the tra vel experience.
      """),
                    agent=agent)

    def plan_task(self, agent, origin, interests, range):
        return Task(description=dedent(f"""
        Expand this guide into a full 7-day tra vel
        itinerary with detailed per-day plans, including
        weather forecasts, places to eat, packing suggestions,
        and a budget breakdown.

        You MUST suggest actual places to visit, actual hotels
        to stay and actual restaurants to go to.

        Trip Date: {range}
        Tra veling from: {origin}
        Tra veler Interests: {interests}
      """),
                    expected_output=dedent(f"""
        Your final answer MUST be a complete expanded tra vel plan,
        formatted as markdown, encompassing a daily schedule,
        anticipated weather conditions, recommended clothing and
        items to pack, and a detailed budget, ensuring THE BEST
        TRIP EVER.
      """),
                    agent=agent)

5. 创建并运行Crew

将Agent和Tasks组装进一个Crew,然后调用kickoff()启动整个工作流:

from crewai import Crew
from textwrap import dedent
from trip_agents import TripAgents
from trip_tasks import TripTasks

class TripCrew:

  def __init__(self, origin, cities, date_range, interests):
    self.cities = cities
    self.origin = origin
    self.interests = interests
    self.date_range = date_range

  def run(self):
    agents = TripAgents()
    tasks = TripTasks()

    city_selector_agent = agents.city_selection_agent()
    local_expert_agent = agents.local_expert()
    tra vel_concierge_agent = agents.tra vel_concierge()

    identify_task = tasks.identify_task(
      city_selector_agent,
      self.origin,
      self.cities,
      self.interests,
      self.date_range
    )
    gather_task = tasks.gather_task(
      local_expert_agent,
      self.origin,
      self.interests,
      self.date_range
    )
    plan_task = tasks.plan_task(
      tra vel_concierge_agent,
      self.origin,
      self.interests,
      self.date_range
    )

    crew = Crew(
      agents=[
        city_selector_agent, local_expert_agent, tra vel_concierge_agent
      ],
      tasks=[identify_task, gather_task, plan_task],
      verbose=True
    )

    result = crew.kickoff()
    return result

if __name__ == "__main__":
  print("## Welcome to Trip Planner Crew")
  print('-------------------------------')
  location = input("From where will you be tra veling from?n")
  cities = input("What are the cities options you are interested in visiting?n")
  date_range = input("What is the date range you are interested in tra veling?n")
  interests = input("What are some of your high level interests and hobbies?n")

  trip_crew = TripCrew(location, cities, date_range, interests)
  result = trip_crew.run()
  print("nn########################")
  print("## Here is you Trip Plan")
  print("########################n")
  print(result)

Part 3 运行结果与分析

输出内容较长,这里截取关键步骤。整体流程如下:

  • Step 1:收集用户的出发地、候选城市、出行时间、偏好信息。
  • Step 2:根据费用、天气、季节活动等因素筛选最佳城市。
  • Step 3:针对选定城市,深入查询景点、当地习俗等深度信息。
  • Step 4:结合天气、景点、餐饮、预算等,规划出完整的行程。

日志中展示了典型的Multi-Agent协作全过程:

-----人工备注1:信息收集,包含出发地、候选城市列表、出行时间、特殊偏好
From where will you be tra veling from?
上海
What are the cities options you are interested in visiting?
安庆 合肥 杭州 惠州 湖州
What is the date range you are interested in tra veling?
next week
What are some of your high level interests and hobbies?
no

-----人工备注2:Agent1开始工作,进行城市选择
Tra veling from: 上海
City Options: 安庆 合肥 杭州 惠州 湖州
Trip Date: next week
Tra veler Interests: no
> Entering new CrewAgentExecutor chain...
我需要使用搜索工具来获取每个城市的天气、季节活动和旅行费用信息。
...
Final Answer:
根据收集到的信息,我推荐选择杭州作为最佳的城市。杭州的航班价格较为合适,天气晴朗,而且有丰富的季节活动和景点供游客参观。

-----人工备注3:Agent2开始工作,进行本地景点、当地风俗、特色活动深入查询介绍
> Entering new CrewAgentExecutor chain...
我需要通过搜索互联网获取关于杭州的深入了解...
...

-----人工备注3.1:遇到程序错误后自我反思纠正,确保不卡壳
I encountered an error while trying to use the tool...
...

-----人工备注4:Agent3开始工作,进行行程规划
> Entering new CrewAgentExecutor chain...
根据旅行者的兴趣,我需要为他们提供一个7天的杭州旅行计划...
...

-----人工备注5:所有Agent完成任务,汇总结果
# 杭州7天旅行计划

## 行程安排
...
## 天气预报
...
## 服装和物品携带
...
## 预算
...
希望这个旅行计划能够帮助旅行者在杭州度过一段难忘的时光!

效果评价:回到核心问题——这种Multi-Agent模式是否真的能落地?

从本次实践来看,流程确实跑通了,Agent之间的协作有模有样,也确实搜索到了杭州的特色景点。但最终输出质量的问题也很明显:上海到杭州的机票价格标得离谱,元宵节之类的活动出现在行程里更是完全不符合实际时间。这些bug很大程度上源于Demo代码本身的硬伤,以及搜索工具返回了不够准确的信息。换成境外旅行场景,数据源可能更成熟,效果或许会好一些。

性能:一次完整的任务耗时在分钟级别以上。如果不是价值较高、不需要实时响应的场景,基本难以直接使用。

成本:Token消耗远超单Agent模式。Agent之间的通信、工具调用、甚至错误纠正过程中的反思机制,都会显著增加Token消耗。

Part 4 思考与展望

“让专业的人做专业的事”这句话,放在人类社会里成立,放在Agent社会里同样适用。关键是要找到真正匹配的场景。如果能找到合适的业务切口,用多个小模型加上精心编排的工作流,或许在GPT-5真正到来之前,我们就能提前体验到一点“智能体”的潜力。

说到底,核心还是在于我们对业务本身有多了解——杀鸡到底要不要用牛刀?答案取决于我们是否真的看清楚了那只鸡的价值。现阶段最有价值的做法,或许就是花最少的开发成本,多设计、多测试、在快速反馈中不断迭代。毕竟,实践才是检验“智能”的唯一标准。

来源:https://www.53ai.com/news/LargeLanguageModel/2024090739501.html

相关热点

继续查看同栏目近期热点。

延伸阅读

补充最近整理过的热点入口。