🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
feat: merge geekan:dev
莘权 马739452edbb0c
diff --cc config/config2.yaml.exampleindex ff9429917,8f4a33fc1..16cdcd8a6--- a/config/config2.yaml.example+++ b/config/config2.yaml.example@@@ -3,13 -3,6 +3,13 @@@ llmbase_url: "YOUR_BASE_URL"api_key: "YOUR_API_KEY"model: "gpt-4-turbo-preview" # or gpt-3.5-turbo-1106 / gpt-4-1106-preview+ # Azure-exclusive pricing plan mappings:- # - gpt-3.5-turbo 4k: "gpt-3.5-turbo"- # - gpt-4-turbo: "gpt-4-1106-preview"- # - gpt-4-turbo-vision: "gpt-4-1106-preview"++ # - gpt-3.5-turbo 4k: "gpt-3.5-turbo-1106"++ # - gpt-4-turbo: "gpt-4-turbo-preview"++ # - gpt-4-turbo-vision: "gpt-4-vision-preview"+ # - gpt-4 8k: "gpt-4"+ # See for more: https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/+ # pricing_plan: "gpt-4-turbo-preview"proxy: "YOUR_PROXY"diff --cc metagpt/actions/rebuild_class_view.pyindex 59dfac8a0,2140ad874..aeff6b42c--- a/metagpt/actions/rebuild_class_view.py+++ b/metagpt/actions/rebuild_class_view.py@@@ -30,28 -29,9 +30,25 @@@ from metagpt.utils.graph_repository impclass RebuildClassView(Action):+ """+ Reconstructs a graph repository about class diagram from a source code project.++ Attributes:+ graph_db (Optional[GraphRepository]): The optional graph repository.+ """++ graph_db: Optional[GraphRepository] = None+async def run(self, with_messages=None, format=config.prompt_schema):+ """+ Implementation of `Action`'s `run` method.++ Args:+ with_messages (Optional[Type]): An optional argument specifying messages to react to.+ format (str): The format for the prompt schema.-- Returns:- None+ """graph_repo_pathname = self.context.git_repo.workdir / GRAPH_REPO_FILE_REPO / self.context.git_repo.workdir.name- graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json")))+ self.graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json")))repo_parser = RepoParser(base_directory=Path(self.i_context))# use pylintclass_views, relationship_views, package_root = await repo_parser.rebuild_class_views(path=Path(self.i_context))@@@ -64,19 -43,12 +61,16 @@@for file_info in symbols:# Align to the same root directory in accordance with `class_views`.file_info.file = self._align_root(file_info.file, direction, diff_path)- await GraphRepository.update_graph_db_with_file_info(graph_db, file_info)- await self._create_mermaid_class_views(graph_db=graph_db)- await graph_db.save()+ await GraphRepository.update_graph_db_with_file_info(self.graph_db, file_info)+ await self._create_mermaid_class_views()+ await self.graph_db.save()++ async def _create_mermaid_class_views(self):+ """Creates a Mermaid class diagram using data from the `graph_db` graph repository.- async def _create_mermaid_class_views(self, graph_db):- path = Path(self.context.git_repo.workdir) / DATA_API_DESIGN_FILE_REPO+ This method utilizes information stored in the graph repository to generate a Mermaid class diagram.-- Returns:- None+ """- path = Path(self.context.git_repo.workdir) / DATA_API_DESIGN_FILE_REPO++ path = self.context.git_repo.workdir / DATA_API_DESIGN_FILE_REPOpath.mkdir(parents=True, exist_ok=True)pathname = path / self.context.git_repo.workdir.nameasync with aiofiles.open(str(pathname.with_suffix(".mmd")), mode="w", encoding="utf-8") as writer:diff --cc metagpt/actions/rebuild_sequence_view.pyindex 947d282d4,777dde8ce..ef0b88889--- a/metagpt/actions/rebuild_sequence_view.py+++ b/metagpt/actions/rebuild_sequence_view.py@@@ -74,144 -21,17 +74,138 @@@ class ReverseUseCaseDetails(BaseModel)class RebuildSequenceView(Action):+ """+ Represents an action to reconstruct sequence view through reverse engineering.++ Attributes:+ graph_db (Optional[GraphRepository]): An optional instance of GraphRepository for graph database operations.+ """++ graph_db: Optional[GraphRepository] = None+async def run(self, with_messages=None, format=config.prompt_schema):+ """+ Implementation of `Action`'s `run` method.++ Args:+ with_messages (Optional[Type]): An optional argument specifying messages to react to.+ format (str): The format for the prompt schema.-- Returns:- None+ """graph_repo_pathname = self.context.git_repo.workdir / GRAPH_REPO_FILE_REPO / self.context.git_repo.workdir.name- graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json")))- entries = await RebuildSequenceView._search_main_entry(graph_db)+ self.graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json")))+ entries = await self._search_main_entry()for entry in entries:- await self._rebuild_sequence_view(entry, graph_db)- await graph_db.save()+ await self._rebuild_main_sequence_view(entry)+ while await self._merge_sequence_view(entry):+ pass+ await self.graph_db.save()- @staticmethod- async def _search_main_entry(graph_db) -> List:- rows = await graph_db.select(predicate=GraphKeyword.HAS_PAGE_INFO)+ @retry(+ wait=wait_random_exponential(min=1, max=20),+ stop=stop_after_attempt(6),+ after=general_after_log(logger),+ )+ async def _rebuild_main_sequence_view(self, entry: SPO):+ """+ Reconstruct the sequence diagram for the __main__ entry of the source code through reverse engineering.++ Args:+ entry (SPO): The SPO (Subject, Predicate, Object) object in the graph database that is related to the+ subject `__name__:__main__`.-- Returns:- None+ """+ filename = entry.subject.split(":", 1)[0]+ rows = await self.graph_db.select(predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS)+ classes = []+ prefix = filename + ":"+ for r in rows:+ if prefix in r.subject:+ classes.append(r)+ await self._rebuild_use_case(r.subject)+ participants = set()+ class_details = []+ class_views = []+ for c in classes:+ detail = await self._get_class_detail(c.subject)+ if not detail:+ continue+ class_details.append(detail)+ view = await self._get_uml_class_view(c.subject)+ if view:+ class_views.append(view)++ actors = await self._get_participants(c.subject)+ participants.update(set(actors))++ use_case_blocks = []+ for c in classes:+ use_cases = await self._get_class_use_cases(c.subject)+ use_case_blocks.extend(use_cases)+ prompt_blocks = ["## Use Cases\n" + "\n".join(use_case_blocks)]+ block = "## Participants\n"+ for p in participants:+ block += f"- {p}\n"+ prompt_blocks.append(block)+ block = "## Mermaid Class Views\n```mermaid\n"+ block += "\n\n".join([c.get_mermaid() for c in class_views])+ block += "\n```\n"+ prompt_blocks.append(block)+ block = "## Source Code\n```python\n"+ block += await self._get_source_code(filename)+ block += "\n```\n"+ prompt_blocks.append(block)+ prompt = "\n---\n".join(prompt_blocks)++ rsp = await self.llm.aask(+ msg=prompt,+ system_msgs=[+ "You are a python code to Mermaid Sequence Diagram translator in function detail.",+ "Translate the given markdown text to a Mermaid Sequence Diagram.",+ "Return the merged Mermaid sequence diagram in a markdown code block format.",+ ],+ )+ sequence_view = rsp.removeprefix("```mermaid").removesuffix("```")+ rows = await self.graph_db.select(subject=entry.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW)+ for r in rows:+ await self.graph_db.delete(subject=r.subject, predicate=r.predicate, object_=r.object_)+ await self.graph_db.insert(+ subject=entry.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW, object_=sequence_view+ )+ await self.graph_db.insert(+ subject=entry.subject,+ predicate=GraphKeyword.HAS_SEQUENCE_VIEW_VER,+ object_=concat_namespace(datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3], add_affix(sequence_view)),+ )+ for c in classes:+ await self.graph_db.insert(+ subject=entry.subject, predicate=GraphKeyword.HAS_PARTICIPANT, object_=auto_namespace(c.subject)+ )+ await self.graph_db.save()++ async def _merge_sequence_view(self, entry: SPO) -> bool:+ """+ Augments additional information to the provided SPO (Subject, Predicate, Object) entry in the sequence diagram.++ Args:+ entry (SPO): The SPO object representing the relationship in the graph database.++ Returns:+ bool: True if additional information has been augmented, otherwise False.+ """+ new_participant = await self._search_new_participant(entry)+ if not new_participant:+ return False++ await self._merge_participant(entry, new_participant)+ return True++ async def _search_main_entry(self) -> List:+ """+ Asynchronously searches for the SPO object that is related to `__name__:__main__`.++ Returns:+ List: A list containing information about the main entry in the sequence diagram.+ """+ rows = await self.graph_db.select(predicate=GraphKeyword.HAS_PAGE_INFO)tag = "__name__:__main__"entries = []for r in rows:@@@ -219,363 -39,24 +213,359 @@@entries.append(r)return entries- async def _rebuild_sequence_view(self, entry, graph_db):- filename = entry.subject.split(":", 1)[0]- src_filename = RebuildSequenceView._get_full_filename(root=self.i_context, pathname=filename)- if not src_filename:+ @retry(+ wait=wait_random_exponential(min=1, max=20),+ stop=stop_after_attempt(6),+ after=general_after_log(logger),+ )+ async def _rebuild_use_case(self, ns_class_name: str):+ """+ Asynchronously reconstructs the use case for the provided namespace-prefixed class name.++ Args:+ ns_class_name (str): The namespace-prefixed class name for which the use case is to be reconstructed.-- Returns:- None+ """+ rows = await self.graph_db.select(subject=ns_class_name, predicate=GraphKeyword.HAS_CLASS_USE_CASE)+ if rows:return- content = await aread(filename=src_filename, encoding="utf-8")- content = f"```python\n{content}\n```\n\n---\nTranslate the code above into Mermaid Sequence Diagram."- data = await self.llm.aask(- msg=content, system_msgs=["You are a python code to Mermaid Sequence Diagram translator in function detail"]++ detail = await self._get_class_detail(ns_class_name)+ if not detail:+ return+ participants = set()+ participants.update(set(detail.compositions))+ participants.update(set(detail.aggregations))+ class_view = await self._get_uml_class_view(ns_class_name)+ source_code = await self._get_source_code(ns_class_name)++ prompt_blocks = []+ block = "## Participants\n"+ for p in participants:+ block += f"- {p}\n"+ prompt_blocks.append(block)+ block = "## Mermaid Class Views\n```mermaid\n"+ block += class_view.get_mermaid()+ block += "\n```\n"+ prompt_blocks.append(block)+ block = "## Source Code\n```python\n"+ block += source_code+ block += "\n```\n"+ prompt_blocks.append(block)+ prompt = "\n---\n".join(prompt_blocks)++ rsp = await self.llm.aask(+ msg=prompt,+ system_msgs=[+ "You are a python code to UML 2.0 Use Case translator.",+ 'The generated UML 2.0 Use Case must include the roles or entities listed in "Participants".',+ "The functional descriptions of Actors and Use Cases in the generated UML 2.0 Use Case must not "+ 'conflict with the information in "Mermaid Class Views".',+ 'The section under `if __name__ == "__main__":` of "Source Code" contains information about external '+ "system interactions with the internal system.",+ "Return a markdown JSON object with:\n"+ '- a "description" key to explain what the whole source code want to do;\n'+ '- a "use_cases" key list all use cases, each use case in the list should including a `description` '+ "key describes about what the use case to do, a `inputs` key lists the input names of the use case "+ "from external sources, a `outputs` key lists the output names of the use case to external sources, "+ "a `actors` key lists the participant actors of the use case, a `steps` key lists the steps about how "+ "the use case works step by step, a `reason` key explaining under what circumstances would the "+ "external system execute this use case.\n"+ '- a "relationship" key lists all the descriptions of relationship among these use cases.\n',+ ],+ )++ code_blocks = parse_json_code_block(rsp)+ for block in code_blocks:+ detail = ReverseUseCaseDetails.model_validate_json(block)+ await self.graph_db.insert(+ subject=ns_class_name, predicate=GraphKeyword.HAS_CLASS_USE_CASE, object_=detail.model_dump_json()+ )+ await self.graph_db.save()++ @retry(+ wait=wait_random_exponential(min=1, max=20),+ stop=stop_after_attempt(6),+ after=general_after_log(logger),+ )+ async def _rebuild_sequence_view(self, ns_class_name: str):+ """+ Asynchronously reconstructs the sequence diagram for the provided namespace-prefixed class name.++ Args:+ ns_class_name (str): The namespace-prefixed class name for which the sequence diagram is to be reconstructed.-- Returns:- None+ """+ await self._rebuild_use_case(ns_class_name)++ prompts_blocks = []+ use_case_markdown = await self._get_class_use_cases(ns_class_name)+ if not use_case_markdown: # external class+ await self.graph_db.insert(subject=ns_class_name, predicate=GraphKeyword.HAS_SEQUENCE_VIEW, object_="")+ await self.graph_db.save()+ return+ block = f"## Use Cases\n{use_case_markdown}"+ prompts_blocks.append(block)++ participants = await self._get_participants(ns_class_name)+ block = "## Participants\n" + "\n".join([f"- {s}" for s in participants])+ prompts_blocks.append(block)++ view = await self._get_uml_class_view(ns_class_name)+ block = "## Mermaid Class Views\n```mermaid\n"+ block += view.get_mermaid()+ block += "\n```\n"+ prompts_blocks.append(block)++ block = "## Source Code\n```python\n"+ block += await self._get_source_code(ns_class_name)+ block += "\n```\n"+ prompts_blocks.append(block)+ prompt = "\n---\n".join(prompts_blocks)++ rsp = await self.llm.aask(+ prompt,+ system_msgs=[+ "You are a Mermaid Sequence Diagram translator in function detail.",+ "Translate the markdown text to a Mermaid Sequence Diagram.",+ "Return a markdown mermaid code block.",+ ],+ )++ sequence_view = rsp.removeprefix("```mermaid").removesuffix("```")+ await self.graph_db.insert(+ subject=ns_class_name, predicate=GraphKeyword.HAS_SEQUENCE_VIEW, object_=sequence_view+ )+ await self.graph_db.save()++ async def _get_participants(self, ns_class_name: str) -> List[str]:+ """+ Asynchronously returns the participants list of the sequence diagram for the provided namespace-prefixed SPO+ object.++ Args:+ ns_class_name (str): The namespace-prefixed class name for which to retrieve the participants list.++ Returns:+ List[str]: A list of participants in the sequence diagram.+ """+ participants = set()+ detail = await self._get_class_detail(ns_class_name)+ if not detail:+ return []+ participants.update(set(detail.compositions))+ participants.update(set(detail.aggregations))+ return list(participants)++ async def _get_class_use_cases(self, ns_class_name: str) -> str:+ """+ Asynchronously assembles the context about the use case information of the namespace-prefixed SPO object.++ Args:+ ns_class_name (str): The namespace-prefixed class name for which to retrieve use case information.++ Returns:+ str: A string containing the assembled context about the use case information.+ """+ block = ""+ rows = await self.graph_db.select(subject=ns_class_name, predicate=GraphKeyword.HAS_CLASS_USE_CASE)+ for i, r in enumerate(rows):+ detail = ReverseUseCaseDetails.model_validate_json(r.object_)+ block += f"\n### {i + 1}. {detail.description}"+ for j, use_case in enumerate(detail.use_cases):+ block += f"\n#### {i + 1}.{j + 1}. {use_case.description}\n"+ block += "\n##### Inputs\n" + "\n".join([f"- {s}" for s in use_case.inputs])+ block += "\n##### Outputs\n" + "\n".join([f"- {s}" for s in use_case.outputs])+ block += "\n##### Actors\n" + "\n".join([f"- {s}" for s in use_case.actors])+ block += "\n##### Steps\n" + "\n".join([f"- {s}" for s in use_case.steps])+ block += "\n#### Use Case Relationship\n" + "\n".join([f"- {s}" for s in detail.relationship])+ return block + "\n"++ async def _get_class_detail(self, ns_class_name: str) -> DotClassInfo | None:+ """+ Asynchronously retrieves the dot format class details of the namespace-prefixed SPO object.++ Args:+ ns_class_name (str): The namespace-prefixed class name for which to retrieve class details.++ Returns:+ Union[DotClassInfo, None]: A DotClassInfo object representing the dot format class details,+ or None if the details are not available.+ """+ rows = await self.graph_db.select(subject=ns_class_name, predicate=GraphKeyword.HAS_DETAIL)+ if not rows:+ return None+ dot_class_info = DotClassInfo.model_validate_json(rows[0].object_)+ return dot_class_info++ async def _get_uml_class_view(self, ns_class_name: str) -> UMLClassView | None:+ """+ Asynchronously retrieves the UML 2.0 format class details of the namespace-prefixed SPO object.++ Args:+ ns_class_name (str): The namespace-prefixed class name for which to retrieve UML class details.++ Returns:+ Union[UMLClassView, None]: A UMLClassView object representing the UML 2.0 format class details,+ or None if the details are not available.+ """+ rows = await self.graph_db.select(subject=ns_class_name, predicate=GraphKeyword.HAS_CLASS_VIEW)+ if not rows:+ return None+ class_view = UMLClassView.model_validate_json(rows[0].object_)+ return class_view++ async def _get_source_code(self, ns_class_name: str) -> str:+ """+ Asynchronously retrieves the source code of the namespace-prefixed SPO object.++ Args:+ ns_class_name (str): The namespace-prefixed class name for which to retrieve the source code.++ Returns:+ str: A string containing the source code of the specified namespace-prefixed class.+ """+ rows = await self.graph_db.select(subject=ns_class_name, predicate=GraphKeyword.HAS_PAGE_INFO)+ filename = split_namespace(ns_class_name=ns_class_name)[0]+ if not rows:+ src_filename = RebuildSequenceView._get_full_filename(root=self.i_context, pathname=filename)+ if not src_filename:+ return ""+ return await aread(filename=src_filename, encoding="utf-8")+ code_block_info = CodeBlockInfo.model_validate_json(rows[0].object_)+ return await read_file_block(+ filename=filename, lineno=code_block_info.lineno, end_lineno=code_block_info.end_lineno)- await graph_db.insert(subject=filename, predicate=GraphKeyword.HAS_SEQUENCE_VIEW, object_=data)- logger.info(data)@staticmethoddef _get_full_filename(root: str | Path, pathname: str | Path) -> Path | None:+ """+ Convert package name to the full path of the module.++ Args:+ root (Union[str, Path]): The root path or string representing the package.+ pathname (Union[str, Path]): The pathname or string representing the module.++ Returns:+ Union[Path, None]: The full path of the module, or None if the path cannot be determined.++++ Examples:++ If `root`(workdir) is "/User/xxx/github/MetaGPT/metagpt", and the `pathname` is++ "metagpt/management/skill_manager.py", then the returned value will be++ "/User/xxx/github/MetaGPT/metagpt/management/skill_manager.py"+ """files = list_files(root=root)postfix = "/" + str(pathname)for i in files:if str(i).endswith(postfix):return ireturn None++ @staticmethod+ def parse_participant(mermaid_sequence_diagram: str) -> List[str]:+ """+ Parses the provided Mermaid sequence diagram and returns the list of participants.++ Args:+ mermaid_sequence_diagram (str): The Mermaid sequence diagram string to be parsed.++ Returns:+ List[str]: A list of participants extracted from the sequence diagram.+ """+ pattern = r"participant ([a-zA-Z\.0-9_]+)"+ matches = re.findall(pattern, mermaid_sequence_diagram)+ matches = [re.sub(r"[\\/'\"]+", "", i) for i in matches]+ return matches++ async def _search_new_participant(self, entry: SPO) -> str | None:+ """+ Asynchronously retrieves a participant whose sequence diagram has not been augmented.++ Args:+ entry (SPO): The SPO object representing the relationship in the graph database.++ Returns:+ Union[str, None]: A participant whose sequence diagram has not been augmented, or None if not found.+ """+ rows = await self.graph_db.select(subject=entry.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW)+ if not rows:+ return None+ sequence_view = rows[0].object_+ rows = await self.graph_db.select(subject=entry.subject, predicate=GraphKeyword.HAS_PARTICIPANT)+ merged_participants = []+ for r in rows:+ name = split_namespace(r.object_)[-1]+ merged_participants.append(name)+ participants = self.parse_participant(sequence_view)+ for p in participants:+ if p in merged_participants:+ continue+ return p+ return None++ @retry(+ wait=wait_random_exponential(min=1, max=20),+ stop=stop_after_attempt(6),+ after=general_after_log(logger),+ )+ async def _merge_participant(self, entry: SPO, class_name: str):+ """+ Augments the sequence diagram of `class_name` to the sequence diagram of `entry`.++ Args:+ entry (SPO): The SPO object representing the base sequence diagram.+ class_name (str): The class name whose sequence diagram is to be augmented.-- Returns:- None+ """+ rows = await self.graph_db.select(predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS)+ participants = []+ for r in rows:+ name = split_namespace(r.subject)[-1]+ if name == class_name:+ participants.append(r)+ if len(participants) == 0: # external participants+ await self.graph_db.insert(+ subject=entry.subject, predicate=GraphKeyword.HAS_PARTICIPANT, object_=concat_namespace("?", class_name)+ )+ await self.graph_db.save()+ return+ if len(participants) > 1:+ for r in participants:+ await self.graph_db.insert(+ subject=entry.subject, predicate=GraphKeyword.HAS_PARTICIPANT, object_=auto_namespace(r.subject)+ )+ await self.graph_db.save()+ return++ participant = participants[0]+ await self._rebuild_sequence_view(participant.subject)+ sequence_views = await self.graph_db.select(+ subject=participant.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW+ )+ if not sequence_views: # external class+ return+ rows = await self.graph_db.select(subject=entry.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW)+ prompt = f"```mermaid\n{sequence_views[0].object_}\n```\n---\n```mermaid\n{rows[0].object_}\n```"++ rsp = await self.llm.aask(+ prompt,+ system_msgs=[+ "You are a tool to merge sequence diagrams into one.",+ "Participants with the same name are considered identical.",+ "Return the merged Mermaid sequence diagram in a markdown code block format.",+ ],+ )++ sequence_view = rsp.removeprefix("```mermaid").removesuffix("```")+ rows = await self.graph_db.select(subject=entry.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW)+ for r in rows:+ await self.graph_db.delete(subject=r.subject, predicate=r.predicate, object_=r.object_)+ await self.graph_db.insert(+ subject=entry.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW, object_=sequence_view+ )+ await self.graph_db.insert(+ subject=entry.subject,+ predicate=GraphKeyword.HAS_SEQUENCE_VIEW_VER,+ object_=concat_namespace(datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3], add_affix(sequence_view)),+ )+ await self.graph_db.insert(+ subject=entry.subject, predicate=GraphKeyword.HAS_PARTICIPANT, object_=auto_namespace(participant.subject)+ )+ await self.graph_db.save()diff --cc metagpt/provider/base_llm.pyindex 8109517d1,b144471b5..616feeef6--- a/metagpt/provider/base_llm.py+++ b/metagpt/provider/base_llm.py@@@ -172,31 -167,12 +172,26 @@@ class BaseLLM(ABC):return dict: return the first function arguments of choice, for example,{'language': 'python', 'code': "print('Hello, World!')"}"""- return json.loads(self.get_choice_function(rsp)["arguments"], strict=False)+ return json.loads(self.get_choice_function(rsp)["arguments"])++ @handle_exception+ def _update_costs(self, usage: CompletionUsage | Dict):+ """+ Updates the costs based on the provided usage information.-- Args:- usage (Union[CompletionUsage, Dict]): The usage information used to calculate and update costs.- It can be either an instance of CompletionUsage or a dictionary.-- Returns:- None: This method does not return any value.-- Raises:- ValueError: If the provided usage is not a valid format.-- Example:- Usage example goes here, demonstrating how to call and utilize this method.+ """+ if self.config.calc_usage and usage and self.cost_manager:+ if isinstance(usage, Dict):+ prompt_tokens = int(usage.get("prompt_tokens", 0))+ completion_tokens = int(usage.get("completion_tokens", 0))+ else:+ prompt_tokens = usage.prompt_tokens+ completion_tokens = usage.completion_tokens+ self.cost_manager.update_cost(prompt_tokens, completion_tokens, self.pricing_plan)++ def messages_to_prompt(self, messages: list[dict]):+ """[{"role": "user", "content": msg}] to user: <msg> etc."""+ return "\n".join([f"{i['role']}: {i['content']}" for i in messages])++ def messages_to_dict(self, messages):+ """objects to [{"role": "user", "content": msg}] etc."""+ return [i.to_dict() for i in messages]diff --cc metagpt/repo_parser.pyindex d4d455c5d,e91ebd215..4c85fc279--- a/metagpt/repo_parser.py+++ b/metagpt/repo_parser.py@@@ -706,15 -227,6 +706,12 @@@ class RepoParser(BaseModel)return [RepoParser._parse_variable(t) for t in node.targets]async def rebuild_class_views(self, path: str | Path = None):+ """+ Executes `pylint` to reconstruct the dot format class view repository file.++ Args:+ path (str | Path): The path to the target directory or file. Default is None.-- Returns:- None+ """if not path:path = self.base_directorypath = Path(path)@@@ -828,17 -305,7 +825,18 @@@return class_name, info@staticmethod- def _split_relationship_line(line: str) -> str:- def _split_relationship_line(line):++ def _split_relationship_line(line: str) -> DotClassRelationship:+ """+ Parses a dot format line about the relationship of two classes and returns 'Generalize', 'Composite',+ or 'Aggregate'.++ Args:+ line (str): The dot format line containing relationship information.++ Returns:- str: The type of relationship, either 'Generalize', 'Composite', or 'Aggregate'.++ DotClassRelationship: The object of relationship representing either 'Generalize', 'Composite',++ or 'Aggregate' relationship.+ """splitters = [" -> ", " [", "];"]idxs = []for tag in splitters:diff --cc requirements.txtindex 93091d137,6cb25d52b..68856dcba--- a/requirements.txt+++ b/requirements.txt@@@ -14,7 -14,7 +14,7 @@@ lancedb==0.4.langchain==0.0.352loguru==0.6.0meilisearch==0.21.0--numpy>=1.24.3++numpy>=1.24.3,<1.25.0openai==1.6.0openpyxlbeautifulsoup4==4.12.2@@@ -58,5 -64,6 +64,6 @@@ websockets~=12.networkx~=3.2.1google-generativeai==0.3.2# playwright==1.40.0 # playwright extras require--anytree- Pillow++anytree==2.12.1+ ipywidgets==8.1.1-Pillow++Pillow==10.1.0diff --cc tests/metagpt/test_schema.pyindex 4973e68e9,a8fa27151..22f6ae9fb--- a/tests/metagpt/test_schema.py+++ b/tests/metagpt/test_schema.py@@@ -22,10 -25,9 +22,12 @@@ from metagpt.schema importDocument,Message,MessageQueue,+ Plan,SystemMessage,+ Task,+ UMLClassAttribute,+ UMLClassMethod,+ UMLClassView,UserMessage,)from metagpt.utils.common import any_to_str