repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/factories/retriever.py
metagpt/rag/factories/retriever.py
"""RAG Retriever Factory.""" from functools import wraps import chromadb import faiss from llama_index.core import StorageContext, VectorStoreIndex from llama_index.core.embeddings import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding from llama_index.core.schema import BaseNode from llama_index.core.vector_stores.types import BasePydanticVectorStore from llama_index.vector_stores.chroma import ChromaVectorStore from llama_index.vector_stores.elasticsearch import ElasticsearchStore from llama_index.vector_stores.faiss import FaissVectorStore from metagpt.rag.factories.base import ConfigBasedFactory from metagpt.rag.retrievers.base import RAGRetriever from metagpt.rag.retrievers.bm25_retriever import DynamicBM25Retriever from metagpt.rag.retrievers.chroma_retriever import ChromaRetriever from metagpt.rag.retrievers.es_retriever import ElasticsearchRetriever from metagpt.rag.retrievers.faiss_retriever import FAISSRetriever from metagpt.rag.retrievers.hybrid_retriever import SimpleHybridRetriever from metagpt.rag.schema import ( BaseRetrieverConfig, BM25RetrieverConfig, ChromaRetrieverConfig, ElasticsearchKeywordRetrieverConfig, ElasticsearchRetrieverConfig, FAISSRetrieverConfig, ) def get_or_build_index(build_index_func): """Decorator to get or build an index. Get index using `_extract_index` method, if not found, using build_index_func. """ @wraps(build_index_func) def wrapper(self, config, **kwargs): index = self._extract_index(config, **kwargs) if index is not None: return index return build_index_func(self, config, **kwargs) return wrapper class RetrieverFactory(ConfigBasedFactory): """Modify creators for dynamically instance implementation.""" def __init__(self): creators = { FAISSRetrieverConfig: self._create_faiss_retriever, BM25RetrieverConfig: self._create_bm25_retriever, ChromaRetrieverConfig: self._create_chroma_retriever, ElasticsearchRetrieverConfig: self._create_es_retriever, ElasticsearchKeywordRetrieverConfig: self._create_es_retriever, } super().__init__(creators) def get_retriever(self, configs: list[BaseRetrieverConfig] = None, **kwargs) -> RAGRetriever: """Creates and returns a retriever instance based on the provided configurations. If multiple retrievers, using SimpleHybridRetriever. """ if not configs: return self._create_default(**kwargs) retrievers = super().get_instances(configs, **kwargs) return SimpleHybridRetriever(*retrievers) if len(retrievers) > 1 else retrievers[0] def _create_default(self, **kwargs) -> RAGRetriever: index = self._extract_index(None, **kwargs) or self._build_default_index(**kwargs) return index.as_retriever() def _create_faiss_retriever(self, config: FAISSRetrieverConfig, **kwargs) -> FAISSRetriever: config.index = self._build_faiss_index(config, **kwargs) return FAISSRetriever(**config.model_dump()) def _create_bm25_retriever(self, config: BM25RetrieverConfig, **kwargs) -> DynamicBM25Retriever: index = self._extract_index(config, **kwargs) nodes = list(index.docstore.docs.values()) if index else self._extract_nodes(config, **kwargs) if index and not config.index: config.index = index if not config.index and config.create_index: config.index = VectorStoreIndex(nodes, embed_model=MockEmbedding(embed_dim=1)) return DynamicBM25Retriever(nodes=nodes, **config.model_dump()) def _create_chroma_retriever(self, config: ChromaRetrieverConfig, **kwargs) -> ChromaRetriever: config.index = self._build_chroma_index(config, **kwargs) return ChromaRetriever(**config.model_dump()) def _create_es_retriever(self, config: ElasticsearchRetrieverConfig, **kwargs) -> ElasticsearchRetriever: config.index = self._build_es_index(config, **kwargs) return ElasticsearchRetriever(**config.model_dump()) def _extract_index(self, config: BaseRetrieverConfig = None, **kwargs) -> VectorStoreIndex: return self._val_from_config_or_kwargs("index", config, **kwargs) def _extract_nodes(self, config: BaseRetrieverConfig = None, **kwargs) -> list[BaseNode]: return self._val_from_config_or_kwargs("nodes", config, **kwargs) def _extract_embed_model(self, config: BaseRetrieverConfig = None, **kwargs) -> BaseEmbedding: return self._val_from_config_or_kwargs("embed_model", config, **kwargs) def _build_default_index(self, **kwargs) -> VectorStoreIndex: index = VectorStoreIndex( nodes=self._extract_nodes(**kwargs), embed_model=self._extract_embed_model(**kwargs), ) return index @get_or_build_index def _build_faiss_index(self, config: FAISSRetrieverConfig, **kwargs) -> VectorStoreIndex: vector_store = FaissVectorStore(faiss_index=faiss.IndexFlatL2(config.dimensions)) return self._build_index_from_vector_store(config, vector_store, **kwargs) @get_or_build_index def _build_chroma_index(self, config: ChromaRetrieverConfig, **kwargs) -> VectorStoreIndex: db = chromadb.PersistentClient(path=str(config.persist_path)) chroma_collection = db.get_or_create_collection(config.collection_name, metadata=config.metadata) vector_store = ChromaVectorStore(chroma_collection=chroma_collection) return self._build_index_from_vector_store(config, vector_store, **kwargs) @get_or_build_index def _build_es_index(self, config: ElasticsearchRetrieverConfig, **kwargs) -> VectorStoreIndex: vector_store = ElasticsearchStore(**config.store_config.model_dump()) return self._build_index_from_vector_store(config, vector_store, **kwargs) def _build_index_from_vector_store( self, config: BaseRetrieverConfig, vector_store: BasePydanticVectorStore, **kwargs ) -> VectorStoreIndex: storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex( nodes=self._extract_nodes(config, **kwargs), storage_context=storage_context, embed_model=self._extract_embed_model(config, **kwargs), ) return index get_retriever = RetrieverFactory().get_retriever
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/factories/embedding.py
metagpt/rag/factories/embedding.py
"""RAG Embedding Factory.""" from __future__ import annotations from typing import Any, Optional from llama_index.core.embeddings import BaseEmbedding from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding from llama_index.embeddings.gemini import GeminiEmbedding from llama_index.embeddings.ollama import OllamaEmbedding from llama_index.embeddings.openai import OpenAIEmbedding from metagpt.config2 import Config from metagpt.configs.embedding_config import EmbeddingType from metagpt.configs.llm_config import LLMType from metagpt.rag.factories.base import GenericFactory class RAGEmbeddingFactory(GenericFactory): """Create LlamaIndex Embedding with MetaGPT's embedding config.""" def __init__(self, config: Optional[Config] = None): creators = { EmbeddingType.OPENAI: self._create_openai, EmbeddingType.AZURE: self._create_azure, EmbeddingType.GEMINI: self._create_gemini, EmbeddingType.OLLAMA: self._create_ollama, # For backward compatibility LLMType.OPENAI: self._create_openai, LLMType.AZURE: self._create_azure, } super().__init__(creators) self.config = config if config else Config.default() def get_rag_embedding(self, key: EmbeddingType = None) -> BaseEmbedding: """Key is EmbeddingType.""" return super().get_instance(key or self._resolve_embedding_type()) def _resolve_embedding_type(self) -> EmbeddingType | LLMType: """Resolves the embedding type. If the embedding type is not specified, for backward compatibility, it checks if the LLM API type is either OPENAI or AZURE. Raise TypeError if embedding type not found. """ if self.config.embedding.api_type: return self.config.embedding.api_type if self.config.llm.api_type in [LLMType.OPENAI, LLMType.AZURE]: return self.config.llm.api_type raise TypeError("To use RAG, please set your embedding in config2.yaml.") def _create_openai(self) -> "OpenAIEmbedding": from llama_index.embeddings.openai import OpenAIEmbedding params = dict( api_key=self.config.embedding.api_key or self.config.llm.api_key, api_base=self.config.embedding.base_url or self.config.llm.base_url, ) self._try_set_model_and_batch_size(params) return OpenAIEmbedding(**params) def _create_azure(self) -> AzureOpenAIEmbedding: params = dict( api_key=self.config.embedding.api_key or self.config.llm.api_key, azure_endpoint=self.config.embedding.base_url or self.config.llm.base_url, api_version=self.config.embedding.api_version or self.config.llm.api_version, ) self._try_set_model_and_batch_size(params) return AzureOpenAIEmbedding(**params) def _create_gemini(self) -> "GeminiEmbedding": from llama_index.embeddings.gemini import GeminiEmbedding params = dict( api_key=self.config.embedding.api_key, api_base=self.config.embedding.base_url, ) self._try_set_model_and_batch_size(params) return GeminiEmbedding(**params) def _create_ollama(self) -> "OllamaEmbedding": from llama_index.embeddings.ollama import OllamaEmbedding params = dict( base_url=self.config.embedding.base_url, ) self._try_set_model_and_batch_size(params) return OllamaEmbedding(**params) def _try_set_model_and_batch_size(self, params: dict): """Set the model_name and embed_batch_size only when they are specified.""" if self.config.embedding.model: params["model_name"] = self.config.embedding.model if self.config.embedding.embed_batch_size: params["embed_batch_size"] = self.config.embedding.embed_batch_size def _raise_for_key(self, key: Any): raise ValueError(f"The embedding type is currently not supported: `{type(key)}`, {key}") def get_rag_embedding(key: EmbeddingType = None, config: Optional[Config] = None): return RAGEmbeddingFactory(config=config).get_rag_embedding(key)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/factories/base.py
metagpt/rag/factories/base.py
"""Base Factory.""" from typing import Any, Callable class GenericFactory: """Designed to get objects based on any keys.""" def __init__(self, creators: dict[Any, Callable] = None): """Creators is a dictionary. Keys are identifiers, and the values are the associated creator function, which create objects. """ self._creators = creators or {} def get_instances(self, keys: list[Any], **kwargs) -> list[Any]: """Get instances by keys.""" return [self.get_instance(key, **kwargs) for key in keys] def get_instance(self, key: Any, **kwargs) -> Any: """Get instance by key. Raise Exception if key not found. """ creator = self._creators.get(key) if creator: return creator(**kwargs) self._raise_for_key(key) def _raise_for_key(self, key: Any): raise ValueError(f"Creator not registered for key: {key}") class ConfigBasedFactory(GenericFactory): """Designed to get objects based on object type.""" def get_instance(self, key: Any, **kwargs) -> Any: """Get instance by the type of key. Key is config, such as a pydantic model, call func by the type of key, and the key will be passed to func. Raise Exception if key not found. """ creator = self._creators.get(type(key)) if creator: return creator(key, **kwargs) self._raise_for_key(key) def _raise_for_key(self, key: Any): raise ValueError(f"Unknown config: `{type(key)}`, {key}") @staticmethod def _val_from_config_or_kwargs(key: str, config: object = None, **kwargs) -> Any: """It prioritizes the configuration object's value unless it is None, in which case it looks into kwargs. Return None if not found. """ if config is not None and hasattr(config, key): val = getattr(config, key) if val is not None: return val if key in kwargs: return kwargs[key] return None
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/factories/index.py
metagpt/rag/factories/index.py
"""RAG Index Factory.""" import chromadb from llama_index.core import StorageContext, VectorStoreIndex, load_index_from_storage from llama_index.core.embeddings import BaseEmbedding from llama_index.core.indices.base import BaseIndex from llama_index.core.vector_stores.types import BasePydanticVectorStore from llama_index.vector_stores.chroma import ChromaVectorStore from llama_index.vector_stores.elasticsearch import ElasticsearchStore from llama_index.vector_stores.faiss import FaissVectorStore from metagpt.rag.factories.base import ConfigBasedFactory from metagpt.rag.schema import ( BaseIndexConfig, BM25IndexConfig, ChromaIndexConfig, ElasticsearchIndexConfig, ElasticsearchKeywordIndexConfig, FAISSIndexConfig, ) class RAGIndexFactory(ConfigBasedFactory): def __init__(self): creators = { FAISSIndexConfig: self._create_faiss, ChromaIndexConfig: self._create_chroma, BM25IndexConfig: self._create_bm25, ElasticsearchIndexConfig: self._create_es, ElasticsearchKeywordIndexConfig: self._create_es, } super().__init__(creators) def get_index(self, config: BaseIndexConfig, **kwargs) -> BaseIndex: """Key is PersistType.""" return super().get_instance(config, **kwargs) def _create_faiss(self, config: FAISSIndexConfig, **kwargs) -> VectorStoreIndex: vector_store = FaissVectorStore.from_persist_dir(str(config.persist_path)) storage_context = StorageContext.from_defaults(vector_store=vector_store, persist_dir=config.persist_path) return self._index_from_storage(storage_context=storage_context, config=config, **kwargs) def _create_bm25(self, config: BM25IndexConfig, **kwargs) -> VectorStoreIndex: storage_context = StorageContext.from_defaults(persist_dir=config.persist_path) return self._index_from_storage(storage_context=storage_context, config=config, **kwargs) def _create_chroma(self, config: ChromaIndexConfig, **kwargs) -> VectorStoreIndex: db = chromadb.PersistentClient(str(config.persist_path)) chroma_collection = db.get_or_create_collection(config.collection_name, metadata=config.metadata) vector_store = ChromaVectorStore(chroma_collection=chroma_collection) return self._index_from_vector_store(vector_store=vector_store, config=config, **kwargs) def _create_es(self, config: ElasticsearchIndexConfig, **kwargs) -> VectorStoreIndex: vector_store = ElasticsearchStore(**config.store_config.model_dump()) return self._index_from_vector_store(vector_store=vector_store, config=config, **kwargs) def _index_from_storage( self, storage_context: StorageContext, config: BaseIndexConfig, **kwargs ) -> VectorStoreIndex: embed_model = self._extract_embed_model(config, **kwargs) return load_index_from_storage(storage_context=storage_context, embed_model=embed_model) def _index_from_vector_store( self, vector_store: BasePydanticVectorStore, config: BaseIndexConfig, **kwargs ) -> VectorStoreIndex: embed_model = self._extract_embed_model(config, **kwargs) return VectorStoreIndex.from_vector_store( vector_store=vector_store, embed_model=embed_model, ) def _extract_embed_model(self, config, **kwargs) -> BaseEmbedding: return self._val_from_config_or_kwargs("embed_model", config, **kwargs) get_index = RAGIndexFactory().get_index
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/rankers/__init__.py
metagpt/rag/rankers/__init__.py
"""Rankers init"""
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/rankers/base.py
metagpt/rag/rankers/base.py
"""Base Ranker.""" from abc import abstractmethod from typing import Optional from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.schema import NodeWithScore, QueryBundle class RAGRanker(BaseNodePostprocessor): """inherit from llama_index""" @abstractmethod def _postprocess_nodes( self, nodes: list[NodeWithScore], query_bundle: Optional[QueryBundle] = None, ) -> list[NodeWithScore]: """postprocess nodes."""
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/rankers/object_ranker.py
metagpt/rag/rankers/object_ranker.py
"""Object ranker.""" import heapq import json from typing import Literal, Optional from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.schema import NodeWithScore, QueryBundle from pydantic import Field from metagpt.rag.schema import ObjectNode class ObjectSortPostprocessor(BaseNodePostprocessor): """Sorted by object's field, desc or asc. Assumes nodes is list of ObjectNode with score. """ field_name: str = Field(..., description="field name of the object, field's value must can be compared.") order: Literal["desc", "asc"] = Field(default="desc", description="the direction of order.") top_n: int = 5 @classmethod def class_name(cls) -> str: return "ObjectSortPostprocessor" def _postprocess_nodes( self, nodes: list[NodeWithScore], query_bundle: Optional[QueryBundle] = None, ) -> list[NodeWithScore]: """Postprocess nodes.""" if query_bundle is None: raise ValueError("Missing query bundle in extra info.") if not nodes: return [] self._check_metadata(nodes[0].node) sort_key = lambda node: json.loads(node.node.metadata["obj_json"])[self.field_name] return self._get_sort_func()(self.top_n, nodes, key=sort_key) def _check_metadata(self, node: ObjectNode): try: obj_dict = json.loads(node.metadata.get("obj_json")) except Exception as e: raise ValueError(f"Invalid object json in metadata: {node.metadata}, error: {e}") if self.field_name not in obj_dict: raise ValueError(f"Field '{self.field_name}' not found in object: {obj_dict}") def _get_sort_func(self): return heapq.nlargest if self.order == "desc" else heapq.nsmallest
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/engines/flare.py
metagpt/rag/engines/flare.py
"""FLARE Engine. Use llamaindex's FLAREInstructQueryEngine as FLAREEngine, which accepts other engines as parameters. For example, Create a simple engine, and then pass it to FLAREEngine. """ from llama_index.core.query_engine import ( # noqa: F401 FLAREInstructQueryEngine as FLAREEngine, )
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/engines/simple.py
metagpt/rag/engines/simple.py
"""Simple Engine.""" import json import os from pathlib import Path from typing import Any, List, Optional, Set, Union import fsspec from llama_index.core import SimpleDirectoryReader from llama_index.core.callbacks.base import CallbackManager from llama_index.core.embeddings import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding from llama_index.core.indices.base import BaseIndex from llama_index.core.ingestion.pipeline import run_transformations from llama_index.core.llms import LLM from llama_index.core.node_parser import SentenceSplitter from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.readers.base import BaseReader from llama_index.core.response_synthesizers import ( BaseSynthesizer, get_response_synthesizer, ) from llama_index.core.retrievers import BaseRetriever from llama_index.core.schema import ( BaseNode, Document, NodeWithScore, QueryBundle, QueryType, TransformComponent, ) from metagpt.config2 import config from metagpt.rag.factories import ( get_index, get_rag_embedding, get_rag_llm, get_rankers, get_retriever, ) from metagpt.rag.interface import NoEmbedding, RAGObject from metagpt.rag.parsers import OmniParse from metagpt.rag.retrievers.base import ( DeletableRAGRetriever, ModifiableRAGRetriever, PersistableRAGRetriever, QueryableRAGRetriever, ) from metagpt.rag.retrievers.hybrid_retriever import SimpleHybridRetriever from metagpt.rag.schema import ( BaseIndexConfig, BaseRankerConfig, BaseRetrieverConfig, BM25RetrieverConfig, ObjectNode, OmniParseOptions, OmniParseType, ParseResultType, ) from metagpt.utils.common import import_class class SimpleEngine(RetrieverQueryEngine): """SimpleEngine is designed to be simple and straightforward. It is a lightweight and easy-to-use search engine that integrates document reading, embedding, indexing, retrieving, and ranking functionalities into a single, straightforward workflow. It is designed to quickly set up a search engine from a collection of documents. """ def __init__( self, retriever: BaseRetriever, response_synthesizer: Optional[BaseSynthesizer] = None, node_postprocessors: Optional[list[BaseNodePostprocessor]] = None, callback_manager: Optional[CallbackManager] = None, transformations: Optional[list[TransformComponent]] = None, ) -> None: super().__init__( retriever=retriever, response_synthesizer=response_synthesizer, node_postprocessors=node_postprocessors, callback_manager=callback_manager, ) self._transformations = transformations or self._default_transformations() self._filenames = set() @classmethod def from_docs( cls, input_dir: str = None, input_files: list[str] = None, transformations: Optional[list[TransformComponent]] = None, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, fs: Optional[fsspec.AbstractFileSystem] = None, ) -> "SimpleEngine": """From docs. Must provide either `input_dir` or `input_files`. Args: input_dir: Path to the directory. input_files: List of file paths to read (Optional; overrides input_dir, exclude). transformations: Parse documents to nodes. Default [SentenceSplitter]. embed_model: Parse nodes to embedding. Must supported by llama index. Default OpenAIEmbedding. llm: Must supported by llama index. Default OpenAI. retriever_configs: Configuration for retrievers. If more than one config, will use SimpleHybridRetriever. ranker_configs: Configuration for rankers. fs: File system to use. """ if not input_dir and not input_files: raise ValueError("Must provide either `input_dir` or `input_files`.") file_extractor = cls._get_file_extractor() documents = SimpleDirectoryReader( input_dir=input_dir, input_files=input_files, file_extractor=file_extractor, fs=fs ).load_data() cls._fix_document_metadata(documents) transformations = transformations or cls._default_transformations() nodes = run_transformations(documents, transformations=transformations) return cls._from_nodes( nodes=nodes, transformations=transformations, embed_model=embed_model, llm=llm, retriever_configs=retriever_configs, ranker_configs=ranker_configs, ) @classmethod def from_objs( cls, objs: Optional[list[RAGObject]] = None, transformations: Optional[list[TransformComponent]] = None, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": """From objs. Args: objs: List of RAGObject. transformations: Parse documents to nodes. Default [SentenceSplitter]. embed_model: Parse nodes to embedding. Must supported by llama index. Default OpenAIEmbedding. llm: Must supported by llama index. Default OpenAI. retriever_configs: Configuration for retrievers. If more than one config, will use SimpleHybridRetriever. ranker_configs: Configuration for rankers. """ objs = objs or [] retriever_configs = retriever_configs or [] if not objs and any(isinstance(config, BM25RetrieverConfig) for config in retriever_configs): raise ValueError("In BM25RetrieverConfig, Objs must not be empty.") nodes = cls.get_obj_nodes(objs) return cls._from_nodes( nodes=nodes, transformations=transformations, embed_model=embed_model, llm=llm, retriever_configs=retriever_configs, ranker_configs=ranker_configs, ) @classmethod def from_index( cls, index_config: BaseIndexConfig, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": """Load from previously maintained index by self.persist(), index_config contains persis_path.""" index = get_index(index_config, embed_model=cls._resolve_embed_model(embed_model, [index_config])) return cls._from_index(index, llm=llm, retriever_configs=retriever_configs, ranker_configs=ranker_configs) async def asearch(self, content: str, **kwargs) -> str: """Inplement tools.SearchInterface""" return await self.aquery(content) def retrieve(self, query: QueryType) -> list[NodeWithScore]: query_bundle = QueryBundle(query) if isinstance(query, str) else query nodes = super().retrieve(query_bundle) self._try_reconstruct_obj(nodes) return nodes async def aretrieve(self, query: QueryType) -> list[NodeWithScore]: """Allow query to be str.""" query_bundle = QueryBundle(query) if isinstance(query, str) else query nodes = await super().aretrieve(query_bundle) self._try_reconstruct_obj(nodes) return nodes def add_docs(self, input_files: List[Union[str, Path]]): """Add docs to retriever. retriever must has add_nodes func.""" self._ensure_retriever_modifiable() documents = SimpleDirectoryReader(input_files=[str(i) for i in input_files]).load_data() self._fix_document_metadata(documents) nodes = run_transformations(documents, transformations=self._transformations) self._save_nodes(nodes) def add_objs(self, objs: list[RAGObject]): """Adds objects to the retriever, storing each object's original form in metadata for future reference.""" self._ensure_retriever_modifiable() nodes = self.get_obj_nodes(objs) self._save_nodes(nodes) def persist(self, persist_dir: Union[str, os.PathLike], **kwargs): """Persist.""" self._ensure_retriever_persistable() self._persist(str(persist_dir), **kwargs) def count(self) -> int: """Count.""" self._ensure_retriever_queryable() return self.retriever.query_total_count() def clear(self, **kwargs): """Clear.""" self._ensure_retriever_deletable() return self.retriever.clear(**kwargs) def delete_docs(self, input_files: List[Union[str, Path]]): """Delete documents from the index and document store. Args: input_files (List[Union[str, Path]]): A list of file paths or file names to be deleted. Raises: NotImplementedError: If the method is not implemented. """ exists_filenames = set() filenames = {str(i) for i in input_files} for doc_id, info in self.retriever._index.ref_doc_info.items(): if info.metadata.get("file_path") in filenames: exists_filenames.add(doc_id) for doc_id in exists_filenames: self.retriever._index.delete_ref_doc(doc_id, delete_from_docstore=True) @staticmethod def get_obj_nodes(objs: Optional[list[RAGObject]] = None) -> list[ObjectNode]: """Converts a list of RAGObjects to a list of ObjectNodes.""" return [ObjectNode(text=obj.rag_key(), metadata=ObjectNode.get_obj_metadata(obj)) for obj in objs] @classmethod def _from_nodes( cls, nodes: list[BaseNode], transformations: Optional[list[TransformComponent]] = None, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": embed_model = cls._resolve_embed_model(embed_model, retriever_configs) llm = llm or get_rag_llm() retriever = get_retriever(configs=retriever_configs, nodes=nodes, embed_model=embed_model) rankers = get_rankers(configs=ranker_configs, llm=llm) # Default [] return cls( retriever=retriever, node_postprocessors=rankers, response_synthesizer=get_response_synthesizer(llm=llm), transformations=transformations, ) @classmethod def _from_nodes( cls, nodes: list[BaseNode], transformations: Optional[list[TransformComponent]] = None, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": embed_model = cls._resolve_embed_model(embed_model, retriever_configs) llm = llm or get_rag_llm() retriever = get_retriever(configs=retriever_configs, nodes=nodes, embed_model=embed_model) rankers = get_rankers(configs=ranker_configs, llm=llm) # Default [] return cls( retriever=retriever, node_postprocessors=rankers, response_synthesizer=get_response_synthesizer(llm=llm), transformations=transformations, ) @classmethod def _from_index( cls, index: BaseIndex, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": llm = llm or get_rag_llm() retriever = get_retriever(configs=retriever_configs, index=index) # Default index.as_retriever rankers = get_rankers(configs=ranker_configs, llm=llm) # Default [] return cls( retriever=retriever, node_postprocessors=rankers, response_synthesizer=get_response_synthesizer(llm=llm), ) def _ensure_retriever_modifiable(self): self._ensure_retriever_of_type(ModifiableRAGRetriever) def _ensure_retriever_persistable(self): self._ensure_retriever_of_type(PersistableRAGRetriever) def _ensure_retriever_queryable(self): self._ensure_retriever_of_type(QueryableRAGRetriever) def _ensure_retriever_deletable(self): self._ensure_retriever_of_type(DeletableRAGRetriever) def _ensure_retriever_of_type(self, required_type: BaseRetriever): """Ensure that self.retriever is required_type, or at least one of its components, if it's a SimpleHybridRetriever. Args: required_type: The class that the retriever is expected to be an instance of. """ if isinstance(self.retriever, SimpleHybridRetriever): if not any(isinstance(r, required_type) for r in self.retriever.retrievers): raise TypeError( f"Must have at least one retriever of type {required_type.__name__} in SimpleHybridRetriever" ) if not isinstance(self.retriever, required_type): raise TypeError(f"The retriever is not of type {required_type.__name__}: {type(self.retriever)}") def _save_nodes(self, nodes: list[BaseNode]): self.retriever.add_nodes(nodes) def _persist(self, persist_dir: str, **kwargs): self.retriever.persist(persist_dir, **kwargs) @staticmethod def _try_reconstruct_obj(nodes: list[NodeWithScore]): """If node is object, then dynamically reconstruct object, and save object to node.metadata["obj"].""" for node in nodes: if node.metadata.get("is_obj", False): obj_cls = import_class(node.metadata["obj_cls_name"], node.metadata["obj_mod_name"]) obj_dict = json.loads(node.metadata["obj_json"]) node.metadata["obj"] = obj_cls(**obj_dict) @staticmethod def _fix_document_metadata(documents: list[Document]): """LlamaIndex keep metadata['file_path'], which is unnecessary, maybe deleted in the near future.""" for doc in documents: doc.excluded_embed_metadata_keys.append("file_path") @staticmethod def _resolve_embed_model(embed_model: BaseEmbedding = None, configs: list[Any] = None) -> BaseEmbedding: if configs and all(isinstance(c, NoEmbedding) for c in configs): return MockEmbedding(embed_dim=1) return embed_model or get_rag_embedding() @staticmethod def _default_transformations(): return [SentenceSplitter()] @property def filenames(self) -> Set[str]: return self._filenames @staticmethod def _get_file_extractor() -> dict[str:BaseReader]: """ Get the file extractor. Currently, only PDF use OmniParse. Other document types use the built-in reader from llama_index. Returns: dict[file_type: BaseReader] """ file_extractor: dict[str:BaseReader] = {} if config.omniparse.base_url: pdf_parser = OmniParse( api_key=config.omniparse.api_key, base_url=config.omniparse.base_url, parse_options=OmniParseOptions(parse_type=OmniParseType.PDF, result_type=ParseResultType.MD), ) file_extractor[".pdf"] = pdf_parser return file_extractor
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/engines/__init__.py
metagpt/rag/engines/__init__.py
"""Engines init""" from metagpt.rag.engines.simple import SimpleEngine from metagpt.rag.engines.flare import FLAREEngine __all__ = ["SimpleEngine", "FLAREEngine"]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/prompts/default_prompts.py
metagpt/rag/prompts/default_prompts.py
"""Set of default prompts.""" from llama_index.core.prompts.base import PromptTemplate from llama_index.core.prompts.prompt_type import PromptType DEFAULT_CHOICE_SELECT_PROMPT_TMPL = """ You are a highly efficient assistant, tasked with evaluating a list of documents to a given question. I will provide you with a question with a list of documents. Your task is to respond with the numbers of the documents you should consult to answer the question, in order of relevance, as well as the relevance score. ## Question {query_str} ## Documents {context_str} ## Format Example Doc: 9, Relevance: 7 ## Instructions - Understand the question. - Evaluate the relevance between the question and the documents. - The relevance score is a number from 1-10 based on how relevant you think the document is to the question. - Do not include any documents that are not relevant to the question. - If none of the documents provided contain information that directly answers the question, simply respond with "no relevant documents". ## Constraint Format: Just print the result in format like **Format Example**. ## Action Follow instructions, generate output and make sure it follows the **Constraint**. """ DEFAULT_CHOICE_SELECT_PROMPT = PromptTemplate(DEFAULT_CHOICE_SELECT_PROMPT_TMPL, prompt_type=PromptType.CHOICE_SELECT)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/prompts/__init__.py
metagpt/rag/prompts/__init__.py
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/retrievers/faiss_retriever.py
metagpt/rag/retrievers/faiss_retriever.py
"""FAISS retriever.""" from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.schema import BaseNode class FAISSRetriever(VectorIndexRetriever): """FAISS retriever.""" def add_nodes(self, nodes: list[BaseNode], **kwargs) -> None: """Support add nodes.""" self._index.insert_nodes(nodes, **kwargs) def persist(self, persist_dir: str, **kwargs) -> None: """Support persist.""" self._index.storage_context.persist(persist_dir)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/retrievers/hybrid_retriever.py
metagpt/rag/retrievers/hybrid_retriever.py
"""Hybrid retriever.""" import copy from llama_index.core.schema import BaseNode, QueryType from metagpt.rag.retrievers.base import RAGRetriever class SimpleHybridRetriever(RAGRetriever): """A composite retriever that aggregates search results from multiple retrievers.""" def __init__(self, *retrievers): self.retrievers: list[RAGRetriever] = retrievers super().__init__() async def _aretrieve(self, query: QueryType, **kwargs): """Asynchronously retrieves and aggregates search results from all configured retrievers. This method queries each retriever in the `retrievers` list with the given query and additional keyword arguments. It then combines the results, ensuring that each node is unique, based on the node's ID. """ all_nodes = [] for retriever in self.retrievers: # Prevent retriever changing query query_copy = copy.deepcopy(query) nodes = await retriever.aretrieve(query_copy, **kwargs) all_nodes.extend(nodes) # combine all nodes result = [] node_ids = set() for n in all_nodes: if n.node.node_id not in node_ids: result.append(n) node_ids.add(n.node.node_id) return result def add_nodes(self, nodes: list[BaseNode]) -> None: """Support add nodes.""" for r in self.retrievers: r.add_nodes(nodes) def persist(self, persist_dir: str, **kwargs) -> None: """Support persist.""" for r in self.retrievers: r.persist(persist_dir, **kwargs)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/retrievers/es_retriever.py
metagpt/rag/retrievers/es_retriever.py
"""Elasticsearch retriever.""" from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.schema import BaseNode class ElasticsearchRetriever(VectorIndexRetriever): """Elasticsearch retriever.""" def add_nodes(self, nodes: list[BaseNode], **kwargs) -> None: """Support add nodes.""" self._index.insert_nodes(nodes, **kwargs) def persist(self, persist_dir: str, **kwargs) -> None: """Support persist. Elasticsearch automatically saves, so there is no need to implement."""
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/retrievers/chroma_retriever.py
metagpt/rag/retrievers/chroma_retriever.py
"""Chroma retriever.""" from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.schema import BaseNode from llama_index.vector_stores.chroma import ChromaVectorStore class ChromaRetriever(VectorIndexRetriever): """Chroma retriever.""" @property def vector_store(self) -> ChromaVectorStore: return self._vector_store def add_nodes(self, nodes: list[BaseNode], **kwargs) -> None: """Support add nodes.""" self._index.insert_nodes(nodes, **kwargs) def persist(self, persist_dir: str, **kwargs) -> None: """Support persist. Chromadb automatically saves, so there is no need to implement.""" def query_total_count(self) -> int: """Support query total count.""" return self.vector_store._collection.count() def clear(self, **kwargs) -> None: """Support deleting all nodes.""" ids = self.vector_store._collection.get()["ids"] if ids: self.vector_store._collection.delete(ids=ids)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/retrievers/bm25_retriever.py
metagpt/rag/retrievers/bm25_retriever.py
"""BM25 retriever.""" from pathlib import Path from typing import Callable, Optional from llama_index.core import VectorStoreIndex from llama_index.core.callbacks.base import CallbackManager from llama_index.core.constants import DEFAULT_SIMILARITY_TOP_K from llama_index.core.schema import BaseNode, IndexNode from llama_index.retrievers.bm25 import BM25Retriever from rank_bm25 import BM25Okapi class DynamicBM25Retriever(BM25Retriever): """BM25 retriever.""" def __init__( self, nodes: list[BaseNode], tokenizer: Optional[Callable[[str], list[str]]] = None, similarity_top_k: int = DEFAULT_SIMILARITY_TOP_K, callback_manager: Optional[CallbackManager] = None, objects: Optional[list[IndexNode]] = None, object_map: Optional[dict] = None, verbose: bool = False, index: VectorStoreIndex = None, ) -> None: super().__init__( nodes=nodes, tokenizer=tokenizer, similarity_top_k=similarity_top_k, callback_manager=callback_manager, object_map=object_map, objects=objects, verbose=verbose, ) self._index = index def add_nodes(self, nodes: list[BaseNode], **kwargs) -> None: """Support add nodes.""" self._nodes.extend(nodes) self._corpus = [self._tokenizer(node.get_content()) for node in self._nodes] self.bm25 = BM25Okapi(self._corpus) if self._index: self._index.insert_nodes(nodes, **kwargs) def persist(self, persist_dir: str, **kwargs) -> None: """Support persist.""" if self._index: self._index.storage_context.persist(persist_dir) def query_total_count(self) -> int: """Support query total count.""" return len(self._nodes) def clear(self, **kwargs) -> None: """Support deleting all nodes.""" self._delete_json_files(kwargs.get("persist_dir")) self._nodes = [] @staticmethod def _delete_json_files(directory: str): """Delete all JSON files in the specified directory.""" if not directory: return for file in Path(directory).glob("*.json"): file.unlink()
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/retrievers/__init__.py
metagpt/rag/retrievers/__init__.py
"""Retrievers init.""" from metagpt.rag.retrievers.hybrid_retriever import SimpleHybridRetriever __all__ = ["SimpleHybridRetriever"]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/retrievers/base.py
metagpt/rag/retrievers/base.py
"""Base retriever.""" from abc import abstractmethod from llama_index.core.retrievers import BaseRetriever from llama_index.core.schema import BaseNode, NodeWithScore, QueryType from metagpt.utils.reflection import check_methods class RAGRetriever(BaseRetriever): """Inherit from llama_index""" @abstractmethod async def _aretrieve(self, query: QueryType) -> list[NodeWithScore]: """Retrieve nodes""" def _retrieve(self, query: QueryType) -> list[NodeWithScore]: """Retrieve nodes""" class ModifiableRAGRetriever(RAGRetriever): """Support modification.""" @classmethod def __subclasshook__(cls, C): if cls is ModifiableRAGRetriever: return check_methods(C, "add_nodes") return NotImplemented @abstractmethod def add_nodes(self, nodes: list[BaseNode], **kwargs) -> None: """To support add docs, must inplement this func""" class PersistableRAGRetriever(RAGRetriever): """Support persistent.""" @classmethod def __subclasshook__(cls, C): if cls is PersistableRAGRetriever: return check_methods(C, "persist") return NotImplemented @abstractmethod def persist(self, persist_dir: str, **kwargs) -> None: """To support persist, must inplement this func""" class QueryableRAGRetriever(RAGRetriever): """Support querying total count.""" @classmethod def __subclasshook__(cls, C): if cls is QueryableRAGRetriever: return check_methods(C, "query_total_count") return NotImplemented @abstractmethod def query_total_count(self) -> int: """To support querying total count, must implement this func.""" class DeletableRAGRetriever(RAGRetriever): """Support deleting all nodes.""" @classmethod def __subclasshook__(cls, C): if cls is DeletableRAGRetriever: return check_methods(C, "clear") return NotImplemented @abstractmethod def clear(self, **kwargs) -> int: """To support deleting all nodes, must implement this func."""
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/parsers/__init__.py
metagpt/rag/parsers/__init__.py
from metagpt.rag.parsers.omniparse import OmniParse __all__ = ["OmniParse"]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/rag/parsers/omniparse.py
metagpt/rag/parsers/omniparse.py
import asyncio from fileinput import FileInput from pathlib import Path from typing import List, Optional, Union from llama_index.core import Document from llama_index.core.async_utils import run_jobs from llama_index.core.readers.base import BaseReader from metagpt.logs import logger from metagpt.rag.schema import OmniParseOptions, OmniParseType, ParseResultType from metagpt.utils.async_helper import NestAsyncio from metagpt.utils.omniparse_client import OmniParseClient class OmniParse(BaseReader): """OmniParse""" def __init__( self, api_key: str = None, base_url: str = "http://localhost:8000", parse_options: OmniParseOptions = None ): """ Args: api_key: Default None, can be used for authentication later. base_url: OmniParse Base URL for the API. parse_options: Optional settings for OmniParse. Default is OmniParseOptions with default values. """ self.parse_options = parse_options or OmniParseOptions() self.omniparse_client = OmniParseClient(api_key, base_url, max_timeout=self.parse_options.max_timeout) @property def parse_type(self): return self.parse_options.parse_type @property def result_type(self): return self.parse_options.result_type @parse_type.setter def parse_type(self, parse_type: Union[str, OmniParseType]): if isinstance(parse_type, str): parse_type = OmniParseType(parse_type) self.parse_options.parse_type = parse_type @result_type.setter def result_type(self, result_type: Union[str, ParseResultType]): if isinstance(result_type, str): result_type = ParseResultType(result_type) self.parse_options.result_type = result_type async def _aload_data( self, file_path: Union[str, bytes, Path], extra_info: Optional[dict] = None, ) -> List[Document]: """ Load data from the input file_path. Args: file_path: File path or file byte data. extra_info: Optional dictionary containing additional information. Returns: List[Document] """ try: if self.parse_type == OmniParseType.PDF: # pdf parse parsed_result = await self.omniparse_client.parse_pdf(file_path) else: # other parse use omniparse_client.parse_document # For compatible byte data, additional filename is required extra_info = extra_info or {} filename = extra_info.get("filename") parsed_result = await self.omniparse_client.parse_document(file_path, bytes_filename=filename) # Get the specified structured data based on result_type content = getattr(parsed_result, self.result_type) docs = [ Document( text=content, metadata=extra_info or {}, ) ] except Exception as e: logger.error(f"OMNI Parse Error: {e}") docs = [] return docs async def aload_data( self, file_path: Union[List[FileInput], FileInput], extra_info: Optional[dict] = None, ) -> List[Document]: """ Load data from the input file_path. Args: file_path: File path or file byte data. extra_info: Optional dictionary containing additional information. Notes: This method ultimately calls _aload_data for processing. Returns: List[Document] """ docs = [] if isinstance(file_path, (str, bytes, Path)): # Processing single file docs = await self._aload_data(file_path, extra_info) elif isinstance(file_path, list): # Concurrently process multiple files parse_jobs = [self._aload_data(file_item, extra_info) for file_item in file_path] doc_ret_list = await run_jobs(jobs=parse_jobs, workers=self.parse_options.num_workers) docs = [doc for docs in doc_ret_list for doc in docs] return docs def load_data( self, file_path: Union[List[FileInput], FileInput], extra_info: Optional[dict] = None, ) -> List[Document]: """ Load data from the input file_path. Args: file_path: File path or file byte data. extra_info: Optional dictionary containing additional information. Notes: This method ultimately calls aload_data for processing. Returns: List[Document] """ NestAsyncio.apply_once() # Ensure compatibility with nested async calls return asyncio.run(self.aload_data(file_path, extra_info))
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/extract_readme.py
metagpt/actions/extract_readme.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module Description: This script defines the LearnReadMe class, which is an action to learn from the contents of a README.md file. Author: mashenquan Date: 2024-3-20 """ from pathlib import Path from typing import Optional from pydantic import Field from metagpt.actions import Action from metagpt.const import GRAPH_REPO_FILE_REPO from metagpt.schema import Message from metagpt.utils.common import aread from metagpt.utils.di_graph_repository import DiGraphRepository from metagpt.utils.graph_repository import GraphKeyword, GraphRepository class ExtractReadMe(Action): """ An action to extract summary, installation, configuration, usages from the contents of a README.md file. Attributes: graph_db (Optional[GraphRepository]): A graph database repository. install_to_path (Optional[str]): The path where the repository to install to. """ graph_db: Optional[GraphRepository] = None install_to_path: Optional[str] = Field(default="/TO/PATH") _readme: Optional[str] = None _filename: Optional[str] = None async def run(self, with_messages=None, **kwargs): """ Implementation of `Action`'s `run` method. Args: with_messages (Optional[Type]): An optional argument specifying messages to react to. """ graph_repo_pathname = self.context.git_repo.workdir / GRAPH_REPO_FILE_REPO / self.context.git_repo.workdir.name self.graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json"))) summary = await self._summarize() await self.graph_db.insert(subject=self._filename, predicate=GraphKeyword.HAS_SUMMARY, object_=summary) install = await self._extract_install() await self.graph_db.insert(subject=self._filename, predicate=GraphKeyword.HAS_INSTALL, object_=install) conf = await self._extract_configuration() await self.graph_db.insert(subject=self._filename, predicate=GraphKeyword.HAS_CONFIG, object_=conf) usage = await self._extract_usage() await self.graph_db.insert(subject=self._filename, predicate=GraphKeyword.HAS_USAGE, object_=usage) await self.graph_db.save() return Message(content="", cause_by=self) async def _summarize(self) -> str: readme = await self._get() summary = await self.llm.aask( readme, system_msgs=[ "You are a tool can summarize git repository README.md file.", "Return the summary about what is the repository.", ], stream=False, ) return summary async def _extract_install(self) -> str: await self._get() install = await self.llm.aask( self._readme, system_msgs=[ "You are a tool can install git repository according to README.md file.", "Return a bash code block of markdown including:\n" f"1. git clone the repository to the directory `{self.install_to_path}`;\n" f"2. cd `{self.install_to_path}`;\n" f"3. install the repository.", ], stream=False, ) return install async def _extract_configuration(self) -> str: await self._get() configuration = await self.llm.aask( self._readme, system_msgs=[ "You are a tool can configure git repository according to README.md file.", "Return a bash code block of markdown object to configure the repository if necessary, otherwise return" " a empty bash code block of markdown object", ], stream=False, ) return configuration async def _extract_usage(self) -> str: await self._get() usage = await self.llm.aask( self._readme, system_msgs=[ "You are a tool can summarize all usages of git repository according to README.md file.", "Return a list of code block of markdown objects to demonstrates the usage of the repository.", ], stream=False, ) return usage async def _get(self) -> str: if self._readme is not None: return self._readme root = Path(self.i_context).resolve() filename = None for file_path in root.iterdir(): if file_path.is_file() and file_path.stem == "README": filename = file_path break if not filename: return "" self._readme = await aread(filename=filename, encoding="utf-8") self._filename = str(filename) return self._readme
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/import_repo.py
metagpt/actions/import_repo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script defines an action to import a Git repository into the MetaGPT project format, enabling incremental appending of requirements. The MetaGPT project format encompasses a structured representation of project data compatible with MetaGPT's capabilities, facilitating the integration of Git repositories into MetaGPT workflows while allowing for the gradual addition of requirements. """ import json import re from pathlib import Path from typing import List, Optional from pydantic import BaseModel from metagpt.actions import Action from metagpt.actions.extract_readme import ExtractReadMe from metagpt.actions.rebuild_class_view import RebuildClassView from metagpt.actions.rebuild_sequence_view import RebuildSequenceView from metagpt.const import GRAPH_REPO_FILE_REPO from metagpt.logs import logger from metagpt.schema import Message from metagpt.tools.libs.git import git_clone from metagpt.utils.common import ( aread, awrite, list_files, parse_json_code_block, split_namespace, ) from metagpt.utils.di_graph_repository import DiGraphRepository from metagpt.utils.file_repository import FileRepository from metagpt.utils.git_repository import GitRepository from metagpt.utils.graph_repository import GraphKeyword, GraphRepository from metagpt.utils.project_repo import ProjectRepo class ImportRepo(Action): """ An action to import a Git repository into a graph database and create related artifacts. Attributes: repo_path (str): The URL of the Git repository to import. graph_db (Optional[GraphRepository]): The output graph database of the Git repository. rid (str): The output requirement ID. """ repo_path: str # input, git repo url. graph_db: Optional[GraphRepository] = None # output. graph db of the git repository rid: str = "" # output, requirement ID. async def run(self, with_messages: List[Message] = None, **kwargs) -> Message: """ Runs the import process for the Git repository. Args: with_messages (List[Message], optional): Additional messages to include. **kwargs: Additional keyword arguments. Returns: Message: A message indicating the completion of the import process. """ await self._create_repo() await self._create_prd() await self._create_system_design() self.context.git_repo.archive(comments="Import") async def _create_repo(self): path = await git_clone(url=self.repo_path, output_dir=self.config.workspace.path) self.repo_path = str(path) self.config.project_path = path self.context.git_repo = GitRepository(local_path=path, auto_init=True) self.context.repo = ProjectRepo(self.context.git_repo) self.context.src_workspace = await self._guess_src_workspace() await awrite( filename=self.context.repo.workdir / ".src_workspace", data=str(self.context.src_workspace.relative_to(self.context.repo.workdir)), ) async def _create_prd(self): action = ExtractReadMe(i_context=str(self.context.repo.workdir), context=self.context) await action.run() graph_repo_pathname = self.context.git_repo.workdir / GRAPH_REPO_FILE_REPO / self.context.git_repo.workdir.name self.graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json"))) rows = await self.graph_db.select(predicate=GraphKeyword.HAS_SUMMARY) prd = {"Project Name": self.context.repo.workdir.name} for r in rows: if Path(r.subject).stem == "README": prd["Original Requirements"] = r.object_ break self.rid = FileRepository.new_filename() await self.repo.docs.prd.save(filename=self.rid + ".json", content=json.dumps(prd)) async def _create_system_design(self): action = RebuildClassView( name="ReverseEngineering", i_context=str(self.context.src_workspace), context=self.context ) await action.run() rows = await action.graph_db.select(predicate="hasMermaidClassDiagramFile") class_view_filename = rows[0].object_ logger.info(f"class view:{class_view_filename}") rows = await action.graph_db.select(predicate=GraphKeyword.HAS_PAGE_INFO) tag = "__name__:__main__" entries = [] src_workspace = self.context.src_workspace.relative_to(self.context.repo.workdir) for r in rows: if tag in r.subject: path = split_namespace(r.subject)[0] elif tag in r.object_: path = split_namespace(r.object_)[0] else: continue if Path(path).is_relative_to(src_workspace): entries.append(Path(path)) main_entry = await self._guess_main_entry(entries) full_path = RebuildSequenceView.get_full_filename(self.context.repo.workdir, main_entry) action = RebuildSequenceView(context=self.context, i_context=str(full_path)) try: await action.run() except Exception as e: logger.warning(f"{e}, use the last successful version.") files = list_files(self.context.repo.resources.data_api_design.workdir) pattern = re.compile(r"[^a-zA-Z0-9]") name = re.sub(pattern, "_", str(main_entry)) filename = Path(name).with_suffix(".sequence_diagram.mmd") postfix = str(filename) sequence_files = [i for i in files if postfix in str(i)] content = await aread(filename=sequence_files[0]) await self.context.repo.resources.data_api_design.save( filename=self.repo.workdir.stem + ".sequence_diagram.mmd", content=content ) await self._save_system_design() async def _save_system_design(self): class_view = await self.context.repo.resources.data_api_design.get( filename=self.repo.workdir.stem + ".class_diagram.mmd" ) sequence_view = await self.context.repo.resources.data_api_design.get( filename=self.repo.workdir.stem + ".sequence_diagram.mmd" ) file_list = self.context.git_repo.get_files(relative_path=".", root_relative_path=self.context.src_workspace) data = { "Data structures and interfaces": class_view.content, "Program call flow": sequence_view.content, "File list": [str(i) for i in file_list], } await self.context.repo.docs.system_design.save(filename=self.rid + ".json", content=json.dumps(data)) async def _guess_src_workspace(self) -> Path: files = list_files(self.context.repo.workdir) dirs = [i.parent for i in files if i.name == "__init__.py"] distinct = set() for i in dirs: done = False for j in distinct: if i.is_relative_to(j): done = True break if j.is_relative_to(i): break if not done: distinct = {j for j in distinct if not j.is_relative_to(i)} distinct.add(i) if len(distinct) == 1: return list(distinct)[0] prompt = "\n".join([f"- {str(i)}" for i in distinct]) rsp = await self.llm.aask( prompt, system_msgs=[ "You are a tool to choose the source code path from a list of paths based on the directory name.", "You should identify the source code path among paths such as unit test path, examples path, etc.", "Return a markdown JSON object containing:\n" '- a "src" field containing the source code path;\n' '- a "reason" field containing explaining why other paths is not the source code path\n', ], ) logger.debug(rsp) json_blocks = parse_json_code_block(rsp) class Data(BaseModel): src: str reason: str data = Data.model_validate_json(json_blocks[0]) logger.info(f"src_workspace: {data.src}") return Path(data.src) async def _guess_main_entry(self, entries: List[Path]) -> Path: if len(entries) == 1: return entries[0] file_list = "## File List\n" file_list += "\n".join([f"- {i}" for i in entries]) rows = await self.graph_db.select(predicate=GraphKeyword.HAS_USAGE) usage = "## Usage\n" for r in rows: if Path(r.subject).stem == "README": usage += r.object_ prompt = file_list + "\n---\n" + usage rsp = await self.llm.aask( prompt, system_msgs=[ 'You are a tool to choose the source file path from "File List" which is used in "Usage".', 'You choose the source file path based on the name of file and the class name and package name used in "Usage".', "Return a markdown JSON object containing:\n" '- a "filename" field containing the chosen source file path from "File List" which is used in "Usage";\n' '- a "reason" field explaining why.', ], stream=False, ) logger.debug(rsp) json_blocks = parse_json_code_block(rsp) class Data(BaseModel): filename: str reason: str data = Data.model_validate_json(json_blocks[0]) logger.info(f"main: {data.filename}") return Path(data.filename)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/design_api.py
metagpt/actions/design_api.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 19:26 @Author : alexanderwu @File : design_api.py @Modified By: mashenquan, 2023/11/27. 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name. 2. According to the design in Section 2.2.3.5.3 of RFC 135, add incremental iteration functionality. @Modified By: mashenquan, 2023/12/5. Move the generation logic of the project name to WritePRD. @Modified By: mashenquan, 2024/5/31. Implement Chapter 3 of RFC 236. """ import json from pathlib import Path from typing import List, Optional, Union from pydantic import BaseModel, Field from metagpt.actions import Action from metagpt.actions.design_api_an import ( DATA_STRUCTURES_AND_INTERFACES, DESIGN_API_NODE, PROGRAM_CALL_FLOW, REFINED_DATA_STRUCTURES_AND_INTERFACES, REFINED_DESIGN_NODE, REFINED_PROGRAM_CALL_FLOW, ) from metagpt.const import DATA_API_DESIGN_FILE_REPO, SEQ_FLOW_FILE_REPO from metagpt.logs import logger from metagpt.schema import AIMessage, Document, Documents, Message from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import ( aread, awrite, rectify_pathname, save_json_to_markdown, to_markdown_code_block, ) from metagpt.utils.mermaid import mermaid_to_file from metagpt.utils.project_repo import ProjectRepo from metagpt.utils.report import DocsReporter, GalleryReporter NEW_REQ_TEMPLATE = """ ### Legacy Content {old_design} ### New Requirements {context} """ @register_tool(include_functions=["run"]) class WriteDesign(Action): name: str = "" i_context: Optional[str] = None desc: str = ( "Based on the PRD, think about the system design, and design the corresponding APIs, " "data structures, library tables, processes, and paths. Please provide your design, feedback " "clearly and in detail." ) repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) async def run( self, with_messages: List[Message] = None, *, user_requirement: str = "", prd_filename: str = "", legacy_design_filename: str = "", extra_info: str = "", output_pathname: str = "", **kwargs, ) -> Union[AIMessage, str]: """ Write a system design. Args: user_requirement (str): The user's requirements for the system design. prd_filename (str, optional): The filename of the Product Requirement Document (PRD). legacy_design_filename (str, optional): The filename of the legacy design document. extra_info (str, optional): Additional information to be included in the system design. output_pathname (str, optional): The output file path of the document. Returns: str: The file path of the generated system design. Example: # Write a new system design and save to the path name. >>> user_requirement = "Write system design for a snake game" >>> extra_info = "Your extra information" >>> output_pathname = "snake_game/docs/system_design.json" >>> action = WriteDesign() >>> result = await action.run(user_requirement=user_requirement, extra_info=extra_info, output_pathname=output_pathname) >>> print(result) System Design filename: "/absolute/path/to/snake_game/docs/system_design.json" # Rewrite an existing system design and save to the path name. >>> user_requirement = "Write system design for a snake game, include new features such as a web UI" >>> extra_info = "Your extra information" >>> legacy_design_filename = "/absolute/path/to/snake_game/docs/system_design.json" >>> output_pathname = "/absolute/path/to/snake_game/docs/system_design_new.json" >>> action = WriteDesign() >>> result = await action.run(user_requirement=user_requirement, extra_info=extra_info, legacy_design_filename=legacy_design_filename, output_pathname=output_pathname) >>> print(result) System Design filename: "/absolute/path/to/snake_game/docs/system_design_new.json" # Write a new system design with the given PRD(Product Requirement Document) and save to the path name. >>> user_requirement = "Write system design for a snake game based on the PRD at /absolute/path/to/snake_game/docs/prd.json" >>> extra_info = "Your extra information" >>> prd_filename = "/absolute/path/to/snake_game/docs/prd.json" >>> output_pathname = "/absolute/path/to/snake_game/docs/sytem_design.json" >>> action = WriteDesign() >>> result = await action.run(user_requirement=user_requirement, extra_info=extra_info, prd_filename=prd_filename, output_pathname=output_pathname) >>> print(result) System Design filename: "/absolute/path/to/snake_game/docs/sytem_design.json" # Rewrite an existing system design with the given PRD(Product Requirement Document) and save to the path name. >>> user_requirement = "Write system design for a snake game, include new features such as a web UI" >>> extra_info = "Your extra information" >>> prd_filename = "/absolute/path/to/snake_game/docs/prd.json" >>> legacy_design_filename = "/absolute/path/to/snake_game/docs/system_design.json" >>> output_pathname = "/absolute/path/to/snake_game/docs/system_design_new.json" >>> action = WriteDesign() >>> result = await action.run(user_requirement=user_requirement, extra_info=extra_info, prd_filename=prd_filename, legacy_design_filename=legacy_design_filename, output_pathname=output_pathname) >>> print(result) System Design filename: "/absolute/path/to/snake_game/docs/system_design_new.json" """ if not with_messages: return await self._execute_api( user_requirement=user_requirement, prd_filename=prd_filename, legacy_design_filename=legacy_design_filename, extra_info=extra_info, output_pathname=output_pathname, ) self.input_args = with_messages[-1].instruct_content self.repo = ProjectRepo(self.input_args.project_path) changed_prds = self.input_args.changed_prd_filenames changed_system_designs = [ str(self.repo.docs.system_design.workdir / i) for i in list(self.repo.docs.system_design.changed_files.keys()) ] # For those PRDs and design documents that have undergone changes, regenerate the design content. changed_files = Documents() for filename in changed_prds: doc = await self._update_system_design(filename=filename) changed_files.docs[filename] = doc for filename in changed_system_designs: if filename in changed_files.docs: continue doc = await self._update_system_design(filename=filename) changed_files.docs[filename] = doc if not changed_files.docs: logger.info("Nothing has changed.") # Wait until all files under `docs/system_designs/` are processed before sending the publish message, # leaving room for global optimization in subsequent steps. kvs = self.input_args.model_dump() kvs["changed_system_design_filenames"] = [ str(self.repo.docs.system_design.workdir / i) for i in list(self.repo.docs.system_design.changed_files.keys()) ] return AIMessage( content="Designing is complete. " + "\n".join( list(self.repo.docs.system_design.changed_files.keys()) + list(self.repo.resources.data_api_design.changed_files.keys()) + list(self.repo.resources.seq_flow.changed_files.keys()) ), instruct_content=AIMessage.create_instruct_value(kvs=kvs, class_name="WriteDesignOutput"), cause_by=self, ) async def _new_system_design(self, context): node = await DESIGN_API_NODE.fill(req=context, llm=self.llm, schema=self.prompt_schema) return node async def _merge(self, prd_doc, system_design_doc): context = NEW_REQ_TEMPLATE.format(old_design=system_design_doc.content, context=prd_doc.content) node = await REFINED_DESIGN_NODE.fill(req=context, llm=self.llm, schema=self.prompt_schema) system_design_doc.content = node.instruct_content.model_dump_json() return system_design_doc async def _update_system_design(self, filename) -> Document: root_relative_path = Path(filename).relative_to(self.repo.workdir) prd = await Document.load(filename=filename, project_path=self.repo.workdir) old_system_design_doc = await self.repo.docs.system_design.get(root_relative_path.name) async with DocsReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "design"}, "meta") if not old_system_design_doc: system_design = await self._new_system_design(context=prd.content) doc = await self.repo.docs.system_design.save( filename=prd.filename, content=system_design.instruct_content.model_dump_json(), dependencies={prd.root_relative_path}, ) else: doc = await self._merge(prd_doc=prd, system_design_doc=old_system_design_doc) await self.repo.docs.system_design.save_doc(doc=doc, dependencies={prd.root_relative_path}) await self._save_data_api_design(doc) await self._save_seq_flow(doc) md = await self.repo.resources.system_design.save_pdf(doc=doc) await reporter.async_report(self.repo.workdir / md.root_relative_path, "path") return doc async def _save_data_api_design(self, design_doc, output_filename: Path = None): m = json.loads(design_doc.content) data_api_design = m.get(DATA_STRUCTURES_AND_INTERFACES.key) or m.get(REFINED_DATA_STRUCTURES_AND_INTERFACES.key) if not data_api_design: return pathname = output_filename or self.repo.workdir / DATA_API_DESIGN_FILE_REPO / Path( design_doc.filename ).with_suffix("") await self._save_mermaid_file(data_api_design, pathname) logger.info(f"Save class view to {str(pathname)}") async def _save_seq_flow(self, design_doc, output_filename: Path = None): m = json.loads(design_doc.content) seq_flow = m.get(PROGRAM_CALL_FLOW.key) or m.get(REFINED_PROGRAM_CALL_FLOW.key) if not seq_flow: return pathname = output_filename or self.repo.workdir / Path(SEQ_FLOW_FILE_REPO) / Path( design_doc.filename ).with_suffix("") await self._save_mermaid_file(seq_flow, pathname) logger.info(f"Saving sequence flow to {str(pathname)}") async def _save_mermaid_file(self, data: str, pathname: Path): pathname.parent.mkdir(parents=True, exist_ok=True) await mermaid_to_file(self.config.mermaid.engine, data, pathname) image_path = pathname.parent / f"{pathname.name}.svg" if image_path.exists(): await GalleryReporter().async_report(image_path, "path") async def _execute_api( self, user_requirement: str = "", prd_filename: str = "", legacy_design_filename: str = "", extra_info: str = "", output_pathname: str = "", ) -> str: prd_content = "" if prd_filename: prd_filename = rectify_pathname(path=prd_filename, default_filename="prd.json") prd_content = await aread(filename=prd_filename) context = "### User Requirements\n{user_requirement}\n### Extra_info\n{extra_info}\n### PRD\n{prd}\n".format( user_requirement=to_markdown_code_block(user_requirement), extra_info=to_markdown_code_block(extra_info), prd=to_markdown_code_block(prd_content), ) async with DocsReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "design"}, "meta") if not legacy_design_filename: node = await self._new_system_design(context=context) design = Document(content=node.instruct_content.model_dump_json()) else: old_design_content = await aread(filename=legacy_design_filename) design = await self._merge( prd_doc=Document(content=context), system_design_doc=Document(content=old_design_content) ) if not output_pathname: output_pathname = Path(output_pathname) / "docs" / "system_design.json" elif not Path(output_pathname).is_absolute(): output_pathname = self.config.workspace.path / output_pathname output_pathname = rectify_pathname(path=output_pathname, default_filename="system_design.json") await awrite(filename=output_pathname, data=design.content) output_filename = output_pathname.parent / f"{output_pathname.stem}-class-diagram" await self._save_data_api_design(design_doc=design, output_filename=output_filename) output_filename = output_pathname.parent / f"{output_pathname.stem}-sequence-diagram" await self._save_seq_flow(design_doc=design, output_filename=output_filename) md_output_filename = output_pathname.with_suffix(".md") await save_json_to_markdown(content=design.content, output_filename=md_output_filename) await reporter.async_report(md_output_filename, "path") return f'System Design filename: "{str(output_pathname)}". \n The System Design has been completed.'
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_tutorial.py
metagpt/actions/write_tutorial.py
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """ @Time : 2023/9/4 15:40:40 @Author : Stitch-z @File : tutorial_assistant.py @Describe : Actions of the tutorial assistant, including writing directories and document content. """ from typing import Dict from metagpt.actions import Action from metagpt.prompts.tutorial_assistant import CONTENT_PROMPT, DIRECTORY_PROMPT from metagpt.utils.common import OutputParser class WriteDirectory(Action): """Action class for writing tutorial directories. Args: name: The name of the action. language: The language to output, default is "Chinese". """ name: str = "WriteDirectory" language: str = "Chinese" async def run(self, topic: str, *args, **kwargs) -> Dict: """Execute the action to generate a tutorial directory according to the topic. Args: topic: The tutorial topic. Returns: the tutorial directory information, including {"title": "xxx", "directory": [{"dir 1": ["sub dir 1", "sub dir 2"]}]}. """ prompt = DIRECTORY_PROMPT.format(topic=topic, language=self.language) resp = await self._aask(prompt=prompt) return OutputParser.extract_struct(resp, dict) class WriteContent(Action): """Action class for writing tutorial content. Args: name: The name of the action. directory: The content to write. language: The language to output, default is "Chinese". """ name: str = "WriteContent" directory: dict = dict() language: str = "Chinese" async def run(self, topic: str, *args, **kwargs) -> str: """Execute the action to write document content according to the directory and topic. Args: topic: The tutorial topic. Returns: The written tutorial content. """ prompt = CONTENT_PROMPT.format(topic=topic, language=self.language, directory=self.directory) return await self._aask(prompt=prompt)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_code_review.py
metagpt/actions/write_code_review.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:45 @Author : alexanderwu @File : write_code_review.py @Modified By: mashenquan, 2023/11/27. Following the think-act principle, solidify the task parameters when creating the WriteCode object, rather than passing them in when calling the run function. """ import asyncio import os from pathlib import Path from typing import Optional from pydantic import BaseModel, Field from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import WriteCode from metagpt.actions.action import Action from metagpt.logs import logger from metagpt.schema import CodingContext, Document from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import CodeParser, aread, awrite from metagpt.utils.project_repo import ProjectRepo from metagpt.utils.report import EditorReporter PROMPT_TEMPLATE = """ # System Role: You are a professional software engineer, and your main task is to review and revise the code. You need to ensure that the code conforms to the google-style standards, is elegantly designed and modularized, easy to read and maintain. Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese. ATTENTION: Use '##' to SPLIT SECTIONS, not '#'. Output format carefully referenced "Format example". # Context {context} ----- ## Code to be Reviewed: {filename} ```Code {code} ``` """ EXAMPLE_AND_INSTRUCTION = """ {format_example} # Instruction: Based on the actual code, follow one of the "Code Review Format example". - Note the code filename should be `{filename}`. Return the only ONE file `{filename}` under review. ## Code Review: Ordered List. Based on the "Code to be Reviewed", provide key, clear, concise, and specific answer. If any answer is no, explain how to fix it step by step. 1. Is the code implemented as per the requirements? If not, how to achieve it? Analyse it step by step. 2. Is the code logic completely correct? If there are errors, please indicate how to correct them. 3. Does the existing code follow the "Data structures and interfaces"? 4. Are all functions implemented? If there is no implementation, please indicate how to achieve it step by step. 5. Have all necessary pre-dependencies been imported? If not, indicate which ones need to be imported 6. Are methods from other files being reused correctly? ## Actions: Ordered List. Things that should be done after CR, such as implementing class A and function B ## Code Review Result: str. If the code doesn't have bugs, we don't need to rewrite it, so answer LGTM and stop. ONLY ANSWER LGTM/LBTM. LGTM/LBTM """ FORMAT_EXAMPLE = """ ----- # Code Review Format example 1 ## Code Review: {filename} 1. No, we should fix the logic of class A due to ... 2. ... 3. ... 4. No, function B is not implemented, ... 5. ... 6. ... ## Actions 1. Fix the `handle_events` method to update the game state only if a move is successful. ```python def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: moved = False if event.key == pygame.K_UP: moved = self.game.move('UP') elif event.key == pygame.K_DOWN: moved = self.game.move('DOWN') elif event.key == pygame.K_LEFT: moved = self.game.move('LEFT') elif event.key == pygame.K_RIGHT: moved = self.game.move('RIGHT') if moved: # Update the game state only if a move was successful self.render() return True ``` 2. Implement function B ## Code Review Result LBTM ----- # Code Review Format example 2 ## Code Review: {filename} 1. Yes. 2. Yes. 3. Yes. 4. Yes. 5. Yes. 6. Yes. ## Actions pass ## Code Review Result LGTM ----- """ REWRITE_CODE_TEMPLATE = """ # Instruction: rewrite the `{filename}` based on the Code Review and Actions ## Rewrite Code: CodeBlock. If it still has some bugs, rewrite {filename} using a Markdown code block, with the filename docstring preceding the code block. Do your utmost to optimize THIS SINGLE FILE. Return all completed codes and prohibit the return of unfinished codes. ```python ## {filename} ... ``` or ```javascript // {filename} ... ``` """ class WriteCodeReview(Action): name: str = "WriteCodeReview" i_context: CodingContext = Field(default_factory=CodingContext) repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6)) async def write_code_review_and_rewrite(self, context_prompt, cr_prompt, doc): filename = doc.filename cr_rsp = await self._aask(context_prompt + cr_prompt) result = CodeParser.parse_block("Code Review Result", cr_rsp) if "LGTM" in result: return result, None # if LBTM, rewrite code async with EditorReporter(enable_llm_stream=True) as reporter: await reporter.async_report( {"type": "code", "filename": filename, "src_path": doc.root_relative_path}, "meta" ) rewrite_prompt = f"{context_prompt}\n{cr_rsp}\n{REWRITE_CODE_TEMPLATE.format(filename=filename)}" code_rsp = await self._aask(rewrite_prompt) code = CodeParser.parse_code(text=code_rsp) doc.content = code await reporter.async_report(doc, "document") return result, code async def run(self, *args, **kwargs) -> CodingContext: iterative_code = self.i_context.code_doc.content k = self.context.config.code_validate_k_times or 1 for i in range(k): format_example = FORMAT_EXAMPLE.format(filename=self.i_context.code_doc.filename) task_content = self.i_context.task_doc.content if self.i_context.task_doc else "" code_context = await WriteCode.get_codes( self.i_context.task_doc, exclude=self.i_context.filename, project_repo=self.repo, use_inc=self.config.inc, ) ctx_list = [ "## System Design\n" + str(self.i_context.design_doc) + "\n", "## Task\n" + task_content + "\n", "## Code Files\n" + code_context + "\n", ] if self.config.inc: requirement_doc = await Document.load(filename=self.input_args.requirements_filename) insert_ctx_list = [ "## User New Requirements\n" + str(requirement_doc) + "\n", "## Code Plan And Change\n" + str(self.i_context.code_plan_and_change_doc) + "\n", ] ctx_list = insert_ctx_list + ctx_list context_prompt = PROMPT_TEMPLATE.format( context="\n".join(ctx_list), code=iterative_code, filename=self.i_context.code_doc.filename, ) cr_prompt = EXAMPLE_AND_INSTRUCTION.format( format_example=format_example, filename=self.i_context.code_doc.filename, ) len1 = len(iterative_code) if iterative_code else 0 len2 = len(self.i_context.code_doc.content) if self.i_context.code_doc.content else 0 logger.info( f"Code review and rewrite {self.i_context.code_doc.filename}: {i + 1}/{k} | len(iterative_code)={len1}, " f"len(self.i_context.code_doc.content)={len2}" ) result, rewrited_code = await self.write_code_review_and_rewrite( context_prompt, cr_prompt, self.i_context.code_doc ) if "LBTM" in result: iterative_code = rewrited_code elif "LGTM" in result: self.i_context.code_doc.content = iterative_code return self.i_context # code_rsp = await self._aask_v1(prompt, "code_rsp", OUTPUT_MAPPING) # self._save(context, filename, code) # 如果rewrited_code是None(原code perfect),那么直接返回code self.i_context.code_doc.content = iterative_code return self.i_context @register_tool(include_functions=["run"]) class ValidateAndRewriteCode(Action): """According to the design and task documents, validate the code to ensure it is complete and correct.""" name: str = "ValidateAndRewriteCode" async def run( self, code_path: str, system_design_input: str = "", project_schedule_input: str = "", code_validate_k_times: int = 2, ) -> str: """Validates the provided code based on the accompanying system design and project schedule documentation, return the complete and correct code. Read the code from code_path, and write the final code to code_path. If both system_design_input and project_schedule_input are absent, it will return and do nothing. Args: code_path (str): The file path of the code snippet to be validated. This should be a string containing the path to the source code file. system_design_input (str): Content or file path of the design document associated with the code. This should describe the system architecture, used in the code. It helps provide context for the validation process. project_schedule_input (str): Content or file path of the task document describing what the code is intended to accomplish. This should outline the functional requirements or objectives of the code. code_validate_k_times (int, optional): The number of iterations for validating and potentially rewriting the code. Defaults to 2. Returns: str: The potentially corrected or approved code after validation. Example Usage: # Example of how to call the run method with a code snippet and documentation await ValidateAndRewriteCode().run( code_path="/tmp/game.js", system_design_input="/tmp/system_design.json", project_schedule_input="/tmp/project_task_list.json" ) """ if not system_design_input and not project_schedule_input: logger.info( "Both `system_design_input` and `project_schedule_input` are absent, ValidateAndRewriteCode will do nothing." ) return code, design_doc, task_doc = await asyncio.gather( aread(code_path), self._try_aread(system_design_input), self._try_aread(project_schedule_input) ) code_doc = self._create_code_doc(code_path=code_path, code=code) review_action = WriteCodeReview(i_context=CodingContext(filename=code_doc.filename)) context = "\n".join( [ "## System Design\n" + design_doc + "\n", "## Task\n" + task_doc + "\n", ] ) for i in range(code_validate_k_times): context_prompt = PROMPT_TEMPLATE.format(context=context, code=code, filename=code_path) cr_prompt = EXAMPLE_AND_INSTRUCTION.format( format_example=FORMAT_EXAMPLE.format(filename=code_path), ) logger.info(f"The {i+1}th time to CodeReview: {code_path}.") result, rewrited_code = await review_action.write_code_review_and_rewrite( context_prompt, cr_prompt, doc=code_doc ) if "LBTM" in result: code = rewrited_code elif "LGTM" in result: break await awrite(filename=code_path, data=code) return ( f"The review and rewriting of the code in the file '{os.path.basename(code_path)}' has been completed." + code ) @staticmethod async def _try_aread(input: str) -> str: """Try to read from the path if it's a file; return input directly if not.""" if os.path.exists(input): return await aread(input) return input @staticmethod def _create_code_doc(code_path: str, code: str) -> Document: """Create a Document to represent the code doc.""" path = Path(code_path) return Document(root_path=str(path.parent), filename=path.name, content=code)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_code_an_draft.py
metagpt/actions/write_code_an_draft.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : alexanderwu @File : write_review.py """ import asyncio from typing import List, Literal from metagpt.actions import Action from metagpt.actions.action_node import ActionNode REVIEW = ActionNode( key="Review", expected_type=List[str], instruction="Act as an experienced reviewer and critically assess the given output. Provide specific and" " constructive feedback, highlighting areas for improvement and suggesting changes.", example=[ "The logic in the function `calculate_total` seems flawed. Shouldn't it consider the discount rate as well?", "The TODO function is not implemented yet? Should we implement it before commit?", ], ) REVIEW_RESULT = ActionNode( key="ReviewResult", expected_type=Literal["LGTM", "LBTM"], instruction="LGTM/LBTM. If the code is fully implemented, " "give a LGTM, otherwise provide a LBTM.", example="LBTM", ) NEXT_STEPS = ActionNode( key="NextSteps", expected_type=str, instruction="Based on the code review outcome, suggest actionable steps. This can include code changes, " "refactoring suggestions, or any follow-up tasks.", example="""1. Refactor the `process_data` method to improve readability and efficiency. 2. Cover edge cases in the `validate_user` function. 3. Implement a the TODO in the `calculate_total` function. 4. Fix the `handle_events` method to update the game state only if a move is successful. ```python def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: moved = False if event.key == pygame.K_UP: moved = self.game.move('UP') elif event.key == pygame.K_DOWN: moved = self.game.move('DOWN') elif event.key == pygame.K_LEFT: moved = self.game.move('LEFT') elif event.key == pygame.K_RIGHT: moved = self.game.move('RIGHT') if moved: # Update the game state only if a move was successful self.render() return True ``` """, ) WRITE_DRAFT = ActionNode( key="WriteDraft", expected_type=str, instruction="Could you write draft code for move function in order to implement it?", example="Draft: ...", ) WRITE_FUNCTION = ActionNode( key="WriteFunction", expected_type=str, instruction="write code for the function not implemented.", example=""" ```Code ... ``` """, ) REWRITE_CODE = ActionNode( key="RewriteCode", expected_type=str, instruction="""rewrite code based on the Review and Actions""", example=""" ```python ## example.py def calculate_total(price, quantity): total = price * quantity ``` """, ) CODE_REVIEW_CONTEXT = """ # System Role: You are a professional software engineer, and your main task is to review and revise the code. You need to ensure that the code conforms to the google-style standards, is elegantly designed and modularized, easy to read and maintain. Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese. # Context ## System Design {"Implementation approach": "我们将使用HTML、CSS和JavaScript来实现这个单机的响应式2048游戏。为了确保游戏性能流畅和响应式设计,我们会选择使用Vue.js框架,因为它易于上手且适合构建交互式界面。我们还将使用localStorage来记录玩家的最高分。", "File list": ["index.html", "styles.css", "main.js", "game.js", "storage.js"], "Data structures and interfaces": "classDiagram\ class Game {\ -board Array\ -score Number\ -bestScore Number\ +constructor()\ +startGame()\ +move(direction: String)\ +getBoard() Array\ +getScore() Number\ +getBestScore() Number\ +setBestScore(score: Number)\ }\ class Storage {\ +getBestScore() Number\ +setBestScore(score: Number)\ }\ class Main {\ +init()\ +bindEvents()\ }\ Game --> Storage : uses\ Main --> Game : uses", "Program call flow": "sequenceDiagram\ participant M as Main\ participant G as Game\ participant S as Storage\ M->>G: init()\ G->>S: getBestScore()\ S-->>G: return bestScore\ M->>G: bindEvents()\ M->>G: startGame()\ loop Game Loop\ M->>G: move(direction)\ G->>S: setBestScore(score)\ S-->>G: return\ end", "Anything UNCLEAR": "目前项目要求明确,没有不清楚的地方。"} ## Tasks {"Required packages": ["无需第三方包"], "Required Other language third-party packages": ["vue.js"], "Logic Analysis": [["index.html", "作为游戏的入口文件和主要的HTML结构"], ["styles.css", "包含所有的CSS样式,确保游戏界面美观"], ["main.js", "包含Main类,负责初始化游戏和绑定事件"], ["game.js", "包含Game类,负责游戏逻辑,如开始游戏、移动方块等"], ["storage.js", "包含Storage类,用于获取和设置玩家的最高分"]], "Task list": ["index.html", "styles.css", "storage.js", "game.js", "main.js"], "Full API spec": "", "Shared Knowledge": "\'game.js\' 包含游戏逻辑相关的函数,被 \'main.js\' 调用。", "Anything UNCLEAR": "目前项目要求明确,没有不清楚的地方。"} ## Code Files ----- index.html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>2048游戏</title> <link rel="stylesheet" href="styles.css"> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> </head> <body> <div id="app"> <h1>2048</h1> <div class="scores-container"> <div class="score-container"> <div class="score-header">分数</div> <div>{{ score }}</div> </div> <div class="best-container"> <div class="best-header">最高分</div> <div>{{ bestScore }}</div> </div> </div> <div class="game-container"> <div v-for="(row, rowIndex) in board" :key="rowIndex" class="grid-row"> <div v-for="(cell, cellIndex) in row" :key="cellIndex" class="grid-cell" :class="\'number-cell-\' + cell"> {{ cell !== 0 ? cell : \'\' }} </div> </div> </div> <button @click="startGame" aria-label="开始新游戏">新游戏</button> </div> <script src="storage.js"></script> <script src="game.js"></script> <script src="main.js"></script> <script src="app.js"></script> </body> </html> ----- styles.css /* styles.css */ body, html { margin: 0; padding: 0; font-family: \'Arial\', sans-serif; } #app { text-align: center; font-size: 18px; color: #776e65; } h1 { color: #776e65; font-size: 72px; font-weight: bold; margin: 20px 0; } .scores-container { display: flex; justify-content: center; margin-bottom: 20px; } .score-container, .best-container { background: #bbada0; padding: 10px; border-radius: 5px; margin: 0 10px; min-width: 100px; text-align: center; } .score-header, .best-header { color: #eee4da; font-size: 18px; margin-bottom: 5px; } .game-container { max-width: 500px; margin: 0 auto 20px; background: #bbada0; padding: 15px; border-radius: 10px; position: relative; } .grid-row { display: flex; } .grid-cell { background: #cdc1b4; width: 100px; height: 100px; margin: 5px; display: flex; justify-content: center; align-items: center; font-size: 35px; font-weight: bold; color: #776e65; border-radius: 3px; } /* Dynamic classes for different number cells */ .number-cell-2 { background: #eee4da; } .number-cell-4 { background: #ede0c8; } .number-cell-8 { background: #f2b179; color: #f9f6f2; } .number-cell-16 { background: #f59563; color: #f9f6f2; } .number-cell-32 { background: #f67c5f; color: #f9f6f2; } .number-cell-64 { background: #f65e3b; color: #f9f6f2; } .number-cell-128 { background: #edcf72; color: #f9f6f2; } .number-cell-256 { background: #edcc61; color: #f9f6f2; } .number-cell-512 { background: #edc850; color: #f9f6f2; } .number-cell-1024 { background: #edc53f; color: #f9f6f2; } .number-cell-2048 { background: #edc22e; color: #f9f6f2; } /* Larger numbers need smaller font sizes */ .number-cell-1024, .number-cell-2048 { font-size: 30px; } button { background-color: #8f7a66; color: #f9f6f2; border: none; border-radius: 3px; padding: 10px 20px; font-size: 18px; cursor: pointer; outline: none; } button:hover { background-color: #9f8b76; } ----- storage.js ## storage.js class Storage { // 获取最高分 getBestScore() { // 尝试从localStorage中获取最高分,如果不存在则默认为0 const bestScore = localStorage.getItem(\'bestScore\'); return bestScore ? Number(bestScore) : 0; } // 设置最高分 setBestScore(score) { // 将最高分设置到localStorage中 localStorage.setItem(\'bestScore\', score.toString()); } } ## Code to be Reviewed: game.js ```Code ## game.js class Game { constructor() { this.board = this.createEmptyBoard(); this.score = 0; this.bestScore = 0; } createEmptyBoard() { const board = []; for (let i = 0; i < 4; i++) { board[i] = [0, 0, 0, 0]; } return board; } startGame() { this.board = this.createEmptyBoard(); this.score = 0; this.addRandomTile(); this.addRandomTile(); } addRandomTile() { let emptyCells = []; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (this.board[r][c] === 0) { emptyCells.push({ r, c }); } } } if (emptyCells.length > 0) { let randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)]; this.board[randomCell.r][randomCell.c] = Math.random() < 0.9 ? 2 : 4; } } move(direction) { // This function will handle the logic for moving tiles // in the specified direction and merging them // It will also update the score and add a new random tile if the move is successful // The actual implementation of this function is complex and would require // a significant amount of code to handle all the cases for moving and merging tiles // For the purposes of this example, we will not implement the full logic // Instead, we will just call addRandomTile to simulate a move this.addRandomTile(); } getBoard() { return this.board; } getScore() { return this.score; } getBestScore() { return this.bestScore; } setBestScore(score) { this.bestScore = score; } } ``` """ CODE_REVIEW_SMALLEST_CONTEXT = """ ## Code to be Reviewed: game.js ```Code // game.js class Game { constructor() { this.board = this.createEmptyBoard(); this.score = 0; this.bestScore = 0; } createEmptyBoard() { const board = []; for (let i = 0; i < 4; i++) { board[i] = [0, 0, 0, 0]; } return board; } startGame() { this.board = this.createEmptyBoard(); this.score = 0; this.addRandomTile(); this.addRandomTile(); } addRandomTile() { let emptyCells = []; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (this.board[r][c] === 0) { emptyCells.push({ r, c }); } } } if (emptyCells.length > 0) { let randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)]; this.board[randomCell.r][randomCell.c] = Math.random() < 0.9 ? 2 : 4; } } move(direction) { // This function will handle the logic for moving tiles // in the specified direction and merging them // It will also update the score and add a new random tile if the move is successful // The actual implementation of this function is complex and would require // a significant amount of code to handle all the cases for moving and merging tiles // For the purposes of this example, we will not implement the full logic // Instead, we will just call addRandomTile to simulate a move this.addRandomTile(); } getBoard() { return this.board; } getScore() { return this.score; } getBestScore() { return this.bestScore; } setBestScore(score) { this.bestScore = score; } } ``` """ CODE_REVIEW_SAMPLE = """ ## Code Review: game.js 1. The code partially implements the requirements. The `Game` class is missing the full implementation of the `move` method, which is crucial for the game\'s functionality. 2. The code logic is not completely correct. The `move` method is not implemented, which means the game cannot process player moves. 3. The existing code follows the "Data structures and interfaces" in terms of class structure but lacks full method implementations. 4. Not all functions are implemented. The `move` method is incomplete and does not handle the logic for moving and merging tiles. 5. All necessary pre-dependencies seem to be imported since the code does not indicate the need for additional imports. 6. The methods from other files (such as `Storage`) are not being used in the provided code snippet, but the class structure suggests that they will be used correctly. ## Actions 1. Implement the `move` method to handle tile movements and merging. This is a complex task that requires careful consideration of the game\'s rules and logic. Here is a simplified version of how one might begin to implement the `move` method: ```javascript move(direction) { // Simplified logic for moving tiles up if (direction === \'up\') { for (let col = 0; col < 4; col++) { let tiles = this.board.map(row => row[col]).filter(val => val !== 0); let merged = []; for (let i = 0; i < tiles.length; i++) { if (tiles[i] === tiles[i + 1]) { tiles[i] *= 2; this.score += tiles[i]; tiles[i + 1] = 0; merged.push(i); } } tiles = tiles.filter(val => val !== 0); while (tiles.length < 4) { tiles.push(0); } for (let row = 0; row < 4; row++) { this.board[row][col] = tiles[row]; } } } // Additional logic needed for \'down\', \'left\', \'right\' // ... this.addRandomTile(); } ``` 2. Integrate the `Storage` class methods to handle the best score. This means updating the `startGame` and `setBestScore` methods to use `Storage` for retrieving and setting the best score: ```javascript startGame() { this.board = this.createEmptyBoard(); this.score = 0; this.bestScore = new Storage().getBestScore(); // Retrieve the best score from storage this.addRandomTile(); this.addRandomTile(); } setBestScore(score) { if (score > this.bestScore) { this.bestScore = score; new Storage().setBestScore(score); // Set the new best score in storage } } ``` ## Code Review Result LBTM ``` """ WRITE_CODE_NODE = ActionNode.from_children("WRITE_REVIEW_NODE", [REVIEW, REVIEW_RESULT, NEXT_STEPS]) WRITE_MOVE_NODE = ActionNode.from_children("WRITE_MOVE_NODE", [WRITE_DRAFT, WRITE_FUNCTION]) CR_FOR_MOVE_FUNCTION_BY_3 = """ The move function implementation provided appears to be well-structured and follows a clear logic for moving and merging tiles in the specified direction. However, there are a few potential improvements that could be made to enhance the code: 1. Encapsulation: The logic for moving and merging tiles could be encapsulated into smaller, reusable functions to improve readability and maintainability. 2. Magic Numbers: There are some magic numbers (e.g., 4, 3) used in the loops that could be replaced with named constants for improved readability and easier maintenance. 3. Comments: Adding comments to explain the logic and purpose of each section of the code can improve understanding for future developers who may need to work on or maintain the code. 4. Error Handling: It's important to consider error handling for unexpected input or edge cases to ensure the function behaves as expected in all scenarios. Overall, the code could benefit from refactoring to improve readability, maintainability, and extensibility. If you would like, I can provide a refactored version of the move function that addresses these considerations. """ class WriteCodeAN(Action): """Write a code review for the context.""" async def run(self, context): self.llm.system_prompt = "You are an outstanding engineer and can implement any code" return await WRITE_MOVE_NODE.fill(req=context, llm=self.llm, schema="json") async def main(): await WriteCodeAN().run(CODE_REVIEW_SMALLEST_CONTEXT) if __name__ == "__main__": asyncio.run(main())
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/rebuild_sequence_view.py
metagpt/actions/rebuild_sequence_view.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/1/4 @Author : mashenquan @File : rebuild_sequence_view.py @Desc : Reconstruct sequence view information through reverse engineering. Implement RFC197, https://deepwisdom.feishu.cn/wiki/VyK0wfq56ivuvjklMKJcmHQknGt """ from __future__ import annotations import re from datetime import datetime from pathlib import Path from typing import List, Optional, Set from pydantic import BaseModel from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import Action from metagpt.const import GRAPH_REPO_FILE_REPO from metagpt.logs import logger from metagpt.repo_parser import CodeBlockInfo, DotClassInfo from metagpt.schema import UMLClassView from metagpt.utils.common import ( add_affix, aread, auto_namespace, concat_namespace, general_after_log, list_files, parse_json_code_block, read_file_block, split_namespace, ) from metagpt.utils.di_graph_repository import DiGraphRepository from metagpt.utils.graph_repository import SPO, GraphKeyword, GraphRepository class ReverseUseCase(BaseModel): """ Represents a reverse engineered use case. Attributes: description (str): A description of the reverse use case. inputs (List[str]): List of inputs for the reverse use case. outputs (List[str]): List of outputs for the reverse use case. actors (List[str]): List of actors involved in the reverse use case. steps (List[str]): List of steps for the reverse use case. reason (str): The reason behind the reverse use case. """ description: str inputs: List[str] outputs: List[str] actors: List[str] steps: List[str] reason: str class ReverseUseCaseDetails(BaseModel): """ Represents details of a reverse engineered use case. Attributes: description (str): A description of the reverse use case details. use_cases (List[ReverseUseCase]): List of reverse use cases. relationship (List[str]): List of relationships associated with the reverse use case details. """ description: str use_cases: List[ReverseUseCase] relationship: List[str] 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=None): """ 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. """ format = format if format else self.config.prompt_schema graph_repo_pathname = self.context.git_repo.workdir / GRAPH_REPO_FILE_REPO / self.context.git_repo.workdir.name self.graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json"))) if not self.i_context: entries = await self._search_main_entry() else: entries = [SPO(subject=self.i_context, predicate="", object_="")] for entry in entries: await self._rebuild_main_sequence_view(entry) while await self._merge_sequence_view(entry): pass 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_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__`. """ 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 = await self._search_participants(split_namespace(entry.subject)[0]) 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.append(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.", ], stream=False, ) sequence_view = rsp.removeprefix("```mermaid").removesuffix("```") rows = await self.graph_db.select(subject=entry.subject, predicate=GraphKeyword.HAS_SEQUENCE_VIEW) for r in rows: if r.predicate == GraphKeyword.HAS_SEQUENCE_VIEW: 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._save_sequence_view(subject=entry.subject, content=sequence_view) 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: if tag in r.subject or tag in r.object_: entries.append(r) return entries @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. """ rows = await self.graph_db.select(subject=ns_class_name, predicate=GraphKeyword.HAS_CLASS_USE_CASE) if rows: return 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', ], stream=False, ) 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() ) @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. """ 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_="") 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.", "Response must be concise.", "Return a markdown mermaid code block.", ], stream=False, ) sequence_view = rsp.removeprefix("```mermaid").removesuffix("```") await self.graph_db.insert( subject=ns_class_name, predicate=GraphKeyword.HAS_SEQUENCE_VIEW, object_=sequence_view ) 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 ) @staticmethod def 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" """ if re.match(r"^/.+", str(pathname)): return pathname files = list_files(root=root) postfix = "/" + str(pathname) for i in files: if str(i).endswith(postfix): return i return 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 ([\w\.]+)" 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. """ 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) ) 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) ) 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.", ], stream=False, ) 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._save_sequence_view(subject=entry.subject, content=sequence_view) async def _save_sequence_view(self, subject: str, content: str): pattern = re.compile(r"[^a-zA-Z0-9]") name = re.sub(pattern, "_", subject) filename = Path(name).with_suffix(".sequence_diagram.mmd") await self.context.repo.resources.data_api_design.save(filename=str(filename), content=content) async def _search_participants(self, filename: str) -> Set: content = await self._get_source_code(filename) rsp = await self.llm.aask( msg=content, system_msgs=[ "You are a tool for listing all class names used in a source file.", "Return a markdown JSON object with: " '- a "class_names" key containing the list of class names used in the file; ' '- a "reasons" key lists all reason objects, each object containing a "class_name" key for class name, a "reference" key explaining the line where the class has been used.', ], ) class _Data(BaseModel): class_names: List[str] reasons: List json_blocks = parse_json_code_block(rsp) data = _Data.model_validate_json(json_blocks[0]) return set(data.class_names)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_prd.py
metagpt/actions/write_prd.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:45 @Author : alexanderwu @File : write_prd.py @Modified By: mashenquan, 2023/11/27. 1. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name. 2. According to the design in Section 2.2.3.5.2 of RFC 135, add incremental iteration functionality. 3. Move the document storage operations related to WritePRD from the save operation of WriteDesign. @Modified By: mashenquan, 2023/12/5. Move the generation logic of the project name to WritePRD. @Modified By: mashenquan, 2024/5/31. Implement Chapter 3 of RFC 236. """ from __future__ import annotations import json from pathlib import Path from typing import List, Optional, Union from pydantic import BaseModel, Field from metagpt.actions import Action, ActionOutput from metagpt.actions.action_node import ActionNode from metagpt.actions.fix_bug import FixBug from metagpt.actions.write_prd_an import ( COMPETITIVE_QUADRANT_CHART, PROJECT_NAME, REFINED_PRD_NODE, WP_IS_RELATIVE_NODE, WP_ISSUE_TYPE_NODE, WRITE_PRD_NODE, ) from metagpt.const import ( BUGFIX_FILENAME, COMPETITIVE_ANALYSIS_FILE_REPO, REQUIREMENT_FILENAME, ) from metagpt.logs import logger from metagpt.schema import AIMessage, Document, Documents, Message from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import ( CodeParser, aread, awrite, rectify_pathname, save_json_to_markdown, to_markdown_code_block, ) from metagpt.utils.file_repository import FileRepository from metagpt.utils.mermaid import mermaid_to_file from metagpt.utils.project_repo import ProjectRepo from metagpt.utils.report import DocsReporter, GalleryReporter CONTEXT_TEMPLATE = """ ### Project Name {project_name} ### Original Requirements {requirements} ### Search Information - """ NEW_REQ_TEMPLATE = """ ### Legacy Content {old_prd} ### New Requirements {requirements} """ @register_tool(include_functions=["run"]) class WritePRD(Action): """WritePRD deal with the following situations: 1. Bugfix: If the requirement is a bugfix, the bugfix document will be generated. 2. New requirement: If the requirement is a new requirement, the PRD document will be generated. 3. Requirement update: If the requirement is an update, the PRD document will be updated. """ repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) async def run( self, with_messages: List[Message] = None, *, user_requirement: str = "", output_pathname: str = "", legacy_prd_filename: str = "", extra_info: str = "", **kwargs, ) -> Union[AIMessage, str]: """ Write a Product Requirement Document. Args: user_requirement (str): A string detailing the user's requirements. output_pathname (str, optional): The output file path of the document. Defaults to "". legacy_prd_filename (str, optional): The file path of the legacy Product Requirement Document to use as a reference. Defaults to "". extra_info (str, optional): Additional information to include in the document. Defaults to "". **kwargs: Additional keyword arguments. Returns: str: The file path of the generated Product Requirement Document. Example: # Write a new PRD (Product Requirement Document) >>> user_requirement = "Write a snake game" >>> output_pathname = "snake_game/docs/prd.json" >>> extra_info = "YOUR EXTRA INFO, if any" >>> write_prd = WritePRD() >>> result = await write_prd.run(user_requirement=user_requirement, output_pathname=output_pathname, extra_info=extra_info) >>> print(result) PRD filename: "/absolute/path/to/snake_game/docs/prd.json" # Rewrite an existing PRD (Product Requirement Document) and save to a new path. >>> user_requirement = "Write PRD for a snake game, include new features such as a web UI" >>> legacy_prd_filename = "/absolute/path/to/snake_game/docs/prd.json" >>> output_pathname = "/absolute/path/to/snake_game/docs/prd_new.json" >>> extra_info = "YOUR EXTRA INFO, if any" >>> write_prd = WritePRD() >>> result = await write_prd.run(user_requirement=user_requirement, legacy_prd_filename=legacy_prd_filename, extra_info=extra_info) >>> print(result) PRD filename: "/absolute/path/to/snake_game/docs/prd_new.json" """ if not with_messages: return await self._execute_api( user_requirement=user_requirement, output_pathname=output_pathname, legacy_prd_filename=legacy_prd_filename, extra_info=extra_info, ) self.input_args = with_messages[-1].instruct_content if not self.input_args: self.repo = ProjectRepo(self.context.kwargs.project_path) await self.repo.docs.save(filename=REQUIREMENT_FILENAME, content=with_messages[-1].content) self.input_args = AIMessage.create_instruct_value( kvs={ "project_path": self.context.kwargs.project_path, "requirements_filename": str(self.repo.docs.workdir / REQUIREMENT_FILENAME), "prd_filenames": [str(self.repo.docs.prd.workdir / i) for i in self.repo.docs.prd.all_files], }, class_name="PrepareDocumentsOutput", ) else: self.repo = ProjectRepo(self.input_args.project_path) req = await Document.load(filename=self.input_args.requirements_filename) docs: list[Document] = [ await Document.load(filename=i, project_path=self.repo.workdir) for i in self.input_args.prd_filenames ] if not req: raise FileNotFoundError("No requirement document found.") if await self._is_bugfix(req.content): logger.info(f"Bugfix detected: {req.content}") return await self._handle_bugfix(req) # remove bugfix file from last round in case of conflict await self.repo.docs.delete(filename=BUGFIX_FILENAME) # if requirement is related to other documents, update them, otherwise create a new one if related_docs := await self.get_related_docs(req, docs): logger.info(f"Requirement update detected: {req.content}") await self._handle_requirement_update(req=req, related_docs=related_docs) else: logger.info(f"New requirement detected: {req.content}") await self._handle_new_requirement(req) kvs = self.input_args.model_dump() kvs["changed_prd_filenames"] = [ str(self.repo.docs.prd.workdir / i) for i in list(self.repo.docs.prd.changed_files.keys()) ] kvs["project_path"] = str(self.repo.workdir) kvs["requirements_filename"] = str(self.repo.docs.workdir / REQUIREMENT_FILENAME) self.context.kwargs.project_path = str(self.repo.workdir) return AIMessage( content="PRD is completed. " + "\n".join( list(self.repo.docs.prd.changed_files.keys()) + list(self.repo.resources.prd.changed_files.keys()) + list(self.repo.resources.competitive_analysis.changed_files.keys()) ), instruct_content=AIMessage.create_instruct_value(kvs=kvs, class_name="WritePRDOutput"), cause_by=self, ) async def _handle_bugfix(self, req: Document) -> AIMessage: # ... bugfix logic ... await self.repo.docs.save(filename=BUGFIX_FILENAME, content=req.content) await self.repo.docs.save(filename=REQUIREMENT_FILENAME, content="") return AIMessage( content=f"A new issue is received: {BUGFIX_FILENAME}", cause_by=FixBug, instruct_content=AIMessage.create_instruct_value( { "project_path": str(self.repo.workdir), "issue_filename": str(self.repo.docs.workdir / BUGFIX_FILENAME), "requirements_filename": str(self.repo.docs.workdir / REQUIREMENT_FILENAME), }, class_name="IssueDetail", ), send_to="Alex", # the name of Engineer ) async def _new_prd(self, requirement: str) -> ActionNode: project_name = self.project_name context = CONTEXT_TEMPLATE.format(requirements=requirement, project_name=project_name) exclude = [PROJECT_NAME.key] if project_name else [] node = await WRITE_PRD_NODE.fill( req=context, llm=self.llm, exclude=exclude, schema=self.prompt_schema ) # schema=schema return node async def _handle_new_requirement(self, req: Document) -> ActionOutput: """handle new requirement""" async with DocsReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "prd"}, "meta") node = await self._new_prd(req.content) await self._rename_workspace(node) new_prd_doc = await self.repo.docs.prd.save( filename=FileRepository.new_filename() + ".json", content=node.instruct_content.model_dump_json() ) await self._save_competitive_analysis(new_prd_doc) md = await self.repo.resources.prd.save_pdf(doc=new_prd_doc) await reporter.async_report(self.repo.workdir / md.root_relative_path, "path") return Documents.from_iterable(documents=[new_prd_doc]).to_action_output() async def _handle_requirement_update(self, req: Document, related_docs: list[Document]) -> ActionOutput: # ... requirement update logic ... for doc in related_docs: await self._update_prd(req=req, prd_doc=doc) return Documents.from_iterable(documents=related_docs).to_action_output() async def _is_bugfix(self, context: str) -> bool: if not self.repo.code_files_exists(): return False node = await WP_ISSUE_TYPE_NODE.fill(req=context, llm=self.llm) return node.get("issue_type") == "BUG" async def get_related_docs(self, req: Document, docs: list[Document]) -> list[Document]: """get the related documents""" # refine: use gather to speed up return [i for i in docs if await self._is_related(req, i)] async def _is_related(self, req: Document, old_prd: Document) -> bool: context = NEW_REQ_TEMPLATE.format(old_prd=old_prd.content, requirements=req.content) node = await WP_IS_RELATIVE_NODE.fill(req=context, llm=self.llm) return node.get("is_relative") == "YES" async def _merge(self, req: Document, related_doc: Document) -> Document: if not self.project_name: self.project_name = Path(self.project_path).name prompt = NEW_REQ_TEMPLATE.format(requirements=req.content, old_prd=related_doc.content) node = await REFINED_PRD_NODE.fill(req=prompt, llm=self.llm, schema=self.prompt_schema) related_doc.content = node.instruct_content.model_dump_json() await self._rename_workspace(node) return related_doc async def _update_prd(self, req: Document, prd_doc: Document) -> Document: async with DocsReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "prd"}, "meta") new_prd_doc: Document = await self._merge(req=req, related_doc=prd_doc) await self.repo.docs.prd.save_doc(doc=new_prd_doc) await self._save_competitive_analysis(new_prd_doc) md = await self.repo.resources.prd.save_pdf(doc=new_prd_doc) await reporter.async_report(self.repo.workdir / md.root_relative_path, "path") return new_prd_doc async def _save_competitive_analysis(self, prd_doc: Document, output_filename: Path = None): m = json.loads(prd_doc.content) quadrant_chart = m.get(COMPETITIVE_QUADRANT_CHART.key) if not quadrant_chart: return pathname = output_filename or self.repo.workdir / COMPETITIVE_ANALYSIS_FILE_REPO / Path(prd_doc.filename).stem pathname.parent.mkdir(parents=True, exist_ok=True) await mermaid_to_file(self.config.mermaid.engine, quadrant_chart, pathname) image_path = pathname.parent / f"{pathname.name}.svg" if image_path.exists(): await GalleryReporter().async_report(image_path, "path") async def _rename_workspace(self, prd): if not self.project_name: if isinstance(prd, (ActionOutput, ActionNode)): ws_name = prd.instruct_content.model_dump()["Project Name"] else: ws_name = CodeParser.parse_str(block="Project Name", text=prd) if ws_name: self.project_name = ws_name if self.repo: self.repo.git_repo.rename_root(self.project_name) async def _execute_api( self, user_requirement: str, output_pathname: str, legacy_prd_filename: str, extra_info: str ) -> str: content = "#### User Requirements\n{user_requirement}\n#### Extra Info\n{extra_info}\n".format( user_requirement=to_markdown_code_block(val=user_requirement), extra_info=to_markdown_code_block(val=extra_info), ) async with DocsReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "prd"}, "meta") req = Document(content=content) if not legacy_prd_filename: node = await self._new_prd(requirement=req.content) new_prd = Document(content=node.instruct_content.model_dump_json()) else: content = await aread(filename=legacy_prd_filename) old_prd = Document(content=content) new_prd = await self._merge(req=req, related_doc=old_prd) if not output_pathname: output_pathname = self.config.workspace.path / "docs" / "prd.json" elif not Path(output_pathname).is_absolute(): output_pathname = self.config.workspace.path / output_pathname output_pathname = rectify_pathname(path=output_pathname, default_filename="prd.json") await awrite(filename=output_pathname, data=new_prd.content) competitive_analysis_filename = output_pathname.parent / f"{output_pathname.stem}-competitive-analysis" await self._save_competitive_analysis(prd_doc=new_prd, output_filename=Path(competitive_analysis_filename)) md_output_filename = output_pathname.with_suffix(".md") await save_json_to_markdown(content=new_prd.content, output_filename=md_output_filename) await reporter.async_report(md_output_filename, "path") return f'PRD filename: "{str(output_pathname)}". The product requirement document (PRD) has been completed.'
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_teaching_plan.py
metagpt/actions/write_teaching_plan.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/7/27 @Author : mashenquan @File : write_teaching_plan.py """ from typing import Optional from metagpt.actions import Action from metagpt.context import Context from metagpt.logs import logger class WriteTeachingPlanPart(Action): """Write Teaching Plan Part""" i_context: Optional[str] = None topic: str = "" language: str = "Chinese" rsp: Optional[str] = None async def run(self, with_message=None, **kwargs): statement_patterns = TeachingPlanBlock.TOPIC_STATEMENTS.get(self.topic, []) statements = [] for p in statement_patterns: s = self.format_value(p, context=self.context) statements.append(s) formatter = ( TeachingPlanBlock.PROMPT_TITLE_TEMPLATE if self.topic == TeachingPlanBlock.COURSE_TITLE else TeachingPlanBlock.PROMPT_TEMPLATE ) prompt = formatter.format( formation=TeachingPlanBlock.FORMATION, role=self.prefix, statements="\n".join(statements), lesson=self.i_context, topic=self.topic, language=self.language, ) logger.debug(prompt) rsp = await self._aask(prompt=prompt) logger.debug(rsp) self._set_result(rsp) return self.rsp def _set_result(self, rsp): if TeachingPlanBlock.DATA_BEGIN_TAG in rsp: ix = rsp.index(TeachingPlanBlock.DATA_BEGIN_TAG) rsp = rsp[ix + len(TeachingPlanBlock.DATA_BEGIN_TAG) :] if TeachingPlanBlock.DATA_END_TAG in rsp: ix = rsp.index(TeachingPlanBlock.DATA_END_TAG) rsp = rsp[0:ix] self.rsp = rsp.strip() if self.topic != TeachingPlanBlock.COURSE_TITLE: return if "#" not in self.rsp or self.rsp.index("#") != 0: self.rsp = "# " + self.rsp def __str__(self): """Return `topic` value when str()""" return self.topic def __repr__(self): """Show `topic` value when debug""" return self.topic @staticmethod def format_value(value, context: Context): """Fill parameters inside `value` with `options`.""" if not isinstance(value, str): return value if "{" not in value: return value options = context.config.model_dump() for k, v in context.kwargs: options[k] = v # None value is allowed to override and disable the value from config. opts = {k: v for k, v in options.items() if v is not None} try: return value.format(**opts) except KeyError as e: logger.warning(f"Parameter is missing:{e}") for k, v in opts.items(): value = value.replace("{" + f"{k}" + "}", str(v)) return value class TeachingPlanBlock: FORMATION = ( '"Capacity and role" defines the role you are currently playing;\n' '\t"[LESSON_BEGIN]" and "[LESSON_END]" tags enclose the content of textbook;\n' '\t"Statement" defines the work detail you need to complete at this stage;\n' '\t"Answer options" defines the format requirements for your responses;\n' '\t"Constraint" defines the conditions that your responses must comply with.' ) COURSE_TITLE = "Title" TOPICS = [ COURSE_TITLE, "Teaching Hours", "Teaching Objectives", "Teaching Content", "Teaching Methods and Strategies", "Learning Activities", "Teaching Time Allocation", "Assessment and Feedback", "Teaching Summary and Improvement", "Vocabulary Cloze", "Choice Questions", "Grammar Questions", "Translation Questions", ] TOPIC_STATEMENTS = { COURSE_TITLE: [ "Statement: Find and return the title of the lesson only in markdown first-level header format, " "without anything else." ], "Teaching Content": [ 'Statement: "Teaching Content" must include vocabulary, analysis, and examples of various grammar ' "structures that appear in the textbook, as well as the listening materials and key points.", 'Statement: "Teaching Content" must include more examples.', ], "Teaching Time Allocation": [ 'Statement: "Teaching Time Allocation" must include how much time is allocated to each ' "part of the textbook content." ], "Teaching Methods and Strategies": [ 'Statement: "Teaching Methods and Strategies" must include teaching focus, difficulties, materials, ' "procedures, in detail." ], "Vocabulary Cloze": [ 'Statement: Based on the content of the textbook enclosed by "[LESSON_BEGIN]" and "[LESSON_END]", ' "create vocabulary cloze. The cloze should include 10 {language} questions with {teaching_language} " "answers, and it should also include 10 {teaching_language} questions with {language} answers. " "The key-related vocabulary and phrases in the textbook content must all be included in the exercises.", ], "Grammar Questions": [ 'Statement: Based on the content of the textbook enclosed by "[LESSON_BEGIN]" and "[LESSON_END]", ' "create grammar questions. 10 questions." ], "Choice Questions": [ 'Statement: Based on the content of the textbook enclosed by "[LESSON_BEGIN]" and "[LESSON_END]", ' "create choice questions. 10 questions." ], "Translation Questions": [ 'Statement: Based on the content of the textbook enclosed by "[LESSON_BEGIN]" and "[LESSON_END]", ' "create translation questions. The translation should include 10 {language} questions with " "{teaching_language} answers, and it should also include 10 {teaching_language} questions with " "{language} answers." ], } # Teaching plan title PROMPT_TITLE_TEMPLATE = ( "Do not refer to the context of the previous conversation records, " "start the conversation anew.\n\n" "Formation: {formation}\n\n" "{statements}\n" "Constraint: Writing in {language}.\n" 'Answer options: Encloses the lesson title with "[TEACHING_PLAN_BEGIN]" ' 'and "[TEACHING_PLAN_END]" tags.\n' "[LESSON_BEGIN]\n" "{lesson}\n" "[LESSON_END]" ) # Teaching plan parts: PROMPT_TEMPLATE = ( "Do not refer to the context of the previous conversation records, " "start the conversation anew.\n\n" "Formation: {formation}\n\n" "Capacity and role: {role}\n" 'Statement: Write the "{topic}" part of teaching plan, ' 'WITHOUT ANY content unrelated to "{topic}"!!\n' "{statements}\n" 'Answer options: Enclose the teaching plan content with "[TEACHING_PLAN_BEGIN]" ' 'and "[TEACHING_PLAN_END]" tags.\n' "Answer options: Using proper markdown format from second-level header format.\n" "Constraint: Writing in {language}.\n" "[LESSON_BEGIN]\n" "{lesson}\n" "[LESSON_END]" ) DATA_BEGIN_TAG = "[TEACHING_PLAN_BEGIN]" DATA_END_TAG = "[TEACHING_PLAN_END]"
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/fix_bug.py
metagpt/actions/fix_bug.py
# -*- coding: utf-8 -*- """ @Time : 2023-12-12 @Author : mashenquan @File : fix_bug.py """ from metagpt.actions import Action class FixBug(Action): """Fix bug action without any implementation details""" name: str = "FixBug"
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/design_api_review.py
metagpt/actions/design_api_review.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 19:31 @Author : alexanderwu @File : design_api_review.py """ from typing import Optional from metagpt.actions.action import Action class DesignReview(Action): name: str = "DesignReview" i_context: Optional[str] = None async def run(self, prd, api_design): prompt = ( f"Here is the Product Requirement Document (PRD):\n\n{prd}\n\nHere is the list of APIs designed " f"based on this PRD:\n\n{api_design}\n\nPlease review whether this API design meets the requirements" f" of the PRD, and whether it complies with good design practices." ) api_review = await self._aask(prompt) return api_review
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/analyze_requirements.py
metagpt/actions/analyze_requirements.py
from metagpt.actions import Action ANALYZE_REQUIREMENTS = """ # Example {examples} ---------------- # Requirements {requirements} # Instructions {instructions} # Output Format {output_format} Follow the instructions and output format. Do not include any additional content. """ EXAMPLES = """ Example 1 Requirements: 创建一个贪吃蛇,只需要给出设计文档和代码 Outputs: [User Restrictions] : 只需要给出设计文档和代码. [Language Restrictions] : The response, message and instruction must be in Chinese. [Programming Language] : HTML (*.html), CSS (*.css), and JavaScript (*.js) Example 2 Requirements: Create 2048 game using Python. Do not write PRD. Outputs: [User Restrictions] : Do not write PRD. [Language Restrictions] : The response, message and instruction must be in English. [Programming Language] : Python Example 3 Requirements: You must ignore create PRD and TRD. Help me write a schedule display program for the Paris Olympics. Outputs: [User Restrictions] : You must ignore create PRD and TRD. [Language Restrictions] : The response, message and instruction must be in English. [Programming Language] : HTML (*.html), CSS (*.css), and JavaScript (*.js) """ INSTRUCTIONS = """ You must output in the same language as the Requirements. First, This language should be consistent with the language used in the requirement description. determine the natural language you must respond in. If the requirements specify a special language, follow those instructions. The default language for responses is English. Second, extract the restrictions in the requirements, specifically the steps. Do not include detailed demand descriptions; focus only on the restrictions. Third, if the requirements is a software development, extract the program language. If no specific programming language is required, Use HTML (*.html), CSS (*.css), and JavaScript (*.js) Note: 1. if there is not restrictions, requirements_restrictions must be "" 2. if the requirements is a not software development, programming language must be "" """ OUTPUT_FORMAT = """ [User Restrictions] : the restrictions in the requirements [Language Restrictions] : The response, message and instruction must be in {{language}} [Programming Language] : Your program must use ... """ class AnalyzeRequirementsRestrictions(Action): """Write a review for the given context.""" name: str = "AnalyzeRequirementsRestrictions" async def run(self, requirements, isinstance=INSTRUCTIONS, output_format=OUTPUT_FORMAT): """Analyze the constraints and the language used in the requirements.""" prompt = ANALYZE_REQUIREMENTS.format( examples=EXAMPLES, requirements=requirements, instructions=isinstance, output_format=output_format ) rsp = await self.llm.aask(prompt) return rsp
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_code.py
metagpt/actions/write_code.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:45 @Author : alexanderwu @File : write_code.py @Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.1.3 of RFC 116, modify the data type of the `cause_by` value of the `Message` object. @Modified By: mashenquan, 2023-11-27. 1. Mark the location of Design, Tasks, Legacy Code and Debug logs in the PROMPT_TEMPLATE with markdown code-block formatting to enhance the understanding for the LLM. 2. Following the think-act principle, solidify the task parameters when creating the WriteCode object, rather than passing them in when calling the run function. 3. Encapsulate the input of RunCode into RunCodeContext and encapsulate the output of RunCode into RunCodeResult to standardize and unify parameter passing between WriteCode, RunCode, and DebugError. """ import json from pathlib import Path from typing import Optional from pydantic import BaseModel, Field from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions.action import Action from metagpt.actions.project_management_an import REFINED_TASK_LIST, TASK_LIST from metagpt.actions.write_code_plan_and_change_an import REFINED_TEMPLATE from metagpt.logs import logger from metagpt.schema import CodingContext, Document, RunCodeResult from metagpt.utils.common import CodeParser, get_markdown_code_block_type from metagpt.utils.project_repo import ProjectRepo from metagpt.utils.report import EditorReporter PROMPT_TEMPLATE = """ NOTICE Role: You are a professional engineer; the main goal is to write google-style, elegant, modular, easy to read and maintain code Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese. ATTENTION: Use '##' to SPLIT SECTIONS, not '#'. Output format carefully referenced "Format example". # Context ## Design {design} ## Task {task} ## Legacy Code {code} ## Debug logs ```text {logs} {summary_log} ``` ## Bug Feedback logs ```text {feedback} ``` # Format example ## Code: {demo_filename}.py ```python ## {demo_filename}.py ... ``` ## Code: {demo_filename}.js ```javascript // {demo_filename}.js ... ``` # Instruction: Based on the context, follow "Format example", write code. ## Code: {filename}. Write code with triple quoto, based on the following attentions and context. 1. Only One file: do your best to implement THIS ONLY ONE FILE. 2. COMPLETE CODE: Your code will be part of the entire project, so please implement complete, reliable, reusable code snippets. 3. Set default value: If there is any setting, ALWAYS SET A DEFAULT VALUE, ALWAYS USE STRONG TYPE AND EXPLICIT VARIABLE. AVOID circular import. 4. Follow design: YOU MUST FOLLOW "Data structures and interfaces". DONT CHANGE ANY DESIGN. Do not use public member functions that do not exist in your design. 5. CAREFULLY CHECK THAT YOU DONT MISS ANY NECESSARY CLASS/FUNCTION IN THIS FILE. 6. Before using a external variable/module, make sure you import it first. 7. Write out EVERY CODE DETAIL, DON'T LEAVE TODO. """ class WriteCode(Action): name: str = "WriteCode" i_context: Document = Field(default_factory=Document) repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6)) async def write_code(self, prompt) -> str: code_rsp = await self._aask(prompt) code = CodeParser.parse_code(text=code_rsp) return code async def run(self, *args, **kwargs) -> CodingContext: bug_feedback = None if self.input_args and hasattr(self.input_args, "issue_filename"): bug_feedback = await Document.load(self.input_args.issue_filename) coding_context = CodingContext.loads(self.i_context.content) if not coding_context.code_plan_and_change_doc: coding_context.code_plan_and_change_doc = await self.repo.docs.code_plan_and_change.get( filename=coding_context.task_doc.filename ) test_doc = await self.repo.test_outputs.get(filename="test_" + coding_context.filename + ".json") requirement_doc = await Document.load(self.input_args.requirements_filename) summary_doc = None if coding_context.design_doc and coding_context.design_doc.filename: summary_doc = await self.repo.docs.code_summary.get(filename=coding_context.design_doc.filename) logs = "" if test_doc: test_detail = RunCodeResult.loads(test_doc.content) logs = test_detail.stderr if self.config.inc or bug_feedback: code_context = await self.get_codes( coding_context.task_doc, exclude=self.i_context.filename, project_repo=self.repo, use_inc=True ) else: code_context = await self.get_codes( coding_context.task_doc, exclude=self.i_context.filename, project_repo=self.repo ) if self.config.inc: prompt = REFINED_TEMPLATE.format( user_requirement=requirement_doc.content if requirement_doc else "", code_plan_and_change=coding_context.code_plan_and_change_doc.content if coding_context.code_plan_and_change_doc else "", design=coding_context.design_doc.content if coding_context.design_doc else "", task=coding_context.task_doc.content if coding_context.task_doc else "", code=code_context, logs=logs, feedback=bug_feedback.content if bug_feedback else "", filename=self.i_context.filename, demo_filename=Path(self.i_context.filename).stem, summary_log=summary_doc.content if summary_doc else "", ) else: prompt = PROMPT_TEMPLATE.format( design=coding_context.design_doc.content if coding_context.design_doc else "", task=coding_context.task_doc.content if coding_context.task_doc else "", code=code_context, logs=logs, feedback=bug_feedback.content if bug_feedback else "", filename=self.i_context.filename, demo_filename=Path(self.i_context.filename).stem, summary_log=summary_doc.content if summary_doc else "", ) logger.info(f"Writing {coding_context.filename}..") async with EditorReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "code", "filename": coding_context.filename}, "meta") code = await self.write_code(prompt) if not coding_context.code_doc: # avoid root_path pydantic ValidationError if use WriteCode alone coding_context.code_doc = Document( filename=coding_context.filename, root_path=str(self.repo.src_relative_path) ) coding_context.code_doc.content = code await reporter.async_report(coding_context.code_doc, "document") return coding_context @staticmethod async def get_codes(task_doc: Document, exclude: str, project_repo: ProjectRepo, use_inc: bool = False) -> str: """ Get codes for generating the exclude file in various scenarios. Attributes: task_doc (Document): Document object of the task file. exclude (str): The file to be generated. Specifies the filename to be excluded from the code snippets. project_repo (ProjectRepo): ProjectRepo object of the project. use_inc (bool): Indicates whether the scenario involves incremental development. Defaults to False. Returns: str: Codes for generating the exclude file. """ if not task_doc: return "" if not task_doc.content: task_doc = project_repo.docs.task.get(filename=task_doc.filename) m = json.loads(task_doc.content) code_filenames = m.get(TASK_LIST.key, []) if not use_inc else m.get(REFINED_TASK_LIST.key, []) codes = [] src_file_repo = project_repo.srcs # Incremental development scenario if use_inc: for filename in src_file_repo.all_files: code_block_type = get_markdown_code_block_type(filename) # Exclude the current file from the all code snippets if filename == exclude: # If the file is in the old workspace, use the old code # Exclude unnecessary code to maintain a clean and focused main.py file, ensuring only relevant and # essential functionality is included for the project’s requirements if filename != "main.py": # Use old code doc = await src_file_repo.get(filename=filename) # If the file is in the src workspace, skip it else: continue codes.insert( 0, f"### The name of file to rewrite: `{filename}`\n```{code_block_type}\n{doc.content}```\n" ) logger.info(f"Prepare to rewrite `{filename}`") # The code snippets are generated from the src workspace else: doc = await src_file_repo.get(filename=filename) # If the file does not exist in the src workspace, skip it if not doc: continue codes.append(f"### File Name: `{filename}`\n```{code_block_type}\n{doc.content}```\n\n") # Normal scenario else: for filename in code_filenames: # Exclude the current file to get the code snippets for generating the current file if filename == exclude: continue doc = await src_file_repo.get(filename=filename) if not doc: continue code_block_type = get_markdown_code_block_type(filename) codes.append(f"### File Name: `{filename}`\n```{code_block_type}\n{doc.content}```\n\n") return "\n".join(codes)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_review.py
metagpt/actions/write_review.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : alexanderwu @File : write_review.py """ from typing import List from metagpt.actions import Action from metagpt.actions.action_node import ActionNode REVIEW = ActionNode( key="Review", expected_type=List[str], instruction="Act as an experienced Reviewer and review the given output. Ask a series of critical questions, " "concisely and clearly, to help the writer improve their work.", example=[ "This is a good PRD, but I think it can be improved by adding more details.", ], ) LGTM = ActionNode( key="LGTM", expected_type=str, instruction="LGTM/LBTM. If the output is good enough, give a LGTM (Looks Good To Me) to the writer, " "else LBTM (Looks Bad To Me).", example="LGTM", ) WRITE_REVIEW_NODE = ActionNode.from_children("WRITE_REVIEW_NODE", [REVIEW, LGTM]) class WriteReview(Action): """Write a review for the given context.""" name: str = "WriteReview" async def run(self, context): return await WRITE_REVIEW_NODE.fill(req=context, llm=self.llm, schema="json")
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_prd_an.py
metagpt/actions/write_prd_an.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/12/14 11:40 @Author : alexanderwu @File : write_prd_an.py """ from typing import List, Union from metagpt.actions.action_node import ActionNode LANGUAGE = ActionNode( key="Language", expected_type=str, instruction="Provide the language used in the project, typically matching the user's requirement language.", example="en_us", ) PROGRAMMING_LANGUAGE = ActionNode( key="Programming Language", expected_type=str, instruction="Mainstream programming language. If not specified in the requirements, use Vite, React, MUI, Tailwind CSS.", example="Vite, React, MUI, Tailwind CSS", ) ORIGINAL_REQUIREMENTS = ActionNode( key="Original Requirements", expected_type=str, instruction="Place the original user's requirements here.", example="Create a 2048 game", ) REFINED_REQUIREMENTS = ActionNode( key="Refined Requirements", expected_type=str, instruction="Place the New user's original requirements here.", example="Create a 2048 game with a new feature that ...", ) PROJECT_NAME = ActionNode( key="Project Name", expected_type=str, instruction='According to the content of "Original Requirements," name the project using snake case style , ' "like 'game_2048' or 'simple_crm.", example="game_2048", ) PRODUCT_GOALS = ActionNode( key="Product Goals", expected_type=List[str], instruction="Provide up to three clear, orthogonal product goals.", example=["Create an engaging user experience", "Improve accessibility, be responsive", "More beautiful UI"], ) REFINED_PRODUCT_GOALS = ActionNode( key="Refined Product Goals", expected_type=List[str], instruction="Update and expand the original product goals to reflect the evolving needs due to incremental " "development. Ensure that the refined goals align with the current project direction and contribute to its success.", example=[ "Enhance user engagement through new features", "Optimize performance for scalability", "Integrate innovative UI enhancements", ], ) USER_STORIES = ActionNode( key="User Stories", expected_type=List[str], instruction="Provide up to 3 to 5 scenario-based user stories.", example=[ "As a player, I want to be able to choose difficulty levels", "As a player, I want to see my score after each game", "As a player, I want to get restart button when I lose", "As a player, I want to see beautiful UI that make me feel good", "As a player, I want to play game via mobile phone", ], ) REFINED_USER_STORIES = ActionNode( key="Refined User Stories", expected_type=List[str], instruction="Update and expand the original scenario-based user stories to reflect the evolving needs due to " "incremental development. Ensure that the refined user stories capture incremental features and improvements. ", example=[ "As a player, I want to choose difficulty levels to challenge my skills", "As a player, I want a visually appealing score display after each game for a better gaming experience", "As a player, I want a convenient restart button displayed when I lose to quickly start a new game", "As a player, I want an enhanced and aesthetically pleasing UI to elevate the overall gaming experience", "As a player, I want the ability to play the game seamlessly on my mobile phone for on-the-go entertainment", ], ) COMPETITIVE_ANALYSIS = ActionNode( key="Competitive Analysis", expected_type=List[str], instruction="Provide 5 to 7 competitive products.", example=[ "2048 Game A: Simple interface, lacks responsive features", "play2048.co: Beautiful and responsive UI with my best score shown", "2048game.com: Responsive UI with my best score shown, but many ads", ], ) COMPETITIVE_QUADRANT_CHART = ActionNode( key="Competitive Quadrant Chart", expected_type=str, instruction="Use mermaid quadrantChart syntax. Distribute scores evenly between 0 and 1", example="""quadrantChart title "Reach and engagement of campaigns" x-axis "Low Reach" --> "High Reach" y-axis "Low Engagement" --> "High Engagement" quadrant-1 "We should expand" quadrant-2 "Need to promote" quadrant-3 "Re-evaluate" quadrant-4 "May be improved" "Campaign A": [0.3, 0.6] "Campaign B": [0.45, 0.23] "Campaign C": [0.57, 0.69] "Campaign D": [0.78, 0.34] "Campaign E": [0.40, 0.34] "Campaign F": [0.35, 0.78] "Our Target Product": [0.5, 0.6]""", ) REQUIREMENT_ANALYSIS = ActionNode( key="Requirement Analysis", expected_type=str, instruction="Provide a detailed analysis of the requirements.", example="", ) REFINED_REQUIREMENT_ANALYSIS = ActionNode( key="Refined Requirement Analysis", expected_type=Union[List[str], str], instruction="Review and refine the existing requirement analysis into a string list to align with the evolving needs of the project " "due to incremental development. Ensure the analysis comprehensively covers the new features and enhancements " "required for the refined project scope.", example=["Require add ...", "Require modify ..."], ) REQUIREMENT_POOL = ActionNode( key="Requirement Pool", expected_type=List[List[str]], instruction="List down the top-5 requirements with their priority (P0, P1, P2).", example=[["P0", "The main code ..."], ["P0", "The game algorithm ..."]], ) REFINED_REQUIREMENT_POOL = ActionNode( key="Refined Requirement Pool", expected_type=List[List[str]], instruction="List down the top 5 to 7 requirements with their priority (P0, P1, P2). " "Cover both legacy content and incremental content. Retain content unrelated to incremental development", example=[["P0", "The main code ..."], ["P0", "The game algorithm ..."]], ) UI_DESIGN_DRAFT = ActionNode( key="UI Design draft", expected_type=str, instruction="Provide a simple description of UI elements, functions, style, and layout.", example="Basic function description with a simple style and layout.", ) ANYTHING_UNCLEAR = ActionNode( key="Anything UNCLEAR", expected_type=str, instruction="Mention any aspects of the project that are unclear and try to clarify them.", example="Currently, all aspects of the project are clear.", ) ISSUE_TYPE = ActionNode( key="issue_type", expected_type=str, instruction="Answer BUG/REQUIREMENT. If it is a bugfix, answer BUG, otherwise answer Requirement", example="BUG", ) IS_RELATIVE = ActionNode( key="is_relative", expected_type=str, instruction="Answer YES/NO. If the requirement is related to the old PRD, answer YES, otherwise NO", example="YES", ) REASON = ActionNode( key="reason", expected_type=str, instruction="Explain the reasoning process from question to answer", example="..." ) NODES = [ LANGUAGE, PROGRAMMING_LANGUAGE, ORIGINAL_REQUIREMENTS, PROJECT_NAME, PRODUCT_GOALS, USER_STORIES, COMPETITIVE_ANALYSIS, COMPETITIVE_QUADRANT_CHART, REQUIREMENT_ANALYSIS, REQUIREMENT_POOL, UI_DESIGN_DRAFT, ANYTHING_UNCLEAR, ] REFINED_NODES = [ LANGUAGE, PROGRAMMING_LANGUAGE, REFINED_REQUIREMENTS, PROJECT_NAME, REFINED_PRODUCT_GOALS, REFINED_USER_STORIES, COMPETITIVE_ANALYSIS, COMPETITIVE_QUADRANT_CHART, REFINED_REQUIREMENT_ANALYSIS, REFINED_REQUIREMENT_POOL, UI_DESIGN_DRAFT, ANYTHING_UNCLEAR, ] WRITE_PRD_NODE = ActionNode.from_children("WritePRD", NODES) REFINED_PRD_NODE = ActionNode.from_children("RefinedPRD", REFINED_NODES) WP_ISSUE_TYPE_NODE = ActionNode.from_children("WP_ISSUE_TYPE", [ISSUE_TYPE, REASON]) WP_IS_RELATIVE_NODE = ActionNode.from_children("WP_IS_RELATIVE", [IS_RELATIVE, REASON])
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_code_plan_and_change_an.py
metagpt/actions/write_code_plan_and_change_an.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/12/26 @Author : mannaandpoem @File : write_code_plan_and_change_an.py """ from typing import List, Optional from pydantic import BaseModel, Field from metagpt.actions.action import Action from metagpt.actions.action_node import ActionNode from metagpt.logs import logger from metagpt.schema import CodePlanAndChangeContext, Document from metagpt.utils.common import get_markdown_code_block_type from metagpt.utils.project_repo import ProjectRepo DEVELOPMENT_PLAN = ActionNode( key="Development Plan", expected_type=List[str], instruction="Develop a comprehensive and step-by-step incremental development plan, providing the detail " "changes to be implemented at each step based on the order of 'Task List'", example=[ "Enhance the functionality of `calculator.py` by extending it to incorporate methods for subtraction, ...", "Update the existing codebase in main.py to incorporate new API endpoints for subtraction, ...", ], ) INCREMENTAL_CHANGE = ActionNode( key="Incremental Change", expected_type=List[str], instruction="Write Incremental Change by making a code draft that how to implement incremental development " "including detailed steps based on the context. Note: Track incremental changes using the marks `+` and `-` to " "indicate additions and deletions, and ensure compliance with the output format of `git diff`", example=[ '''```diff --- Old/calculator.py +++ New/calculator.py class Calculator: self.result = number1 + number2 return self.result - def sub(self, number1, number2) -> float: + def subtract(self, number1: float, number2: float) -> float: + """ + Subtracts the second number from the first and returns the result. + + Args: + number1 (float): The number to be subtracted from. + number2 (float): The number to subtract. + + Returns: + float: The difference of number1 and number2. + """ + self.result = number1 - number2 + return self.result + def multiply(self, number1: float, number2: float) -> float: - pass + """ + Multiplies two numbers and returns the result. + + Args: + number1 (float): The first number to multiply. + number2 (float): The second number to multiply. + + Returns: + float: The product of number1 and number2. + """ + self.result = number1 * number2 + return self.result + def divide(self, number1: float, number2: float) -> float: - pass + """ + ValueError: If the second number is zero. + """ + if number2 == 0: + raise ValueError('Cannot divide by zero') + self.result = number1 / number2 + return self.result + - def reset_result(self): + def clear(self): + if self.result != 0.0: + print("Result is not zero, clearing...") + else: + print("Result is already zero, no need to clear.") + self.result = 0.0 ```''', """```diff --- Old/main.py +++ New/main.py def add_numbers(): result = calculator.add_numbers(num1, num2) return jsonify({'result': result}), 200 -# TODO: Implement subtraction, multiplication, and division operations +@app.route('/subtract_numbers', methods=['POST']) +def subtract_numbers(): + data = request.get_json() + num1 = data.get('num1', 0) + num2 = data.get('num2', 0) + result = calculator.subtract_numbers(num1, num2) + return jsonify({'result': result}), 200 + +@app.route('/multiply_numbers', methods=['POST']) +def multiply_numbers(): + data = request.get_json() + num1 = data.get('num1', 0) + num2 = data.get('num2', 0) + try: + result = calculator.divide_numbers(num1, num2) + except ValueError as e: + return jsonify({'error': str(e)}), 400 + return jsonify({'result': result}), 200 + if __name__ == '__main__': app.run() ```""", ], ) CODE_PLAN_AND_CHANGE_CONTEXT = """ ## User New Requirements {requirement} ## Issue {issue} ## PRD {prd} ## Design {design} ## Task {task} ## Legacy Code {code} """ REFINED_TEMPLATE = """ NOTICE Role: You are a professional engineer; The main goal is to complete incremental development by combining legacy code and plan and Incremental Change, ensuring the integration of new features. # Context ## User New Requirements {user_requirement} ## Code Plan And Change {code_plan_and_change} ## Design {design} ## Task {task} ## Legacy Code {code} ## Debug logs ```text {logs} {summary_log} ``` ## Bug Feedback logs ```text {feedback} ``` # Format example ## Code: {demo_filename}.py ```python ## {demo_filename}.py ... ``` ## Code: {demo_filename}.js ```javascript // {demo_filename}.js ... ``` # Instruction: Based on the context, follow "Format example", write or rewrite code. ## Write/Rewrite Code: Only write one file {filename}, write or rewrite complete code using triple quotes based on the following attentions and context. 1. Only One file: do your best to implement THIS ONLY ONE FILE. 2. COMPLETE CODE: Your code will be part of the entire project, so please implement complete, reliable, reusable code snippets. 3. Set default value: If there is any setting, ALWAYS SET A DEFAULT VALUE, ALWAYS USE STRONG TYPE AND EXPLICIT VARIABLE. AVOID circular import. 4. Follow design: YOU MUST FOLLOW "Data structures and interfaces". DONT CHANGE ANY DESIGN. Do not use public member functions that do not exist in your design. 5. Follow Code Plan And Change: If there is any "Incremental Change" that is marked by the git diff format with '+' and '-' symbols, or Legacy Code files contain "{filename} to be rewritten", you must merge it into the code file according to the "Development Plan". 6. CAREFULLY CHECK THAT YOU DONT MISS ANY NECESSARY CLASS/FUNCTION IN THIS FILE. 7. Before using a external variable/module, make sure you import it first. 8. Write out EVERY CODE DETAIL, DON'T LEAVE TODO. 9. Attention: Retain details that are not related to incremental development but are important for maintaining the consistency and clarity of the old code. """ CODE_PLAN_AND_CHANGE = [DEVELOPMENT_PLAN, INCREMENTAL_CHANGE] WRITE_CODE_PLAN_AND_CHANGE_NODE = ActionNode.from_children("WriteCodePlanAndChange", CODE_PLAN_AND_CHANGE) class WriteCodePlanAndChange(Action): name: str = "WriteCodePlanAndChange" i_context: CodePlanAndChangeContext = Field(default_factory=CodePlanAndChangeContext) repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) async def run(self, *args, **kwargs): self.llm.system_prompt = "You are a professional software engineer, your primary responsibility is to " "meticulously craft comprehensive incremental development plan and deliver detailed incremental change" prd_doc = await Document.load(filename=self.i_context.prd_filename) design_doc = await Document.load(filename=self.i_context.design_filename) task_doc = await Document.load(filename=self.i_context.task_filename) context = CODE_PLAN_AND_CHANGE_CONTEXT.format( requirement=f"```text\n{self.i_context.requirement}\n```", issue=f"```text\n{self.i_context.issue}\n```", prd=prd_doc.content, design=design_doc.content, task=task_doc.content, code=await self.get_old_codes(), ) logger.info("Writing code plan and change..") return await WRITE_CODE_PLAN_AND_CHANGE_NODE.fill(req=context, llm=self.llm, schema="json") async def get_old_codes(self) -> str: old_codes = await self.repo.srcs.get_all() codes = [ f"### File Name: `{code.filename}`\n```{get_markdown_code_block_type(code.filename)}\n{code.content}```\n" for code in old_codes ] return "\n".join(codes)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/execute_task.py
metagpt/actions/execute_task.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/9/13 12:26 @Author : femto Zheng @File : execute_task.py """ from metagpt.actions import Action from metagpt.schema import Message class ExecuteTask(Action): name: str = "ExecuteTask" i_context: list[Message] = [] async def run(self, *args, **kwargs): pass
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/skill_action.py
metagpt/actions/skill_action.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/8/28 @Author : mashenquan @File : skill_action.py @Desc : Call learned skill """ from __future__ import annotations import ast import importlib import traceback from copy import deepcopy from typing import Dict, Optional from metagpt.actions import Action from metagpt.learn.skill_loader import Skill from metagpt.logs import logger from metagpt.schema import Message # TOTEST class ArgumentsParingAction(Action): skill: Skill ask: str rsp: Optional[Message] = None args: Optional[Dict] = None @property def prompt(self): prompt = f"{self.skill.name} function parameters description:\n" for k, v in self.skill.arguments.items(): prompt += f"parameter `{k}`: {v}\n" prompt += "\n---\n" prompt += "Examples:\n" for e in self.skill.examples: prompt += f"If want you to do `{e.ask}`, return `{e.answer}` brief and clear.\n" prompt += "\n---\n" prompt += ( f"\nRefer to the `{self.skill.name}` function description, and fill in the function parameters according " 'to the example "I want you to do xx" in the Examples section.' f"\nNow I want you to do `{self.ask}`, return function parameters in Examples format above, brief and " "clear." ) return prompt async def run(self, with_message=None, **kwargs) -> Message: prompt = self.prompt rsp = await self.llm.aask( msg=prompt, system_msgs=["You are a function parser.", "You can convert spoken words into function parameters."], stream=False, ) logger.debug(f"SKILL:{prompt}\n, RESULT:{rsp}") self.args = ArgumentsParingAction.parse_arguments(skill_name=self.skill.name, txt=rsp) self.rsp = Message(content=rsp, role="assistant", instruct_content=self.args, cause_by=self) return self.rsp @staticmethod def parse_arguments(skill_name, txt) -> dict: prefix = skill_name + "(" if prefix not in txt: logger.error(f"{skill_name} not in {txt}") return None if ")" not in txt: logger.error(f"')' not in {txt}") return None begin_ix = txt.find(prefix) end_ix = txt.rfind(")") args_txt = txt[begin_ix + len(prefix) : end_ix] logger.info(args_txt) fake_expression = f"dict({args_txt})" parsed_expression = ast.parse(fake_expression, mode="eval") args = {} for keyword in parsed_expression.body.keywords: key = keyword.arg value = ast.literal_eval(keyword.value) args[key] = value return args class SkillAction(Action): skill: Skill args: Dict rsp: Optional[Message] = None async def run(self, with_message=None, **kwargs) -> Message: """Run action""" options = deepcopy(kwargs) if self.args: for k in self.args.keys(): if k in options: options.pop(k) try: rsp = await self.find_and_call_function(self.skill.name, args=self.args, **options) self.rsp = Message(content=rsp, role="assistant", cause_by=self) except Exception as e: logger.exception(f"{e}, traceback:{traceback.format_exc()}") self.rsp = Message(content=f"Error: {e}", role="assistant", cause_by=self) return self.rsp @staticmethod async def find_and_call_function(function_name, args, **kwargs) -> str: try: module = importlib.import_module("metagpt.learn") function = getattr(module, function_name) # Invoke function and return result result = await function(**args, **kwargs) return result except (ModuleNotFoundError, AttributeError): logger.error(f"{function_name} not found") raise ValueError(f"{function_name} not found")
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/action_output.py
metagpt/actions/action_output.py
#!/usr/bin/env python # coding: utf-8 """ @Time : 2023/7/11 10:03 @Author : chengmaoyu @File : action_output """ from pydantic import BaseModel class ActionOutput: content: str instruct_content: BaseModel def __init__(self, content: str, instruct_content: BaseModel): self.content = content self.instruct_content = instruct_content
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/project_management.py
metagpt/actions/project_management.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 19:12 @Author : alexanderwu @File : project_management.py @Modified By: mashenquan, 2023/11/27. 1. Divide the context into three components: legacy code, unit test code, and console log. 2. Move the document storage operations related to WritePRD from the save operation of WriteDesign. 3. According to the design in Section 2.2.3.5.4 of RFC 135, add incremental iteration functionality. @Modified By: mashenquan, 2024/5/31. Implement Chapter 3 of RFC 236. """ import json from pathlib import Path from typing import List, Optional, Union from pydantic import BaseModel, Field from metagpt.actions.action import Action from metagpt.actions.project_management_an import PM_NODE, REFINED_PM_NODE from metagpt.const import PACKAGE_REQUIREMENTS_FILENAME from metagpt.logs import logger from metagpt.schema import AIMessage, Document, Documents, Message from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import ( aread, awrite, rectify_pathname, save_json_to_markdown, to_markdown_code_block, ) from metagpt.utils.project_repo import ProjectRepo from metagpt.utils.report import DocsReporter NEW_REQ_TEMPLATE = """ ### Legacy Content {old_task} ### New Requirements {context} """ @register_tool(include_functions=["run"]) class WriteTasks(Action): name: str = "CreateTasks" i_context: Optional[str] = None repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) async def run( self, with_messages: List[Message] = None, *, user_requirement: str = "", design_filename: str = "", output_pathname: str = "", **kwargs, ) -> Union[AIMessage, str]: """ Write a project schedule given a project system design file. Args: user_requirement (str, optional): A string specifying the user's requirements. Defaults to an empty string. design_filename (str): The output file path of the document. Defaults to an empty string. output_pathname (str, optional): The output path name of file that the project schedule should be saved to. **kwargs: Additional keyword arguments. Returns: str: Path to the generated project schedule. Example: # Write a project schedule with a given system design. >>> design_filename = "/absolute/path/to/snake_game/docs/system_design.json" >>> output_pathname = "/absolute/path/to/snake_game/docs/project_schedule.json" >>> user_requirement = "Write project schedule for a snake game following these requirements:..." >>> action = WriteTasks() >>> result = await action.run(user_requirement=user_requirement, design_filename=design_filename, output_pathname=output_pathname) >>> print(result) The project schedule is at /absolute/path/to/snake_game/docs/project_schedule.json # Write a project schedule with a user requirement. >>> user_requirement = "Write project schedule for a snake game following these requirements: ..." >>> output_pathname = "/absolute/path/to/snake_game/docs/project_schedule.json" >>> action = WriteTasks() >>> result = await action.run(user_requirement=user_requirement, output_pathname=output_pathname) >>> print(result) The project schedule is at /absolute/path/to/snake_game/docs/project_schedule.json """ if not with_messages: return await self._execute_api( user_requirement=user_requirement, design_filename=design_filename, output_pathname=output_pathname ) self.input_args = with_messages[-1].instruct_content self.repo = ProjectRepo(self.input_args.project_path) changed_system_designs = self.input_args.changed_system_design_filenames changed_tasks = [str(self.repo.docs.task.workdir / i) for i in list(self.repo.docs.task.changed_files.keys())] change_files = Documents() # Rewrite the system designs that have undergone changes based on the git head diff under # `docs/system_designs/`. for filename in changed_system_designs: task_doc = await self._update_tasks(filename=filename) change_files.docs[str(self.repo.docs.task.workdir / task_doc.filename)] = task_doc # Rewrite the task files that have undergone changes based on the git head diff under `docs/tasks/`. for filename in changed_tasks: if filename in change_files.docs: continue task_doc = await self._update_tasks(filename=filename) change_files.docs[filename] = task_doc if not change_files.docs: logger.info("Nothing has changed.") # Wait until all files under `docs/tasks/` are processed before sending the publish_message, leaving room for # global optimization in subsequent steps. kvs = self.input_args.model_dump() kvs["changed_task_filenames"] = [ str(self.repo.docs.task.workdir / i) for i in list(self.repo.docs.task.changed_files.keys()) ] kvs["python_package_dependency_filename"] = str(self.repo.workdir / PACKAGE_REQUIREMENTS_FILENAME) return AIMessage( content="WBS is completed. " + "\n".join( [PACKAGE_REQUIREMENTS_FILENAME] + list(self.repo.docs.task.changed_files.keys()) + list(self.repo.resources.api_spec_and_task.changed_files.keys()) ), instruct_content=AIMessage.create_instruct_value(kvs=kvs, class_name="WriteTaskOutput"), cause_by=self, ) async def _update_tasks(self, filename): root_relative_path = Path(filename).relative_to(self.repo.workdir) system_design_doc = await Document.load(filename=filename, project_path=self.repo.workdir) task_doc = await self.repo.docs.task.get(root_relative_path.name) async with DocsReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "task"}, "meta") if task_doc: task_doc = await self._merge(system_design_doc=system_design_doc, task_doc=task_doc) await self.repo.docs.task.save_doc(doc=task_doc, dependencies={system_design_doc.root_relative_path}) else: rsp = await self._run_new_tasks(context=system_design_doc.content) task_doc = await self.repo.docs.task.save( filename=system_design_doc.filename, content=rsp.instruct_content.model_dump_json(), dependencies={system_design_doc.root_relative_path}, ) await self._update_requirements(task_doc) md = await self.repo.resources.api_spec_and_task.save_pdf(doc=task_doc) await reporter.async_report(self.repo.workdir / md.root_relative_path, "path") return task_doc async def _run_new_tasks(self, context: str): node = await PM_NODE.fill(req=context, llm=self.llm, schema=self.prompt_schema) return node async def _merge(self, system_design_doc, task_doc) -> Document: context = NEW_REQ_TEMPLATE.format(context=system_design_doc.content, old_task=task_doc.content) node = await REFINED_PM_NODE.fill(req=context, llm=self.llm, schema=self.prompt_schema) task_doc.content = node.instruct_content.model_dump_json() return task_doc async def _update_requirements(self, doc): m = json.loads(doc.content) packages = set(m.get("Required packages", set())) requirement_doc = await self.repo.get(filename=PACKAGE_REQUIREMENTS_FILENAME) if not requirement_doc: requirement_doc = Document(filename=PACKAGE_REQUIREMENTS_FILENAME, root_path=".", content="") lines = requirement_doc.content.splitlines() for pkg in lines: if pkg == "": continue packages.add(pkg) await self.repo.save(filename=PACKAGE_REQUIREMENTS_FILENAME, content="\n".join(packages)) async def _execute_api( self, user_requirement: str = "", design_filename: str = "", output_pathname: str = "" ) -> str: context = to_markdown_code_block(user_requirement) if design_filename: design_filename = rectify_pathname(path=design_filename, default_filename="system_design.md") content = await aread(filename=design_filename) context += to_markdown_code_block(content) async with DocsReporter(enable_llm_stream=True) as reporter: await reporter.async_report({"type": "task"}, "meta") node = await self._run_new_tasks(context) file_content = node.instruct_content.model_dump_json() if not output_pathname: output_pathname = Path(output_pathname) / "docs" / "project_schedule.json" elif not Path(output_pathname).is_absolute(): output_pathname = self.config.workspace.path / output_pathname output_pathname = rectify_pathname(path=output_pathname, default_filename="project_schedule.json") await awrite(filename=output_pathname, data=file_content) md_output_filename = output_pathname.with_suffix(".md") await save_json_to_markdown(content=file_content, output_filename=md_output_filename) await reporter.async_report(md_output_filename, "path") return f'Project Schedule filename: "{str(output_pathname)}"'
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/talk_action.py
metagpt/actions/talk_action.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/8/28 @Author : mashenquan @File : talk_action.py @Desc : Act as it’s a talk """ from typing import Optional from metagpt.actions import Action from metagpt.logs import logger from metagpt.schema import Message class TalkAction(Action): i_context: str history_summary: str = "" knowledge: str = "" rsp: Optional[Message] = None @property def agent_description(self): return self.context.kwargs.agent_description @property def language(self): return self.context.kwargs.language or self.config.language @property def prompt(self): prompt = "" if self.agent_description: prompt = ( f"You are {self.agent_description}. Your responses should align with the role-play agreement, " f"maintaining the character's persona and habits. When faced with unrelated questions, playfully " f"decline to answer without revealing your AI nature to preserve the character's image.\n\n" ) prompt += f"Knowledge:\n{self.knowledge}\n\n" if self.knowledge else "" prompt += f"{self.history_summary}\n\n" prompt += ( "If the information is insufficient, you can search in the historical conversation or knowledge above.\n" ) language = self.language prompt += ( f"Answer the following questions strictly in {language}, and the answers must follow the Markdown format.\n " f"{self.i_context}" ) logger.debug(f"PROMPT: {prompt}") return prompt @property def prompt_gpt4(self): kvs = { "{role}": self.agent_description or "", "{history}": self.history_summary or "", "{knowledge}": self.knowledge or "", "{language}": self.language, "{ask}": self.i_context, } prompt = TalkActionPrompt.FORMATION_LOOSE for k, v in kvs.items(): prompt = prompt.replace(k, v) logger.info(f"PROMPT: {prompt}") return prompt # async def run_old(self, *args, **kwargs) -> ActionOutput: # prompt = self.prompt # rsp = await self.llm.aask(msg=prompt, system_msgs=[]) # logger.debug(f"PROMPT:{prompt}\nRESULT:{rsp}\n") # self._rsp = ActionOutput(content=rsp) # return self._rsp @property def aask_args(self): language = self.language system_msgs = [ f"You are {self.agent_description}.", "Your responses should align with the role-play agreement, " "maintaining the character's persona and habits. When faced with unrelated questions, playfully " "decline to answer without revealing your AI nature to preserve the character's image.", "If the information is insufficient, you can search in the context or knowledge.", f"Answer the following questions strictly in {language}, and the answers must follow the Markdown format.", ] format_msgs = [] if self.knowledge: format_msgs.append({"role": "assistant", "content": self.knowledge}) if self.history_summary: format_msgs.append({"role": "assistant", "content": self.history_summary}) return self.i_context, format_msgs, system_msgs async def run(self, with_message=None, **kwargs) -> Message: msg, format_msgs, system_msgs = self.aask_args rsp = await self.llm.aask(msg=msg, format_msgs=format_msgs, system_msgs=system_msgs, stream=False) self.rsp = Message(content=rsp, role="assistant", cause_by=self) return self.rsp class TalkActionPrompt: FORMATION = """Formation: "Capacity and role" defines the role you are currently playing; "[HISTORY_BEGIN]" and "[HISTORY_END]" tags enclose the historical conversation; "[KNOWLEDGE_BEGIN]" and "[KNOWLEDGE_END]" tags enclose the knowledge may help for your responses; "Statement" defines the work detail you need to complete at this stage; "[ASK_BEGIN]" and [ASK_END] tags enclose the questions; "Constraint" defines the conditions that your responses must comply with. "Personality" defines your language style。 "Insight" provides a deeper understanding of the characters' inner traits. "Initial" defines the initial setup of a character. Capacity and role: {role} Statement: Your responses should align with the role-play agreement, maintaining the character's persona and habits. When faced with unrelated questions, playfully decline to answer without revealing your AI nature to preserve the character's image. [HISTORY_BEGIN] {history} [HISTORY_END] [KNOWLEDGE_BEGIN] {knowledge} [KNOWLEDGE_END] Statement: If the information is insufficient, you can search in the historical conversation or knowledge. Statement: Unless you are a language professional, answer the following questions strictly in {language} , and the answers must follow the Markdown format. Strictly excluding any tag likes "[HISTORY_BEGIN]" , "[HISTORY_END]", "[KNOWLEDGE_BEGIN]", "[KNOWLEDGE_END]" in responses. {ask} """ FORMATION_LOOSE = """Formation: "Capacity and role" defines the role you are currently playing; "[HISTORY_BEGIN]" and "[HISTORY_END]" tags enclose the historical conversation; "[KNOWLEDGE_BEGIN]" and "[KNOWLEDGE_END]" tags enclose the knowledge may help for your responses; "Statement" defines the work detail you need to complete at this stage; "Constraint" defines the conditions that your responses must comply with. "Personality" defines your language style。 "Insight" provides a deeper understanding of the characters' inner traits. "Initial" defines the initial setup of a character. Capacity and role: {role} Statement: Your responses should maintaining the character's persona and habits. When faced with unrelated questions , playfully decline to answer without revealing your AI nature to preserve the character's image. [HISTORY_BEGIN] {history} [HISTORY_END] [KNOWLEDGE_BEGIN] {knowledge} [KNOWLEDGE_END] Statement: If the information is insufficient, you can search in the historical conversation or knowledge. Statement: Unless you are a language professional, answer the following questions strictly in {language} , and the answers must follow the Markdown format. Strictly excluding any tag likes "[HISTORY_BEGIN]" , "[HISTORY_END]", "[KNOWLEDGE_BEGIN]", "[KNOWLEDGE_END]" in responses. {ask} """
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/add_requirement.py
metagpt/actions/add_requirement.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/20 17:46 @Author : alexanderwu @File : add_requirement.py """ from metagpt.actions import Action class UserRequirement(Action): """User Requirement without any implementation details"""
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/search_enhanced_qa.py
metagpt/actions/search_enhanced_qa.py
"""Enhancing question-answering capabilities through search engine augmentation.""" from __future__ import annotations import json from pydantic import Field, PrivateAttr, model_validator from metagpt.actions import Action from metagpt.actions.research import CollectLinks, WebBrowseAndSummarize from metagpt.logs import logger from metagpt.tools.tool_registry import register_tool from metagpt.tools.web_browser_engine import WebBrowserEngine from metagpt.utils.common import CodeParser from metagpt.utils.parse_html import WebPage from metagpt.utils.report import ThoughtReporter REWRITE_QUERY_PROMPT = """ Role: You are a highly efficient assistant that provide a better search query for web search engine to answer the given question. I will provide you with a question. Your task is to provide a better search query for web search engine. ## Context ### Question {q} ## Format Example ```json {{ "query": "the better search query for web search engine.", }} ``` ## Instructions - Understand the question given by the user. - Provide a better search query for web search engine to answer the given question, your answer must be written in the same language as the question. - When rewriting, if you are unsure of the specific time, do not include the time. ## Constraint Format: Just print the result in json format like **Format Example**. ## Action Follow **Instructions**, generate output and make sure it follows the **Constraint**. """ SEARCH_ENHANCED_QA_SYSTEM_PROMPT = """ You are a large language AI assistant built by MGX. You are given a user question, and please write clean, concise and accurate answer to the question. You will be given a set of related contexts to the question, each starting with a reference number like [[citation:x]], where x is a number. Please use the context. Your answer must be correct, accurate and written by an expert using an unbiased and professional tone. Please limit to 1024 tokens. Do not give any information that is not related to the question, and do not repeat. Say "information is missing on" followed by the related topic, if the given context do not provide sufficient information. Do not include [citation:x] in your anwser, where x is a number. Other than code and specific names and citations, your answer must be written in the same language as the question. Here are the set of contexts: {context} Remember, don't blindly repeat the contexts verbatim. And here is the user question: """ @register_tool(include_functions=["run"]) class SearchEnhancedQA(Action): """Question answering and info searching through search engine.""" name: str = "SearchEnhancedQA" desc: str = "Integrating search engine results to anwser the question." collect_links_action: CollectLinks = Field( default_factory=CollectLinks, description="Action to collect relevant links from a search engine." ) web_browse_and_summarize_action: WebBrowseAndSummarize = Field( default=None, description="Action to explore the web and provide summaries of articles and webpages.", ) per_page_timeout: float = Field( default=20, description="The maximum time for fetching a single page is in seconds. Defaults to 20s." ) java_script_enabled: bool = Field( default=False, description="Whether or not to enable JavaScript in the web browser context. Defaults to False." ) user_agent: str = Field( default="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.81", description="Specific user agent to use in browser.", ) extra_http_headers: dict = Field( default={"sec-ch-ua": 'Chromium";v="125", "Not.A/Brand";v="24'}, description="An object containing additional HTTP headers to be sent with every request.", ) max_chars_per_webpage_summary: int = Field( default=4000, description="Maximum summary length for each web page content." ) max_search_results: int = Field( default=10, description="Maximum number of search results (links) to collect using the collect_links_action. This controls the number of potential sources for answering the question.", ) _reporter: ThoughtReporter = PrivateAttr(ThoughtReporter()) @model_validator(mode="after") def initialize(self): if self.web_browse_and_summarize_action is None: web_browser_engine = WebBrowserEngine.from_browser_config( self.config.browser, proxy=self.config.proxy, java_script_enabled=self.java_script_enabled, extra_http_headers=self.extra_http_headers, user_agent=self.user_agent, ) self.web_browse_and_summarize_action = WebBrowseAndSummarize(web_browser_engine=web_browser_engine) return self async def run(self, query: str, rewrite_query: bool = True) -> str: """Answer a query by leveraging web search results. Args: query (str): The original user query. rewrite_query (bool): Whether to rewrite the query for better web search results. Defaults to True. Returns: str: A detailed answer based on web search results. Raises: ValueError: If the query is invalid. """ async with self._reporter: await self._reporter.async_report({"type": "search", "stage": "init"}) self._validate_query(query) processed_query = await self._process_query(query, rewrite_query) context = await self._build_context(processed_query) return await self._generate_answer(processed_query, context) def _validate_query(self, query: str) -> None: """Validate the input query. Args: query (str): The query to validate. Raises: ValueError: If the query is invalid. """ if not query.strip(): raise ValueError("Query cannot be empty or contain only whitespace.") async def _process_query(self, query: str, should_rewrite: bool) -> str: """Process the query, optionally rewriting it.""" if should_rewrite: return await self._rewrite_query(query) return query async def _rewrite_query(self, query: str) -> str: """Write a better search query for web search engine. If the rewrite process fails, the original query is returned. Args: query (str): The original search query. Returns: str: The rewritten query if successful, otherwise the original query. """ prompt = REWRITE_QUERY_PROMPT.format(q=query) try: resp = await self._aask(prompt) rewritten_query = self._extract_rewritten_query(resp) logger.info(f"Query rewritten: '{query}' -> '{rewritten_query}'") return rewritten_query except Exception as e: logger.warning(f"Query rewrite failed. Returning original query. Error: {e}") return query def _extract_rewritten_query(self, response: str) -> str: """Extract the rewritten query from the LLM's JSON response.""" resp_json = json.loads(CodeParser.parse_code(response, lang="json")) return resp_json["query"] async def _build_context(self, query: str) -> str: """Construct a context string from web search citations. Args: query (str): The search query. Returns: str: Formatted context with numbered citations. """ citations = await self._search_citations(query) context = "\n\n".join([f"[[citation:{i+1}]] {c}" for i, c in enumerate(citations)]) return context async def _search_citations(self, query: str) -> list[str]: """Perform web search and summarize relevant content. Args: query (str): The search query. Returns: list[str]: Summaries of relevant web content. """ relevant_urls = await self._collect_relevant_links(query) await self._reporter.async_report({"type": "search", "stage": "searching", "urls": relevant_urls}) if not relevant_urls: logger.warning(f"No relevant URLs found for query: {query}") return [] logger.info(f"The Relevant links are: {relevant_urls}") web_summaries = await self._summarize_web_content(relevant_urls) if not web_summaries: logger.warning(f"No summaries generated for query: {query}") return [] citations = list(web_summaries.values()) return citations async def _collect_relevant_links(self, query: str) -> list[str]: """Search and rank URLs relevant to the query. Args: query (str): The search query. Returns: list[str]: Ranked list of relevant URLs. """ return await self.collect_links_action._search_and_rank_urls( topic=query, query=query, max_num_results=self.max_search_results ) async def _summarize_web_content(self, urls: list[str]) -> dict[str, str]: """Fetch and summarize content from given URLs. Args: urls (list[str]): List of URLs to summarize. Returns: dict[str, str]: Mapping of URLs to their summaries. """ contents = await self._fetch_web_contents(urls) summaries = {} await self._reporter.async_report( {"type": "search", "stage": "browsing", "pages": [i.model_dump() for i in contents]} ) for content in contents: url = content.url inner_text = content.inner_text.replace("\n", "") if self.web_browse_and_summarize_action._is_content_invalid(inner_text): logger.warning(f"Invalid content detected for URL {url}: {inner_text[:10]}...") continue summary = inner_text[: self.max_chars_per_webpage_summary] summaries[url] = summary return summaries async def _fetch_web_contents(self, urls: list[str]) -> list[WebPage]: return await self.web_browse_and_summarize_action._fetch_web_contents( *urls, per_page_timeout=self.per_page_timeout ) async def _generate_answer(self, query: str, context: str) -> str: """Generate an answer using the query and context. Args: query (str): The user's question. context (str): Relevant information from web search. Returns: str: Generated answer based on the context. """ system_prompt = SEARCH_ENHANCED_QA_SYSTEM_PROMPT.format(context=context) async with ThoughtReporter(uuid=self._reporter.uuid, enable_llm_stream=True) as reporter: await reporter.async_report({"type": "search", "stage": "answer"}) rsp = await self._aask(query, [system_prompt]) return rsp
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/run_code.py
metagpt/actions/run_code.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:46 @Author : alexanderwu @File : run_code.py @Modified By: mashenquan, 2023/11/27. 1. Mark the location of Console logs in the PROMPT_TEMPLATE with markdown code-block formatting to enhance the understanding for the LLM. 2. Fix bug: Add the "install dependency" operation. 3. Encapsulate the input of RunCode into RunCodeContext and encapsulate the output of RunCode into RunCodeResult to standardize and unify parameter passing between WriteCode, RunCode, and DebugError. 4. According to section 2.2.3.5.7 of RFC 135, change the method of transferring file content (code files, unit test files, log files) from using the message to using the file name. 5. Merged the `Config` class of send18:dev branch to take over the set/get operations of the Environment class. """ import subprocess from pathlib import Path from typing import Tuple from pydantic import Field from metagpt.actions.action import Action from metagpt.logs import logger from metagpt.schema import RunCodeContext, RunCodeResult from metagpt.utils.exceptions import handle_exception PROMPT_TEMPLATE = """ Role: You are a senior development and qa engineer, your role is summarize the code running result. If the running result does not include an error, you should explicitly approve the result. On the other hand, if the running result indicates some error, you should point out which part, the development code or the test code, produces the error, and give specific instructions on fixing the errors. Here is the code info: {context} Now you should begin your analysis --- ## instruction: Please summarize the cause of the errors and give correction instruction ## File To Rewrite: Determine the ONE file to rewrite in order to fix the error, for example, xyz.py, or test_xyz.py ## Status: Determine if all of the code works fine, if so write PASS, else FAIL, WRITE ONLY ONE WORD, PASS OR FAIL, IN THIS SECTION ## Send To: Please write NoOne if there are no errors, Engineer if the errors are due to problematic development codes, else QaEngineer, WRITE ONLY ONE WORD, NoOne OR Engineer OR QaEngineer, IN THIS SECTION. --- You should fill in necessary instruction, status, send to, and finally return all content between the --- segment line. """ TEMPLATE_CONTEXT = """ ## Development Code File Name {code_file_name} ## Development Code ```python {code} ``` ## Test File Name {test_file_name} ## Test Code ```python {test_code} ``` ## Running Command {command} ## Running Output standard output: ```text {outs} ``` standard errors: ```text {errs} ``` """ class RunCode(Action): name: str = "RunCode" i_context: RunCodeContext = Field(default_factory=RunCodeContext) @classmethod async def run_text(cls, code) -> Tuple[str, str]: try: # We will document_store the result in this dictionary namespace = {} exec(code, namespace) except Exception as e: return "", str(e) return namespace.get("result", ""), "" async def run_script(self, working_directory, additional_python_paths=[], command=[]) -> Tuple[str, str]: working_directory = str(working_directory) additional_python_paths = [str(path) for path in additional_python_paths] # Copy the current environment variables env = self.context.new_environ() # Modify the PYTHONPATH environment variable additional_python_paths = [working_directory] + additional_python_paths additional_python_paths = ":".join(additional_python_paths) env["PYTHONPATH"] = additional_python_paths + ":" + env.get("PYTHONPATH", "") RunCode._install_dependencies(working_directory=working_directory, env=env) # Start the subprocess process = subprocess.Popen( command, cwd=working_directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) logger.info(" ".join(command)) try: # Wait for the process to complete, with a timeout stdout, stderr = process.communicate(timeout=10) except subprocess.TimeoutExpired: logger.info("The command did not complete within the given timeout.") process.kill() # Kill the process if it times out stdout, stderr = process.communicate() return stdout.decode("utf-8"), stderr.decode("utf-8") async def run(self, *args, **kwargs) -> RunCodeResult: logger.info(f"Running {' '.join(self.i_context.command)}") if self.i_context.mode == "script": outs, errs = await self.run_script( command=self.i_context.command, working_directory=self.i_context.working_directory, additional_python_paths=self.i_context.additional_python_paths, ) elif self.i_context.mode == "text": outs, errs = await self.run_text(code=self.i_context.code) logger.info(f"{outs=}") logger.info(f"{errs=}") context = TEMPLATE_CONTEXT.format( code=self.i_context.code, code_file_name=self.i_context.code_filename, test_code=self.i_context.test_code, test_file_name=self.i_context.test_filename, command=" ".join(self.i_context.command), outs=outs[:500], # outs might be long but they are not important, truncate them to avoid token overflow errs=errs[:10000], # truncate errors to avoid token overflow ) prompt = PROMPT_TEMPLATE.format(context=context) rsp = await self._aask(prompt) return RunCodeResult(summary=rsp, stdout=outs, stderr=errs) @staticmethod @handle_exception(exception_type=subprocess.CalledProcessError) def _install_via_subprocess(cmd, check, cwd, env): return subprocess.run(cmd, check=check, cwd=cwd, env=env) @staticmethod def _install_requirements(working_directory, env): file_path = Path(working_directory) / "requirements.txt" if not file_path.exists(): return if file_path.stat().st_size == 0: return install_command = ["python", "-m", "pip", "install", "-r", "requirements.txt"] logger.info(" ".join(install_command)) RunCode._install_via_subprocess(install_command, check=True, cwd=working_directory, env=env) @staticmethod def _install_pytest(working_directory, env): install_pytest_command = ["python", "-m", "pip", "install", "pytest"] logger.info(" ".join(install_pytest_command)) RunCode._install_via_subprocess(install_pytest_command, check=True, cwd=working_directory, env=env) @staticmethod def _install_dependencies(working_directory, env): RunCode._install_requirements(working_directory, env) RunCode._install_pytest(working_directory, env)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/design_api_an.py
metagpt/actions/design_api_an.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/12/12 22:24 @Author : alexanderwu @File : design_api_an.py """ from typing import List, Optional from metagpt.actions.action_node import ActionNode from metagpt.utils.mermaid import MMC1, MMC2 IMPLEMENTATION_APPROACH = ActionNode( key="Implementation approach", expected_type=str, instruction="Analyze the difficult points of the requirements, select the appropriate open-source framework.", example="We will ...", ) REFINED_IMPLEMENTATION_APPROACH = ActionNode( key="Refined Implementation Approach", expected_type=str, instruction="Update and extend the original implementation approach to reflect the evolving challenges and " "requirements due to incremental development. Outline the steps involved in the implementation process with the " "detailed strategies.", example="We will refine ...", ) PROJECT_NAME = ActionNode( key="Project name", expected_type=str, instruction="The project name with underline", example="game_2048" ) FILE_LIST = ActionNode( key="File list", expected_type=List[str], instruction="Only need relative paths. Succinctly designate the correct entry file for your project based on the programming language: use main.js for JavaScript, main.py for Python, and so on for other languages.", example=["a.js", "b.py", "c.css", "d.html"], ) REFINED_FILE_LIST = ActionNode( key="Refined File list", expected_type=List[str], instruction="Update and expand the original file list including only relative paths. Up to 2 files can be added." "Ensure that the refined file list reflects the evolving structure of the project.", example=["main.py", "game.py", "new_feature.py"], ) # optional,because low success reproduction of class diagram in non py project. DATA_STRUCTURES_AND_INTERFACES = ActionNode( key="Data structures and interfaces", expected_type=Optional[str], instruction="Use mermaid classDiagram code syntax, including classes, method(__init__ etc.) and functions with type" " annotations, CLEARLY MARK the RELATIONSHIPS between classes, and comply with PEP8 standards. " "The data structures SHOULD BE VERY DETAILED and the API should be comprehensive with a complete design.", example=MMC1, ) REFINED_DATA_STRUCTURES_AND_INTERFACES = ActionNode( key="Refined Data structures and interfaces", expected_type=str, instruction="Update and extend the existing mermaid classDiagram code syntax to incorporate new classes, " "methods (including __init__), and functions with precise type annotations. Delineate additional " "relationships between classes, ensuring clarity and adherence to PEP8 standards." "Retain content that is not related to incremental development but important for consistency and clarity.", example=MMC1, ) PROGRAM_CALL_FLOW = ActionNode( key="Program call flow", expected_type=Optional[str], instruction="Use sequenceDiagram code syntax, COMPLETE and VERY DETAILED, using CLASSES AND API DEFINED ABOVE " "accurately, covering the CRUD AND INIT of each object, SYNTAX MUST BE CORRECT.", example=MMC2, ) REFINED_PROGRAM_CALL_FLOW = ActionNode( key="Refined Program call flow", expected_type=str, instruction="Extend the existing sequenceDiagram code syntax with detailed information, accurately covering the" "CRUD and initialization of each object. Ensure correct syntax usage and reflect the incremental changes introduced" "in the classes and API defined above. " "Retain content that is not related to incremental development but important for consistency and clarity.", example=MMC2, ) ANYTHING_UNCLEAR = ActionNode( key="Anything UNCLEAR", expected_type=str, instruction="Mention unclear project aspects, then try to clarify it.", example="Clarification needed on third-party API integration, ...", ) NODES = [ IMPLEMENTATION_APPROACH, # PROJECT_NAME, FILE_LIST, DATA_STRUCTURES_AND_INTERFACES, PROGRAM_CALL_FLOW, ANYTHING_UNCLEAR, ] REFINED_NODES = [ REFINED_IMPLEMENTATION_APPROACH, REFINED_FILE_LIST, REFINED_DATA_STRUCTURES_AND_INTERFACES, REFINED_PROGRAM_CALL_FLOW, ANYTHING_UNCLEAR, ] DESIGN_API_NODE = ActionNode.from_children("DesignAPI", NODES) REFINED_DESIGN_NODE = ActionNode.from_children("RefinedDesignAPI", REFINED_NODES)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/action.py
metagpt/actions/action.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 14:43 @Author : alexanderwu @File : action.py """ from __future__ import annotations from typing import Any, Optional, Union from pydantic import BaseModel, ConfigDict, Field, model_validator from metagpt.actions.action_node import ActionNode from metagpt.configs.models_config import ModelsConfig from metagpt.context_mixin import ContextMixin from metagpt.provider.llm_provider_registry import create_llm_instance from metagpt.schema import ( CodePlanAndChangeContext, CodeSummarizeContext, CodingContext, RunCodeContext, SerializationMixin, TestingContext, ) class Action(SerializationMixin, ContextMixin, BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True) name: str = "" i_context: Union[ dict, CodingContext, CodeSummarizeContext, TestingContext, RunCodeContext, CodePlanAndChangeContext, str, None ] = "" prefix: str = "" # aask*时会加上prefix,作为system_message desc: str = "" # for skill manager node: ActionNode = Field(default=None, exclude=True) # The model name or API type of LLM of the `models` in the `config2.yaml`; # Using `None` to use the `llm` configuration in the `config2.yaml`. llm_name_or_type: Optional[str] = None @model_validator(mode="after") @classmethod def _update_private_llm(cls, data: Any) -> Any: config = ModelsConfig.default().get(data.llm_name_or_type) if config: llm = create_llm_instance(config) llm.cost_manager = data.llm.cost_manager data.llm = llm return data @property def prompt_schema(self): return self.config.prompt_schema @property def project_name(self): return self.config.project_name @project_name.setter def project_name(self, value): self.config.project_name = value @property def project_path(self): return self.config.project_path @model_validator(mode="before") @classmethod def set_name_if_empty(cls, values): if "name" not in values or not values["name"]: values["name"] = cls.__name__ return values @model_validator(mode="before") @classmethod def _init_with_instruction(cls, values): if "instruction" in values: name = values["name"] i = values.pop("instruction") values["node"] = ActionNode(key=name, expected_type=str, instruction=i, example="", schema="raw") return values def set_prefix(self, prefix): """Set prefix for later usage""" self.prefix = prefix self.llm.system_prompt = prefix if self.node: self.node.llm = self.llm return self def __str__(self): return self.__class__.__name__ def __repr__(self): return self.__str__() async def _aask(self, prompt: str, system_msgs: Optional[list[str]] = None) -> str: """Append default prefix""" return await self.llm.aask(prompt, system_msgs) async def _run_action_node(self, *args, **kwargs): """Run action node""" msgs = args[0] context = "## History Messages\n" context += "\n".join([f"{idx}: {i}" for idx, i in enumerate(reversed(msgs))]) return await self.node.fill(req=context, llm=self.llm) async def run(self, *args, **kwargs): """Run action""" if self.node: return await self._run_action_node(*args, **kwargs) raise NotImplementedError("The run method should be implemented in a subclass.") def override_context(self): """Set `private_context` and `context` to the same `Context` object.""" if not self.private_context: self.private_context = self.context
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_docstring.py
metagpt/actions/write_docstring.py
"""Code Docstring Generator. This script provides a tool to automatically generate docstrings for Python code. It uses the specified style to create docstrings for the given code and system text. Usage: python3 -m metagpt.actions.write_docstring <filename> [--overwrite] [--style=<docstring_style>] Arguments: filename The path to the Python file for which you want to generate docstrings. Options: --overwrite If specified, overwrite the original file with the code containing docstrings. --style=<docstring_style> Specify the style of the generated docstrings. Valid values: 'google', 'numpy', or 'sphinx'. Default: 'google' Example: python3 -m metagpt.actions.write_docstring ./metagpt/software_company.py --overwrite False --style=numpy This script uses the 'fire' library to create a command-line interface. It generates docstrings for the given Python code using the specified docstring style and adds them to the code. """ from __future__ import annotations import ast from pathlib import Path from typing import Literal, Optional from metagpt.actions.action import Action from metagpt.utils.common import OutputParser, aread, awrite from metagpt.utils.pycst import merge_docstring PYTHON_DOCSTRING_SYSTEM = """### Requirements 1. Add docstrings to the given code following the {style} style. 2. Replace the function body with an Ellipsis object(...) to reduce output. 3. If the types are already annotated, there is no need to include them in the docstring. 4. Extract only class, function or the docstrings for the module parts from the given Python code, avoiding any other text. ### Input Example ```python def function_with_pep484_type_annotations(param1: int) -> bool: return isinstance(param1, int) class ExampleError(Exception): def __init__(self, msg: str): self.msg = msg ``` ### Output Example ```python {example} ``` """ # https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html PYTHON_DOCSTRING_EXAMPLE_GOOGLE = ''' def function_with_pep484_type_annotations(param1: int) -> bool: """Example function with PEP 484 type annotations. Extended description of function. Args: param1: The first parameter. Returns: The return value. True for success, False otherwise. """ ... class ExampleError(Exception): """Exceptions are documented in the same way as classes. The __init__ method was documented in the class level docstring. Args: msg: Human readable string describing the exception. Attributes: msg: Human readable string describing the exception. """ ... ''' PYTHON_DOCSTRING_EXAMPLE_NUMPY = ''' def function_with_pep484_type_annotations(param1: int) -> bool: """ Example function with PEP 484 type annotations. Extended description of function. Parameters ---------- param1 The first parameter. Returns ------- bool The return value. True for success, False otherwise. """ ... class ExampleError(Exception): """ Exceptions are documented in the same way as classes. The __init__ method was documented in the class level docstring. Parameters ---------- msg Human readable string describing the exception. Attributes ---------- msg Human readable string describing the exception. """ ... ''' PYTHON_DOCSTRING_EXAMPLE_SPHINX = ''' def function_with_pep484_type_annotations(param1: int) -> bool: """Example function with PEP 484 type annotations. Extended description of function. :param param1: The first parameter. :type param1: int :return: The return value. True for success, False otherwise. :rtype: bool """ ... class ExampleError(Exception): """Exceptions are documented in the same way as classes. The __init__ method was documented in the class level docstring. :param msg: Human-readable string describing the exception. :type msg: str """ ... ''' _python_docstring_style = { "google": PYTHON_DOCSTRING_EXAMPLE_GOOGLE.strip(), "numpy": PYTHON_DOCSTRING_EXAMPLE_NUMPY.strip(), "sphinx": PYTHON_DOCSTRING_EXAMPLE_SPHINX.strip(), } class WriteDocstring(Action): """This class is used to write docstrings for code. Attributes: desc: A string describing the action. """ desc: str = "Write docstring for code." i_context: Optional[str] = None async def run( self, code: str, system_text: str = PYTHON_DOCSTRING_SYSTEM, style: Literal["google", "numpy", "sphinx"] = "google", ) -> str: """Writes docstrings for the given code and system text in the specified style. Args: code: A string of Python code. system_text: A string of system text. style: A string specifying the style of the docstring. Can be 'google', 'numpy', or 'sphinx'. Returns: The Python code with docstrings added. """ system_text = system_text.format(style=style, example=_python_docstring_style[style]) simplified_code = _simplify_python_code(code) documented_code = await self._aask(f"```python\n{simplified_code}\n```", [system_text]) documented_code = OutputParser.parse_python_code(documented_code) return merge_docstring(code, documented_code) @staticmethod async def write_docstring( filename: str | Path, overwrite: bool = False, style: Literal["google", "numpy", "sphinx"] = "google" ) -> str: data = await aread(str(filename)) code = await WriteDocstring().run(data, style=style) if overwrite: await awrite(filename, code) return code def _simplify_python_code(code: str) -> None: """Simplifies the given Python code by removing expressions and the last if statement. Args: code: A string of Python code. Returns: The simplified Python code. """ code_tree = ast.parse(code) code_tree.body = [i for i in code_tree.body if not isinstance(i, ast.Expr)] if isinstance(code_tree.body[-1], ast.If): code_tree.body.pop() return ast.unparse(code_tree) if __name__ == "__main__": import fire fire.Fire(WriteDocstring.write_docstring)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/debug_error.py
metagpt/actions/debug_error.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:46 @Author : alexanderwu @File : debug_error.py @Modified By: mashenquan, 2023/11/27. 1. Divide the context into three components: legacy code, unit test code, and console log. 2. According to Section 2.2.3.1 of RFC 135, replace file data in the message with the file name. """ import re from typing import Optional from pydantic import BaseModel, Field from metagpt.actions.action import Action from metagpt.logs import logger from metagpt.schema import RunCodeContext, RunCodeResult from metagpt.utils.common import CodeParser from metagpt.utils.project_repo import ProjectRepo PROMPT_TEMPLATE = """ NOTICE 1. Role: You are a Development Engineer or QA engineer; 2. Task: You received this message from another Development Engineer or QA engineer who ran or tested your code. Based on the message, first, figure out your own role, i.e. Engineer or QaEngineer, then rewrite the development code or the test code based on your role, the error, and the summary, such that all bugs are fixed and the code performs well. Attention: Use '##' to split sections, not '#', and '## <SECTION_NAME>' SHOULD WRITE BEFORE the test case or script and triple quotes. The message is as follows: # Legacy Code ```python {code} ``` --- # Unit Test Code ```python {test_code} ``` --- # Console logs ```text {logs} ``` --- Now you should start rewriting the code: ## file name of the code to rewrite: Write code with triple quote. Do your best to implement THIS IN ONLY ONE FILE. """ class DebugError(Action): i_context: RunCodeContext = Field(default_factory=RunCodeContext) repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) async def run(self, *args, **kwargs) -> str: output_doc = await self.repo.test_outputs.get(filename=self.i_context.output_filename) if not output_doc: return "" output_detail = RunCodeResult.loads(output_doc.content) pattern = r"Ran (\d+) tests in ([\d.]+)s\n\nOK" matches = re.search(pattern, output_detail.stderr) if matches: return "" logger.info(f"Debug and rewrite {self.i_context.test_filename}") code_doc = await self.repo.srcs.get(filename=self.i_context.code_filename) if not code_doc: return "" test_doc = await self.repo.tests.get(filename=self.i_context.test_filename) if not test_doc: return "" prompt = PROMPT_TEMPLATE.format(code=code_doc.content, test_code=test_doc.content, logs=output_detail.stderr) rsp = await self._aask(prompt) code = CodeParser.parse_code(text=rsp) return code
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/search_and_summarize.py
metagpt/actions/search_and_summarize.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/23 17:26 @Author : alexanderwu @File : search_google.py """ from typing import Optional import pydantic from pydantic import model_validator from metagpt.actions import Action from metagpt.logs import logger from metagpt.schema import Message from metagpt.tools.search_engine import SearchEngine SEARCH_AND_SUMMARIZE_SYSTEM = """### Requirements 1. Please summarize the latest dialogue based on the reference information (secondary) and dialogue history (primary). Do not include text that is irrelevant to the conversation. - The context is for reference only. If it is irrelevant to the user's search request history, please reduce its reference and usage. 2. If there are citable links in the context, annotate them in the main text in the format [main text](citation link). If there are none in the context, do not write links. 3. The reply should be graceful, clear, non-repetitive, smoothly written, and of moderate length, in {LANG}. ### Dialogue History (For example) A: MLOps competitors ### Current Question (For example) A: MLOps competitors ### Current Reply (For example) 1. Alteryx Designer: <desc> etc. if any 2. Matlab: ditto 3. IBM SPSS Statistics 4. RapidMiner Studio 5. DataRobot AI Platform 6. Databricks Lakehouse Platform 7. Amazon SageMaker 8. Dataiku """ SEARCH_AND_SUMMARIZE_SYSTEM_EN_US = SEARCH_AND_SUMMARIZE_SYSTEM.format(LANG="en-us") SEARCH_AND_SUMMARIZE_PROMPT = """ ### Reference Information {CONTEXT} ### Dialogue History {QUERY_HISTORY} {QUERY} ### Current Question {QUERY} ### Current Reply: Based on the information, please write the reply to the Question """ SEARCH_AND_SUMMARIZE_SALES_SYSTEM = """## Requirements 1. Please summarize the latest dialogue based on the reference information (secondary) and dialogue history (primary). Do not include text that is irrelevant to the conversation. - The context is for reference only. If it is irrelevant to the user's search request history, please reduce its reference and usage. 2. If there are citable links in the context, annotate them in the main text in the format [main text](citation link). If there are none in the context, do not write links. 3. The reply should be graceful, clear, non-repetitive, smoothly written, and of moderate length, in Simplified Chinese. # Example ## Reference Information ... ## Dialogue History user: Which facial cleanser is good for oily skin? Salesperson: Hello, for oily skin, it is suggested to choose a product that can deeply cleanse, control oil, and is gentle and skin-friendly. According to customer feedback and market reputation, the following facial cleansers are recommended:... user: Do you have any by L'Oreal? > Salesperson: ... ## Ideal Answer Yes, I've selected the following for you: 1. L'Oreal Men's Facial Cleanser: Oil control, anti-acne, balance of water and oil, pore purification, effectively against blackheads, deep exfoliation, refuse oil shine. Dense foam, not tight after washing. 2. L'Oreal Age Perfect Hydrating Cleanser: Added with sodium cocoyl glycinate and Centella Asiatica, two effective ingredients, it can deeply cleanse, tighten the skin, gentle and not tight. """ SEARCH_AND_SUMMARIZE_SALES_PROMPT = """ ## Reference Information {CONTEXT} ## Dialogue History {QUERY_HISTORY} {QUERY} > {ROLE}: """ SEARCH_FOOD = """ # User Search Request What are some delicious foods in Xiamen? # Requirements You are a member of a professional butler team and will provide helpful suggestions: 1. Please summarize the user's search request based on the context and avoid including unrelated text. 2. Use [main text](reference link) in markdown format to **naturally annotate** 3-5 textual elements (such as product words or similar text sections) within the main text for easy navigation. 3. The response should be elegant, clear, **without any repetition of text**, smoothly written, and of moderate length. """ class SearchAndSummarize(Action): name: str = "" content: Optional[str] = None search_engine: SearchEngine = None result: str = "" @model_validator(mode="after") def validate_search_engine(self): if self.search_engine is None: try: config = self.config search_engine = SearchEngine.from_search_config(config.search, proxy=config.proxy) except pydantic.ValidationError: search_engine = None self.search_engine = search_engine return self async def run(self, context: list[Message], system_text=SEARCH_AND_SUMMARIZE_SYSTEM) -> str: if self.search_engine is None: logger.warning("Configure one of SERPAPI_API_KEY, SERPER_API_KEY, GOOGLE_API_KEY to unlock full feature") return "" query = context[-1].content # logger.debug(query) rsp = await self.search_engine.run(query) self.result = rsp if not rsp: logger.error("empty rsp...") return "" # logger.info(rsp) system_prompt = [system_text] prompt = SEARCH_AND_SUMMARIZE_PROMPT.format( ROLE=self.prefix, CONTEXT=rsp, QUERY_HISTORY="\n".join([str(i) for i in context[:-1]]), QUERY=str(context[-1]), ) result = await self._aask(prompt, system_prompt) logger.debug(prompt) logger.debug(result) return result
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/generate_questions.py
metagpt/actions/generate_questions.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @File : generate_questions.py """ from metagpt.actions import Action from metagpt.actions.action_node import ActionNode QUESTIONS = ActionNode( key="Questions", expected_type=list[str], instruction="Task: Refer to the context to further inquire about the details that interest you, within a word limit" " of 150 words. Please provide the specific details you would like to inquire about here", example=["1. What ...", "2. How ...", "3. ..."], ) class GenerateQuestions(Action): """This class allows LLM to further mine noteworthy details based on specific "##TOPIC"(discussion topic) and "##RECORD" (discussion records), thereby deepening the discussion.""" name: str = "GenerateQuestions" async def run(self, context) -> ActionNode: return await QUESTIONS.fill(req=context, llm=self.llm)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/__init__.py
metagpt/actions/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:44 @Author : alexanderwu @File : __init__.py """ from enum import Enum from metagpt.actions.action import Action from metagpt.actions.action_output import ActionOutput from metagpt.actions.add_requirement import UserRequirement from metagpt.actions.debug_error import DebugError from metagpt.actions.design_api import WriteDesign from metagpt.actions.design_api_review import DesignReview from metagpt.actions.project_management import WriteTasks from metagpt.actions.research import CollectLinks, WebBrowseAndSummarize, ConductResearch from metagpt.actions.run_code import RunCode from metagpt.actions.search_and_summarize import SearchAndSummarize from metagpt.actions.write_code import WriteCode from metagpt.actions.write_code_review import WriteCodeReview from metagpt.actions.write_prd import WritePRD from metagpt.actions.write_prd_review import WritePRDReview from metagpt.actions.write_test import WriteTest from metagpt.actions.di.execute_nb_code import ExecuteNbCode from metagpt.actions.di.write_analysis_code import WriteAnalysisCode from metagpt.actions.di.write_plan import WritePlan class ActionType(Enum): """All types of Actions, used for indexing.""" ADD_REQUIREMENT = UserRequirement WRITE_PRD = WritePRD WRITE_PRD_REVIEW = WritePRDReview WRITE_DESIGN = WriteDesign DESIGN_REVIEW = DesignReview WRTIE_CODE = WriteCode WRITE_CODE_REVIEW = WriteCodeReview WRITE_TEST = WriteTest RUN_CODE = RunCode DEBUG_ERROR = DebugError WRITE_TASKS = WriteTasks SEARCH_AND_SUMMARIZE = SearchAndSummarize COLLECT_LINKS = CollectLinks WEB_BROWSE_AND_SUMMARIZE = WebBrowseAndSummarize CONDUCT_RESEARCH = ConductResearch EXECUTE_NB_CODE = ExecuteNbCode WRITE_ANALYSIS_CODE = WriteAnalysisCode WRITE_PLAN = WritePlan __all__ = [ "ActionType", "Action", "ActionOutput", ]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/prepare_documents.py
metagpt/actions/prepare_documents.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/11/20 @Author : mashenquan @File : prepare_documents.py @Desc: PrepareDocuments Action: initialize project folder and add new requirements to docs/requirements.txt. RFC 135 2.2.3.5.1. """ import shutil from pathlib import Path from typing import Dict, Optional from metagpt.actions import Action, UserRequirement from metagpt.const import REQUIREMENT_FILENAME from metagpt.logs import logger from metagpt.schema import AIMessage from metagpt.utils.common import any_to_str from metagpt.utils.file_repository import FileRepository from metagpt.utils.project_repo import ProjectRepo class PrepareDocuments(Action): """PrepareDocuments Action: initialize project folder and add new requirements to docs/requirements.txt.""" name: str = "PrepareDocuments" i_context: Optional[str] = None key_descriptions: Optional[Dict[str, str]] = None send_to: str def __init__(self, **kwargs): super().__init__(**kwargs) if not self.key_descriptions: self.key_descriptions = {"project_path": 'the project path if exists in "Original Requirement"'} @property def config(self): return self.context.config def _init_repo(self) -> ProjectRepo: """Initialize the Git environment.""" if not self.config.project_path: name = self.config.project_name or FileRepository.new_filename() path = Path(self.config.workspace.path) / name else: path = Path(self.config.project_path) if path.exists() and not self.config.inc: shutil.rmtree(path) self.context.kwargs.project_path = path self.context.kwargs.inc = self.config.inc return ProjectRepo(path) async def run(self, with_messages, **kwargs): """Create and initialize the workspace folder, initialize the Git environment.""" user_requirements = [i for i in with_messages if i.cause_by == any_to_str(UserRequirement)] if not self.config.project_path and user_requirements and self.key_descriptions: args = await user_requirements[0].parse_resources(llm=self.llm, key_descriptions=self.key_descriptions) for k, v in args.items(): if not v or k in ["resources", "reason"]: continue self.context.kwargs.set(k, v) logger.info(f"{k}={v}") if self.context.kwargs.project_path: self.config.update_via_cli( project_path=self.context.kwargs.project_path, project_name="", inc=False, reqa_file=self.context.kwargs.reqa_file or "", max_auto_summarize_code=0, ) repo = self._init_repo() # Write the newly added requirements from the main parameter idea to `docs/requirement.txt`. await repo.docs.save(filename=REQUIREMENT_FILENAME, content=with_messages[0].content) # Send a Message notification to the WritePRD action, instructing it to process requirements using # `docs/requirement.txt` and `docs/prd/`. return AIMessage( content="", instruct_content=AIMessage.create_instruct_value( kvs={ "project_path": str(repo.workdir), "requirements_filename": str(repo.docs.workdir / REQUIREMENT_FILENAME), "prd_filenames": [str(repo.docs.prd.workdir / i) for i in repo.docs.prd.all_files], }, class_name="PrepareDocumentsOutput", ), cause_by=self, send_to=self.send_to, )
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_test.py
metagpt/actions/write_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 22:12 @Author : alexanderwu @File : write_test.py @Modified By: mashenquan, 2023-11-27. Following the think-act principle, solidify the task parameters when creating the WriteTest object, rather than passing them in when calling the run function. """ from typing import Optional from metagpt.actions.action import Action from metagpt.const import TEST_CODES_FILE_REPO from metagpt.logs import logger from metagpt.schema import Document, TestingContext from metagpt.utils.common import CodeParser PROMPT_TEMPLATE = """ NOTICE 1. Role: You are a QA engineer; the main goal is to design, develop, and execute PEP8 compliant, well-structured, maintainable test cases and scripts for Python 3.9. Your focus should be on ensuring the product quality of the entire project through systematic testing. 2. Requirement: Based on the context, develop a comprehensive test suite that adequately covers all relevant aspects of the code file under review. Your test suite will be part of the overall project QA, so please develop complete, robust, and reusable test cases. 3. Attention1: Use '##' to split sections, not '#', and '## <SECTION_NAME>' SHOULD WRITE BEFORE the test case or script. 4. Attention2: If there are any settings in your tests, ALWAYS SET A DEFAULT VALUE, ALWAYS USE STRONG TYPE AND EXPLICIT VARIABLE. 5. Attention3: YOU MUST FOLLOW "Data structures and interfaces". DO NOT CHANGE ANY DESIGN. Make sure your tests respect the existing design and ensure its validity. 6. Think before writing: What should be tested and validated in this document? What edge cases could exist? What might fail? 7. CAREFULLY CHECK THAT YOU DON'T MISS ANY NECESSARY TEST CASES/SCRIPTS IN THIS FILE. Attention: Use '##' to split sections, not '#', and '## <SECTION_NAME>' SHOULD WRITE BEFORE the test case or script and triple quotes. ----- ## Given the following code, please write appropriate test cases using Python's unittest framework to verify the correctness and robustness of this code: ```python {code_to_test} ``` Note that the code to test is at {source_file_path}, we will put your test code at {workspace}/tests/{test_file_name}, and run your test code from {workspace}, you should correctly import the necessary classes based on these file locations! ## {test_file_name}: Write test code with triple quote. Do your best to implement THIS ONLY ONE FILE. """ class WriteTest(Action): name: str = "WriteTest" i_context: Optional[TestingContext] = None async def write_code(self, prompt): code_rsp = await self._aask(prompt) try: code = CodeParser.parse_code(text=code_rsp) except Exception: # Handle the exception if needed logger.error(f"Can't parse the code: {code_rsp}") # Return code_rsp in case of an exception, assuming llm just returns code as it is and doesn't wrap it inside ``` code = code_rsp return code async def run(self, *args, **kwargs) -> TestingContext: if not self.i_context.test_doc: self.i_context.test_doc = Document( filename="test_" + self.i_context.code_doc.filename, root_path=TEST_CODES_FILE_REPO ) fake_root = "/data" prompt = PROMPT_TEMPLATE.format( code_to_test=self.i_context.code_doc.content, test_file_name=self.i_context.test_doc.filename, source_file_path=fake_root + "/" + self.i_context.code_doc.root_relative_path, workspace=fake_root, ) self.i_context.test_doc.content = await self.write_code(prompt) return self.i_context
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/action_outcls_registry.py
metagpt/actions/action_outcls_registry.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Desc : registry to store Dynamic Model from ActionNode.create_model_class to keep it as same Class # with same class name and mapping from functools import wraps action_outcls_registry = dict() def register_action_outcls(func): """ Due to `create_model` return different Class even they have same class name and mapping. In order to do a comparison, use outcls_id to identify same Class with same class name and field definition """ @wraps(func) def decorater(*args, **kwargs): """ arr example [<class 'metagpt.actions.action_node.ActionNode'>, 'test', {'field': (str, Ellipsis)}] """ arr = list(args) + list(kwargs.values()) """ outcls_id example "<class 'metagpt.actions.action_node.ActionNode'>_test_{'field': (str, Ellipsis)}" """ for idx, item in enumerate(arr): if isinstance(item, dict): arr[idx] = dict(sorted(item.items())) outcls_id = "_".join([str(i) for i in arr]) # eliminate typing influence outcls_id = outcls_id.replace("typing.List", "list").replace("typing.Dict", "dict") if outcls_id in action_outcls_registry: return action_outcls_registry[outcls_id] out_cls = func(*args, **kwargs) action_outcls_registry[outcls_id] = out_cls return out_cls return decorater
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/project_management_an.py
metagpt/actions/project_management_an.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/12/14 15:28 @Author : alexanderwu @File : project_management_an.py """ from typing import List, Optional from metagpt.actions.action_node import ActionNode REQUIRED_PACKAGES = ActionNode( key="Required packages", expected_type=Optional[List[str]], instruction="Provide required packages The response language should correspond to the context and requirements.", example=["flask==1.1.2", "bcrypt==3.2.0"], ) REQUIRED_OTHER_LANGUAGE_PACKAGES = ActionNode( key="Required Other language third-party packages", expected_type=List[str], instruction="List down the required packages for languages other than Python.", example=["No third-party dependencies required"], ) LOGIC_ANALYSIS = ActionNode( key="Logic Analysis", expected_type=List[List[str]], instruction="Provide a list of files with the classes/methods/functions to be implemented, " "including dependency analysis and imports." "Ensure consistency between System Design and Logic Analysis; the files must match exactly. " "If the file is written in Vue or React, use Tailwind CSS for styling.", example=[ ["game.py", "Contains Game class and ... functions"], ["main.py", "Contains main function, from game import Game"], ], ) REFINED_LOGIC_ANALYSIS = ActionNode( key="Refined Logic Analysis", expected_type=List[List[str]], instruction="Review and refine the logic analysis by merging the Legacy Content and Incremental Content. " "Provide a comprehensive list of files with classes/methods/functions to be implemented or modified incrementally. " "Include dependency analysis, consider potential impacts on existing code, and document necessary imports.", example=[ ["game.py", "Contains Game class and ... functions"], ["main.py", "Contains main function, from game import Game"], ["new_feature.py", "Introduces NewFeature class and related functions"], ["utils.py", "Modifies existing utility functions to support incremental changes"], ], ) TASK_LIST = ActionNode( key="Task list", expected_type=List[str], instruction="Break down the tasks into a list of filenames, prioritized by dependency order.", example=["game.py", "main.py"], ) REFINED_TASK_LIST = ActionNode( key="Refined Task list", expected_type=List[str], instruction="Review and refine the combined task list after the merger of Legacy Content and Incremental Content, " "and consistent with Refined File List. Ensure that tasks are organized in a logical and prioritized order, " "considering dependencies for a streamlined and efficient development process. ", example=["new_feature.py", "utils", "game.py", "main.py"], ) FULL_API_SPEC = ActionNode( key="Full API spec", expected_type=str, instruction="Describe all APIs using OpenAPI 3.0 spec that may be used by both frontend and backend. If front-end " "and back-end communication is not required, leave it blank.", example="openapi: 3.0.0 ...", ) SHARED_KNOWLEDGE = ActionNode( key="Shared Knowledge", expected_type=str, instruction="Detail any shared knowledge, like common utility functions or configuration variables.", example="`game.py` contains functions shared across the project.", ) REFINED_SHARED_KNOWLEDGE = ActionNode( key="Refined Shared Knowledge", expected_type=str, instruction="Update and expand shared knowledge to reflect any new elements introduced. This includes common " "utility functions, configuration variables for team collaboration. Retain content that is not related to " "incremental development but important for consistency and clarity.", example="`new_module.py` enhances shared utility functions for improved code reusability and collaboration.", ) ANYTHING_UNCLEAR_PM = ActionNode( key="Anything UNCLEAR", expected_type=str, instruction="Mention any unclear aspects in the project management context and try to clarify them.", example="Clarification needed on how to start and initialize third-party libraries.", ) NODES = [ REQUIRED_PACKAGES, REQUIRED_OTHER_LANGUAGE_PACKAGES, LOGIC_ANALYSIS, TASK_LIST, FULL_API_SPEC, SHARED_KNOWLEDGE, ANYTHING_UNCLEAR_PM, ] REFINED_NODES = [ REQUIRED_PACKAGES, REQUIRED_OTHER_LANGUAGE_PACKAGES, REFINED_LOGIC_ANALYSIS, REFINED_TASK_LIST, FULL_API_SPEC, REFINED_SHARED_KNOWLEDGE, ANYTHING_UNCLEAR_PM, ] PM_NODE = ActionNode.from_children("PM_NODE", NODES) REFINED_PM_NODE = ActionNode.from_children("REFINED_PM_NODE", REFINED_NODES)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/invoice_ocr.py
metagpt/actions/invoice_ocr.py
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """ @Time : 2023/9/21 18:10:20 @Author : Stitch-z @File : invoice_ocr.py @Describe : Actions of the invoice ocr assistant. """ import os import zipfile from datetime import datetime from pathlib import Path from typing import Optional import pandas as pd from paddleocr import PaddleOCR from metagpt.actions import Action from metagpt.const import INVOICE_OCR_TABLE_PATH from metagpt.logs import logger from metagpt.prompts.invoice_ocr import ( EXTRACT_OCR_MAIN_INFO_PROMPT, REPLY_OCR_QUESTION_PROMPT, ) from metagpt.utils.common import OutputParser from metagpt.utils.file import File class InvoiceOCR(Action): """Action class for performing OCR on invoice files, including zip, PDF, png, and jpg files. Args: name: The name of the action. Defaults to an empty string. language: The language for OCR output. Defaults to "ch" (Chinese). """ name: str = "InvoiceOCR" i_context: Optional[str] = None @staticmethod async def _check_file_type(file_path: Path) -> str: """Check the file type of the given filename. Args: file_path: The path of the file. Returns: The file type based on FileExtensionType enum. Raises: Exception: If the file format is not zip, pdf, png, or jpg. """ ext = file_path.suffix if ext not in [".zip", ".pdf", ".png", ".jpg"]: raise Exception("The invoice format is not zip, pdf, png, or jpg") return ext @staticmethod async def _unzip(file_path: Path) -> Path: """Unzip a file and return the path to the unzipped directory. Args: file_path: The path to the zip file. Returns: The path to the unzipped directory. """ file_directory = file_path.parent / "unzip_invoices" / datetime.now().strftime("%Y%m%d%H%M%S") with zipfile.ZipFile(file_path, "r") as zip_ref: for zip_info in zip_ref.infolist(): # Use CP437 to encode the file name, and then use GBK decoding to prevent Chinese garbled code relative_name = Path(zip_info.filename.encode("cp437").decode("gbk")) if relative_name.suffix: full_filename = file_directory / relative_name await File.write(full_filename.parent, relative_name.name, zip_ref.read(zip_info.filename)) logger.info(f"unzip_path: {file_directory}") return file_directory @staticmethod async def _ocr(invoice_file_path: Path): ocr = PaddleOCR(use_angle_cls=True, lang="ch", page_num=1) ocr_result = ocr.ocr(str(invoice_file_path), cls=True) for result in ocr_result[0]: result[1] = (result[1][0], round(result[1][1], 2)) # round long confidence scores to reduce token costs return ocr_result async def run(self, file_path: Path, *args, **kwargs) -> list: """Execute the action to identify invoice files through OCR. Args: file_path: The path to the input file. Returns: A list of OCR results. """ file_ext = await self._check_file_type(file_path) if file_ext == ".zip": # OCR recognizes zip batch files unzip_path = await self._unzip(file_path) ocr_list = [] for root, _, files in os.walk(unzip_path): for filename in files: invoice_file_path = Path(root) / Path(filename) # Identify files that match the type if Path(filename).suffix in [".zip", ".pdf", ".png", ".jpg"]: ocr_result = await self._ocr(str(invoice_file_path)) ocr_list.append(ocr_result) return ocr_list else: # OCR identifies single file ocr_result = await self._ocr(file_path) return [ocr_result] class GenerateTable(Action): """Action class for generating tables from OCR results. Args: name: The name of the action. Defaults to an empty string. language: The language used for the generated table. Defaults to "ch" (Chinese). """ name: str = "GenerateTable" i_context: Optional[str] = None language: str = "ch" async def run(self, ocr_results: list, filename: str, *args, **kwargs) -> dict[str, str]: """Processes OCR results, extracts invoice information, generates a table, and saves it as an Excel file. Args: ocr_results: A list of OCR results obtained from invoice processing. filename: The name of the output Excel file. Returns: A dictionary containing the invoice information. """ table_data = [] pathname = INVOICE_OCR_TABLE_PATH pathname.mkdir(parents=True, exist_ok=True) for ocr_result in ocr_results: # Extract invoice OCR main information prompt = EXTRACT_OCR_MAIN_INFO_PROMPT.format(ocr_result=ocr_result, language=self.language) ocr_info = await self._aask(prompt=prompt) invoice_data = OutputParser.extract_struct(ocr_info, dict) if invoice_data: table_data.append(invoice_data) # Generate Excel file filename = f"{filename.split('.')[0]}.xlsx" full_filename = f"{pathname}/{filename}" df = pd.DataFrame(table_data) df.to_excel(full_filename, index=False) return table_data class ReplyQuestion(Action): """Action class for generating replies to questions based on OCR results. Args: name: The name of the action. Defaults to an empty string. language: The language used for generating the reply. Defaults to "ch" (Chinese). """ language: str = "ch" async def run(self, query: str, ocr_result: list, *args, **kwargs) -> str: """Reply to questions based on ocr results. Args: query: The question for which a reply is generated. ocr_result: A list of OCR results. Returns: A reply result of string type. """ prompt = REPLY_OCR_QUESTION_PROMPT.format(query=query, ocr_result=ocr_result, language=self.language) resp = await self._aask(prompt=prompt) return resp
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/action_graph.py
metagpt/actions/action_graph.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/1/30 13:52 @Author : alexanderwu @File : action_graph.py """ from __future__ import annotations # from metagpt.actions.action_node import ActionNode class ActionGraph: """ActionGraph: a directed graph to represent the dependency between actions.""" def __init__(self): self.nodes = {} self.edges = {} self.execution_order = [] def add_node(self, node): """Add a node to the graph""" self.nodes[node.key] = node def add_edge(self, from_node: "ActionNode", to_node: "ActionNode"): """Add an edge to the graph""" if from_node.key not in self.edges: self.edges[from_node.key] = [] self.edges[from_node.key].append(to_node.key) from_node.add_next(to_node) to_node.add_prev(from_node) def topological_sort(self): """Topological sort the graph""" visited = set() stack = [] def visit(k): if k not in visited: visited.add(k) if k in self.edges: for next_node in self.edges[k]: visit(next_node) stack.insert(0, k) for key in self.nodes: visit(key) self.execution_order = stack
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/research.py
metagpt/actions/research.py
#!/usr/bin/env python from __future__ import annotations import asyncio from datetime import datetime from typing import Any, Callable, Coroutine, Optional, Union from pydantic import TypeAdapter, model_validator from metagpt.actions import Action from metagpt.logs import logger from metagpt.tools.search_engine import SearchEngine from metagpt.tools.web_browser_engine import WebBrowserEngine from metagpt.utils.common import OutputParser from metagpt.utils.parse_html import WebPage from metagpt.utils.text import generate_prompt_chunk, reduce_message_length LANG_PROMPT = "Please respond in {language}." RESEARCH_BASE_SYSTEM = """You are an AI critical thinker research assistant. Your sole purpose is to write well \ written, critically acclaimed, objective and structured reports on the given text.""" RESEARCH_TOPIC_SYSTEM = "You are an AI researcher assistant, and your research topic is:\n#TOPIC#\n{topic}" SEARCH_TOPIC_PROMPT = """Please provide up to 2 necessary keywords related to your research topic for Google search. \ Your response must be in JSON format, for example: ["keyword1", "keyword2"].""" SUMMARIZE_SEARCH_PROMPT = """### Requirements 1. The keywords related to your research topic and the search results are shown in the "Search Result Information" section. 2. Provide up to {decomposition_nums} queries related to your research topic base on the search results. 3. Please respond in the following JSON format: ["query1", "query2", "query3", ...]. ### Search Result Information {search_results} """ COLLECT_AND_RANKURLS_PROMPT = """### Topic {topic} ### Query {query} ### The online search results {results} ### Requirements Please remove irrelevant search results that are not related to the query or topic. If the query is time-sensitive or specifies a certain time frame, please also remove search results that are outdated or outside the specified time frame. Notice that the current time is {time_stamp}. Then, sort the remaining search results based on the link credibility. If two results have equal credibility, prioritize them based on the relevance. Provide the ranked results' indices in JSON format, like [0, 1, 3, 4, ...], without including other words. """ WEB_BROWSE_AND_SUMMARIZE_PROMPT = """### Requirements 1. Utilize the text in the "Reference Information" section to respond to the question "{query}". 2. If the question cannot be directly answered using the text, but the text is related to the research topic, please provide \ a comprehensive summary of the text. 3. If the text is entirely unrelated to the research topic, please reply with a simple text "Not relevant." 4. Include all relevant factual information, numbers, statistics, etc., if available. ### Reference Information {content} """ CONDUCT_RESEARCH_PROMPT = """### Reference Information {content} ### Requirements Please provide a detailed research report in response to the following topic: "{topic}", using the information provided \ above. The report must meet the following requirements: - Focus on directly addressing the chosen topic. - Ensure a well-structured and in-depth presentation, incorporating relevant facts and figures where available. - Present data and findings in an intuitive manner, utilizing feature comparative tables, if applicable. - The report should have a minimum word count of 2,000 and be formatted with Markdown syntax following APA style guidelines. - Include all source URLs in APA format at the end of the report. """ class CollectLinks(Action): """Action class to collect links from a search engine.""" name: str = "CollectLinks" i_context: Optional[str] = None desc: str = "Collect links from a search engine." search_func: Optional[Any] = None search_engine: Optional[SearchEngine] = None rank_func: Optional[Callable[[list[str]], None]] = None @model_validator(mode="after") def validate_engine_and_run_func(self): if self.search_engine is None: self.search_engine = SearchEngine.from_search_config(self.config.search, proxy=self.config.proxy) return self async def run( self, topic: str, decomposition_nums: int = 4, url_per_query: int = 4, system_text: str | None = None, ) -> dict[str, list[str]]: """Run the action to collect links. Args: topic: The research topic. decomposition_nums: The number of search questions to generate. url_per_query: The number of URLs to collect per search question. system_text: The system text. Returns: A dictionary containing the search questions as keys and the collected URLs as values. """ system_text = system_text if system_text else RESEARCH_TOPIC_SYSTEM.format(topic=topic) keywords = await self._aask(SEARCH_TOPIC_PROMPT, [system_text]) try: keywords = OutputParser.extract_struct(keywords, list) keywords = TypeAdapter(list[str]).validate_python(keywords) except Exception as e: logger.exception(f"fail to get keywords related to the research topic '{topic}' for {e}") keywords = [topic] results = await asyncio.gather(*(self.search_engine.run(i, as_string=False) for i in keywords)) def gen_msg(): while True: search_results = "\n".join( f"#### Keyword: {i}\n Search Result: {j}\n" for (i, j) in zip(keywords, results) ) prompt = SUMMARIZE_SEARCH_PROMPT.format( decomposition_nums=decomposition_nums, search_results=search_results ) yield prompt remove = max(results, key=len) remove.pop() if len(remove) == 0: break model_name = self.config.llm.model prompt = reduce_message_length(gen_msg(), model_name, system_text, self.config.llm.max_token) logger.debug(prompt) queries = await self._aask(prompt, [system_text]) try: queries = OutputParser.extract_struct(queries, list) queries = TypeAdapter(list[str]).validate_python(queries) except Exception as e: logger.exception(f"fail to break down the research question due to {e}") queries = keywords ret = {} for query in queries: ret[query] = await self._search_and_rank_urls(topic, query, url_per_query) return ret async def _search_and_rank_urls( self, topic: str, query: str, num_results: int = 4, max_num_results: int = None ) -> list[str]: """Search and rank URLs based on a query. Args: topic: The research topic. query: The search query. num_results: The number of URLs to collect. max_num_results: The max number of URLs to collect. Returns: A list of ranked URLs. """ max_results = max_num_results or max(num_results * 2, 6) results = await self._search_urls(query, max_results=max_results) if len(results) == 0: return [] _results = "\n".join(f"{i}: {j}" for i, j in zip(range(max_results), results)) time_stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") prompt = COLLECT_AND_RANKURLS_PROMPT.format(topic=topic, query=query, results=_results, time_stamp=time_stamp) logger.debug(prompt) indices = await self._aask(prompt) try: indices = OutputParser.extract_struct(indices, list) assert all(isinstance(i, int) for i in indices) except Exception as e: logger.exception(f"fail to rank results for {e}") indices = list(range(max_results)) results = [results[i] for i in indices] if self.rank_func: results = self.rank_func(results) return [i["link"] for i in results[:num_results]] async def _search_urls(self, query: str, max_results: int) -> list[dict[str, str]]: """Use search_engine to get urls. Returns: e.g. [{"title": "...", "link": "...", "snippet", "..."}] """ return await self.search_engine.run(query, max_results=max_results, as_string=False) class WebBrowseAndSummarize(Action): """Action class to explore the web and provide summaries of articles and webpages.""" name: str = "WebBrowseAndSummarize" i_context: Optional[str] = None desc: str = "Explore the web and provide summaries of articles and webpages." browse_func: Union[Callable[[list[str]], None], None] = None web_browser_engine: Optional[WebBrowserEngine] = None @model_validator(mode="after") def validate_engine_and_run_func(self): if self.web_browser_engine is None: self.web_browser_engine = WebBrowserEngine.from_browser_config( self.config.browser, browse_func=self.browse_func, proxy=self.config.proxy, ) return self async def run( self, url: str, *urls: str, query: str, system_text: str = RESEARCH_BASE_SYSTEM, use_concurrent_summarization: bool = False, per_page_timeout: Optional[float] = None, ) -> dict[str, str]: """Run the action to browse the web and provide summaries. Args: url: The main URL to browse. urls: Additional URLs to browse. query: The research question. system_text: The system text. use_concurrent_summarization: Whether to concurrently summarize the content of the webpage by LLM. per_page_timeout: The maximum time for fetching a single page in seconds. Returns: A dictionary containing the URLs as keys and their summaries as values. """ contents = await self._fetch_web_contents(url, *urls, per_page_timeout=per_page_timeout) all_urls = [url] + list(urls) summarize_tasks = [self._summarize_content(content, query, system_text) for content in contents] summaries = await self._execute_summarize_tasks(summarize_tasks, use_concurrent_summarization) result = {url: summary for url, summary in zip(all_urls, summaries) if summary} return result async def _fetch_web_contents( self, url: str, *urls: str, per_page_timeout: Optional[float] = None ) -> list[WebPage]: """Fetch web contents from given URLs.""" contents = await self.web_browser_engine.run(url, *urls, per_page_timeout=per_page_timeout) return [contents] if not urls else contents async def _summarize_content(self, page: WebPage, query: str, system_text: str) -> str: """Summarize web content.""" try: prompt_template = WEB_BROWSE_AND_SUMMARIZE_PROMPT.format(query=query, content="{}") content = page.inner_text if self._is_content_invalid(content): logger.warning(f"Invalid content detected for URL {page.url}: {content[:10]}...") return None chunk_summaries = [] for prompt in generate_prompt_chunk(content, prompt_template, self.llm.model, system_text, 4096): logger.debug(prompt) summary = await self._aask(prompt, [system_text]) if summary == "Not relevant.": continue chunk_summaries.append(summary) if not chunk_summaries: return None if len(chunk_summaries) == 1: return chunk_summaries[0] content = "\n".join(chunk_summaries) prompt = WEB_BROWSE_AND_SUMMARIZE_PROMPT.format(query=query, content=content) summary = await self._aask(prompt, [system_text]) return summary except Exception as e: logger.error(f"Error summarizing content: {e}") return None def _is_content_invalid(self, content: str) -> bool: """Check if the content is invalid based on specific starting phrases.""" invalid_starts = ["Fail to load page", "Access Denied"] return any(content.strip().startswith(phrase) for phrase in invalid_starts) async def _execute_summarize_tasks(self, tasks: list[Coroutine[Any, Any, str]], use_concurrent: bool) -> list[str]: """Execute summarize tasks either concurrently or sequentially.""" if use_concurrent: return await asyncio.gather(*tasks) return [await task for task in tasks] class ConductResearch(Action): """Action class to conduct research and generate a research report.""" def __init__(self, **kwargs): super().__init__(**kwargs) async def run( self, topic: str, content: str, system_text: str = RESEARCH_BASE_SYSTEM, ) -> str: """Run the action to conduct research and generate a research report. Args: topic: The research topic. content: The content for research. system_text: The system text. Returns: The generated research report. """ prompt = CONDUCT_RESEARCH_PROMPT.format(topic=topic, content=content) logger.debug(prompt) self.llm.auto_max_tokens = True return await self._aask(prompt, [system_text]) def get_research_system_text(topic: str, language: str): """Get the system text for conducting research. Args: topic: The research topic. language: The language for the system text. Returns: The system text for conducting research. """ return " ".join((RESEARCH_TOPIC_SYSTEM.format(topic=topic), LANG_PROMPT.format(language=language)))
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/prepare_interview.py
metagpt/actions/prepare_interview.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/9/19 15:02 @Author : DevXiaolan @File : prepare_interview.py """ from metagpt.actions import Action from metagpt.actions.action_node import ActionNode QUESTIONS = ActionNode( key="Questions", expected_type=list[str], instruction="""Role: You are an interviewer of our company who is well-knonwn in frontend or backend develop; Requirement: Provide a list of questions for the interviewer to ask the interviewee, by reading the resume of the interviewee in the context. Attention: Provide as markdown block as the format above, at least 10 questions.""", example=["1. What ...", "2. How ..."], ) class PrepareInterview(Action): name: str = "PrepareInterview" async def run(self, context): return await QUESTIONS.fill(req=context, llm=self.llm)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/write_prd_review.py
metagpt/actions/write_prd_review.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/11 17:45 @Author : alexanderwu @File : write_prd_review.py """ from typing import Optional from metagpt.actions.action import Action class WritePRDReview(Action): name: str = "" i_context: Optional[str] = None prd: Optional[str] = None desc: str = "Based on the PRD, conduct a PRD Review, providing clear and detailed feedback" prd_review_prompt_template: str = """ Given the following Product Requirement Document (PRD): {prd} As a project manager, please review it and provide your feedback and suggestions. """ async def run(self, prd): self.prd = prd prompt = self.prd_review_prompt_template.format(prd=self.prd) review = await self._aask(prompt) return review
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/rebuild_class_view.py
metagpt/actions/rebuild_class_view.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/12/19 @Author : mashenquan @File : rebuild_class_view.py @Desc : Reconstructs class diagram from a source code project. Implement RFC197, https://deepwisdom.feishu.cn/wiki/VyK0wfq56ivuvjklMKJcmHQknGt """ from pathlib import Path from typing import Optional, Set, Tuple import aiofiles from metagpt.actions import Action from metagpt.const import ( AGGREGATION, COMPOSITION, DATA_API_DESIGN_FILE_REPO, GENERALIZATION, GRAPH_REPO_FILE_REPO, ) from metagpt.logs import logger from metagpt.repo_parser import DotClassInfo, RepoParser from metagpt.schema import UMLClassView from metagpt.utils.common import concat_namespace, split_namespace from metagpt.utils.di_graph_repository import DiGraphRepository from metagpt.utils.graph_repository import GraphKeyword, GraphRepository class 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=None): """ 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. """ format = format if format else self.config.prompt_schema graph_repo_pathname = self.context.git_repo.workdir / GRAPH_REPO_FILE_REPO / self.context.git_repo.workdir.name self.graph_db = await DiGraphRepository.load_from(str(graph_repo_pathname.with_suffix(".json"))) repo_parser = RepoParser(base_directory=Path(self.i_context)) # use pylint class_views, relationship_views, package_root = await repo_parser.rebuild_class_views(path=Path(self.i_context)) await GraphRepository.update_graph_db_with_class_views(self.graph_db, class_views) await GraphRepository.update_graph_db_with_class_relationship_views(self.graph_db, relationship_views) await GraphRepository.rebuild_composition_relationship(self.graph_db) # use ast direction, diff_path = self._diff_path(path_root=Path(self.i_context).resolve(), package_root=package_root) symbols = repo_parser.generate_symbols() 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(self.graph_db, file_info) await self._create_mermaid_class_views() await self.graph_db.save() async def _create_mermaid_class_views(self) -> str: """Creates a Mermaid class diagram using data from the `graph_db` graph repository. This method utilizes information stored in the graph repository to generate a Mermaid class diagram. Returns: mermaid class diagram file name. """ path = self.context.git_repo.workdir / DATA_API_DESIGN_FILE_REPO path.mkdir(parents=True, exist_ok=True) pathname = path / self.context.git_repo.workdir.name filename = str(pathname.with_suffix(".class_diagram.mmd")) async with aiofiles.open(filename, mode="w", encoding="utf-8") as writer: content = "classDiagram\n" logger.debug(content) await writer.write(content) # class names rows = await self.graph_db.select(predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS) class_distinct = set() relationship_distinct = set() for r in rows: content = await self._create_mermaid_class(r.subject) if content: await writer.write(content) class_distinct.add(r.subject) for r in rows: content, distinct = await self._create_mermaid_relationship(r.subject) if content: logger.debug(content) await writer.write(content) relationship_distinct.update(distinct) logger.info(f"classes: {len(class_distinct)}, relationship: {len(relationship_distinct)}") if self.i_context: r_filename = Path(filename).relative_to(self.context.git_repo.workdir) await self.graph_db.insert( subject=self.i_context, predicate="hasMermaidClassDiagramFile", object_=str(r_filename) ) logger.info(f"{self.i_context} hasMermaidClassDiagramFile {filename}") return filename async def _create_mermaid_class(self, ns_class_name) -> str: """Generates a Mermaid class diagram for a specific class using data from the `graph_db` graph repository. Args: ns_class_name (str): The namespace-prefixed name of the class for which the Mermaid class diagram is to be created. Returns: str: A Mermaid code block object in markdown representing the class diagram. """ fields = split_namespace(ns_class_name) if len(fields) > 2: # Ignore sub-class return "" rows = await self.graph_db.select(subject=ns_class_name, predicate=GraphKeyword.HAS_DETAIL) if not rows: return "" dot_class_info = DotClassInfo.model_validate_json(rows[0].object_) class_view = UMLClassView.load_dot_class_info(dot_class_info) # update uml view await self.graph_db.insert(ns_class_name, GraphKeyword.HAS_CLASS_VIEW, class_view.model_dump_json()) # update uml isCompositeOf for c in dot_class_info.compositions: await self.graph_db.insert( subject=ns_class_name, predicate=GraphKeyword.IS + COMPOSITION + GraphKeyword.OF, object_=concat_namespace("?", c), ) # update uml isAggregateOf for a in dot_class_info.aggregations: await self.graph_db.insert( subject=ns_class_name, predicate=GraphKeyword.IS + AGGREGATION + GraphKeyword.OF, object_=concat_namespace("?", a), ) content = class_view.get_mermaid(align=1) logger.debug(content) return content async def _create_mermaid_relationship(self, ns_class_name: str) -> Tuple[Optional[str], Optional[Set]]: """Generates a Mermaid class relationship diagram for a specific class using data from the `graph_db` graph repository. Args: ns_class_name (str): The namespace-prefixed class name for which the Mermaid relationship diagram is to be created. Returns: Tuple[str, Set]: A tuple containing the relationship diagram as a string and a set of deduplication. """ s_fields = split_namespace(ns_class_name) if len(s_fields) > 2: # Ignore sub-class return None, None predicates = {GraphKeyword.IS + v + GraphKeyword.OF: v for v in [GENERALIZATION, COMPOSITION, AGGREGATION]} mappings = { GENERALIZATION: " <|-- ", COMPOSITION: " *-- ", AGGREGATION: " o-- ", } content = "" distinct = set() for p, v in predicates.items(): rows = await self.graph_db.select(subject=ns_class_name, predicate=p) for r in rows: o_fields = split_namespace(r.object_) if len(o_fields) > 2: # Ignore sub-class continue relationship = mappings.get(v, " .. ") link = f"{o_fields[1]}{relationship}{s_fields[1]}" distinct.add(link) content += f"\t{link}\n" return content, distinct @staticmethod def _diff_path(path_root: Path, package_root: Path) -> (str, str): """Returns the difference between the root path and the path information represented in the package name. Args: path_root (Path): The root path. package_root (Path): The package root path. Returns: Tuple[str, str]: A tuple containing the representation of the difference ("+", "-", "=") and the path detail of the differing part. Example: >>> _diff_path(path_root=Path("/Users/x/github/MetaGPT"), package_root=Path("/Users/x/github/MetaGPT/metagpt")) "-", "metagpt" >>> _diff_path(path_root=Path("/Users/x/github/MetaGPT/metagpt"), package_root=Path("/Users/x/github/MetaGPT/metagpt")) "=", "." """ if len(str(path_root)) > len(str(package_root)): return "+", str(path_root.relative_to(package_root)) if len(str(path_root)) < len(str(package_root)): return "-", str(package_root.relative_to(path_root)) return "=", "." @staticmethod def _align_root(path: str, direction: str, diff_path: str) -> str: """Aligns the path to the same root represented by `diff_path`. Args: path (str): The path to be aligned. direction (str): The direction of alignment ('+', '-', '='). diff_path (str): The path representing the difference. Returns: str: The aligned path. Example: >>> _align_root(path="metagpt/software_company.py", direction="+", diff_path="MetaGPT") "MetaGPT/metagpt/software_company.py" >>> _align_root(path="metagpt/software_company.py", direction="-", diff_path="metagpt") "software_company.py" """ if direction == "=": return path if direction == "+": return diff_path + "/" + path else: return path[len(diff_path) + 1 :]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/action_node.py
metagpt/actions/action_node.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/12/11 18:45 @Author : alexanderwu @File : action_node.py NOTE: You should use typing.List instead of list to do type annotation. Because in the markdown extraction process, we can use typing to extract the type of the node, but we cannot use built-in list to extract. """ import json import re import typing from enum import Enum from typing import Any, Dict, List, Optional, Tuple, Type, Union from pydantic import BaseModel, Field, create_model, model_validator from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions.action_outcls_registry import register_action_outcls from metagpt.const import MARKDOWN_TITLE_PREFIX, USE_CONFIG_TIMEOUT from metagpt.exp_pool import exp_cache from metagpt.exp_pool.serializers import ActionNodeSerializer from metagpt.llm import BaseLLM from metagpt.logs import logger from metagpt.provider.postprocess.llm_output_postprocess import llm_output_postprocess from metagpt.utils.common import OutputParser, general_after_log from metagpt.utils.human_interaction import HumanInteraction from metagpt.utils.sanitize import sanitize class ReviewMode(Enum): HUMAN = "human" AUTO = "auto" class ReviseMode(Enum): HUMAN = "human" # human revise HUMAN_REVIEW = "human_review" # human-review and auto-revise AUTO = "auto" # auto-review and auto-revise TAG = "CONTENT" class FillMode(Enum): CODE_FILL = "code_fill" XML_FILL = "xml_fill" SINGLE_FILL = "single_fill" LANGUAGE_CONSTRAINT = "Language: Please use the same language as Human INPUT." FORMAT_CONSTRAINT = f"Format: output wrapped inside [{TAG}][/{TAG}] like format example, nothing else." SIMPLE_TEMPLATE = """ ## context {context} ----- ## format example {example} ## nodes: "<node>: <type> # <instruction>" {instruction} ## constraint {constraint} ## action Follow instructions of nodes, generate output and make sure it follows the format example. """ REVIEW_TEMPLATE = """ ## context Compare the key's value of nodes_output and the corresponding requirements one by one. If a key's value that does not match the requirement is found, provide the comment content on how to modify it. No output is required for matching keys. ### nodes_output {nodes_output} ----- ## format example [{tag}] {{ "key1": "comment1", "key2": "comment2", "keyn": "commentn" }} [/{tag}] ## nodes: "<node>: <type> # <instruction>" - key1: <class \'str\'> # the first key name of mismatch key - key2: <class \'str\'> # the second key name of mismatch key - keyn: <class \'str\'> # the last key name of mismatch key ## constraint {constraint} ## action Follow format example's {prompt_schema} format, generate output and make sure it follows the format example. """ REVISE_TEMPLATE = """ ## context change the nodes_output key's value to meet its comment and no need to add extra comment. ### nodes_output {nodes_output} ----- ## format example {example} ## nodes: "<node>: <type> # <instruction>" {instruction} ## constraint {constraint} ## action Follow format example's {prompt_schema} format, generate output and make sure it follows the format example. """ def dict_to_markdown(d, prefix=MARKDOWN_TITLE_PREFIX, kv_sep="\n", postfix="\n"): markdown_str = "" for key, value in d.items(): markdown_str += f"{prefix}{key}{kv_sep}{value}{postfix}" return markdown_str class ActionNode: """ActionNode is a tree of nodes.""" schema: str # raw/json/markdown, default: "" # Action Context context: str # all the context, including all necessary info llm: BaseLLM # LLM with aask interface children: dict[str, "ActionNode"] # Action Input key: str # Product Requirement / File list / Code func: typing.Callable # 与节点相关联的函数或LLM调用 params: Dict[str, Type] # 输入参数的字典,键为参数名,值为参数类型 expected_type: Type # such as str / int / float etc. # context: str # everything in the history. instruction: str # the instructions should be followed. example: Any # example for In Context-Learning. # Action Output content: str instruct_content: BaseModel # For ActionGraph prevs: List["ActionNode"] # previous nodes nexts: List["ActionNode"] # next nodes def __init__( self, key: str, expected_type: Type, instruction: str, example: Any, content: str = "", children: dict[str, "ActionNode"] = None, schema: str = "", ): self.key = key self.expected_type = expected_type self.instruction = instruction self.example = example self.content = content self.children = children if children is not None else {} self.schema = schema self.prevs = [] self.nexts = [] def __str__(self): return ( f"{self.key}, {repr(self.expected_type)}, {self.instruction}, {self.example}" f", {self.content}, {self.children}" ) def __repr__(self): return self.__str__() def add_prev(self, node: "ActionNode"): """增加前置ActionNode""" self.prevs.append(node) def add_next(self, node: "ActionNode"): """增加后置ActionNode""" self.nexts.append(node) def add_child(self, node: "ActionNode"): """增加子ActionNode""" self.children[node.key] = node def get_child(self, key: str) -> Union["ActionNode", None]: return self.children.get(key, None) def add_children(self, nodes: List["ActionNode"]): """批量增加子ActionNode""" for node in nodes: self.add_child(node) @classmethod def from_children(cls, key, nodes: List["ActionNode"]): """直接从一系列的子nodes初始化""" obj = cls(key, str, "", "") obj.add_children(nodes) return obj def _get_children_mapping(self, exclude=None) -> Dict[str, Any]: """获得子ActionNode的字典,以key索引,支持多级结构。""" exclude = exclude or [] def _get_mapping(node: "ActionNode") -> Dict[str, Any]: mapping = {} for key, child in node.children.items(): if key in exclude: continue # 对于嵌套的子节点,递归调用 _get_mapping if child.children: mapping[key] = _get_mapping(child) else: mapping[key] = (child.expected_type, Field(default=child.example, description=child.instruction)) return mapping return _get_mapping(self) def _get_self_mapping(self) -> Dict[str, Tuple[Type, Any]]: """get self key: type mapping""" return {self.key: (self.expected_type, ...)} def get_mapping(self, mode="children", exclude=None) -> Dict[str, Tuple[Type, Any]]: """get key: type mapping under mode""" if mode == "children" or (mode == "auto" and self.children): return self._get_children_mapping(exclude=exclude) return {} if exclude and self.key in exclude else self._get_self_mapping() @classmethod @register_action_outcls def create_model_class(cls, class_name: str, mapping: Dict[str, Tuple[Type, Any]]): """基于pydantic v2的模型动态生成,用来检验结果类型正确性""" def check_fields(cls, values): all_fields = set(mapping.keys()) required_fields = set() for k, v in mapping.items(): type_v, field_info = v if ActionNode.is_optional_type(type_v): continue required_fields.add(k) missing_fields = required_fields - set(values.keys()) if missing_fields: raise ValueError(f"Missing fields: {missing_fields}") unrecognized_fields = set(values.keys()) - all_fields if unrecognized_fields: logger.warning(f"Unrecognized fields: {unrecognized_fields}") return values validators = {"check_missing_fields_validator": model_validator(mode="before")(check_fields)} new_fields = {} for field_name, field_value in mapping.items(): if isinstance(field_value, dict): # 对于嵌套结构,递归创建模型类 nested_class_name = f"{class_name}_{field_name}" nested_class = cls.create_model_class(nested_class_name, field_value) new_fields[field_name] = (nested_class, ...) else: new_fields[field_name] = field_value new_class = create_model(class_name, __validators__=validators, **new_fields) return new_class def create_class(self, mode: str = "auto", class_name: str = None, exclude=None): class_name = class_name if class_name else f"{self.key}_AN" mapping = self.get_mapping(mode=mode, exclude=exclude) return self.create_model_class(class_name, mapping) def _create_children_class(self, exclude=None): """使用object内有的字段直接生成model_class""" class_name = f"{self.key}_AN" mapping = self._get_children_mapping(exclude=exclude) return self.create_model_class(class_name, mapping) def to_dict(self, format_func=None, mode="auto", exclude=None) -> Dict: """将当前节点与子节点都按照node: format的格式组织成字典""" nodes = self._to_dict(format_func=format_func, mode=mode, exclude=exclude) if not isinstance(nodes, dict): nodes = {self.key: nodes} return nodes def _to_dict(self, format_func=None, mode="auto", exclude=None) -> Dict: """将当前节点与子节点都按照node: format的格式组织成字典""" # 如果没有提供格式化函数,则使用默认的格式化函数 if format_func is None: format_func = lambda node: node.instruction # 使用提供的格式化函数来格式化当前节点的值 formatted_value = format_func(self) # 创建当前节点的键值对 if (mode == "children" or mode == "auto") and self.children: node_value = {} else: node_value = formatted_value if mode == "root": return {self.key: node_value} # 递归处理子节点 exclude = exclude or [] for child_key, child_node in self.children.items(): if child_key in exclude: continue # 递归调用 to_dict 方法并更新节点字典 child_dict = child_node._to_dict(format_func, mode, exclude) node_value[child_key] = child_dict return node_value def update_instruct_content(self, incre_data: dict[str, Any]): assert self.instruct_content origin_sc_dict = self.instruct_content.model_dump() origin_sc_dict.update(incre_data) output_class = self.create_class() self.instruct_content = output_class(**origin_sc_dict) def keys(self, mode: str = "auto") -> list: if mode == "children" or (mode == "auto" and self.children): keys = [] else: keys = [self.key] if mode == "root": return keys for _, child_node in self.children.items(): keys.append(child_node.key) return keys def compile_to(self, i: Dict, schema, kv_sep) -> str: if schema == "json": return json.dumps(i, indent=4, ensure_ascii=False) elif schema == "markdown": return dict_to_markdown(i, kv_sep=kv_sep) else: return str(i) def tagging(self, text, schema, tag="") -> str: if not tag: return text return f"[{tag}]\n{text}\n[/{tag}]" def _compile_f(self, schema, mode, tag, format_func, kv_sep, exclude=None) -> str: nodes = self.to_dict(format_func=format_func, mode=mode, exclude=exclude) text = self.compile_to(nodes, schema, kv_sep) return self.tagging(text, schema, tag) def compile_instruction(self, schema="markdown", mode="children", tag="", exclude=None) -> str: """compile to raw/json/markdown template with all/root/children nodes""" format_func = lambda i: f"{i.expected_type} # {i.instruction}" return self._compile_f(schema, mode, tag, format_func, kv_sep=": ", exclude=exclude) def compile_example(self, schema="json", mode="children", tag="", exclude=None) -> str: """compile to raw/json/markdown examples with all/root/children nodes""" # 这里不能使用f-string,因为转译为str后再json.dumps会额外加上引号,无法作为有效的example # 错误示例:"File list": "['main.py', 'const.py', 'game.py']", 注意这里值不是list,而是str format_func = lambda i: i.example return self._compile_f(schema, mode, tag, format_func, kv_sep="\n", exclude=exclude) def compile(self, context, schema="json", mode="children", template=SIMPLE_TEMPLATE, exclude=[]) -> str: """ mode: all/root/children mode="children": 编译所有子节点为一个统一模板,包括instruction与example mode="all": NotImplemented mode="root": NotImplemented schmea: raw/json/markdown schema="raw": 不编译,context, lang_constaint, instruction schema="json":编译context, example(json), instruction(markdown), constraint, action schema="markdown": 编译context, example(markdown), instruction(markdown), constraint, action """ if schema == "raw": return f"{context}\n\n## Actions\n{LANGUAGE_CONSTRAINT}\n{self.instruction}" ### 直接使用 pydantic BaseModel 生成 instruction 与 example,仅限 JSON # child_class = self._create_children_class() # node_schema = child_class.model_json_schema() # defaults = { # k: str(v) # for k, v in child_class.model_fields.items() # if k not in exclude # } # instruction = node_schema # example = json.dumps(defaults, indent=4) # FIXME: json instruction会带来格式问题,如:"Project name": "web_2048 # 项目名称使用下划线", # compile example暂时不支持markdown instruction = self.compile_instruction(schema="markdown", mode=mode, exclude=exclude) example = self.compile_example(schema=schema, tag=TAG, mode=mode, exclude=exclude) # nodes = ", ".join(self.to_dict(mode=mode).keys()) constraints = [LANGUAGE_CONSTRAINT, FORMAT_CONSTRAINT] constraint = "\n".join(constraints) prompt = template.format( context=context, example=example, instruction=instruction, constraint=constraint, ) return prompt @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _aask_v1( self, prompt: str, output_class_name: str, output_data_mapping: dict, images: Optional[Union[str, list[str]]] = None, system_msgs: Optional[list[str]] = None, schema="markdown", # compatible to original format timeout=USE_CONFIG_TIMEOUT, ) -> (str, BaseModel): """Use ActionOutput to wrap the output of aask""" content = await self.llm.aask(prompt, system_msgs, images=images, timeout=timeout) logger.debug(f"llm raw output:\n{content}") output_class = self.create_model_class(output_class_name, output_data_mapping) if schema == "json": parsed_data = llm_output_postprocess( output=content, schema=output_class.model_json_schema(), req_key=f"[/{TAG}]" ) else: # using markdown parser parsed_data = OutputParser.parse_data_with_mapping(content, output_data_mapping) logger.debug(f"parsed_data:\n{parsed_data}") instruct_content = output_class(**parsed_data) return content, instruct_content def get(self, key): return self.instruct_content.model_dump()[key] def set_recursive(self, name, value): setattr(self, name, value) for _, i in self.children.items(): i.set_recursive(name, value) def set_llm(self, llm): self.set_recursive("llm", llm) def set_context(self, context): self.set_recursive("context", context) async def simple_fill( self, schema, mode, images: Optional[Union[str, list[str]]] = None, timeout=USE_CONFIG_TIMEOUT, exclude=None ): prompt = self.compile(context=self.context, schema=schema, mode=mode, exclude=exclude) if schema != "raw": mapping = self.get_mapping(mode, exclude=exclude) class_name = f"{self.key}_AN" content, scontent = await self._aask_v1( prompt, class_name, mapping, images=images, schema=schema, timeout=timeout ) self.content = content self.instruct_content = scontent else: self.content = await self.llm.aask(prompt) self.instruct_content = None return self def get_field_name(self): """ Get the field name from the Pydantic model associated with this ActionNode. """ model_class = self.create_class() fields = model_class.model_fields # Assuming there's only one field in the model if len(fields) == 1: return next(iter(fields)) # If there are multiple fields, we might want to use self.key to find the right one return self.key def get_field_names(self): """ Get the field names associated with this ActionNode's Pydantic model. """ model_class = self.create_class() return model_class.model_fields.keys() def get_field_types(self): """ Get the field types associated with this ActionNode's Pydantic model. """ model_class = self.create_class() return {field_name: field.annotation for field_name, field in model_class.model_fields.items()} def xml_compile(self, context): """ Compile the prompt to make it easier for the model to understand the xml format. """ field_names = self.get_field_names() # Construct the example using the field names examples = [] for field_name in field_names: examples.append(f"<{field_name}>content</{field_name}>") # Join all examples into a single string example_str = "\n".join(examples) # Add the example to the context context += f""" ### Response format (must be strictly followed): All content must be enclosed in the given XML tags, ensuring each opening <tag> has a corresponding closing </tag>, with no incomplete or self-closing tags allowed.\n {example_str} """ return context async def code_fill( self, context: str, function_name: Optional[str] = None, timeout: int = USE_CONFIG_TIMEOUT ) -> Dict[str, str]: """ Fill CodeBlock Using ``` ``` """ field_name = self.get_field_name() prompt = context content = await self.llm.aask(prompt, timeout=timeout) extracted_code = sanitize(code=content, entrypoint=function_name) result = {field_name: extracted_code} return result async def single_fill(self, context: str, images: Optional[Union[str, list[str]]] = None) -> Dict[str, str]: field_name = self.get_field_name() prompt = context content = await self.llm.aask(prompt, images=images) result = {field_name: content} return result async def xml_fill(self, context: str, images: Optional[Union[str, list[str]]] = None) -> Dict[str, Any]: """ Fill context with XML tags and convert according to field types, including string, integer, boolean, list and dict types """ field_names = self.get_field_names() field_types = self.get_field_types() extracted_data: Dict[str, Any] = {} content = await self.llm.aask(context, images=images) for field_name in field_names: pattern = rf"<{field_name}>(.*?)</{field_name}>" match = re.search(pattern, content, re.DOTALL) if match: raw_value = match.group(1).strip() field_type = field_types.get(field_name) if field_type == str: extracted_data[field_name] = raw_value elif field_type == int: try: extracted_data[field_name] = int(raw_value) except ValueError: extracted_data[field_name] = 0 # 或者其他默认值 elif field_type == bool: extracted_data[field_name] = raw_value.lower() in ("true", "yes", "1", "on", "True") elif field_type == list: try: extracted_data[field_name] = eval(raw_value) if not isinstance(extracted_data[field_name], list): raise ValueError except: extracted_data[field_name] = [] # 默认空列表 elif field_type == dict: try: extracted_data[field_name] = eval(raw_value) if not isinstance(extracted_data[field_name], dict): raise ValueError except: extracted_data[field_name] = {} # 默认空字典 return extracted_data @exp_cache(serializer=ActionNodeSerializer()) async def fill( self, *, req, llm, schema="json", mode="auto", strgy="simple", images: Optional[Union[str, list[str]]] = None, timeout=USE_CONFIG_TIMEOUT, exclude=[], function_name: str = None, ): """Fill the node(s) with mode. :param req: Everything we should know when filling node. :param llm: Large Language Model with pre-defined system message. :param schema: json/markdown, determine example and output format. - raw: free form text - json: it's easy to open source LLM with json format - markdown: when generating code, markdown is always better :param mode: auto/children/root - auto: automated fill children's nodes and gather outputs, if no children, fill itself - children: fill children's nodes and gather outputs - root: fill root's node and gather output :param strgy: simple/complex - simple: run only once - complex: run each node :param images: the list of image url or base64 for gpt4-v :param timeout: Timeout for llm invocation. :param exclude: The keys of ActionNode to exclude. :return: self """ self.set_llm(llm) self.set_context(req) if self.schema: schema = self.schema if mode == FillMode.CODE_FILL.value: result = await self.code_fill(context, function_name, timeout) self.instruct_content = self.create_class()(**result) return self elif mode == FillMode.XML_FILL.value: context = self.xml_compile(context=self.context) result = await self.xml_fill(context, images=images) self.instruct_content = self.create_class()(**result) return self elif mode == FillMode.SINGLE_FILL.value: result = await self.single_fill(context, images=images) self.instruct_content = self.create_class()(**result) return self if strgy == "simple": return await self.simple_fill(schema=schema, mode=mode, images=images, timeout=timeout, exclude=exclude) elif strgy == "complex": # 这里隐式假设了拥有children tmp = {} for _, i in self.children.items(): if exclude and i.key in exclude: continue child = await i.simple_fill(schema=schema, mode=mode, images=images, timeout=timeout, exclude=exclude) tmp.update(child.instruct_content.model_dump()) cls = self._create_children_class() self.instruct_content = cls(**tmp) return self async def human_review(self) -> dict[str, str]: review_comments = HumanInteraction().interact_with_instruct_content( instruct_content=self.instruct_content, interact_type="review" ) return review_comments def _makeup_nodes_output_with_req(self) -> dict[str, str]: instruct_content_dict = self.instruct_content.model_dump() nodes_output = {} for key, value in instruct_content_dict.items(): child = self.get_child(key) nodes_output[key] = {"value": value, "requirement": child.instruction if child else self.instruction} return nodes_output async def auto_review(self, template: str = REVIEW_TEMPLATE) -> dict[str, str]: """use key's output value and its instruction to review the modification comment""" nodes_output = self._makeup_nodes_output_with_req() """nodes_output format: { "key": {"value": "output value", "requirement": "key instruction"} } """ if not nodes_output: return dict() prompt = template.format( nodes_output=json.dumps(nodes_output, ensure_ascii=False), tag=TAG, constraint=FORMAT_CONSTRAINT, prompt_schema="json", ) content = await self.llm.aask(prompt) # Extract the dict of mismatch key and its comment. Due to the mismatch keys are unknown, here use the keys # of ActionNode to judge if exist in `content` and then follow the `data_mapping` method to create model class. keys = self.keys() include_keys = [] for key in keys: if f'"{key}":' in content: include_keys.append(key) if not include_keys: return dict() exclude_keys = list(set(keys).difference(include_keys)) output_class_name = f"{self.key}_AN_REVIEW" output_class = self.create_class(class_name=output_class_name, exclude=exclude_keys) parsed_data = llm_output_postprocess( output=content, schema=output_class.model_json_schema(), req_key=f"[/{TAG}]" ) instruct_content = output_class(**parsed_data) return instruct_content.model_dump() async def simple_review(self, review_mode: ReviewMode = ReviewMode.AUTO): # generate review comments if review_mode == ReviewMode.HUMAN: review_comments = await self.human_review() else: review_comments = await self.auto_review() if not review_comments: logger.warning("There are no review comments") return review_comments async def review(self, strgy: str = "simple", review_mode: ReviewMode = ReviewMode.AUTO): """only give the review comment of each exist and mismatch key :param strgy: simple/complex - simple: run only once - complex: run each node """ if not hasattr(self, "llm"): raise RuntimeError("use `review` after `fill`") assert review_mode in ReviewMode assert self.instruct_content, 'review only support with `schema != "raw"`' if strgy == "simple": review_comments = await self.simple_review(review_mode) elif strgy == "complex": # review each child node one-by-one review_comments = {} for _, child in self.children.items(): child_review_comment = await child.simple_review(review_mode) review_comments.update(child_review_comment) return review_comments async def human_revise(self) -> dict[str, str]: review_contents = HumanInteraction().interact_with_instruct_content( instruct_content=self.instruct_content, mapping=self.get_mapping(mode="auto"), interact_type="revise" ) # re-fill the ActionNode self.update_instruct_content(review_contents) return review_contents def _makeup_nodes_output_with_comment(self, review_comments: dict[str, str]) -> dict[str, str]: instruct_content_dict = self.instruct_content.model_dump() nodes_output = {} for key, value in instruct_content_dict.items(): if key in review_comments: nodes_output[key] = {"value": value, "comment": review_comments[key]} return nodes_output async def auto_revise( self, revise_mode: ReviseMode = ReviseMode.AUTO, template: str = REVISE_TEMPLATE ) -> dict[str, str]: """revise the value of incorrect keys""" # generate review comments if revise_mode == ReviseMode.AUTO: review_comments: dict = await self.auto_review() elif revise_mode == ReviseMode.HUMAN_REVIEW: review_comments: dict = await self.human_review() include_keys = list(review_comments.keys()) # generate revise content, two-steps # step1, find the needed revise keys from review comments to makeup prompt template nodes_output = self._makeup_nodes_output_with_comment(review_comments) keys = self.keys() exclude_keys = list(set(keys).difference(include_keys)) example = self.compile_example(schema="json", mode="auto", tag=TAG, exclude=exclude_keys) instruction = self.compile_instruction(schema="markdown", mode="auto", exclude=exclude_keys) prompt = template.format( nodes_output=json.dumps(nodes_output, ensure_ascii=False), example=example, instruction=instruction, constraint=FORMAT_CONSTRAINT, prompt_schema="json", ) # step2, use `_aask_v1` to get revise structure result output_mapping = self.get_mapping(mode="auto", exclude=exclude_keys) output_class_name = f"{self.key}_AN_REVISE" content, scontent = await self._aask_v1( prompt=prompt, output_class_name=output_class_name, output_data_mapping=output_mapping, schema="json" ) # re-fill the ActionNode sc_dict = scontent.model_dump() self.update_instruct_content(sc_dict) return sc_dict async def simple_revise(self, revise_mode: ReviseMode = ReviseMode.AUTO) -> dict[str, str]: if revise_mode == ReviseMode.HUMAN: revise_contents = await self.human_revise() else: revise_contents = await self.auto_revise(revise_mode) return revise_contents async def revise(self, strgy: str = "simple", revise_mode: ReviseMode = ReviseMode.AUTO) -> dict[str, str]: """revise the content of ActionNode and update the instruct_content :param strgy: simple/complex - simple: run only once - complex: run each node """ if not hasattr(self, "llm"): raise RuntimeError("use `revise` after `fill`") assert revise_mode in ReviseMode assert self.instruct_content, 'revise only support with `schema != "raw"`' if strgy == "simple": revise_contents = await self.simple_revise(revise_mode) elif strgy == "complex": # revise each child node one-by-one revise_contents = {} for _, child in self.children.items(): child_revise_content = await child.simple_revise(revise_mode) revise_contents.update(child_revise_content) self.update_instruct_content(revise_contents) return revise_contents @classmethod def from_pydantic(cls, model: Type[BaseModel], key: str = None): """ Creates an ActionNode tree from a Pydantic model. Args: model (Type[BaseModel]): The Pydantic model to convert. Returns: ActionNode: The root node of the created ActionNode tree. """ key = key or model.__name__ root_node = cls(key=key, expected_type=Type[model], instruction="", example="")
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
true
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/summarize_code.py
metagpt/actions/summarize_code.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : alexanderwu @File : summarize_code.py @Modified By: mashenquan, 2023/12/5. Archive the summarization content of issue discovery for use in WriteCode. """ from pathlib import Path from typing import Optional from pydantic import BaseModel, Field from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions.action import Action from metagpt.logs import logger from metagpt.schema import CodeSummarizeContext from metagpt.utils.common import get_markdown_code_block_type from metagpt.utils.project_repo import ProjectRepo PROMPT_TEMPLATE = """ NOTICE Role: You are a professional software engineer, and your main task is to review the code. Language: Please use the same language as the user requirement, but the title and code should be still in English. For example, if the user speaks Chinese, the specific text of your answer should also be in Chinese. ATTENTION: Use '##' to SPLIT SECTIONS, not '#'. Output format carefully referenced "Format example". ----- # System Design ```text {system_design} ``` ----- # Task ```text {task} ``` ----- {code_blocks} ## Code Review All: Please read all historical files and find possible bugs in the files, such as unimplemented functions, calling errors, unreferences, etc. ## Call flow: mermaid code, based on the implemented function, use mermaid to draw a complete call chain ## Summary: Summary based on the implementation of historical files ## TODOs: Python dict[str, str], write down the list of files that need to be modified and the reasons. We will modify them later. """ FORMAT_EXAMPLE = """ ## Code Review All ### a.py - It fulfills less of xxx requirements... - Field yyy is not given... -... ### b.py ... ### c.py ... ## Call flow ```mermaid flowchart TB c1-->a2 subgraph one a1-->a2 end subgraph two b1-->b2 end subgraph three c1-->c2 end ``` ## Summary - a.py:... - b.py:... - c.py:... - ... ## TODOs { "a.py": "implement requirement xxx...", } """ class SummarizeCode(Action): name: str = "SummarizeCode" i_context: CodeSummarizeContext = Field(default_factory=CodeSummarizeContext) repo: Optional[ProjectRepo] = Field(default=None, exclude=True) input_args: Optional[BaseModel] = Field(default=None, exclude=True) @retry(stop=stop_after_attempt(2), wait=wait_random_exponential(min=1, max=60)) async def summarize_code(self, prompt): code_rsp = await self._aask(prompt) return code_rsp async def run(self): design_pathname = Path(self.i_context.design_filename) design_doc = await self.repo.docs.system_design.get(filename=design_pathname.name) task_pathname = Path(self.i_context.task_filename) task_doc = await self.repo.docs.task.get(filename=task_pathname.name) code_blocks = [] for filename in self.i_context.codes_filenames: code_doc = await self.repo.srcs.get(filename) code_block = f"```{get_markdown_code_block_type(filename)}\n{code_doc.content}\n```\n---\n" code_blocks.append(code_block) format_example = FORMAT_EXAMPLE prompt = PROMPT_TEMPLATE.format( system_design=design_doc.content, task=task_doc.content, code_blocks="\n".join(code_blocks), format_example=format_example, ) logger.info("Summarize code..") rsp = await self.summarize_code(prompt) return rsp
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/evaluate_action.py
metagpt/actions/requirement_analysis/evaluate_action.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : evaluate_action.py @Desc : The implementation of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from typing import Optional from pydantic import BaseModel from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import Action from metagpt.logs import logger from metagpt.utils.common import CodeParser, general_after_log, to_markdown_code_block class EvaluationData(BaseModel): """Model to represent evaluation data. Attributes: is_pass (bool): Indicates if the evaluation passed or failed. conclusion (Optional[str]): Conclusion or remarks about the evaluation. """ is_pass: bool conclusion: Optional[str] = None class EvaluateAction(Action): """The base class for an evaluation action. This class provides methods to evaluate prompts using a specified language model. """ @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _evaluate(self, prompt: str) -> (bool, str): """Evaluates a given prompt. Args: prompt (str): The prompt to be evaluated. Returns: tuple: A tuple containing: - bool: Indicates if the evaluation passed. - str: The JSON string containing the evaluation data. """ rsp = await self.llm.aask(prompt) json_data = CodeParser.parse_code(text=rsp, lang="json") data = EvaluationData.model_validate_json(json_data) return data.is_pass, to_markdown_code_block(val=json_data, type_="json") async def _vote(self, prompt: str) -> EvaluationData: """Evaluates a prompt multiple times and returns the consensus. Args: prompt (str): The prompt to be evaluated. Returns: EvaluationData: An object containing the evaluation result and a summary of evaluations. """ evaluations = {} for i in range(3): vote, evaluation = await self._evaluate(prompt) val = evaluations.get(vote, []) val.append(evaluation) if len(val) > 1: return EvaluationData(is_pass=vote, conclusion="\n".join(val)) evaluations[vote] = val
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/__init__.py
metagpt/actions/requirement_analysis/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : __init__.py @Desc : The implementation of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from metagpt.actions.requirement_analysis.evaluate_action import EvaluationData, EvaluateAction __all__ = [EvaluationData, EvaluateAction]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/framework/write_framework.py
metagpt/actions/requirement_analysis/framework/write_framework.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : write_framework.py @Desc : The implementation of Chapter 2.1.8 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ import json from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import Action from metagpt.logs import logger from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import general_after_log, to_markdown_code_block @register_tool(include_functions=["run"]) class WriteFramework(Action): """WriteFramework deal with the following situations: 1. Given a TRD, write out the software framework. """ async def run( self, *, use_case_actors: str, trd: str, acknowledge: str, legacy_output: str, evaluation_conclusion: str, additional_technical_requirements: str, ) -> str: """ Run the action to generate a software framework based on the provided TRD and related information. Args: use_case_actors (str): Description of the use case actors involved. trd (str): Technical Requirements Document detailing the requirements. acknowledge (str): External acknowledgements or acknowledgements required. legacy_output (str): Previous version of the software framework returned by `WriteFramework.run`. evaluation_conclusion (str): Conclusion from the evaluation of the requirements. additional_technical_requirements (str): Any additional technical requirements. Returns: str: The generated software framework as a string. Example: >>> write_framework = WriteFramework() >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;" >>> trd = "## TRD\\n..." >>> acknowledge = "## Interfaces\\n..." >>> legacy_output = '{"path":"balabala", "filename":"...", ...' >>> evaluation_conclusion = "Balabala..." >>> constraint = "Using Java language, ..." >>> framework = await write_framework.run( >>> use_case_actors=use_case_actors, >>> trd=trd, >>> acknowledge=acknowledge, >>> legacy_output=framework, >>> evaluation_conclusion=evaluation_conclusion, >>> additional_technical_requirements=constraint, >>> ) >>> print(framework) {"path":"balabala", "filename":"...", ... """ acknowledge = await self._extract_external_interfaces(trd=trd, knowledge=acknowledge) prompt = PROMPT.format( use_case_actors=use_case_actors, trd=to_markdown_code_block(val=trd), acknowledge=to_markdown_code_block(val=acknowledge), legacy_output=to_markdown_code_block(val=legacy_output), evaluation_conclusion=evaluation_conclusion, additional_technical_requirements=to_markdown_code_block(val=additional_technical_requirements), ) return await self._write(prompt) @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _write(self, prompt: str) -> str: rsp = await self.llm.aask(prompt) # Do not use `CodeParser` here. tags = ["```json", "```"] bix = rsp.find(tags[0]) eix = rsp.rfind(tags[1]) if bix >= 0: rsp = rsp[bix : eix + len(tags[1])] json_data = rsp.removeprefix("```json").removesuffix("```") json.loads(json_data) # validate return json_data @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _extract_external_interfaces(self, trd: str, knowledge: str) -> str: prompt = f"## TRD\n{to_markdown_code_block(val=trd)}\n\n## Knowledge\n{to_markdown_code_block(val=knowledge)}\n" rsp = await self.llm.aask( prompt, system_msgs=[ "You are a tool that removes impurities from articles; you can remove irrelevant content from articles.", 'Identify which interfaces are used in "TRD"? Remove the relevant content of the interfaces NOT used in "TRD" from "Knowledge" and return the simplified content of "Knowledge".', ], ) return rsp PROMPT = """ ## Actor, System, External System {use_case_actors} ## TRD {trd} ## Acknowledge {acknowledge} ## Legacy Outputs {legacy_output} ## Evaluation Conclusion {evaluation_conclusion} ## Additional Technical Requirements {additional_technical_requirements} --- You are a tool that generates software framework code based on TRD. The content of "Actor, System, External System" provides an explanation of actors and systems that appear in UML Use Case diagram; The descriptions of the interfaces of the external system used in the "TRD" can be found in the "Acknowledge" section; Do not implement the interface of the external system in "Acknowledge" section until it is used in "TRD"; "Legacy Outputs" contains the software framework code generated by you last time, which you can improve by addressing the issues raised in "Evaluation Conclusion"; "Additional Technical Requirements" specifies the additional technical requirements that the generated software framework code must meet; Develop the software framework based on the "TRD", the output files should include: - The `README.md` file should include: - The folder structure diagram of the entire project; - Correspondence between classes, interfaces, and functions with the content in the "TRD" section; - Prerequisites if necessary; - Installation if necessary; - Configuration if necessary; - Usage if necessary; - The `CLASS.md` file should include the class diagram in PlantUML format based on the "TRD"; - The `SEQUENCE.md` file should include the sequence diagram in PlantUML format based on the "TRD"; - The source code files that implement the "TRD" and "Additional Technical Requirements"; do not add comments to source code files; - The configuration files that required by the source code files, "TRD" and "Additional Technical Requirements"; Return a markdown JSON object list, each object containing: - a "path" key with a value specifying its path; - a "filename" key with a value specifying its file name; - a "content" key with a value containing its file content; """
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/framework/evaluate_framework.py
metagpt/actions/requirement_analysis/framework/evaluate_framework.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : evaluate_framework.py @Desc : The implementation of Chapter 2.1.8 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from metagpt.actions.requirement_analysis import EvaluateAction, EvaluationData from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import to_markdown_code_block @register_tool(include_functions=["run"]) class EvaluateFramework(EvaluateAction): """WriteFramework deal with the following situations: 1. Given a TRD and the software framework based on the TRD, evaluate the quality of the software framework. """ async def run( self, *, use_case_actors: str, trd: str, acknowledge: str, legacy_output: str, additional_technical_requirements: str, ) -> EvaluationData: """ Run the evaluation of the software framework based on the provided TRD and related parameters. Args: use_case_actors (str): A description of the actors involved in the use case. trd (str): The Technical Requirements Document (TRD) that outlines the requirements for the software framework. acknowledge (str): External acknowledgments or acknowledgments information related to the framework. legacy_output (str): The previous versions of software framework returned by `WriteFramework`. additional_technical_requirements (str): Additional technical requirements that need to be considered during evaluation. Returns: EvaluationData: An object containing the results of the evaluation. Example: >>> evaluate_framework = EvaluateFramework() >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;" >>> trd = "## TRD\\n..." >>> acknowledge = "## Interfaces\\n..." >>> framework = '{"path":"balabala", "filename":"...", ...' >>> constraint = "Using Java language, ..." >>> evaluation = await evaluate_framework.run( >>> use_case_actors=use_case_actors, >>> trd=trd, >>> acknowledge=acknowledge, >>> legacy_output=framework, >>> additional_technical_requirements=constraint, >>> ) >>> is_pass = evaluation.is_pass >>> print(is_pass) True >>> evaluation_conclusion = evaluation.conclusion >>> print(evaluation_conclusion) Balabala... """ prompt = PROMPT.format( use_case_actors=use_case_actors, trd=to_markdown_code_block(val=trd), acknowledge=to_markdown_code_block(val=acknowledge), legacy_output=to_markdown_code_block(val=legacy_output), additional_technical_requirements=to_markdown_code_block(val=additional_technical_requirements), ) return await self._vote(prompt) PROMPT = """ ## Actor, System, External System {use_case_actors} ## Legacy TRD {trd} ## Acknowledge {acknowledge} ## Legacy Outputs {legacy_output} ## Additional Technical Requirements {additional_technical_requirements} --- You are a tool that evaluates the quality of framework code based on the TRD content; You need to refer to the content of the "Legacy TRD" section to check for any errors or omissions in the framework code found in "Legacy Outputs"; The content of "Actor, System, External System" provides an explanation of actors and systems that appear in UML Use Case diagram; Information about the external system missing from the "Legacy TRD" can be found in the "Acknowledge" section; Which interfaces defined in "Acknowledge" are used in the "Legacy TRD"? Do not implement the interface in "Acknowledge" section until it is used in "Legacy TRD", you can check whether they are the same interface by looking at its ID or url; Parts not mentioned in the "Legacy TRD" will be handled by other TRDs, therefore, processes not present in the "Legacy TRD" are considered ready; "Additional Technical Requirements" specifies the additional technical requirements that the generated software framework code must meet; Do the parameters of the interface of the external system used in the code comply with it's specifications in 'Acknowledge'? Is there a lack of necessary configuration files? Return a markdown JSON object with: - an "issues" key containing a string list of natural text about the issues that need to addressed, found in the "Legacy Outputs" if any exits, each issue found must provide a detailed description and include reasons; - a "conclusion" key containing the evaluation conclusion; - a "misalignment" key containing the judgement detail of the natural text string list about the misalignment with "Legacy TRD"; - a "is_pass" key containing a true boolean value if there is not any issue in the "Legacy Outputs"; """
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/framework/__init__.py
metagpt/actions/requirement_analysis/framework/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : __init__.py @Desc : The implementation of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ import json import uuid from datetime import datetime from pathlib import Path from typing import Optional, Union, List from pydantic import BaseModel from metagpt.actions.requirement_analysis.framework.evaluate_framework import EvaluateFramework from metagpt.actions.requirement_analysis.framework.write_framework import WriteFramework from metagpt.config2 import config from metagpt.utils.common import awrite async def save_framework( dir_data: str, trd: Optional[str] = None, output_dir: Optional[Union[str, Path]] = None ) -> List[str]: """ Saves framework data to files based on input JSON data and optionally saves a TRD (technical requirements document). Args: dir_data (str): JSON data in string format enclosed in triple backticks ("```json" "...data..." "```"). trd (str, optional): Technical requirements document content to be saved. Defaults to None. output_dir (Union[str, Path], optional): Output directory path where files will be saved. If not provided, a default directory is created based on the current timestamp and a random UUID suffix. Returns: List[str]: List of file paths where data was saved. Raises: Any exceptions raised during file writing operations. Notes: - JSON data should be provided in the format "```json ...data... ```". - The function ensures that paths and filenames are correctly formatted and creates necessary directories. Example: ```python dir_data = "```json\n[{\"path\": \"/folder\", \"filename\": \"file1.txt\", \"content\": \"Some content\"}]\n```" trd = "Technical requirements document content." output_dir = '/path/to/output/dir' saved_files = await save_framework(dir_data, trd, output_dir) print(saved_files) ``` """ output_dir = ( Path(output_dir) if output_dir else config.workspace.path / (datetime.now().strftime("%Y%m%d%H%M%ST") + uuid.uuid4().hex[0:8]) ) output_dir.mkdir(parents=True, exist_ok=True) json_data = dir_data.removeprefix("```json").removesuffix("```") items = json.loads(json_data) class Data(BaseModel): path: str filename: str content: str if trd: pathname = output_dir / "TRD.md" await awrite(filename=pathname, data=trd) files = [] for i in items: v = Data.model_validate(i) if v.path and v.path[0] == "/": v.path = "." + v.path pathname = output_dir / v.path pathname.mkdir(parents=True, exist_ok=True) pathname = pathname / v.filename await awrite(filename=pathname, data=v.content) files.append(str(pathname)) return files __all__ = [WriteFramework, EvaluateFramework]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/requirement/__init__.py
metagpt/actions/requirement_analysis/requirement/__init__.py
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/requirement/pic2txt.py
metagpt/actions/requirement_analysis/requirement/pic2txt.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/27 @Author : mashenquan @File : pic2txt.py """ import json from pathlib import Path from typing import List from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import Action from metagpt.logs import logger from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import encode_image, general_after_log, to_markdown_code_block @register_tool(include_functions=["run"]) class Pic2Txt(Action): """Pic2Txt deal with the following situations: Given some pictures depicting user requirements alongside contextual description, write out the intact textual user requirements. """ async def run( self, *, image_paths: List[str], textual_user_requirement: str = "", legacy_output: str = "", evaluation_conclusion: str = "", additional_technical_requirements: str = "", ) -> str: """ Given some pictures depicting user requirements alongside contextual description, write out the intact textual user requirements Args: image_paths (List[str]): A list of file paths to the input image(s) depicting user requirements. textual_user_requirement (str, optional): Textual user requirement that alongside the given images, if any. legacy_output (str, optional): The intact textual user requirements generated by you last time, if any. evaluation_conclusion (str, optional): Conclusion or evaluation based on the processed requirements. additional_technical_requirements (str, optional): Any supplementary technical details relevant to the process. Returns: str: Textual representation of user requirements extracted from the provided image(s). Raises: ValueError: If image_paths list is empty. OSError: If there is an issue accessing or reading the image files. Example: >>> images = ["requirements/pic/1.png", "requirements/pic/2.png", "requirements/pic/3.png"] >>> textual_user_requirements = "User requirement paragraph 1 ..., ![](1.png). paragraph 2...![](2.png)..." >>> action = Pic2Txt() >>> intact_textual_user_requirements = await action.run(image_paths=images, textual_user_requirement=textual_user_requirements) >>> print(intact_textual_user_requirements) "User requirement paragraph 1 ..., ![...](1.png) This picture describes... paragraph 2...![...](2.png)..." """ descriptions = {} for i in image_paths: filename = Path(i) base64_image = encode_image(filename) rsp = await self._pic2txt( "Generate a paragraph of text based on the content of the image, the language of the text is consistent with the language in the image.", base64_image=base64_image, ) descriptions[filename.name] = rsp prompt = PROMPT.format( textual_user_requirement=textual_user_requirement, acknowledge=to_markdown_code_block(val=json.dumps(descriptions), type_="json"), legacy_output=to_markdown_code_block(val=legacy_output), evaluation_conclusion=evaluation_conclusion, additional_technical_requirements=to_markdown_code_block(val=additional_technical_requirements), ) return await self._write(prompt) @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _write(self, prompt: str) -> str: rsp = await self.llm.aask(prompt) return rsp @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _pic2txt(self, prompt: str, base64_image: str) -> str: rsp = await self.llm.aask(prompt, images=base64_image) return rsp PROMPT = """ ## Textual User Requirements {textual_user_requirement} ## Acknowledge {acknowledge} ## Legacy Outputs {legacy_output} ## Evaluation Conclusion {evaluation_conclusion} ## Additional Technical Requirements {additional_technical_requirements} --- You are a tool that generates an intact textual user requirements given a few of textual fragments of user requirements and some fragments of UI pictures. The content of "Textual User Requirements" provides a few of textual fragments of user requirements; The content of "Acknowledge" provides the descriptions of pictures used in "Textual User Requirements"; "Legacy Outputs" contains the intact textual user requirements generated by you last time, which you can improve by addressing the issues raised in "Evaluation Conclusion"; "Additional Technical Requirements" specifies the additional technical requirements that the generated textual user requirements must meet; You need to merge the text content of the corresponding image in the "Acknowledge" into the "Textual User Requirements" to generate a complete, natural and coherent description of the user requirements; Return the intact textual user requirements according to the given fragments of the user requirement of "Textual User Requirements" and the UI pictures; """
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/trd/write_trd.py
metagpt/actions/requirement_analysis/trd/write_trd.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : write_trd.py @Desc : The implementation of Chapter 2.1.6~2.1.7 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import Action from metagpt.logs import logger from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import general_after_log, to_markdown_code_block @register_tool(include_functions=["run"]) class WriteTRD(Action): """WriteTRD deal with the following situations: 1. Given some new user requirements, write out a new TRD(Technical Requirements Document). 2. Given some incremental user requirements, update the legacy TRD. """ async def run( self, *, user_requirements: str = "", use_case_actors: str, available_external_interfaces: str, evaluation_conclusion: str = "", interaction_events: str, previous_version_trd: str = "", legacy_user_requirements: str = "", legacy_user_requirements_trd: str = "", legacy_user_requirements_interaction_events: str = "", ) -> str: """ Handles the writing or updating of a Technical Requirements Document (TRD) based on user requirements. Args: user_requirements (str): The new/incremental user requirements. use_case_actors (str): Description of the actors involved in the use case. available_external_interfaces (str): List of available external interfaces. evaluation_conclusion (str, optional): The conclusion of the evaluation of the TRD written by you. Defaults to an empty string. interaction_events (str): The interaction events related to the user requirements that you are handling. previous_version_trd (str, optional): The previous version of the TRD written by you, for updating. legacy_user_requirements (str, optional): Existing user requirements handled by an external object for your use. Defaults to an empty string. legacy_user_requirements_trd (str, optional): The TRD associated with the existing user requirements handled by an external object for your use. Defaults to an empty string. legacy_user_requirements_interaction_events (str, optional): Interaction events related to the existing user requirements handled by an external object for your use. Defaults to an empty string. Returns: str: The newly created or updated TRD written by you. Example: >>> # Given a new user requirements, write out a new TRD. >>> user_requirements = "Write a 'snake game' TRD." >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;" >>> available_external_interfaces = "The available external interfaces returned by `CompressExternalInterfaces.run` are ..." >>> previous_version_trd = "TRD ..." # The last version of the TRD written out if there is. >>> evaluation_conclusion = "Conclusion ..." # The conclusion returned by `EvaluateTRD.run` if there is. >>> interaction_events = "Interaction ..." # The interaction events returned by `DetectInteraction.run`. >>> write_trd = WriteTRD() >>> new_version_trd = await write_trd.run( >>> user_requirements=user_requirements, >>> use_case_actors=use_case_actors, >>> available_external_interfaces=available_external_interfaces, >>> evaluation_conclusion=evaluation_conclusion, >>> interaction_events=interaction_events, >>> previous_version_trd=previous_version_trd, >>> ) >>> print(new_version_trd) ## Technical Requirements Document\n ... >>> # Given an incremental requirements, update the legacy TRD. >>> legacy_user_requirements = ["User requirements 1. ...", "User requirements 2. ...", ...] >>> legacy_user_requirements_trd = "## Technical Requirements Document\\n ..." # The TRD before integrating more user requirements. >>> legacy_user_requirements_interaction_events = ["The interaction events list of user requirements 1 ...", "The interaction events list of user requiremnts 2 ...", ...] >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;" >>> available_external_interfaces = "The available external interfaces returned by `CompressExternalInterfaces.run` are ..." >>> increment_requirements = "The incremental user requirements are ..." >>> evaluation_conclusion = "Conclusion ..." # The conclusion returned by `EvaluateTRD.run` if there is. >>> previous_version_trd = "TRD ..." # The last version of the TRD written out if there is. >>> write_trd = WriteTRD() >>> new_version_trd = await write_trd.run( >>> user_requirements=increment_requirements, >>> use_case_actors=use_case_actors, >>> available_external_interfaces=available_external_interfaces, >>> evaluation_conclusion=evaluation_conclusion, >>> interaction_events=interaction_events, >>> previous_version_trd=previous_version_trd, >>> legacy_user_requirements=str(legacy_user_requirements), >>> legacy_user_requirements_trd=legacy_user_requirements_trd, >>> legacy_user_requirements_interaction_events=str(legacy_user_requirements_interaction_events), >>> ) >>> print(new_version_trd) ## Technical Requirements Document\n ... """ if legacy_user_requirements: return await self._write_incremental_trd( use_case_actors=use_case_actors, legacy_user_requirements=legacy_user_requirements, available_external_interfaces=available_external_interfaces, legacy_user_requirements_trd=legacy_user_requirements_trd, legacy_user_requirements_interaction_events=legacy_user_requirements_interaction_events, incremental_user_requirements=user_requirements, previous_version_trd=previous_version_trd, evaluation_conclusion=evaluation_conclusion, incremental_user_requirements_interaction_events=interaction_events, ) return await self._write_new_trd( use_case_actors=use_case_actors, original_user_requirement=user_requirements, available_external_interfaces=available_external_interfaces, legacy_trd=previous_version_trd, evaluation_conclusion=evaluation_conclusion, interaction_events=interaction_events, ) @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _write_new_trd( self, *, use_case_actors: str, original_user_requirement: str, available_external_interfaces: str, legacy_trd: str, evaluation_conclusion: str, interaction_events: str, ) -> str: prompt = NEW_PROMPT.format( use_case_actors=use_case_actors, original_user_requirement=to_markdown_code_block(val=original_user_requirement), available_external_interfaces=available_external_interfaces, legacy_trd=to_markdown_code_block(val=legacy_trd), evaluation_conclusion=evaluation_conclusion, interaction_events=interaction_events, ) return await self.llm.aask(prompt) @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def _write_incremental_trd( self, *, use_case_actors: str, legacy_user_requirements: str, available_external_interfaces: str, legacy_user_requirements_trd: str, legacy_user_requirements_interaction_events: str, incremental_user_requirements: str, previous_version_trd: str, evaluation_conclusion: str, incremental_user_requirements_interaction_events: str, ): prompt = INCREMENTAL_PROMPT.format( use_case_actors=use_case_actors, legacy_user_requirements=to_markdown_code_block(val=legacy_user_requirements), available_external_interfaces=available_external_interfaces, legacy_user_requirements_trd=to_markdown_code_block(val=legacy_user_requirements_trd), legacy_user_requirements_interaction_events=legacy_user_requirements_interaction_events, incremental_user_requirements=to_markdown_code_block(val=incremental_user_requirements), previous_version_trd=to_markdown_code_block(val=previous_version_trd), evaluation_conclusion=evaluation_conclusion, incremental_user_requirements_interaction_events=incremental_user_requirements_interaction_events, ) return await self.llm.aask(prompt) NEW_PROMPT = """ ## Actor, System, External System {use_case_actors} ## User Requirements {original_user_requirement} ## Available External Interfaces {available_external_interfaces} ## Legacy TRD {legacy_trd} ## Evaluation Conclusion {evaluation_conclusion} ## Interaction Events {interaction_events} --- You are a TRD generator. The content of "Actor, System, External System" provides an explanation of actors and systems that appear in UML Use Case diagram; The content of "Available External Interfaces" provides the candidate steps, along with the inputs and outputs of each step; "User Requirements" provides the original requirements description, any parts not mentioned in this description will be handled by other modules, so do not fabricate requirements; "Legacy TRD" provides the old version of the TRD based on the "User Requirements" and can serve as a reference for the new TRD; "Evaluation Conclusion" provides a summary of the evaluation of the old TRD in the "Legacy TRD" and can serve as a reference for the new TRD; "Interaction Events" provides some identified interaction events and the interacting participants based on the content of the "User Requirements"; 1. What inputs and outputs are described in the "User Requirements"? 2. How many steps are needed to achieve the inputs and outputs described in the "User Requirements"? Which actors from the "Actor, System, External System" section are involved in each step? What are the inputs and outputs of each step? Where is this output used, for example, as input for which interface or where it is required in the requirements, etc.? 3. Output a complete Technical Requirements Document (TRD): 3.1. In the description, use the actor and system names defined in the "Actor, System, External System" section to describe the interactors; 3.2. The content should include the original text of the requirements from "User Requirements"; 3.3. In the TRD, each step can involve a maximum of two participants. If there are more than two participants, the step needs to be further split; 3.4. In the TRD, each step must include detailed descriptions, inputs, outputs, participants, initiator, and the rationale for the step's existence. The rationale should reference the original text to justify it, such as specifying which interface requires the output of this step as parameters or where in the requirements this step is mandated, etc.; 3.5. In the TRD, if you need to call interfaces of external systems, you must explicitly specify the interface IDs of the external systems you want to call; """ INCREMENTAL_PROMPT = """ ## Actor, System, External System {use_case_actors} ## Legacy User Requirements {legacy_user_requirements} ## Available External Interfaces {available_external_interfaces} ## The TRD of Legacy User Requirements {legacy_user_requirements_trd} ## The Interaction Events of Legacy User Requirements {legacy_user_requirements_interaction_events} ## Incremental Requirements {incremental_user_requirements} ## Legacy TRD {previous_version_trd} ## Evaluation Conclusion {evaluation_conclusion} ## Interaction Events {incremental_user_requirements_interaction_events} --- You are a TRD generator. The content of "Actor, System, External System" provides an explanation of actors and systems that appear in UML Use Case diagram; The content of "Available External Interfaces" provides the candidate steps, along with the inputs and outputs of each step; "Legacy User Requirements" provides the original requirements description handled by other modules for your use; "The TRD of Legacy User Requirements" is the TRD generated by other modules based on the "Legacy User Requirements" for your use; "The Interaction Events of Legacy User Requirements" is the interaction events list generated by other modules based on the "Legacy User Requirements" for your use; "Incremental Requirements" provides the original requirements description that you need to address, any parts not mentioned in this description will be handled by other modules, so do not fabricate requirements; The requirements in "Legacy User Requirements" combined with the "Incremental Requirements" form a complete set of requirements, therefore, you need to add the TRD portion of the "Incremental Requirements" to "The TRD of Legacy User Requirements", the added content must not conflict with the original content of "The TRD of Legacy User Requirements"; "Legacy TRD" provides the old version of the TRD you previously wrote based on the "Incremental Requirements" and can serve as a reference for the new TRD; "Evaluation Conclusion" provides a summary of the evaluation of the old TRD you generated in the "Legacy TRD", and the identified issues can serve as a reference for the new TRD you create; "Interaction Events" provides some identified interaction events and the interacting participants based on the content of the "Incremental Requirements"; 1. What inputs and outputs are described in the "Incremental Requirements"? 2. How many steps are needed to achieve the inputs and outputs described in the "Incremental Requirements"? Which actors from the "Actor, System, External System" section are involved in each step? What are the inputs and outputs of each step? Where is this output used, for example, as input for which interface or where it is required in the requirements, etc.? 3. Output a complete Technical Requirements Document (TRD): 3.1. In the description, use the actor and system names defined in the "Actor, System, External System" section to describe the interactors; 3.2. The content should include the original text of the requirements from "User Requirements"; 3.3. In the TRD, each step can involve a maximum of two participants. If there are more than two participants, the step needs to be further split; 3.4. In the TRD, each step must include detailed descriptions, inputs, outputs, participants, initiator, and the rationale for the step's existence. The rationale should reference the original text to justify it, such as specifying which interface requires the output of this step as parameters or where in the requirements this step is mandated, etc. """
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/trd/detect_interaction.py
metagpt/actions/requirement_analysis/trd/detect_interaction.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : detect_interaction.py @Desc : The implementation of Chapter 2.1.6 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import Action from metagpt.logs import logger from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import general_after_log, to_markdown_code_block @register_tool(include_functions=["run"]) class DetectInteraction(Action): """DetectInteraction deal with the following situations: 1. Given a natural text of user requirements, it identifies the interaction events and the participants of those interactions from the original text. """ @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def run( self, *, user_requirements: str, use_case_actors: str, legacy_interaction_events: str, evaluation_conclusion: str, ) -> str: """ Identifies interaction events and participants from the user requirements. Args: user_requirements (str): A natural language text detailing the user's requirements. use_case_actors (str): A description of the actors involved in the use case. legacy_interaction_events (str): The previous version of the interaction events identified by you. evaluation_conclusion (str): The external evaluation conclusions regarding the interactions events identified by you. Returns: str: A string summarizing the identified interaction events and their participants. Example: >>> detect_interaction = DetectInteraction() >>> user_requirements = "User requirements 1. ..." >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;" >>> previous_version_interaction_events = "['interaction ...', ...]" >>> evaluation_conclusion = "Issues: ..." >>> interaction_events = await detect_interaction.run( >>> user_requirements=user_requirements, >>> use_case_actors=use_case_actors, >>> legacy_interaction_events=previous_version_interaction_events, >>> evaluation_conclusion=evaluation_conclusion, >>> ) >>> print(interaction_events) "['interaction ...', ...]" """ msg = PROMPT.format( use_case_actors=use_case_actors, original_user_requirements=to_markdown_code_block(val=user_requirements), previous_version_of_interaction_events=legacy_interaction_events, the_evaluation_conclusion_of_previous_version_of_trd=evaluation_conclusion, ) return await self.llm.aask(msg=msg) PROMPT = """ ## Actor, System, External System {use_case_actors} ## User Requirements {original_user_requirements} ## Legacy Interaction Events {previous_version_of_interaction_events} ## Evaluation Conclusion {the_evaluation_conclusion_of_previous_version_of_trd} --- You are a tool for capturing interaction events. "Actor, System, External System" provides the possible participants of the interaction event; "Legacy Interaction Events" is the contents of the interaction events that you output earlier; Some descriptions in the "Evaluation Conclusion" relate to the content of "User Requirements", and these descriptions in the "Evaluation Conclusion" address some issues regarding the content of "Legacy Interaction Events"; You need to capture the interaction events occurring in the description within the content of "User Requirements" word-for-word, including: 1. Who is interacting with whom. An interaction event has a maximum of 2 participants. If there are multiple participants, it indicates that multiple events are combined into one event and should be further split; 2. When an interaction event occurs, who is the initiator? What data did the initiator enter? 3. What data does the interaction event ultimately return according to the "User Requirements"? You can check the data flow described in the "User Requirements" to see if there are any missing interaction events; Return a markdown JSON object list, each object of the list containing: - a "name" key containing the name of the interaction event; - a "participants" key containing a string list of the names of the two participants; - a "initiator" key containing the name of the participant who initiate the interaction; - a "input" key containing a natural text description about the input data; """
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/trd/compress_external_interfaces.py
metagpt/actions/requirement_analysis/trd/compress_external_interfaces.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : compress_external_interfaces.py @Desc : The implementation of Chapter 2.1.5 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from tenacity import retry, stop_after_attempt, wait_random_exponential from metagpt.actions import Action from metagpt.logs import logger from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import general_after_log @register_tool(include_functions=["run"]) class CompressExternalInterfaces(Action): """CompressExternalInterfaces deal with the following situations: 1. Given a natural text of acknowledgement, it extracts and compresses the information about external system interfaces. """ @retry( wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), after=general_after_log(logger), ) async def run( self, *, acknowledge: str, ) -> str: """ Extracts and compresses information about external system interfaces from a given acknowledgement text. Args: acknowledge (str): A natural text of acknowledgement containing details about external system interfaces. Returns: str: A compressed version of the information about external system interfaces. Example: >>> compress_acknowledge = CompressExternalInterfaces() >>> acknowledge = "## Interfaces\\n..." >>> available_external_interfaces = await compress_acknowledge.run(acknowledge=acknowledge) >>> print(available_external_interfaces) ```json\n[\n{\n"id": 1,\n"inputs": {... """ return await self.llm.aask( msg=acknowledge, system_msgs=[ "Extracts and compresses the information about external system interfaces.", "Return a markdown JSON list of objects, each object containing:\n" '- an "id" key containing the interface id;\n' '- an "inputs" key containing a dict of input parameters that consist of name and description pairs;\n' '- an "outputs" key containing a dict of returns that consist of name and description pairs;\n', ], )
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/trd/__init__.py
metagpt/actions/requirement_analysis/trd/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : __init__.py @Desc : The implementation of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from metagpt.actions.requirement_analysis.trd.detect_interaction import DetectInteraction from metagpt.actions.requirement_analysis.trd.evaluate_trd import EvaluateTRD from metagpt.actions.requirement_analysis.trd.write_trd import WriteTRD from metagpt.actions.requirement_analysis.trd.compress_external_interfaces import CompressExternalInterfaces __all__ = [CompressExternalInterfaces, DetectInteraction, WriteTRD, EvaluateTRD]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/requirement_analysis/trd/evaluate_trd.py
metagpt/actions/requirement_analysis/trd/evaluate_trd.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/6/13 @Author : mashenquan @File : evaluate_trd.py @Desc : The implementation of Chapter 2.1.6~2.1.7 of RFC243. https://deepwisdom.feishu.cn/wiki/QobGwPkImijoyukBUKHcrYetnBb """ from metagpt.actions.requirement_analysis import EvaluateAction, EvaluationData from metagpt.tools.tool_registry import register_tool from metagpt.utils.common import to_markdown_code_block @register_tool(include_functions=["run"]) class EvaluateTRD(EvaluateAction): """EvaluateTRD deal with the following situations: 1. Given a TRD, evaluates the quality and returns a conclusion. """ async def run( self, *, user_requirements: str, use_case_actors: str, trd: str, interaction_events: str, legacy_user_requirements_interaction_events: str = "", ) -> EvaluationData: """ Evaluates the given TRD based on user requirements, use case actors, interaction events, and optionally external legacy interaction events. Args: user_requirements (str): The requirements provided by the user. use_case_actors (str): The actors involved in the use case. trd (str): The TRD (Technical Requirements Document) to be evaluated. interaction_events (str): The interaction events related to the user requirements and the TRD. legacy_user_requirements_interaction_events (str, optional): External legacy interaction events tied to the user requirements. Defaults to an empty string. Returns: EvaluationData: The conclusion of the TRD evaluation. Example: >>> evaluate_trd = EvaluateTRD() >>> user_requirements = "User requirements 1. ..." >>> use_case_actors = "- Actor: game player;\\n- System: snake game; \\n- External System: game center;" >>> trd = "## TRD\\n..." >>> interaction_events = "['interaction ...', ...]" >>> evaluation_conclusion = "Issues: ..." >>> legacy_user_requirements_interaction_events = ["user requirements 1. ...", ...] >>> evaluation = await evaluate_trd.run( >>> user_requirements=user_requirements, >>> use_case_actors=use_case_actors, >>> trd=trd, >>> interaction_events=interaction_events, >>> legacy_user_requirements_interaction_events=str(legacy_user_requirements_interaction_events), >>> ) >>> is_pass = evaluation.is_pass >>> print(is_pass) True >>> evaluation_conclusion = evaluation.conclusion >>> print(evaluation_conclusion) ## Conclustion\n balabalabala... """ prompt = PROMPT.format( use_case_actors=use_case_actors, user_requirements=to_markdown_code_block(val=user_requirements), trd=to_markdown_code_block(val=trd), legacy_user_requirements_interaction_events=legacy_user_requirements_interaction_events, interaction_events=interaction_events, ) return await self._vote(prompt) PROMPT = """ ## Actor, System, External System {use_case_actors} ## User Requirements {user_requirements} ## TRD Design {trd} ## External Interaction Events {legacy_user_requirements_interaction_events} ## Interaction Events {legacy_user_requirements_interaction_events} {interaction_events} --- You are a tool to evaluate the TRD design. "Actor, System, External System" provides the all possible participants in interaction events; "User Requirements" provides the original requirements description, any parts not mentioned in this description will be handled by other modules, so do not fabricate requirements; "External Interaction Events" is provided by an external module for your use, its content is also referred to "Interaction Events" section; The content in "External Interaction Events" can be determined to be problem-free; "External Interaction Events" provides some identified interaction events and the interacting participants based on the part of the content of the "User Requirements"; "Interaction Events" provides some identified interaction events and the interacting participants based on the content of the "User Requirements"; "TRD Design" provides a comprehensive design of the implementation steps for the original requirements, incorporating the interaction events from "Interaction Events" and adding additional steps to connect the complete upstream and downstream data flows; In order to integrate the full upstream and downstream data flow, the "TRD Design" allows for the inclusion of steps that do not appear in the original requirements description, but do not conflict with those explicitly described in the "User Requirements"; Which interactions from "Interaction Events" correspond to which steps in "TRD Design"? Please provide reasons. Which aspects of "TRD Design" and "Interaction Events" do not align with the descriptions in "User Requirements"? Please provide detailed descriptions and reasons. If the descriptions in "User Requirements" are divided into multiple steps in "TRD Design" and "Interaction Events," it can be considered compliant with the descriptions in "User Requirements" as long as it does not conflict with them; There is a possibility of missing details in the descriptions of "User Requirements". Any additional steps in "TRD Design" and "Interaction Events" are considered compliant with "User Requirements" as long as they do not conflict with the descriptions provided in "User Requirements"; If there are interaction events with external systems in "TRD Design", you must explicitly specify the ID of the external interface to use for the interaction events, the input and output parameters of the used external interface must explictly match the input and output of the interaction event; Does the sequence of steps in "Interaction Events" cause performance or cost issues? Please provide detailed descriptions and reasons; If each step of "TRD Design" has input data, its input data is provided either by the output of the previous steps or by participants of "Actor, System, External System", and there should be no passive data; Return a markdown JSON object with: - an "issues" key containing a string list of natural text about the issues that need to be addressed, found in the "TRD Design" if any exist, each issue found must provide a detailed description and include reasons; - a "conclusion" key containing the evaluation conclusion; - a "correspondence_between" key containing the judgement detail of the natural text string list about the correspondence between "Interaction Events" and "TRD Design" steps; - a "misalignment" key containing the judgement detail of the natural text string list about the misalignment with "User Requirements"; - a "is_pass" key containing a true boolean value if there is not any issue in the "TRD Design"; """
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/di/ask_review.py
metagpt/actions/di/ask_review.py
from __future__ import annotations from typing import Tuple from metagpt.actions import Action from metagpt.logs import get_human_input, logger from metagpt.schema import Message, Plan class ReviewConst: TASK_REVIEW_TRIGGER = "task" CODE_REVIEW_TRIGGER = "code" CONTINUE_WORDS = ["confirm", "continue", "c", "yes", "y"] CHANGE_WORDS = ["change"] EXIT_WORDS = ["exit"] TASK_REVIEW_INSTRUCTION = ( f"If you want to change, add, delete a task or merge tasks in the plan, say '{CHANGE_WORDS[0]} task task_id or current task, ... (things to change)' " f"If you confirm the output from the current task and wish to continue, type: {CONTINUE_WORDS[0]}" ) CODE_REVIEW_INSTRUCTION = ( f"If you want the codes to be rewritten, say '{CHANGE_WORDS[0]} ... (your change advice)' " f"If you want to leave it as is, type: {CONTINUE_WORDS[0]} or {CONTINUE_WORDS[1]}" ) EXIT_INSTRUCTION = f"If you want to terminate the process, type: {EXIT_WORDS[0]}" class AskReview(Action): async def run( self, context: list[Message] = [], plan: Plan = None, trigger: str = ReviewConst.TASK_REVIEW_TRIGGER ) -> Tuple[str, bool]: if plan: logger.info("Current overall plan:") logger.info( "\n".join( [f"{task.task_id}: {task.instruction}, is_finished: {task.is_finished}" for task in plan.tasks] ) ) logger.info("Most recent context:") latest_action = context[-1].cause_by if context and context[-1].cause_by else "" review_instruction = ( ReviewConst.TASK_REVIEW_INSTRUCTION if trigger == ReviewConst.TASK_REVIEW_TRIGGER else ReviewConst.CODE_REVIEW_INSTRUCTION ) prompt = ( f"This is a <{trigger}> review. Please review output from {latest_action}\n" f"{review_instruction}\n" f"{ReviewConst.EXIT_INSTRUCTION}\n" "Please type your review below:\n" ) rsp = await get_human_input(prompt) if rsp.lower() in ReviewConst.EXIT_WORDS: exit() # Confirmation can be one of "confirm", "continue", "c", "yes", "y" exactly, or sentences containing "confirm". # One could say "confirm this task, but change the next task to ..." confirmed = rsp.lower() in ReviewConst.CONTINUE_WORDS or ReviewConst.CONTINUE_WORDS[0] in rsp.lower() return rsp, confirmed
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/di/write_plan.py
metagpt/actions/di/write_plan.py
# -*- encoding: utf-8 -*- """ @Date : 2023/11/20 11:24:03 @Author : orange-crow @File : plan.py """ from __future__ import annotations import json from copy import deepcopy from typing import Tuple from metagpt.actions import Action from metagpt.logs import logger from metagpt.schema import Message, Plan, Task from metagpt.strategy.task_type import TaskType from metagpt.utils.common import CodeParser PROMPT_TEMPLATE: str = """ # Context: {context} # Available Task Types: {task_type_desc} # Task: Based on the context, write a plan or modify an existing plan of what you should do to achieve the goal. A plan consists of one to {max_tasks} tasks. If you are modifying an existing plan, carefully follow the instruction, don't make unnecessary changes. Give the whole plan unless instructed to modify only one task of the plan. If you encounter errors on the current task, revise and output the current single task only. Output a list of jsons following the format: ```json [ {{ "task_id": str = "unique identifier for a task in plan, can be an ordinal", "dependent_task_ids": list[str] = "ids of tasks prerequisite to this task", "instruction": "what you should do in this task, one short phrase or sentence.", "task_type": "type of this task, should be one of Available Task Types.", }}, ... ] ``` """ class WritePlan(Action): async def run(self, context: list[Message], max_tasks: int = 5) -> str: task_type_desc = "\n".join([f"- **{tt.type_name}**: {tt.value.desc}" for tt in TaskType]) prompt = PROMPT_TEMPLATE.format( context="\n".join([str(ct) for ct in context]), max_tasks=max_tasks, task_type_desc=task_type_desc ) rsp = await self._aask(prompt) rsp = CodeParser.parse_code(text=rsp) return rsp def update_plan_from_rsp(rsp: str, current_plan: Plan): rsp = json.loads(rsp) tasks = [Task(**task_config) for task_config in rsp] if len(tasks) == 1 or tasks[0].dependent_task_ids: if tasks[0].dependent_task_ids and len(tasks) > 1: # tasks[0].dependent_task_ids means the generated tasks are not a complete plan # for they depend on tasks in the current plan, in this case, we only support updating one task each time logger.warning( "Current plan will take only the first generated task if the generated tasks are not a complete plan" ) # handle a single task if current_plan.has_task_id(tasks[0].task_id): # replace an existing task current_plan.replace_task( tasks[0].task_id, tasks[0].dependent_task_ids, tasks[0].instruction, tasks[0].assignee ) else: # append one task current_plan.append_task( tasks[0].task_id, tasks[0].dependent_task_ids, tasks[0].instruction, tasks[0].assignee ) else: # add tasks in general current_plan.add_tasks(tasks) def precheck_update_plan_from_rsp(rsp: str, current_plan: Plan) -> Tuple[bool, str]: temp_plan = deepcopy(current_plan) try: update_plan_from_rsp(rsp, temp_plan) return True, "" except Exception as e: return False, e
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/di/run_command.py
metagpt/actions/di/run_command.py
from metagpt.actions import Action class RunCommand(Action): """A dummy RunCommand action used as a symbol only"""
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/di/write_analysis_code.py
metagpt/actions/di/write_analysis_code.py
# -*- encoding: utf-8 -*- """ @Date : 2023/11/20 13:19:39 @Author : orange-crow @File : write_analysis_code.py """ from __future__ import annotations from metagpt.actions import Action from metagpt.prompts.di.write_analysis_code import ( CHECK_DATA_PROMPT, DEBUG_REFLECTION_EXAMPLE, INTERPRETER_SYSTEM_MSG, REFLECTION_PROMPT, REFLECTION_SYSTEM_MSG, STRUCTUAL_PROMPT, ) from metagpt.schema import Message, Plan from metagpt.utils.common import CodeParser, remove_comments class WriteAnalysisCode(Action): async def _debug_with_reflection(self, context: list[Message], working_memory: list[Message]): reflection_prompt = REFLECTION_PROMPT.format( debug_example=DEBUG_REFLECTION_EXAMPLE, context=context, previous_impl=working_memory, ) rsp = await self._aask(reflection_prompt, system_msgs=[REFLECTION_SYSTEM_MSG]) # reflection = json.loads(CodeParser.parse_code(block=None, text=rsp)) # return reflection["improved_impl"] reflection = CodeParser.parse_code(block=None, text=rsp) return reflection async def run( self, user_requirement: str, plan_status: str = "", tool_info: str = "", working_memory: list[Message] = None, use_reflection: bool = False, memory: list[Message] = None, **kwargs, ) -> str: structual_prompt = STRUCTUAL_PROMPT.format( user_requirement=user_requirement, plan_status=plan_status, tool_info=tool_info, ) working_memory = working_memory or [] memory = memory or [] context = self.llm.format_msg(memory + [Message(content=structual_prompt, role="user")] + working_memory) # LLM call if use_reflection: code = await self._debug_with_reflection(context=context, working_memory=working_memory) else: rsp = await self.llm.aask(context, system_msgs=[INTERPRETER_SYSTEM_MSG], **kwargs) code = CodeParser.parse_code(text=rsp, lang="python") return code class CheckData(Action): async def run(self, plan: Plan) -> dict: finished_tasks = plan.get_finished_tasks() code_written = [remove_comments(task.code) for task in finished_tasks] code_written = "\n\n".join(code_written) prompt = CHECK_DATA_PROMPT.format(code_written=code_written) rsp = await self._aask(prompt) code = CodeParser.parse_code(text=rsp) return code
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/di/__init__.py
metagpt/actions/di/__init__.py
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/actions/di/execute_nb_code.py
metagpt/actions/di/execute_nb_code.py
# -*- encoding: utf-8 -*- """ @Date : 2023/11/17 14:22:15 @Author : orange-crow @File : execute_nb_code.py """ from __future__ import annotations import asyncio import base64 import re from typing import Literal, Tuple import nbformat from nbclient import NotebookClient from nbclient.exceptions import CellExecutionComplete, CellTimeoutError, DeadKernelError from nbclient.util import ensure_async from nbformat import NotebookNode from nbformat.v4 import new_code_cell, new_markdown_cell, new_output, output_from_msg from rich.box import MINIMAL from rich.console import Console, Group from rich.live import Live from rich.markdown import Markdown from rich.panel import Panel from rich.syntax import Syntax from metagpt.actions import Action from metagpt.logs import logger from metagpt.utils.report import NotebookReporter INSTALL_KEEPLEN = 500 INI_CODE = """import warnings import logging root_logger = logging.getLogger() root_logger.setLevel(logging.ERROR) warnings.filterwarnings('ignore')""" class RealtimeOutputNotebookClient(NotebookClient): """Realtime output of Notebook execution.""" def __init__(self, *args, notebook_reporter=None, **kwargs) -> None: super().__init__(*args, **kwargs) self.notebook_reporter = notebook_reporter or NotebookReporter() async def _async_poll_output_msg(self, parent_msg_id: str, cell: NotebookNode, cell_index: int) -> None: """Implement a feature to enable sending messages.""" assert self.kc is not None while True: msg = await ensure_async(self.kc.iopub_channel.get_msg(timeout=None)) await self._send_msg(msg) if msg["parent_header"].get("msg_id") == parent_msg_id: try: # Will raise CellExecutionComplete when completed self.process_message(msg, cell, cell_index) except CellExecutionComplete: return async def _send_msg(self, msg: dict): msg_type = msg.get("header", {}).get("msg_type") if msg_type not in ["stream", "error", "execute_result"]: return await self.notebook_reporter.async_report(output_from_msg(msg), "content") class ExecuteNbCode(Action): """execute notebook code block, return result to llm, and display it.""" nb: NotebookNode nb_client: RealtimeOutputNotebookClient = None console: Console interaction: str timeout: int = 600 def __init__(self, nb=nbformat.v4.new_notebook(), timeout=600): super().__init__( nb=nb, timeout=timeout, console=Console(), interaction=("ipython" if self.is_ipython() else "terminal"), ) self.reporter = NotebookReporter() self.set_nb_client() self.init_called = False async def init_code(self): if not self.init_called: await self.run(INI_CODE) self.init_called = True def set_nb_client(self): self.nb_client = RealtimeOutputNotebookClient( self.nb, timeout=self.timeout, resources={"metadata": {"path": self.config.workspace.path}}, notebook_reporter=self.reporter, coalesce_streams=True, ) async def build(self): if self.nb_client.kc is None or not await self.nb_client.kc.is_alive(): self.nb_client.create_kernel_manager() self.nb_client.start_new_kernel() self.nb_client.start_new_kernel_client() async def terminate(self): """kill NotebookClient""" if self.nb_client.km is not None and await self.nb_client.km.is_alive(): await self.nb_client.km.shutdown_kernel(now=True) await self.nb_client.km.cleanup_resources() channels = [ self.nb_client.kc.stdin_channel, # The channel for handling standard input to the kernel. self.nb_client.kc.hb_channel, # The channel for heartbeat communication between the kernel and client. self.nb_client.kc.control_channel, # The channel for controlling the kernel. ] # Stops all the running channels for this kernel for channel in channels: if channel.is_alive(): channel.stop() self.nb_client.kc = None self.nb_client.km = None async def reset(self): """reset NotebookClient""" await self.terminate() # sleep 1s to wait for the kernel to be cleaned up completely await asyncio.sleep(1) await self.build() self.set_nb_client() def add_code_cell(self, code: str): self.nb.cells.append(new_code_cell(source=code)) def add_markdown_cell(self, markdown: str): self.nb.cells.append(new_markdown_cell(source=markdown)) def _display(self, code: str, language: Literal["python", "markdown"] = "python"): if language == "python": code = Syntax(code, "python", theme="paraiso-dark", line_numbers=True) self.console.print(code) elif language == "markdown": display_markdown(code) else: raise ValueError(f"Only support for python, markdown, but got {language}") def add_output_to_cell(self, cell: NotebookNode, output: str): """add outputs of code execution to notebook cell.""" if "outputs" not in cell: cell["outputs"] = [] else: cell["outputs"].append(new_output(output_type="stream", name="stdout", text=str(output))) def parse_outputs(self, outputs: list[str], keep_len: int = 5000) -> Tuple[bool, str]: """Parses the outputs received from notebook execution.""" assert isinstance(outputs, list) parsed_output, is_success = [], True for i, output in enumerate(outputs): output_text = "" if output["output_type"] == "stream" and not any( tag in output["text"] for tag in ["| INFO | metagpt", "| ERROR | metagpt", "| WARNING | metagpt", "DEBUG"] ): output_text = output["text"] elif output["output_type"] == "display_data": if "image/png" in output["data"]: self.show_bytes_figure(output["data"]["image/png"], self.interaction) else: logger.info( f"{i}th output['data'] from nbclient outputs dont have image/png, continue next output ..." ) elif output["output_type"] == "execute_result": output_text = output["data"]["text/plain"] elif output["output_type"] == "error": output_text, is_success = "\n".join(output["traceback"]), False # handle coroutines that are not executed asynchronously if output_text.strip().startswith("<coroutine object"): output_text = "Executed code failed, you need use key word 'await' to run a async code." is_success = False output_text = remove_escape_and_color_codes(output_text) if is_success: output_text = remove_log_and_warning_lines(output_text) # The useful information of the exception is at the end, # the useful information of normal output is at the begining. if "<!DOCTYPE html>" not in output_text: output_text = output_text[:keep_len] if is_success else output_text[-keep_len:] parsed_output.append(output_text) return is_success, ",".join(parsed_output) def show_bytes_figure(self, image_base64: str, interaction_type: Literal["ipython", None]): image_bytes = base64.b64decode(image_base64) if interaction_type == "ipython": from IPython.display import Image, display display(Image(data=image_bytes)) else: import io from PIL import Image image = Image.open(io.BytesIO(image_bytes)) image.show() def is_ipython(self) -> bool: try: # 如果在Jupyter Notebook中运行,__file__ 变量不存在 from IPython import get_ipython if get_ipython() is not None and "IPKernelApp" in get_ipython().config: return True else: return False except NameError: return False async def run_cell(self, cell: NotebookNode, cell_index: int) -> Tuple[bool, str]: """set timeout for run code. returns the success or failure of the cell execution, and an optional error message. """ await self.reporter.async_report(cell, "content") try: await self.nb_client.async_execute_cell(cell, cell_index) return self.parse_outputs(self.nb.cells[-1].outputs) except CellTimeoutError: assert self.nb_client.km is not None await self.nb_client.km.interrupt_kernel() await asyncio.sleep(1) error_msg = "Cell execution timed out: Execution exceeded the time limit and was stopped; consider optimizing your code for better performance." return False, error_msg except DeadKernelError: await self.reset() return False, "DeadKernelError" except Exception: return self.parse_outputs(self.nb.cells[-1].outputs) async def run(self, code: str, language: Literal["python", "markdown"] = "python") -> Tuple[str, bool]: """ return the output of code execution, and a success indicator (bool) of code execution. """ self._display(code, language) async with self.reporter: if language == "python": # add code to the notebook self.add_code_cell(code=code) # build code executor await self.build() # run code cell_index = len(self.nb.cells) - 1 success, outputs = await self.run_cell(self.nb.cells[-1], cell_index) if "!pip" in code: success = False outputs = outputs[-INSTALL_KEEPLEN:] elif "git clone" in code: outputs = outputs[:INSTALL_KEEPLEN] + "..." + outputs[-INSTALL_KEEPLEN:] elif language == "markdown": # add markdown content to markdown cell in a notebook. self.add_markdown_cell(code) # return True, beacuse there is no execution failure for markdown cell. outputs, success = code, True else: raise ValueError(f"Only support for language: python, markdown, but got {language}, ") file_path = self.config.workspace.path / "code.ipynb" nbformat.write(self.nb, file_path) await self.reporter.async_report(file_path, "path") return outputs, success def remove_log_and_warning_lines(input_str: str) -> str: delete_lines = ["[warning]", "warning:", "[cv]", "[info]"] result = "\n".join( [line for line in input_str.split("\n") if not any(dl in line.lower() for dl in delete_lines)] ).strip() return result def remove_escape_and_color_codes(input_str: str): # 使用正则表达式去除jupyter notebook输出结果中的转义字符和颜色代码 # Use regular expressions to get rid of escape characters and color codes in jupyter notebook output. pattern = re.compile(r"\x1b\[[0-9;]*[mK]") result = pattern.sub("", input_str) return result def display_markdown(content: str): # Use regular expressions to match blocks of code one by one. matches = re.finditer(r"```(.+?)```", content, re.DOTALL) start_index = 0 content_panels = [] # Set the text background color and text color. style = "black on white" # Print the matching text and code one by one. for match in matches: text_content = content[start_index : match.start()].strip() code_content = match.group(0).strip()[3:-3] # Remove triple backticks if text_content: content_panels.append(Panel(Markdown(text_content), style=style, box=MINIMAL)) if code_content: content_panels.append(Panel(Markdown(f"```{code_content}"), style=style, box=MINIMAL)) start_index = match.end() # Print remaining text (if any). remaining_text = content[start_index:].strip() if remaining_text: content_panels.append(Panel(Markdown(remaining_text), style=style, box=MINIMAL)) # Display all panels in Live mode. with Live(auto_refresh=False, console=Console(), vertical_overflow="visible") as live: live.update(Group(*content_panels)) live.refresh()
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/memory/memory.py
metagpt/memory/memory.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/20 12:15 @Author : alexanderwu @File : memory.py @Modified By: mashenquan, 2023-11-1. According to RFC 116: Updated the type of index key. """ from collections import defaultdict from typing import DefaultDict, Iterable, Optional, Set from pydantic import BaseModel, Field, SerializeAsAny from metagpt.const import IGNORED_MESSAGE_ID from metagpt.schema import Message from metagpt.utils.common import any_to_str, any_to_str_set from metagpt.utils.exceptions import handle_exception class Memory(BaseModel): """The most basic memory: super-memory""" storage: list[SerializeAsAny[Message]] = [] index: DefaultDict[str, list[SerializeAsAny[Message]]] = Field(default_factory=lambda: defaultdict(list)) ignore_id: bool = False def add(self, message: Message): """Add a new message to storage, while updating the index""" if self.ignore_id: message.id = IGNORED_MESSAGE_ID if message in self.storage: return self.storage.append(message) if message.cause_by: self.index[message.cause_by].append(message) def add_batch(self, messages: Iterable[Message]): for message in messages: self.add(message) def get_by_role(self, role: str) -> list[Message]: """Return all messages of a specified role""" return [message for message in self.storage if message.role == role] def get_by_content(self, content: str) -> list[Message]: """Return all messages containing a specified content""" return [message for message in self.storage if content in message.content] def delete_newest(self) -> "Message": """delete the newest message from the storage""" if len(self.storage) > 0: newest_msg = self.storage.pop() if newest_msg.cause_by and newest_msg in self.index[newest_msg.cause_by]: self.index[newest_msg.cause_by].remove(newest_msg) else: newest_msg = None return newest_msg def delete(self, message: Message): """Delete the specified message from storage, while updating the index""" if self.ignore_id: message.id = IGNORED_MESSAGE_ID self.storage.remove(message) if message.cause_by and message in self.index[message.cause_by]: self.index[message.cause_by].remove(message) def clear(self): """Clear storage and index""" self.storage = [] self.index = defaultdict(list) def count(self) -> int: """Return the number of messages in storage""" return len(self.storage) def try_remember(self, keyword: str) -> list[Message]: """Try to recall all messages containing a specified keyword""" return [message for message in self.storage if keyword in message.content] def get(self, k=0) -> list[Message]: """Return the most recent k memories, return all when k=0""" return self.storage[-k:] def find_news(self, observed: list[Message], k=0) -> list[Message]: """find news (previously unseen messages) from the most recent k memories, from all memories when k=0""" already_observed = self.get(k) news: list[Message] = [] for i in observed: if i in already_observed: continue news.append(i) return news def get_by_action(self, action) -> list[Message]: """Return all messages triggered by a specified Action""" index = any_to_str(action) return self.index[index] def get_by_actions(self, actions: Set) -> list[Message]: """Return all messages triggered by specified Actions""" rsp = [] indices = any_to_str_set(actions) for action in indices: if action not in self.index: continue rsp += self.index[action] return rsp @handle_exception def get_by_position(self, position: int) -> Optional[Message]: """Returns the message at the given position if valid, otherwise returns None""" return self.storage[position]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/memory/memory_storage.py
metagpt/memory/memory_storage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Desc : the implement of memory storage """ import shutil from pathlib import Path from llama_index.core.embeddings import BaseEmbedding from metagpt.const import DATA_PATH, MEM_TTL from metagpt.logs import logger from metagpt.rag.engines.simple import SimpleEngine from metagpt.rag.schema import FAISSIndexConfig, FAISSRetrieverConfig from metagpt.schema import Message from metagpt.utils.embedding import get_embedding class MemoryStorage(object): """ The memory storage with Faiss as ANN search engine """ def __init__(self, mem_ttl: int = MEM_TTL, embedding: BaseEmbedding = None): self.role_id: str = None self.role_mem_path: str = None self.mem_ttl: int = mem_ttl # later use self.threshold: float = 0.1 # experience value. TODO The threshold to filter similar memories self._initialized: bool = False self.embedding = embedding or get_embedding() self.faiss_engine = None @property def is_initialized(self) -> bool: return self._initialized def recover_memory(self, role_id: str) -> list[Message]: self.role_id = role_id self.role_mem_path = Path(DATA_PATH / f"role_mem/{self.role_id}/") self.role_mem_path.mkdir(parents=True, exist_ok=True) self.cache_dir = self.role_mem_path if self.role_mem_path.joinpath("default__vector_store.json").exists(): self.faiss_engine = SimpleEngine.from_index( index_config=FAISSIndexConfig(persist_path=self.cache_dir), retriever_configs=[FAISSRetrieverConfig()], embed_model=self.embedding, ) else: self.faiss_engine = SimpleEngine.from_objs( objs=[], retriever_configs=[FAISSRetrieverConfig()], embed_model=self.embedding ) self._initialized = True def add(self, message: Message) -> bool: """add message into memory storage""" self.faiss_engine.add_objs([message]) logger.info(f"Role {self.role_id}'s memory_storage add a message") async def search_similar(self, message: Message, k=4) -> list[Message]: """search for similar messages""" # filter the result which score is smaller than the threshold filtered_resp = [] resp = await self.faiss_engine.aretrieve(message.content) for item in resp: if item.score < self.threshold: filtered_resp.append(item.metadata.get("obj")) return filtered_resp def clean(self): shutil.rmtree(self.cache_dir, ignore_errors=True) self._initialized = False def persist(self): if self.faiss_engine: self.faiss_engine.retriever._index.storage_context.persist(self.cache_dir)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/memory/__init__.py
metagpt/memory/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/4/30 20:57 @Author : alexanderwu @File : __init__.py """ from metagpt.memory.memory import Memory # from metagpt.memory.longterm_memory import LongTermMemory __all__ = [ "Memory", # "LongTermMemory", ]
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/memory/longterm_memory.py
metagpt/memory/longterm_memory.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Desc : the implement of Long-term memory """ from typing import Optional from pydantic import ConfigDict, Field from metagpt.logs import logger from metagpt.memory import Memory from metagpt.memory.memory_storage import MemoryStorage from metagpt.roles.role import RoleContext from metagpt.schema import Message class LongTermMemory(Memory): """ The Long-term memory for Roles - recover memory when it staruped - update memory when it changed """ model_config = ConfigDict(arbitrary_types_allowed=True) memory_storage: MemoryStorage = Field(default_factory=MemoryStorage) rc: Optional[RoleContext] = None msg_from_recover: bool = False def recover_memory(self, role_id: str, rc: RoleContext): self.memory_storage.recover_memory(role_id) self.rc = rc if not self.memory_storage.is_initialized: logger.warning(f"It may the first time to run Role {role_id}, the long-term memory is empty") else: logger.warning(f"Role {role_id} has existing memory storage and has recovered them.") self.msg_from_recover = True # self.add_batch(messages) # TODO no need self.msg_from_recover = False def add(self, message: Message): super().add(message) for action in self.rc.watch: if message.cause_by == action and not self.msg_from_recover: # currently, only add role's watching messages to its memory_storage # and ignore adding messages from recover repeatedly self.memory_storage.add(message) async def find_news(self, observed: list[Message], k=0) -> list[Message]: """ find news (previously unseen messages) from the the most recent k memories, from all memories when k=0 1. find the short-term memory(stm) news 2. furthermore, filter out similar messages based on ltm(long-term memory), get the final news """ stm_news = super().find_news(observed, k=k) # shot-term memory news if not self.memory_storage.is_initialized: # memory_storage hasn't initialized, use default `find_news` to get stm_news return stm_news ltm_news: list[Message] = [] for mem in stm_news: # filter out messages similar to those seen previously in ltm, only keep fresh news mem_searched = await self.memory_storage.search_similar(mem) if len(mem_searched) == 0: ltm_news.append(mem) return ltm_news[-k:] def persist(self): self.memory_storage.persist() def delete(self, message: Message): super().delete(message) # TODO delete message in memory_storage def clear(self): super().clear() self.memory_storage.clean()
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/memory/role_zero_memory.py
metagpt/memory/role_zero_memory.py
""" This module implements a memory system combining short-term and long-term storage for AI role memory management. It utilizes a RAG (Retrieval-Augmented Generation) engine for long-term memory storage and retrieval. """ from typing import TYPE_CHECKING, Any, Optional from pydantic import Field from metagpt.actions import UserRequirement from metagpt.const import TEAMLEADER_NAME from metagpt.logs import logger from metagpt.memory import Memory from metagpt.schema import LongTermMemoryItem, Message from metagpt.utils.common import any_to_str from metagpt.utils.exceptions import handle_exception if TYPE_CHECKING: from llama_index.core.schema import NodeWithScore from metagpt.rag.engines import SimpleEngine class RoleZeroLongTermMemory(Memory): """ Implements a memory system combining short-term and long-term storage using a RAG engine. Transfers old memories to long-term storage when short-term capacity is reached. Retrieves combined short-term and long-term memories as needed. """ persist_path: str = Field(default=".role_memory_data", description="The directory to save data.") collection_name: str = Field(default="role_zero", description="The name of the collection, such as the role name.") memory_k: int = Field(default=200, description="The capacity of short-term memory.") similarity_top_k: int = Field(default=5, description="The number of long-term memories to retrieve.") use_llm_ranker: bool = Field(default=False, description="Whether to use LLM Reranker to get better result.") _rag_engine: Any = None @property def rag_engine(self) -> "SimpleEngine": if self._rag_engine is None: self._rag_engine = self._resolve_rag_engine() return self._rag_engine def _resolve_rag_engine(self) -> "SimpleEngine": """Lazy loading of the RAG engine components, ensuring they are only loaded when needed. It uses `Chroma` for retrieval and `LLMRanker` for ranking. """ try: from metagpt.rag.engines import SimpleEngine from metagpt.rag.schema import ChromaRetrieverConfig, LLMRankerConfig except ImportError: raise ImportError("To use the RoleZeroMemory, you need to install the rag module.") retriever_configs = [ ChromaRetrieverConfig( persist_path=self.persist_path, collection_name=self.collection_name, similarity_top_k=self.similarity_top_k, ) ] ranker_configs = [LLMRankerConfig()] if self.use_llm_ranker else [] rag_engine = SimpleEngine.from_objs(retriever_configs=retriever_configs, ranker_configs=ranker_configs) return rag_engine def add(self, message: Message): """Add a new message and potentially transfer it to long-term memory.""" super().add(message) if not self._should_use_longterm_memory_for_add(): return self._transfer_to_longterm_memory() def get(self, k=0) -> list[Message]: """Return recent memories and optionally combines them with related long-term memories.""" memories = super().get(k) if not self._should_use_longterm_memory_for_get(k=k): return memories query = self._build_longterm_memory_query() related_memories = self._fetch_longterm_memories(query) logger.info(f"Fetched {len(related_memories)} long-term memories.") final_memories = related_memories + memories return final_memories def _should_use_longterm_memory_for_add(self) -> bool: """Determines if long-term memory should be used for add.""" return self.count() > self.memory_k def _should_use_longterm_memory_for_get(self, k: int) -> bool: """Determines if long-term memory should be used for get. Long-term memory is used if: - k is not 0. - The last message is from user requirement. - The count of recent memories is greater than self.memory_k. """ conds = [ k != 0, self._is_last_message_from_user_requirement(), self.count() > self.memory_k, ] return all(conds) def _transfer_to_longterm_memory(self): item = self._get_longterm_memory_item() self._add_to_longterm_memory(item) def _get_longterm_memory_item(self) -> Optional[LongTermMemoryItem]: """Retrieves the most recent message before the last k messages.""" index = -(self.memory_k + 1) message = self.get_by_position(index) return LongTermMemoryItem(message=message) if message else None @handle_exception def _add_to_longterm_memory(self, item: LongTermMemoryItem): """Adds a long-term memory item to the RAG engine. If adding long-term memory fails, it will only log the error without interrupting program execution. """ if not item or not item.message.content: return self.rag_engine.add_objs([item]) @handle_exception(default_return=[]) def _fetch_longterm_memories(self, query: str) -> list[Message]: """Fetches long-term memories based on a query. If fetching long-term memories fails, it will return the default value (an empty list) without interrupting program execution. Args: query (str): The query string to search for relevant memories. Returns: list[Message]: A list of user and AI messages related to the query. """ if not query: return [] nodes = self.rag_engine.retrieve(query) items = self._get_items_from_nodes(nodes) memories = [item.message for item in items] return memories def _get_items_from_nodes(self, nodes: list["NodeWithScore"]) -> list[LongTermMemoryItem]: """Get items from nodes and arrange them in order of their `created_at`.""" items: list[LongTermMemoryItem] = [node.metadata["obj"] for node in nodes] items.sort(key=lambda item: item.created_at) return items def _build_longterm_memory_query(self) -> str: """Build the content used to query related long-term memory. Default is to get the most recent user message, or an empty string if none is found. """ message = self._get_the_last_message() return message.content if message else "" def _get_the_last_message(self) -> Optional[Message]: if not self.count(): return None return self.get_by_position(-1) def _is_last_message_from_user_requirement(self) -> bool: """Checks if the last message is from a user requirement or sent by the team leader.""" message = self._get_the_last_message() if not message: return False is_user_message = message.is_user_message() cause_by_user_requirement = message.cause_by == any_to_str(UserRequirement) sent_from_team_leader = message.sent_from == TEAMLEADER_NAME return is_user_message and (cause_by_user_requirement or sent_from_team_leader)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/memory/brain_memory.py
metagpt/memory/brain_memory.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/8/18 @Author : mashenquan @File : brain_memory.py @Desc : Used by AgentStore. Used for long-term storage and automatic compression. @Modified By: mashenquan, 2023/9/4. + redis memory cache. @Modified By: mashenquan, 2023/12/25. Simplify Functionality. """ import json import re from typing import Dict, List, Optional from pydantic import BaseModel, Field, field_validator from metagpt.config2 import Config as _Config from metagpt.const import DEFAULT_MAX_TOKENS, DEFAULT_TOKEN_SIZE from metagpt.logs import logger from metagpt.provider import MetaGPTLLM from metagpt.provider.base_llm import BaseLLM from metagpt.schema import Message, SimpleMessage from metagpt.utils.redis import Redis class BrainMemory(BaseModel): history: List[Message] = Field(default_factory=list) knowledge: List[Message] = Field(default_factory=list) historical_summary: str = "" last_history_id: str = "" is_dirty: bool = False last_talk: Optional[str] = None cacheable: bool = True llm: Optional[BaseLLM] = Field(default=None, exclude=True) config: Optional[_Config] = None @field_validator("config") @classmethod def set_default_config(cls, config): return config if config else _Config.default() class Config: arbitrary_types_allowed = True def add_talk(self, msg: Message): """ Add message from user. """ msg.role = "user" self.add_history(msg) self.is_dirty = True def add_answer(self, msg: Message): """Add message from LLM""" msg.role = "assistant" self.add_history(msg) self.is_dirty = True def get_knowledge(self) -> str: texts = [m.content for m in self.knowledge] return "\n".join(texts) async def loads(self, redis_key: str) -> "BrainMemory": redis = Redis(self.config.redis) if not redis_key: return BrainMemory() v = await redis.get(key=redis_key) logger.debug(f"REDIS GET {redis_key} {v}") if v: bm = BrainMemory.parse_raw(v) bm.is_dirty = False return bm return BrainMemory() async def dumps(self, redis_key: str, timeout_sec: int = 30 * 60): if not self.is_dirty: return redis = Redis(self.config.redis) if not redis_key: return False v = self.model_dump_json() if self.cacheable: await redis.set(key=redis_key, data=v, timeout_sec=timeout_sec) logger.debug(f"REDIS SET {redis_key} {v}") self.is_dirty = False @staticmethod def to_redis_key(prefix: str, user_id: str, chat_id: str): return f"{prefix}:{user_id}:{chat_id}" async def set_history_summary(self, history_summary, redis_key): if self.historical_summary == history_summary: if self.is_dirty: await self.dumps(redis_key=redis_key) self.is_dirty = False return self.historical_summary = history_summary self.history = [] await self.dumps(redis_key=redis_key) self.is_dirty = False def add_history(self, msg: Message): if msg.id: if self.to_int(msg.id, 0) <= self.to_int(self.last_history_id, -1): return self.history.append(msg) self.last_history_id = str(msg.id) self.is_dirty = True def exists(self, text) -> bool: for m in reversed(self.history): if m.content == text: return True return False @staticmethod def to_int(v, default_value): try: return int(v) except: return default_value def pop_last_talk(self): v = self.last_talk self.last_talk = None return v async def summarize(self, llm, max_words=200, keep_language: bool = False, limit: int = -1, **kwargs): if isinstance(llm, MetaGPTLLM): return await self._metagpt_summarize(max_words=max_words) self.llm = llm return await self._openai_summarize(llm=llm, max_words=max_words, keep_language=keep_language, limit=limit) async def _openai_summarize(self, llm, max_words=200, keep_language: bool = False, limit: int = -1): texts = [self.historical_summary] for m in self.history: texts.append(m.content) text = "\n".join(texts) text_length = len(text) if limit > 0 and text_length < limit: return text summary = await self._summarize(text=text, max_words=max_words, keep_language=keep_language, limit=limit) if summary: await self.set_history_summary(history_summary=summary, redis_key=self.config.redis_key) return summary raise ValueError(f"text too long:{text_length}") async def _metagpt_summarize(self, max_words=200): if not self.history: return "" total_length = 0 msgs = [] for m in reversed(self.history): delta = len(m.content) if total_length + delta > max_words: left = max_words - total_length if left == 0: break m.content = m.content[0:left] msgs.append(m) break msgs.append(m) total_length += delta msgs.reverse() self.history = msgs self.is_dirty = True await self.dumps(redis_key=self.config.redis.key) self.is_dirty = False return BrainMemory.to_metagpt_history_format(self.history) @staticmethod def to_metagpt_history_format(history) -> str: mmsg = [SimpleMessage(role=m.role, content=m.content).model_dump() for m in history] return json.dumps(mmsg, ensure_ascii=False) async def get_title(self, llm, max_words=5, **kwargs) -> str: """Generate text title""" if isinstance(llm, MetaGPTLLM): return self.history[0].content if self.history else "New" summary = await self.summarize(llm=llm, max_words=500) language = self.config.language command = f"Translate the above summary into a {language} title of less than {max_words} words." summaries = [summary, command] msg = "\n".join(summaries) logger.debug(f"title ask:{msg}") response = await llm.aask(msg=msg, system_msgs=[], stream=False) logger.debug(f"title rsp: {response}") return response async def is_related(self, text1, text2, llm): if isinstance(llm, MetaGPTLLM): return await self._metagpt_is_related(text1=text1, text2=text2, llm=llm) return await self._openai_is_related(text1=text1, text2=text2, llm=llm) @staticmethod async def _metagpt_is_related(**kwargs): return False @staticmethod async def _openai_is_related(text1, text2, llm, **kwargs): context = f"## Paragraph 1\n{text2}\n---\n## Paragraph 2\n{text1}\n" rsp = await llm.aask( msg=context, system_msgs=[ "You are a tool capable of determining whether two paragraphs are semantically related." 'Return "TRUE" if "Paragraph 1" is semantically relevant to "Paragraph 2", otherwise return "FALSE".' ], stream=False, ) result = True if "TRUE" in rsp else False p2 = text2.replace("\n", "") p1 = text1.replace("\n", "") logger.info(f"IS_RELATED:\nParagraph 1: {p2}\nParagraph 2: {p1}\nRESULT: {result}\n") return result async def rewrite(self, sentence: str, context: str, llm): if isinstance(llm, MetaGPTLLM): return await self._metagpt_rewrite(sentence=sentence, context=context, llm=llm) return await self._openai_rewrite(sentence=sentence, context=context, llm=llm) @staticmethod async def _metagpt_rewrite(sentence: str, **kwargs): return sentence @staticmethod async def _openai_rewrite(sentence: str, context: str, llm): prompt = f"## Context\n{context}\n---\n## Sentence\n{sentence}\n" rsp = await llm.aask( msg=prompt, system_msgs=[ 'You are a tool augmenting the "Sentence" with information from the "Context".', "Do not supplement the context with information that is not present, especially regarding the subject and object.", "Return the augmented sentence.", ], stream=False, ) logger.info(f"REWRITE:\nCommand: {prompt}\nRESULT: {rsp}\n") return rsp @staticmethod def extract_info(input_string, pattern=r"\[([A-Z]+)\]:\s*(.+)"): match = re.match(pattern, input_string) if match: return match.group(1), match.group(2) else: return None, input_string @property def is_history_available(self): return bool(self.history or self.historical_summary) @property def history_text(self): if len(self.history) == 0 and not self.historical_summary: return "" texts = [self.historical_summary] if self.historical_summary else [] for m in self.history[:-1]: if isinstance(m, Dict): t = Message(**m).content elif isinstance(m, Message): t = m.content else: continue texts.append(t) return "\n".join(texts) async def _summarize(self, text: str, max_words=200, keep_language: bool = False, limit: int = -1) -> str: max_token_count = DEFAULT_MAX_TOKENS max_count = 100 text_length = len(text) if limit > 0 and text_length < limit: return text summary = "" while max_count > 0: if text_length < max_token_count: summary = await self._get_summary(text=text, max_words=max_words, keep_language=keep_language) break padding_size = 20 if max_token_count > 20 else 0 text_windows = self.split_texts(text, window_size=max_token_count - padding_size) part_max_words = min(int(max_words / len(text_windows)) + 1, 100) summaries = [] for ws in text_windows: response = await self._get_summary(text=ws, max_words=part_max_words, keep_language=keep_language) summaries.append(response) if len(summaries) == 1: summary = summaries[0] break # Merged and retry text = "\n".join(summaries) text_length = len(text) max_count -= 1 # safeguard return summary async def _get_summary(self, text: str, max_words=20, keep_language: bool = False): """Generate text summary""" if len(text) < max_words: return text system_msgs = [ "You are a tool for summarizing and abstracting text.", f"Return the summarized text to less than {max_words} words.", ] if keep_language: system_msgs.append("The generated summary should be in the same language as the original text.") response = await self.llm.aask(msg=text, system_msgs=system_msgs, stream=False) logger.debug(f"{text}\nsummary rsp: {response}") return response @staticmethod def split_texts(text: str, window_size) -> List[str]: """Splitting long text into sliding windows text""" if window_size <= 0: window_size = DEFAULT_TOKEN_SIZE total_len = len(text) if total_len <= window_size: return [text] padding_size = 20 if window_size > 20 else 0 windows = [] idx = 0 data_len = window_size - padding_size while idx < total_len: if window_size + idx > total_len: # 不足一个滑窗 windows.append(text[idx:]) break # 每个窗口少算padding_size自然就可实现滑窗功能, 比如: [1, 2, 3, 4, 5, 6, 7, ....] # window_size=3, padding_size=1: # [1, 2, 3], [3, 4, 5], [5, 6, 7], .... # idx=2, | idx=5 | idx=8 | ... w = text[idx : idx + window_size] windows.append(w) idx += data_len return windows
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/token_counter.py
metagpt/utils/token_counter.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/5/18 00:40 @Author : alexanderwu @File : token_counter.py ref1: https://openai.com/pricing ref2: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb ref3: https://github.com/Significant-Gravitas/Auto-GPT/blob/master/autogpt/llm/token_counter.py ref4: https://github.com/hwchase17/langchain/blob/master/langchain/chat_models/openai.py ref5: https://ai.google.dev/models/gemini """ import anthropic import tiktoken from metagpt.logs import logger TOKEN_COSTS = { "anthropic/claude-3.5-sonnet": {"prompt": 0.003, "completion": 0.015}, "gpt-3.5-turbo": {"prompt": 0.0015, "completion": 0.002}, "gpt-3.5-turbo-0301": {"prompt": 0.0015, "completion": 0.002}, "gpt-3.5-turbo-0613": {"prompt": 0.0015, "completion": 0.002}, "gpt-3.5-turbo-16k": {"prompt": 0.003, "completion": 0.004}, "gpt-3.5-turbo-16k-0613": {"prompt": 0.003, "completion": 0.004}, "gpt-35-turbo": {"prompt": 0.0015, "completion": 0.002}, "gpt-35-turbo-16k": {"prompt": 0.003, "completion": 0.004}, "gpt-3.5-turbo-1106": {"prompt": 0.001, "completion": 0.002}, "gpt-3.5-turbo-0125": {"prompt": 0.001, "completion": 0.002}, "gpt-4-0314": {"prompt": 0.03, "completion": 0.06}, "gpt-4": {"prompt": 0.03, "completion": 0.06}, "gpt-4-32k": {"prompt": 0.06, "completion": 0.12}, "gpt-4-32k-0314": {"prompt": 0.06, "completion": 0.12}, "gpt-4-0613": {"prompt": 0.06, "completion": 0.12}, "gpt-4-turbo-preview": {"prompt": 0.01, "completion": 0.03}, "gpt-4-1106-preview": {"prompt": 0.01, "completion": 0.03}, "gpt-4-0125-preview": {"prompt": 0.01, "completion": 0.03}, "gpt-4-turbo": {"prompt": 0.01, "completion": 0.03}, "gpt-4-turbo-2024-04-09": {"prompt": 0.01, "completion": 0.03}, "gpt-4-vision-preview": {"prompt": 0.01, "completion": 0.03}, # TODO add extra image price calculator "gpt-4-1106-vision-preview": {"prompt": 0.01, "completion": 0.03}, "gpt-4o": {"prompt": 0.005, "completion": 0.015}, "gpt-4o-mini": {"prompt": 0.00015, "completion": 0.0006}, "gpt-4o-mini-2024-07-18": {"prompt": 0.00015, "completion": 0.0006}, "gpt-4o-2024-05-13": {"prompt": 0.005, "completion": 0.015}, "gpt-4o-2024-08-06": {"prompt": 0.0025, "completion": 0.01}, "o1-preview": {"prompt": 0.015, "completion": 0.06}, "o1-preview-2024-09-12": {"prompt": 0.015, "completion": 0.06}, "o1-mini": {"prompt": 0.003, "completion": 0.012}, "o1-mini-2024-09-12": {"prompt": 0.003, "completion": 0.012}, "text-embedding-ada-002": {"prompt": 0.0004, "completion": 0.0}, "glm-3-turbo": {"prompt": 0.0007, "completion": 0.0007}, # 128k version, prompt + completion tokens=0.005¥/k-tokens "glm-4": {"prompt": 0.014, "completion": 0.014}, # 128k version, prompt + completion tokens=0.1¥/k-tokens "glm-4-flash": {"prompt": 0, "completion": 0}, "glm-4-plus": {"prompt": 0.007, "completion": 0.007}, "gemini-1.5-flash": {"prompt": 0.000075, "completion": 0.0003}, "gemini-1.5-pro": {"prompt": 0.0035, "completion": 0.0105}, "gemini-1.0-pro": {"prompt": 0.0005, "completion": 0.0015}, "moonshot-v1-8k": {"prompt": 0.012, "completion": 0.012}, # prompt + completion tokens=0.012¥/k-tokens "moonshot-v1-32k": {"prompt": 0.024, "completion": 0.024}, "moonshot-v1-128k": {"prompt": 0.06, "completion": 0.06}, "open-mistral-7b": {"prompt": 0.00025, "completion": 0.00025}, "open-mixtral-8x7b": {"prompt": 0.0007, "completion": 0.0007}, "mistral-small-latest": {"prompt": 0.002, "completion": 0.006}, "mistral-medium-latest": {"prompt": 0.0027, "completion": 0.0081}, "mistral-large-latest": {"prompt": 0.008, "completion": 0.024}, "claude-instant-1.2": {"prompt": 0.0008, "completion": 0.0024}, "claude-2.0": {"prompt": 0.008, "completion": 0.024}, "claude-2.1": {"prompt": 0.008, "completion": 0.024}, "claude-3-sonnet-20240229": {"prompt": 0.003, "completion": 0.015}, "claude-3-5-sonnet": {"prompt": 0.003, "completion": 0.015}, "claude-3-5-sonnet-v2": {"prompt": 0.003, "completion": 0.015}, # alias of newer 3.5 sonnet "claude-3-5-sonnet-20240620": {"prompt": 0.003, "completion": 0.015}, "claude-3-opus-20240229": {"prompt": 0.015, "completion": 0.075}, "claude-3-haiku-20240307": {"prompt": 0.00025, "completion": 0.00125}, "claude-3-7-sonnet-20250219": {"prompt": 0.003, "completion": 0.015}, "yi-34b-chat-0205": {"prompt": 0.0003, "completion": 0.0003}, "yi-34b-chat-200k": {"prompt": 0.0017, "completion": 0.0017}, "openai/gpt-4": {"prompt": 0.03, "completion": 0.06}, # start, for openrouter "openai/gpt-4-turbo": {"prompt": 0.01, "completion": 0.03}, "openai/gpt-4o": {"prompt": 0.005, "completion": 0.015}, "openai/gpt-4o-2024-05-13": {"prompt": 0.005, "completion": 0.015}, "openai/gpt-4o-mini": {"prompt": 0.00015, "completion": 0.0006}, "openai/gpt-4o-mini-2024-07-18": {"prompt": 0.00015, "completion": 0.0006}, "google/gemini-flash-1.5": {"prompt": 0.00025, "completion": 0.00075}, "deepseek/deepseek-coder": {"prompt": 0.00014, "completion": 0.00028}, "deepseek/deepseek-chat": {"prompt": 0.00014, "completion": 0.00028}, # end, for openrouter "yi-large": {"prompt": 0.0028, "completion": 0.0028}, "microsoft/wizardlm-2-8x22b": {"prompt": 0.00108, "completion": 0.00108}, # for openrouter, start "meta-llama/llama-3-70b-instruct": {"prompt": 0.008, "completion": 0.008}, "llama3-70b-8192": {"prompt": 0.0059, "completion": 0.0079}, "openai/gpt-3.5-turbo-0125": {"prompt": 0.0005, "completion": 0.0015}, "openai/gpt-4-turbo-preview": {"prompt": 0.01, "completion": 0.03}, "openai/o1-preview": {"prompt": 0.015, "completion": 0.06}, "openai/o1-mini": {"prompt": 0.003, "completion": 0.012}, "anthropic/claude-3-opus": {"prompt": 0.015, "completion": 0.075}, "anthropic.claude-3-5-sonnet-20241022-v2:0": {"prompt": 0.003, "completion": 0.015}, "us.anthropic.claude-3-5-sonnet-20241022-v2:0": {"prompt": 0.003, "completion": 0.015}, "anthropic/claude-3.7-sonnet": {"prompt": 0.003, "completion": 0.015}, "anthropic/claude-3.7-sonnet:beta": {"prompt": 0.003, "completion": 0.015}, "anthropic/claude-3.7-sonnet:thinking": {"prompt": 0.003, "completion": 0.015}, "anthropic.claude-3-7-sonnet-20250219-v1:0": {"prompt": 0.003, "completion": 0.015}, "us.anthropic.claude-3-7-sonnet-20250219-v1:0": {"prompt": 0.003, "completion": 0.015}, "google/gemini-pro-1.5": {"prompt": 0.0025, "completion": 0.0075}, # for openrouter, end "deepseek-chat": {"prompt": 0.00027, "completion": 0.0011}, "deepseek-coder": {"prompt": 0.00027, "completion": 0.0011}, "deepseek-reasoner": {"prompt": 0.00055, "completion": 0.0022}, # For ark model https://www.volcengine.com/docs/82379/1099320 "doubao-lite-4k-240515": {"prompt": 0.000043, "completion": 0.000086}, "doubao-lite-32k-240515": {"prompt": 0.000043, "completion": 0.000086}, "doubao-lite-128k-240515": {"prompt": 0.00011, "completion": 0.00014}, "doubao-pro-4k-240515": {"prompt": 0.00011, "completion": 0.00029}, "doubao-pro-32k-240515": {"prompt": 0.00011, "completion": 0.00029}, "doubao-pro-128k-240515": {"prompt": 0.0007, "completion": 0.0013}, "llama3-70b-llama3-70b-instruct": {"prompt": 0.0, "completion": 0.0}, "llama3-8b-llama3-8b-instruct": {"prompt": 0.0, "completion": 0.0}, "llama-4-Scout-17B-16E-Instruct-FP8" : {"prompt": 0.0, "completion": 0.0}, # start, for Llama API "llama-4-Maverick-17B-128E-Instruct-FP8": {"prompt": 0.0, "completion": 0.0}, "llama-3.3-8B-Instruct": {"prompt": 0.0, "completion": 0.0}, "llama-3.3-70B-Instruct": {"prompt": 0.0, "completion": 0.0}, # end, for Llama API } """ QianFan Token Price https://cloud.baidu.com/doc/WENXINWORKSHOP/s/hlrk4akp7#tokens%E5%90%8E%E4%BB%98%E8%B4%B9 Due to QianFan has multi price strategies, we unify `Tokens post-payment` as a statistical method. """ QIANFAN_MODEL_TOKEN_COSTS = { "ERNIE-Bot-4": {"prompt": 0.017, "completion": 0.017}, "ERNIE-Bot-8k": {"prompt": 0.0034, "completion": 0.0067}, "ERNIE-Bot": {"prompt": 0.0017, "completion": 0.0017}, "ERNIE-Bot-turbo": {"prompt": 0.0011, "completion": 0.0011}, "EB-turbo-AppBuilder": {"prompt": 0.0011, "completion": 0.0011}, "ERNIE-Speed": {"prompt": 0.00056, "completion": 0.0011}, "BLOOMZ-7B": {"prompt": 0.00056, "completion": 0.00056}, "Llama-2-7B-Chat": {"prompt": 0.00056, "completion": 0.00056}, "Llama-2-13B-Chat": {"prompt": 0.00084, "completion": 0.00084}, "Llama-2-70B-Chat": {"prompt": 0.0049, "completion": 0.0049}, "ChatGLM2-6B-32K": {"prompt": 0.00056, "completion": 0.00056}, "AquilaChat-7B": {"prompt": 0.00056, "completion": 0.00056}, "Mixtral-8x7B-Instruct": {"prompt": 0.0049, "completion": 0.0049}, "SQLCoder-7B": {"prompt": 0.00056, "completion": 0.00056}, "CodeLlama-7B-Instruct": {"prompt": 0.00056, "completion": 0.00056}, "XuanYuan-70B-Chat-4bit": {"prompt": 0.0049, "completion": 0.0049}, "Qianfan-BLOOMZ-7B-compressed": {"prompt": 0.00056, "completion": 0.00056}, "Qianfan-Chinese-Llama-2-7B": {"prompt": 0.00056, "completion": 0.00056}, "Qianfan-Chinese-Llama-2-13B": {"prompt": 0.00084, "completion": 0.00084}, "ChatLaw": {"prompt": 0.0011, "completion": 0.0011}, "Yi-34B-Chat": {"prompt": 0.0, "completion": 0.0}, } QIANFAN_ENDPOINT_TOKEN_COSTS = { "completions_pro": QIANFAN_MODEL_TOKEN_COSTS["ERNIE-Bot-4"], "ernie_bot_8k": QIANFAN_MODEL_TOKEN_COSTS["ERNIE-Bot-8k"], "completions": QIANFAN_MODEL_TOKEN_COSTS["ERNIE-Bot"], "eb-instant": QIANFAN_MODEL_TOKEN_COSTS["ERNIE-Bot-turbo"], "ai_apaas": QIANFAN_MODEL_TOKEN_COSTS["EB-turbo-AppBuilder"], "ernie_speed": QIANFAN_MODEL_TOKEN_COSTS["ERNIE-Speed"], "bloomz_7b1": QIANFAN_MODEL_TOKEN_COSTS["BLOOMZ-7B"], "llama_2_7b": QIANFAN_MODEL_TOKEN_COSTS["Llama-2-7B-Chat"], "llama_2_13b": QIANFAN_MODEL_TOKEN_COSTS["Llama-2-13B-Chat"], "llama_2_70b": QIANFAN_MODEL_TOKEN_COSTS["Llama-2-70B-Chat"], "chatglm2_6b_32k": QIANFAN_MODEL_TOKEN_COSTS["ChatGLM2-6B-32K"], "aquilachat_7b": QIANFAN_MODEL_TOKEN_COSTS["AquilaChat-7B"], "mixtral_8x7b_instruct": QIANFAN_MODEL_TOKEN_COSTS["Mixtral-8x7B-Instruct"], "sqlcoder_7b": QIANFAN_MODEL_TOKEN_COSTS["SQLCoder-7B"], "codellama_7b_instruct": QIANFAN_MODEL_TOKEN_COSTS["CodeLlama-7B-Instruct"], "xuanyuan_70b_chat": QIANFAN_MODEL_TOKEN_COSTS["XuanYuan-70B-Chat-4bit"], "qianfan_bloomz_7b_compressed": QIANFAN_MODEL_TOKEN_COSTS["Qianfan-BLOOMZ-7B-compressed"], "qianfan_chinese_llama_2_7b": QIANFAN_MODEL_TOKEN_COSTS["Qianfan-Chinese-Llama-2-7B"], "qianfan_chinese_llama_2_13b": QIANFAN_MODEL_TOKEN_COSTS["Qianfan-Chinese-Llama-2-13B"], "chatlaw": QIANFAN_MODEL_TOKEN_COSTS["ChatLaw"], "yi_34b_chat": QIANFAN_MODEL_TOKEN_COSTS["Yi-34B-Chat"], } """ DashScope Token price https://help.aliyun.com/zh/dashscope/developer-reference/tongyi-thousand-questions-metering-and-billing Different model has different detail page. Attention, some model are free for a limited time. Some new model published by Alibaba will be prioritized to be released on the Model Studio instead of the Dashscope. Token price on Model Studio shows on https://help.aliyun.com/zh/model-studio/getting-started/models#ced16cb6cdfsy """ DASHSCOPE_TOKEN_COSTS = { "qwen2.5-72b-instruct": {"prompt": 0.00057, "completion": 0.0017}, # per 1k tokens "qwen2.5-32b-instruct": {"prompt": 0.0005, "completion": 0.001}, "qwen2.5-14b-instruct": {"prompt": 0.00029, "completion": 0.00086}, "qwen2.5-7b-instruct": {"prompt": 0.00014, "completion": 0.00029}, "qwen2.5-3b-instruct": {"prompt": 0.0, "completion": 0.0}, "qwen2.5-1.5b-instruct": {"prompt": 0.0, "completion": 0.0}, "qwen2.5-0.5b-instruct": {"prompt": 0.0, "completion": 0.0}, "qwen2-72b-instruct": {"prompt": 0.000714, "completion": 0.001428}, "qwen2-57b-a14b-instruct": {"prompt": 0.0005, "completion": 0.001}, "qwen2-7b-instruct": {"prompt": 0.000143, "completion": 0.000286}, "qwen2-1.5b-instruct": {"prompt": 0, "completion": 0}, "qwen2-0.5b-instruct": {"prompt": 0, "completion": 0}, "qwen1.5-110b-chat": {"prompt": 0.001, "completion": 0.002}, "qwen1.5-72b-chat": {"prompt": 0.000714, "completion": 0.001428}, "qwen1.5-32b-chat": {"prompt": 0.0005, "completion": 0.001}, "qwen1.5-14b-chat": {"prompt": 0.000286, "completion": 0.000571}, "qwen1.5-7b-chat": {"prompt": 0.000143, "completion": 0.000286}, "qwen1.5-1.8b-chat": {"prompt": 0, "completion": 0}, "qwen1.5-0.5b-chat": {"prompt": 0, "completion": 0}, "qwen-turbo": {"prompt": 0.00028, "completion": 0.00083}, "qwen-long": {"prompt": 0.00007, "completion": 0.00028}, "qwen-plus": {"prompt": 0.00055, "completion": 0.00166}, "qwen-max": {"prompt": 0.0055, "completion": 0.0166}, "qwen-max-0428": {"prompt": 0.0055, "completion": 0.0166}, "qwen-max-0403": {"prompt": 0.0055, "completion": 0.0166}, "qwen-max-0107": {"prompt": 0.0055, "completion": 0.0166}, "qwen-max-1201": {"prompt": 0.0166, "completion": 0.0166}, "qwen-max-longcontext": {"prompt": 0.0055, "completion": 0.0166}, "llama2-7b-chat-v2": {"prompt": 0.0, "completion": 0.0}, "llama2-13b-chat-v2": {"prompt": 0.0, "completion": 0.0}, "qwen-72b-chat": {"prompt": 0.0028, "completion": 0.0028}, "qwen-14b-chat": {"prompt": 0.0011, "completion": 0.0011}, "qwen-7b-chat": {"prompt": 0.00084, "completion": 0.00084}, "qwen-1.8b-chat": {"prompt": 0.0, "completion": 0.0}, "baichuan2-13b-chat-v1": {"prompt": 0.0011, "completion": 0.0011}, "baichuan2-7b-chat-v1": {"prompt": 0.00084, "completion": 0.00084}, "baichuan-7b-v1": {"prompt": 0.0, "completion": 0.0}, "chatglm-6b-v2": {"prompt": 0.0011, "completion": 0.0011}, "chatglm3-6b": {"prompt": 0.0, "completion": 0.0}, "ziya-llama-13b-v1": {"prompt": 0.0, "completion": 0.0}, # no price page, judge it as free "dolly-12b-v2": {"prompt": 0.0, "completion": 0.0}, "belle-llama-13b-2m-v1": {"prompt": 0.0, "completion": 0.0}, "moss-moon-003-sft-v1": {"prompt": 0.0, "completion": 0.0}, "chatyuan-large-v2": {"prompt": 0.0, "completion": 0.0}, "billa-7b-sft-v1": {"prompt": 0.0, "completion": 0.0}, } FIREWORKS_GRADE_TOKEN_COSTS = { "-1": {"prompt": 0.0, "completion": 0.0}, # abnormal condition "16": {"prompt": 0.2, "completion": 0.8}, # 16 means model size <= 16B; 0.2 means $0.2/1M tokens "80": {"prompt": 0.7, "completion": 2.8}, # 80 means 16B < model size <= 80B "mixtral-8x7b": {"prompt": 0.4, "completion": 1.6}, } # https://console.volcengine.com/ark/region:ark+cn-beijing/model DOUBAO_TOKEN_COSTS = { "doubao-lite": {"prompt": 0.000043, "completion": 0.000086}, "doubao-lite-128k": {"prompt": 0.00011, "completion": 0.00014}, "doubao-pro": {"prompt": 0.00011, "completion": 0.00029}, "doubao-pro-128k": {"prompt": 0.00071, "completion": 0.0013}, "doubao-pro-256k": {"prompt": 0.00071, "completion": 0.0013}, } # https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo TOKEN_MAX = { "o1-preview": 128000, "o1-preview-2024-09-12": 128000, "o1-mini": 128000, "o1-mini-2024-09-12": 128000, "gpt-4o": 128000, "gpt-4o-2024-05-13": 128000, "gpt-4o-2024-08-06": 128000, "gpt-4o-mini-2024-07-18": 128000, "gpt-4o-mini": 128000, "gpt-4-turbo-2024-04-09": 128000, "gpt-4-0125-preview": 128000, "gpt-4-turbo-preview": 128000, "gpt-4-1106-preview": 128000, "gpt-4-turbo": 128000, "gpt-4-vision-preview": 128000, "gpt-4-1106-vision-preview": 128000, "gpt-4": 8192, "gpt-4-0613": 8192, "gpt-4-32k": 32768, "gpt-4-32k-0613": 32768, "gpt-3.5-turbo-0125": 16385, "gpt-3.5-turbo": 16385, "gpt-3.5-turbo-1106": 16385, "gpt-3.5-turbo-instruct": 4096, "gpt-3.5-turbo-16k": 16385, "gpt-3.5-turbo-0613": 4096, "gpt-3.5-turbo-16k-0613": 16385, "text-embedding-ada-002": 8192, "glm-3-turbo": 128000, "glm-4": 128000, "gemini-1.5-flash": 1000000, "gemini-1.5-pro": 2000000, "gemini-1.0-pro": 32000, "moonshot-v1-8k": 8192, "moonshot-v1-32k": 32768, "moonshot-v1-128k": 128000, "open-mistral-7b": 8192, "open-mixtral-8x7b": 32768, "mistral-small-latest": 32768, "mistral-medium-latest": 32768, "mistral-large-latest": 32768, "claude-instant-1.2": 100000, "claude-2.0": 100000, "claude-2.1": 200000, "claude-3-sonnet-20240229": 200000, "claude-3-opus-20240229": 200000, "claude-3-5-sonnet-20240620": 200000, "claude-3-haiku-20240307": 200000, "yi-34b-chat-0205": 4000, "yi-34b-chat-200k": 200000, "openai/gpt-4": 8192, # start, for openrouter "openai/gpt-4-turbo": 128000, "openai/gpt-4o": 128000, "openai/gpt-4o-2024-05-13": 128000, "openai/gpt-4o-mini": 128000, "openai/gpt-4o-mini-2024-07-18": 128000, "google/gemini-flash-1.5": 2800000, "deepseek/deepseek-coder": 128000, "deepseek/deepseek-chat": 128000, # end, for openrouter "deepseek-chat": 128000, "deepseek-coder": 128000, "deepseek-ai/DeepSeek-Coder-V2-Instruct": 32000, # siliconflow "yi-large": 16385, "microsoft/wizardlm-2-8x22b": 65536, "meta-llama/llama-3-70b-instruct": 8192, "llama3-70b-8192": 8192, "openai/gpt-3.5-turbo-0125": 16385, "openai/gpt-4-turbo-preview": 128000, "openai/o1-preview": 128000, "openai/o1-mini": 128000, "anthropic/claude-3-opus": 200000, "anthropic/claude-3.5-sonnet": 200000, "google/gemini-pro-1.5": 4000000, "doubao-lite-4k-240515": 4000, "doubao-lite-32k-240515": 32000, "doubao-lite-128k-240515": 128000, "doubao-pro-4k-240515": 4000, "doubao-pro-32k-240515": 32000, "doubao-pro-128k-240515": 128000, # Qwen https://help.aliyun.com/zh/dashscope/developer-reference/tongyi-qianwen-7b-14b-72b-api-detailes?spm=a2c4g.11186623.0.i20 "qwen2.5-72b-instruct": 131072, "qwen2.5-32b-instruct": 131072, "qwen2.5-14b-instruct": 131072, "qwen2.5-7b-instruct": 131072, "qwen2.5-3b-instruct": 32768, "qwen2.5-1.5b-instruct": 32768, "qwen2.5-0.5b-instruct": 32768, "qwen2-57b-a14b-instruct": 32768, "qwen2-72b-instruct": 131072, "qwen2-7b-instruct": 32768, "qwen2-1.5b-instruct": 32768, "qwen2-0.5b-instruct": 32768, "qwen1.5-110b-chat": 32000, "qwen1.5-72b-chat": 32000, "qwen1.5-32b-chat": 32000, "qwen1.5-14b-chat": 8000, "qwen1.5-7b-chat": 32000, "qwen1.5-1.8b-chat": 32000, "qwen1.5-0.5b-chat": 32000, "codeqwen1.5-7b-chat": 64000, "qwen-72b-chat": 32000, "qwen-14b-chat": 8000, "qwen-7b-chat": 32000, "qwen-1.8b-longcontext-chat": 32000, "qwen-1.8b-chat": 8000, } # For Amazon Bedrock US region # See https://aws.amazon.com/cn/bedrock/pricing/ BEDROCK_TOKEN_COSTS = { "amazon.titan-tg1-large": {"prompt": 0.0008, "completion": 0.0008}, "amazon.titan-text-express-v1": {"prompt": 0.0008, "completion": 0.0008}, "amazon.titan-text-express-v1:0:8k": {"prompt": 0.0008, "completion": 0.0008}, "amazon.titan-text-lite-v1:0:4k": {"prompt": 0.0003, "completion": 0.0004}, "amazon.titan-text-lite-v1": {"prompt": 0.0003, "completion": 0.0004}, "anthropic.claude-instant-v1": {"prompt": 0.0008, "completion": 0.00024}, "anthropic.claude-instant-v1:2:100k": {"prompt": 0.0008, "completion": 0.00024}, "anthropic.claude-v1": {"prompt": 0.008, "completion": 0.0024}, "anthropic.claude-v2": {"prompt": 0.008, "completion": 0.0024}, "anthropic.claude-v2:1": {"prompt": 0.008, "completion": 0.0024}, "anthropic.claude-v2:0:18k": {"prompt": 0.008, "completion": 0.0024}, "anthropic.claude-v2:1:200k": {"prompt": 0.008, "completion": 0.0024}, "anthropic.claude-3-sonnet-20240229-v1:0": {"prompt": 0.003, "completion": 0.015}, "anthropic.claude-3-sonnet-20240229-v1:0:28k": {"prompt": 0.003, "completion": 0.015}, "anthropic.claude-3-sonnet-20240229-v1:0:200k": {"prompt": 0.003, "completion": 0.015}, "anthropic.claude-3-5-sonnet-20240620-v1:0": {"prompt": 0.003, "completion": 0.015}, "anthropic.claude-3-haiku-20240307-v1:0": {"prompt": 0.00025, "completion": 0.00125}, "anthropic.claude-3-haiku-20240307-v1:0:48k": {"prompt": 0.00025, "completion": 0.00125}, "anthropic.claude-3-haiku-20240307-v1:0:200k": {"prompt": 0.00025, "completion": 0.00125}, # currently (2024-4-29) only available at US West (Oregon) AWS Region. "anthropic.claude-3-opus-20240229-v1:0": {"prompt": 0.015, "completion": 0.075}, "anthropic.claude-3-5-sonnet-20241022-v2:0": {"prompt": 0.003, "completion": 0.015}, "us.anthropic.claude-3-5-sonnet-20241022-v2:0": {"prompt": 0.003, "completion": 0.015}, "anthropic.claude-3-7-sonnet-20250219-v1:0": {"prompt": 0.003, "completion": 0.015}, "us.anthropic.claude-3-7-sonnet-20250219-v1:0": {"prompt": 0.003, "completion": 0.015}, "cohere.command-text-v14": {"prompt": 0.0015, "completion": 0.0015}, "cohere.command-text-v14:7:4k": {"prompt": 0.0015, "completion": 0.0015}, "cohere.command-light-text-v14": {"prompt": 0.0003, "completion": 0.0003}, "cohere.command-light-text-v14:7:4k": {"prompt": 0.0003, "completion": 0.0003}, "meta.llama2-13b-chat-v1:0:4k": {"prompt": 0.00075, "completion": 0.001}, "meta.llama2-13b-chat-v1": {"prompt": 0.00075, "completion": 0.001}, "meta.llama2-70b-v1": {"prompt": 0.00195, "completion": 0.00256}, "meta.llama2-70b-v1:0:4k": {"prompt": 0.00195, "completion": 0.00256}, "meta.llama2-70b-chat-v1": {"prompt": 0.00195, "completion": 0.00256}, "meta.llama2-70b-chat-v1:0:4k": {"prompt": 0.00195, "completion": 0.00256}, "meta.llama3-8b-instruct-v1:0": {"prompt": 0.0004, "completion": 0.0006}, "meta.llama3-70b-instruct-v1:0": {"prompt": 0.00265, "completion": 0.0035}, "mistral.mistral-7b-instruct-v0:2": {"prompt": 0.00015, "completion": 0.0002}, "mistral.mixtral-8x7b-instruct-v0:1": {"prompt": 0.00045, "completion": 0.0007}, "mistral.mistral-large-2402-v1:0": {"prompt": 0.008, "completion": 0.024}, "ai21.j2-grande-instruct": {"prompt": 0.0125, "completion": 0.0125}, "ai21.j2-jumbo-instruct": {"prompt": 0.0188, "completion": 0.0188}, "ai21.j2-mid": {"prompt": 0.0125, "completion": 0.0125}, "ai21.j2-mid-v1": {"prompt": 0.0125, "completion": 0.0125}, "ai21.j2-ultra": {"prompt": 0.0188, "completion": 0.0188}, "ai21.j2-ultra-v1": {"prompt": 0.0188, "completion": 0.0188}, } # https://xinghuo.xfyun.cn/sparkapi?scr=price SPARK_TOKENS = { "general": {"prompt": 0.0, "completion": 0.0}, # Spark-Lite "generalv2": {"prompt": 0.0188, "completion": 0.0188}, # Spark V2.0 "generalv3": {"prompt": 0.0035, "completion": 0.0035}, # Spark Pro "generalv3.5": {"prompt": 0.0035, "completion": 0.0035}, # Spark3.5 Max } def count_claude_message_tokens(messages: list[dict], model: str) -> int: # rough estimation for models newer than claude-2.1, needs api_key or auth_token ac = anthropic.Client() system_prompt = "" new_messages = [] for msg in messages: if msg.get("role") == "system": system_prompt = msg.get("content") else: new_messages.append(msg) num_tokens = ac.beta.messages.count_tokens(messages=new_messages, model=model, system=system_prompt) return num_tokens.input_tokens def count_message_tokens(messages, model="gpt-3.5-turbo-0125"): """Return the number of tokens used by a list of messages.""" if "claude" in model: num_tokens = count_claude_message_tokens(messages, model) return num_tokens try: encoding = tiktoken.encoding_for_model(model) except KeyError: logger.info(f"Warning: model {model} not found in tiktoken. Using cl100k_base encoding.") encoding = tiktoken.get_encoding("cl100k_base") if model in { "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613", "gpt-35-turbo", "gpt-35-turbo-16k", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-1106", "gpt-3.5-turbo-0125", "gpt-4-0314", "gpt-4-32k-0314", "gpt-4-0613", "gpt-4-32k-0613", "gpt-4-turbo", "gpt-4-turbo-preview", "gpt-4-0125-preview", "gpt-4-1106-preview", "gpt-4-turbo", "gpt-4-vision-preview", "gpt-4-1106-vision-preview", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "o1-preview", "o1-preview-2024-09-12", "o1-mini", "o1-mini-2024-09-12", }: tokens_per_message = 3 # # every reply is primed with <|start|>assistant<|message|> tokens_per_name = 1 elif model == "gpt-3.5-turbo-0301": tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n tokens_per_name = -1 # if there's a name, the role is omitted elif "gpt-3.5-turbo" == model: logger.info("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0125.") return count_message_tokens(messages, model="gpt-3.5-turbo-0125") elif "gpt-4" == model: logger.info("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.") return count_message_tokens(messages, model="gpt-4-0613") elif "open-llm-model" == model: """ For self-hosted open_llm api, they include lots of different models. The message tokens calculation is inaccurate. It's a reference result. """ tokens_per_message = 0 # ignore conversation message template prefix tokens_per_name = 0 else: raise NotImplementedError( f"num_tokens_from_messages() is not implemented for model {model}. " f"See https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken " f"for information on how messages are converted to tokens." ) num_tokens = 0 for message in messages: num_tokens += tokens_per_message for key, value in message.items(): content = value if isinstance(value, list): # for gpt-4v for item in value: if isinstance(item, dict) and item.get("type") in ["text"]: content = item.get("text", "") num_tokens += len(encoding.encode(content)) if key == "name": num_tokens += tokens_per_name num_tokens += 3 # every reply is primed with <|start|>assistant<|message|> return num_tokens def count_output_tokens(string: str, model: str) -> int: """ Returns the number of tokens in a text string. Args: string (str): The text string. model (str): The name of the encoding to use. (e.g., "gpt-3.5-turbo") Returns: int: The number of tokens in the text string. """ if "claude" in model: messages = [{"role": "assistant", "content": string}] num_tokens = count_claude_message_tokens(messages, model) return num_tokens try: encoding = tiktoken.encoding_for_model(model) except KeyError: logger.info(f"Warning: model {model} not found in tiktoken. Using cl100k_base encoding.") encoding = tiktoken.get_encoding("cl100k_base") return len(encoding.encode(string)) def get_max_completion_tokens(messages: list[dict], model: str, default: int) -> int: """Calculate the maximum number of completion tokens for a given model and list of messages. Args: messages: A list of messages. model: The model name. Returns: The maximum number of completion tokens. """ if model not in TOKEN_MAX: return default return TOKEN_MAX[model] - count_message_tokens(messages, model) - 1
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/file_repository.py
metagpt/utils/file_repository.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/11/20 @Author : mashenquan @File : git_repository.py @Desc: File repository management. RFC 135 2.2.3.2, 2.2.3.4 and 2.2.3.13. """ from __future__ import annotations import json import os from datetime import datetime from pathlib import Path from typing import Dict, List, Set from metagpt.logs import logger from metagpt.schema import Document from metagpt.utils.common import aread, awrite from metagpt.utils.json_to_markdown import json_to_markdown class FileRepository: """A class representing a FileRepository associated with a Git repository. :param git_repo: The associated GitRepository instance. :param relative_path: The relative path within the Git repository. Attributes: _relative_path (Path): The relative path within the Git repository. _git_repo (GitRepository): The associated GitRepository instance. """ def __init__(self, git_repo, relative_path: Path = Path(".")): """Initialize a FileRepository instance. :param git_repo: The associated GitRepository instance. :param relative_path: The relative path within the Git repository. """ self._relative_path = relative_path self._git_repo = git_repo # Initializing self.workdir.mkdir(parents=True, exist_ok=True) async def save(self, filename: Path | str, content, dependencies: List[str] = None) -> Document: """Save content to a file and update its dependencies. :param filename: The filename or path within the repository. :param content: The content to be saved. :param dependencies: List of dependency filenames or paths. """ pathname = self.workdir / filename pathname.parent.mkdir(parents=True, exist_ok=True) content = content if content else "" # avoid `argument must be str, not None` to make it continue await awrite(filename=str(pathname), data=content) logger.info(f"save to: {str(pathname)}") if dependencies is not None: dependency_file = await self._git_repo.get_dependency() await dependency_file.update(pathname, set(dependencies)) logger.info(f"update dependency: {str(pathname)}:{dependencies}") return Document(root_path=str(self._relative_path), filename=str(filename), content=content) async def get_dependency(self, filename: Path | str) -> Set[str]: """Get the dependencies of a file. :param filename: The filename or path within the repository. :return: Set of dependency filenames or paths. """ pathname = self.workdir / filename dependency_file = await self._git_repo.get_dependency() return await dependency_file.get(pathname) async def get_changed_dependency(self, filename: Path | str) -> Set[str]: """Get the dependencies of a file that have changed. :param filename: The filename or path within the repository. :return: List of changed dependency filenames or paths. """ dependencies = await self.get_dependency(filename=filename) changed_files = set(self.changed_files.keys()) changed_dependent_files = set() for df in dependencies: rdf = Path(df).relative_to(self._relative_path) if str(rdf) in changed_files: changed_dependent_files.add(df) return changed_dependent_files async def get(self, filename: Path | str) -> Document | None: """Read the content of a file. :param filename: The filename or path within the repository. :return: The content of the file. """ doc = Document(root_path=str(self.root_path), filename=str(filename)) path_name = self.workdir / filename if not path_name.exists(): return None if not path_name.is_file(): return None doc.content = await aread(path_name) return doc async def get_all(self, filter_ignored=True) -> List[Document]: """Get the content of all files in the repository. :return: List of Document instances representing files. """ docs = [] if filter_ignored: for f in self.all_files: doc = await self.get(f) docs.append(doc) else: for root, dirs, files in os.walk(str(self.workdir)): for file in files: file_path = Path(root) / file relative_path = file_path.relative_to(self.workdir) doc = await self.get(relative_path) docs.append(doc) return docs @property def workdir(self): """Return the absolute path to the working directory of the FileRepository. :return: The absolute path to the working directory. """ return self._git_repo.workdir / self._relative_path @property def root_path(self): """Return the relative path from git repository root""" return self._relative_path @property def changed_files(self) -> Dict[str, str]: """Return a dictionary of changed files and their change types. :return: A dictionary where keys are file paths and values are change types. """ files = self._git_repo.changed_files relative_files = {} for p, ct in files.items(): if ct.value == "D": # deleted continue try: rf = Path(p).relative_to(self._relative_path) except ValueError: continue relative_files[str(rf)] = ct return relative_files @property def all_files(self) -> List: """Get a dictionary of all files in the repository. The dictionary includes file paths relative to the current FileRepository. :return: A dictionary where keys are file paths and values are file information. :rtype: List """ return self._git_repo.get_files(relative_path=self._relative_path) def get_change_dir_files(self, dir: Path | str) -> List: """Get the files in a directory that have changed. :param dir: The directory path within the repository. :return: List of changed filenames or paths within the directory. """ changed_files = self.changed_files children = [] for f in changed_files: try: Path(f).relative_to(Path(dir)) except ValueError: continue children.append(str(f)) return children @staticmethod def new_filename(): """Generate a new filename based on the current timestamp and a UUID suffix. :return: A new filename string. """ current_time = datetime.now().strftime("%Y%m%d%H%M%S") return current_time async def save_doc(self, doc: Document, dependencies: List[str] = None): """Save content to a file and update its dependencies. :param doc: The Document instance to be saved. :type doc: Document :param dependencies: A list of dependencies for the saved file. :type dependencies: List[str], optional """ doc = await self.save(filename=doc.filename, content=doc.content, dependencies=dependencies) logger.debug(f"File Saved: {str(doc.filename)}") return doc async def save_pdf(self, doc: Document, with_suffix: str = ".md", dependencies: List[str] = None): """Save a Document instance as a PDF file. This method converts the content of the Document instance to Markdown, saves it to a file with an optional specified suffix, and logs the saved file. :param doc: The Document instance to be saved. :type doc: Document :param with_suffix: An optional suffix to append to the saved file's name. :type with_suffix: str, optional :param dependencies: A list of dependencies for the saved file. :type dependencies: List[str], optional """ m = json.loads(doc.content) filename = Path(doc.filename).with_suffix(with_suffix) if with_suffix is not None else Path(doc.filename) doc = await self.save(filename=str(filename), content=json_to_markdown(m), dependencies=dependencies) logger.debug(f"File Saved: {str(filename)}") return doc async def delete(self, filename: Path | str): """Delete a file from the file repository. This method deletes a file from the file repository based on the provided filename. :param filename: The name or path of the file to be deleted. :type filename: Path or str """ pathname = self.workdir / filename if not pathname.exists(): return pathname.unlink(missing_ok=True) dependency_file = await self._git_repo.get_dependency() await dependency_file.update(filename=pathname, dependencies=None) logger.info(f"remove dependency key: {str(pathname)}")
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/proxy_env.py
metagpt/utils/proxy_env.py
import os def get_proxy_from_env(): proxy_config = {} server = None for i in ("ALL_PROXY", "all_proxy", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"): if os.environ.get(i): server = os.environ.get(i) if server: proxy_config["server"] = server no_proxy = os.environ.get("NO_PROXY") or os.environ.get("no_proxy") if no_proxy: proxy_config["bypass"] = no_proxy if not proxy_config: proxy_config = None return proxy_config
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/custom_decoder.py
metagpt/utils/custom_decoder.py
import json import re from json import JSONDecodeError from json.decoder import _decode_uXXXX NUMBER_RE = re.compile(r"(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?", (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook object_pairs_hook = context.object_pairs_hook memo = context.memo def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration(idx) from None if nextchar in ("'", '"'): if idx + 2 < len(string) and string[idx + 1] == nextchar and string[idx + 2] == nextchar: # Handle the case where the next two characters are the same as nextchar return parse_string(string, idx + 3, strict, delimiter=nextchar * 3) # triple quote else: # Handle the case where the next two characters are not the same as nextchar return parse_string(string, idx + 1, strict, delimiter=nextchar) elif nextchar == "{": return parse_object((string, idx + 1), strict, _scan_once, object_hook, object_pairs_hook, memo) elif nextchar == "[": return parse_array((string, idx + 1), _scan_once) elif nextchar == "n" and string[idx : idx + 4] == "null": return None, idx + 4 elif nextchar == "t" and string[idx : idx + 4] == "true": return True, idx + 4 elif nextchar == "f" and string[idx : idx + 5] == "false": return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or "") + (exp or "")) else: res = parse_int(integer) return res, m.end() elif nextchar == "N" and string[idx : idx + 3] == "NaN": return parse_constant("NaN"), idx + 3 elif nextchar == "I" and string[idx : idx + 8] == "Infinity": return parse_constant("Infinity"), idx + 8 elif nextchar == "-" and string[idx : idx + 9] == "-Infinity": return parse_constant("-Infinity"), idx + 9 else: raise StopIteration(idx) def scan_once(string, idx): try: return _scan_once(string, idx) finally: memo.clear() return scan_once FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) STRINGCHUNK_SINGLEQUOTE = re.compile(r"(.*?)([\'\\\x00-\x1f])", FLAGS) STRINGCHUNK_TRIPLE_DOUBLE_QUOTE = re.compile(r"(.*?)(\"\"\"|[\\\x00-\x1f])", FLAGS) STRINGCHUNK_TRIPLE_SINGLEQUOTE = re.compile(r"(.*?)('''|[\\\x00-\x1f])", FLAGS) BACKSLASH = { '"': '"', "\\": "\\", "/": "/", "b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t", } WHITESPACE = re.compile(r"[ \t\n\r]*", FLAGS) WHITESPACE_STR = " \t\n\r" def JSONObject( s_and_end, strict, scan_once, object_hook, object_pairs_hook, memo=None, _w=WHITESPACE.match, _ws=WHITESPACE_STR ): """Parse a JSON object from a string and return the parsed object. Args: s_and_end (tuple): A tuple containing the input string to parse and the current index within the string. strict (bool): If `True`, enforces strict JSON string decoding rules. If `False`, allows literal control characters in the string. Defaults to `True`. scan_once (callable): A function to scan and parse JSON values from the input string. object_hook (callable): A function that, if specified, will be called with the parsed object as a dictionary. object_pairs_hook (callable): A function that, if specified, will be called with the parsed object as a list of pairs. memo (dict, optional): A dictionary used to memoize string keys for optimization. Defaults to None. _w (function): A regular expression matching function for whitespace. Defaults to WHITESPACE.match. _ws (str): A string containing whitespace characters. Defaults to WHITESPACE_STR. Returns: tuple or dict: A tuple containing the parsed object and the index of the character in the input string after the end of the object. """ s, end = s_and_end pairs = [] pairs_append = pairs.append # Backwards compatibility if memo is None: memo = {} memo_get = memo.setdefault # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end : end + 1] # Normally we expect nextchar == '"' if nextchar != '"' and nextchar != "'": if nextchar in _ws: end = _w(s, end).end() nextchar = s[end : end + 1] # Trivial empty object if nextchar == "}": if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end + 1 pairs = {} if object_hook is not None: pairs = object_hook(pairs) return pairs, end + 1 elif nextchar != '"': raise JSONDecodeError("Expecting property name enclosed in double quotes", s, end) end += 1 while True: if end + 1 < len(s) and s[end] == nextchar and s[end + 1] == nextchar: # Handle the case where the next two characters are the same as nextchar key, end = scanstring(s, end + 2, strict, delimiter=nextchar * 3) else: # Handle the case where the next two characters are not the same as nextchar key, end = scanstring(s, end, strict, delimiter=nextchar) key = memo_get(key, key) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end : end + 1] != ":": end = _w(s, end).end() if s[end : end + 1] != ":": raise JSONDecodeError("Expecting ':' delimiter", s, end) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration as err: raise JSONDecodeError("Expecting value", s, err.value) from None pairs_append((key, value)) try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = "" end += 1 if nextchar == "}": break elif nextchar != ",": raise JSONDecodeError("Expecting ',' delimiter", s, end - 1) end = _w(s, end).end() nextchar = s[end : end + 1] end += 1 if nextchar != '"': raise JSONDecodeError("Expecting property name enclosed in double quotes", s, end - 1) if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end pairs = dict(pairs) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def py_scanstring(s, end, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match, delimiter='"'): """Scan the string s for a JSON string. Args: s (str): The input string to be scanned for a JSON string. end (int): The index of the character in `s` after the quote that started the JSON string. strict (bool): If `True`, enforces strict JSON string decoding rules. If `False`, allows literal control characters in the string. Defaults to `True`. _b (dict): A dictionary containing escape sequence mappings. _m (function): A regular expression matching function for string chunks. delimiter (str): The string delimiter used to define the start and end of the JSON string. Can be one of: '"', "'", '\"""', or "'''". Defaults to '"'. Returns: tuple: A tuple containing the decoded string and the index of the character in `s` after the end quote. """ chunks = [] _append = chunks.append begin = end - 1 if delimiter == '"': _m = STRINGCHUNK.match elif delimiter == "'": _m = STRINGCHUNK_SINGLEQUOTE.match elif delimiter == '"""': _m = STRINGCHUNK_TRIPLE_DOUBLE_QUOTE.match else: _m = STRINGCHUNK_TRIPLE_SINGLEQUOTE.match while 1: chunk = _m(s, end) if chunk is None: raise JSONDecodeError("Unterminated string starting at", s, begin) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == delimiter: break elif terminator != "\\": if strict: # msg = "Invalid control character %r at" % (terminator,) msg = "Invalid control character {0!r} at".format(terminator) raise JSONDecodeError(msg, s, end) else: _append(terminator) continue try: esc = s[end] except IndexError: raise JSONDecodeError("Unterminated string starting at", s, begin) from None # If not a unicode escape sequence, must be in the lookup table if esc != "u": try: char = _b[esc] except KeyError: msg = "Invalid \\escape: {0!r}".format(esc) raise JSONDecodeError(msg, s, end) end += 1 else: uni = _decode_uXXXX(s, end) end += 5 if 0xD800 <= uni <= 0xDBFF and s[end : end + 2] == "\\u": uni2 = _decode_uXXXX(s, end + 1) if 0xDC00 <= uni2 <= 0xDFFF: uni = 0x10000 + (((uni - 0xD800) << 10) | (uni2 - 0xDC00)) end += 6 char = chr(uni) _append(char) return "".join(chunks), end scanstring = py_scanstring class CustomDecoder(json.JSONDecoder): def __init__( self, *, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None ): super().__init__( object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, strict=strict, object_pairs_hook=object_pairs_hook, ) self.parse_object = JSONObject self.parse_string = py_scanstring self.scan_once = py_make_scanner(self) def decode(self, s, _w=json.decoder.WHITESPACE.match): return super().decode(s)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/highlight.py
metagpt/utils/highlight.py
# 添加代码语法高亮显示 from pygments import highlight as highlight_ from pygments.formatters import HtmlFormatter, TerminalFormatter from pygments.lexers import PythonLexer, SqlLexer def highlight(code: str, language: str = "python", formatter: str = "terminal"): # 指定要高亮的语言 if language.lower() == "python": lexer = PythonLexer() elif language.lower() == "sql": lexer = SqlLexer() else: raise ValueError(f"Unsupported language: {language}") # 指定输出格式 if formatter.lower() == "terminal": formatter = TerminalFormatter() elif formatter.lower() == "html": formatter = HtmlFormatter() else: raise ValueError(f"Unsupported formatter: {formatter}") # 使用 Pygments 高亮代码片段 return highlight_(code, lexer, formatter)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/special_tokens.py
metagpt/utils/special_tokens.py
# token to separate different code messages in a WriteCode Message content MSG_SEP = "#*000*#" # token to seperate file name and the actual code text in a code message FILENAME_CODE_SEP = "#*001*#"
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/file.py
metagpt/utils/file.py
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """ @Time : 2023/9/4 15:40:40 @Author : Stitch-z @File : file.py @Describe : General file operations. """ import base64 from pathlib import Path from typing import Optional, Tuple, Union import aiofiles from fsspec.implementations.memory import MemoryFileSystem as _MemoryFileSystem from metagpt.config2 import config from metagpt.logs import logger from metagpt.utils import read_docx from metagpt.utils.common import aread, aread_bin, awrite_bin, check_http_endpoint from metagpt.utils.exceptions import handle_exception from metagpt.utils.repo_to_markdown import is_text_file class File: """A general util for file operations.""" CHUNK_SIZE = 64 * 1024 @classmethod @handle_exception async def write(cls, root_path: Path, filename: str, content: bytes) -> Path: """Write the file content to the local specified path. Args: root_path: The root path of file, such as "/data". filename: The name of file, such as "test.txt". content: The binary content of file. Returns: The full filename of file, such as "/data/test.txt". Raises: Exception: If an unexpected error occurs during the file writing process. """ root_path.mkdir(parents=True, exist_ok=True) full_path = root_path / filename async with aiofiles.open(full_path, mode="wb") as writer: await writer.write(content) logger.debug(f"Successfully write file: {full_path}") return full_path @classmethod @handle_exception async def read(cls, file_path: Path, chunk_size: int = None) -> bytes: """Partitioning read the file content from the local specified path. Args: file_path: The full file name of file, such as "/data/test.txt". chunk_size: The size of each chunk in bytes (default is 64kb). Returns: The binary content of file. Raises: Exception: If an unexpected error occurs during the file reading process. """ chunk_size = chunk_size or cls.CHUNK_SIZE async with aiofiles.open(file_path, mode="rb") as reader: chunks = list() while True: chunk = await reader.read(chunk_size) if not chunk: break chunks.append(chunk) content = b"".join(chunks) logger.debug(f"Successfully read file, the path of file: {file_path}") return content @staticmethod async def is_textual_file(filename: Union[str, Path]) -> bool: """Determines if a given file is a textual file. A file is considered a textual file if it is plain text or has a specific set of MIME types associated with textual formats, including PDF and Microsoft Word documents. Args: filename (Union[str, Path]): The path to the file to be checked. Returns: bool: True if the file is a textual file, False otherwise. """ is_text, mime_type = await is_text_file(filename) if is_text: return True if mime_type == "application/pdf": return True if mime_type in { "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.ms-word.document.macroEnabled.12", "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "application/vnd.ms-word.template.macroEnabled.12", }: return True return False @staticmethod async def read_text_file(filename: Union[str, Path]) -> Optional[str]: """Read the whole content of a file. Using absolute paths as the argument for specifying the file location.""" is_text, mime_type = await is_text_file(filename) if is_text: return await File._read_text(filename) if mime_type == "application/pdf": return await File._read_pdf(filename) if mime_type in { "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.ms-word.document.macroEnabled.12", "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "application/vnd.ms-word.template.macroEnabled.12", }: return await File._read_docx(filename) return None @staticmethod async def _read_text(path: Union[str, Path]) -> str: return await aread(path) @staticmethod async def _read_pdf(path: Union[str, Path]) -> str: result = await File._omniparse_read_file(path) if result: return result from llama_index.readers.file import PDFReader reader = PDFReader() lines = reader.load_data(file=Path(path)) return "\n".join([i.text for i in lines]) @staticmethod async def _read_docx(path: Union[str, Path]) -> str: result = await File._omniparse_read_file(path) if result: return result return "\n".join(read_docx(str(path))) @staticmethod async def _omniparse_read_file(path: Union[str, Path], auto_save_image: bool = False) -> Optional[str]: from metagpt.tools.libs import get_env_default from metagpt.utils.omniparse_client import OmniParseClient env_base_url = await get_env_default(key="base_url", app_name="OmniParse", default_value="") env_timeout = await get_env_default(key="timeout", app_name="OmniParse", default_value="") conf_base_url, conf_timeout = await File._read_omniparse_config() base_url = env_base_url or conf_base_url if not base_url: return None api_key = await get_env_default(key="api_key", app_name="OmniParse", default_value="") timeout = env_timeout or conf_timeout or 600 try: timeout = int(timeout) except ValueError: timeout = 600 try: if not await check_http_endpoint(url=base_url): logger.warning(f"{base_url}: NOT AVAILABLE") return None client = OmniParseClient(api_key=api_key, base_url=base_url, max_timeout=timeout) file_data = await aread_bin(filename=path) ret = await client.parse_document(file_input=file_data, bytes_filename=str(path)) except (ValueError, Exception) as e: logger.exception(f"{path}: {e}") return None if not ret.images or not auto_save_image: return ret.text result = [ret.text] img_dir = Path(path).parent / (Path(path).name.replace(".", "_") + "_images") img_dir.mkdir(parents=True, exist_ok=True) for i in ret.images: byte_data = base64.b64decode(i.image) filename = img_dir / i.image_name await awrite_bin(filename=filename, data=byte_data) result.append(f"![{i.image_name}]({str(filename)})") return "\n".join(result) @staticmethod async def _read_omniparse_config() -> Tuple[str, int]: if config.omniparse and config.omniparse.base_url: return config.omniparse.base_url, config.omniparse.timeout return "", 0 class MemoryFileSystem(_MemoryFileSystem): @classmethod def _strip_protocol(cls, path): return super()._strip_protocol(str(path))
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/report.py
metagpt/utils/report.py
import asyncio import os import typing from enum import Enum from pathlib import Path from typing import Any, Callable, Literal, Optional, Union from urllib.parse import unquote, urlparse, urlunparse from uuid import UUID, uuid4 from aiohttp import ClientSession, UnixConnector from playwright.async_api import Page as AsyncPage from playwright.sync_api import Page as SyncPage from pydantic import BaseModel, Field, PrivateAttr from metagpt.const import METAGPT_REPORTER_DEFAULT_URL from metagpt.logs import create_llm_stream_queue, get_llm_stream_queue if typing.TYPE_CHECKING: from metagpt.roles.role import Role try: import requests_unixsocket as requests except ImportError: import requests from contextvars import ContextVar CURRENT_ROLE: ContextVar["Role"] = ContextVar("role") class BlockType(str, Enum): """Enumeration for different types of blocks.""" TERMINAL = "Terminal" TASK = "Task" BROWSER = "Browser" BROWSER_RT = "Browser-RT" EDITOR = "Editor" GALLERY = "Gallery" NOTEBOOK = "Notebook" DOCS = "Docs" THOUGHT = "Thought" END_MARKER_NAME = "end_marker" END_MARKER_VALUE = "\x18\x19\x1B\x18\n" class ResourceReporter(BaseModel): """Base class for resource reporting.""" block: BlockType = Field(description="The type of block that is reporting the resource") uuid: UUID = Field(default_factory=uuid4, description="The unique identifier for the resource") enable_llm_stream: bool = Field(False, description="Indicates whether to connect to an LLM stream for reporting") callback_url: str = Field(METAGPT_REPORTER_DEFAULT_URL, description="The URL to which the report should be sent") _llm_task: Optional[asyncio.Task] = PrivateAttr(None) def report(self, value: Any, name: str, extra: Optional[dict] = None): """Synchronously report resource observation data. Args: value: The data to report. name: The type name of the data. """ return self._report(value, name, extra) async def async_report(self, value: Any, name: str, extra: Optional[dict] = None): """Asynchronously report resource observation data. Args: value: The data to report. name: The type name of the data. """ return await self._async_report(value, name, extra) @classmethod def set_report_fn(cls, fn: Callable): """Set the synchronous report function. Args: fn: A callable function used for synchronous reporting. For example: >>> def _report(self, value: Any, name: str): ... print(value, name) """ cls._report = fn @classmethod def set_async_report_fn(cls, fn: Callable): """Set the asynchronous report function. Args: fn: A callable function used for asynchronous reporting. For example: ```python >>> async def _report(self, value: Any, name: str): ... print(value, name) ``` """ cls._async_report = fn def _report(self, value: Any, name: str, extra: Optional[dict] = None): if not self.callback_url: return data = self._format_data(value, name, extra) resp = requests.post(self.callback_url, json=data) resp.raise_for_status() return resp.text async def _async_report(self, value: Any, name: str, extra: Optional[dict] = None): if not self.callback_url: return data = self._format_data(value, name, extra) url = self.callback_url _result = urlparse(url) sessiion_kwargs = {} if _result.scheme.endswith("+unix"): parsed_list = list(_result) parsed_list[0] = parsed_list[0][:-5] parsed_list[1] = "fake.org" url = urlunparse(parsed_list) sessiion_kwargs["connector"] = UnixConnector(path=unquote(_result.netloc)) async with ClientSession(**sessiion_kwargs) as client: async with client.post(url, json=data) as resp: resp.raise_for_status() return await resp.text() def _format_data(self, value, name, extra): data = self.model_dump(mode="json", exclude=("callback_url", "llm_stream")) if isinstance(value, BaseModel): value = value.model_dump(mode="json") elif isinstance(value, Path): value = str(value) if name == "path": value = os.path.abspath(value) data["value"] = value data["name"] = name role = CURRENT_ROLE.get(None) if role: role_name = role.name else: role_name = os.environ.get("METAGPT_ROLE") data["role"] = role_name if extra: data["extra"] = extra return data def __enter__(self): """Enter the synchronous streaming callback context.""" return self def __exit__(self, *args, **kwargs): """Exit the synchronous streaming callback context.""" self.report(None, END_MARKER_NAME) async def __aenter__(self): """Enter the asynchronous streaming callback context.""" if self.enable_llm_stream: queue = create_llm_stream_queue() self._llm_task = asyncio.create_task(self._llm_stream_report(queue)) return self async def __aexit__(self, exc_type, exc_value, exc_tb): """Exit the asynchronous streaming callback context.""" if self.enable_llm_stream and exc_type != asyncio.CancelledError: await get_llm_stream_queue().put(None) await self._llm_task self._llm_task = None await self.async_report(None, END_MARKER_NAME) async def _llm_stream_report(self, queue: asyncio.Queue): while True: data = await queue.get() if data is None: return await self.async_report(data, "content") async def wait_llm_stream_report(self): """Wait for the LLM stream report to complete.""" queue = get_llm_stream_queue() while self._llm_task: if queue.empty(): break await asyncio.sleep(0.01) class TerminalReporter(ResourceReporter): """Terminal output callback for streaming reporting of command and output. The terminal has state, and an agent can open multiple terminals and input different commands into them. To correctly display these states, each terminal should have its own unique ID, so in practice, each terminal should instantiate its own TerminalReporter object. """ block: Literal[BlockType.TERMINAL] = BlockType.TERMINAL def report(self, value: str, name: Literal["cmd", "output"]): """Report terminal command or output synchronously.""" return super().report(value, name) async def async_report(self, value: str, name: Literal["cmd", "output"]): """Report terminal command or output asynchronously.""" return await super().async_report(value, name) class BrowserReporter(ResourceReporter): """Browser output callback for streaming reporting of requested URL and page content. The browser has state, so in practice, each browser should instantiate its own BrowserReporter object. """ block: Literal[BlockType.BROWSER] = BlockType.BROWSER def report(self, value: Union[str, SyncPage], name: Literal["url", "page"]): """Report browser URL or page content synchronously.""" if name == "page": value = {"page_url": value.url, "title": value.title(), "screenshot": str(value.screenshot())} return super().report(value, name) async def async_report(self, value: Union[str, AsyncPage], name: Literal["url", "page"]): """Report browser URL or page content asynchronously.""" if name == "page": value = {"page_url": value.url, "title": await value.title(), "screenshot": str(await value.screenshot())} return await super().async_report(value, name) class ServerReporter(ResourceReporter): """Callback for server deployment reporting.""" block: Literal[BlockType.BROWSER_RT] = BlockType.BROWSER_RT def report(self, value: str, name: Literal["local_url"] = "local_url"): """Report server deployment synchronously.""" return super().report(value, name) async def async_report(self, value: str, name: Literal["local_url"] = "local_url"): """Report server deployment asynchronously.""" return await super().async_report(value, name) class ObjectReporter(ResourceReporter): """Callback for reporting complete object resources.""" def report(self, value: dict, name: Literal["object"] = "object"): """Report object resource synchronously.""" return super().report(value, name) async def async_report(self, value: dict, name: Literal["object"] = "object"): """Report object resource asynchronously.""" return await super().async_report(value, name) class TaskReporter(ObjectReporter): """Reporter for object resources to Task Block.""" block: Literal[BlockType.TASK] = BlockType.TASK class ThoughtReporter(ObjectReporter): """Reporter for object resources to Task Block.""" block: Literal[BlockType.THOUGHT] = BlockType.THOUGHT class FileReporter(ResourceReporter): """File resource callback for reporting complete file paths. There are two scenarios: if the file needs to be output in its entirety at once, use non-streaming callback; if the file can be partially output for display first, use streaming callback. """ def report( self, value: Union[Path, dict, Any], name: Literal["path", "meta", "content"] = "path", extra: Optional[dict] = None, ): """Report file resource synchronously.""" return super().report(value, name, extra) async def async_report( self, value: Union[Path, dict, Any], name: Literal["path", "meta", "content"] = "path", extra: Optional[dict] = None, ): """Report file resource asynchronously.""" return await super().async_report(value, name, extra) class NotebookReporter(FileReporter): """Equivalent to FileReporter(block=BlockType.NOTEBOOK).""" block: Literal[BlockType.NOTEBOOK] = BlockType.NOTEBOOK class DocsReporter(FileReporter): """Equivalent to FileReporter(block=BlockType.DOCS).""" block: Literal[BlockType.DOCS] = BlockType.DOCS class EditorReporter(FileReporter): """Equivalent to FileReporter(block=BlockType.EDITOR).""" block: Literal[BlockType.EDITOR] = BlockType.EDITOR class GalleryReporter(FileReporter): """Image resource callback for reporting complete file paths. Since images need to be complete before display, each callback is a complete file path. However, the Gallery needs to display the type of image and prompt, so if there is meta information, it should be reported in a streaming manner. """ block: Literal[BlockType.GALLERY] = BlockType.GALLERY def report(self, value: Union[dict, Path], name: Literal["meta", "path"] = "path"): """Report image resource synchronously.""" return super().report(value, name) async def async_report(self, value: Union[dict, Path], name: Literal["meta", "path"] = "path"): """Report image resource asynchronously.""" return await super().async_report(value, name)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/yaml_model.py
metagpt/utils/yaml_model.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/1/4 10:18 @Author : alexanderwu @File : YamlModel.py """ from pathlib import Path from typing import Dict, Optional import yaml from pydantic import BaseModel, model_validator class YamlModel(BaseModel): """Base class for yaml model""" extra_fields: Optional[Dict[str, str]] = None @classmethod def read_yaml(cls, file_path: Path, encoding: str = "utf-8") -> Dict: """Read yaml file and return a dict""" if not file_path.exists(): return {} with open(file_path, "r", encoding=encoding) as file: return yaml.safe_load(file) @classmethod def from_yaml_file(cls, file_path: Path) -> "YamlModel": """Read yaml file and return a YamlModel instance""" return cls(**cls.read_yaml(file_path)) def to_yaml_file(self, file_path: Path, encoding: str = "utf-8") -> None: """Dump YamlModel instance to yaml file""" with open(file_path, "w", encoding=encoding) as file: yaml.dump(self.model_dump(), file) class YamlModelWithoutDefault(YamlModel): """YamlModel without default values""" @model_validator(mode="before") @classmethod def check_not_default_config(cls, values): """Check if there is any default config in config2.yaml""" if any(["YOUR" in v for v in values]): raise ValueError("Please set your config in config2.yaml") return values
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/read_document.py
metagpt/utils/read_document.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/4/29 15:45 @Author : alexanderwu @File : read_document.py """ import docx def read_docx(file_path: str) -> list: """Open a docx file""" doc = docx.Document(file_path) # Create an empty list to store paragraph contents paragraphs_list = [] # Iterate through the paragraphs in the document and add their content to the list for paragraph in doc.paragraphs: paragraphs_list.append(paragraph.text) return paragraphs_list
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/pycst.py
metagpt/utils/pycst.py
from __future__ import annotations from typing import Union import libcst as cst from libcst._nodes.module import Module DocstringNode = Union[cst.Module, cst.ClassDef, cst.FunctionDef] def get_docstring_statement(body: DocstringNode) -> cst.SimpleStatementLine: """Extracts the docstring from the body of a node. Args: body: The body of a node. Returns: The docstring statement if it exists, None otherwise. """ if isinstance(body, cst.Module): body = body.body else: body = body.body.body if not body: return statement = body[0] if not isinstance(statement, cst.SimpleStatementLine): return expr = statement while isinstance(expr, (cst.BaseSuite, cst.SimpleStatementLine)): if len(expr.body) == 0: return None expr = expr.body[0] if not isinstance(expr, cst.Expr): return None val = expr.value if not isinstance(val, (cst.SimpleString, cst.ConcatenatedString)): return None evaluated_value = val.evaluated_value if isinstance(evaluated_value, bytes): return None return statement def has_decorator(node: DocstringNode, name: str) -> bool: return hasattr(node, "decorators") and any( (hasattr(i.decorator, "value") and i.decorator.value == name) or (hasattr(i.decorator, "func") and hasattr(i.decorator.func, "value") and i.decorator.func.value == name) for i in node.decorators ) class DocstringCollector(cst.CSTVisitor): """A visitor class for collecting docstrings from a CST. Attributes: stack: A list to keep track of the current path in the CST. docstrings: A dictionary mapping paths in the CST to their corresponding docstrings. """ def __init__(self): self.stack: list[str] = [] self.docstrings: dict[tuple[str, ...], cst.SimpleStatementLine] = {} def visit_Module(self, node: cst.Module) -> bool | None: self.stack.append("") def leave_Module(self, node: cst.Module) -> None: return self._leave(node) def visit_ClassDef(self, node: cst.ClassDef) -> bool | None: self.stack.append(node.name.value) def leave_ClassDef(self, node: cst.ClassDef) -> None: return self._leave(node) def visit_FunctionDef(self, node: cst.FunctionDef) -> bool | None: self.stack.append(node.name.value) def leave_FunctionDef(self, node: cst.FunctionDef) -> None: return self._leave(node) def _leave(self, node: DocstringNode) -> None: key = tuple(self.stack) self.stack.pop() if has_decorator(node, "overload"): return statement = get_docstring_statement(node) if statement: self.docstrings[key] = statement class DocstringTransformer(cst.CSTTransformer): """A transformer class for replacing docstrings in a CST. Attributes: stack: A list to keep track of the current path in the CST. docstrings: A dictionary mapping paths in the CST to their corresponding docstrings. """ def __init__( self, docstrings: dict[tuple[str, ...], cst.SimpleStatementLine], ): self.stack: list[str] = [] self.docstrings = docstrings def visit_Module(self, node: cst.Module) -> bool | None: self.stack.append("") def leave_Module(self, original_node: Module, updated_node: Module) -> Module: return self._leave(original_node, updated_node) def visit_ClassDef(self, node: cst.ClassDef) -> bool | None: self.stack.append(node.name.value) def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.CSTNode: return self._leave(original_node, updated_node) def visit_FunctionDef(self, node: cst.FunctionDef) -> bool | None: self.stack.append(node.name.value) def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.CSTNode: return self._leave(original_node, updated_node) def _leave(self, original_node: DocstringNode, updated_node: DocstringNode) -> DocstringNode: key = tuple(self.stack) self.stack.pop() if has_decorator(updated_node, "overload"): return updated_node statement = self.docstrings.get(key) if not statement: return updated_node original_statement = get_docstring_statement(original_node) if isinstance(updated_node, cst.Module): body = updated_node.body if original_statement: return updated_node.with_changes(body=(statement, *body[1:])) else: updated_node = updated_node.with_changes(body=(statement, cst.EmptyLine(), *body)) return updated_node body = updated_node.body.body[1:] if original_statement else updated_node.body.body return updated_node.with_changes(body=updated_node.body.with_changes(body=(statement, *body))) def merge_docstring(code: str, documented_code: str) -> str: """Merges the docstrings from the documented code into the original code. Args: code: The original code. documented_code: The documented code. Returns: The original code with the docstrings from the documented code. """ code_tree = cst.parse_module(code) documented_code_tree = cst.parse_module(documented_code) visitor = DocstringCollector() documented_code_tree.visit(visitor) transformer = DocstringTransformer(visitor.docstrings) modified_tree = code_tree.visit(transformer) return modified_tree.code
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false
FoundationAgents/MetaGPT
https://github.com/FoundationAgents/MetaGPT/blob/fc6e8433747be02826dec818627ed5cec0950e77/metagpt/utils/graph_repository.py
metagpt/utils/graph_repository.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/12/19 @Author : mashenquan @File : graph_repository.py @Desc : Superclass for graph repository. This script defines a superclass for a graph repository, providing a foundation for specific implementations. """ from abc import ABC, abstractmethod from collections import defaultdict from pathlib import Path from typing import List from pydantic import BaseModel from metagpt.repo_parser import DotClassInfo, DotClassRelationship, RepoFileInfo from metagpt.utils.common import concat_namespace, split_namespace class GraphKeyword: """Basic words for a Graph database. This class defines a set of basic words commonly used in the context of a Graph database. """ IS = "is" OF = "Of" ON = "On" CLASS = "class" FUNCTION = "function" HAS_FUNCTION = "has_function" SOURCE_CODE = "source_code" NULL = "<null>" GLOBAL_VARIABLE = "global_variable" CLASS_METHOD = "class_method" CLASS_PROPERTY = "class_property" HAS_CLASS_METHOD = "has_class_method" HAS_CLASS_PROPERTY = "has_class_property" HAS_CLASS = "has_class" HAS_DETAIL = "has_detail" HAS_PAGE_INFO = "has_page_info" HAS_CLASS_VIEW = "has_class_view" HAS_SEQUENCE_VIEW = "has_sequence_view" HAS_SEQUENCE_VIEW_VER = "has_sequence_view_ver" HAS_CLASS_USE_CASE = "has_class_use_case" IS_COMPOSITE_OF = "is_composite_of" IS_AGGREGATE_OF = "is_aggregate_of" HAS_PARTICIPANT = "has_participant" HAS_SUMMARY = "has_summary" HAS_INSTALL = "has_install" HAS_CONFIG = "has_config" HAS_USAGE = "has_usage" class SPO(BaseModel): """Graph repository record type. This class represents a record in a graph repository with three components: - Subject: The subject of the triple. - Predicate: The predicate describing the relationship between the subject and the object. - Object: The object of the triple. Attributes: subject (str): The subject of the triple. predicate (str): The predicate describing the relationship. object_ (str): The object of the triple. Example: spo_record = SPO(subject="Node1", predicate="connects_to", object_="Node2") # Represents a triple: Node1 connects_to Node2 """ subject: str predicate: str object_: str class GraphRepository(ABC): """Abstract base class for a Graph Repository. This class defines the interface for a graph repository, providing methods for inserting, selecting, deleting, and saving graph data. Concrete implementations of this class must provide functionality for these operations. """ def __init__(self, name: str, **kwargs): self._repo_name = name self._kwargs = kwargs @abstractmethod async def insert(self, subject: str, predicate: str, object_: str): """Insert a new triple into the graph repository. Args: subject (str): The subject of the triple. predicate (str): The predicate describing the relationship. object_ (str): The object of the triple. Example: await my_repository.insert(subject="Node1", predicate="connects_to", object_="Node2") # Inserts a triple: Node1 connects_to Node2 into the graph repository. """ pass @abstractmethod async def select(self, subject: str = None, predicate: str = None, object_: str = None) -> List[SPO]: """Retrieve triples from the graph repository based on specified criteria. Args: subject (str, optional): The subject of the triple to filter by. predicate (str, optional): The predicate describing the relationship to filter by. object_ (str, optional): The object of the triple to filter by. Returns: List[SPO]: A list of SPO objects representing the selected triples. Example: selected_triples = await my_repository.select(subject="Node1", predicate="connects_to") # Retrieves triples where Node1 is the subject and the predicate is 'connects_to'. """ pass @abstractmethod async def delete(self, subject: str = None, predicate: str = None, object_: str = None) -> int: """Delete triples from the graph repository based on specified criteria. Args: subject (str, optional): The subject of the triple to filter by. predicate (str, optional): The predicate describing the relationship to filter by. object_ (str, optional): The object of the triple to filter by. Returns: int: The number of triples deleted from the repository. Example: deleted_count = await my_repository.delete(subject="Node1", predicate="connects_to") # Deletes triples where Node1 is the subject and the predicate is 'connects_to'. """ pass @abstractmethod async def save(self): """Save any changes made to the graph repository. Example: await my_repository.save() # Persists any changes made to the graph repository. """ pass @property def name(self) -> str: """Get the name of the graph repository.""" return self._repo_name @staticmethod async def update_graph_db_with_file_info(graph_db: "GraphRepository", file_info: RepoFileInfo): """Insert information of RepoFileInfo into the specified graph repository. This function updates the provided graph repository with information from the given RepoFileInfo object. The function inserts triples related to various dimensions such as file type, class, class method, function, global variable, and page info. Triple Patterns: - (?, is, [file type]) - (?, has class, ?) - (?, is, [class]) - (?, has class method, ?) - (?, has function, ?) - (?, is, [function]) - (?, is, global variable) - (?, has page info, ?) Args: graph_db (GraphRepository): The graph repository object to be updated. file_info (RepoFileInfo): The RepoFileInfo object containing information to be inserted. Example: await update_graph_db_with_file_info(my_graph_repo, my_file_info) # Updates 'my_graph_repo' with information from 'my_file_info'. """ await graph_db.insert(subject=file_info.file, predicate=GraphKeyword.IS, object_=GraphKeyword.SOURCE_CODE) file_types = {".py": "python", ".js": "javascript"} file_type = file_types.get(Path(file_info.file).suffix, GraphKeyword.NULL) await graph_db.insert(subject=file_info.file, predicate=GraphKeyword.IS, object_=file_type) for c in file_info.classes: class_name = c.get("name", "") # file -> class await graph_db.insert( subject=file_info.file, predicate=GraphKeyword.HAS_CLASS, object_=concat_namespace(file_info.file, class_name), ) # class detail await graph_db.insert( subject=concat_namespace(file_info.file, class_name), predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS, ) methods = c.get("methods", []) for fn in methods: await graph_db.insert( subject=concat_namespace(file_info.file, class_name), predicate=GraphKeyword.HAS_CLASS_METHOD, object_=concat_namespace(file_info.file, class_name, fn), ) await graph_db.insert( subject=concat_namespace(file_info.file, class_name, fn), predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS_METHOD, ) for f in file_info.functions: # file -> function await graph_db.insert( subject=file_info.file, predicate=GraphKeyword.HAS_FUNCTION, object_=concat_namespace(file_info.file, f) ) # function detail await graph_db.insert( subject=concat_namespace(file_info.file, f), predicate=GraphKeyword.IS, object_=GraphKeyword.FUNCTION ) for g in file_info.globals: await graph_db.insert( subject=concat_namespace(file_info.file, g), predicate=GraphKeyword.IS, object_=GraphKeyword.GLOBAL_VARIABLE, ) for code_block in file_info.page_info: if code_block.tokens: await graph_db.insert( subject=concat_namespace(file_info.file, *code_block.tokens), predicate=GraphKeyword.HAS_PAGE_INFO, object_=code_block.model_dump_json(), ) for k, v in code_block.properties.items(): await graph_db.insert( subject=concat_namespace(file_info.file, k, v), predicate=GraphKeyword.HAS_PAGE_INFO, object_=code_block.model_dump_json(), ) @staticmethod async def update_graph_db_with_class_views(graph_db: "GraphRepository", class_views: List[DotClassInfo]): """Insert dot format class information into the specified graph repository. This function updates the provided graph repository with class information from the given list of DotClassInfo objects. The function inserts triples related to various aspects of class views, including source code, file type, class, class property, class detail, method, composition, and aggregation. Triple Patterns: - (?, is, source code) - (?, is, file type) - (?, has class, ?) - (?, is, class) - (?, has class property, ?) - (?, is, class property) - (?, has detail, ?) - (?, has method, ?) - (?, is composite of, ?) - (?, is aggregate of, ?) Args: graph_db (GraphRepository): The graph repository object to be updated. class_views (List[DotClassInfo]): List of DotClassInfo objects containing class information to be inserted. Example: await update_graph_db_with_class_views(my_graph_repo, [class_info1, class_info2]) # Updates 'my_graph_repo' with class information from the provided list of DotClassInfo objects. """ for c in class_views: filename, _ = c.package.split(":", 1) await graph_db.insert(subject=filename, predicate=GraphKeyword.IS, object_=GraphKeyword.SOURCE_CODE) file_types = {".py": "python", ".js": "javascript"} file_type = file_types.get(Path(filename).suffix, GraphKeyword.NULL) await graph_db.insert(subject=filename, predicate=GraphKeyword.IS, object_=file_type) await graph_db.insert(subject=filename, predicate=GraphKeyword.HAS_CLASS, object_=c.package) await graph_db.insert( subject=c.package, predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS, ) await graph_db.insert(subject=c.package, predicate=GraphKeyword.HAS_DETAIL, object_=c.model_dump_json()) for vn, vt in c.attributes.items(): # class -> property await graph_db.insert( subject=c.package, predicate=GraphKeyword.HAS_CLASS_PROPERTY, object_=concat_namespace(c.package, vn), ) # property detail await graph_db.insert( subject=concat_namespace(c.package, vn), predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS_PROPERTY, ) await graph_db.insert( subject=concat_namespace(c.package, vn), predicate=GraphKeyword.HAS_DETAIL, object_=vt.model_dump_json(), ) for fn, ft in c.methods.items(): # class -> function await graph_db.insert( subject=c.package, predicate=GraphKeyword.HAS_CLASS_METHOD, object_=concat_namespace(c.package, fn), ) # function detail await graph_db.insert( subject=concat_namespace(c.package, fn), predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS_METHOD, ) await graph_db.insert( subject=concat_namespace(c.package, fn), predicate=GraphKeyword.HAS_DETAIL, object_=ft.model_dump_json(), ) for i in c.compositions: await graph_db.insert( subject=c.package, predicate=GraphKeyword.IS_COMPOSITE_OF, object_=concat_namespace("?", i) ) for i in c.aggregations: await graph_db.insert( subject=c.package, predicate=GraphKeyword.IS_AGGREGATE_OF, object_=concat_namespace("?", i) ) @staticmethod async def update_graph_db_with_class_relationship_views( graph_db: "GraphRepository", relationship_views: List[DotClassRelationship] ): """Insert class relationships and labels into the specified graph repository. This function updates the provided graph repository with class relationship information from the given list of DotClassRelationship objects. The function inserts triples representing relationships and labels between classes. Triple Patterns: - (?, is relationship of, ?) - (?, is relationship on, ?) Args: graph_db (GraphRepository): The graph repository object to be updated. relationship_views (List[DotClassRelationship]): List of DotClassRelationship objects containing class relationship information to be inserted. Example: await update_graph_db_with_class_relationship_views(my_graph_repo, [relationship1, relationship2]) # Updates 'my_graph_repo' with class relationship information from the provided list of DotClassRelationship objects. """ for r in relationship_views: await graph_db.insert( subject=r.src, predicate=GraphKeyword.IS + r.relationship + GraphKeyword.OF, object_=r.dest ) if not r.label: continue await graph_db.insert( subject=r.src, predicate=GraphKeyword.IS + r.relationship + GraphKeyword.ON, object_=concat_namespace(r.dest, r.label), ) @staticmethod async def rebuild_composition_relationship(graph_db: "GraphRepository"): """Append namespace-prefixed information to relationship SPO (Subject-Predicate-Object) objects in the graph repository. This function updates the provided graph repository by appending namespace-prefixed information to existing relationship SPO objects. Args: graph_db (GraphRepository): The graph repository object to be updated. """ classes = await graph_db.select(predicate=GraphKeyword.IS, object_=GraphKeyword.CLASS) mapping = defaultdict(list) for c in classes: name = split_namespace(c.subject)[-1] mapping[name].append(c.subject) rows = await graph_db.select(predicate=GraphKeyword.IS_COMPOSITE_OF) for r in rows: ns, class_ = split_namespace(r.object_) if ns != "?": continue val = mapping[class_] if len(val) != 1: continue ns_name = val[0] await graph_db.delete(subject=r.subject, predicate=r.predicate, object_=r.object_) await graph_db.insert(subject=r.subject, predicate=r.predicate, object_=ns_name)
python
MIT
fc6e8433747be02826dec818627ed5cec0950e77
2026-01-04T14:38:37.890126Z
false