Skip to main content

Error Handling

Common errors and how to handle them.

Error Response Format

All errors return JSON with status, error code, and message:
{
  "status": "error",
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message"
  }
}

HTTP Status Codes

StatusMeaning
200Success
201Created
204No Content (successful deletion)
400Bad Request (invalid params)
401Unauthorized (invalid API key/token)
404Not Found (resource missing)
422Validation Error (invalid format)
500Server Error

Common Errors

401 - Invalid API Key

Error:
{
  "status": "error",
  "error": {
    "code": "INVALID_API_KEY",
    "message": "API key is invalid or expired"
  }
}
Solution:
  1. Check API key format (should start with mk_)
  2. Verify in Moorcheh console
  3. Generate new key if needed

401 - Missing Session Token

Error:
{
  "status": "error",
  "error": {
    "code": "MISSING_SESSION_TOKEN",
    "message": "X-Session-Token header is required"
  }
}
Solution:
  1. Activate agent: POST /agents/{agent_id}/activate
  2. Get session_token from response
  3. Include in X-Session-Token header

401 - Expired Session Token

Error:
{
  "status": "error",
  "error": {
    "code": "EXPIRED_SESSION_TOKEN",
    "message": "Session token has expired"
  }
}
Solution:
# Extend current session
httpx.post(
    f"{base}/session/extend",
    params={"extend_hours": 6},
    headers={"Authorization": f"Bearer {api_key}", "X-Session-Token": token}
)

# Or activate new session
httpx.post(
    f"{base}/agents/{agent_id}/activate",
    headers={"Authorization": f"Bearer {api_key}"}
)

404 - Agent Not Found

Error:
{
  "status": "error",
  "error": {
    "code": "AGENT_NOT_FOUND",
    "message": "Agent 'xyz' not found"
  }
}
Solution:
  1. List agents: GET /agents
  2. Verify agent name
  3. Create if missing: POST /agents

422 - Validation Error

Error:
{
  "status": "error",
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "memory_type must be one of: fact, preference, decision, ..."
  }
}
Solution:
  1. Check parameter format
  2. Use valid memory types
  3. Ensure required fields present

500 - Server Error

Error:
{
  "status": "error",
  "error": {
    "code": "INTERNAL_SERVER_ERROR",
    "message": "An unexpected error occurred"
  }
}
Solution:
  1. Check MEMANTO server logs
  2. Verify Moorcheh connectivity
  3. Retry after a few seconds
  4. Contact support if persists

Error Handling Pattern

import httpx

try:
    response = httpx.post(
        f"{base}/agents/{agent_id}/remember",
        params={"content": "...", "type": "fact"},
        headers=headers
    )
    response.raise_for_status()
    result = response.json()

except httpx.HTTPStatusError as e:
    error = e.response.json()
    code = error["error"]["code"]

    if code == "MISSING_SESSION_TOKEN":
        # Activate session and retry
        activate_resp = httpx.post(
            f"{base}/agents/{agent_id}/activate",
            headers={"Authorization": f"Bearer {api_key}"}
        )
        new_token = activate_resp.json()["session_token"]
        # Retry with new token

    elif code == "INVALID_API_KEY":
        print("API key is invalid. Check configuration.")

    elif code == "AGENT_NOT_FOUND":
        print("Agent doesn't exist. Create it first.")

    else:
        print(f"Error: {code} - {error['error']['message']}")

Retry Logic

import time
import httpx

def retry_request(func, max_retries=3, delay=1):
    """Retry a request with exponential backoff."""
    for attempt in range(max_retries):
        try:
            return func()
        except httpx.HTTPStatusError as e:
            if e.response.status_code in [408, 429, 500, 502, 503]:
                if attempt < max_retries - 1:
                    time.sleep(delay * (2 ** attempt))
                    continue
            raise

# Usage
def remember():
    return httpx.post(
        f"{base}/agents/{agent_id}/remember",
        params={"content": "...", "type": "fact"},
        headers=headers
    )

response = retry_request(remember)

Debugging

Enable Verbose Logging

import httpx
import logging

logging.basicConfig(level=logging.DEBUG)

client = httpx.Client()
# Now see all HTTP details

Check Server Health

curl http://localhost:8000/health

Verify API Key

curl -X GET "http://localhost:8000/api/v2/agents" \
  -H "Authorization: Bearer mk_your_key"

Check Session Token Validity

import jwt

token = "eyJhbGc..."
payload = jwt.decode(token, options={"verify_signature": False})
print(f"Agent: {payload['agent_id']}")
print(f"Expires: {payload['expires_at']}")

Next Steps