sickn33/agentic-awesome-skills · error

OpenAI API error: {err_msg}

Error message

OpenAI API error: {err_msg}

What it means

parse_reddit_response logs this when the JSON body from the OpenAI Responses API (POST to OPENAI_RESPONSES_URL with the web_search tool limited to reddit.com) contains a truthy top-level 'error' field. It logs error.message (or the stringified error) and returns an empty list, so the failure appears downstream as zero Reddit items rather than an exception. Typical causes: auth, quota/billing, model access, or a rejected request payload.

Source

Thrown at skills/last30days/scripts/lib/openai_reddit.py:156

    return http.post(OPENAI_RESPONSES_URL, payload, headers=headers, timeout=timeout)


def parse_reddit_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Parse OpenAI response to extract Reddit items.

    Args:
        response: Raw API response

    Returns:
        List of item dicts
    """
    items = []

    # Check for API errors first
    if "error" in response and response["error"]:
        error = response["error"]
        err_msg = error.get("message", str(error)) if isinstance(error, dict) else str(error)
        _log_error(f"OpenAI API error: {err_msg}")
        if http.DEBUG:
            _log_error(f"Full error response: {json.dumps(response, indent=2)[:1000]}")
        return items

    # Try to find the output text
    output_text = ""
    if "output" in response:
        output = response["output"]
        if isinstance(output, str):
            output_text = output
        elif isinstance(output, list):
            for item in output:
                if isinstance(item, dict):
                    if item.get("type") == "message":
                        content = item.get("content", [])
                        for c in content:
                            if isinstance(c, dict) and c.get("type") == "output_text":
                                output_text = c.get("text", "")

View on GitHub (pinned to 58d857988f)

Solutions

  1. Run with http.DEBUG enabled to print the full error body — the message names the code (invalid_api_key, model_not_found, rate_limit_exceeded, insufficient_quota).
  2. Verify OPENAI_API_KEY: correct value, no whitespace, account active; smoke-test with a minimal curl to /v1/responses.
  3. Check the model argument: use a current Responses-API model that supports web_search; fix typos and deprecated names.
  4. If the message cites rate limits or quota, check org billing/credits, back off, and retry after the window.
  5. Because the function returns [] on error, treat empty results as suspect and surface API errors to the caller instead of silently continuing.

Example fix

# before: error swallowed; caller cannot tell 'no results' from 'API error'
if "error" in response and response["error"]:
    _log_error(f"OpenAI API error: {err_msg}")
    return items

# after: raise so the caller can retry or report
if "error" in response and response["error"]:
    raise RuntimeError(f"OpenAI API error: {err_msg}")
Defensive patterns

Strategy: try-catch

Validate before calling

# Validate key and model before calling the API
import re

def precheck_openai(api_key: str, model: str) -> None:
    if not api_key or not re.fullmatch(r'sk-[A-Za-z0-9_-]+', api_key):
        raise ValueError('OPENAI_API_KEY is missing or malformed')
    if not model or not model.startswith('gpt-'):
        raise ValueError(f'Unsupported Responses model: {model}')

Type guard

from typing import Any, Dict

def is_openai_error_response(response: Dict[str, Any]) -> bool:
    """True when the Responses API returned an error body."""
    return bool(response.get("error"))

def has_output_items(response: Dict[str, Any]) -> bool:
    return isinstance(response.get("output"), list) and len(response["output"]) > 0

Try / catch

items = parse_reddit_response(response)  # returns [] on error
# Instead, inspect the body explicitly:
if response.get("error"):
    msg = response["error"].get("message", str(response["error"]))
    if any(k in msg for k in ('rate_limit', 'quota')):
        time.sleep(backoff)  # then retry once
    else:
        raise RuntimeError(f'OpenAI API error: {msg}')  # never report empty as 'no results'

Prevention

When it happens

Trigger: Calling the Reddit fetch with an invalid/expired bearer key (401 error body), an org out of quota or with billing disabled (429/402), a model name that does not exist or lacks Responses/web_search support, or a malformed payload/oversized prompt. In each case http.post still returns a JSON body whose 'error' key triggers the log and an empty list.

Common situations: Wrong or rotated OPENAI_API_KEY in the environment; typo'd or deprecated model passed via --model; billing disabled so every call errors; using the web_search tool against a model or base URL that does not support it; empty report sections mistaken for 'no Reddit posts found' when the API actually failed.

Related errors


AI-assisted analysis of sickn33/agentic-awesome-skills@58d857988f (2026-08-26). Data as JSON: /api/errors/88f4ad458a114b69. Report an issue: GitHub.