Add V2 get_all (#1969)

This commit is contained in:
Dev Khant
2024-10-17 11:41:59 +05:30
committed by GitHub
parent 4661d55913
commit 5667bc1eab
7 changed files with 307 additions and 6 deletions

View File

@@ -1,4 +1,4 @@
---
title: 'Get Memories'
title: 'V1 Get Memories'
openapi: get /v1/memories/
---

View File

@@ -0,0 +1,74 @@
---
title: 'V2 Get Memories'
openapi: post /v2/memories/
---
Mem0 offers two versions of the get memories API: v1 and v2. Here's how they differ:
<Tabs>
<Tab title="v1 Get Memories">
<CodeGroup>
```python Code
memories = m.get_all(user_id="alex")
```
```json Output
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"travelling to Paris",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"created_at":"2023-02-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
}
]
```
</CodeGroup>
</Tab>
<Tab title="v2 Get Memories">
<CodeGroup>
```python Code
memories = m.get_all(
filters={
"AND": [
{
"user_id": "alex"
},
{
"created_at": {
"gte": "2024-07-01",
"lte": "2024-07-31"
}
}
]
},
version="v2"
)
```
```json Output
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
}
]
```
</CodeGroup>
</Tab>
</Tabs>
Key difference between v1 and v2 get memories:
• **Filters**: v2 allows you to apply filters to narrow down memory retrieval based on specific criteria. This includes support for complex logical operations (AND, OR) and comparison operators (IN, gte, lte, gt, lt, ne, icontains) for advanced filtering capabilities.
The v2 get memories API is more powerful and flexible, allowing for more precise memory retrieval without the need for a search query.

View File

@@ -34,7 +34,7 @@ Mem0 offers two versions of the search API: v1 and v2. Here's how they differ:
<Tab title="v2 Search">
<CodeGroup>
```python Code
related_memories = m.v2_search(
related_memories = m.vsearch(
query="What are Alice's hobbies?",
filters={
"AND":[
@@ -50,7 +50,8 @@ Mem0 offers two versions of the search API: v1 and v2. Here's how they differ:
}
}
]
}
},
version="v2"
)
```

View File

@@ -145,7 +145,8 @@
{
"group": "Memory APIs",
"pages": [
"api-reference/memory/get-memories",
"api-reference/memory/v1-get-memories",
"api-reference/memory/v2-get-memories",
"api-reference/memory/add-memories",
"api-reference/memory/delete-memories",
"api-reference/memory/get-memory",

View File

@@ -730,6 +730,145 @@
"x-codegen-request-body-name": "data"
}
},
"/v2/memories/": {
"post": {
"tags": [
"memories"
],
"description": "Get all memories",
"operationId": "memories_list_v2",
"parameters": [
{
"name": "filters",
"in": "query",
"schema": {
"type": "object"
},
"description": "Filters to apply to the memories",
"style": "deepObject",
"explode": true
},
{
"name": "org_name",
"in": "query",
"schema": {
"type": "string"
},
"description": "Filter memories by organization name"
},
{
"name": "project_name",
"in": "query",
"schema": {
"type": "string"
},
"description": "Filter memories by project name"
}
],
"responses": {
"200": {
"description": "",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"created_at": {
"type": "string",
"format": "date-time"
},
"updated_at": {
"type": "string",
"format": "date-time"
},
"total_memories": {
"type": "integer"
},
"owner": {
"type": "string"
},
"organization": {
"type": "string"
},
"metadata": {
"type": "object"
},
"type": {
"type": "string",
"enum": [
"user",
"agent"
]
}
},
"required": [
"id",
"name",
"created_at",
"updated_at",
"total_memories",
"owner",
"organization",
"type"
]
}
}
}
}
},
"400": {
"description": "Bad Request",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {
"type": "string",
"example": "One of the filters: app_id, user_id, agent_id, run_id is required!"
}
}
}
}
}
}
},
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your-api-key\")\n\n# Retrieve memories with filters\nmemories = client.get_all(\n filters={\n \"AND\": [\n {\n \"user_id\": \"alex\"\n },\n {\n \"created_at\": {\n \"gte\": \"2024-07-01\",\n \"lte\": \"2024-07-31\"\n }\n }\n ]\n },\n version=\"v2\"\n)\n\nprint(memories)"
},
{
"lang": "JavaScript",
"source": "const axios = require('axios');\n\nconst filters = {\n AND: [\n { user_id: 'alex' },\n { created_at: { gte: '2024-07-01', lte: '2024-07-31' } }\n ]\n};\n\naxios.post('https://api.mem0.ai/v2/memories/', { filters }, {\n headers: { 'Authorization': 'Token your-api-key' }\n})\n.then(response => console.log(response.data))\n.catch(error => console.error(error));"
},
{
"lang": "cURL",
"source": "curl -X POST 'https://api.mem0.ai/v2/memories/' \\\n-H 'Authorization: Token your-api-key' \\\n-H 'Content-Type: application/json' \\\n-d '{\n \"filters\": {\n \"AND\": [\n { \"user_id\": \"alex\" },\n { \"created_at\": { \"gte\": \"2024-07-01\", \"lte\": \"2024-07-31\" } }\n ]\n }\n}'"
},
{
"lang": "Go",
"source": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\nfunc main() {\n\turl := \"https://api.mem0.ai/v2/memories/\"\n\tfilters := map[string]interface{}{\n\t\t\"AND\": []map[string]interface{}{\n\t\t\t{\"user_id\": \"alex\"},\n\t\t\t{\"created_at\": map[string]string{\n\t\t\t\t\"gte\": \"2024-07-01\",\n\t\t\t\t\"lte\": \"2024-07-31\",\n\t\t\t}},\n\t\t},\n\t}\n\tpayload, _ := json.Marshal(map[string]interface{}{\"filters\": filters})\n\treq, _ := http.NewRequest(\"POST\", url, bytes.NewBuffer(payload))\n\treq.Header.Add(\"Authorization\", \"Token your-api-key\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(string(body))\n}"
},
{
"lang": "PHP",
"source": "<?php\n\n$curl = curl_init();\n\n$filters = [\n 'AND' => [\n ['user_id' => 'alex'],\n ['created_at' => ['gte' => '2024-07-01', 'lte' => '2024-07-31']]\n ]\n];\n\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/v2/memories/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"POST\",\n CURLOPT_POSTFIELDS => json_encode(['filters' => $filters]),\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token your-api-key\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n\nif ($err) {\n echo \"cURL Error #:\" . $err;\n} else {\n echo $response;\n}"
},
{
"lang": "Java",
"source": "import com.konghq.unirest.http.HttpResponse;\nimport com.konghq.unirest.http.Unirest;\nimport org.json.JSONObject;\n\nJSONObject filters = new JSONObject()\n .put(\"AND\", new JSONArray()\n .put(new JSONObject().put(\"user_id\", \"alex\"))\n .put(new JSONObject().put(\"created_at\", new JSONObject()\n .put(\"gte\", \"2024-07-01\")\n .put(\"lte\", \"2024-07-31\")\n ))\n );\n\nHttpResponse<String> response = Unirest.post(\"https://api.mem0.ai/v2/memories/\")\n .header(\"Authorization\", \"Token your-api-key\")\n .header(\"Content-Type\", \"application/json\")\n .body(new JSONObject().put(\"filters\", filters).toString())\n .asString();\n\nSystem.out.println(response.getBody());"
}
]
}
},
"/v1/memories/events/": {
"get": {
"tags": [

View File

@@ -861,6 +861,88 @@ curl -X GET "https://api.mem0.ai/v1/memories/582bbe6d-506b-48c6-a4c6-5df3b1e6342
```
</CodeGroup>
#### Get all memories using custom filters
Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, date, and more.
Here you need to define `version` as `v2` in the get_all method.
Example: Get all memories using user_id and date filters
<CodeGroup>
```python Python
filters = {
"AND":[
{
"user_id":"alex"
},
{
"created_at":{
"gte":"2024-07-01",
"lte":"2024-07-31"
}
}
]
}
client.get_all(version="v2", filters=filters)
```
```javascript JavaScript
const filters = {
"AND":[
{
"user_id":"alex"
},
{
"created_at":{
"gte":"2024-07-01",
"lte":"2024-07-31"
}
}
]
};
client.getAll({ version: "v2", filters })
.then(memories => console.log(memories))
.catch(error => console.error(error));
```
```bash cURL
curl -X GET "https://api.mem0.ai/v1/memories/?version=v2" \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"filters": {
"AND": [
{
"user_id": "alex"
},
{
"created_at": {
"gte": "2024-07-01",
"lte": "2024-07-31"
}
}
]
}
}'
```
```json Output
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
}
]
```
</CodeGroup>
### 4.5 Memory History
Get history of how a memory has changed over time.

View File

@@ -139,10 +139,11 @@ class MemoryClient:
return response.json()
@api_error_handler
def get_all(self, **kwargs) -> List[Dict[str, Any]]:
def get_all(self, version: str = "v1", **kwargs) -> List[Dict[str, Any]]:
"""Retrieve all memories, with optional filtering.
Args:
version: The API version to use for the search endpoint.
**kwargs: Optional parameters for filtering (user_id, agent_id, app_id, limit).
Returns:
@@ -153,7 +154,10 @@ class MemoryClient:
"""
kwargs.update({"org_name": self.organization, "project_name": self.project})
params = self._prepare_params(kwargs)
response = self.client.get("/v1/memories/", params=params)
if version == "v1":
response = self.client.get(f"/{version}/memories/", params=params)
elif version == "v2":
response = self.client.post(f"/{version}/memories/", json=params)
response.raise_for_status()
capture_client_event(
"client.get_all",