sickn33/agentic-awesome-skills · error

xAI API error: {err_msg}

Error message

xAI API error: {err_msg}

What it means

parse_x_response logs this when the JSON body from the xAI Responses/Agent-Tools API (POST to XAI_RESPONSES_URL with tools:[{type: x_search}]) contains a truthy top-level 'error' field. It logs error.message (or the stringified error) and returns an empty list, so the failure appears as zero X posts instead of an exception. Typical causes: invalid API key, quota/credits, unsupported or misspelled model, or x_search not available for the account/model.

Source

Thrown at skills/last30days/scripts/lib/xai_x.py:132

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


def parse_x_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Parse xAI response to extract X 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"xAI 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. Enable http.DEBUG to dump the full error body — the message identifies the code (invalid_api_key, model_not_found, rate_limit, tool_not_supported).
  2. Verify XAI_API_KEY is set, current, and the account has credits/billing active; smoke-test with a minimal request to the xAI responses endpoint.
  3. Check the --model value against xAI's current model list; fix typos or switch to a model that supports x_search.
  4. If the error cites the tool or payload shape, update the script's payload to the current xAI API version and confirm x_search availability.
  5. Treat empty output as a possible failure: check for the 'error' key and propagate it instead of reporting an empty X section.

Example fix

# before: empty list hides the failure
if "error" in response and response["error"]:
    _log_error(f"xAI API error: {err_msg}")
    return items

# after: raise a typed error for the caller
if "error" in response and response["error"]:
    raise RuntimeError(f"xAI API error: {err_msg}")
Defensive patterns

Strategy: try-catch

Validate before calling

# Validate key and model before calling the xAI API
import re

def precheck_xai(api_key: str, model: str) -> None:
    if not api_key or not re.fullmatch(r'xai-[A-Za-z0-9_-]+', api_key):
        raise ValueError('XAI_API_KEY is missing or malformed')
    if not model:
        raise ValueError('xAI model name is required')

Type guard

from typing import Any, Dict

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

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

Try / catch

if response.get("error"):
    msg = response["error"].get("message", str(response["error"]))
    if any(k in msg for k in ('rate_limit', 'quota', 'credit')):
        time.sleep(backoff)  # then retry once
    else:
        raise RuntimeError(f'xAI API error: {msg}')  # never silently return []

Prevention

When it happens

Trigger: Calling the X fetch with an invalid XAI_API_KEY bearer token (401 error body), a team out of credits (429/403), a model that does not exist or is not enabled for the key, or a payload whose x_search tool is rejected by the endpoint or API version in use. The HTTP layer returns the JSON body, the 'error' key is detected, the message is logged, and [] is returned.

Common situations: Wrong or missing XAI_API_KEY env var; xAI deprecating/renaming the configured model so every request errors in the body; x_search not enabled for the API tier; oversized prompts from wide date ranges; empty X sections in a report mistaken for 'no recent posts' during a run.

Related errors


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