diff --git a/docs/api-reference/memory/v1-get-memories.mdx b/docs/api-reference/memory/v1-get-memories.mdx index d980625e..29b664ee 100644 --- a/docs/api-reference/memory/v1-get-memories.mdx +++ b/docs/api-reference/memory/v1-get-memories.mdx @@ -1,4 +1,4 @@ --- -title: 'V1 Get Memories' +title: 'Get Memories (v1 - Deprecated)' openapi: get /v1/memories/ --- diff --git a/docs/api-reference/memory/v1-search-memories.mdx b/docs/api-reference/memory/v1-search-memories.mdx index 989ba5f7..c6440657 100644 --- a/docs/api-reference/memory/v1-search-memories.mdx +++ b/docs/api-reference/memory/v1-search-memories.mdx @@ -1,4 +1,4 @@ --- -title: 'V1 Search Memories' +title: 'Search Memories (v1 - Deprecated)' openapi: post /v1/memories/search/ ---- \ No newline at end of file +--- diff --git a/docs/api-reference/memory/v2-get-memories.mdx b/docs/api-reference/memory/v2-get-memories.mdx index b16fd861..885d853e 100644 --- a/docs/api-reference/memory/v2-get-memories.mdx +++ b/docs/api-reference/memory/v2-get-memories.mdx @@ -1,74 +1,43 @@ --- -title: 'V2 Get Memories' +title: 'Get Memories (v2)' openapi: post /v2/memories/ --- +The v2 get memories API is powerful and flexible, allowing for more precise memory listing without the need for a search query. It supports complex logical operations (AND, OR) and comparison operators for advanced filtering capabilities. The comparison operators include: +- `in`: Matches any of the values specified +- `gte`: Greater than or equal to +- `lte`: Less than or equal to +- `gt`: Greater than +- `lt`: Less than -Mem0 offers two versions of the get memories API: v1 and v2. Here's how they differ: + +```python Code +memories = m.get_all( + filters={ + "AND": [ + { + "user_id": "alex" + }, + { + "created_at": {"gte": "2024-07-01", "lte": "2024-07-31"} + } + ] + }, + version="v2" +) +``` - - - - ```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" - } +```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" +} ] - ``` - - - - - - ```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" - } -] - ``` - - - - -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. +``` + diff --git a/docs/api-reference/memory/v2-search-memories.mdx b/docs/api-reference/memory/v2-search-memories.mdx index a7c31db4..2f0606bb 100644 --- a/docs/api-reference/memory/v2-search-memories.mdx +++ b/docs/api-reference/memory/v2-search-memories.mdx @@ -1,83 +1,51 @@ --- -title: 'V2 Search Memories' +title: 'Search Memories (v2)' openapi: post /v2/memories/search/ --- -Mem0 offers two versions of the search API: v1 and v2. Here's how they differ: +The v2 search API is powerful and flexible, allowing for more precise memory retrieval. It supports complex logical operations (AND, OR) and comparison operators for advanced filtering capabilities. The comparison operators include: +- `in`: Matches any of the values specified +- `gte`: Greater than or equal to +- `lte`: Less than or equal to +- `gt`: Greater than +- `lt`: Less than +- `ne`: Not equal to +- `icontains`: Case-insensitive containment check - - - - ```python Code - related_memories = m.search(query="What are Alice's hobbies?", user_id="alice") - ``` + + ```python Code + related_memories = m.vsearch( + query="What are Alice's hobbies?", + version="v2", + filters={ + "AND": [ + { + "user_id": "alice" + }, + { + "agent_id": {"in": ["travel-agent", "sports-agent"]} + } + ] + }, + ) + ``` - ```json Output - [ - { - "id":"ea925981-272f-40dd-b576-be64e4871429", - "memory":"Likes to play cricket and plays cricket on weekends.", - "metadata":{ - "category":"hobbies" - }, - "score":0.32116443111457704, - "created_at":"2024-07-26T10:29:36.630547-07:00", - "updated_at":"None", - "user_id":"alice" - } - ] - ``` - - - - - - ```python Code - related_memories = m.vsearch( - query="What are Alice's hobbies?", - filters={ - "AND":[ - { - "user_id":"alice" - }, - { - "agent_id":{ - "in":[ - "travelling", - "sports" - ] - } - } - ] - }, - version="v2" - ) - ``` - - ```json Output - { - "memories": [ - { - "id": "ea925981-272f-40dd-b576-be64e4871429", - "memory": "Likes to play cricket and plays cricket on weekends.", - "metadata": { - "category": "hobbies" - }, - "score": 0.32116443111457704, - "created_at": "2024-07-26T10:29:36.630547-07:00", - "updated_at": null, - "user_id": "alice", - "agent_id": "sports" - } - ], - } - ``` - - - - -Key difference between v1 and v2 search: - -• **Filters**: v2 allows you to apply filters to narrow down search results 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 search API is more powerful and flexible, allowing for more precise memory retrieval. + ```json Output + { + "memories": [ + { + "id": "ea925981-272f-40dd-b576-be64e4871429", + "memory": "Likes to play cricket and plays cricket on weekends.", + "metadata": { + "category": "hobbies" + }, + "score": 0.32116443111457704, + "created_at": "2024-07-26T10:29:36.630547-07:00", + "updated_at": null, + "user_id": "alice", + "agent_id": "sports-agent" + } + ], + } + ``` + diff --git a/docs/api-reference/overview.mdx b/docs/api-reference/overview.mdx index eb36b4f7..c994ec71 100644 --- a/docs/api-reference/overview.mdx +++ b/docs/api-reference/overview.mdx @@ -38,28 +38,26 @@ Organizations and projects provide the following capabilities: Example with the mem0 Python package: + + + ```python from mem0 import MemoryClient - -# Recommended: Using organization and project IDs -client = MemoryClient( - org_id='YOUR_ORG_ID', # It can be found on the organization settings page in dashboard - project_id='YOUR_PROJECT_ID', -) +client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID') ``` -Example with the mem0 Node.js package: + + + ```javascript import { MemoryClient } from "mem0ai"; - -# Recommended: Using organization and project IDs -const client = new MemoryClient({ - organizationId: "YOUR_ORG_ID", - projectId: "YOUR_PROJECT_ID" -}); +const client = new MemoryClient({organizationId: "YOUR_ORG_ID", projectId: "YOUR_PROJECT_ID"}); ``` + + + ## Getting Started To begin using the Mem0 API, you'll need to: diff --git a/docs/docs.json b/docs/docs.json index 3ea7ea7c..4577d591 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -70,7 +70,8 @@ "pages": [ "features/openai_compatibility", "features/custom-prompts", - "open-source/multimodal-support" + "open-source/multimodal-support", + "open-source/features/rest-api" ] }, { @@ -201,18 +202,18 @@ "group": "Memory APIs", "icon": "microchip", "pages": [ - "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/v2-search-memories", + "api-reference/memory/v1-search-memories", + "api-reference/memory/v2-get-memories", + "api-reference/memory/v1-get-memories", + "api-reference/memory/history-memory", "api-reference/memory/get-memory", "api-reference/memory/update-memory", - "api-reference/memory/delete-memory", - "api-reference/memory/v1-search-memories", - "api-reference/memory/v2-search-memories", - "api-reference/memory/history-memory", "api-reference/memory/batch-update", + "api-reference/memory/delete-memory", "api-reference/memory/batch-delete", + "api-reference/memory/delete-memories", "api-reference/memory/create-memory-export", "api-reference/memory/get-memory-export" ] @@ -229,17 +230,12 @@ "group": "Organizations APIs", "icon": "building", "pages": [ + "api-reference/organization/create-org", "api-reference/organization/get-orgs", "api-reference/organization/get-org", - "api-reference/organization/create-org", - "api-reference/organization/update-org", - "api-reference/organization/delete-org", "api-reference/organization/get-org-members", "api-reference/organization/add-org-member", - "api-reference/organization/remove-org-member", - "api-reference/organization/get-org-projects", - "api-reference/organization/add-org-project", - "api-reference/organization/remove-org-project" + "api-reference/organization/delete-org" ] } ] diff --git a/docs/images/ai-assistant.png b/docs/images/ai-assistant.png deleted file mode 100644 index b116a440..00000000 Binary files a/docs/images/ai-assistant.png and /dev/null differ diff --git a/docs/images/ai-tutor.png b/docs/images/ai-tutor.png deleted file mode 100644 index abd4a9b8..00000000 Binary files a/docs/images/ai-tutor.png and /dev/null differ diff --git a/docs/images/customer-support-agent.png b/docs/images/customer-support-agent.png deleted file mode 100644 index 5ae06b36..00000000 Binary files a/docs/images/customer-support-agent.png and /dev/null differ diff --git a/docs/images/personal-travel-agent.png b/docs/images/personal-travel-agent.png deleted file mode 100644 index 290d205f..00000000 Binary files a/docs/images/personal-travel-agent.png and /dev/null differ diff --git a/docs/images/rest-api-server.png b/docs/images/rest-api-server.png new file mode 100644 index 00000000..d6a8c500 Binary files /dev/null and b/docs/images/rest-api-server.png differ diff --git a/docs/open-source/features/rest-api.mdx b/docs/open-source/features/rest-api.mdx new file mode 100644 index 00000000..7474dd2d --- /dev/null +++ b/docs/open-source/features/rest-api.mdx @@ -0,0 +1,77 @@ +--- +title: REST API Server +icon: "server" +iconType: "solid" +--- + +Mem0 provides a REST API server (written using FastAPI). Users can perform all operations through REST endpoints. The API also includes OpenAPI documentation, accessible at `/docs` when the server is running. + + + + + +## Features + +- **Create memories:** Create memories based on messages for a user, agent, or run. +- **Retrieve memories:** Get all memories for a given user, agent, or run. +- **Search memories:** Search stored memories based on a query. +- **Update memories:** Update an existing memory. +- **Delete memories:** Delete a specific memory or all memories for a user, agent, or run. +- **Reset memories:** Reset all memories for a user, agent, or run. +- **OpenAPI Documentation:** Accessible via `/docs` endpoint. + +## Running Locally + + + + +1. Create a `.env` file in the current directory and set your environment variables. For example: + +```txt +OPENAI_API_KEY=your-openai-api-key +``` + +2. Build the Docker image: + +```bash +docker build -t mem0-api-server . +``` + +3. Run the Docker container: + +``` bash +docker run -p 8000:8000 mem0-api-server +``` + +4. Access the API at http://localhost:8000. + + + + + +1. Create a `.env` file in the current directory and set your environment variables. For example: + +```txt +OPENAI_API_KEY=your-openai-api-key +``` + +2. Install dependencies: + +```bash +pip install -r requirements.txt +``` + +3. Start the FastAPI server: + +```bash +uvicorn main:app --reload +``` + +4. Access the API at http://localhost:8000. + + + + +## Usage + +Once the server is running (locally or via Docker), you can interact with it using any REST client or through your preferred programming language (e.g., Go, Java, etc.). You can test out the APIs using the OpenAPI documentation at [http://localhost:8000/docs](http://localhost:8000/docs) endpoint. diff --git a/docs/platform/quickstart.mdx b/docs/platform/quickstart.mdx index 77af8e69..01626642 100644 --- a/docs/platform/quickstart.mdx +++ b/docs/platform/quickstart.mdx @@ -1156,7 +1156,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&keywords=to play&p #### 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, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see [V2 Get Memories](/api-reference/memory/v2-get-memories). +Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see [v2 Get Memories](/api-reference/memory/v2-get-memories). Here you need to define `version` as `v2` in the get_all method. diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 00000000..7130f95a --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,16 @@ +FROM python:3.12-slim + +WORKDIR /app + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +COPY .env . +COPY . . + +EXPOSE 8000 + +ENV PYTHONUNBUFFERED=1 + +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] diff --git a/server/Makefile b/server/Makefile new file mode 100644 index 00000000..00f81484 --- /dev/null +++ b/server/Makefile @@ -0,0 +1,7 @@ +build: + docker build -t mem0-api-server . + +run_local: + docker run -p 8000:8000 -v $(shell pwd):/app mem0-api-server + +.PHONY: build run_local diff --git a/server/README.md b/server/README.md new file mode 100644 index 00000000..a736825b --- /dev/null +++ b/server/README.md @@ -0,0 +1,63 @@ +# Mem0 REST API Server + +Mem0 provides a REST API server (written using FastAPI). Users can perform all operations through REST endpoints. The API also includes OpenAPI documentation, accessible at `/docs` when the server is running. + +## Features + +- **Create memories:** Create memories based on messages for a user, agent, or run. +- **Retrieve memories:** Get all memories for a given user, agent, or run. +- **Search memories:** Search stored memories based on a query. +- **Update memories:** Update an existing memory. +- **Delete memories:** Delete a specific memory or all memories for a user, agent, or run. +- **Reset memories:** Reset all memories for a user, agent, or run. +- **OpenAPI Documentation:** Accessible via `/docs` endpoint. + +## Running Locally + +### With Docker + +1. Create a `.env` file in the root directory of the project and set your environment variables. For example: + +```env +OPENAI_API_KEY=your-openai-api-key +``` + +2. Build the Docker image: + +```bash +docker build -t mem0-api-server . +``` + +3. Run the Docker container: + +``` bash +docker run -p 8000:8000 mem0-api-server +``` + +4. Access the API at http://localhost:8000. + +### Without Docker + +1. Create a `.env` file in the root directory of the project and set your environment variables. For example: + +```env +OPENAI_API_KEY=your-openai-api-key +``` + +2. Install dependencies: + +```bash +pip install -r requirements.txt +``` + +3. Start the FastAPI server: + +```bash +uvicorn main:app --reload +``` + +4. Access the API at http://localhost:8000. + +### Usage + +Once the server is running (locally or via Docker), you can interact with it using any REST client or through your preferred programming language (e.g., Go, Java, etc.). You can test out the APIs using the OpenAPI documentation at [`http://localhost:8000/docs`](http://localhost:8000/docs) endpoint. diff --git a/server/main.py b/server/main.py new file mode 100644 index 00000000..af3ce764 --- /dev/null +++ b/server/main.py @@ -0,0 +1,158 @@ +import os +from fastapi import FastAPI, HTTPException, Query, Path +from fastapi.responses import JSONResponse, RedirectResponse +from pydantic import BaseModel, Field +from typing import Optional, List, Any, Dict +from mem0 import Memory +from dotenv import load_dotenv + +# Load environment variables +load_dotenv() + +MEMORY_INSTANCE = Memory() + +app = FastAPI( + title="Mem0 REST APIs", + description="A REST API for managing and searching memories for your AI Agents and Apps.", + version="1.0.0", +) + + +class Message(BaseModel): + role: str = Field(..., description="Role of the message (user or assistant).") + content: str = Field(..., description="Message content.") + + +class MemoryCreate(BaseModel): + messages: List[Message] = Field(..., description="List of messages to store.") + user_id: Optional[str] = None + agent_id: Optional[str] = None + run_id: Optional[str] = None + metadata: Optional[Dict[str, Any]] = None + + +class SearchRequest(BaseModel): + query: str = Field(..., description="Search query.") + user_id: Optional[str] = None + run_id: Optional[str] = None + agent_id: Optional[str] = None + + +@app.post("/configure", summary="Configure Mem0") +def set_config(config: Dict[str, Any]): + """Set memory configuration.""" + global MEMORY_INSTANCE + MEMORY_INSTANCE = Memory.from_config(config) + return {"message": "Configuration set successfully"} + + +@app.post("/memories", summary="Create memories") +def add_memory(memory_create: MemoryCreate): + """Store new memories.""" + if not any([memory_create.user_id, memory_create.agent_id, memory_create.run_id]): + raise HTTPException( + status_code=400, detail="At least one identifier (user_id, agent_id, run_id) is required." + ) + + params = {k: v for k, v in memory_create.model_dump().items() if v is not None and k != "messages"} + try: + response = MEMORY_INSTANCE.add(messages=[m.model_dump() for m in memory_create.messages], **params) + return JSONResponse(content=response) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.get("/memories", summary="Get memories") +def get_all_memories( + user_id: Optional[str] = None, + run_id: Optional[str] = None, + agent_id: Optional[str] = None, +): + """Retrieve stored memories.""" + if not any([user_id, run_id, agent_id]): + raise HTTPException(status_code=400, detail="At least one identifier is required.") + try: + params = {k: v for k, v in {"user_id": user_id, "run_id": run_id, "agent_id": agent_id}.items() if v is not None} + return MEMORY_INSTANCE.get_all(**params) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.get("/memories/{memory_id}", summary="Get a memory") +def get_memory(memory_id: str): + """Retrieve a specific memory by ID.""" + try: + return MEMORY_INSTANCE.get(memory_id) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.post("/search", summary="Search memories") +def search_memories(search_req: SearchRequest): + """Search for memories based on a query.""" + try: + params = {k: v for k, v in search_req.model_dump().items() if v is not None and k != "query"} + return MEMORY_INSTANCE.search(query=search_req.query, **params) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.put("/memories/{memory_id}", summary="Update a memory") +def update_memory(memory_id: str, updated_memory: Dict[str, Any]): + """Update an existing memory.""" + try: + return MEMORY_INSTANCE.update(memory_id=memory_id, data=updated_memory) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.get("/memories/{memory_id}/history", summary="Get memory history") +def memory_history(memory_id: str): + """Retrieve memory history.""" + try: + return MEMORY_INSTANCE.history(memory_id=memory_id) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.delete("/memories/{memory_id}", summary="Delete a memory") +def delete_memory(memory_id: str): + """Delete a specific memory by ID.""" + try: + MEMORY_INSTANCE.delete(memory_id=memory_id) + return {"message": "Memory deleted successfully"} + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.delete("/memories", summary="Delete all memories") +def delete_all_memories( + user_id: Optional[str] = None, + run_id: Optional[str] = None, + agent_id: Optional[str] = None, +): + """Delete all memories for a given identifier.""" + if not any([user_id, run_id, agent_id]): + raise HTTPException(status_code=400, detail="At least one identifier is required.") + try: + params = {k: v for k, v in {"user_id": user_id, "run_id": run_id, "agent_id": agent_id}.items() if v is not None} + MEMORY_INSTANCE.delete_all(**params) + return {"message": "All relevant memories deleted"} + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.post("/reset", summary="Reset all memories") +def reset_memory(): + """Completely reset stored memories.""" + try: + MEMORY_INSTANCE.reset() + return {"message": "All memories reset"} + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@app.get("/", summary="Redirect to the OpenAPI documentation", include_in_schema=False) +def home(): + """Redirect to the OpenAPI documentation.""" + return RedirectResponse(url='/docs') diff --git a/server/requirements.txt b/server/requirements.txt new file mode 100644 index 00000000..82a524ee --- /dev/null +++ b/server/requirements.txt @@ -0,0 +1,5 @@ +fastapi==0.115.8 +uvicorn==0.34.0 +pydantic==2.10.4 +mem0ai>=0.1.48 +python-dotenv==1.0.1