### Run Quickstart Example Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/index.md Execute the quickstart example using the core API with the uv unicorn server. ```bash uv run python examples/quickstart.py ``` -------------------------------- ### FastEmbed Embedding Adapter Setup Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/custom-providers.md Installation and usage of the local FastEmbed adapter. ```bash uv add memvee[local] ``` ```python from memv.embeddings import FastEmbedAdapter embedder = FastEmbedAdapter() # BAAI/bge-small-en-v1.5 (384 dims) embedder = FastEmbedAdapter(model="BAAI/bge-base-en-v1.5") # 768 dims ``` -------------------------------- ### Clone and Install Project Source: https://github.com/vstorm-co/memv/blob/main/CONTRIBUTING.md Clone the repository and install project dependencies using make install. ```bash git clone https://github.com/vstorm-co/memv.git cd memv make install ``` -------------------------------- ### Development Setup Commands Source: https://github.com/vstorm-co/memv/blob/main/CLAUDE.md Commands for managing dependencies and environment setup using uv. ```bash make install # uv sync + pre-commit hooks make sync # update deps ``` -------------------------------- ### Run LangGraph Example Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/index.md Execute the LangGraph integration example with the uv unicorn server. ```bash uv run python examples/langgraph_agent.py ``` -------------------------------- ### Run LlamaIndex Example Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/index.md Execute the LlamaIndex integration example with the uv unicorn server. ```bash uv run python examples/llamaindex_agent.py ``` -------------------------------- ### Run AutoGen Example Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/index.md Execute the Microsoft AutoGen integration example with the uv unicorn server. ```bash uv run python examples/autogen_agent.py ``` -------------------------------- ### Cohere Embedding Adapter Setup Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/custom-providers.md Installation and usage of the Cohere embedding adapter. ```bash uv add memvee[cohere] ``` ```python from memv.embeddings import CohereEmbedAdapter embedder = CohereEmbedAdapter() # embed-v4.0 (1024 dims) embedder = CohereEmbedAdapter(model="embed-english-light-v3.0") # 384 dims ``` -------------------------------- ### Run Full Demo Example Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/index.md Execute the full demo example using the core API with the uv unicorn server. ```bash uv run python examples/demo.py ``` -------------------------------- ### OpenAI Embedding Adapter Setup Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/custom-providers.md Installation and usage of the OpenAI embedding adapter. ```bash uv add memvee # included by default ``` ```python from memv.embeddings import OpenAIEmbedAdapter embedder = OpenAIEmbedAdapter() # text-embedding-3-small (1536 dims) embedder = OpenAIEmbedAdapter(model="text-embedding-3-large") # 3072 dims ``` -------------------------------- ### Run PydanticAI Example Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/index.md Execute the PydanticAI integration example with the uv unicorn server. ```bash uv run python examples/pydantic_ai_agent.py ``` -------------------------------- ### Install Memv development environment Source: https://github.com/vstorm-co/memv/blob/main/README.md Use these commands to clone the repository and install necessary dependencies. ```bash git clone https://github.com/vstorm-co/memv.git cd memv make install make all ``` -------------------------------- ### Voyage Embedding Adapter Setup Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/custom-providers.md Installation and usage of the Voyage embedding adapter. ```bash uv add memvee[voyage] ``` ```python from memv.embeddings import VoyageEmbedAdapter embedder = VoyageEmbedAdapter() # voyage-3-lite (1024 dims) embedder = VoyageEmbedAdapter(model="voyage-3") # voyage-3 (1024 dims) ``` -------------------------------- ### Run CrewAI Agent Example Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/crewai.md Executes the CrewAI agent example script using uv run. Requires pip install crewai. ```bash uv run python examples/crewai_agent.py ``` -------------------------------- ### Install memv with PostgreSQL support Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/postgres.md Commands to install the necessary dependencies for PostgreSQL integration. ```bash uv add memvee[postgres] # or: pip install memvee[postgres] ``` -------------------------------- ### Initialize Memory with Docker instance Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/postgres.md Example of connecting to the local Dockerized PostgreSQL instance. ```python memory = Memory( db_url="postgresql://memv:memv@localhost:5432/memv", embedding_client=embedder, llm_client=llm, ) ``` -------------------------------- ### Install Memvee via uv Source: https://github.com/vstorm-co/memv/blob/main/docs/installation.md Install the core package or the package with PostgreSQL support using the uv package manager. ```bash uv add memvee ``` ```bash uv add memvee[postgres] ``` -------------------------------- ### Install AutoGen Dependencies Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/autogen.md Install the necessary packages for AutoGen integration with memv. ```bash pip install autogen-agentchat autogen-ext[openai] ``` -------------------------------- ### Initialize Alternative Embedding Adapters Source: https://context7.com/vstorm-co/memv/llms.txt Shows initialization for Voyage, Cohere, and local FastEmbed adapters. Installation instructions and default/alternative models with their dimensions are provided. ```python # Voyage embeddings (install: uv add memvee[voyage]) from memv.embeddings import VoyageEmbedAdapter voyage = VoyageEmbedAdapter() # voyage-3-lite (1024 dims) voyage = VoyageEmbedAdapter(model="voyage-3") # voyage-3 (1024 dims) # Cohere embeddings (install: uv add memvee[cohere]) from memv.embeddings import CohereEmbedAdapter cohere = CohereEmbedAdapter() # embed-v4.0 (1024 dims) cohere = CohereEmbedAdapter(model="embed-english-light-v3.0") # 384 dims # Local embeddings - no API key needed (install: uv add memvee[local]) from memv.embeddings import FastEmbedAdapter local = FastEmbedAdapter() # BAAI/bge-small-en-v1.5 (384 dims) local = FastEmbedAdapter(model="BAAI/bge-base-en-v1.5") # 768 dims ``` -------------------------------- ### Install memv Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/sqlite.md Use a package manager to add the memv library to your project. ```bash uv add memvee # or: pip install memvee ``` -------------------------------- ### Install Memvee via pip Source: https://github.com/vstorm-co/memv/blob/main/docs/installation.md Install the core package or the package with PostgreSQL support using pip. ```bash pip install memvee ``` ```bash pip install memvee[postgres] # with PostgreSQL ``` -------------------------------- ### Configure LLM providers Source: https://github.com/vstorm-co/memv/blob/main/docs/getting-started.md Examples of initializing the PydanticAIAdapter with different supported LLM providers. ```python from memv.llm import PydanticAIAdapter llm = PydanticAIAdapter("openai:gpt-4o-mini") ``` ```python from memv.llm import PydanticAIAdapter llm = PydanticAIAdapter("anthropic:claude-3-5-sonnet-latest") ``` ```python from memv.llm import PydanticAIAdapter llm = PydanticAIAdapter("google-gla:gemini-2.5-flash") ``` ```python from memv.llm import PydanticAIAdapter llm = PydanticAIAdapter("groq:llama-3.3-70b-versatile") ``` -------------------------------- ### Run Agent Integration Source: https://github.com/vstorm-co/memv/blob/main/examples/README.md Execute the interactive chat agent example using the raw OpenAI client. ```bash uv run python examples/agent_integration.py ``` -------------------------------- ### Install memvee with PostgreSQL and Voyage Embeddings Source: https://context7.com/vstorm-co/memv/llms.txt Install the memvee package with support for PostgreSQL databases and Voyage embedding models. Alternatively, use 'pip install memvee[postgres,voyage]'. ```bash uv add memvee[postgres,voyage] ``` -------------------------------- ### Define Memory Context and System Prompt Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/pydantic-ai.md Setup the dataclass for dependency injection and the system prompt decorator to include memory context. ```python @dataclass class MemoryContext: user_id: str context_prompt: str agent: Agent[MemoryContext, str] = Agent( "openai:gpt-4o-mini", deps_type=MemoryContext, system_prompt="You are a helpful assistant with memory.", ) @agent.system_prompt def add_memory_context(ctx: RunContext[MemoryContext]) -> str: if ctx.deps.context_prompt: return f"\n\n{ctx.deps.context_prompt}" return "" ``` -------------------------------- ### Public API Usage Source: https://github.com/vstorm-co/memv/blob/main/CLAUDE.md Example of interacting with the Memory class as an async context manager. ```python async with memory: await memory.add_exchange(user_id, user_msg, assistant_msg) # store conversation pair await memory.add_message(message) # store single Message await memory.process(user_id) # extract knowledge (blocking) result = await memory.retrieve("query", user_id=user_id) # hybrid search result.to_prompt() # format for LLM context await memory.clear_user(user_id) # delete all user data ``` -------------------------------- ### Configure Memv with PostgreSQL Backend Source: https://context7.com/vstorm-co/memv/llms.txt Set up Memv to use PostgreSQL with pgvector for production deployments. This example shows direct configuration and using MemoryConfig for explicit backend selection. Ensure your PostgreSQL instance is running and accessible. ```python import asyncio from memv import Memory, MemoryConfig from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter async def main(): # PostgreSQL connection URL memory = Memory( db_url="postgresql://user:password@localhost:5432/mydb", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) # Or explicitly set backend config = MemoryConfig( backend="postgres", db_url="postgresql://user:password@localhost:5432/mydb", ) memory = Memory( config=config, embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: await memory.add_exchange( user_id="user-123", user_message="Hello!", assistant_message="Hi there!", ) asyncio.run(main()) # Docker quickstart for PostgreSQL with pgvector: # docker run -d \ # --name memv-postgres \ # -e POSTGRES_USER=memv \ # -e POSTGRES_PASSWORD=memv \ # -e POSTGRES_DB=memv \ # -p 5432:5432 \ # pgvector/pgvector:pg17 ``` -------------------------------- ### Common Configuration: Minimal (no optional processing) Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/configuration.md Example configuration for minimal processing, disabling optional features like episode merging, knowledge deduplication, and embedding caching. ```APIDOC ## Common Configuration: Minimal (no optional processing) ### Description This configuration disables optional processing features to minimize resource usage and complexity. ### Method Instantiation with Minimal Configuration ### Endpoint N/A (Class Initialization) ### Parameters #### Request Body - **enable_episode_merging** (bool) - `False` - **enable_knowledge_dedup** (bool) - `False` - **enable_embedding_cache** (bool) - `False` ### Request Example ```python memory = Memory( enable_episode_merging=False, enable_knowledge_dedup=False, enable_embedding_cache=False, # ... ) ``` ### Response N/A (Class Initialization) ``` -------------------------------- ### Common Configuration: Precision extraction (slower, more accurate) Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/configuration.md Example configuration for precision extraction, prioritizing accuracy over speed by increasing prediction and similarity thresholds. ```APIDOC ## Common Configuration: Precision extraction (slower, more accurate) ### Description This configuration prioritizes accuracy and precision in memory extraction, potentially at the cost of higher processing time and token usage. ### Method Instantiation with Precision Extraction Configuration ### Endpoint N/A (Class Initialization) ### Parameters #### Request Body - **max_statements_for_prediction** (int) - `20` - **knowledge_dedup_threshold** (float) - `0.95` - **merge_similarity_threshold** (float) - `0.95` ### Request Example ```python memory = Memory( max_statements_for_prediction=20, knowledge_dedup_threshold=0.95, merge_similarity_threshold=0.95, # ... ) ``` ### Response N/A (Class Initialization) ``` -------------------------------- ### Anthropic LLM Implementation Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/custom-providers.md Example implementation of an LLMClient using the Anthropic AsyncAnthropic client. ```python import anthropic import json class AnthropicLLM: def __init__(self, model: str = "claude-sonnet-4-20250514"): self.client = anthropic.AsyncAnthropic() self.model = model async def generate(self, prompt: str) -> str: response = await self.client.messages.create( model=self.model, max_tokens=1024, messages=[{"role": "user", "content": prompt}], ) return response.content[0].text async def generate_structured(self, prompt: str, response_model: type[T]) -> T: schema = response_model.model_json_schema() response = await self.client.messages.create( model=self.model, max_tokens=1024, messages=[{"role": "user", "content": prompt}], tools=[{"name": "output", "description": "Output", "input_schema": schema}], tool_choice={"type": "tool", "name": "output"}, ) data = response.content[0].input return response_model.model_validate(data) ``` -------------------------------- ### Set OpenAI API Key Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/index.md Set the OPENAI_API_KEY environment variable before running examples that use OpenAI models. ```bash export OPENAI_API_KEY=sk-... ``` -------------------------------- ### Memv Message Model Example Source: https://context7.com/vstorm-co/memv/llms.txt Illustrates the creation of a Message object, a core data model in memv. Specify the message ID, user ID, role (USER, ASSISTANT, SYSTEM), content, and timestamp. ```python from datetime import datetime, timezone from uuid import uuid4 from memv import Message, MessageRole, Episode, SemanticKnowledge, KnowledgeInput, RetrievalResult # Message model message = Message( id=uuid4(), user_id="user-123", role=MessageRole.USER, # USER, ASSISTANT, or SYSTEM content="I work at Anthropic.", sent_at=datetime.now(timezone.utc), ) ``` -------------------------------- ### Common Configuration: High-throughput chat agent Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/configuration.md Example configuration for a high-throughput chat agent, optimizing for speed and efficiency. ```APIDOC ## Common Configuration: High-throughput chat agent ### Description This configuration is optimized for high-throughput scenarios, enabling features that improve processing speed and efficiency. ### Method Instantiation with High-throughput Configuration ### Endpoint N/A (Class Initialization) ### Parameters #### Request Body - **auto_process** (bool) - `True` - **batch_threshold** (int) - `20` - **enable_episode_merging** (bool) - `True` - **enable_knowledge_dedup** (bool) - `True` - **enable_embedding_cache** (bool) - `True` ### Request Example ```python memory = Memory( auto_process=True, batch_threshold=20, enable_episode_merging=True, enable_knowledge_dedup=True, enable_embedding_cache=True, # ... ) ``` ### Response N/A (Class Initialization) ``` -------------------------------- ### Memv Episode Model Example Source: https://context7.com/vstorm-co/memv/llms.txt Shows how to create an Episode object, which represents a conversation or a segment of interaction. Episodes are typically created by the process() function and include an ID, user ID, title, content, and message timestamps. ```python # Episode model (created by process()) episode = Episode( id=uuid4(), user_id="user-123", title="User's Work Background", content="The user mentioned they work at Anthropic as a researcher...", original_messages=[{"role": "user", "content": "I work at Anthropic."}], start_time=datetime.now(timezone.utc), end_time=datetime.now(timezone.utc), ) print(f"Episode has {episode.message_count} messages") ``` -------------------------------- ### List, Get, Invalidate, Delete, and Clear Knowledge Entries Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates managing knowledge entries for a user, including pagination, retrieval by ID, soft deletion (invalidation), hard deletion, and clearing all user data. Requires asyncio and memv library. ```python import asyncio from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter async def main(): memory = Memory( db_url="memory.db", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: user_id = "user-123" # List knowledge with pagination entries = await memory.list_knowledge( user_id=user_id, limit=20, offset=0, include_expired=False, # Only current knowledge ) for entry in entries: print(f"- {entry.statement} (importance: {entry.importance_score})") # Get specific knowledge by ID if entries: knowledge = await memory.get_knowledge(entries[0].id) print(f"Retrieved: {knowledge.statement if knowledge else 'Not found'}") # Mark as expired (soft delete, preserves history) success = await memory.invalidate_knowledge(entries[0].id) print(f"Invalidated: {success}") # Hard delete (removes from all stores) success = await memory.delete_knowledge(entries[0].id) print(f"Deleted: {success}") # Clear all data for a user deleted = await memory.clear_user(user_id) print(f"Cleared: {deleted}") asyncio.run(main()) ``` -------------------------------- ### Initialize and use memv Memory Source: https://github.com/vstorm-co/memv/blob/main/docs/index.md Demonstrates initializing the Memory client and performing basic operations like adding exchanges, processing knowledge, and retrieving context. ```python from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter memory = Memory( db_url="memory.db", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: # Store conversation await memory.add_exchange( user_id="user-123", user_message="I just started at Anthropic as a researcher.", assistant_message="Congrats! What's your focus area?", ) # Extract knowledge await memory.process("user-123") # Retrieve context result = await memory.retrieve("What does the user do?", user_id="user-123") print(result.to_prompt()) ``` -------------------------------- ### Initialize and use Memv memory Source: https://github.com/vstorm-co/memv/blob/main/docs/getting-started.md Demonstrates setting up a Memory instance, adding conversation exchanges, processing episodes, and retrieving context. ```python import asyncio from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter async def main(): memory = Memory( db_url="memory.db", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: user_id = "user-123" # Add a conversation exchange await memory.add_exchange( user_id=user_id, user_message="I work at Anthropic as a researcher.", assistant_message="That's great! What area do you focus on?", ) await memory.add_exchange( user_id=user_id, user_message="AI safety, specifically interpretability.", assistant_message="Fascinating field!", ) # Process messages into episodes and extract knowledge count = await memory.process(user_id) print(f"Extracted {count} knowledge entries") # Retrieve relevant context for a query result = await memory.retrieve("What does the user do for work?", user_id=user_id) print(result.to_prompt()) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Memory with Configuration Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/configuration.md Create a Memory instance using a predefined MemoryConfig object. ```python from memv import Memory, MemoryConfig config = MemoryConfig( max_statements_for_prediction=5, enable_episode_merging=False, ) memory = Memory(config=config, embedding_client=embedder, llm_client=llm) ``` -------------------------------- ### Reset SQLite Database Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/sqlite.md Delete the database file to perform a fresh start. ```bash rm memory.db # fresh start ``` -------------------------------- ### Initialize and Use Memory Class for AI Agents Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates initializing the Memory class with a SQLite backend, OpenAI embeddings, and a GPT-4o-mini LLM. Shows how to add conversation exchanges, process them into episodes, extract knowledge, and retrieve relevant context for a user query. ```python import asyncio from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter async def main(): # Initialize memory with SQLite backend memory = Memory( db_url="memory.db", # or "postgresql://user:pass@host/db" embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: user_id = "user-123" # Add conversation exchanges await memory.add_exchange( user_id=user_id, user_message="I work at Anthropic as a researcher.", assistant_message="That's great! What area do you focus on?", ) await memory.add_exchange( user_id=user_id, user_message="AI safety, specifically interpretability.", assistant_message="Fascinating field!", ) # Process messages into episodes and extract knowledge count = await memory.process(user_id) print(f"Extracted {count} knowledge entries") # Retrieve relevant context for a query result = await memory.retrieve("What does the user do for work?", user_id=user_id) print(result.to_prompt()) # Output: # ## Relevant Context # - The user works at Anthropic as a researcher # - The user focuses on AI safety, specifically interpretability asyncio.run(main()) ``` -------------------------------- ### MemoryConfig Initialization Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/configuration.md Demonstrates how to initialize MemoryConfig with custom parameters and pass it to the Memory class. ```APIDOC ## MemoryConfig Initialization ### Description This section shows how to create and use the `MemoryConfig` object to customize the behavior of the `Memory` class. ### Method Instantiation and Initialization ### Endpoint N/A (Class Initialization) ### Parameters #### Request Body - **max_statements_for_prediction** (int) - Optional - Maximum number of existing knowledge statements to use during prediction. - **enable_episode_merging** (bool) - Optional - Whether to merge similar episodes to reduce redundancy. ### Request Example ```python from memv import Memory, MemoryConfig config = MemoryConfig( max_statements_for_prediction=5, enable_episode_merging=False, ) memory = Memory(config=config, embedding_client=embedder, llm_client=llm) ``` ### Response N/A (Class Initialization) ``` -------------------------------- ### Initialize and use memv Memory Source: https://github.com/vstorm-co/memv/blob/main/README.md Configure the memory instance with database and client adapters, then process exchanges and retrieve information. ```python from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter memory = Memory( db_url="memory.db", # or "postgresql://user:pass@host/db" embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: await memory.add_exchange( user_id="user-123", user_message="I just started at Anthropic as a researcher.", assistant_message="Congrats! What's your focus area?", ) await memory.process("user-123") result = await memory.retrieve("What does the user do?", user_id="user-123") print(result.to_prompt()) ``` -------------------------------- ### Initialize Memory with explicit configuration Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/postgres.md Alternative initialization method using MemoryConfig to explicitly set the backend. ```python from memv import Memory, MemoryConfig config = MemoryConfig(backend="postgres", db_url="postgresql://...") memory = Memory(config=config, embedding_client=embedder, llm_client=llm) ``` -------------------------------- ### Initialize OpenAIEmbedAdapter Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates initializing OpenAIEmbedAdapter with default, larger, or custom API key models. Supports text-embedding-3-small, text-embedding-3-large, and text-embedding-ada-002. ```python from memv.embeddings import OpenAIEmbedAdapter # Default: text-embedding-3-small (1536 dimensions) embedder = OpenAIEmbedAdapter() # Use larger model for higher quality embedder_large = OpenAIEmbedAdapter(model="text-embedding-3-large") # 3072 dims # With explicit API key embedder_custom = OpenAIEmbedAdapter( api_key="sk-...", model="text-embedding-3-small", ) ``` -------------------------------- ### Initialize Memory with SQLite Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/sqlite.md Configure the Memory instance with a database URL and required adapters for embeddings and LLM interactions. ```python from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter memory = Memory( db_url="memory.db", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) ``` -------------------------------- ### Initialize Memory with PostgreSQL Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/postgres.md Basic initialization of the Memory object using a PostgreSQL connection URL. ```python from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter memory = Memory( db_url="postgresql://user:password@localhost:5432/mydb", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: await memory.add_exchange(...) ``` -------------------------------- ### Main Function for Memv Agent Conversation Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates the usage of the MemoryAgent and Memory classes. Initializes memory, creates an agent, conducts a sample conversation, and flushes memory. Ensure the database path and client configurations are correct. ```python async def main(): memory = Memory( db_url=".db/agent.db", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), auto_process=True, batch_threshold=10, ) async with memory: agent = MemoryAgent(memory) # Conversation with memory response = await agent.chat("I'm a Python developer at Meta.") print(f"Assistant: {response}") response = await agent.chat("What programming language do I use?") print(f"Assistant: {response}") # Should reference Python # Flush before exit await memory.flush(agent.user_id) asyncio.run(main()) ``` -------------------------------- ### Add Conversation Exchanges to Memory Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates using the `add_exchange` method to store user and assistant messages. Includes examples of basic exchange and adding an exchange with an explicit timestamp. The method can buffer messages if auto_process is enabled. ```python import asyncio from datetime import datetime, timezone from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter async def main(): memory = Memory( db_url="memory.db", embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: # Basic exchange user_msg, assistant_msg = await memory.add_exchange( user_id="user-123", user_message="My favorite programming language is Python.", assistant_message="Python is a great choice for many applications!", ) # Exchange with explicit timestamp await memory.add_exchange( user_id="user-123", user_message="I've been learning Rust lately.", assistant_message="Rust has excellent memory safety features.", timestamp=datetime.now(timezone.utc), ) asyncio.run(main()) ``` -------------------------------- ### Memv SemanticKnowledge Model Example Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates the SemanticKnowledge model, used for storing extracted or injected facts. Includes fields for ID, user ID, statement, importance score, and validity/expiration times. Use is_current() and is_valid_at() for checks. ```python # SemanticKnowledge model (extracted or injected) knowledge = SemanticKnowledge( id=uuid4(), user_id="user-123", statement="User works at Anthropic as a researcher", importance_score=0.85, valid_at=datetime(2024, 1, 1, tzinfo=timezone.utc), invalid_at=None, # Still true expired_at=None, # Current record ) print(f"Is current: {knowledge.is_current()}") print(f"Valid at 2024-06: {knowledge.is_valid_at(datetime(2024, 6, 1, tzinfo=timezone.utc))}") ``` -------------------------------- ### Project Management Commands Source: https://github.com/vstorm-co/memv/blob/main/CLAUDE.md Standard commands for quality assurance, testing, documentation, and pre-commit hooks. ```bash # Quality make format # ruff format + fix make lint # ruff check + format check make typecheck # ty check src/ make all # format + lint + typecheck + test # Testing uv run pytest # all tests uv run pytest tests/test_models.py::test_name # single test # Docs make docs # mkdocs build --strict make docs-serve # local preview # Pre-commit uv run pre-commit run --all-files ``` -------------------------------- ### Initialize MemoryAgent Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/llamaindex.md Constructor for the MemoryAgent class, setting up the memory store and OpenAI LLM. ```python class MemoryAgent: def __init__(self, memory: Memory, user_id: str = "default-user"): self.memory = memory self.user_id = user_id self.llm = OpenAI(model="gpt-4o-mini", temperature=0.7) ``` -------------------------------- ### Integrate memv into an Agent class Source: https://github.com/vstorm-co/memv/blob/main/docs/index.md Shows how to incorporate memory retrieval and storage within a custom agent class structure. ```python class MyAgent: def __init__(self, memory: Memory): self.memory = memory async def run(self, user_input: str, user_id: str) -> str: # 1. Retrieve relevant context context = await self.memory.retrieve(user_input, user_id=user_id) # 2. Generate response with context response = await self.llm.generate( f"{context.to_prompt()}\n\nUser: {user_input}" ) # 3. Store the exchange await self.memory.add_exchange(user_id, user_input, response) return response ``` -------------------------------- ### PydanticAI LLM Adapter Usage Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/custom-providers.md Initialize the PydanticAI adapter with various supported providers. ```python from memv.llm import PydanticAIAdapter llm = PydanticAIAdapter("openai:gpt-4o-mini") llm = PydanticAIAdapter("anthropic:claude-3-5-sonnet-latest") llm = PydanticAIAdapter("google-gla:gemini-2.5-flash") llm = PydanticAIAdapter("groq:llama-3.3-70b-versatile") ``` -------------------------------- ### Configure Memory with MemoryConfig Source: https://context7.com/vstorm-co/memv/llms.txt Illustrates using MemoryConfig for centralized configuration of Memv parameters, including options for high-throughput chat and precision extraction. Individual parameters can override config values. ```python import asyncio from memv import Memory, MemoryConfig from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter async def main(): # High-throughput chat configuration config = MemoryConfig( db_url=".db/production.db", auto_process=True, batch_threshold=20, enable_episode_merging=True, enable_knowledge_dedup=True, enable_embedding_cache=True, embedding_cache_size=1000, embedding_cache_ttl_seconds=600, ) # Precision extraction configuration precision_config = MemoryConfig( max_statements_for_prediction=20, # More context for better predictions knowledge_dedup_threshold=0.95, # Higher threshold = less dedup merge_similarity_threshold=0.95, segmentation_threshold=10, # Smaller episodes time_gap_minutes=15, # Shorter time gaps ) # Minimal configuration (no optional processing) minimal_config = MemoryConfig( enable_episode_merging=False, enable_knowledge_dedup=False, enable_embedding_cache=False, ) # Use config with Memory memory = Memory( config=config, embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), # Individual params override config values auto_process=False, # Override config.auto_process ) async with memory: pass # Use memory asyncio.run(main()) ``` -------------------------------- ### Run Code Quality Tools Source: https://github.com/vstorm-co/memv/blob/main/docs/installation.md Execute linting, type checking, and pre-commit hooks to maintain code quality. ```bash make lint make typecheck uv run pre-commit run --all-files ``` -------------------------------- ### Run PostgreSQL with Docker Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/backends/postgres.md Docker command to quickly spin up a PostgreSQL instance with pgvector. ```bash docker run -d \ --name memv-postgres \ -e POSTGRES_USER=memv \ -e POSTGRES_PASSWORD=memv \ -e POSTGRES_DB=memv \ -p 5432:5432 \ pgvector/pgvector:pg17 ``` -------------------------------- ### Integrate OpenAIEmbedAdapter with Memory Source: https://context7.com/vstorm-co/memv/llms.txt Illustrates how to integrate OpenAIEmbedAdapter with the Memory class. The embedding client is passed during Memory initialization, and dimensions are auto-detected. ```python from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter # Use with Memory (dimensions auto-detected) memory = Memory( db_url="memory.db", embedding_client=embedder, llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) ``` -------------------------------- ### Memory Class - Core Entry Point Source: https://context7.com/vstorm-co/memv/llms.txt The Memory class is the main entry point for all memv operations. It manages database connections, message storage, knowledge extraction, and retrieval. ```APIDOC ## Memory Class - Core Entry Point ### Description The `Memory` class is the main entry point for all memv operations. It manages database connections, message storage, knowledge extraction, and retrieval. ### Method Initialization of the `Memory` class requires a database URL, an embedding client, and an LLM client. ### Endpoint N/A (This is a class initialization) ### Parameters #### Initialization Parameters - **db_url** (string) - Required - The database connection URL (e.g., "memory.db" for SQLite or "postgresql://user:pass@host/db" for PostgreSQL). - **embedding_client** (object) - Required - An instance of an embedding client (e.g., `OpenAIEmbedAdapter`). - **llm_client** (object) - Required - An instance of an LLM client (e.g., `PydanticAIAdapter`). ### Request Example ```python import asyncio from memv import Memory from memv.embeddings import OpenAIEmbedAdapter from memv.llm import PydanticAIAdapter async def main(): # Initialize memory with SQLite backend memory = Memory( db_url="memory.db", # or "postgresql://user:pass@host/db" embedding_client=OpenAIEmbedAdapter(), llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) async with memory: user_id = "user-123" # Add conversation exchanges await memory.add_exchange( user_id=user_id, user_message="I work at Anthropic as a researcher.", assistant_message="That's great! What area do you focus on?", ) await memory.add_exchange( user_id=user_id, user_message="AI safety, specifically interpretability.", assistant_message="Fascinating field!", ) # Process messages into episodes and extract knowledge count = await memory.process(user_id) print(f"Extracted {count} knowledge entries") # Retrieve relevant context for a query result = await memory.retrieve("What does the user do for work?", user_id=user_id) print(result.to_prompt()) asyncio.run(main()) ``` ### Response #### Success Response (Initialization) - The `Memory` object is successfully initialized and ready for use. #### Response Example (Output from `print(result.to_prompt())`) ``` ## Relevant Context - The user works at Anthropic as a researcher - The user focuses on AI safety, specifically interpretability ``` ``` -------------------------------- ### Initialize PydanticAIAdapter for LLMs Source: https://context7.com/vstorm-co/memv/llms.txt Shows how to initialize PydanticAIAdapter for various LLM providers including OpenAI, Anthropic, Google, and Groq. Each provider uses a specific string format for model selection. ```python from memv.llm import PydanticAIAdapter # OpenAI models llm_openai = PydanticAIAdapter("openai:gpt-4o-mini") llm_gpt4 = PydanticAIAdapter("openai:gpt-4o") # Anthropic models llm_claude = PydanticAIAdapter("anthropic:claude-3-5-sonnet-latest") # Google models llm_gemini = PydanticAIAdapter("google-gla:gemini-2.5-flash") # Groq models (fast inference) llm_groq = PydanticAIAdapter("groq:llama-3.3-70b-versatile") ``` -------------------------------- ### Implement Retrieve-Inject-Store Pattern Source: https://github.com/vstorm-co/memv/blob/main/docs/examples/pydantic-ai.md Logic for retrieving memory, injecting it into the agent dependencies, and storing the resulting exchange. ```python async def chat(self, user_message: str) -> str: # 1. Retrieve context result = await self.memory.retrieve(user_message, user_id=self.user_id, top_k=5) # 2. Inject via dependency deps = MemoryContext( user_id=self.user_id, context_prompt=result.to_prompt(), ) response = await self.agent.run(user_message, deps=deps) # 3. Store exchange await self.memory.add_exchange( user_id=self.user_id, user_message=user_message, assistant_message=response.output, ) return response.output ``` -------------------------------- ### Use PydanticAIAdapter for Generation Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates direct LLM generation using an initialized PydanticAIAdapter. The `generate` method takes a prompt and returns the LLM's response. ```python # Direct LLM usage response = await llm_openai.generate("Summarize AI safety research") print(response) ``` -------------------------------- ### Integrate Alternative Embedders with Memory Source: https://context7.com/vstorm-co/memv/llms.txt Demonstrates using alternative embedding adapters like Voyage, Cohere, or local FastEmbed with the Memory class. The chosen embedding client is passed during Memory initialization. ```python from memv import Memory from memv.embeddings import FastEmbedAdapter from memv.llm import PydanticAIAdapter # Use any adapter with Memory memory = Memory( db_url="memory.db", embedding_client=local, # Use local embeddings llm_client=PydanticAIAdapter("openai:gpt-4o-mini"), ) ``` -------------------------------- ### Implement Custom LLMClient Source: https://github.com/vstorm-co/memv/blob/main/docs/advanced/custom-providers.md Define a custom LLM provider by implementing generate and generate_structured methods. ```python from memv.protocols import LLMClient from typing import TypeVar T = TypeVar("T") class MyLLM: async def generate(self, prompt: str) -> str: """Generate unstructured text response.""" ... async def generate_structured(self, prompt: str, response_model: type[T]) -> T: """Generate structured response matching Pydantic model.""" ... ``` -------------------------------- ### Memv KnowledgeInput for Direct Injection Source: https://context7.com/vstorm-co/memv/llms.txt Shows how to use KnowledgeInput for directly injecting facts into memv. Specify the statement and validity periods (valid_at, invalid_at). ```python # KnowledgeInput for direct injection input_item = KnowledgeInput( statement="User prefers dark mode", valid_at=datetime(2024, 1, 1, tzinfo=timezone.utc), invalid_at=None, ) ``` -------------------------------- ### Run Tests and Checks Source: https://github.com/vstorm-co/memv/blob/main/CONTRIBUTING.md Execute tests or run all checks including format, lint, typecheck, and test. ```bash make test # Run tests make all # Run format + lint + typecheck + test ``` -------------------------------- ### Use OpenAIEmbedAdapter for Embedding Source: https://context7.com/vstorm-co/memv/llms.txt Shows direct and batch embedding usage with OpenAIEmbedAdapter. Batch embedding is more efficient for multiple texts. Dimensions are inferred from the model. ```python # Direct embedding usage vector = await embedder.embed("User works at Anthropic") print(f"Vector dimensions: {len(vector)}") # Batch embedding (more efficient) vectors = await embedder.embed_batch([ "User works at Anthropic", "User focuses on AI safety", "User prefers Python", ]) print(f"Embedded {len(vectors)} texts") ``` -------------------------------- ### Memv Built-in Adapters Source: https://github.com/vstorm-co/memv/blob/main/docs/api.md Documentation for the built-in adapters for embeddings and LLMs in the Memv library. ```APIDOC ## Built-in Adapters ### memv.embeddings.OpenAIEmbedAdapter Details of the `OpenAIEmbedAdapter` class. ### memv.llm.PydanticAIAdapter Details of the `PydanticAIAdapter` class. ```