MetaGPT/metagpt/environment.py

65 lines
1.9 KiB
Python
Raw Normal View History

2023-06-30 17:10:48 +08:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2023/5/11 22:12
@Author : alexanderwu
@File : environment.py
"""
import asyncio
from typing import Iterable
from pydantic import BaseModel, Field
2023-07-12 15:46:51 +08:00
2023-07-22 11:28:22 +08:00
from metagpt.memory import Memory
2023-06-30 17:10:48 +08:00
from metagpt.roles import Role
from metagpt.schema import Message
2023-07-12 15:46:51 +08:00
class Environment(BaseModel):
2023-08-02 15:57:10 -05:00
"""Environment that carries a set of roles. Roles can publish messages to the environment, which can be observed by other roles."""
2023-07-12 15:46:51 +08:00
roles: dict[str, Role] = Field(default_factory=dict)
memory: Memory = Field(default_factory=Memory)
history: str = Field(default='')
class Config:
arbitrary_types_allowed = True
2023-06-30 17:10:48 +08:00
def add_role(self, role: Role):
2023-08-02 15:57:10 -05:00
"""Add a Role to the current environment."""
2023-06-30 17:10:48 +08:00
role.set_env(self)
self.roles[role.profile] = role
def add_roles(self, roles: Iterable[Role]):
2023-08-02 15:57:10 -05:00
"""Add a batch of Roles to the current environment."""
2023-06-30 17:10:48 +08:00
for role in roles:
self.add_role(role)
def publish_message(self, message: Message):
"""Publish a message to the current environment."""
2023-08-02 15:57:10 -05:00
# self.message_queue.put(message)
2023-06-30 17:10:48 +08:00
self.memory.add(message)
self.history += f"\n{message}"
async def run(self, k=1):
2023-08-02 15:57:10 -05:00
"""Process the run of all Roles once."""
2023-06-30 17:10:48 +08:00
# while not self.message_queue.empty():
# message = self.message_queue.get()
# rsp = await self.manager.handle(message, self)
# self.message_queue.put(rsp)
for _ in range(k):
futures = []
for role in self.roles.values():
future = role.run()
futures.append(future)
await asyncio.gather(*futures)
def get_roles(self) -> dict[str, Role]:
2023-08-02 15:57:10 -05:00
"""Get all Roles within the environment."""
2023-06-30 17:10:48 +08:00
return self.roles
def get_role(self, name: str) -> Role:
2023-08-02 15:57:10 -05:00
"""Get a specified Role within the environment."""
2023-06-30 17:10:48 +08:00
return self.roles.get(name, None)