From pip install to AI with memory in 5 minutes ⚡
pip install memofaiCreate first_app.py:
from memofai import create_moa_client
import os
# Initialize
client = create_moa_client(
api_token=os.getenv('MEMOFAI_TOKEN'),
environment='production'
)
# Create workspace
print("Creating workspace...")
workspace = client.workspaces.create({
'name': 'My First Workspace',
'description': 'Learning Memof.ai!'
})
print(f"✓ Workspace: {workspace['name']}")
# Create bot
print("Creating bot...")
bot = client.bots.create({
'name': 'My First Bot',
'workspace_id': workspace['id']
})
print(f"✓ Bot: {bot['name']}")
# Store memory
print("Storing memory...")
memory = client.memories.create({
'bot_id': bot['id'],
'content': 'User loves Python and building AI applications'
})
print(f"✓ Memory stored: {memory['id']}")
# Search
print("Searching memories...")
results = client.memories.search({
'bot_id': bot['id'],
'query': 'programming preferences',
'limit': 5
})
print(f"✓ Found {len(results)} memories:")
for result in results:
print(f" - {result['content']}")export MEMOFAI_TOKEN="moa_your_token"
python first_app.pyA more realistic pattern
from memofai import create_moa_client
from typing import List, Dict, Any
import os
class UserContextManager:
"""Manages AI memory for a user"""
def __init__(self, user_id: str):
self.user_id = user_id
self.client = create_moa_client(
api_token=os.getenv('MEMOFAI_TOKEN'),
environment='production'
)
self.workspace_id = self._get_workspace()
self.bot_id = self._get_or_create_bot()
def _get_workspace(self) -> str:
"""Get or create workspace"""
workspaces = self.client.workspaces.list()
# Find existing or create new
app_workspace = next(
(ws for ws in workspaces if ws['name'] == 'My App'),
None
)
if not app_workspace:
app_workspace = self.client.workspaces.create({
'name': 'My App',
'description': 'Main application workspace'
})
return app_workspace['id']
def _get_or_create_bot(self) -> str:
"""Get or create user-specific bot"""
bots = self.client.bots.list()
# Find user's bot
user_bot = next(
(bot for bot in bots
if bot['name'] == f'user_{self.user_id}'
and bot['workspace_id'] == self.workspace_id),
None
)
if not user_bot:
user_bot = self.client.bots.create({
'name': f'user_{self.user_id}',
'workspace_id': self.workspace_id,
'description': f'Context for user {self.user_id}'
})
return user_bot['id']
def remember(self, content: str) -> Dict[str, Any]:
"""Store a memory"""
return self.client.memories.create({
'bot_id': self.bot_id,
'content': content
})
def recall(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
"""Search memories"""
return self.client.memories.search({
'bot_id': self.bot_id,
'query': query,
'limit': limit
})
def get_all_memories(self) -> List[Dict[str, Any]]:
"""Get all memories"""
return self.client.memories.list({
'bot_id': self.bot_id
})
def forget(self, memory_id: str) -> None:
"""Delete a memory"""
self.client.memories.delete(memory_id)
def update_memory(self, memory_id: str, new_content: str) -> Dict[str, Any]:
"""Update a memory"""
return self.client.memories.update({
'id': memory_id,
'content': new_content
})
# Usage Example
if __name__ == '__main__':
# Initialize for user
manager = UserContextManager(user_id='user_123')
# Store user preferences
manager.remember("User prefers dark mode and compact layout")
manager.remember("User is working on a FastAPI project")
manager.remember("User timezone is EST")
# Recall context
ui_prefs = manager.recall("UI preferences")
project_info = manager.recall("current project")
print("UI Preferences:")
for pref in ui_prefs:
print(f" - {pref['content']}")
print("\nProject Context:")
for info in project_info:
print(f" - {info['content']}")
# Get all memories
all_memories = manager.get_all_memories()
print(f"\nTotal memories: {len(all_memories)}")from memofai import create_moa_client
client = create_moa_client(api_token='moa_your_token')
def store_user_preference(bot_id: str, preference: str):
"""Store a user preference"""
return client.memories.create({
'bot_id': bot_id,
'content': preference
})
def get_user_preferences(bot_id: str):
"""Get all user preferences"""
return client.memories.search({
'bot_id': bot_id,
'query': 'user preferences',
'limit': 10
})class ConversationMemory:
"""Store conversation history"""
def __init__(self, session_id: str, bot_id: str):
self.session_id = session_id
self.bot_id = bot_id
self.client = create_moa_client(api_token=os.getenv('MEMOFAI_TOKEN'))
def add_message(self, role: str, content: str):
"""Add message to conversation"""
return self.client.memories.create({
'bot_id': self.bot_id,
'content': f"[{role}]: {content}",
'metadata': {
'session_id': self.session_id,
'role': role,
'timestamp': datetime.now().isoformat()
}
})
def get_context(self, last_n: int = 10):
"""Get recent conversation context"""
return self.client.memories.list({
'bot_id': self.bot_id,
'limit': last_n
})class KnowledgeBase:
"""Shared knowledge bot"""
def __init__(self, kb_bot_id: str):
self.kb_bot_id = kb_bot_id
self.client = create_moa_client(api_token=os.getenv('MEMOFAI_TOKEN'))
def add_knowledge(self, content: str, category: str = None):
"""Add to knowledge base"""
memory_content = f"[{category}] {content}" if category else content
return self.client.memories.create({
'bot_id': self.kb_bot_id,
'content': memory_content
})
def search_knowledge(self, query: str, limit: int = 5):
"""Search knowledge base"""
return self.client.memories.search({
'bot_id': self.kb_bot_id,
'query': query,
'limit': limit
})from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from memofai import create_moa_client
import os
app = FastAPI()
# Initialize client
moa_client = create_moa_client(
api_token=os.getenv('MEMOFAI_TOKEN'),
environment='production'
)
class MemoryCreate(BaseModel):
bot_id: str
content: str
class MemorySearch(BaseModel):
bot_id: str
query: str
limit: int = 5
@app.post("/memories")
def create_memory(memory: MemoryCreate):
"""Store a memory"""
try:
result = moa_client.memories.create({
'bot_id': memory.bot_id,
'content': memory.content
})
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/search")
def search_memories(search: MemorySearch):
"""Search memories"""
try:
results = moa_client.memories.search({
'bot_id': search.bot_id,
'query': search.query,
'limit': search.limit
})
return {'results': results}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/bots")
def list_bots():
"""List all bots"""
try:
return moa_client.bots.list()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))from flask import Flask, request, jsonify
from memofai import create_moa_client
import os
app = Flask(__name__)
# Initialize client
moa_client = create_moa_client(
api_token=os.getenv('MEMOFAI_TOKEN'),
environment='production'
)
@app.route('/memories', methods=['POST'])
def create_memory():
"""Store a memory"""
data = request.json
try:
result = moa_client.memories.create({
'bot_id': data['bot_id'],
'content': data['content']
})
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/search', methods=['POST'])
def search_memories():
"""Search memories"""
data = request.json
try:
results = moa_client.memories.search({
'bot_id': data['bot_id'],
'query': data['query'],
'limit': data.get('limit', 5)
})
return jsonify({'results': results})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)from memofai import create_moa_client
from memofai.exceptions import (
MoaError,
AuthenticationError,
NotFoundError,
RateLimitError
)
client = create_moa_client(api_token='moa_your_token')
try:
memory = client.memories.create({
'bot_id': 'bot_123',
'content': 'Some content'
})
except AuthenticationError:
print("Invalid API token")
except NotFoundError:
print("Bot not found")
except RateLimitError:
print("Rate limit exceeded, retry later")
except MoaError as e:
print(f"API error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")Questions? → support@memof.ai