赞
踩
action是动作的逻辑抽象,通过将预设的prompt传入llm,来获取输出,并对输出进行格式化
具体的实现如下
定义prompt模版
PROMPT_TEMPLATE = """
Write a python function that can {instruction} and provide two runnnable test cases.
Return ```python your_code_here ```with NO other texts,
your code:
"""
调用llm生成代码
async def run(self, instruction: str):
prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)
rsp = await self._aask(prompt)
code_text = SimpleWriteCode.parse_code(rsp)
return code_text
对llm output进行格式化
@staticmethod
def parse_code(rsp):
pattern = r'```python(.*)```'
match = re.search(pattern, rsp, re.DOTALL)
code_text = match.group(1) if match else rsp
return code_text
完整代码
import asyncio import re import subprocess import fire from metagpt.actions import Action from metagpt.logs import logger from metagpt.roles.role import Role, RoleReactMode from metagpt.schema import Message class SimpleWriteCode(Action): PROMPT_TEMPLATE: str = """ Write a python function that can {instruction} and provide two runnnable test cases. 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 = SimpleWriteCode.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 rsp return code_text
初始化上下文
class SimpleCoder(Role):
name: str = "Alice"
profile: str = "SimpleCoder"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([SimpleWriteCode])
SimpleWriteCode
会被加入到代办self._rc.todo
中,定义执行规则
async def _act(self) -> Message:
logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
todo = self.rc.todo # todo will be SimpleWriteCode()
msg = self.get_memories(k=1)[0] # find the most recent messages
code_text = await todo.run(msg.content)
msg = Message(content=code_text, role=self.profile, cause_by=type(todo))
return msg
self._rc.memory
属性,在之后的_observe
中存储每一个message,以便后续的检索,所以也可以理解role的memory就是一个含有message的list完整代码
class SimpleCoder(Role): name: str = "Alice" profile: str = "SimpleCoder" def __init__(self, **kwargs): super().__init__(**kwargs) self.set_actions([SimpleWriteCode]) async def _act(self) -> Message: logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})") todo = self.rc.todo # todo will be SimpleWriteCode() msg = self.get_memories(k=1)[0] # find the most recent messages code_text = await todo.run(msg.content) msg = Message(content=code_text, role=self.profile, cause_by=type(todo)) return msg ```
测试demo
代码
async def main():
msg = "write a function that calculates the sum of a list"
role = SimpleCoder()
logger.info(msg)
result = await role.run(msg)
logger.info(result)
asyncio.run(main())
运行
demo如果想正常运行的话,需要调用llm的key,环境配置可以参照 metagpt环境配置参考
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。