Troubleshooting

When things don't work as expected πŸ”§

Don't panic! Most issues have simple solutions. Let's debug together.

Quick Diagnostic

Run this checklist first:

  • API token starts with moa_
  • Using correct environment (production for live)
  • SDK is up to date (pip install -U memofai or npm update memofai)
  • Internet connection is working
  • Token has not expired

Common Issues

Authentication Errors

"Invalid API token" / 401 Unauthorized

Symptoms:

Error: 401 Unauthorized Message: Invalid API token

Causes & Solutions:

  1. Wrong token format

    # ❌ Wrong
    api_token = "your_token_here"
    
    # βœ… Correct (must start with moa_)
    api_token = "moa_abc123xyz..."
  2. Token not set

    # Check if token is actually set
    import os
    print(os.getenv('MEMOFAI_TOKEN'))  # Should not be None
  3. Expired token

    • Get a new token from memof.ai
    • Update your environment variables
  4. Whitespace in token

    # ❌ Has whitespace
    api_token = " moa_abc123 "
    
    # βœ… Clean
    api_token = "moa_abc123".strip()

Quick Fix:

# Get fresh token from memof.ai
export MEMOFAI_TOKEN="moa_your_new_token"

# Test it
curl -H "Authorization: Bearer $MEMOFAI_TOKEN" \
     https://api.memof.ai/api/workspaces/workspaces

Connection Errors

"Connection refused" / "Cannot connect to host"

Symptoms:

Error: Connection refused Unable to connect to api.memof.ai

Causes & Solutions:

  1. Wrong environment URL

    # ❌ Wrong
    client = create_moa_client(
        api_token='moa_...',
        environment='localhost'  # Wrong!
    )
    
    # βœ… Correct
    client = create_moa_client(
        api_token='moa_...',
        environment='production'
    )
  2. Network/Firewall blocking

    # Test connectivity
    ping api.memof.ai
    curl -I https://api.memof.ai
  3. VPN/Proxy interference

    • Try disabling VPN temporarily
    • Configure proxy if needed:
      import os
      os.environ['HTTPS_PROXY'] = 'http://proxy:8080'
  4. Typo in base URL

    # Check your custom base URL
    print(client.base_url)
    # Should be: https://api.memof.ai

Quick Fix:

# Test basic connectivity
curl https://api.memof.ai/api/workspaces/workspaces \
  -H "Authorization: Bearer moa_your_token"

# If this fails, it's a network issue

Rate Limiting

"429 Too Many Requests"

Symptoms:

Error: 429 Too Many Requests Rate limit exceeded

Explanation: You're making too many requests too quickly.

Current Limits:

  • 1,000 requests per minute
  • Resets every 60 seconds

Solutions:

  1. Add delays

    import time
    
    for item in items:
        client.memories.create(...)
        time.sleep(0.1)  # 100ms delay
  2. Implement retry logic

    from time import sleep
    
    def create_with_retry(memory_data, max_retries=3):
        for attempt in range(max_retries):
            try:
                return client.memories.create(memory_data)
            except RateLimitError:
                if attempt == max_retries - 1:
                    raise
                wait_time = 2 ** attempt  # Exponential backoff
                sleep(wait_time)
  3. Batch operations properly

    # ❌ Too fast
    for i in range(10000):
        client.memories.create(...)
    
    # βœ… Controlled rate
    from concurrent.futures import ThreadPoolExecutor
    
    def store_memory(data):
        return client.memories.create(data)
    
    with ThreadPoolExecutor(max_workers=5) as executor:
        results = list(executor.map(store_memory, memories))
  4. Use background workers

    # Queue operations instead of doing them all at once
    from celery import Celery
    
    @celery.task(rate_limit='10/m')  # 10 per minute
    def store_memory_async(data):
        return client.memories.create(data)

Not Found Errors

"404 Not Found" / "Resource not found"

Symptoms:

Error: 404 Not Found Bot/Workspace/Memory not found

Common Causes:

  1. Wrong ID

    # Make sure IDs are correct
    print(f"Bot ID: {bot_id}")  # Should be bot_...
    print(f"Workspace ID: {workspace_id}")  # Should be ws_...
  2. Using ID from different environment

    # ❌ Using production bot_id in sandbox
    client = create_moa_client(environment='sandbox')
    client.bots.get('bot_from_production')  # Won't work!
    
    # βœ… Use correct environment
    client = create_moa_client(environment='production')
    client.bots.get('bot_from_production')  # Works!
  3. Resource was deleted

    # Check if resource exists
    try:
        bot = client.bots.get(bot_id)
    except NotFoundError:
        print("Bot doesn't exist, creating new one")
        bot = client.bots.create({...})
  4. Wrong endpoint

    # ❌ Wrong
    client.bots.list({'workspace_id': 'ws_123'})
    
    # βœ… Correct
    bots = client.bots.list()
    workspace_bots = [b for b in bots if b['workspace_id'] == 'ws_123']

SDK Installation Issues

Python: "No module named 'memofai'"

Solutions:

  1. SDK not installed

    pip install memofai
  2. Wrong Python environment

    # Check which Python you're using
    which python
    python --version
    
    # Make sure pip installs to the right place
    python -m pip install memofai
  3. Virtual environment not activated

    # Activate your venv
    source venv/bin/activate  # Unix
    .\venv\Scripts\activate   # Windows
    
    # Then install
    pip install memofai
  4. Outdated pip

    pip install --upgrade pip
    pip install memofai

JavaScript: "Cannot find module 'memofai'"

Solutions:

  1. SDK not installed

    npm install memofai
  2. Wrong package manager

    # If using yarn
    yarn add memofai
    
    # If using pnpm
    pnpm add memofai
  3. Node modules not installed

    # Reinstall all dependencies
    rm -rf node_modules package-lock.json
    npm install
  4. Check package.json

    {
      "dependencies": {
        "memofai": "^1.0.0"  // Should be present
      }
    }

Search Not Finding Results

"Search returns empty array"

Symptoms:

results = client.memories.search({
    'bot_id': bot_id,
    'query': 'user preferences'
})
print(results)  # []

Common Causes:

  1. No memories stored yet

    # Check if bot has any memories
    all_memories = client.memories.list({'bot_id': bot_id})
    print(f"Total memories: {len(all_memories)}")
  2. Query too specific

    # ❌ Too specific
    results = client.memories.search({
        'query': 'exact phrase that might not exist'
    })
    
    # βœ… Broader query
    results = client.memories.search({
        'query': 'general topic'
    })
  3. Wrong bot ID

    # Make sure you're searching the right bot
    print(f"Searching bot: {bot_id}")
    print(f"Memories stored in bot: {correct_bot_id}")
    # These should match!
  4. Memories too recent (rare)

    # Give it a moment to index
    import time
    client.memories.create({...})
    time.sleep(1)  # Brief pause
    results = client.memories.search({...})

Debugging:

# Debug search issues
def debug_search(bot_id, query):
    # 1. Check total memories
    all_memories = client.memories.list({'bot_id': bot_id})
    print(f"Total memories in bot: {len(all_memories)}")
    
    # 2. Print some memories
    for mem in all_memories[:5]:
        print(f"  - {mem['content'][:100]}")
    
    # 3. Try search
    results = client.memories.search({
        'bot_id': bot_id,
        'query': query,
        'limit': 10
    })
    print(f"Search results: {len(results)}")
    
    return results

Type Errors (TypeScript/Python)

TypeScript: "Property 'xyz' does not exist"

Solutions:

  1. Outdated types

    npm update memofai
  2. Wrong type import

    // βœ… Correct
    import { createMoaClient, WorkspaceData } from 'memofai';
    
    // ❌ Wrong
    import { WorkspaceData } from 'memofai/types';  // Don't do this
  3. Type assertion needed

    const workspace = await client.workspaces.create({
      name: "Test"
    }) as WorkspaceData;

Python: "Type error in mypy"

Solutions:

  1. Add type hints

    from memofai.types import BotData
    
    bot: BotData = client.bots.create({
        'name': 'Test Bot',
        'workspace_id': workspace_id
    })
  2. Disable type checking for specific line

    result = client.memories.search(...)  # type: ignore

Memory Size Issues

"Memory too large" / "Payload too big"

Limit: 10KB per memory

Solutions:

  1. Check memory size

    import sys
    
    content = "Your memory content..."
    size_bytes = sys.getsizeof(content)
    size_kb = size_bytes / 1024
    
    if size_kb > 10:
        print(f"Memory too large: {size_kb:.2f}KB")
  2. Split large memories

    def split_memory(content, max_size=10000):
        """Split large content into chunks"""
        chunks = []
        while content:
            chunks.append(content[:max_size])
            content = content[max_size:]
        return chunks
    
    # Store in parts
    large_content = "..." # Your large content
    for i, chunk in enumerate(split_memory(large_content)):
        client.memories.create({
            'bot_id': bot_id,
            'content': f"Part {i+1}: {chunk}"
        })
  3. Summarize instead of storing raw data

    # ❌ Don't store huge logs
    full_log = "..." # 50KB of logs
    
    # βœ… Store summary
    summary = summarize(full_log)  # Use AI to summarize
    client.memories.create({
        'bot_id': bot_id,
        'content': summary
    })

Environment-Specific Issues

Sandbox vs Production

Issue: Data doesn't transfer between environments

This is expected! Each environment is completely isolated:

# Data in sandbox
sandbox_client = create_moa_client(environment='sandbox')
sandbox_client.memories.create(...)

# Won't appear in production
prod_client = create_moa_client(environment='production')
prod_client.memories.list()  # Won't see sandbox data

Solution: Migrate manually if needed:

# Export from sandbox
sandbox_memories = sandbox_client.memories.list({'bot_id': bot_id})

# Import to production
for mem in sandbox_memories:
    prod_client.memories.create({
        'bot_id': prod_bot_id,
        'content': mem['content']
    })

Performance Issues

Slow Searches

Symptoms: Searches taking >2 seconds

Common Causes:

  1. Large result sets

    # ❌ Fetching too many
    results = client.memories.search({
        'bot_id': bot_id,
        'query': query,
        'limit': 100  # Probably overkill
    })
    
    # βœ… Reasonable limit
    results = client.memories.search({
        'bot_id': bot_id,
        'query': query,
        'limit': 10
    })
  2. Network latency

    # Measure
    import time
    start = time.time()
    results = client.memories.search(...)
    duration = time.time() - start
    print(f"Search took {duration:.2f}s")
  3. Too many memories (thousands in one bot)

    • Consider splitting into multiple bots
    • Archive old memories

Optimization:

# Cache frequently accessed data
from functools import lru_cache

@lru_cache(maxsize=100)
def get_user_preferences(user_id):
    """Cache user preferences for 1 hour"""
    return client.memories.search({
        'bot_id': get_user_bot(user_id),
        'query': 'preferences'
    })

Getting Help

When all else fails πŸ†˜

Before Reaching Out

Gather this information:

  1. Your setup

    # Python
    pip show memofai
    python --version
    
    # JavaScript
    npm list memofai
    node --version
  2. Error message

    # Full error trace
    import traceback
    try:
        client.memories.create(...)
    except Exception as e:
        print(traceback.format_exc())
  3. Minimal reproduction

    # Simplest code that shows the problem
    from memofai import create_moa_client
    
    client = create_moa_client(api_token='moa_...')
    # ... minimal steps to reproduce

Contact Support

Community Resources

  • πŸ“š Documentation: You're here!
  • πŸ’‘ GitHub Discussions: Share ideas
  • ⭐ Examples: Check GitHub repos
  • πŸ” Search Issues: Someone might have had the same problem

Debug Mode

For deep troubleshooting πŸ”¬

Python

import logging

# Enable debug logging
logging.basicConfig(level=logging.DEBUG)

# Now all API calls will be logged
client = create_moa_client(
    api_token='moa_...',
    # debug=True  # If SDK supports it
)

JavaScript

// Enable debug mode
const client = createMoaClient({
  apiToken: 'moa_...',
  debug: true  // Logs all requests
});

// Or use environment variable
process.env.DEBUG = 'memofai:*';

Prevention Tips

Avoid problems before they happen πŸ›‘οΈ

  1. Always handle errors

    try:
        result = client.memories.create(...)
    except Exception as e:
        logger.error(f"Failed: {e}")
        # Handle gracefully
  2. Validate inputs

    def store_memory(content):
        if not content or len(content) > 10000:
            raise ValueError("Invalid content")
        return client.memories.create({...})
  3. Test in sandbox first

    # Always test with sandbox environment
    client = create_moa_client(environment='sandbox')
  4. Keep SDKs updated

    # Check for updates regularly
    pip install -U memofai
    npm update memofai
  5. Monitor your usage

    # Log all operations
    def store_with_logging(data):
        logger.info(f"Storing memory: {data}")
        result = client.memories.create(data)
        logger.info(f"Stored: {result['id']}")
        return result

Still Stuck?

We're here to help! 🀝

Remember: No question is too simple. We want to help!


Solved your problem? Great! β†’ Back to Guide | Best Practices