LangMem API Documentation

Complete reference for the fact-based LangMem API with individual fact extraction, intelligent deduplication, memory updates, and precision search (0.86+ similarity scores).

Base URL & Authentication

🔗 Base URL

http://localhost:8765

🔐 Authentication

All API requests require Bearer token authentication:

Authorization: Bearer langmem_api_key_2025

Core Memory Endpoints

📥 POST /v1/memories/store

Store a memory with fact-based extraction, deduplication, and intelligent memory actions (ADD/UPDATE/DELETE)

Request Body

{
  "content": "Ondrej has a son named Cyril who is 8 years old and loves playing soccer. Cyril goes to elementary school in Prague.",
  "user_id": "user123",
  "session_id": "session1",
  "metadata": {
    "category": "family",
    "importance": "high",
    "privacy_level": "personal",
    "tags": ["family", "son", "personal"]
  }
}

Response

{
  "total_facts": 5,
  "stored_facts": 5,
  "status": "stored",
  "approach": "fact_based_with_deduplication",
  "facts": [
    {
      "action": "added",
      "fact": "Ondrej's son, Cyril, is 8 years old.",
      "id": "550e8400-e29b-41d4-a716-446655440001"
    },
    {
      "action": "added",
      "fact": "Cyril loves playing soccer.",
      "id": "550e8400-e29b-41d4-a716-446655440002"
    },
    {
      "action": "added",
      "fact": "Cyril attends elementary school in Prague.",
      "id": "550e8400-e29b-41d4-a716-446655440003"
    }
  ],
  "created_at": "2025-07-17T19:30:00Z"
}

cURL Example

curl -X POST "http://localhost:8765/v1/memories/store" \
  -H "Authorization: Bearer langmem_api_key_2025" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "John works for Google in California",
    "user_id": "user123",
    "metadata": {"category": "business"}
  }'

🔍 POST /v1/memories/search

Search individual facts using precision vector search with 0.86+ similarity scores for specific queries

Request Body

{
  "query": "How old is Cyril?",
  "user_id": "user123",
  "limit": 10,
  "threshold": 0.5,
  "include_graph": true
}

Response

{
  "memories": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440001",
      "content": "Ondrej's son, Cyril, is 8 years old.",
      "metadata": {
        "type": "fact",
        "extraction_method": "llm_fact_extraction",
        "category": "family"
      },
      "user_id": "user123",
      "session_id": "session1",
      "similarity": 0.759,
      "created_at": "2025-07-17T19:30:00Z",
      "relationships": [
        {
          "entity1_name": "Ondrej",
          "entity1_type": "Person",
          "relationship": "IS_FATHER_OF",
          "entity2_name": "Cyril",
          "entity2_type": "Person",
          "confidence": 0.9
        }
      ]
    },
    {
      "id": "550e8400-e29b-41d4-a716-446655440004",
      "content": "Cyril is currently 9 years old.",
      "metadata": {
        "type": "fact",
        "extraction_method": "llm_fact_extraction"
      },
      "similarity": 0.913
    }
  ],
  "context": {
    "query": "How old is Cyril?",
    "user_id": "user123",
    "threshold": 0.5,
    "search_type": "fact_based_hybrid",
    "approach": "fact_based_with_deduplication"
  },
  "total_count": 2
}

cURL Example

curl -X POST "http://localhost:8765/v1/memories/search" \
  -H "Authorization: Bearer langmem_api_key_2025" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Where does John work?",
    "user_id": "user123",
    "limit": 5,
    "threshold": 0.5,
    "include_graph": true
  }'

🧠 POST /v1/memories/retrieve

Retrieve relevant memories for conversation context

Request Body

{
  "messages": [
    {
      "role": "user",
      "content": "Tell me about my family"
    },
    {
      "role": "assistant", 
      "content": "I'd be happy to help with family information. What would you like to know?"
    },
    {
      "role": "user",
      "content": "Who are my children?"
    }
  ],
  "user_id": "user123",
  "session_id": "session1"
}

Response

{
  "memories": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "content": "Ondrej has a son named Cyril who is 8 years old",
      "similarity": 0.745,
      "relationships": [
        {
          "entity_name": "Cyril",
          "entity_type": "Person",
          "relationship": "HAS_SON",
          "confidence": 1.0
        }
      ]
    }
  ],
  "context": {
    "session_id": "session1",
    "message_count": 3,
    "user_context": {},
    "retrieved_at": "2025-07-16T19:30:00Z"
  },
  "total_count": 1
}

👤 GET /v1/memories/users/{user_id}

Get all memories for a specific user

Query Parameters

Parameter Type Default Description
limit integer 50 Maximum number of memories to return
offset integer 0 Number of memories to skip

Response

{
  "memories": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "content": "Ondrej has a son named Cyril who is 8 years old",
      "metadata": {
        "category": "family",
        "importance": "high"
      },
      "user_id": "user123",
      "session_id": "session1",
      "created_at": "2025-07-16T19:30:00Z",
      "updated_at": "2025-07-16T19:30:00Z"
    }
  ],
  "total_count": 1,
  "limit": 50,
  "offset": 0
}

cURL Example

curl -X GET "http://localhost:8765/v1/memories/users/user123?limit=10&offset=0" \
  -H "Authorization: Bearer langmem_api_key_2025"

🗑️ DELETE /v1/memories/{memory_id}

Delete a specific memory and its graph relationships

Response

{
  "status": "deleted",
  "id": "550e8400-e29b-41d4-a716-446655440000"
}

cURL Example

curl -X DELETE "http://localhost:8765/v1/memories/550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer langmem_api_key_2025"

System Endpoints

🏠 GET /

Root endpoint with system information

Response

{
  "message": "LangMem API - Long-term Memory System",
  "version": "1.0.0",
  "status": "running"
}

❤️ GET /health

Health check with service status

Response

{
  "status": "healthy",
  "services": {
    "ollama": "healthy",
    "supabase": "healthy",
    "neo4j": "healthy",
    "postgres": "healthy"
  },
  "timestamp": "2025-07-16T19:30:00Z"
}

cURL Example

curl -X GET "http://localhost:8765/health"

AI Relationship Extraction

🤖 Automatic Relationship Extraction

LangMem automatically extracts relationships from content using Llama3.2 model. Here are examples of relationship types that are dynamically generated:

Relationship Types

Category Example Relationships Entity Types
Family IS_FATHER_OF, IS_SON_OF, IS_PARENT_OF Person → Person
Business FOUNDED, WORKS_FOR, EMPLOYED Person → Organization
Technology CREATED_BY, USES, DEVELOPED Technology → Person
Geography LOCATED_IN, DESIGNED Location → Location
Science REVOLUTIONIZED, WORKED_AT Person → Concept

Example AI Extraction

{
  "input": "Steve Jobs founded Apple Inc. in Cupertino, California",
  "extracted_relationships": [
    {
      "entity1": "Steve Jobs",
      "entity1_type": "Person",
      "relationship": "FOUNDED",
      "entity2": "Apple Inc.",
      "entity2_type": "Organization",
      "confidence": 0.9
    },
    {
      "entity1": "Apple Inc.",
      "entity1_type": "Organization",
      "relationship": "LOCATED_IN",
      "entity2": "Cupertino, California",
      "entity2_type": "Location",
      "confidence": 0.9
    }
  ]
}

Error Handling

🚨 Error Response Format

{
  "detail": "Failed to store memory: Invalid content format"
}

Common Error Codes

HTTP Status Description Common Causes
400 Bad Request Invalid JSON, missing required fields
401 Unauthorized Missing or invalid Bearer token
404 Not Found Memory ID not found
500 Internal Server Error Database connection, AI processing errors

Database Access

🗄️ Direct Database Access

For advanced users, direct database access is available:

PostgreSQL (Vector Storage)

-- Connect to PostgreSQL
psql "postgresql://postgres:CzkaYmRvc26Y@localhost:5435/postgres"

-- Query memories
SELECT id, content, user_id, metadata 
FROM langmem_documents 
WHERE user_id = 'user123' 
ORDER BY created_at DESC;

-- Vector similarity search
SELECT id, content, 1 - (embedding <=> '[0.1, 0.2, ...]') as similarity
FROM langmem_documents
WHERE user_id = 'user123'
ORDER BY embedding <=> '[0.1, 0.2, ...]'
LIMIT 10;

Neo4j (Graph Relationships)

// Connect to Neo4j Browser: http://localhost:7474
// Username: neo4j, Password: langmem_neo4j_password

// View all relationships
MATCH (n)-[r]->(m) RETURN n, r, m LIMIT 25;

// Find specific relationship types
MATCH (p:Person)-[r:IS_FATHER_OF]->(c:Person) 
RETURN p.name, r, c.name;

// Complex graph traversal
MATCH (p:Person)-[:FOUNDED]->(org:Organization)-[:LOCATED_IN]->(loc:Location)
RETURN p.name, org.name, loc.name;

Integration Examples

🐍 Python Client

import requests
import json

class LangMemClient:
    def __init__(self, base_url="http://localhost:8765", api_key="langmem_api_key_2025"):
        self.base_url = base_url
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
    
    def store_memory(self, content, user_id, session_id=None, metadata=None):
        """Store a memory with AI relationship extraction."""
        data = {
            'content': content,
            'user_id': user_id,
            'session_id': session_id,
            'metadata': metadata or {}
        }
        response = requests.post(
            f"{self.base_url}/v1/memories/store",
            headers=self.headers,
            json=data
        )
        return response.json()
    
    def search_memories(self, query, user_id, limit=10, threshold=0.5):
        """Search memories with hybrid search."""
        data = {
            'query': query,
            'user_id': user_id,
            'limit': limit,
            'threshold': threshold,
            'include_graph': True
        }
        response = requests.post(
            f"{self.base_url}/v1/memories/search",
            headers=self.headers,
            json=data
        )
        return response.json()

# Usage
client = LangMemClient()

# Store memory
result = client.store_memory(
    content="John works for Google in California",
    user_id="user123",
    metadata={"category": "business"}
)
print(f"Memory stored: {result['id']}")

# Search memories
results = client.search_memories(
    query="Where does John work?",
    user_id="user123"
)
print(f"Found {results['total_count']} memories")
for memory in results['memories']:
    print(f"- {memory['content']} (similarity: {memory['similarity']:.3f})")
    if 'relationships' in memory:
        for rel in memory['relationships']:
            print(f"  → {rel['relationship']} {rel['entity_name']}")

🟨 JavaScript Client

class LangMemClient {
    constructor(baseUrl = 'http://localhost:8765', apiKey = 'langmem_api_key_2025') {
        this.baseUrl = baseUrl;
        this.headers = {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        };
    }
    
    async storeMemory(content, userId, sessionId = null, metadata = {}) {
        const response = await fetch(`${this.baseUrl}/v1/memories/store`, {
            method: 'POST',
            headers: this.headers,
            body: JSON.stringify({
                content,
                user_id: userId,
                session_id: sessionId,
                metadata
            })
        });
        return await response.json();
    }
    
    async searchMemories(query, userId, limit = 10, threshold = 0.5) {
        const response = await fetch(`${this.baseUrl}/v1/memories/search`, {
            method: 'POST',
            headers: this.headers,
            body: JSON.stringify({
                query,
                user_id: userId,
                limit,
                threshold,
                include_graph: true
            })
        });
        return await response.json();
    }
}

// Usage
const client = new LangMemClient();

// Store memory
const result = await client.storeMemory(
    'John works for Google in California',
    'user123',
    null,
    { category: 'business' }
);
console.log('Memory stored:', result.id);

// Search memories
const results = await client.searchMemories(
    'Where does John work?',
    'user123'
);
console.log(`Found ${results.total_count} memories`);
results.memories.forEach(memory => {
    console.log(`- ${memory.content} (similarity: ${memory.similarity.toFixed(3)})`);
    if (memory.relationships) {
        memory.relationships.forEach(rel => {
            console.log(`  → ${rel.relationship} ${rel.entity_name}`);
        });
    }
});

Ready to Build?

Use the LangMem API to integrate AI-powered memory with automatic relationship extraction into your applications.