From caffcf02810a6940104cf3dfc5699271c9236f40 Mon Sep 17 00:00:00 2001 From: shenchucheng Date: Fri, 2 Feb 2024 18:18:32 +0800 Subject: [PATCH] fix not fully defined error --- metagpt/roles/role.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/metagpt/roles/role.py b/metagpt/roles/role.py index c098f95af..9961c87a1 100644 --- a/metagpt/roles/role.py +++ b/metagpt/roles/role.py @@ -23,7 +23,7 @@ from __future__ import annotations from enum import Enum -from typing import Iterable, Optional, Set, Type, Union +from typing import TYPE_CHECKING, Iterable, Optional, Set, Type, Union from pydantic import BaseModel, ConfigDict, Field, SerializeAsAny, model_validator @@ -39,6 +39,10 @@ from metagpt.utils.common import any_to_name, any_to_str, role_raise_decorator from metagpt.utils.project_repo import ProjectRepo from metagpt.utils.repair_llm_raw_output import extract_state_value_from_output +if TYPE_CHECKING: + from metagpt.environment import Environment # noqa: F401 + + PREFIX_TEMPLATE = """You are a {profile}, named {name}, your goal is {goal}. """ CONSTRAINT_TEMPLATE = "the constraint is {constraints}. " @@ -117,6 +121,13 @@ class RoleContext(BaseModel): def history(self) -> list[Message]: return self.memory.get() + @classmethod + def model_rebuild(cls, **kwargs): + # https://stackoverflow.com/questions/63420889/fastapi-pydantic-circular-references-in-separate-files + from metagpt.environment import Environment # noqa: F401 + + super().model_rebuild(**kwargs) + class Role(SerializationMixin, ContextMixin, BaseModel): """Role/Agent""" @@ -155,7 +166,6 @@ class Role(SerializationMixin, ContextMixin, BaseModel): return self def _process_role_extra(self): - self.pydantic_rebuild_model() kwargs = self.model_extra or {} if self.is_human: @@ -168,14 +178,6 @@ class Role(SerializationMixin, ContextMixin, BaseModel): if self.latest_observed_msg: self.recovered = True - @staticmethod - def pydantic_rebuild_model(): - """Rebuild model to avoid `RecursionError: maximum recursion depth exceeded in comparison`""" - from metagpt.environment import Environment - - Environment - Role.model_rebuild() - @property def todo(self) -> Action: """Get action to do""" @@ -559,3 +561,6 @@ class Role(SerializationMixin, ContextMixin, BaseModel): if self.actions: return any_to_name(self.actions[0]) return "" + + +RoleContext.model_rebuild()