agentrun-mem0ai 0.0.11__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentrun_mem0/__init__.py +6 -0
- agentrun_mem0/client/__init__.py +0 -0
- agentrun_mem0/client/main.py +1747 -0
- agentrun_mem0/client/project.py +931 -0
- agentrun_mem0/client/utils.py +115 -0
- agentrun_mem0/configs/__init__.py +0 -0
- agentrun_mem0/configs/base.py +90 -0
- agentrun_mem0/configs/embeddings/__init__.py +0 -0
- agentrun_mem0/configs/embeddings/base.py +110 -0
- agentrun_mem0/configs/enums.py +7 -0
- agentrun_mem0/configs/llms/__init__.py +0 -0
- agentrun_mem0/configs/llms/anthropic.py +56 -0
- agentrun_mem0/configs/llms/aws_bedrock.py +192 -0
- agentrun_mem0/configs/llms/azure.py +57 -0
- agentrun_mem0/configs/llms/base.py +62 -0
- agentrun_mem0/configs/llms/deepseek.py +56 -0
- agentrun_mem0/configs/llms/lmstudio.py +59 -0
- agentrun_mem0/configs/llms/ollama.py +56 -0
- agentrun_mem0/configs/llms/openai.py +79 -0
- agentrun_mem0/configs/llms/vllm.py +56 -0
- agentrun_mem0/configs/prompts.py +459 -0
- agentrun_mem0/configs/rerankers/__init__.py +0 -0
- agentrun_mem0/configs/rerankers/base.py +17 -0
- agentrun_mem0/configs/rerankers/cohere.py +15 -0
- agentrun_mem0/configs/rerankers/config.py +12 -0
- agentrun_mem0/configs/rerankers/huggingface.py +17 -0
- agentrun_mem0/configs/rerankers/llm.py +48 -0
- agentrun_mem0/configs/rerankers/sentence_transformer.py +16 -0
- agentrun_mem0/configs/rerankers/zero_entropy.py +28 -0
- agentrun_mem0/configs/vector_stores/__init__.py +0 -0
- agentrun_mem0/configs/vector_stores/alibabacloud_mysql.py +64 -0
- agentrun_mem0/configs/vector_stores/aliyun_tablestore.py +32 -0
- agentrun_mem0/configs/vector_stores/azure_ai_search.py +57 -0
- agentrun_mem0/configs/vector_stores/azure_mysql.py +84 -0
- agentrun_mem0/configs/vector_stores/baidu.py +27 -0
- agentrun_mem0/configs/vector_stores/chroma.py +58 -0
- agentrun_mem0/configs/vector_stores/databricks.py +61 -0
- agentrun_mem0/configs/vector_stores/elasticsearch.py +65 -0
- agentrun_mem0/configs/vector_stores/faiss.py +37 -0
- agentrun_mem0/configs/vector_stores/langchain.py +30 -0
- agentrun_mem0/configs/vector_stores/milvus.py +42 -0
- agentrun_mem0/configs/vector_stores/mongodb.py +25 -0
- agentrun_mem0/configs/vector_stores/neptune.py +27 -0
- agentrun_mem0/configs/vector_stores/opensearch.py +41 -0
- agentrun_mem0/configs/vector_stores/pgvector.py +52 -0
- agentrun_mem0/configs/vector_stores/pinecone.py +55 -0
- agentrun_mem0/configs/vector_stores/qdrant.py +47 -0
- agentrun_mem0/configs/vector_stores/redis.py +24 -0
- agentrun_mem0/configs/vector_stores/s3_vectors.py +28 -0
- agentrun_mem0/configs/vector_stores/supabase.py +44 -0
- agentrun_mem0/configs/vector_stores/upstash_vector.py +34 -0
- agentrun_mem0/configs/vector_stores/valkey.py +15 -0
- agentrun_mem0/configs/vector_stores/vertex_ai_vector_search.py +28 -0
- agentrun_mem0/configs/vector_stores/weaviate.py +41 -0
- agentrun_mem0/embeddings/__init__.py +0 -0
- agentrun_mem0/embeddings/aws_bedrock.py +100 -0
- agentrun_mem0/embeddings/azure_openai.py +55 -0
- agentrun_mem0/embeddings/base.py +31 -0
- agentrun_mem0/embeddings/configs.py +30 -0
- agentrun_mem0/embeddings/gemini.py +39 -0
- agentrun_mem0/embeddings/huggingface.py +44 -0
- agentrun_mem0/embeddings/langchain.py +35 -0
- agentrun_mem0/embeddings/lmstudio.py +29 -0
- agentrun_mem0/embeddings/mock.py +11 -0
- agentrun_mem0/embeddings/ollama.py +53 -0
- agentrun_mem0/embeddings/openai.py +49 -0
- agentrun_mem0/embeddings/together.py +31 -0
- agentrun_mem0/embeddings/vertexai.py +64 -0
- agentrun_mem0/exceptions.py +503 -0
- agentrun_mem0/graphs/__init__.py +0 -0
- agentrun_mem0/graphs/configs.py +105 -0
- agentrun_mem0/graphs/neptune/__init__.py +0 -0
- agentrun_mem0/graphs/neptune/base.py +497 -0
- agentrun_mem0/graphs/neptune/neptunedb.py +511 -0
- agentrun_mem0/graphs/neptune/neptunegraph.py +474 -0
- agentrun_mem0/graphs/tools.py +371 -0
- agentrun_mem0/graphs/utils.py +97 -0
- agentrun_mem0/llms/__init__.py +0 -0
- agentrun_mem0/llms/anthropic.py +87 -0
- agentrun_mem0/llms/aws_bedrock.py +665 -0
- agentrun_mem0/llms/azure_openai.py +141 -0
- agentrun_mem0/llms/azure_openai_structured.py +91 -0
- agentrun_mem0/llms/base.py +131 -0
- agentrun_mem0/llms/configs.py +34 -0
- agentrun_mem0/llms/deepseek.py +107 -0
- agentrun_mem0/llms/gemini.py +201 -0
- agentrun_mem0/llms/groq.py +88 -0
- agentrun_mem0/llms/langchain.py +94 -0
- agentrun_mem0/llms/litellm.py +87 -0
- agentrun_mem0/llms/lmstudio.py +114 -0
- agentrun_mem0/llms/ollama.py +117 -0
- agentrun_mem0/llms/openai.py +147 -0
- agentrun_mem0/llms/openai_structured.py +52 -0
- agentrun_mem0/llms/sarvam.py +89 -0
- agentrun_mem0/llms/together.py +88 -0
- agentrun_mem0/llms/vllm.py +107 -0
- agentrun_mem0/llms/xai.py +52 -0
- agentrun_mem0/memory/__init__.py +0 -0
- agentrun_mem0/memory/base.py +63 -0
- agentrun_mem0/memory/graph_memory.py +698 -0
- agentrun_mem0/memory/kuzu_memory.py +713 -0
- agentrun_mem0/memory/main.py +2229 -0
- agentrun_mem0/memory/memgraph_memory.py +689 -0
- agentrun_mem0/memory/setup.py +56 -0
- agentrun_mem0/memory/storage.py +218 -0
- agentrun_mem0/memory/telemetry.py +90 -0
- agentrun_mem0/memory/utils.py +208 -0
- agentrun_mem0/proxy/__init__.py +0 -0
- agentrun_mem0/proxy/main.py +189 -0
- agentrun_mem0/reranker/__init__.py +9 -0
- agentrun_mem0/reranker/base.py +20 -0
- agentrun_mem0/reranker/cohere_reranker.py +85 -0
- agentrun_mem0/reranker/huggingface_reranker.py +147 -0
- agentrun_mem0/reranker/llm_reranker.py +142 -0
- agentrun_mem0/reranker/sentence_transformer_reranker.py +107 -0
- agentrun_mem0/reranker/zero_entropy_reranker.py +96 -0
- agentrun_mem0/utils/factory.py +283 -0
- agentrun_mem0/utils/gcp_auth.py +167 -0
- agentrun_mem0/vector_stores/__init__.py +0 -0
- agentrun_mem0/vector_stores/alibabacloud_mysql.py +547 -0
- agentrun_mem0/vector_stores/aliyun_tablestore.py +252 -0
- agentrun_mem0/vector_stores/azure_ai_search.py +396 -0
- agentrun_mem0/vector_stores/azure_mysql.py +463 -0
- agentrun_mem0/vector_stores/baidu.py +368 -0
- agentrun_mem0/vector_stores/base.py +58 -0
- agentrun_mem0/vector_stores/chroma.py +332 -0
- agentrun_mem0/vector_stores/configs.py +67 -0
- agentrun_mem0/vector_stores/databricks.py +761 -0
- agentrun_mem0/vector_stores/elasticsearch.py +237 -0
- agentrun_mem0/vector_stores/faiss.py +479 -0
- agentrun_mem0/vector_stores/langchain.py +180 -0
- agentrun_mem0/vector_stores/milvus.py +250 -0
- agentrun_mem0/vector_stores/mongodb.py +310 -0
- agentrun_mem0/vector_stores/neptune_analytics.py +467 -0
- agentrun_mem0/vector_stores/opensearch.py +292 -0
- agentrun_mem0/vector_stores/pgvector.py +404 -0
- agentrun_mem0/vector_stores/pinecone.py +382 -0
- agentrun_mem0/vector_stores/qdrant.py +270 -0
- agentrun_mem0/vector_stores/redis.py +295 -0
- agentrun_mem0/vector_stores/s3_vectors.py +176 -0
- agentrun_mem0/vector_stores/supabase.py +237 -0
- agentrun_mem0/vector_stores/upstash_vector.py +293 -0
- agentrun_mem0/vector_stores/valkey.py +824 -0
- agentrun_mem0/vector_stores/vertex_ai_vector_search.py +635 -0
- agentrun_mem0/vector_stores/weaviate.py +343 -0
- agentrun_mem0ai-0.0.11.data/data/README.md +205 -0
- agentrun_mem0ai-0.0.11.dist-info/METADATA +277 -0
- agentrun_mem0ai-0.0.11.dist-info/RECORD +150 -0
- agentrun_mem0ai-0.0.11.dist-info/WHEEL +4 -0
- agentrun_mem0ai-0.0.11.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import uuid
|
|
3
|
+
from typing import Dict, List, Mapping, Optional
|
|
4
|
+
from urllib.parse import urlparse
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
import weaviate
|
|
10
|
+
except ImportError:
|
|
11
|
+
raise ImportError(
|
|
12
|
+
"The 'weaviate' library is required. Please install it using 'pip install weaviate-client weaviate'."
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
import weaviate.classes.config as wvcc
|
|
16
|
+
from weaviate.classes.init import AdditionalConfig, Auth, Timeout
|
|
17
|
+
from weaviate.classes.query import Filter, MetadataQuery
|
|
18
|
+
from weaviate.util import get_valid_uuid
|
|
19
|
+
|
|
20
|
+
from agentrun_mem0.vector_stores.base import VectorStoreBase
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class OutputData(BaseModel):
|
|
26
|
+
id: str
|
|
27
|
+
score: float
|
|
28
|
+
payload: Dict
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Weaviate(VectorStoreBase):
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
collection_name: str,
|
|
35
|
+
embedding_model_dims: int,
|
|
36
|
+
cluster_url: str = None,
|
|
37
|
+
auth_client_secret: str = None,
|
|
38
|
+
additional_headers: dict = None,
|
|
39
|
+
):
|
|
40
|
+
"""
|
|
41
|
+
Initialize the Weaviate vector store.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
collection_name (str): Name of the collection/class in Weaviate.
|
|
45
|
+
embedding_model_dims (int): Dimensions of the embedding model.
|
|
46
|
+
client (WeaviateClient, optional): Existing Weaviate client instance. Defaults to None.
|
|
47
|
+
cluster_url (str, optional): URL for Weaviate server. Defaults to None.
|
|
48
|
+
auth_config (dict, optional): Authentication configuration for Weaviate. Defaults to None.
|
|
49
|
+
additional_headers (dict, optional): Additional headers for requests. Defaults to None.
|
|
50
|
+
"""
|
|
51
|
+
if "localhost" in cluster_url:
|
|
52
|
+
self.client = weaviate.connect_to_local(headers=additional_headers)
|
|
53
|
+
elif auth_client_secret:
|
|
54
|
+
self.client = weaviate.connect_to_weaviate_cloud(
|
|
55
|
+
cluster_url=cluster_url,
|
|
56
|
+
auth_credentials=Auth.api_key(auth_client_secret),
|
|
57
|
+
headers=additional_headers,
|
|
58
|
+
)
|
|
59
|
+
else:
|
|
60
|
+
parsed = urlparse(cluster_url) # e.g., http://mem0_store:8080
|
|
61
|
+
http_host = parsed.hostname or "localhost"
|
|
62
|
+
http_port = parsed.port or (443 if parsed.scheme == "https" else 8080)
|
|
63
|
+
http_secure = parsed.scheme == "https"
|
|
64
|
+
|
|
65
|
+
# Weaviate gRPC defaults (inside Docker network)
|
|
66
|
+
grpc_host = http_host
|
|
67
|
+
grpc_port = 50051
|
|
68
|
+
grpc_secure = False
|
|
69
|
+
|
|
70
|
+
self.client = weaviate.connect_to_custom(
|
|
71
|
+
http_host,
|
|
72
|
+
http_port,
|
|
73
|
+
http_secure,
|
|
74
|
+
grpc_host,
|
|
75
|
+
grpc_port,
|
|
76
|
+
grpc_secure,
|
|
77
|
+
headers=additional_headers,
|
|
78
|
+
skip_init_checks=True,
|
|
79
|
+
additional_config=AdditionalConfig(timeout=Timeout(init=2.0)),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
self.collection_name = collection_name
|
|
83
|
+
self.embedding_model_dims = embedding_model_dims
|
|
84
|
+
self.create_col(embedding_model_dims)
|
|
85
|
+
|
|
86
|
+
def _parse_output(self, data: Dict) -> List[OutputData]:
|
|
87
|
+
"""
|
|
88
|
+
Parse the output data.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
data (Dict): Output data.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
List[OutputData]: Parsed output data.
|
|
95
|
+
"""
|
|
96
|
+
keys = ["ids", "distances", "metadatas"]
|
|
97
|
+
values = []
|
|
98
|
+
|
|
99
|
+
for key in keys:
|
|
100
|
+
value = data.get(key, [])
|
|
101
|
+
if isinstance(value, list) and value and isinstance(value[0], list):
|
|
102
|
+
value = value[0]
|
|
103
|
+
values.append(value)
|
|
104
|
+
|
|
105
|
+
ids, distances, metadatas = values
|
|
106
|
+
max_length = max(len(v) for v in values if isinstance(v, list) and v is not None)
|
|
107
|
+
|
|
108
|
+
result = []
|
|
109
|
+
for i in range(max_length):
|
|
110
|
+
entry = OutputData(
|
|
111
|
+
id=ids[i] if isinstance(ids, list) and ids and i < len(ids) else None,
|
|
112
|
+
score=(distances[i] if isinstance(distances, list) and distances and i < len(distances) else None),
|
|
113
|
+
payload=(metadatas[i] if isinstance(metadatas, list) and metadatas and i < len(metadatas) else None),
|
|
114
|
+
)
|
|
115
|
+
result.append(entry)
|
|
116
|
+
|
|
117
|
+
return result
|
|
118
|
+
|
|
119
|
+
def create_col(self, vector_size, distance="cosine"):
|
|
120
|
+
"""
|
|
121
|
+
Create a new collection with the specified schema.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
vector_size (int): Size of the vectors to be stored.
|
|
125
|
+
distance (str, optional): Distance metric for vector similarity. Defaults to "cosine".
|
|
126
|
+
"""
|
|
127
|
+
if self.client.collections.exists(self.collection_name):
|
|
128
|
+
logger.debug(f"Collection {self.collection_name} already exists. Skipping creation.")
|
|
129
|
+
return
|
|
130
|
+
|
|
131
|
+
properties = [
|
|
132
|
+
wvcc.Property(name="ids", data_type=wvcc.DataType.TEXT),
|
|
133
|
+
wvcc.Property(name="hash", data_type=wvcc.DataType.TEXT),
|
|
134
|
+
wvcc.Property(
|
|
135
|
+
name="metadata",
|
|
136
|
+
data_type=wvcc.DataType.TEXT,
|
|
137
|
+
description="Additional metadata",
|
|
138
|
+
),
|
|
139
|
+
wvcc.Property(name="data", data_type=wvcc.DataType.TEXT),
|
|
140
|
+
wvcc.Property(name="created_at", data_type=wvcc.DataType.TEXT),
|
|
141
|
+
wvcc.Property(name="category", data_type=wvcc.DataType.TEXT),
|
|
142
|
+
wvcc.Property(name="updated_at", data_type=wvcc.DataType.TEXT),
|
|
143
|
+
wvcc.Property(name="user_id", data_type=wvcc.DataType.TEXT),
|
|
144
|
+
wvcc.Property(name="agent_id", data_type=wvcc.DataType.TEXT),
|
|
145
|
+
wvcc.Property(name="run_id", data_type=wvcc.DataType.TEXT),
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
vectorizer_config = wvcc.Configure.Vectorizer.none()
|
|
149
|
+
vector_index_config = wvcc.Configure.VectorIndex.hnsw()
|
|
150
|
+
|
|
151
|
+
self.client.collections.create(
|
|
152
|
+
self.collection_name,
|
|
153
|
+
vectorizer_config=vectorizer_config,
|
|
154
|
+
vector_index_config=vector_index_config,
|
|
155
|
+
properties=properties,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def insert(self, vectors, payloads=None, ids=None):
|
|
159
|
+
"""
|
|
160
|
+
Insert vectors into a collection.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
vectors (list): List of vectors to insert.
|
|
164
|
+
payloads (list, optional): List of payloads corresponding to vectors. Defaults to None.
|
|
165
|
+
ids (list, optional): List of IDs corresponding to vectors. Defaults to None.
|
|
166
|
+
"""
|
|
167
|
+
logger.info(f"Inserting {len(vectors)} vectors into collection {self.collection_name}")
|
|
168
|
+
with self.client.batch.fixed_size(batch_size=100) as batch:
|
|
169
|
+
for idx, vector in enumerate(vectors):
|
|
170
|
+
object_id = ids[idx] if ids and idx < len(ids) else str(uuid.uuid4())
|
|
171
|
+
object_id = get_valid_uuid(object_id)
|
|
172
|
+
|
|
173
|
+
data_object = payloads[idx] if payloads and idx < len(payloads) else {}
|
|
174
|
+
|
|
175
|
+
# Ensure 'id' is not included in properties (it's used as the Weaviate object ID)
|
|
176
|
+
if "ids" in data_object:
|
|
177
|
+
del data_object["ids"]
|
|
178
|
+
|
|
179
|
+
batch.add_object(collection=self.collection_name, properties=data_object, uuid=object_id, vector=vector)
|
|
180
|
+
|
|
181
|
+
def search(
|
|
182
|
+
self, query: str, vectors: List[float], limit: int = 5, filters: Optional[Dict] = None
|
|
183
|
+
) -> List[OutputData]:
|
|
184
|
+
"""
|
|
185
|
+
Search for similar vectors.
|
|
186
|
+
"""
|
|
187
|
+
collection = self.client.collections.get(str(self.collection_name))
|
|
188
|
+
filter_conditions = []
|
|
189
|
+
if filters:
|
|
190
|
+
for key, value in filters.items():
|
|
191
|
+
if value and key in ["user_id", "agent_id", "run_id"]:
|
|
192
|
+
filter_conditions.append(Filter.by_property(key).equal(value))
|
|
193
|
+
combined_filter = Filter.all_of(filter_conditions) if filter_conditions else None
|
|
194
|
+
response = collection.query.hybrid(
|
|
195
|
+
query="",
|
|
196
|
+
vector=vectors,
|
|
197
|
+
limit=limit,
|
|
198
|
+
filters=combined_filter,
|
|
199
|
+
return_properties=["hash", "created_at", "updated_at", "user_id", "agent_id", "run_id", "data", "category"],
|
|
200
|
+
return_metadata=MetadataQuery(score=True),
|
|
201
|
+
)
|
|
202
|
+
results = []
|
|
203
|
+
for obj in response.objects:
|
|
204
|
+
payload = obj.properties.copy()
|
|
205
|
+
|
|
206
|
+
for id_field in ["run_id", "agent_id", "user_id"]:
|
|
207
|
+
if id_field in payload and payload[id_field] is None:
|
|
208
|
+
del payload[id_field]
|
|
209
|
+
|
|
210
|
+
payload["id"] = str(obj.uuid).split("'")[0] # Include the id in the payload
|
|
211
|
+
if obj.metadata.distance is not None:
|
|
212
|
+
score = 1 - obj.metadata.distance # Convert distance to similarity score
|
|
213
|
+
elif obj.metadata.score is not None:
|
|
214
|
+
score = obj.metadata.score
|
|
215
|
+
else:
|
|
216
|
+
score = 1.0 # Default score if none provided
|
|
217
|
+
results.append(
|
|
218
|
+
OutputData(
|
|
219
|
+
id=str(obj.uuid),
|
|
220
|
+
score=score,
|
|
221
|
+
payload=payload,
|
|
222
|
+
)
|
|
223
|
+
)
|
|
224
|
+
return results
|
|
225
|
+
|
|
226
|
+
def delete(self, vector_id):
|
|
227
|
+
"""
|
|
228
|
+
Delete a vector by ID.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
vector_id: ID of the vector to delete.
|
|
232
|
+
"""
|
|
233
|
+
collection = self.client.collections.get(str(self.collection_name))
|
|
234
|
+
collection.data.delete_by_id(vector_id)
|
|
235
|
+
|
|
236
|
+
def update(self, vector_id, vector=None, payload=None):
|
|
237
|
+
"""
|
|
238
|
+
Update a vector and its payload.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
vector_id: ID of the vector to update.
|
|
242
|
+
vector (list, optional): Updated vector. Defaults to None.
|
|
243
|
+
payload (dict, optional): Updated payload. Defaults to None.
|
|
244
|
+
"""
|
|
245
|
+
collection = self.client.collections.get(str(self.collection_name))
|
|
246
|
+
|
|
247
|
+
if payload:
|
|
248
|
+
collection.data.update(uuid=vector_id, properties=payload)
|
|
249
|
+
|
|
250
|
+
if vector:
|
|
251
|
+
existing_data = self.get(vector_id)
|
|
252
|
+
if existing_data:
|
|
253
|
+
existing_data = dict(existing_data)
|
|
254
|
+
if "id" in existing_data:
|
|
255
|
+
del existing_data["id"]
|
|
256
|
+
existing_payload: Mapping[str, str] = existing_data
|
|
257
|
+
collection.data.update(uuid=vector_id, properties=existing_payload, vector=vector)
|
|
258
|
+
|
|
259
|
+
def get(self, vector_id):
|
|
260
|
+
"""
|
|
261
|
+
Retrieve a vector by ID.
|
|
262
|
+
|
|
263
|
+
Args:
|
|
264
|
+
vector_id: ID of the vector to retrieve.
|
|
265
|
+
|
|
266
|
+
Returns:
|
|
267
|
+
dict: Retrieved vector and metadata.
|
|
268
|
+
"""
|
|
269
|
+
vector_id = get_valid_uuid(vector_id)
|
|
270
|
+
collection = self.client.collections.get(str(self.collection_name))
|
|
271
|
+
|
|
272
|
+
response = collection.query.fetch_object_by_id(
|
|
273
|
+
uuid=vector_id,
|
|
274
|
+
return_properties=["hash", "created_at", "updated_at", "user_id", "agent_id", "run_id", "data", "category"],
|
|
275
|
+
)
|
|
276
|
+
# results = {}
|
|
277
|
+
# print("reponse",response)
|
|
278
|
+
# for obj in response.objects:
|
|
279
|
+
payload = response.properties.copy()
|
|
280
|
+
payload["id"] = str(response.uuid).split("'")[0]
|
|
281
|
+
results = OutputData(
|
|
282
|
+
id=str(response.uuid).split("'")[0],
|
|
283
|
+
score=1.0,
|
|
284
|
+
payload=payload,
|
|
285
|
+
)
|
|
286
|
+
return results
|
|
287
|
+
|
|
288
|
+
def list_cols(self):
|
|
289
|
+
"""
|
|
290
|
+
List all collections.
|
|
291
|
+
|
|
292
|
+
Returns:
|
|
293
|
+
list: List of collection names.
|
|
294
|
+
"""
|
|
295
|
+
collections = self.client.collections.list_all()
|
|
296
|
+
logger.debug(f"collections: {collections}")
|
|
297
|
+
print(f"collections: {collections}")
|
|
298
|
+
return {"collections": [{"name": col.name} for col in collections]}
|
|
299
|
+
|
|
300
|
+
def delete_col(self):
|
|
301
|
+
"""Delete a collection."""
|
|
302
|
+
self.client.collections.delete(self.collection_name)
|
|
303
|
+
|
|
304
|
+
def col_info(self):
|
|
305
|
+
"""
|
|
306
|
+
Get information about a collection.
|
|
307
|
+
|
|
308
|
+
Returns:
|
|
309
|
+
dict: Collection information.
|
|
310
|
+
"""
|
|
311
|
+
schema = self.client.collections.get(self.collection_name)
|
|
312
|
+
if schema:
|
|
313
|
+
return schema
|
|
314
|
+
return None
|
|
315
|
+
|
|
316
|
+
def list(self, filters=None, limit=100) -> List[OutputData]:
|
|
317
|
+
"""
|
|
318
|
+
List all vectors in a collection.
|
|
319
|
+
"""
|
|
320
|
+
collection = self.client.collections.get(self.collection_name)
|
|
321
|
+
filter_conditions = []
|
|
322
|
+
if filters:
|
|
323
|
+
for key, value in filters.items():
|
|
324
|
+
if value and key in ["user_id", "agent_id", "run_id"]:
|
|
325
|
+
filter_conditions.append(Filter.by_property(key).equal(value))
|
|
326
|
+
combined_filter = Filter.all_of(filter_conditions) if filter_conditions else None
|
|
327
|
+
response = collection.query.fetch_objects(
|
|
328
|
+
limit=limit,
|
|
329
|
+
filters=combined_filter,
|
|
330
|
+
return_properties=["hash", "created_at", "updated_at", "user_id", "agent_id", "run_id", "data", "category"],
|
|
331
|
+
)
|
|
332
|
+
results = []
|
|
333
|
+
for obj in response.objects:
|
|
334
|
+
payload = obj.properties.copy()
|
|
335
|
+
payload["id"] = str(obj.uuid).split("'")[0]
|
|
336
|
+
results.append(OutputData(id=str(obj.uuid).split("'")[0], score=1.0, payload=payload))
|
|
337
|
+
return [results]
|
|
338
|
+
|
|
339
|
+
def reset(self):
|
|
340
|
+
"""Reset the index by deleting and recreating it."""
|
|
341
|
+
logger.warning(f"Resetting index {self.collection_name}...")
|
|
342
|
+
self.delete_col()
|
|
343
|
+
self.create_col()
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://github.com/mem0ai/mem0">
|
|
3
|
+
<img src="docs/images/banner-sm.png" width="800px" alt="Mem0 - The Memory Layer for Personalized AI">
|
|
4
|
+
</a>
|
|
5
|
+
</p>
|
|
6
|
+
<p align="center" style="display: flex; justify-content: center; gap: 20px; align-items: center;">
|
|
7
|
+
<a href="https://trendshift.io/repositories/11194" target="blank">
|
|
8
|
+
<img src="https://trendshift.io/api/badge/repositories/11194" alt="mem0ai%2Fmem0 | Trendshift" width="250" height="55"/>
|
|
9
|
+
</a>
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<a href="https://mem0.ai">Learn more</a>
|
|
14
|
+
·
|
|
15
|
+
<a href="https://mem0.dev/DiG">Join Discord</a>
|
|
16
|
+
·
|
|
17
|
+
<a href="https://mem0.dev/demo">Demo</a>
|
|
18
|
+
·
|
|
19
|
+
<a href="https://mem0.dev/openmemory">OpenMemory</a>
|
|
20
|
+
</p>
|
|
21
|
+
|
|
22
|
+
<p align="center">
|
|
23
|
+
<a href="https://mem0.dev/DiG">
|
|
24
|
+
<img src="https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white" alt="Mem0 Discord">
|
|
25
|
+
</a>
|
|
26
|
+
<a href="https://pepy.tech/project/mem0ai">
|
|
27
|
+
<img src="https://img.shields.io/pypi/dm/mem0ai" alt="Mem0 PyPI - Downloads">
|
|
28
|
+
</a>
|
|
29
|
+
<a href="https://github.com/mem0ai/mem0">
|
|
30
|
+
<img src="https://img.shields.io/github/commit-activity/m/mem0ai/mem0?style=flat-square" alt="GitHub commit activity">
|
|
31
|
+
</a>
|
|
32
|
+
<a href="https://pypi.org/project/mem0ai" target="blank">
|
|
33
|
+
<img src="https://img.shields.io/pypi/v/mem0ai?color=%2334D058&label=pypi%20package" alt="Package version">
|
|
34
|
+
</a>
|
|
35
|
+
<a href="https://www.npmjs.com/package/mem0ai" target="blank">
|
|
36
|
+
<img src="https://img.shields.io/npm/v/mem0ai" alt="Npm package">
|
|
37
|
+
</a>
|
|
38
|
+
<a href="https://www.ycombinator.com/companies/mem0">
|
|
39
|
+
<img src="https://img.shields.io/badge/Y%20Combinator-S24-orange?style=flat-square" alt="Y Combinator S24">
|
|
40
|
+
</a>
|
|
41
|
+
</p>
|
|
42
|
+
|
|
43
|
+
<p align="center">
|
|
44
|
+
<a href="https://mem0.ai/research"><strong>📄 Building Production-Ready AI Agents with Scalable Long-Term Memory →</strong></a>
|
|
45
|
+
</p>
|
|
46
|
+
<p align="center">
|
|
47
|
+
<strong>⚡ +26% Accuracy vs. OpenAI Memory • 🚀 91% Faster • 💰 90% Fewer Tokens</strong>
|
|
48
|
+
</p>
|
|
49
|
+
|
|
50
|
+
> **🎉 mem0ai v1.0.0 is now available!** This major release includes API modernization, improved vector store support, and enhanced GCP integration. [See migration guide →](MIGRATION_GUIDE_v1.0.md)
|
|
51
|
+
|
|
52
|
+
## 🔥 Research Highlights
|
|
53
|
+
- **+26% Accuracy** over OpenAI Memory on the LOCOMO benchmark
|
|
54
|
+
- **91% Faster Responses** than full-context, ensuring low-latency at scale
|
|
55
|
+
- **90% Lower Token Usage** than full-context, cutting costs without compromise
|
|
56
|
+
- [Read the full paper](https://mem0.ai/research)
|
|
57
|
+
|
|
58
|
+
# Introduction
|
|
59
|
+
|
|
60
|
+
[Mem0](https://mem0.ai) ("mem-zero") enhances AI assistants and agents with an intelligent memory layer, enabling personalized AI interactions. It remembers user preferences, adapts to individual needs, and continuously learns over time—ideal for customer support chatbots, AI assistants, and autonomous systems.
|
|
61
|
+
|
|
62
|
+
### Key Features & Use Cases
|
|
63
|
+
|
|
64
|
+
**Core Capabilities:**
|
|
65
|
+
- **Multi-Level Memory**: Seamlessly retains User, Session, and Agent state with adaptive personalization
|
|
66
|
+
- **Developer-Friendly**: Intuitive API, cross-platform SDKs, and a fully managed service option
|
|
67
|
+
|
|
68
|
+
**Applications:**
|
|
69
|
+
- **AI Assistants**: Consistent, context-rich conversations
|
|
70
|
+
- **Customer Support**: Recall past tickets and user history for tailored help
|
|
71
|
+
- **Healthcare**: Track patient preferences and history for personalized care
|
|
72
|
+
- **Productivity & Gaming**: Adaptive workflows and environments based on user behavior
|
|
73
|
+
|
|
74
|
+
## 🚀 Quickstart Guide <a name="quickstart"></a>
|
|
75
|
+
|
|
76
|
+
Choose between our hosted platform or self-hosted package:
|
|
77
|
+
|
|
78
|
+
### Hosted Platform
|
|
79
|
+
|
|
80
|
+
Get up and running in minutes with automatic updates, analytics, and enterprise security.
|
|
81
|
+
|
|
82
|
+
1. Sign up on [Mem0 Platform](https://app.mem0.ai)
|
|
83
|
+
2. Embed the memory layer via SDK or API keys
|
|
84
|
+
|
|
85
|
+
### Self-Hosted (Open Source)
|
|
86
|
+
|
|
87
|
+
> **✨ agentrun-mem0ai**:基于 `mem0ai` 的扩展版本,增加了阿里云 TableStore (OTS) 支持。
|
|
88
|
+
>
|
|
89
|
+
> **重要**:使用独立的模块名 `agentrun_mem0`,与官方 `mem0` 包**无冲突**,可以共存!
|
|
90
|
+
|
|
91
|
+
Install the sdk via pip:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
# 使用扩展版本(支持阿里云 OTS)
|
|
95
|
+
pip install agentrun-mem0ai
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
官方版本:
|
|
99
|
+
```bash
|
|
100
|
+
# 官方 Python SDK
|
|
101
|
+
pip install mem0ai
|
|
102
|
+
|
|
103
|
+
# 官方 npm SDK
|
|
104
|
+
npm install mem0ai
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Basic Usage
|
|
108
|
+
|
|
109
|
+
Mem0 requires an LLM to function, with `gpt-4.1-nano-2025-04-14 from OpenAI as the default. However, it supports a variety of LLMs; for details, refer to our [Supported LLMs documentation](https://docs.mem0.ai/components/llms/overview).
|
|
110
|
+
|
|
111
|
+
First step is to instantiate the memory:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from openai import OpenAI
|
|
115
|
+
from agentrun_mem0 import Memory
|
|
116
|
+
|
|
117
|
+
openai_client = OpenAI()
|
|
118
|
+
memory = Memory()
|
|
119
|
+
|
|
120
|
+
def chat_with_memories(message: str, user_id: str = "default_user") -> str:
|
|
121
|
+
# Retrieve relevant memories
|
|
122
|
+
relevant_memories = memory.search(query=message, user_id=user_id, limit=3)
|
|
123
|
+
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories["results"])
|
|
124
|
+
|
|
125
|
+
# Generate Assistant response
|
|
126
|
+
system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
|
|
127
|
+
messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": message}]
|
|
128
|
+
response = openai_client.chat.completions.create(model="gpt-4.1-nano-2025-04-14", messages=messages)
|
|
129
|
+
assistant_response = response.choices[0].message.content
|
|
130
|
+
|
|
131
|
+
# Create new memories from the conversation
|
|
132
|
+
messages.append({"role": "assistant", "content": assistant_response})
|
|
133
|
+
memory.add(messages, user_id=user_id)
|
|
134
|
+
|
|
135
|
+
return assistant_response
|
|
136
|
+
|
|
137
|
+
def main():
|
|
138
|
+
print("Chat with AI (type 'exit' to quit)")
|
|
139
|
+
while True:
|
|
140
|
+
user_input = input("You: ").strip()
|
|
141
|
+
if user_input.lower() == 'exit':
|
|
142
|
+
print("Goodbye!")
|
|
143
|
+
break
|
|
144
|
+
print(f"AI: {chat_with_memories(user_input)}")
|
|
145
|
+
|
|
146
|
+
if __name__ == "__main__":
|
|
147
|
+
main()
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
For detailed integration steps, see the [Quickstart](https://docs.mem0.ai/quickstart) and [API Reference](https://docs.mem0.ai/api-reference).
|
|
151
|
+
|
|
152
|
+
## 🔗 Integrations & Demos
|
|
153
|
+
|
|
154
|
+
- **ChatGPT with Memory**: Personalized chat powered by Mem0 ([Live Demo](https://mem0.dev/demo))
|
|
155
|
+
- **Browser Extension**: Store memories across ChatGPT, Perplexity, and Claude ([Chrome Extension](https://chromewebstore.google.com/detail/onihkkbipkfeijkadecaafbgagkhglop?utm_source=item-share-cb))
|
|
156
|
+
- **Langgraph Support**: Build a customer bot with Langgraph + Mem0 ([Guide](https://docs.mem0.ai/integrations/langgraph))
|
|
157
|
+
- **CrewAI Integration**: Tailor CrewAI outputs with Mem0 ([Example](https://docs.mem0.ai/integrations/crewai))
|
|
158
|
+
|
|
159
|
+
## 📚 Documentation & Support
|
|
160
|
+
|
|
161
|
+
- Full docs: https://docs.mem0.ai
|
|
162
|
+
- Community: [Discord](https://mem0.dev/DiG) · [Twitter](https://x.com/mem0ai)
|
|
163
|
+
- Contact: founders@mem0.ai
|
|
164
|
+
|
|
165
|
+
## Citation
|
|
166
|
+
|
|
167
|
+
We now have a paper you can cite:
|
|
168
|
+
|
|
169
|
+
```bibtex
|
|
170
|
+
@article{mem0,
|
|
171
|
+
title={Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory},
|
|
172
|
+
author={Chhikara, Prateek and Khant, Dev and Aryan, Saket and Singh, Taranjeet and Yadav, Deshraj},
|
|
173
|
+
journal={arXiv preprint arXiv:2504.19413},
|
|
174
|
+
year={2025}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## 📦 PyPI 自动发布
|
|
179
|
+
|
|
180
|
+
使用自动化脚本快速发布到 PyPI:
|
|
181
|
+
|
|
182
|
+
### 1. 安装发布工具
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
pip install --upgrade build twine
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### 2. 运行发布脚本
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
./publish.sh
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
脚本会自动完成以下步骤:
|
|
195
|
+
- 清理旧的构建文件
|
|
196
|
+
- 构建新的发行包
|
|
197
|
+
- 检查包的完整性
|
|
198
|
+
- 可选:先上传到测试环境验证
|
|
199
|
+
- 上传到正式 PyPI
|
|
200
|
+
|
|
201
|
+
发布 PyPI 所需 Token 可查看文件 [.pypirc](.pypirc)
|
|
202
|
+
|
|
203
|
+
## ⚖️ License
|
|
204
|
+
|
|
205
|
+
Apache 2.0 — see the [LICENSE](https://github.com/mem0ai/mem0/blob/main/LICENSE) file for details.
|