在探索前沿技术的旅程中,MetaGPT 不仅仅是一个多 Agent 框架,它更是一个强大的后台框架,能够将多个智能 Agent 整合在一起,形成一个高效且可用的超级 Agent。通过结合 Chainlit 和 MetaGPT,我们可以创建一个功能丰富、交互性强的界面化 AI Agent,为用户提供前所未有的智能化体验。
本文将先给出1个MetaGPT智能体使用Chanlit快速集成的例子,然后深入介绍Chanlit的关键生命周期,最后对两者集成的优势进行总结。
1. 快速集成的例子
使用MetaGPT+Chanlit完成一个界面交互化的Agent APP,主要是两个步骤,首先构建一个MetaGPT智能体,然后用Chanlit集成MetaGPT智能体,在1.3章节将会看到这种集成的效果远大于单独的MetaGPT智能体。
1.1 构建一个MetaGPT智能体
例如MetaGPT官网给出的一个生成代码的例子
import re
from metagpt.actions import Action
from metagpt.config2 import config
from metagpt.const import METAGPT_ROOT
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import Message
EXAMPLE_CODE_FILE = METAGPT_ROOT / "examples/build_customized_agent.py"
MULTI_ACTION_AGENT_CODE_EXAMPLE = EXAMPLE_CODE_FILE.read_text()
class CreateAgent(Action):
PROMPT_TEMPLATE: str = """
### BACKGROUND
You are using an agent framework called metagpt to write agents capable of different actions,
the usage of metagpt can be illustrated by the following example:
### EXAMPLE STARTS AT THIS LINE
{example}
### EXAMPLE ENDS AT THIS LINE
### TASK
Now you should create an agent with appropriate actions based on the instruction, consider carefully about
the PROMPT_TEMPLATE of all actions and when to call self._aask()
### INSTRUCTION
{instruction}
### YOUR CODE
Return ```python your_code_here ``` with NO other texts, your code:
"""
async def run(self, example: str, instruction: str):
prompt = self.PROMPT_TEMPLATE.format(example=example, instruction=instruction)
# logger.info(prompt)
rsp = await self._aask(prompt)
code_text = CreateAgent.parse_code(rsp)
return code_text
@staticmethod
def parse_code(rsp):
pattern = r"```python(.*)```"
match = re.search(pattern, rsp, re.DOTALL)
code_text = match.group(1) if match else ""
config.workspace.path.mkdir(parents=True, exist_ok=True)
new_file = config.workspace.path / "agent_created_agent.py"
new_file.write_text(code_text)
return code_text
class AgentCreator(Role):
name: str = "Matrix"
profile: str = "AgentCreator"
agent_template: str = MULTI_ACTION_AGENT_CODE_EXAMPLE
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([CreateAgent])
async def _act(self) -> Message:
logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
todo = self.rc.todo
msg = self.rc.memory.get()[-1]
instruction = msg.content
code_text = await CreateAgent().run(example=self.agent_template, instruction=instruction)
msg = Message(content=code_text, role=self.profile, cause_by=todo)
return msg
if __name__ == "__main__":
import asyncio
async def main():
agent_template = MULTI_ACTION_AGENT_CODE_EXAMPLE
creator = AgentCreator(agent_template=agent_template)
msg = """
Write an agent called SimpleTester that will take any code snippet (str) and do the following:
1. write a testing code (str) for testing the given code snippet, save the testing code as a .py file in the current working directory;
2. run the testing code.
You can use pytest as the testing framework.
"""
await creator.run(msg)
asyncio.run(main())
该Agent通过代码Creator的Role和相关的Action生成底代码以完成任务。
1.2 使用Chanlit集成MetaGPT
import chainlit as cl
from example.agent_creator import AgentCreator
from metagpt.team import Team
# https://docs.chainlit.io/concepts/message
@cl.on_message
async def startup(message: cl.Message) -> None:
"""On Message in UI, Create a MetaGPT software company
Args:
message (chainlit.Message): message by chainlist
"""
idea = message.content
company = Team(env=ChainlitEnv())
# Similar to software_company.py
company.hire(
[
AgentCreator(),
]
)
company.invest(investment=3.0)
company.run_project(idea=idea)
await company.run(n_round=2)
file = company.env.config.workspace.path / "agent_created_agent.py"
await cl.Message(
content=f"""
Codes can be found here:{file}
).send()
代码编写非常简单,引入MetaGPT中编写的CodeCreator,在on_message函数中解析输入信息,然后用CodeCreator完成消息处理,将消息送回对话框,完全无缝集成。
1.3 效果
可以运行Chainlit run app.py, 会自动弹出对话框页面,我们能看到如下页面:
紧接着我们在页面中操作交互:
- 在消息框中输入各种代码生成任务,例如说example中的生成字符串测试代码生成
- Agent生成完毕,弹出消息生成文件在xx位置
是不是非常简单简洁!
2. 深入Chainlit
Chanlit可以点击下面链接看官网:
Chainlit is an open-source Python package to build production ready Conversational AI.
重点是理解Chanlit的生命周期,其它知识可以在官网上查看
2.1 Chanlit的Life Cycle
当运行命令Chanlit run app.py的时候,就会运行一个Chanlit应用,这个Chanlit应用给了一堆钩子,运用在Agent app的各个交互周期中。
2.1.1 On Chat Start
当页面打开的时候,一个会话会被创建,会回调该函数。
@cl.on_chat_start
def on_chat_start():
print("A new chat session has started!")
2.1.2 On Message
当用户从页面输入框输入信息并点击红色向上箭头的时候,会回调该函数。
@cl.on_message
def on_message(msg: cl.Message):
print("The user sent: ", msg.content)
2.1.3 On Stop
当程序正在运行,输入框的红色小箭头会变成红色四方块,点击该四方块,会回调该函数。
@cl.on_stop
def on_stop():
print("The user wants to stop the task!")
2.1.4 On Chat End
当页面被关闭,会话结束,会回调该函数。
@cl.on_chat_end
def on_chat_end():
print("The user disconnected!")
3. 总结
其主要优势在于智能体和界面交互的功能无缝集成,开发成本低廉,如果开发不太复杂的APP,利用Chanlit+MetaGPT是比较快捷的方式。