|
| 1 | +import abc |
| 2 | +import re |
| 3 | +from typing import Dict, List, Optional, Union |
| 4 | + |
| 5 | +from pydantic import Field, field_validator, model_validator |
| 6 | + |
| 7 | +import controlflow |
| 8 | +from controlflow.tools.tools import Tool |
| 9 | +from controlflow.utilities.general import ControlFlowModel, unwrap |
| 10 | +from controlflow.utilities.logging import get_logger |
| 11 | + |
| 12 | +logger = get_logger("controlflow.memory") |
| 13 | + |
| 14 | + |
| 15 | +def sanitize_memory_key(key: str) -> str: |
| 16 | + # Remove any characters that are not alphanumeric or underscore |
| 17 | + return re.sub(r"[^a-zA-Z0-9_]", "", key) |
| 18 | + |
| 19 | + |
| 20 | +class AsyncMemoryProvider(ControlFlowModel, abc.ABC): |
| 21 | + async def configure(self, memory_key: str) -> None: |
| 22 | + """Configure the provider for a specific memory.""" |
| 23 | + pass |
| 24 | + |
| 25 | + @abc.abstractmethod |
| 26 | + async def add(self, memory_key: str, content: str) -> str: |
| 27 | + """Create a new memory and return its ID.""" |
| 28 | + pass |
| 29 | + |
| 30 | + @abc.abstractmethod |
| 31 | + async def delete(self, memory_key: str, memory_id: str) -> None: |
| 32 | + """Delete a memory by its ID.""" |
| 33 | + pass |
| 34 | + |
| 35 | + @abc.abstractmethod |
| 36 | + async def search(self, memory_key: str, query: str, n: int = 20) -> Dict[str, str]: |
| 37 | + """Search for n memories using a string query.""" |
| 38 | + pass |
| 39 | + |
| 40 | + |
| 41 | +class AsyncMemory(ControlFlowModel): |
| 42 | + """ |
| 43 | + A memory module is a partitioned collection of memories that are stored in a |
| 44 | + vector database, configured by a MemoryProvider. |
| 45 | + """ |
| 46 | + |
| 47 | + key: str |
| 48 | + instructions: str = Field( |
| 49 | + description="Explain what this memory is for and how it should be used." |
| 50 | + ) |
| 51 | + provider: AsyncMemoryProvider = Field( |
| 52 | + default_factory=lambda: controlflow.defaults.memory_provider, |
| 53 | + validate_default=True, |
| 54 | + ) |
| 55 | + |
| 56 | + def __hash__(self) -> int: |
| 57 | + return id(self) |
| 58 | + |
| 59 | + @field_validator("provider", mode="before") |
| 60 | + @classmethod |
| 61 | + def validate_provider( |
| 62 | + cls, v: Optional[Union[AsyncMemoryProvider, str]] |
| 63 | + ) -> AsyncMemoryProvider: |
| 64 | + if isinstance(v, str): |
| 65 | + return get_memory_provider(v) |
| 66 | + if v is None: |
| 67 | + raise ValueError( |
| 68 | + unwrap( |
| 69 | + """ |
| 70 | + Memory modules require a MemoryProvider to configure the |
| 71 | + underlying vector database. No provider was passed as an |
| 72 | + argument, and no default value has been configured. |
| 73 | + |
| 74 | + For more information on configuring a memory provider, see |
| 75 | + the [Memory |
| 76 | + documentation](https://controlflow.ai/patterns/memory), and |
| 77 | + please review the [default provider |
| 78 | + guide](https://controlflow.ai/guides/default-memory) for |
| 79 | + information on configuring a default provider. |
| 80 | + |
| 81 | + Please note that if you are using ControlFlow for the first |
| 82 | + time, this error is expected because ControlFlow does not include |
| 83 | + vector dependencies by default. |
| 84 | + """ |
| 85 | + ) |
| 86 | + ) |
| 87 | + return v |
| 88 | + |
| 89 | + @field_validator("key") |
| 90 | + @classmethod |
| 91 | + def validate_key(cls, v: str) -> str: |
| 92 | + sanitized = sanitize_memory_key(v) |
| 93 | + if sanitized != v: |
| 94 | + raise ValueError( |
| 95 | + "Memory key must contain only alphanumeric characters and underscores" |
| 96 | + ) |
| 97 | + return sanitized |
| 98 | + |
| 99 | + async def _configure_provider(self): |
| 100 | + await self.provider.configure(self.key) |
| 101 | + return self |
| 102 | + |
| 103 | + async def add(self, content: str) -> str: |
| 104 | + return await self.provider.add(self.key, content) |
| 105 | + |
| 106 | + async def delete(self, memory_id: str) -> None: |
| 107 | + await self.provider.delete(self.key, memory_id) |
| 108 | + |
| 109 | + async def search(self, query: str, n: int = 20) -> Dict[str, str]: |
| 110 | + return await self.provider.search(self.key, query, n) |
| 111 | + |
| 112 | + def get_tools(self) -> List[Tool]: |
| 113 | + return [ |
| 114 | + Tool.from_function( |
| 115 | + self.add, |
| 116 | + name=f"store_memory_{self.key}", |
| 117 | + description=f'Create a new memory in Memory: "{self.key}".', |
| 118 | + ), |
| 119 | + Tool.from_function( |
| 120 | + self.delete, |
| 121 | + name=f"delete_memory_{self.key}", |
| 122 | + description=f'Delete a memory by its ID from Memory: "{self.key}".', |
| 123 | + ), |
| 124 | + Tool.from_function( |
| 125 | + self.search, |
| 126 | + name=f"search_memories_{self.key}", |
| 127 | + description=f'Search for memories relevant to a string query in Memory: "{self.key}". Returns a dictionary of memory IDs and their contents.', |
| 128 | + ), |
| 129 | + ] |
| 130 | + |
| 131 | + |
| 132 | +def get_memory_provider(provider: str) -> AsyncMemoryProvider: |
| 133 | + logger.debug(f"Loading memory provider: {provider}") |
| 134 | + |
| 135 | + # --- async postgres --- |
| 136 | + |
| 137 | + if provider.startswith("async-postgres"): |
| 138 | + try: |
| 139 | + import sqlalchemy |
| 140 | + except ImportError: |
| 141 | + raise ImportError( |
| 142 | + """To use async Postgres as a memory provider, please install the `sqlalchemy, `psycopg-pool`, |
| 143 | + `psycopg-binary`, and `psycopg` packages.""" |
| 144 | + ) |
| 145 | + |
| 146 | + import controlflow.memory.providers.postgres as postgres_providers |
| 147 | + |
| 148 | + return postgres_providers.AsyncPostgresMemory() |
| 149 | + raise ValueError(f'Memory provider "{provider}" could not be loaded from a string.') |
0 commit comments