MetaGPT-Memory

在 Meta 中,每个 Role 拥有自己的记忆,存储在 self.rc.memory, 其中的 memory 是 role 实例化 Memory 类得到的,关系如下图所示

MetaGPT-Memory-20250111110751

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import nest_asyncio
nest_asyncio.apply()
import re
from metagpt.actions import Action
from metagpt.logs import logger
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

2024-12-13 13:42:14.821 | INFO | metagpt.const:get_metagpt_package_root:29 - Package root set to c:\CodeRepos\python\MyCode\Learnning_MetaGPT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from metagpt.roles import Role
from metagpt.schema import Message
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 # 从RoleContext取下一个Action
msg = self.rc.memory.get(k=1)[0] # 从RoleContext取最近的K个Message
code_text = await todo.run(msg.content)
msg = Message(content=code_text, role=self.profile, cause_by=type(todo))
self.rc.memory.add(message=msg) # 保存本次Message
return msg

import asyncio
from metagpt.context import Context
async def main():
msg = "编写一个函数,计算数组的和"
context = Context()
role = SimpleCoder(context=context)
logger.info(f'1-todo:{role.rc.todo}\nmemory:{role.rc.memory}')
result = await role.run(msg)
logger.info(f'2-todo:{role.rc.todo}\nmemory:{role.rc.memory}')
asyncio.run(main())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2024-12-13 13:42:21.304 | INFO     | __main__:main:9 - 1-todo:None
memory:storage=[] index=defaultdict(<class 'list'>, {}) ignore_id=False
2024-12-13 13:42:21.307 | INFO | __main__:_act:13 - Alice(SimpleCoder): to do SimpleWriteCode(SimpleWriteCode)
```python
def calculate_array_sum(arr):
return sum(arr)
# Test case 1: Positive integers
assert calculate_array_sum([1, 2, 3, 4]) == 10
# Test case 2: Including negative numbers and zero
assert calculate_array_sum([-5, 1,
2024-12-13 13:42:26.482 | WARNING | metagpt.utils.cost_manager:update_cost:49 - Model qwen2.5:14b not found in TOKEN_COSTS.
2024-12-13 13:42:26.483 | INFO | __main__:main:13 - 2-todo:None
memory:storage=[user: 编写一个函数,计算数组的和, SimpleCoder:
def calculate_array_sum(arr):
return sum(arr)
# Test case 1: Positive integers
assert calculate_array_sum([1, 2, 3, 4]) == 10
# Test case 2: Including negative numbers and zero
assert calculate_array_sum([-5, 1, -1, 6]) == 1
] index=defaultdict(<class 'list'>, {'metagpt.actions.add_requirement.UserRequirement': [user: 编写一个函数,计算数组的和], '__main__.SimpleWriteCode': [SimpleCoder:
def calculate_array_sum(arr):
return sum(arr)
# Test case 1: Positive integers
assert calculate_array_sum([1, 2, 3, 4]) == 10
# Test case 2: Including negative numbers and zero
assert calculate_array_sum([-5, 1, -1, 6]) == 1
]}) ignore_id=False
-1, 6]) == 1
\```