Fosowl/agenticSeek · error · ValueError

API key {api_key_var} not found in .env file. Please add it

Error message

API key {api_key_var} not found in .env file. Please add it to your .env file and restart the server.

What it means

get_api_key loads a .env file via python-dotenv, builds the variable name as f"{provider.upper()}_API_KEY" (e.g. OPENAI_API_KEY), and raises this ValueError when that environment variable is unset or empty. The library requires an API key for cloud providers before any request is made.

Source

Thrown at sources/llm_provider.py:63

        self.internal_url, self.in_docker = self.get_internal_url()
        self.unsafe_providers = ["openai", "deepseek", "dsk_deepseek", "together", "google", "openrouter", "anthropic", "minimax"]
        if self.provider_name not in self.available_providers:
            raise ValueError(f"Unknown provider: {provider_name}")
        if self.provider_name in self.unsafe_providers and self.is_local == False:
            pretty_print("Warning: you are using an API provider. You data will be sent to the cloud.", color="warning")
            self.api_key = self.get_api_key(self.provider_name)
        elif self.provider_name != "ollama":
            pretty_print(f"Provider: {provider_name} initialized at {self.server_ip}", color="success")

    def get_model_name(self) -> str:
        return self.model

    def get_api_key(self, provider):
        load_dotenv()
        api_key_var = f"{provider.upper()}_API_KEY"
        api_key = os.getenv(api_key_var)
        if not api_key:
            raise ValueError(
                f"API key {api_key_var} not found in .env file. "
                "Please add it to your .env file and restart the server."
            )
        return api_key

    def get_internal_url(self):
        load_dotenv()
        url = os.getenv("DOCKER_INTERNAL_URL")
        if not url: # running on host
            return "http://localhost", False
        return url, True

    def respond(self, history, verbose=True):
        """
        Use the choosen provider to generate text.
        """
        llm = self.available_providers[self.provider_name]
        self.logger.info(f"Using provider: {self.provider_name} at {self.server_ip}")

View on GitHub (pinned to ae57a23577)

Solutions

  1. Add the correctly named key to your .env (e.g. OPENAI_API_KEY=sk-...) and restart the server.
  2. Verify the exact expected variable name: f"{provider.upper()}_API_KEY" for your provider string.
  3. Ensure the .env file is in the current working directory where the server is launched, or pass an explicit path to load_dotenv().
  4. Check the value is non-empty (an empty OPENAI_API_KEY= line still fails).

Example fix

// before (.env)
OPEN_AI_KEY=sk-...
// after (.env)
OPENAI_API_KEY=sk-...
Defensive patterns

Strategy: validation

Validate before calling

import os
from dotenv import load_dotenv

load_dotenv()
required = f"{provider_name.upper()}_API_KEY"
if not os.getenv(required):
    raise SystemExit(f"Set {required} in your .env before starting the server.")

Type guard

def has_api_key(provider: str) -> bool:
    return bool(os.getenv(f"{provider.upper()}_API_KEY"))

Try / catch

try:
    provider = LLMProvider("openai")
except ValueError as e:
    # message names the missing {PROVIDER}_API_KEY variable
    print(e)
    sys.exit(1)

Prevention

When it happens

Trigger: Using a provider in unsafe_providers ('openai', 'deepseek', 'dsk_deepseek', 'together', 'google', 'openrouter', 'anthropic', 'minimax') while the corresponding {PROVIDER}_API_KEY is missing from .env or the process environment; an empty API_KEY line in .env (load_dotenv sets empty string -> falsy); calling get_api_key with a provider whose variable naming differs from the convention; also triggered via huggingface_fn which calls get_api_key.

Common situations: Cloning a repo without the .env (it's gitignored); .env present but not in the working directory so load_dotenv finds nothing; wrong variable name (e.g. OPEN_AI_API_KEY instead of OPENAI_API_KEY); forgetting to restart the server/shell after adding the key; dsk_deepseek expecting DSK_DEEPSEEK_API_KEY while the user set DEEPSEEK_API_KEY.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of Fosowl/agenticSeek@ae57a23577 (2026-08-30). Data as JSON: /api/errors/be000c9dfa95c86d. Report an issue: GitHub.