AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


基于CrewAI的大模型Multi-Agent实践及分析
发布日期:2024-09-07 07:26:53 浏览次数: 1575


本文使用CrewAI框架实现的大模型Multi-Agent进行旅行规划,并尝试思考Multi Agent的模式是否在实际场景中能落地。

Part 1 概念介绍


定义
属性
Agents

Agent作为自主单元用于

  • 完成任务

  • 制定决策

  • 与其Agent通信

可以类别为一家公司里面有着特定技能的工程师,比如产品、测试、开发,为最终公司的目标努力。


  • 角色定义

  • 目标

  • 上下文背景

Tasks提供了执行所需的细节如描述、对应agent、所需工具等
  • 任务描述

  • 负责的Agent

  • 预期输出

Toolsagent完成任务所需技能,来自crewai toolKit和langchain tools如SerperDevTool搜索
Process团队协作的方式
  • 顺序执行

  • 层次执行:一个经理agent调度,其他agent并行或顺序完成

Crew代表一个团队,通过多agent按workflow使用多个工具完成特定任务
  • Tasks

  • Agents

  • Process

以接下来CrewAI提供的旅行规划demo为例:

    Ref:https://docs.crewai.com/core-concepts/Processes/

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"] = '此处填写'

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)
    # check if there is an organic key
    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

agents.py

from crewai import Agent

from search_tools import SearchTools
from azure.identity import ClientSecretCredential
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage

# 这里使用azure openai
sp_credential = ClientSecretCredential(
    client_id=“填写你的”,
    client_secret=填写你的”,
    tenant_id=填写你的”
)
token = sp_credential.get_token("https://cognitiveservices.azure.com/.default")
azurellm = AzureChatOpenAI(
    model_name='gpt-3.5-turbo-16k', deployment_name='gpt-35-turbo-16k',
    openai_api_type="azure_ad",
    openai_api_version="2024-02-15-preview",
    openai_api_base="填写你的”,
    openai_api_key=token.token
)


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 travel data to pick ideal destinations。Reply In Chinese!',
        tools=[
            SearchTools.search_internet,
            #BrowserTools.scrape_and_summarize_website,
        ],llm=azurellm,
        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,
            #BrowserTools.scrape_and_summarize_website,
        ],llm=azurellm,
        verbose=True)

  def travel_concierge(self):
    return Agent(
        role='Amazing Travel Concierge',
        goal="""Create the most amazing travel itineraries with budget and 
        packing suggestions for the city""",
        backstory="""Specialist in travel planning and logistics with 
        decades of experience。Reply In Chinese!""",
        tools=[
            SearchTools.search_internet,
            #BrowserTools.scrape_and_summarize_website,
            CalculatorTools.calculate,
        ],llm=azurellm,
        verbose=True)

4、创建Tasks

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 travel costs. This task involves comparing
        multiple cities, considering factors like current weather
        conditions, upcoming cultural or seasonal events, and
        overall travel expenses. 
        
        {self.__tip_section()}

        Traveling from: {origin}
        City Options: {cities}
        Trip Date: {range}
        Traveler 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 traveling there and wanting 
        to have 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.
        This guide should provide a thorough overview of what 
        the city has to offer, including hidden gems, cultural
        hotspots, must-visit landmarks, weather forecasts, and
        high level costs. Reply In Chinese!
        
        {self.__tip_section()}

        Trip Date: {range}
        Traveling from: {origin}
        Traveler 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 travel experience.
      """),
                    agent=agent)

    def plan_task(self, agent, origin, interests, range):
        return Task(description=dedent(f"""
        Expand this guide into a a full 7-day travel 
        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.
        
        This itinerary should cover all aspects of the trip, 
        from arrival to departure, integrating the city guide
        information with practical travel logistics. Reply In Chinese!

        Trip Date: {range}
        Traveling from: {origin}
        Traveler Interests: {interests}
      """),
                    expected_output=dedent(f"""
        Your final answer MUST be a complete expanded travel 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, Be specific and give it a reason why you picked
        # up each place, what make them special! {self.__tip_section()} 。Reply In Chinese!
      """),
                    agent=agent)


    def __tip_section(self):
        return "If you do your BEST WORK, I'll tip you $100!"

5、创建Crew、运行Crew

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()
    travel_concierge_agent = agents.travel_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(
      travel_concierge_agent, 
      self.origin,
      self.interests,
      self.date_range
    )

    crew = Crew(
      agents=[
        city_selector_agent, local_expert_agent, travel_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(
    dedent("""
      From where will you be traveling from?
    """))
  cities = input(
    dedent("""
      What are the cities options you are interested in visiting?
    """))
  date_range = input(
    dedent("""
      What is the date range you are interested in traveling?
    """))
  interests = input(
    dedent("""
      What are some of your high level interests and hobbies?
    """))
  
  trip_crew = TripCrew(location, cities, date_range, interests)
  result = trip_crew.run()
  print("\n\n########################")
  print("## Here is you Trip Plan")
  print("########################\n")
  print(result)

Part 3 运行结果log

因为输出太长,这里只截取出部分log,能体现基本multi-agent流程的内容。

大致流程为: 

1、收集用户旅行的信息如出行目的地候选,特殊偏好

2、根据费用、天气、季节活动、旅行费用等选择城市 

3、根据选择城市查询景点、活动等 

4、根据天气、景点、活动、费用、餐馆等规划行程

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

-----人工备注2:Agent1开始工作,进行城市选择

Traveling from: 上海
City Options: 安庆 合肥 杭州 惠州 湖州
Trip Date: next week
Traveler Interests: no
> Entering new CrewAgentExecutor chain...
我需要使用搜索工具来获取每个城市的天气、季节活动和旅行费用信息。然后,我可以根据这些信息来选择最佳的城市。

Action: Search the internet
Action Input: {"query": "上海到安庆航班价格"} 

Title: 从上海出发前往安庆的特价机票 - 机票预订
Link: https://www.tianxun.com/routes/csha/aqg/shanghai-to-anqing.html
Snippet: 从上海到安庆的航班价格. 正在寻找从上海到安庆的最后时刻航班或超值往返航班?在这里您可以找到单程机票和往返机票的最低价格。安庆.每位乘客¥2,346。6月3日周一 ...


Thought:
我已经找到了安庆的天气预报信息。现在我需要搜索安庆的季节活动和旅行费用。

Action: Search the internet
Action Input: {"query": "安庆季节活动"} 
-----------------

Thought:
我已经收集到了上海到安庆的航班价格、安庆的天气预报和一些季节活动信息。现在我需要搜索其他城市的相关信息,以便选择最佳的城市。


Action: Search the internet
Action Input: {"query": "上海到杭州航班价格"} 

Title: 从上海出发前往杭州的特价机票 - 机票预订
Link: https://www.tianxun.com/routes/csha/hgh/shanghai-to-hangzhou.html
Snippet: 春秋航空的非直飞去程航班,5月16日周四从上海浦东出发,到达杭州。吉祥航空的非直飞回程航班,5月18日周六从杭州出发,到达上海浦东。价格包括税款和费用。¥1,763起,选择。

Thought:
我已经找到了上海到杭州的航班价格信息。现在我需要搜索杭州的天气预报和季节活动。

Action: Search the internet
Action Input: {"query": "杭州天气预报"} 

Title: 预报- 杭州 - 中国天气网
Link: http://www.weather.com.cn/weather/101210101.shtml
Snippet: 13日(今天). 晴. 15℃. 3-4级 · 14日(明天). 晴. 28℃/14℃. 4-5级转3-4级 · 15日(后天). 晴. 28℃/13℃. 4-5级转3-4级 · 16日(周四). 晴转多云. 28℃/13℃. 3-4级转<3级 ...

Thought:
我已经找到了杭州的天气预报信息。现在我需要搜索杭州的季节活动和旅行费用。

Action: Search the internet
Action Input: {"query": "杭州季节活动"} 

Title: 杭州最佳旅行时间
Link: https://www.hangyouquan.com/guide/besttraveltime.html
Snippet: 3-4月、9-10月是杭州的最佳旅行时间。但品味杭州,无所谓季节,也无所谓天气。因为西湖如同一位魔术师,无论春夏秋冬、阴晴雨雪,都能幻化出绝美的姿容。

Thought:
我已经收集了杭州的天气预报和季节活动信息。现在我需要搜索杭州的旅行费用。

。。。

Final Answer:
根据收集到的信息,以下是每个城市的相关信息:

安庆:
- 上海到安庆的航班价格为每位乘客¥2,346。
- 安庆的天气预报显示,下周的天气晴朗,气温在26℃到27℃之间。
- 安庆的季节活动包括“四季有戏”黄梅戏展演和安庆市的各个公园和景点如巨石山、菱湖公园等。

合肥:
- 上海到合肥的航班价格为每位乘客¥1,367。
- 合肥的天气预报显示,下周的天气晴朗,气温在28℃到29℃之间。
- 合肥的季节活动包括“村晚”示范展示点活动和合肥市的各个公园和景点如逍遥津公园、天鹅湖等。

杭州:
- 上海到杭州的航班价格为每位乘客¥1,763。
- 杭州的天气预报显示,下周的天气晴朗,气温在28℃到29℃之间。
- 杭州的季节活动包括湖州的各个公园和景点如小莲庄、湖州飞英公园等。

湖州:
- 上海到湖州的航班价格为每位乘客¥300-500。
- 湖州的天气预报显示,下周的天气晴朗,气温在28℃到29℃之间。
- 湖州的季节活动包括湖州的各个公园和景点如小莲庄、湖州飞英公园等。

根据这些信息,我推荐选择杭州作为最佳的城市。杭州的航班价格较为合适,天气晴朗,而且有丰富的季节活动和景点供游客参观。

-----人工备注3:Agent2开始工作,进行本地景点、当地风俗、特色活动 深入查询介绍

> Entering new CrewAgentExecutor chain...
我需要通过搜索互联网和向同事提问来获取关于杭州的深入了解,以便为旅行者提供最佳的旅行体验。我将首先搜索杭州的主要景点和当地的特色活动。接下来,我将向同事询问一些问题,以获得更多关于杭州的信息。

Action: Search the internet
Action Input: {"query": "杭州主要景点"} 

Title: 杭州市10 大景点玩乐 - Tripadvisor
Link: https://cn.tripadvisor.com/Attractions-g298559-Activities-Hangzhou_Zhejiang.html
Snippet: 1. 西湖 · 7,546. 景观步行区. 入场门票低至US$65 · 2. 灵隐寺 · 1,467. 历史景点 · 3. 飞来峰 · 495. 历史景点 · 4. 平湖秋月 · 420. 游客中心 · 5. 孤山 · 451. 历史遗迹徒步 ...


Thought: 通过搜索互联网,我找到了一些杭州的主要景点。现在我需要向同事询问一些问题,以获取更多关于杭州的信息。

Action: Ask question to co-worker
Action Input: {"question": "杭州有哪些当地的特色活动?", "context": "根据收集到的信息,以下是每个城市的相关信息:\n\n安庆:\n- 上海到安庆的航班价格为每位乘客¥2,346。\n- 安庆的天气预报显示,下周的天气晴朗,气温在26℃到27℃之间。\n- 安庆的季节活动包括“四季有戏”黄梅戏展演和安庆市的各个公园和景点如巨石山、菱湖公园等。\n\n合肥:\n- 上海到合肥的航班价格为每位乘客¥1,367。\n- 合肥的天气预报显示,下周的天气晴朗,气温在28℃到29℃之间。\n- 合肥的季节活动包括“村晚”示范展示点活动和合肥市的各个公园和景点如逍遥津公园、天鹅湖等。\n\n杭州:\n- 上海到杭州的航班价格为每位乘客¥1,763。\n- 杭州的天气预报显示,下周的天气晴朗,气温在28℃到29℃之间。\n- 杭州的季节活动包括湖州的各个公园和景点如小莲庄、湖州飞英公园等。\n\n湖州:\n- 上海到湖州的航班价格为每位乘客¥300-500。\n- 湖州的天气预报显示,下周的天气晴朗,气温在28℃到29℃之间。\n- 湖州的季节活动包括湖州的各个公园和景点如小莲庄、湖州飞英公园等。\n\n根据这些信息,我推荐选择杭州作为最佳的城市。杭州的航班价格较为合适,天气晴朗,而且有丰富的季节活动和景点供游客参观。"} 

-----人工备注3. 1: 遇到程序错误汇自我反思纠正,确保不卡壳
I encountered an error while trying to use the tool. This was the error: 'NoneType' object has no attribute 'startswith'.
 Tool Ask question to co-worker accepts these inputs: Ask question to co-worker(question: str, context: str, coworker: Optional[str] = None, **kwargs) - Ask a specific question to one of the following co-workers: [City Selection Expert, Amazing Travel Concierge]
The input to this tool should be the co-worker, the question you have for them, and ALL necessary context to ask the question properly, they know nothing about the question, so share absolute everything you know, don't reference things but instead explain them.


-----人工备注4:Agent3开始工作,进行行程的规划,需要考虑天气等

> Entering new CrewAgentExecutor chain...
根据旅行者的兴趣,我需要为他们提供一个7天的杭州旅行计划。在这个计划中,我需要提供每天的行程安排、天气预报、推荐的服装和物品携带、详细的预算。我将使用以下工具来完成这个任务:搜索互联网、进行计算、委派任务给同事、向同事提问。

Action: Search the internet
Action Input: {"query": "杭州当地的餐厅推荐"} 

Title: 杭州市10 大餐厅 - Tripadvisor
Link: https://cn.tripadvisor.com/Restaurants-g298559-Hangzhou_Zhejiang.html
Snippet: 杭州市餐厅 ; 1. 澜亭中餐厅. (153). 中餐, 亚洲料理¥¥¥¥ ; 2. 静岸标帜自助餐厅&酒吧(杭州绿城尊蓝钱江豪华精选酒店). (157). 牛排馆, 烧烤¥¥ - ¥¥¥ ; 3. 四季酒店金沙厅.
。。。

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

## 行程安排
### 第一天:到达杭州
- 上午:抵达杭州,入住酒店,休息
- 下午:漫步西湖,欣赏美丽的自然景色
- 晚上:逛西湖商圈,品尝当地美食
### 第二天:探索名胜古迹
- 上午:参观灵隐寺,感受宁静的氛围,了解佛教文化
- 下午:爬上飞来峰,俯瞰整个城市的美景
- 晚上:参观平湖秋月,欣赏秋天的美景
### 第三天:体验当地风俗
- 上午:参加拜年活动,体验中国农历新年的传统习俗
- 下午:参加元宵节活动,品尝元宵、赏花灯、猜灯谜
- 晚上:参加中秋节活动,品尝月饼、赏月、放天灯
### 第四天:探索自然风光
- 上午:徒步游览孤山,欣赏壮丽的自然风景
- 下午:参观湿地公园,欣赏丰富的生态系统和各种鸟类
- 晚上:享受自由时光,休息放松
### 第五天:品味茶文化
- 上午:参观龙井茶园,品尝杭州龙井茶,了解茶文化的历史和传统
- 下午:参观杭州的博物馆,了解当地的历史和文化
- 晚上:享受自由时光,休息放松
### 第六天:漫游西湖
- 上午:乘船游览西湖,欣赏美丽的湖景和周围的山水
- 下午:逛西湖商圈,购物品尝当地美食
- 晚上:参加西湖漫游活动,感受西湖的独特魅力
### 第七天:离开杭州
- 上午:自由活动,购买纪念品
- 下午:离开杭州,结束愉快的旅行
## 天气预报
根据中国天气网的预报,下周杭州的天气如下:
- 周一:阴,29℃/20℃,东南风3-4级转<3级
- 周二:雨转阴
- 周三:晴转多云
- 周四:晴
- 周五:晴转小雨
## 服装和物品携带
根据知乎专栏和其他网站的推荐,建议携带以下物品:
- 个人常用药
- 笔记本电脑
- 换洗衣服
- 卫生用品
- 化妆品
- 面膜
- 洗漱用品
- 吸汗的、透气的棉质衣物
- 轻薄的外套
- 保温的衣服
- 棉鞋
## 预算
根据收集到的信息,杭州的航班价格为每位乘客¥1,763。其他花费如酒店、餐饮和门票价格因个人需求而异,预计每天的花费在300-500元左右。
希望这个旅行计划能够帮助旅行者在杭州度过一段难忘的时光!

效果:能不能完成任务,从这个任务来看,虽然按顺序流程有模有样的执行,也成功搜索到了杭州的旅行特色景点等,但最终的结果有挺大问题,上海去杭州还得买这么贵机票,不知道怎么来的;还有元宵节等活动也是比较离谱。可能是因为是直接复用crewai的demo代码和工具本身获取的信息有误,换成国外的case可能会好一些。

虽然结果上来说挺差的,但不妨碍帮助我们理解多agent的运行流程,在这个基础上我们可以在其他场景进一步优化。 

性能:耗时需要分钟以上级别。所以如果不是个价值高无需实时的场景是没法用的

成本:所需token会比单agent更多,因为不同agent通信也会增加token量,加上调用工具及反思的迭代过程所需token依赖比较高。

Part 4 思考

让专业的人做专业的事,这是多智能体的哲学,在人类社会和agent社会是一样的道理,找到比较符合的场景,使用多智能体的方式去做,可能会达到不错的效果。在GPT5来临之前,使用更小的模型经过精心的编排可能可以提前感受到智能体的智慧。其中的一个关键,还是我们足够理解业务,理解自身的需求,到底杀鸡要不要用牛刀?取决于我们对鸡的了解和重视程度。使用最少的开发成本多去设计、尝试,在实践中获得反馈,或许是我们可以做的事情。


53AI,企业落地应用大模型首选服务商

产品:大模型应用平台+智能体定制开发+落地咨询服务

承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

与创始人交个朋友

回到顶部

 
扫码咨询