Fosowl/agenticSeek · error · Exception

OpenAI API error: {str(e)}

Error message

OpenAI API error: {str(e)}

What it means

This is the catch-all wrapper in openai_fn (sources/llm_provider.py:249): every exception raised inside the try block — including the library's own 'OpenAI response is empty.' error and any OpenAI SDK exception (authentication, rate limit, bad model, timeout) — is re-raised as Exception(f"OpenAI API error: {str(e)}") with the original as __cause__. It means the chat completion call failed for a reason captured in the appended message.

Source

Thrown at sources/llm_provider.py:249

            client = OpenAI(api_key=self.api_key, base_url=f"{self.internal_url}:{port}")
        elif self.is_local:
            client = OpenAI(api_key=self.api_key, base_url=f"http://{base_url}")
        else:
            client = OpenAI(api_key=self.api_key)

        try:
            response = client.chat.completions.create(
                model=self.model,
                messages=history,
            )
            if response is None:
                raise Exception("OpenAI response is empty.")
            thought = response.choices[0].message.content
            if verbose:
                print(thought)
            return thought
        except Exception as e:
            raise Exception(f"OpenAI API error: {str(e)}") from e

    def anthropic_fn(self, history, verbose=False):
        """
        Use Anthropic to generate text.
        """
        from anthropic import Anthropic

        client = Anthropic(api_key=self.api_key)
        system_message = None
        messages = []
        for message in history:
            clean_message = {'role': message['role'], 'content': message['content']}
            if message['role'] == 'system':
                system_message = message['content']
            else:
                messages.append(clean_message)

        try:

View on GitHub (pinned to ae57a23577)

Solutions

  1. Read the wrapped str(e) to identify the root cause (401 auth, 404 model, 429 rate limit, 5xx server) and fix accordingly.
  2. Verify the API key: check that self.api_key (from config/env) is valid, active, and has billing/quota available.
  3. Validate the model name against the account's available models (GET /v1/models) and correct it in config.ini.
  4. For 429 errors, add retry with exponential backoff around the provider call.
  5. Inspect the cause chain (raise ... from e) — log e.__cause__ to see the original SDK exception with full details.
  6. If pointing at a local server, confirm the server is up and OpenAI-compatible, and that base_url/port are correct.

Example fix

// before
thought = provider.openai_fn(history)

// after
import time
for attempt in range(3):
    try:
        thought = provider.openai_fn(history)
        break
    except Exception as e:
        if '429' in str(e) and attempt < 2:
            time.sleep(2 ** attempt)
            continue
        raise
Defensive patterns

Strategy: try-catch

Validate before calling

import os, httpx

def assert_openai_ready(api_key=None, model="gpt-4o-mini"):
    key = api_key or os.environ.get("OPENAI_API_KEY")
    if not key:
        raise RuntimeError("OPENAI_API_KEY is not set")
    r = httpx.get(
        "https://api.openai.com/v1/models",
        headers={"Authorization": f"Bearer {key}"}, timeout=10,
    )
    if r.status_code == 401:
        raise RuntimeError("OpenAI API key is invalid or expired")
    r.raise_for_status()
    if model not in {m["id"] for m in r.json()["data"]}:
        raise RuntimeError(f"Model '{model}' is not available to this account")

Type guard

def is_retryable_openai_error(err: BaseException) -> bool:
    """Distinguish transient (rate limit / server) errors from permanent ones."""
    msg = str(err).lower()
    return any(tok in msg for tok in ("429", "rate limit", "503", "502", "timeout", "overloaded"))

Try / catch

import time

def openai_fn_with_retry(provider, history, retries=4):
    for attempt in range(retries):
        try:
            return provider.openai_fn(history)
        except Exception as e:
            if is_retryable_openai_error(e) and attempt < retries - 1:
                time.sleep(2 ** attempt)
                continue
            if "401" in str(e) or "auth" in str(e).lower():
                raise RuntimeError("Fix OPENAI_API_KEY (invalid/expired).") from e.__cause__
            if "404" in str(e) or "model" in str(e).lower():
                raise RuntimeError("Unknown model name; check /v1/models for your account.") from e.__cause__
            raise

Prevention

When it happens

Trigger: Any failure during client.chat.completions.create(model=self.model, messages=history): invalid/missing API key (401), unknown model name (404/not found), rate limit (429), server error (5xx), network timeout, malformed messages payload, or the internal None-response check at line 243.

Common situations: Expired or wrong OPENAI_API key passed as self.api_key; typo in model name (e.g. 'gpt-4o-mini' vs 'gpt-4-32k') or using a model not available to the account; quota/billing exhausted causing 429; local compatible server down or returning errors; messages containing roles/fields the API rejects.

Related errors


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