bytedance/deer-flow · error · Mem0AuthError

mem0 authentication failed (check the API key)

Error message

mem0 authentication failed (check the API key)

What it means

Raised as Mem0AuthError by Mem0Client._request when the mem0 server answers HTTP 401. The client authenticates with an 'Authorization: Token <key>' header, where the key comes from the environment variable named by api_key_env (default MEM0_API_KEY) via Mem0Config.resolve_api_key. A 401 means a response was received but the presented token was rejected — wrong, expired, or revoked key.

Source

Thrown at backend/packages/harness/deerflow/agents/memory/backends/mem0/client.py:51

        transport: httpx.BaseTransport | None = None,
    ) -> None:
        self._http = httpx.Client(
            base_url=base_url.rstrip("/"),
            headers={"Authorization": f"Token {api_key}", "Accept": "application/json"},
            timeout=timeout_seconds,
            transport=transport,
        )

    def close(self) -> None:
        self._http.close()

    def _request(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:
        try:
            resp = self._http.request(method, path, **kwargs)
        except httpx.HTTPError as e:
            raise Mem0APIError(f"mem0 request failed: {e}") from e
        if resp.status_code == 401:
            raise Mem0AuthError("mem0 authentication failed (check the API key)")
        if resp.status_code >= 400:
            raise Mem0APIError(f"mem0 {method} {path} -> {resp.status_code}: {resp.text[:200]}")
        if not resp.content:
            return {}
        try:
            return resp.json()
        except json.JSONDecodeError as e:
            raise Mem0APIError(f"mem0 {method} {path} returned malformed JSON: {e}") from e

    def add_memories(
        self,
        *,
        messages: list[dict[str, str]],
        user_id: str | None = None,
        agent_id: str | None = None,
        run_id: str | None = None,
    ) -> dict[str, Any]:
        """Queue extraction (async server-side; response carries an event_id)."""

View on GitHub (pinned to 1dd6ba1acb)

Solutions

  1. Verify the key: re-copy the current API key from the mem0 dashboard and set it in the env var named by api_key_env (default MEM0_API_KEY), then restart the Gateway
  2. Confirm api_key_env matches the variable actually exported in the Gateway's environment (config api_key_env vs deployed env var name)
  3. Confirm base_url matches the environment (platform vs self-hosted) the key was issued for
  4. mem0 startup_policy: fail_fast (default) runs an auth check at config load — use it so a bad key fails at boot, not mid-conversation

Example fix

# before
export MEM0_API_KEY="m0-sk-old-revoked-key"

# after
export MEM0_API_KEY="m0-sk-current-valid-key"   # re-copied from mem0 dashboard
Defensive patterns

Strategy: validation

Validate before calling

import os

def mem0_credentials_present(api_key_env: str = "MEM0_API_KEY") -> bool:
    return bool(os.environ.get(api_key_env, "").strip())

# With startup_policy: fail_fast (default), the backend performs a real auth
# check at config load — prefer that over hand-rolled checks.

Try / catch

from deerflow.agents.memory.backends.mem0.client import Mem0AuthError

try:
    client.search(query="ping", user_id=u)
except Mem0AuthError:
    alert("mem0 API key rejected — rotate MEM0_API_KEY and restart")
    raise

Prevention

When it happens

Trigger: Any Mem0Client request when the resolved API key is invalid: MEM0_API_KEY holds a stale/revoked platform key, api_key_env points at the wrong env var that happens to contain another service's key, or the key belongs to a different mem0 environment than base_url targets.

Common situations: Rotated the mem0 API key in the dashboard but did not update the env var in the Gateway process; renamed the env var in config but kept the old name deployed; copied a key from a different mem0 project/org; trailing whitespace/newline pasted into the env var value (resolve_api_key strips whitespace, but a wrong key is still wrong).

Understand the failure class

Related errors


AI-assisted analysis of bytedance/deer-flow@1dd6ba1acb (2026-08-14). Data as JSON: /api/errors/45df784fbbb99d43. Report an issue: GitHub.