3. MetaGPT框架组件介绍

Untitled

3.1 实现一个单动作Agent SimpleCoder

# Action类中包含和大模型通信的方法, self._aask, 是通过llm.aask和大模型的通信
async def_aask(self, prompt: str, system_msgs: Optional[list[str]] = None) -> str:
    """Append default prefix"""
    return await self.llm.aask(prompt. system_msgs)

# 定义Action的子类
class SimpleWriteCode(Action):
    PROMPT_TEMPLATE: str = """
    Write a python function that can {instruction} and provide 2 runnable test cases.
    Return ```python your_code_here ``` with NO other texts,
    your code:
    """

    def __init__(self, name="SiimpleWriteCode", context=None, llm=None):
        super().__init__(name, context, llm)

    # @param instruction是由role调用action的run方法传入;
    async def run(self, instruction: str):
        prompt = self.PROMPT_TEMPLAGE.format(instruction=instruction)
        rsp = await self._aask(prompt)
        code_text = SimpleWriteCode.parse_code(rsp);
        return code_text

# regex 从llm response解析出python代码;
@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

Untitled

from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.logs import logger

class SimpleCoder(Role):
    def __init__(
        self,
        name: str = "Alice",
        profile: str = "SimpleCoder",
        **kwargs,
    ):
        super().__init__(name, profile, **kwargs)
        self._init_actions([SimpleWriteCode])

async def _act(self) -> Message:
    logger.info(f"{self._setting}: ready to {self._rc.todo}")
    todo = self._rc.todo    # todo是在Role中设定的SimpleWriteCoder
    msg = self.get_memories(k=1)[0]    # 取出最近的记忆
    code_text = await todo.run(msg.content)    # 最近记忆任务的content as instruction
    msg = Messsage(content=code_text, role=self.profile, cause_by=type(todo))
    return msg
import asyncio

async def main():
    msg = "write a function that calculates the sum of a list"
    role =SimpleCoder()
    logger.info(msg)
    result = awaitrole.run(msg)

3.2 实现一个多动作Agent

Untitled