mem0ai/mem0 · error · ValueError

Either 'api_key' must be provided or TURBOPUFFER_API_KEY env

Error message

Either 'api_key' must be provided or TURBOPUFFER_API_KEY environment variable must be set.

What it means

TurbopufferConfig's `before` validator requires either a non-empty 'api_key' in the config or the environment variable TURBOPUFFER_API_KEY to be set. Because it runs before field defaults, an omitted/None/empty api_key with no env var raises this ValueError at Memory construction time.

Source

Thrown at mem0/configs/vector_stores/turbopuffer.py:27

    embedding_model_dims: int = Field(1536, description="Dimensions of the embedding model")
    api_key: Optional[str] = Field(None, description="API key for Turbopuffer")
    region: str = Field("gcp-us-central1", description="Turbopuffer region (e.g., 'gcp-us-central1', 'aws-us-west-2')")
    distance_metric: str = Field(
        "cosine_distance",
        description="Distance metric for vector similarity ('cosine_distance' or 'euclidean_squared')",
    )
    batch_size: int = Field(100, description="Batch size for bulk operations")
    extra_params: Optional[Dict[str, Any]] = Field(
        None,
        description="Additional parameters for Turbopuffer client",
    )

    @model_validator(mode="before")
    @classmethod
    def check_api_key(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        api_key = values.get("api_key")
        if not api_key and "TURBOPUFFER_API_KEY" not in os.environ:
            raise ValueError(
                "Either 'api_key' must be provided or TURBOPUFFER_API_KEY environment variable must be set."
            )
        return values

    @model_validator(mode="before")
    @classmethod
    def validate_extra_fields(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        allowed_fields = set(cls.model_fields.keys())
        input_fields = set(values.keys())
        extra_fields = input_fields - allowed_fields
        if extra_fields:
            raise ValueError(
                f"Extra fields not allowed: {', '.join(extra_fields)}. "
                f"Please input only the following fields: {', '.join(allowed_fields)}"
            )
        return values

    model_config = ConfigDict(arbitrary_types_allowed=True)

View on GitHub (pinned to 001c235229)

Solutions

  1. Set TURBOPUFFER_API_KEY in the environment the process actually runs in (export it, add to .env loaded before import, or Docker ENV)
  2. Or pass the key explicitly: vector_store={'provider': 'turbopuffer', 'config': {'api_key': '...'}}
  3. Verify with a quick check (python -c "import os; print(os.environ.get('TURBOPUFFER_API_KEY'))") in the same environment that runs the app

Example fix

# before
os.environ.pop("TURBOPUFFER_API_KEY", None)
config = {}

# after
config = {"api_key": "tpuf_..."}  # or: os.environ["TURBOPUFFER_API_KEY"] = "tpuf_..."
Defensive patterns

Strategy: validation

Validate before calling

import os
if not cfg.get("api_key") and not os.environ.get("TURBOPUFFER_API_KEY"):
    raise ConfigError("Provide api_key or set TURBOPUFFER_API_KEY")

Try / catch

try:
    memory = Memory(config=full_config)
except ValueError as e:
    if "TURBOPUFFER_API_KEY" in str(e):
        os.environ["TURBOPUFFER_API_KEY"] = load_secret("turbopuffer")
        memory = Memory(config=full_config)
    else:
        raise

Prevention

When it happens

Trigger: Memory(vector_store={'provider': 'turbopuffer'}) with no api_key while TURBOPUFFER_API_KEY is unset in the process; passing api_key=None or api_key=''; running under a service (systemd, Docker, cron) where the env var was set in the shell but not exported into the service environment.

Common situations: Setting the env var in ~/.bashrc but launching the app from an IDE or Docker where it is absent; rotating/renaming the variable name; assuming mem0 reads TURBOPUFFER_KEY or another spelling.

Related errors


AI-assisted analysis of mem0ai/mem0@001c235229 (2026-08-15). Data as JSON: /api/errors/5892063ad2ba671b. Report an issue: GitHub.