
Agent(智能体): 具有一定自主性和目标导向性,可以在没有持续人类干预的情况下执行任务和作出决策。以下为Agent的一些特性:
(1)自主性和目标导向性
(2)复杂的工作流程
(3)学习和适应能力
(4)记忆机制
(5)工具使用与集成
LLM 驱动的自主Agents系统概述如下图所示:(包含工具调用、记忆、计划、执行模块)

Agent与ChatGPT的区别: Agent与ChatGPT在设计、功能和目标上有一些关键区别。虽然它们都是基于人工智能技术,但应用方式和交互性质大不相同。下面是这两者的主要区别:
(1)目标和自主性
(2) 交互方式
(3)任务执行和规划能力
(4)技术整合与应用
(5)学习和适应

安装: 必须要python版本在3.9以上 ,这里使用conda,尝鲜安装。
conda create -n metagpt python=3.9 && conda activate metagpt开发模式下安装: 为开发人员推荐。实现新想法和定制化功能。
git clone https://github.com/geekan/MetaGPT.git
cd ./MetaGPT
pip install -e .模型配置: 在文件 ~/.metagpt/config2.yaml下,有关于各大厂商模型的配置详细列表参考:LLM API Configuration
llm:
api_type: "openai" # or azure / ollama / groq etc. Check LLMType for more options
model: "gpt-4-turbo" # or gpt-3.5-turbo
base_url: "https://api.openai.com/v1" # or forward url / other llm url
api_key: "YOUR_API_KEY"概述: 调用ProductManager Agent,注意,会话上下文是需要独立创建的
import asyncio
from metagpt.context import Context
from metagpt.roles.product_manager import ProductManager
from metagpt.logs import logger
async def main():
msg = "Write a PRD for a snake game"
context = Context() # The session Context object is explicitly created, and the Role object implicitly shares it automatically with its own Action object
role = ProductManager(context=context)
while msg:
msg = await role.run(msg)
logger.info(str(msg))
if __name__ == '__main__':
asyncio.run(main())输出结果:

多智能体系统: 即智能体社会,用公式表示为:
MultiAgent = 智能体 + 环境 + 标准化的操作程序(SOP)+ 通信 +经济
各个部分的详细介绍:
简单示例:

具体介绍如下:
概述: 虽然单智能体可以解决很多任务,但是复杂的任务还是需要多智能体之间的协作。
构建智能体团队的步骤如下:
具体的智能体以及对应的行为定义如下:
写代码行为如下:
from metagpt.actions import Action
class SimpleWriteCode(Action):
PROMPT_TEMPLATE: str = """
Write a python function that can {instruction}.
Return ```python your_code_here ```with NO other texts,
your code:
"""
name: str = "SimpleWriteCode"
async def run(self, instruction: str):
prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)
rsp = await self._aask(prompt)
code_text = parse_code(rsp)
return code_text测试用例代码书写行为如下:
class SimpleWriteTest(Action):
PROMPT_TEMPLATE: str = """
Context: {context}
Write {k} unit tests using pytest for the given function, assuming you have imported it.
Return ```python your_code_here ```with NO other texts,
your code:
"""
name: str = "SimpleWriteTest"
async def run(self, context: str, k: int = 3):
prompt = self.PROMPT_TEMPLATE.format(context=context, k=k)
rsp = await self._aask(prompt)
code_text = parse_code(rsp)
return code_text测试用例评审行为如下:
class SimpleWriteReview(Action):
PROMPT_TEMPLATE: str = """
Context: {context}
Review the test cases and provide one critical comments:
"""
name: str = "SimpleWriteReview"
async def run(self, context: str):
prompt = self.PROMPT_TEMPLATE.format(context=context)
rsp = await self._aask(prompt)
return rsp写代码角色定义:
代码测试角色定义:
class SimpleTester(Role):
name: str = "Bob"
profile: str = "SimpleTester"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([SimpleWriteTest])
self._watch([SimpleWriteCode])
# 既观察SimpleWriteCode,也观察SimpleWriteReview,这样可以做到一个循环的自我修正。
# self._watch([SimpleWriteCode, SimpleWriteReview]) # feel free to try this too
async def _act(self) -> Message:
logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
todo = self.rc.todo
# context = self.get_memories(k=1)[0].content # use the most recent memory as context
context = self.get_memories() # use all memories as context
code_text = await todo.run(context, k=5) # specify arguments
msg = Message(content=code_text, role=self.profile, cause_by=type(todo))
return msg测试用例评审角色定义: 同上。
class SimpleReviewer(Role):
name: str = "Charlie"
profile: str = "SimpleReviewer"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([SimpleWriteReview])
self._watch([SimpleWriteTest])概述: 使用Team来雇佣三位角色
import asyncio
import typer
from metagpt.logs import logger
from metagpt.team import Team
app = typer.Typer()
@app.command()
def main(
idea: str = typer.Argument(..., help="write a function that calculates the product of a list"),
investment: float = typer.Option(default=3.0, help="Dollar amount to invest in the AI company."),
n_round: int = typer.Option(default=5, help="Number of rounds for the simulation."),
):
logger.info(idea)
team = Team()
team.hire(
[
SimpleCoder(),
SimpleTester(),
SimpleReviewer(),
]
)
team.invest(investment=investment)
team.run_project(idea)
asyncio.run(team.run(n_round=n_round))
if __name__ == '__main__':
app()输出:

概述: 详细介绍整个多智能体系统的运行机制。

概述: 在真实场景下,我们往往需要人类介入来修正多智能体团队协作中的一些错误。
在2-4-4中,我们设置SimpleReviewer的is_human参数为True即可。这样我们可以控制协作流程,代替测试用例评审角色,作为测试用例评审角色来参与到整个流程中。每次轮到我们响应时(测试用例评审角色),正在运行的进程都会暂停等待我们的输入。我们可以根据其他Agent的输出,提出合理要求以参与到整个交互中。
team.hire(
[
SimpleCoder(),
SimpleTester(),
# SimpleReviewer(), # the original line
SimpleReviewer(is_human=True), # change to this line
]
)概述: 记忆是Agent的核心,Agent需要依靠记忆来做决策。类Memory是Agent记忆的抽象表示,当角色初始化时,以self.rc.memory初始化记忆,它将把它随后观察到的每条消息存储在一个列表中,以便将来检索。当记录的记忆被需要时,你可以使用self.get_memories来获取记忆。
def get_memories(self, k=0) -> list[Message]:
"""A wrapper to return the most recent k memories of this role, return all when k=0"""
return self.rc.memory.get(k=k)例如在2-4-3中: 我们调用整个函数是为了向测试智能体提供完整的历史记录。
async def _act(self) -> Message:
logger.info(f"{self._setting}: ready to {self.rc.todo}")
todo = self.rc.todo
# context = self.get_memories(k=1)[0].content # use the most recent memory as context
context = self.get_memories() # use all memories as context
code_text = await todo.run(context, k=5) # specify arguments
msg = Message(content=code_text, role=self.profile, cause_by=todo)
return msg添加记忆: 使用self.rc.memory.add(msg)添加记忆,并且msg必须是Message对象。
Notice: 角色通常需要记住它之前说过或做过什么,以便采取下一步行动。所以建议在复写act函数的逻辑时,建议将动作输出的消息添加到角色的内存中。
概述: 接收到对环境的观察后,智能体会进行思考以及做出一些行为来应对,MetaGPT目前提供两种方式,即ReAct和By Order。
ReAct: 先思考,后行动,直到Agent决定停止循环。每次思考(_think)时,角色会选择一种行为来回应观察,并且执行选择的行为在_act函数,而行为的输出结果将会是下一次思考的观察对象,LLM作为大脑,动态的选择行为去执行。

Notice: 如果你想要角色执行更多次思考-行动循环,那么你可以设置参数max_react_loop。实验证明,设置该参数非常有必要,在react的过程中,如果思考-行动循环少,往往会做出错误的决策,即少执行或者错误执行行为
self._set_react_mode(react_mode="react", max_react_loop=6)By order: 按照set_actions中设定的行为去依次执行。该情况适用于我们清楚Agent该依次执行哪些行为。

例如在目录2-4-2的案例中,我们就是顺序执行行为,先写代码,后执行代码。
class RunnableCoder(Role):
name: str = "Alice"
profile: str = "RunnableCoder"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([SimpleWriteCode, SimpleRunCode])
self._set_react_mode(react_mode="by_order")
async def _act(self) -> Message:
...先拟定计划,之后使用计划去执行一系列动作:

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。