instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Create docstrings for reusable components
from collections.abc import Callable from typing import Any, Optional from embedchain.config.embedder.base import BaseEmbedderConfig try: from chromadb.api.types import Embeddable, EmbeddingFunction, Embeddings except RuntimeError: from embedchain.utils.misc import use_pysqlite3 use_pysqlite3() from ...
--- +++ @@ -21,8 +21,20 @@ class BaseEmbedder: + """ + Class that manages everything regarding embeddings. Including embedding function, loaders and chunkers. + + Embedding functions and vector dimensions are set based on the child class you choose. + To manually overwrite you can use this classes `set_...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/embedder/base.py
Generate documentation strings for clarity
from typing import Any, Optional from embedchain.config.base_config import BaseConfig from embedchain.helpers.json_serializable import register_deserializable @register_deserializable class CacheSimilarityEvalConfig(BaseConfig): def __init__( self, strategy: Optional[str] = "distance", m...
--- +++ @@ -6,6 +6,18 @@ @register_deserializable class CacheSimilarityEvalConfig(BaseConfig): + """ + This is the evaluator to compare two embeddings according to their distance computed in embedding retrieval stage. + In the retrieval stage, `search_result` is the distance used for approximate nearest nei...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/cache_config.py
Annotate my code with docstrings
from dotenv import load_dotenv from fastapi import Body, FastAPI, responses from modal import Image, Secret, Stub, asgi_app from embedchain import App load_dotenv(".env") image = Image.debian_slim().pip_install( "embedchain", "lanchain_community==0.2.6", "youtube-transcript-api==0.6.1", "pytube==15.0...
--- +++ @@ -37,6 +37,11 @@ source: str = Body(..., description="Source to be added"), data_type: str | None = Body(None, description="Type of the data source"), ): + """ + Adds a new source to the EmbedChain app. + Expects a JSON with a "source" and "data_type" key. + "data_type" is optional. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/deployment/modal.com/app.py
Add standardized docstrings across the file
from typing import Any from embedchain import App from embedchain.config import AddConfig, AppConfig, BaseLlmConfig from embedchain.embedder.openai import OpenAIEmbedder from embedchain.helpers.json_serializable import ( JSONSerializable, register_deserializable, ) from embedchain.llm.openai import OpenAILlm f...
--- +++ @@ -17,12 +17,32 @@ self.app = App(config=AppConfig(), llm=OpenAILlm(), db=ChromaDB(), embedding_model=OpenAIEmbedder()) def add(self, data: Any, config: AddConfig = None): + """ + Add data to the bot (to the vector database). + Auto-dectects type only, so some data types mig...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/bots/base.py
Add docstrings to clarify complex logic
from typing import Optional from embedchain.helpers.json_serializable import register_deserializable from .base_app_config import BaseAppConfig @register_deserializable class AppConfig(BaseAppConfig): def __init__( self, log_level: str = "WARNING", id: Optional[str] = None, name...
--- +++ @@ -7,6 +7,9 @@ @register_deserializable class AppConfig(BaseAppConfig): + """ + Config to initialize an embedchain custom `App` instance, with extra config options. + """ def __init__( self, @@ -16,5 +19,16 @@ collect_metrics: Optional[bool] = True, **kwargs, )...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/app_config.py
Add docstrings to improve readability
import logging from typing import Optional from embedchain.config.base_config import BaseConfig from embedchain.helpers.json_serializable import JSONSerializable from embedchain.vectordb.base import BaseVectorDB logger = logging.getLogger(__name__) class BaseAppConfig(BaseConfig, JSONSerializable): def __init_...
--- +++ @@ -9,6 +9,9 @@ class BaseAppConfig(BaseConfig, JSONSerializable): + """ + Parent config to initialize an instance of `App`. + """ def __init__( self, @@ -18,6 +21,23 @@ collect_metrics: bool = True, collection_name: Optional[str] = None, ): + """ + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/base_app_config.py
Write docstrings that follow conventions
from importlib import import_module from typing import Any, Optional from embedchain.chunkers.base_chunker import BaseChunker from embedchain.config import AddConfig from embedchain.config.add_config import ChunkerConfig, LoaderConfig from embedchain.helpers.json_serializable import JSONSerializable from embedchain.lo...
--- +++ @@ -10,6 +10,11 @@ class DataFormatter(JSONSerializable): + """ + DataFormatter is an internal utility class which abstracts the mapping for + loaders and chunkers to the data_type entered by the user in their + .add or .add_local method call + """ def __init__( self, @@ -18,6...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/data_formatter/data_formatter.py
Add well-formatted docstrings
from fastapi import FastAPI, responses from pydantic import BaseModel from embedchain import App app = FastAPI(title="Embedchain FastAPI App") embedchain_app = App() class SourceModel(BaseModel): source: str class QuestionModel(BaseModel): question: str @app.post("/add") async def add_source(source_mode...
--- +++ @@ -17,6 +17,10 @@ @app.post("/add") async def add_source(source_model: SourceModel): + """ + Adds a new source to the EmbedChain app. + Expects a JSON with a "source" key. + """ source = source_model.source embedchain_app.add(source) return {"message": f"Source '{source}' added su...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/deployment/render.com/app.py
Add structured docstrings to improve clarity
import hashlib import json import logging from typing import Any, Optional, Union from dotenv import load_dotenv from langchain.docstore.document import Document from embedchain.cache import ( adapt, get_gptcache_session, gptcache_data_convert, gptcache_update_cache_callback, ) from embedchain.chunker...
--- +++ @@ -44,6 +44,22 @@ embedder: BaseEmbedder = None, system_prompt: Optional[str] = None, ): + """ + Initializes the EmbedChain instance, sets up a vector DB client and + creates a collection. + + :param config: Configuration just for the app, not the db or llm or ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/embedchain.py
Add docstrings to make code maintainable
from dotenv import load_dotenv from fastapi import FastAPI, responses from pydantic import BaseModel from embedchain import App load_dotenv(".env") app = FastAPI(title="Embedchain FastAPI App") embedchain_app = App() class SourceModel(BaseModel): source: str class QuestionModel(BaseModel): question: str ...
--- +++ @@ -20,6 +20,10 @@ @app.post("/add") async def add_source(source_model: SourceModel): + """ + Adds a new source to the EmbedChain app. + Expects a JSON with a "source" key. + """ source = source_model.source embedchain_app.add(source) return {"message": f"Source '{source}' added su...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/deployment/fly.io/app.py
Write beginner-friendly docstrings
import os from alembic import command from alembic.config import Config from sqlalchemy import create_engine from sqlalchemy.engine.base import Engine from sqlalchemy.orm import Session as SQLAlchemySession from sqlalchemy.orm import scoped_session, sessionmaker from .models import Base class DatabaseManager: d...
--- +++ @@ -18,6 +18,7 @@ self._session_factory = None def setup_engine(self) -> None: + """Initializes the database engine and session factory.""" if not self.database_uri: raise RuntimeError("Database URI is not set. Set the EMBEDCHAIN_DB_URI environment variable.") ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/core/db/database.py
Add missing documentation to my Python functions
import ast import concurrent.futures import json import logging import os from typing import Any, Optional, Union import requests import yaml from tqdm import tqdm from embedchain.cache import ( Config, ExactMatchEvaluation, SearchDistanceEvaluation, cache, gptcache_data_manager, gptcache_pre_...
--- +++ @@ -46,6 +46,11 @@ @register_deserializable class App(EmbedChain): + """ + EmbedChain App lets you create a LLM powered app for your unstructured + data by defining your chosen data source, embedding model, + and vector database. + """ def __init__( self, @@ -62,6 +67,23 @@ ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/app.py
Add return value explanations in docstrings
from typing import Optional from embedchain.config.vector_db.base import BaseVectorDbConfig from embedchain.helpers.json_serializable import register_deserializable @register_deserializable class QdrantDBConfig(BaseVectorDbConfig): def __init__( self, collection_name: Optional[str] = None, ...
--- +++ @@ -6,6 +6,10 @@ @register_deserializable class QdrantDBConfig(BaseVectorDbConfig): + """ + Config to initialize a qdrant client. + :param: url. qdrant url or list of nodes url to be used for connection + """ def __init__( self, @@ -17,9 +21,28 @@ batch_size: Optional[int]...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/vector_db/qdrant.py
Write docstrings for algorithm functions
import queue from typing import Any, Union from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.schema import LLMResult STOP_ITEM = "[END]" """ This is a special item that is used to signal the end of the stream. """ class StreamingStdOutCallbackHandlerYield(StreamingStdOut...
--- +++ @@ -11,6 +11,10 @@ class StreamingStdOutCallbackHandlerYield(StreamingStdOutCallbackHandler): + """ + This is a callback handler that yields the tokens as they are generated. + For a usage example, see the :func:`generate` function below. + """ q: queue.Queue """ @@ -18,27 +22,52 @@ ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/helpers/callbacks.py
Generate docstrings for exported functions
import concurrent.futures import logging import os from string import Template from typing import Optional import numpy as np from openai import OpenAI from tqdm import tqdm from embedchain.config.evaluation.base import GroundednessConfig from embedchain.evaluation.base import BaseMetric from embedchain.utils.evaluat...
--- +++ @@ -16,6 +16,9 @@ class Groundedness(BaseMetric): + """ + Metric for groundedness of answer from the given contexts. + """ def __init__(self, config: Optional[GroundednessConfig] = None): super().__init__(name=EvalMetric.GROUNDEDNESS.value) @@ -26,10 +29,16 @@ self.client = ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/evaluation/metrics/groundedness.py
Write proper docstrings for these functions
import hashlib import os from dropbox.files import FileMetadata from embedchain.helpers.json_serializable import register_deserializable from embedchain.loaders.base_loader import BaseLoader from embedchain.loaders.directory_loader import DirectoryLoader @register_deserializable class DropboxLoader(BaseLoader): ...
--- +++ @@ -27,6 +27,7 @@ raise ValueError("Invalid Dropbox access token. Please verify your token and try again.") from ex def _download_folder(self, path: str, local_root: str) -> list[FileMetadata]: + """Download a folder from Dropbox and save it preserving the directory structure.""" ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/loaders/dropbox.py
Add docstrings including usage examples
import json import logging from string import Template from typing import Any, Type, TypeVar, Union T = TypeVar("T", bound="JSONSerializable") # NOTE: Through inheritance, all of our classes should be children of JSONSerializable. (highest level) # NOTE: The @register_deserializable decorator should be added to all u...
--- +++ @@ -12,15 +12,50 @@ def register_deserializable(cls: Type[T]) -> Type[T]: + """ + A class decorator to register a class as deserializable. + + When a class is decorated with @register_deserializable, it becomes + a part of the set of classes that the JSONSerializable class can + deserialize. ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/helpers/json_serializable.py
Replace inline comments with docstrings
import os from alembic import context from sqlalchemy import engine_from_config, pool from embedchain.core.db.models import Base # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config target_metadata = Base.metadata # other values from the co...
--- +++ @@ -19,6 +19,17 @@ def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/migrations/env.py
Write documentation strings for class attributes
import hashlib import json import os import re from typing import Union import requests from embedchain.loaders.base_loader import BaseLoader from embedchain.utils.misc import clean_string, is_valid_json_string class JSONReader: def __init__(self) -> None: pass @staticmethod def load_data(json_...
--- +++ @@ -12,10 +12,19 @@ class JSONReader: def __init__(self) -> None: + """Initialize the JSONReader.""" pass @staticmethod def load_data(json_data: Union[dict, str]) -> list[str]: + """Load data from a JSON structure. + + Args: + json_data (Union[dict, st...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/loaders/json.py
Generate descriptive docstrings automatically
import concurrent.futures import os from string import Template from typing import Optional import numpy as np import pysbd from openai import OpenAI from tqdm import tqdm from embedchain.config.evaluation.base import ContextRelevanceConfig from embedchain.evaluation.base import BaseMetric from embedchain.utils.evalu...
--- +++ @@ -14,6 +14,9 @@ class ContextRelevance(BaseMetric): + """ + Metric for evaluating the relevance of context in a dataset. + """ def __init__(self, config: Optional[ContextRelevanceConfig] = ContextRelevanceConfig()): super().__init__(name=EvalMetric.CONTEXT_RELEVANCY.value) @@ -25,...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/evaluation/metrics/context_relevancy.py
Generate docstrings for this script
import hashlib import logging import os from typing import Any, Optional import requests from embedchain.helpers.json_serializable import register_deserializable from embedchain.loaders.base_loader import BaseLoader from embedchain.utils.misc import clean_string logger = logging.getLogger(__name__) class NotionDoc...
--- +++ @@ -13,6 +13,9 @@ class NotionDocument: + """ + A simple Document class to hold the text and additional information of a page. + """ def __init__(self, text: str, extra_info: dict[str, Any]): self.text = text @@ -20,10 +23,15 @@ class NotionPageLoader: + """ + Notion Page ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/loaders/notion.py
Generate docstrings for exported functions
from enum import Enum class DirectDataType(Enum): TEXT = "text" class IndirectDataType(Enum): YOUTUBE_VIDEO = "youtube_video" PDF_FILE = "pdf_file" WEB_PAGE = "web_page" SITEMAP = "sitemap" XML = "xml" DOCX = "docx" DOCS_SITE = "docs_site" NOTION = "notion" CSV = "csv" ...
--- +++ @@ -2,11 +2,17 @@ class DirectDataType(Enum): + """ + DirectDataType enum contains data types that contain raw data directly. + """ TEXT = "text" class IndirectDataType(Enum): + """ + IndirectDataType enum contains data types that contain references to data stored elsewhere. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/models/data_type.py
Document functions with clear intent
import concurrent.futures import hashlib import logging import re import shlex from typing import Any, Optional from tqdm import tqdm from embedchain.loaders.base_loader import BaseLoader from embedchain.utils.misc import clean_string GITHUB_URL = "https://github.com" GITHUB_API_URL = "https://api.github.com" VALID...
--- +++ @@ -17,6 +17,7 @@ class GithubLoader(BaseLoader): + """Load data from GitHub search query.""" def __init__(self, config: Optional[dict[str, Any]] = None): super().__init__() @@ -47,6 +48,7 @@ self.client = None def _github_search_code(self, query: str): + """Sear...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/loaders/github.py
Generate NumPy-style docstrings
import logging import os from collections.abc import Generator from typing import Any, Optional from langchain.schema import BaseMessage as LCBaseMessage from embedchain.config import BaseLlmConfig from embedchain.config.llm.base import ( DEFAULT_PROMPT, DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE, DEFAULT_PROMP...
--- +++ @@ -23,6 +23,11 @@ class BaseLlm(JSONSerializable): def __init__(self, config: Optional[BaseLlmConfig] = None): + """Initialize a base LLM class + + :param config: LLM configuration option class, defaults to None + :type config: Optional[BaseLlmConfig], optional + """ ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/llm/base.py
Fill in missing docstrings in my code
import logging import time from typing import Any, Optional, Union from tqdm import tqdm try: from opensearchpy import OpenSearch from opensearchpy.helpers import bulk except ImportError: raise ImportError( "OpenSearch requires extra dependencies. Install with `pip install --upgrade embedchain[ope...
--- +++ @@ -1,196 +1,253 @@-import logging -import time -from typing import Any, Optional, Union - -from tqdm import tqdm - -try: - from opensearchpy import OpenSearch - from opensearchpy.helpers import bulk -except ImportError: - raise ImportError( - "OpenSearch requires extra dependencies. Install wit...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/opensearch.py
Create docstrings for API functions
import copy import os from typing import Any, Optional, Union try: from qdrant_client import QdrantClient from qdrant_client.http import models from qdrant_client.http.models import Batch from qdrant_client.models import Distance, VectorParams except ImportError: raise ImportError("Qdrant requires ...
--- +++ @@ -17,8 +17,15 @@ class QdrantDB(BaseVectorDB): + """ + Qdrant as vector database + """ def __init__(self, config: QdrantDBConfig = None): + """ + Qdrant as vector database + :param config. Qdrant database config to be used for connection + """ if config...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/qdrant.py
Replace inline comments with docstrings
import logging from typing import Any, Optional from embedchain.helpers.json_serializable import JSONSerializable logger = logging.getLogger(__name__) class BaseMessage(JSONSerializable): # The string content of the message. content: str # The created_by of the message. AI, Human, Bot etc. created...
--- +++ @@ -7,6 +7,11 @@ class BaseMessage(JSONSerializable): + """ + The base abstract message class. + + Messages are the inputs and outputs of Models. + """ # The string content of the message. content: str @@ -25,9 +30,11 @@ @property def type(self) -> str: + """Type of...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/memory/message.py
Add docstrings that explain inputs and outputs
import hashlib import logging import os from embedchain.helpers.json_serializable import register_deserializable from embedchain.loaders.base_loader import BaseLoader logger = logging.getLogger(__name__) @register_deserializable class DiscordLoader(BaseLoader): def __init__(self): if not os.environ.get...
--- +++ @@ -10,6 +10,9 @@ @register_deserializable class DiscordLoader(BaseLoader): + """ + Load data from a Discord Channel ID. + """ def __init__(self): if not os.environ.get("DISCORD_TOKEN"): @@ -94,6 +97,7 @@ } def load_data(self, channel_id: str): + """Load data fr...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/loaders/discord.py
Add docstrings that explain inputs and outputs
from typing import Any, Dict, List, Optional, Union import pyarrow as pa try: import lancedb except ImportError: raise ImportError('LanceDB is required. Install with pip install "embedchain[lancedb]"') from None from embedchain.config.vector_db.lancedb import LanceDBConfig from embedchain.helpers.json_serial...
--- +++ @@ -14,11 +14,19 @@ @register_deserializable class LanceDB(BaseVectorDB): + """ + LanceDB as vector database + """ def __init__( self, config: Optional[LanceDBConfig] = None, ): + """LanceDB as vector database. + + :param config: LanceDB database config, d...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/lancedb.py
Write docstrings for backend logic
import json import logging import uuid from typing import Any, Optional from embedchain.core.db.database import get_session from embedchain.core.db.models import ChatHistory as ChatHistoryModel from embedchain.memory.message import ChatMessage from embedchain.memory.utils import merge_metadata_dict logger = logging.g...
--- +++ @@ -41,6 +41,15 @@ return memory_id def delete(self, app_id: str, session_id: Optional[str] = None): + """ + Delete all chat history for a given app_id and session_id. + This is useful for deleting chat history for a given user. + + :param app_id: The app_id to delete ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/memory/base.py
Annotate my code with docstrings
import logging import os from typing import Optional, Union try: import pinecone except ImportError: raise ImportError( "Pinecone requires extra dependencies. Install with `pip install pinecone-text pinecone-client`" ) from None from pinecone_text.sparse import BM25Encoder from embedchain.config....
--- +++ @@ -21,11 +21,20 @@ @register_deserializable class PineconeDB(BaseVectorDB): + """ + Pinecone as vector database + """ def __init__( self, config: Optional[PineconeDBConfig] = None, ): + """Pinecone as vector database. + + :param config: Pinecone database ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/pinecone.py
Add docstrings for better understanding
import logging from typing import Any, Optional, Union from chromadb import Collection, QueryResult from langchain.docstore.document import Document from tqdm import tqdm from embedchain.config import ChromaDbConfig from embedchain.helpers.json_serializable import register_deserializable from embedchain.vectordb.base...
--- +++ @@ -27,8 +27,14 @@ @register_deserializable class ChromaDB(BaseVectorDB): + """Vector database using ChromaDB.""" def __init__(self, config: Optional[ChromaDbConfig] = None): + """Initialize a new ChromaDB instance + + :param config: Configuration options for Chroma, defaults to None ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/chroma.py
Document this script properly
import statistics from collections import defaultdict from typing import Dict, List, Union import nltk from bert_score import score as bert_score from nltk.translate.bleu_score import SmoothingFunction, sentence_bleu from nltk.translate.meteor_score import meteor_score from rouge_score import rouge_scorer from senten...
--- +++ @@ -1,3 +1,14 @@+""" +Borrowed from https://github.com/WujiangXu/AgenticMemory/blob/main/utils.py + +@article{xu2025mem, + title={A-mem: Agentic memory for llm agents}, + author={Xu, Wujiang and Liang, Zujie and Mei, Kai and Gao, Hang and Tan, Juntao + and Zhang, Yongfeng}, + journal={arXiv p...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/evaluation/metrics/utils.py
Provide docstrings following PEP 257
import datetime import itertools import json import logging import os import re import string from typing import Any from schema import Optional, Or, Schema from tqdm import tqdm from embedchain.models.data_type import DataType logger = logging.getLogger(__name__) def parse_content(content, type): implemented ...
--- +++ @@ -72,6 +72,16 @@ def clean_string(text): + """ + This function takes in a string and performs a series of text cleaning operations. + + Args: + text (str): The text to be cleaned. This is expected to be a string. + + Returns: + cleaned_text (str): The cleaned text after all the c...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/utils/misc.py
Document my Python code with docstrings
import logging from typing import Any, Optional, Union from embedchain.config import ZillizDBConfig from embedchain.helpers.json_serializable import register_deserializable from embedchain.vectordb.base import BaseVectorDB try: from pymilvus import ( Collection, CollectionSchema, DataType,...
--- +++ @@ -25,8 +25,14 @@ @register_deserializable class ZillizVectorDB(BaseVectorDB): + """Base class for vector database.""" def __init__(self, config: ZillizDBConfig = None): + """Initialize the database. Save the config and client as an attribute. + + :param config: Database configuratio...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/zilliz.py
Improve my code by adding docstrings
from embedchain.config.vector_db.base import BaseVectorDbConfig from embedchain.embedder.base import BaseEmbedder from embedchain.helpers.json_serializable import JSONSerializable class BaseVectorDB(JSONSerializable): def __init__(self, config: BaseVectorDbConfig): self.client = self._get_or_create_db() ...
--- +++ @@ -4,41 +4,79 @@ class BaseVectorDB(JSONSerializable): + """Base class for vector database.""" def __init__(self, config: BaseVectorDbConfig): + """Initialize the database. Save the config and client as an attribute. + + :param config: Database configuration class instance. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/base.py
Add docstrings including usage examples
import logging from typing import Any, Optional, Union try: from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk except ImportError: raise ImportError( "Elasticsearch requires extra dependencies. Install with `pip install --upgrade embedchain[elasticsearch]`" ) from No...
--- +++ @@ -1,196 +1,269 @@-import logging -from typing import Any, Optional, Union - -try: - from elasticsearch import Elasticsearch - from elasticsearch.helpers import bulk -except ImportError: - raise ImportError( - "Elasticsearch requires extra dependencies. Install with `pip install --upgrade embed...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/elasticsearch.py
Add docstrings following best practices
import argparse import json from collections import defaultdict import numpy as np from openai import OpenAI from mem0.memory.utils import extract_json client = OpenAI() ACCURACY_PROMPT = """ Your task is to label an answer to a question as ’CORRECT’ or ’WRONG’. You will be given the following data: (1) a quest...
--- +++ @@ -37,6 +37,7 @@ def evaluate_llm_judge(question, gold_answer, generated_answer): + """Evaluate the generated answer against the gold answer using an LLM judge.""" response = client.chat.completions.create( model="gpt-4o-mini", messages=[ @@ -55,6 +56,7 @@ def main(): + """...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/evaluation/metrics/llm_judge.py
Add minimal docstrings for each function
import copy import os from typing import Optional, Union try: import weaviate except ImportError: raise ImportError( "Weaviate requires extra dependencies. Install with `pip install --upgrade 'embedchain[weaviate]'`" ) from None from embedchain.config.vector_db.weaviate import WeaviateDBConfig fro...
--- +++ @@ -16,11 +16,19 @@ @register_deserializable class WeaviateDB(BaseVectorDB): + """ + Weaviate as vector database + """ def __init__( self, config: Optional[WeaviateDBConfig] = None, ): + """Weaviate as vector database. + :param config: Weaviate database co...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/vectordb/weaviate.py
Document this script properly
from typing import Optional from mem0.configs.llms.base import BaseLlmConfig class DeepSeekConfig(BaseLlmConfig): def __init__( self, # Base parameters model: Optional[str] = None, temperature: float = 0.1, api_key: Optional[str] = None, max_tokens: int = 2000, ...
--- +++ @@ -4,6 +4,10 @@ class DeepSeekConfig(BaseLlmConfig): + """ + Configuration class for DeepSeek-specific parameters. + Inherits from BaseLlmConfig and adds DeepSeek-specific settings. + """ def __init__( self, @@ -20,6 +24,21 @@ # DeepSeek-specific parameters deep...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/deepseek.py
Write docstrings for utility functions
from typing import Any, Dict, Optional from mem0.configs.llms.base import BaseLlmConfig class LMStudioConfig(BaseLlmConfig): def __init__( self, # Base parameters model: Optional[str] = None, temperature: float = 0.1, api_key: Optional[str] = None, max_tokens: int...
--- +++ @@ -4,6 +4,10 @@ class LMStudioConfig(BaseLlmConfig): + """ + Configuration class for LM Studio-specific parameters. + Inherits from BaseLlmConfig and adds LM Studio-specific settings. + """ def __init__( self, @@ -21,6 +25,22 @@ lmstudio_base_url: Optional[str] = None, ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/lmstudio.py
Add docstrings that explain purpose and usage
from typing import Any, Callable, List, Optional from mem0.configs.llms.base import BaseLlmConfig class OpenAIConfig(BaseLlmConfig): def __init__( self, # Base parameters model: Optional[str] = None, temperature: float = 0.1, api_key: Optional[str] = None, max_tok...
--- +++ @@ -4,6 +4,10 @@ class OpenAIConfig(BaseLlmConfig): + """ + Configuration class for OpenAI and OpenRouter-specific parameters. + Inherits from BaseLlmConfig and adds OpenAI-specific settings. + """ def __init__( self, @@ -28,6 +32,27 @@ # Response monitoring callback ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/openai.py
Write docstrings for algorithm functions
from typing import Optional from mem0.configs.llms.base import BaseLlmConfig class VllmConfig(BaseLlmConfig): def __init__( self, # Base parameters model: Optional[str] = None, temperature: float = 0.1, api_key: Optional[str] = None, max_tokens: int = 2000, ...
--- +++ @@ -4,6 +4,10 @@ class VllmConfig(BaseLlmConfig): + """ + Configuration class for vLLM-specific parameters. + Inherits from BaseLlmConfig and adds vLLM-specific settings. + """ def __init__( self, @@ -20,6 +24,21 @@ # vLLM-specific parameters vllm_base_url: Optio...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/vllm.py
Generate documentation strings for clarity
from typing import Any, Dict, Optional from pydantic import BaseModel, Field, model_validator class AzureMySQLConfig(BaseModel): host: str = Field(..., description="MySQL server host (e.g., myserver.mysql.database.azure.com)") port: int = Field(3306, description="MySQL server port") user: str = Field(.....
--- +++ @@ -4,6 +4,7 @@ class AzureMySQLConfig(BaseModel): + """Configuration for Azure MySQL vector database.""" host: str = Field(..., description="MySQL server host (e.g., myserver.mysql.database.azure.com)") port: int = Field(3306, description="MySQL server port") @@ -28,6 +29,7 @@ @model_val...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/vector_stores/azure_mysql.py
Create documentation strings for testing functions
from typing import Any, Dict, Optional from pydantic import BaseModel, ConfigDict, Field, model_validator from databricks.sdk.service.vectorsearch import EndpointType, VectorIndexType, PipelineType class DatabricksConfig(BaseModel): workspace_url: str = Field(..., description="Databricks workspace URL") ac...
--- +++ @@ -6,6 +6,7 @@ class DatabricksConfig(BaseModel): + """Configuration for Databricks Vector Search vector store.""" workspace_url: str = Field(..., description="Databricks workspace URL") access_token: Optional[str] = Field(None, description="Personal access token for authentication") @@ -44,...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/vector_stores/databricks.py
Generate missing documentation strings
from typing import Optional from mem0.configs.llms.base import BaseLlmConfig class OllamaConfig(BaseLlmConfig): def __init__( self, # Base parameters model: Optional[str] = None, temperature: float = 0.1, api_key: Optional[str] = None, max_tokens: int = 2000, ...
--- +++ @@ -4,6 +4,10 @@ class OllamaConfig(BaseLlmConfig): + """ + Configuration class for Ollama-specific parameters. + Inherits from BaseLlmConfig and adds Ollama-specific settings. + """ def __init__( self, @@ -20,6 +24,21 @@ # Ollama-specific parameters ollama_base_...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/ollama.py
Generate docstrings for script automation
import subprocess import sys from typing import Literal, Optional from mem0.configs.embeddings.base import BaseEmbedderConfig from mem0.embeddings.base import EmbeddingBase try: from ollama import Client except ImportError: user_input = input("The 'ollama' library is required. Install it now? [y/N]: ") if...
--- +++ @@ -32,10 +32,22 @@ self._ensure_model_exists() def _ensure_model_exists(self): + """ + Ensure the specified model exists locally. If not, pull it from Ollama. + """ local_models = self.client.list()["models"] if not any(model.get("name") == self.config.mode...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/embeddings/ollama.py
Document this module using docstrings
from pydantic import BaseModel, Field class NeptuneAnalyticsConfig(BaseModel): collection_name: str = Field("mem0", description="Default name for the collection") endpoint: str = Field("endpoint", description="Graph ID for the runtime") model_config = { "arbitrary_types_allowed": False, }
--- +++ @@ -1,11 +1,27 @@+""" +Configuration for Amazon Neptune Analytics vector store. + +This module provides configuration settings for integrating with Amazon Neptune Analytics +as a vector store backend for Mem0's memory layer. +""" from pydantic import BaseModel, Field class NeptuneAnalyticsConfig(BaseMod...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/vector_stores/neptune.py
Add docstrings with type hints explained
import logging from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional import httpx from pydantic import BaseModel, ConfigDict, Field from mem0.client.utils import api_error_handler from mem0.memory.telemetry import capture_client_event # Exception classes are referenced in docstrings only l...
--- +++ @@ -13,6 +13,9 @@ class ProjectConfig(BaseModel): + """ + Configuration for project management operations. + """ org_id: Optional[str] = Field(default=None, description="Organization ID") project_id: Optional[str] = Field(default=None, description="Project ID") @@ -22,6 +25,9 @@ cla...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/client/project.py
Add docstrings that explain inputs and outputs
from typing import Any, Dict, Optional class MemoryError(Exception): def __init__( self, message: str, error_code: str, details: Optional[Dict[str, Any]] = None, suggestion: Optional[str] = None, debug_info: Optional[Dict[str, Any]] = None, ): self...
--- +++ @@ -1,8 +1,59 @@+"""Structured exception classes for Mem0 with error codes, suggestions, and debug information. + +This module provides a comprehensive set of exception classes that replace the generic +APIError with specific, actionable exceptions. Each exception includes error codes, +user-friendly suggestion...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/exceptions.py
Add docstrings following best practices
from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field, model_validator class CassandraConfig(BaseModel): contact_points: List[str] = Field( ..., description="List of contact point addresses (e.g., ['127.0.0.1', '127.0.0.2'])" ) port: int = Field(9042, descrip...
--- +++ @@ -4,6 +4,7 @@ class CassandraConfig(BaseModel): + """Configuration for Apache Cassandra vector database.""" contact_points: List[str] = Field( ..., @@ -28,6 +29,7 @@ @model_validator(mode="before") @classmethod def check_auth(cls, values: Dict[str, Any]) -> Dict[str, Any]:...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/vector_stores/cassandra.py
Auto-generate documentation strings for this file
import json import logging import httpx from mem0.exceptions import ( NetworkError, create_exception_from_response, ) logger = logging.getLogger(__name__) class APIError(Exception): pass def api_error_handler(func): from functools import wraps @wraps(func) def wrapper(*args, **kwargs): ...
--- +++ @@ -11,11 +11,25 @@ class APIError(Exception): + """Exception raised for errors in the API. + + Deprecated: Use specific exception classes from mem0.exceptions instead. + This class is maintained for backward compatibility. + """ pass def api_error_handler(func): + """Decorato...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/client/utils.py
Add docstrings explaining edge cases
from abc import ABC, abstractmethod from typing import Literal, Optional from mem0.configs.embeddings.base import BaseEmbedderConfig class EmbeddingBase(ABC): def __init__(self, config: Optional[BaseEmbedderConfig] = None): if config is None: self.config = BaseEmbedderConfig() else: ...
--- +++ @@ -5,6 +5,11 @@ class EmbeddingBase(ABC): + """Initialized a base embedding class + + :param config: Embedding configuration option class, defaults to None + :type config: Optional[BaseEmbedderConfig], optional + """ def __init__(self, config: Optional[BaseEmbedderConfig] = None): ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/embeddings/base.py
Write docstrings for utility functions
import json import os import time from collections import defaultdict import numpy as np import tiktoken from dotenv import load_dotenv from jinja2 import Template from openai import OpenAI from tqdm import tqdm load_dotenv() PROMPT = """ # Question: {{QUESTION}} # Context: {{CONTEXT}} # Short answer: """ clas...
--- +++ @@ -80,6 +80,19 @@ return np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2)) def search(self, query, chunks, embeddings, k=1): + """ + Search for the top-k most similar chunks to the query. + + Args: + query: The query string...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/evaluation/src/rag.py
Add docstrings for internal functions
from typing import Any, Dict, Optional from mem0.configs.base import AzureConfig from mem0.configs.llms.base import BaseLlmConfig class AzureOpenAIConfig(BaseLlmConfig): def __init__( self, # Base parameters model: Optional[str] = None, temperature: float = 0.1, api_key: ...
--- +++ @@ -5,6 +5,10 @@ class AzureOpenAIConfig(BaseLlmConfig): + """ + Configuration class for Azure OpenAI-specific parameters. + Inherits from BaseLlmConfig and adds Azure OpenAI-specific settings. + """ def __init__( self, @@ -21,6 +25,21 @@ # Azure OpenAI-specific parameter...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/azure.py
Write reusable docstrings
import json from typing import Dict, List, Optional, Union try: from ollama import Client except ImportError: raise ImportError("The 'ollama' library is required. Please install it using 'pip install ollama'.") from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.ollama import OllamaConfig ...
--- +++ @@ -41,6 +41,16 @@ self.client = Client(host=self.config.ollama_base_url) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The list ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/ollama.py
Add docstrings including usage examples
import hashlib import logging import os import warnings from typing import Any, Dict, List, Optional, Union import httpx import requests from mem0.client.project import AsyncProject, Project from mem0.client.utils import api_error_handler # Exception classes are referenced in docstrings only from mem0.memory.setup im...
--- +++ @@ -22,6 +22,19 @@ class MemoryClient: + """Client for interacting with the Mem0 API. + + This class provides methods to create, retrieve, search, and delete + memories using the Mem0 API. + + Attributes: + api_key (str): The API key for authenticating with the Mem0 API. + host (st...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/client/main.py
Replace inline comments with docstrings
from typing import Optional from mem0.configs.llms.base import BaseLlmConfig class AnthropicConfig(BaseLlmConfig): def __init__( self, # Base parameters model: Optional[str] = None, temperature: float = 0.1, api_key: Optional[str] = None, max_tokens: int = 2000, ...
--- +++ @@ -4,6 +4,10 @@ class AnthropicConfig(BaseLlmConfig): + """ + Configuration class for Anthropic-specific parameters. + Inherits from BaseLlmConfig and adds Anthropic-specific settings. + """ def __init__( self, @@ -20,6 +24,21 @@ # Anthropic-specific parameters ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/anthropic.py
Turn comments into proper docstrings
from abc import ABC, abstractmethod from typing import Dict, List, Optional, Union from mem0.configs.llms.base import BaseLlmConfig class LLMBase(ABC): def __init__(self, config: Optional[Union[BaseLlmConfig, Dict]] = None): if config is None: self.config = BaseLlmConfig() elif isins...
--- +++ @@ -5,8 +5,17 @@ class LLMBase(ABC): + """ + Base class for all LLM providers. + Handles common functionality and delegates provider-specific logic to subclasses. + """ def __init__(self, config: Optional[Union[BaseLlmConfig, Dict]] = None): + """Initialize a base LLM class + + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/base.py
Add docstrings to meet PEP guidelines
import json import os from typing import Literal, Optional try: import boto3 except ImportError: raise ImportError("The 'boto3' library is required. Please install it using 'pip install boto3'.") import numpy as np from mem0.configs.embeddings.base import BaseEmbedderConfig from mem0.embeddings.base import E...
--- +++ @@ -14,6 +14,10 @@ class AWSBedrockEmbedding(EmbeddingBase): + """AWS Bedrock embedding implementation. + + This class uses AWS Bedrock's embedding models. + """ def __init__(self, config: Optional[BaseEmbedderConfig] = None): super().__init__(config) @@ -43,11 +47,13 @@ ) ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/embeddings/aws_bedrock.py
Fully document this Python code with docstrings
import logging from .base import NeptuneBase try: from langchain_aws import NeptuneAnalyticsGraph from botocore.config import Config except ImportError: raise ImportError("langchain_aws is not installed. Please install it using 'make install_all'.") logger = logging.getLogger(__name__) class MemoryGrap...
--- +++ @@ -43,6 +43,15 @@ self.threshold = self.config.graph_store.threshold if hasattr(self.config.graph_store, 'threshold') else 0.7 def _delete_entities_cypher(self, source, destination, relationship, user_id): + """ + Returns the OpenCypher query and parameters for deleting entities in...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/graphs/neptune/neptunegraph.py
Document this module using docstrings
import json import os from typing import Dict, List, Optional, Union from azure.identity import DefaultAzureCredential, get_bearer_token_provider from openai import AzureOpenAI from mem0.configs.llms.azure import AzureOpenAIConfig from mem0.configs.llms.base import BaseLlmConfig from mem0.llms.base import LLMBase fro...
--- +++ @@ -68,6 +68,16 @@ ) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The list of tools provided in the request. + + Returns:...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/azure_openai.py
Add professional docstrings to my codebase
import json import os from typing import Dict, List, Optional, Union from openai import OpenAI from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.vllm import VllmConfig from mem0.llms.base import LLMBase from mem0.memory.utils import extract_json class VllmLLM(LLMBase): def __init__(self, c...
--- +++ @@ -41,6 +41,16 @@ self.client = OpenAI(api_key=self.config.api_key, base_url=base_url) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + to...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/vllm.py
Add docstrings explaining edge cases
import json from typing import Dict, List, Optional, Union from openai import OpenAI from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.lmstudio import LMStudioConfig from mem0.llms.base import LLMBase from mem0.memory.utils import extract_json class LMStudioLLM(LLMBase): def __init__(self,...
--- +++ @@ -41,6 +41,16 @@ self.client = OpenAI(base_url=self.config.lmstudio_base_url, api_key=self.config.api_key) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/lmstudio.py
Add clean documentation to messy code
import json import logging import re from typing import Any, Dict, List, Optional, Union try: import boto3 from botocore.exceptions import ClientError, NoCredentialsError except ImportError: raise ImportError("The 'boto3' library is required. Please install it using 'pip install boto3'.") from mem0.config...
--- +++ @@ -23,6 +23,7 @@ def extract_provider(model: str) -> str: + """Extract provider from model identifier.""" for provider in PROVIDERS: if re.search(rf"\b{re.escape(provider)}\b", model): return provider @@ -30,8 +31,19 @@ class AWSBedrockLLM(LLMBase): + """ + AWS Bedro...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/aws_bedrock.py
Write reusable docstrings
import os from typing import Any, Dict, List, Optional from mem0.configs.llms.base import BaseLlmConfig class AWSBedrockConfig(BaseLlmConfig): def __init__( self, model: Optional[str] = None, temperature: float = 0.1, max_tokens: int = 2000, top_p: float = 0.9, to...
--- +++ @@ -5,6 +5,11 @@ class AWSBedrockConfig(BaseLlmConfig): + """ + Configuration class for AWS Bedrock LLM integration. + + Supports all available Bedrock models with automatic provider detection. + """ def __init__( self, @@ -21,6 +26,23 @@ model_kwargs: Optional[Dict[str, ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/aws_bedrock.py
Write docstrings for backend logic
import json import logging import os from typing import Dict, List, Optional, Union from openai import OpenAI from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.openai import OpenAIConfig from mem0.llms.base import LLMBase from mem0.memory.utils import extract_json class OpenAILLM(LLMBase): ...
--- +++ @@ -51,6 +51,16 @@ self.client = OpenAI(api_key=api_key, base_url=base_url) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/openai.py
Add docstrings with type hints explained
from abc import ABC from typing import Dict, Optional, Union import httpx class BaseLlmConfig(ABC): def __init__( self, model: Optional[Union[str, Dict]] = None, temperature: float = 0.1, api_key: Optional[str] = None, max_tokens: int = 2000, top_p: float = 0.1, ...
--- +++ @@ -5,6 +5,13 @@ class BaseLlmConfig(ABC): + """ + Base configuration for LLMs with only common parameters. + Provider-specific configurations should be handled by separate config classes. + + This class contains only the parameters that are common across all LLM providers. + For provider-spe...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/configs/llms/base.py
Write beginner-friendly docstrings
import json import os from typing import Dict, List, Optional try: from together import Together except ImportError: raise ImportError("The 'together' library is required. Please install it using 'pip install together'.") from mem0.configs.llms.base import BaseLlmConfig from mem0.llms.base import LLMBase from...
--- +++ @@ -23,6 +23,16 @@ self.client = Together(api_key=api_key) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The list of tools provid...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/together.py
Add documentation for all methods
from typing import List, Dict, Any, Union import numpy as np from mem0.reranker.base import BaseReranker from mem0.configs.rerankers.base import BaseRerankerConfig from mem0.configs.rerankers.huggingface import HuggingFaceRerankerConfig try: from transformers import AutoTokenizer, AutoModelForSequenceClassificati...
--- +++ @@ -14,8 +14,15 @@ class HuggingFaceReranker(BaseReranker): + """HuggingFace Transformers based reranker implementation.""" def __init__(self, config: Union[BaseRerankerConfig, HuggingFaceRerankerConfig, Dict]): + """ + Initialize HuggingFace reranker. + + Args: + c...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/reranker/huggingface_reranker.py
Write reusable docstrings
import re from typing import List, Dict, Any, Union from mem0.reranker.base import BaseReranker from mem0.utils.factory import LlmFactory from mem0.configs.rerankers.base import BaseRerankerConfig from mem0.configs.rerankers.llm import LLMRerankerConfig class LLMReranker(BaseReranker): def __init__(self, config...
--- +++ @@ -8,8 +8,15 @@ class LLMReranker(BaseReranker): + """LLM-based reranker implementation.""" def __init__(self, config: Union[BaseRerankerConfig, LLMRerankerConfig, Dict]): + """ + Initialize LLM reranker. + + Args: + config: Configuration object with reranker param...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/reranker/llm_reranker.py
Help me document legacy Python code
import hashlib import logging import re from mem0.configs.prompts import ( AGENT_MEMORY_EXTRACTION_PROMPT, FACT_RETRIEVAL_PROMPT, USER_MEMORY_EXTRACTION_PROMPT, ) logger = logging.getLogger(__name__) def get_fact_retrieval_messages(message, is_agent_memory=False): if is_agent_memory: return ...
--- +++ @@ -12,6 +12,15 @@ def get_fact_retrieval_messages(message, is_agent_memory=False): + """Get fact retrieval messages based on the memory type. + + Args: + message: The message content to extract facts from + is_agent_memory: If True, use agent memory extraction prompt, else use user ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/memory/utils.py
Write docstrings for this repository
import os from typing import List, Dict, Any from mem0.reranker.base import BaseReranker try: import cohere COHERE_AVAILABLE = True except ImportError: COHERE_AVAILABLE = False class CohereReranker(BaseReranker): def __init__(self, config): if not COHERE_AVAILABLE: raise Imp...
--- +++ @@ -11,8 +11,15 @@ class CohereReranker(BaseReranker): + """Cohere-based reranker implementation.""" def __init__(self, config): + """ + Initialize Cohere reranker. + + Args: + config: CohereRerankerConfig object with configuration parameters + ""...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/reranker/cohere_reranker.py
Add docstrings including usage examples
import logging import sqlite3 import threading import uuid from typing import Any, Dict, List, Optional logger = logging.getLogger(__name__) class SQLiteManager: def __init__(self, db_path: str = ":memory:"): self.db_path = db_path self.connection = sqlite3.connect(self.db_path, check_same_thread...
--- +++ @@ -16,6 +16,11 @@ self._create_history_table() def _migrate_history_table(self) -> None: + """ + If a pre-existing history table had the old group-chat columns, + rename it, create the new schema, copy the intersecting data, then + drop the old table. + """ ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/memory/storage.py
Generate consistent documentation across files
from typing import List, Dict, Any, Union import numpy as np from mem0.reranker.base import BaseReranker from mem0.configs.rerankers.base import BaseRerankerConfig from mem0.configs.rerankers.sentence_transformer import SentenceTransformerRerankerConfig try: from sentence_transformers import SentenceTransformer ...
--- +++ @@ -13,8 +13,15 @@ class SentenceTransformerReranker(BaseReranker): + """Sentence Transformer based reranker implementation.""" def __init__(self, config: Union[BaseRerankerConfig, SentenceTransformerRerankerConfig, Dict]): + """ + Initialize Sentence Transformer reranker. + + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/reranker/sentence_transformer_reranker.py
Can you add docstrings to this Python file?
import os from typing import List, Dict, Any from mem0.reranker.base import BaseReranker try: from zeroentropy import ZeroEntropy ZERO_ENTROPY_AVAILABLE = True except ImportError: ZERO_ENTROPY_AVAILABLE = False class ZeroEntropyReranker(BaseReranker): def __init__(self, config): if not ...
--- +++ @@ -11,8 +11,15 @@ class ZeroEntropyReranker(BaseReranker): + """Zero Entropy-based reranker implementation.""" def __init__(self, config): + """ + Initialize Zero Entropy reranker. + + Args: + config: ZeroEntropyRerankerConfig object with configuration ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/reranker/zero_entropy_reranker.py
Improve documentation using docstrings
import json import logging from contextlib import contextmanager from typing import Any, Dict, List, Optional from pydantic import BaseModel try: import pymysql from pymysql.cursors import DictCursor from dbutils.pooled_db import PooledDB except ImportError: raise ImportError( "Azure MySQL vec...
--- +++ @@ -49,6 +49,24 @@ maxconn: int = 5, connection_pool: Optional[Any] = None, ): + """ + Initialize the Azure MySQL vector store. + + Args: + host (str): MySQL server host + port (int): MySQL server port + user (str): Database user + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/azure_mysql.py
Write clean docstrings for readability
from abc import ABC, abstractmethod class VectorStoreBase(ABC): @abstractmethod def create_col(self, name, vector_size, distance): pass @abstractmethod def insert(self, vectors, payloads=None, ids=None): pass @abstractmethod def search(self, query, vectors, limit=5, filters=N...
--- +++ @@ -4,44 +4,55 @@ class VectorStoreBase(ABC): @abstractmethod def create_col(self, name, vector_size, distance): + """Create a new collection.""" pass @abstractmethod def insert(self, vectors, payloads=None, ids=None): + """Insert vectors into a collection.""" ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/base.py
Add docstrings for utility scripts
import os import json from typing import Optional, Dict, Any try: from google.oauth2 import service_account from google.auth import default import google.auth.credentials except ImportError: raise ImportError("google-auth is required for GCP authentication. Install with: pip install google-auth") cla...
--- +++ @@ -11,6 +11,15 @@ class GCPAuthenticator: + """ + Centralized GCP authentication handler that supports multiple credential methods. + + Priority order: + 1. service_account_json (dict) - In-memory service account credentials + 2. credentials_path (str) - Path to service account JSON file + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/utils/gcp_auth.py
Write clean docstrings for readability
import importlib from typing import Dict, Optional, Union from mem0.configs.embeddings.base import BaseEmbedderConfig from mem0.configs.llms.anthropic import AnthropicConfig from mem0.configs.llms.azure import AzureOpenAIConfig from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.deepseek import Dee...
--- +++ @@ -26,6 +26,10 @@ class LlmFactory: + """ + Factory for creating LLM instances with appropriate configurations. + Supports both old-style BaseLlmConfig and new provider-specific configs. + """ # Provider mappings with their config classes provider_to_class = { @@ -50,6 +54,20 @@ ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/utils/factory.py
Add docstrings for internal functions
import logging from typing import Dict, List, Optional from pydantic import BaseModel try: import chromadb from chromadb.config import Settings except ImportError: raise ImportError("The 'chromadb' library is required. Please install it using 'pip install chromadb'.") from mem0.vector_stores.base import ...
--- +++ @@ -31,6 +31,18 @@ api_key: Optional[str] = None, tenant: Optional[str] = None, ): + """ + Initialize the Chromadb vector store. + + Args: + collection_name (str): Name of the collection. + client (chromadb.Client, optional): Existing chromadb cli...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/chroma.py
Replace inline comments with docstrings
import logging import time from typing import Any, Dict, List, Optional try: from opensearchpy import OpenSearch, RequestsHttpConnection except ImportError: raise ImportError("OpenSearch requires extra dependencies. Install with `pip install opensearch-py`") from None from pydantic import BaseModel from mem0...
--- +++ @@ -42,6 +42,7 @@ self.create_col(self.collection_name, self.embedding_model_dims) def create_index(self) -> None: + """Create OpenSearch index with proper mappings if it doesn't exist.""" index_settings = { "settings": { "index": {"number_of_replicas...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/opensearch.py
Add detailed docstrings explaining each function
import json import logging import uuid from typing import Any, Dict, List, Optional import numpy as np from pydantic import BaseModel try: from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider except ImportError: raise ImportError( "Apache Cassandra vector store re...
--- +++ @@ -40,6 +40,21 @@ protocol_version: int = 4, load_balancing_policy: Optional[Any] = None, ): + """ + Initialize the Apache Cassandra vector store. + + Args: + contact_points (List[str]): List of contact point addresses (e.g., ['127.0.0.1']) + por...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/cassandra.py
Add docstrings for better understanding
import logging from typing import Any, Dict, List, Optional try: from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk except ImportError: raise ImportError("Elasticsearch requires extra dependencies. Install with `pip install elasticsearch`") from None from pydantic import BaseMo...
--- +++ @@ -54,6 +54,7 @@ self.custom_search_query = None def create_index(self) -> None: + """Create Elasticsearch index with proper mappings if it doesn't exist""" index_settings = { "settings": {"index": {"number_of_replicas": 1, "number_of_shards": 5, "refresh_interva...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/elasticsearch.py
Expand my code with proper documentation strings
import json import logging import uuid from typing import Optional, List from datetime import datetime, date from databricks.sdk.service.catalog import ColumnInfo, ColumnTypeName, TableType, DataSourceFormat from databricks.sdk.service.catalog import TableConstraint, PrimaryKeyConstraint from databricks.sdk import Work...
--- +++ @@ -51,6 +51,29 @@ warehouse_name: Optional[str] = None, query_type: str = "ANN", ): + """ + Initialize the Databricks Vector Search vector store. + + Args: + workspace_url (str): Databricks workspace URL. + access_token (str, optional): Personal ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/databricks.py
Add docstrings that explain logic
import logging import time import uuid from typing import Dict, List, Optional from pydantic import BaseModel try: from langchain_aws import NeptuneAnalyticsGraph except ImportError: raise ImportError("langchain_aws is not installed. Please install it using pip install langchain_aws") from mem0.vector_stores...
--- +++ @@ -21,6 +21,12 @@ class NeptuneAnalyticsVector(VectorStoreBase): + """ + Neptune Analytics vector store implementation for Mem0. + + Provides vector storage and similarity search capabilities using Amazon Neptune Analytics, + a serverless graph analytics service that supports vector operati...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/neptune_analytics.py
Expand my code with proper documentation strings
import logging import time from typing import Dict, Optional from pydantic import BaseModel from mem0.vector_stores.base import VectorStoreBase try: import pymochow from pymochow.auth.bce_credentials import BceCredentials from pymochow.configuration import Configuration from pymochow.exception import...
--- +++ @@ -56,6 +56,17 @@ embedding_model_dims: int, metric_type: MetricType, ) -> None: + """Initialize the BaiduDB database. + + Args: + endpoint (str): Endpoint URL for Baidu VectorDB. + account (str): Account for Baidu VectorDB. + api_key (str): ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/baidu.py
Write Python docstrings for this snippet
import json import logging from datetime import datetime from typing import Dict import numpy as np import pytz import valkey from pydantic import BaseModel from valkey.exceptions import ResponseError from mem0.memory.utils import extract_json from mem0.vector_stores.base import VectorStoreBase logger = logging.getL...
--- +++ @@ -53,6 +53,19 @@ hnsw_ef_construction: int = 200, hnsw_ef_runtime: int = 10, ): + """ + Initialize the Valkey vector store. + + Args: + valkey_url (str): Valkey URL. + collection_name (str): Collection name. + embedding_model_dims (in...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/valkey.py
Generate docstrings with parameter types
import json import logging from contextlib import contextmanager from typing import Any, List, Optional from pydantic import BaseModel # Try to import psycopg (psycopg3) first, then fall back to psycopg2 try: from psycopg.types.json import Json from psycopg_pool import ConnectionPool PSYCOPG_VERSION = 3 ...
--- +++ @@ -54,6 +54,25 @@ connection_string=None, connection_pool=None, ): + """ + Initialize the PGVector database. + + Args: + dbname (str): Database name + collection_name (str): Collection name + embedding_model_dims (int): Dimension of th...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/pgvector.py
Create structured documentation for my script
import logging import os from typing import Any, Dict, List, Optional, Union from pydantic import BaseModel try: from pinecone import Pinecone, PodSpec, ServerlessSpec, Vector except ImportError: raise ImportError( "Pinecone requires extra dependencies. Install with `pip install pinecone pinecone-text...
--- +++ @@ -38,6 +38,23 @@ extra_params: Optional[Dict[str, Any]], namespace: Optional[str] = None, ): + """ + Initialize the Pinecone vector store. + + Args: + collection_name (str): Name of the index/collection. + embedding_model_dims (int): Dimensions ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/pinecone.py
Help me document legacy Python code
import logging from importlib.metadata import version from typing import Any, Dict, List, Optional from pydantic import BaseModel try: from pymongo import MongoClient from pymongo.driver_info import DriverInfo from pymongo.errors import PyMongoError from pymongo.operations import SearchIndexModel exce...
--- +++ @@ -30,6 +30,15 @@ SIMILARITY_METRIC = "cosine" def __init__(self, db_name: str, collection_name: str, embedding_model_dims: int, mongo_uri: str): + """ + Initialize the MongoDB vector store with vector search capabilities. + + Args: + db_name (str): Database name + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/mongodb.py
Help me document legacy Python code
import logging from typing import Dict, List, Optional from pydantic import BaseModel from mem0.vector_stores.base import VectorStoreBase try: from upstash_vector import Index except ImportError: raise ImportError("The 'upstash_vector' library is required. Please install it using 'pip install upstash_vector'...
--- +++ @@ -29,6 +29,15 @@ client: Optional[Index] = None, enable_embeddings: bool = False, ): + """ + Initialize the UpstashVector vector store. + + Args: + url (str, optional): URL for Upstash Vector index. Defaults to None. + token (int, optional): Tok...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/upstash_vector.py
Generate docstrings with parameter types
import json import logging from datetime import datetime from functools import reduce import numpy as np import pytz import redis from redis.commands.search.query import Query from redisvl.index import SearchIndex from redisvl.query import VectorQuery from redisvl.query.filter import Tag from mem0.memory.utils import...
--- +++ @@ -52,6 +52,14 @@ collection_name: str, embedding_model_dims: int, ): + """ + Initialize the Redis vector store. + + Args: + redis_url (str): Redis URL. + collection_name (str): Collection name. + embedding_model_dims (int): Embedding ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/redis.py
Document all public functions with docstrings
import logging from typing import Dict, Optional from pydantic import BaseModel from mem0.configs.vector_stores.milvus import MetricType from mem0.vector_stores.base import VectorStoreBase try: import pymilvus # noqa: F401 except ImportError: raise ImportError("The 'pymilvus' library is required. Please ins...
--- +++ @@ -32,6 +32,16 @@ metric_type: MetricType, db_name: str, ) -> None: + """Initialize the MilvusDB database. + + Args: + url (str): Full URL for Milvus/Zilliz server. + token (str): Token/api_key for Zilliz server / for local setup defaults to None. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/milvus.py
Add docstrings following best practices
import logging import os import pickle import uuid from pathlib import Path from typing import Dict, List, Optional import numpy as np from pydantic import BaseModel import warnings try: # Suppress SWIG deprecation warnings from FAISS warnings.filterwarnings("ignore", category=DeprecationWarning, message=".*...
--- +++ @@ -46,6 +46,17 @@ normalize_L2: bool = False, embedding_model_dims: int = 1536, ): + """ + Initialize the FAISS vector store. + + Args: + collection_name (str): Name of the collection. + path (str, optional): Path for local FAISS database. Defaul...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/faiss.py
Add missing documentation to my Python functions
import json import logging import re from typing import List, Optional from pydantic import BaseModel from mem0.memory.utils import extract_json from mem0.vector_stores.base import VectorStoreBase try: from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import ResourceNotFoundErr...
--- +++ @@ -52,6 +52,21 @@ hybrid_search: bool = False, vector_filter_mode: Optional[str] = None, ): + """ + Initialize the Azure AI Search vector store. + + Args: + service_name (str): Azure AI Search service name. + collection_name (str): Index name. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/azure_ai_search.py
Add minimal docstrings for each function
import json import os from typing import Dict, List, Optional try: from groq import Groq except ImportError: raise ImportError("The 'groq' library is required. Please install it using 'pip install groq'.") from mem0.configs.llms.base import BaseLlmConfig from mem0.llms.base import LLMBase from mem0.memory.uti...
--- +++ @@ -23,6 +23,16 @@ self.client = Groq(api_key=api_key) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The list of tools provided i...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/groq.py
Improve documentation using docstrings
import logging import traceback import uuid from typing import Any, Dict, List, Optional, Tuple import google.api_core.exceptions from google.cloud import aiplatform, aiplatform_v1 from google.cloud.aiplatform.matching_engine.matching_engine_index_endpoint import Namespace from google.oauth2 import service_account fro...
--- +++ @@ -32,6 +32,7 @@ class GoogleMatchingEngine(VectorStoreBase): def __init__(self, **kwargs): + """Initialize Google Matching Engine client.""" logger.debug("Initializing Google Matching Engine with kwargs: %s", kwargs) # If collection_name is passed, use it as deployment_index_...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/vertex_ai_vector_search.py
Add docstrings explaining edge cases
import os import sys from logging.config import fileConfig from alembic import context from dotenv import load_dotenv from sqlalchemy import engine_from_config, pool # Add the parent directory to the Python path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Load environment variables...
--- +++ @@ -35,6 +35,17 @@ def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/openmemory/api/alembic/env.py
Add docstrings to improve code quality
import logging import os import shutil from qdrant_client import QdrantClient from qdrant_client.models import ( Distance, FieldCondition, Filter, MatchValue, PointIdsList, PointStruct, Range, VectorParams, ) from mem0.vector_stores.base import VectorStoreBase logger = logging.getLogg...
--- +++ @@ -32,6 +32,20 @@ api_key: str = None, on_disk: bool = False, ): + """ + Initialize the Qdrant vector store. + + Args: + collection_name (str): Name of the collection. + embedding_model_dims (int): Dimensions of the embedding model. + ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/qdrant.py