Skip to content

MemSync Tutorial

NOTE

For comprehensive documentation and detailed examples, see the Full Guide.

Welcome to MemSync

This quickstart guide will help you integrate MemSync into your application and start building personalized AI experiences. You'll learn how to store memories, search for relevant context, and retrieve user profiles.

Prerequisites

Before getting started, make sure you have:

  • A MemSync account and API key
  • Basic knowledge of REST APIs
  • Your preferred programming language setup (Python, JavaScript, etc.)

Authentication

In order to interact with the MemSync API you need to create a service account and API key. You can register and generate an API key in the MemSync app.

TIP

You can generate API keys on the MemSync Developers page.

MemSync uses API key-based authentication for all API requests. You'll need to include your API key in the X-API-Key header:

X-API-Key: YOUR_API_KEY

Coming Soon: OAuth 2.0 authentication will be available for enhanced security and easier integration with third-party applications.

Step 1: Store Your First Memory

Let's start by storing a conversation that MemSync will process to extract meaningful memories:

python
import requests

url = "https://api.memchat.io/v1/memories"
headers = {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}

data = {
    "messages": [
        {
            "role": "user", 
            "content": "I'm a software engineer at Google working on machine learning projects. I love hiking and photography in my free time."
        },
        {
            "role": "assistant", 
            "content": "That's great! It sounds like you have a nice balance between your technical work and creative hobbies."
        }
    ],
    "agent_id": "my-chatbot",
    "thread_id": "conversation-123",
    "source": "chat"
}

response = requests.post(url, json=data, headers=headers)
print(response.json())
javascript
const response = await fetch("https://api.memchat.io/v1/memories", {
  method: "POST",
  headers: {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    messages: [
      {
        role: "user",
        content: "I'm a software engineer at Google working on machine learning projects. I love hiking and photography in my free time."
      },
      {
        role: "assistant",
        content: "That's great! It sounds like you have a nice balance between your technical work and creative hobbies."
      }
    ],
    agent_id: "my-chatbot",
    thread_id: "conversation-123",
    source: "chat"
  })
});

const data = await response.json();
console.log(data);

Step 2: Search for Relevant Memories

Now let's search for memories related to the user's interests:

python
import requests

url = "https://api.memchat.io/v1/memories/search"
headers = {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}

data = {
    "query": "What does the user do for work?",
    "limit": 5,
    "rerank": True
}

response = requests.post(url, json=data, headers=headers)
result = response.json()

print("User Bio:", result['user_bio'])
print("Relevant Memories:")
for memory in result['memories']:
    print(f"- {memory['memory']}")
javascript
const response = await fetch("https://api.memchat.io/v1/memories/search", {
  method: "POST",
  headers: {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    query: "What does the user do for work?",
    limit: 5,
    rerank: true
  })
});

const result = await response.json();
console.log("User Bio:", result.user_bio);
console.log("Relevant Memories:");
result.memories.forEach(memory => {
  console.log(`- ${memory.memory}`);
});

Step 3: Get User Profile

Retrieve the user's complete profile with auto-generated bio and insights:

python
import requests

url = "https://api.memchat.io/v1/users/profile"
headers = {
    "X-API-Key": "YOUR_API_KEY"
}

response = requests.get(url, headers=headers)
profile = response.json()

print("User Bio:", profile['user_bio'])
print("Profiles:", profile['profiles'])
print("Insights:", profile['insights'])
javascript
const response = await fetch("https://api.memchat.io/v1/users/profile", {
  method: "GET",
  headers: {
    "X-API-Key": "YOUR_API_KEY"
  }
});

const profile = await response.json();
console.log("User Bio:", profile.user_bio);
console.log("Profiles:", profile.profiles);
console.log("Insights:", profile.insights);

Understanding the Response

When you search for memories, MemSync returns:

json
{
  "user_bio": "Software engineer at Google specializing in machine learning with interests in hiking and photography",
  "memories": [
    {
      "id": "mem_123",
      "memory": "Works as a software engineer at Google focusing on machine learning projects",
      "categories": ["career"],
      "type": "semantic",
      "vector_distance": 0.15,
      "rerank_score": 0.92,
      "source": "chat",
      "created_at": "2024-03-20T10:00:00Z"
    }
  ]
}

Key Fields:

  • user_bio: Auto-generated summary of the user
  • memory: The extracted fact or memory
  • categories: Organized tags (career, interests, etc.)
  • type: semantic (lasting facts) or episodic (time-bound events)
  • vector_distance: Similarity score for search relevance
  • rerank_score: Enhanced relevance score when reranking is enabled

Next Steps

Now that you've made your first API calls, explore these advanced features:

  • Memory Categories: Learn how memories are organized into categories like work, hobbies, and relationships
  • Integration Setup: Import data from social media, documents, and chat platforms
  • API Reference: Explore all available endpoints and advanced features
  • Best Practices: Learn optimization techniques for memory storage and retrieval

Example: Building a Personalized Chatbot

Here's a complete example of how to build a chatbot that remembers user context:

python
import requests

class PersonalizedChatbot:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.memchat.io/v1"
        self.headers = {
            "X-API-Key": api_key,
            "Content-Type": "application/json"
        }
    
    def chat(self, user_message, user_id, thread_id="default"):
        # 1. Search for relevant memories
        memories = self.search_memories(user_message)
        
        # 2. Create context from memories
        context = self.build_context(memories)
        
        # 3. Generate response (using your LLM)
        response = self.generate_response(context, user_message)
        
        # 4. Store the conversation
        self.store_conversation(user_message, response, thread_id)
        
        return response
    
    def search_memories(self, query):
        response = requests.post(
            f"{self.base_url}/memories/search",
            headers=self.headers,
            json={"query": query, "limit": 5, "rerank": True}
        )
        return response.json()
    
    def store_conversation(self, user_msg, bot_response, thread_id):
        requests.post(
            f"{self.base_url}/memories",
            headers=self.headers,
            json={
                "messages": [
                    {"role": "user", "content": user_msg},
                    {"role": "assistant", "content": bot_response}
                ],
                "agent_id": "my-chatbot",
                "thread_id": thread_id,
                "source": "chat"
            }
        )

# Usage
chatbot = PersonalizedChatbot("YOUR_API_KEY")
response = chatbot.chat("What should I work on today?", "user123")

This example shows the basic pattern: search for context, generate response, store conversation. MemSync handles the complex memory extraction and organization automatically.

Common Issues

401 Unauthorized Error

Make sure your API key is correctly set in the X-API-Key header and that it's valid.

No memories returned

Ensure you've stored some conversations first using the /memories endpoint before searching.

Rate limiting

MemSync has rate limits to ensure fair usage. If you hit rate limits, implement exponential backoff and retry logic.

TIP

Ready to dive deeper? Check out our Full Guide, Core Concepts, or explore the full API reference.