AutoGen和metagpt使用

什么是 AutoGen

AutoGen 是一个框架,它支持使用多个可以相互交流以解决任务的代理来开发 LLM 应用程序。AutoGen 代理可自定义、可交流,并可无缝允许人类参与。它们可以采用多种模式运行,这些模式结合了 LLM、人类输入和工具。

AutoGen 概述

  • AutoGen 能够以最小的努力构建基于多代理对话的下一代 LLM 应用程序。它简化了复杂 LLM 工作流程的编排、自动化和优化。它最大限度地提高了 LLM 模型的性能并克服了它们的弱点。
  • 它支持复杂工作流的多种对话模式。借助可自定义且可对话的代理,开发人员可以使用 AutoGen 构建有关对话自主性、代理数量和代理对话拓扑的各种对话模式。
  • 它提供了一系列具有不同复杂性的工作系统。这些系统涵盖各种领域和复杂性的广泛应用。这演示了 AutoGen 如何轻松支持不同的对话模式。
  • AutoGen 提供增强的 LLM 推理。它提供 API 统一和缓存等实用程序,以及错误处理、多配置推理、上下文编程等高级使用模式。

AutoGen由微软、宾夕法尼亚州立大学和华盛顿大学的合作研究提供支持。

多代理对话框架

Autogen 为下一代 LLM 应用程序提供了通用的多代理对话框架。它提供可定制且可对话的代理,将 LLM、工具和人员集成在一起。通过自动在多个有能力的代理之间进行聊天,可以轻松地让他们集体自主执行任务或在人工反馈下执行任务,包括需要通过代码使用工具的任务。

此用例的特点包括:

  • 多代理对话:AutoGen 代理可以相互通信以解决任务。与单个 LLM 相比,这可以实现更复杂、更精密的应用程序。
  • 定制:可以定制 AutoGen 代理以满足应用程序的特定需求。这包括选择要使用的法学硕士、允许的人工输入类型以及要使用的工具的能力。
  • 人工参与:AutoGen 无缝允许人工参与。这意味着人类可以根据需要向代理提供输入和反馈。

例如

from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
# Load LLM inference endpoints from an env variable or a file
# See https://microsoft.github.io/autogen/docs/FAQ#set-your-api-endpoints
# and OAI_CONFIG_LIST_sample
config_list = config_list_from_json(env_or_file="OAI_CONFIG_LIST")
# You can also set config_list directly as a list, for example, config_list = [{'model': 'gpt-4', 'api_key': '<your OpenAI API key here>'},]
assistant = AssistantAgent("assistant", llm_config={"config_list": config_list})
user_proxy = UserProxyAgent("user_proxy", code_execution_config={"work_dir": "coding", "use_docker": False}) # IMPORTANT: set to True to run code in docker, recommended
user_proxy.initiate_chat(assistant, message="Plot a chart of NVDA and TESLA stock price change YTD.")
# This initiates an automated chat between the two agents to solve the task
 

这个例子可以运行

python test/twoagent.py
 

克隆存储库后。下图显示了 AutoGen 的示例对话流程。 代理聊天示例

另外,此处的示例代码允许用户以 ChatGPT 风格与 AutoGen 代理聊天。请查看此功能的更多代码示例。

 

一个实际应用示例:

# 导入autogen包
import autogen

#配置大模型
llm_config = {
    "config_list": [{"model": "gpt-3.5-turbo", "api_key": 'xxxxx'}]
}

# 定义鲜花电商的运营任务
inventory_tasks = [
    """查看当前库存中各种鲜花的数量,并报告哪些鲜花库存不足。""",
    """根据过去一个月的销售数据,预测接下来一个月哪些鲜花的需求量会增加。""",
]

market_research_tasks = ["""分析市场趋势,找出当前最受欢迎的鲜花种类及其可能的原因。"""]

content_creation_tasks = ["""利用提供的信息,撰写一篇吸引人的博客文章,介绍最受欢迎的鲜花及选购技巧。"""]

# 创建Agent角色
inventory_assistant = autogen.AssistantAgent(
    name="库存管理助理",
    llm_config=llm_config
)
market_research_assistant = autogen.AssistantAgent(
    name="市场研究助理",
    llm_config= llm_config
)
content_creator = autogen.AssistantAgent(
    name="内容创作助理",
    llm_config= llm_config,
    system_message="""
        你是一名专业的写作者,以洞察力强和文章引人入胜著称。
        你能将复杂的概念转化为引人入胜的叙述。
        当一切完成后,请回复“结束”。
        """
)

# 创建用户代理
user_proxy_auto = autogen.UserProxyAgent(
    name="用户代理_自动",
    human_input_mode="NEVER",
    is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("结束"),
    code_execution_config={
        "last_n_messages": 1,
        "work_dir": "tasks",
        "use_docker": False,
    },
)

user_proxy = autogen.UserProxyAgent(
    name="用户代理",
    human_input_mode="ALWAYS",
    is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("结束"),
    code_execution_config={
        "last_n_messages": 1,
        "work_dir": "tasks",
        "use_docker": False,
    },
)

# 发起对话
chat_results = autogen.initiate_chats(
    [
        {
            "sender": user_proxy_auto,
            "recipient": inventory_assistant,
            "message": inventory_tasks[0],
            "clear_history": True,
            "silent": False,
            "summary_method": "last_msg",
        },
        {
            "sender": user_proxy_auto,
            "recipient": market_research_assistant,
            "message": market_research_tasks[0],
            "max_turns": 2,
            "summary_method": "reflection_with_llm",
        },
        {
            "sender": user_proxy,
            "recipient": content_creator,
            "message": content_creation_tasks[0],
            "carryover": "我希望在博客文章中包含一张数据表格或图表。",
        },
    ]
)

  

这段代码是一个示例,展示了如何使用一个名为"autogen"的包来创建对话系统。在代码中:

  1. 导入了 "autogen" 包。
  2. 配置了一个大型语言模型(llm)的参数。
  3. 定义了不同角色的任务列表,例如库存管理、市场研究和内容创作任务。
  4. 创建了不同的代理角色,如库存管理助理、市场研究助理和内容创作助理。
  5. 创建了用户代理角色,分为自动和手动两种模式,用于发起对话。
  6. 最后,通过调用 "initiate_chats" 函数,模拟了用户与不同角色代理之间的对话流程。

总体来说,这段代码演示了如何使用自动生成的对话系统来模拟各种角色之间的交互,例如用户代理、库存管理助理、市场研究助理和内容创作助理之间的对话交流。

运行结果:

********************************************************************************
Starting a new chat....

********************************************************************************
用户代理_自动 (to 库存管理助理):

查看当前库存中各种鲜花的数量,并报告哪些鲜花库存不足。

--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

```python
# filename: check_inventory.py

# Create a dictionary with flower types and their corresponding quantities in the inventory
inventory = {
    'rose': 15,
    'lily': 20,
    'tulip': 10,
    'daisy': 5
}

# Define the minimum quantity required for each flower type
min_quantity = {
    'rose': 10,
    'lily': 15,
    'tulip': 8,
    'daisy': 3
}

# Iterate over the inventory to check for flowers with insufficient stock
flowers_shortage = []
for flower, quantity in inventory.items():
    if quantity < min_quantity[flower]:
        flowers_shortage.append(flower)

# Output the flowers with insufficient stock
if len(flowers_shortage) == 0:
    print("All flowers are in sufficient stock.")
else:
    print("The following flowers have insufficient stock:")
    for flower in flowers_shortage:
        print(flower)

```

After executing the provided Python script, you will be able to see which flowers have insufficient stock in the current inventory. The script compares the quantity of each flower type in the inventory with the defined minimum quantity required and reports the flowers that do not meet the minimum stock requirement.

Please run the Python script provided above to check the flower inventory and identify which flowers are in short supply.

If there are any issues or errors, please let me know for further assistance.

--------------------------------------------------------------------------------

>>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...
用户代理_自动 (to 库存管理助理):

exitcode: 0 (execution succeeded)
Code output:
All flowers are in sufficient stock.


--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

Great! The output indicates that all flowers in the inventory are in sufficient stock.

If you have any more questions or need further assistance, feel free to ask.

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------
库存管理助理 (to 用户代理_自动):

TERMINATE

--------------------------------------------------------------------------------
用户代理_自动 (to 库存管理助理):



--------------------------------------------------------------------------------

  

 

软件公司作为多代理系统

  1. MetaGPT 将一行需求作为输入并输出用户故事/竞争分析/需求/数据结构/API/文档等。
  2. MetaGPT 内部包括产品经理/架构师/项目经理/工程师,提供软件公司的完整流程以及精心策划的 SOP。
    1. Code = SOP(Team)是核心理念。我们具体化SOP并将其应用于由法学硕士组成的团队。

一家软件公司由 LLM 职位组成

软件公司多Agent示意图(逐步实施)

# 导入所需的库
import re
import fire
from metagpt.actions import Action, UserRequirement
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.team import Team

# 定义订单处理动作
class ProcessOrder(Action):
    PROMPT_TEMPLATE: str = """
    Process the following order: {order_details}.
    """

    name: str = "ProcessOrder"

    async def run(self, order_details: str):
        prompt = self.PROMPT_TEMPLATE.format(order_details=order_details)
        rsp = await self._aask(prompt)
        return rsp.strip()

# 定义订单处理角色
class OrderProcessor(Role):
    name: str = "OrderProcessor"
    profile: str = "Process orders"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._watch([UserRequirement])
        self.set_actions([ProcessOrder])


# 定义库存管理动作
class ManageInventory(Action):
    PROMPT_TEMPLATE: str = """
    Update inventory based on the following order: {order_details}.
    """

    name: str = "ManageInventory"

    async def run(self, order_details: str):
        prompt = self.PROMPT_TEMPLATE.format(order_details=order_details)
        rsp = await self._aask(prompt)
        return rsp.strip()

# 定义库存管理角色
class InventoryManager(Role):
    name: str = "InventoryManager"
    profile: str = "Manage inventory"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._watch([ProcessOrder])
        self.set_actions([ManageInventory])


# 定义客服处理动作
class HandleCustomerService(Action):
    PROMPT_TEMPLATE: str = """
    Handle the following customer service request: {request_details}.
    """

    name: str = "HandleCustomerService"

    async def run(self, request_details: str):
        prompt = self.PROMPT_TEMPLATE.format(request_details=request_details)
        rsp = await self._aask(prompt)
        return rsp.strip()

# 定义客服处理角色
class CustomerServiceRepresentative(Role):
    name: str = "CustomerServiceRepresentative"
    profile: str = "Handle customer service"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._watch([UserRequirement, ManageInventory])
        self.set_actions([HandleCustomerService])


# 主函数
async def main(
    order_details: str = "A bouquet of red roses",
    investment: float = 3.0,
    n_round: int = 5,
    add_human: bool = False,
):
    logger.info(order_details)

    team = Team()
    team.hire(
        [
            OrderProcessor(),
            InventoryManager(),
            CustomerServiceRepresentative(is_human=add_human),
        ]
    )

    team.invest(investment=investment)
    team.run_project(order_details)
    await team.run(n_round=n_round)

# 执行程序
if __name__ == "__main__":
    fire.Fire(main)

  

这段Python代码定义了一个团队内部的订单、库存和客服管理系统。以下是代码中的关键组件功能解析:

  1. 动作:代码中定义了三个主要动作:

    • ProcessOrder:根据提供的订单细节处理订单。
    • ManageInventory:根据订单更新库存。
    • HandleCustomerService:处理客服请求。
  2. 角色:

    • OrderProcessor:负责处理订单的角色。包括ProcessOrder动作。
    • InventoryManager:管理库存的角色。包括ManageInventory动作。
    • CustomerServiceRepresentative:处理客服请求的角色。包括HandleCustomerService动作。
  3. 主函数:

    • main函数建立了一个团队,包括处理订单、管理库存和客服角色。
    • 允许自定义订单细节、投资金额、轮数,并可选择是否添加人员参与。
    • 函数雇佣团队成员、投资团队、使用指定订单细节运行项目,然后运行团队多轮。
  4. 执行:

    • 脚本使用fire.Fire(main)来执行main函数,并通过命令行提供参数。

总体而言,这段代码建立了一个模拟环境,用于团队内部管理订单、库存和客服。它允许测试不同场景和团队成员之间在处理业务运营各方面的互动。

运行结果:

metagpt --init-config
2024-05-23 14:42:02.862 | INFO     | metagpt.const:get_metagpt_package_root:29 - Package root set to D:\source\ai_agent\ai-agents\10-multi-agents
Configuration file initialized at C:\Users\l00379637\.metagpt\config2.yaml
PS D:\source\ai_agent\ai-agents\10-multi-agents> notepad  C:\Users\l00379637\.metagpt\config2.yaml
PS D:\source\ai_agent\ai-agents\10-multi-agents> python .\10.2_MetaGPT.py
2024-05-23 14:42:59.957 | INFO     | metagpt.const:get_metagpt_package_root:29 - Package root set to D:\source\ai_agent\ai-agents\10-multi-agents
2024-05-23 14:43:04.395 | INFO     | __main__:main:89 - A bouquet of red roses
2024-05-23 14:43:04.468 | INFO     | metagpt.team:invest:90 - Investment: $3.0.
2024-05-23 14:43:04.471 | INFO     | metagpt.roles.role:_act:391 - OrderProcessor(Process orders): to do ProcessOrder(ProcessOrder)
2024-05-23 14:43:04.509 | INFO     | metagpt.roles.role:_act:391 - CustomerServiceRepresentative(Handle customer service): to do HandleCustomerService(HandleCustomerService)
IHello'm sorry, but as a Process orders,! Thank you for reaching out to Handle customer service. We are happy to assist you with I am not able to physically process your request for orders for tangible items. However, I can provide guidance a bouquet of red roses. We have a on how to process the order, such as finding variety of beautiful red rose bouquets available for purchase. Could you please a florist provide us with the delivery address and any specific or placing an order online. Let me know if delivery instructions? Additionally, do you have a budget in you need any assistance with that!
2024-05-23 14:43:13.867 | INFO     | metagpt.utils.cost_manager:update_cost:57 - Total running cost: $0.000 | Max budget: $3.000 | Current cost: $0.000, prompt_tokens: 43, completion_tokens: 58
 mind for the bouquet? We want to ensure that we find the perfect arrangement for you. Thank you!
2024-05-23 14:43:13.885 | INFO     | metagpt.utils.cost_manager:update_cost:57 - Total running cost: $0.000 | Max budget: $3.000 | Current cost: $0.000, prompt_tokens: 48, completion_tokens: 86
2024-05-23 14:43:13.891 | INFO     | metagpt.roles.role:_act:391 - InventoryManager(Manage inventory): to do ManageInventory(ManageInventory)
As an Inventory Manager, I can assist with updating the inventory for the bouquet of red roses. However, I am not able to physically process orders for tangible items. I recommend reaching out to a florist or placing an order online to fulfill the request for a bouquet of red roses. If you need any further assistance with inventory management or guidance on finding a florist, feel free to ask!
2024-05-23 14:43:16.255 | INFO     | metagpt.utils.cost_manager:update_cost:57 - Total running cost: $0.001 | Max budget: $3.000 | Current cost: $0.000, prompt_tokens: 198, completion_tokens: 79
2024-05-23 14:43:16.262 | INFO     | metagpt.roles.role:_act:391 - CustomerServiceRepresentative(Handle customer service): to do HandleCustomerService(HandleCustomerService)
Hello! Thank you for reaching out to Handle customer service. We are happy to assist you with your request for a bouquet of red roses. We have a variety of beautiful red rose bouquets available for purchase. Could you please provide us with the delivery address and any specific delivery instructions? Additionally, do you have a budget in mind for the bouquet? We want to ensure that we find the perfect arrangement for you. Thank you!
2024-05-23 14:43:38.683 | INFO     | metagpt.utils.cost_manager:update_cost:57 - Total running cost: $0.001 | Max budget: $3.000 | Current cost: $0.000, prompt_tokens: 282, completion_tokens: 86

  

posted @ 2024-05-23 14:33  bonelee  阅读(266)  评论(0编辑  收藏  举报