mem0ai/mem0 · error · ValueError

Either api_key or user/password must be provided

Error message

Either api_key or user/password must be provided

What it means

Raised by the Elasticsearch config auth validator when no authentication material is present. It accepts either an api_key or the user/password pair; with neither, the config cannot authenticate to the cluster and Pydantic raises during construction.

Source

Thrown at mem0/configs/vector_stores/elasticsearch.py:34

    verify_certs: bool = Field(True, description="Verify SSL certificates")
    ca_certs: Optional[str] = Field(None, description="Path to CA bundle for SSL certificate verification")
    use_ssl: bool = Field(True, description="Use SSL for connection")
    auto_create_index: bool = Field(True, description="Automatically create index during initialization")
    custom_search_query: Optional[Callable[[List[float], int, Optional[Dict]], Dict]] = Field(
        None, description="Custom search query function. Parameters: (query, top_k, filters) -> Dict"
    )
    headers: Optional[Dict[str, str]] = Field(None, description="Custom headers to include in requests")

    @model_validator(mode="before")
    @classmethod
    def validate_auth(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        # Check if either cloud_id or host/port is provided
        if not values.get("cloud_id") and not values.get("host"):
            raise ValueError("Either cloud_id or host must be provided")

        # Check if authentication is provided
        if not any([values.get("api_key"), (values.get("user") and values.get("password"))]):
            raise ValueError("Either api_key or user/password must be provided")

        return values

    @model_validator(mode="before")
    @classmethod
    def validate_headers(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        """Validate headers format and content"""
        headers = values.get("headers")
        if headers is not None:
            # Check if headers is a dictionary
            if not isinstance(headers, dict):
                raise ValueError("headers must be a dictionary")
            
            # Check if all keys and values are strings
            for key, value in headers.items():
                if not isinstance(key, str) or not isinstance(value, str):
                    raise ValueError("All header keys and values must be strings")
        

View on GitHub (pinned to 001c235229)

Solutions

  1. Set 'api_key' (Elastic Cloud-encoded api key) in the config
  2. Or set both 'user' and 'password' (basic auth), e.g. user='elastic', password from your secret store
  3. Confirm both members of the pair are non-empty; a lone username does not pass
  4. Load and assert secrets resolve to non-None values before constructing the config

Example fix

# before
ElasticsearchConfig(host="http://localhost:9200")

# after
ElasticsearchConfig(host="http://localhost:9200", user="elastic", password=os.environ["ES_PASSWORD"])
Defensive patterns

Strategy: validation

Validate before calling

def validate_es_auth(cfg: dict) -> None:
    if not (cfg.get("api_key") or (cfg.get("user") and cfg.get("password"))):
        raise RuntimeError("Elasticsearch config needs api_key or user+password")

Type guard

def es_auth_ok(cfg: dict) -> bool:
    return bool(cfg.get("api_key") or (cfg.get("user") and cfg.get("password")))

Try / catch

from pydantic import ValidationError
try:
    ElasticsearchConfig(**cfg)
except ValidationError as e:
    if "api_key or user/password" in str(e):
        # resolve the missing credential from the secret store, then retry
        ...

Prevention

When it happens

Trigger: Creating ElasticsearchConfig with cloud_id or host set but api_key missing AND user/password missing (or only one of user/password supplied — the pair must be truthy together).

Common situations: Local dev against an open ES cluster that later gets security enabled; api_key stored in a vault call that silently returned None; providing user but empty password after a config templating pass; using an encoded api_key tuple where a string key is expected.

Related errors


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