{"record":{"id":"418cdf7d80deb597","repo":"sickn33/agentic-awesome-skills","slug":"xai-api-error-err-msg","errorCode":null,"errorMessage":"xAI API error: {err_msg}","messagePattern":"xAI API error: (.+?)","errorType":"console","errorClass":null,"httpStatus":null,"severity":"error","filePath":"skills/last30days/scripts/lib/xai_x.py","lineNumber":132,"sourceCode":"    return http.post(XAI_RESPONSES_URL, payload, headers=headers, timeout=timeout)\n\n\ndef parse_x_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:\n    \"\"\"Parse xAI response to extract X items.\n\n    Args:\n        response: Raw API response\n\n    Returns:\n        List of item dicts\n    \"\"\"\n    items = []\n\n    # Check for API errors first\n    if \"error\" in response and response[\"error\"]:\n        error = response[\"error\"]\n        err_msg = error.get(\"message\", str(error)) if isinstance(error, dict) else str(error)\n        _log_error(f\"xAI API error: {err_msg}\")\n        if http.DEBUG:\n            _log_error(f\"Full error response: {json.dumps(response, indent=2)[:1000]}\")\n        return items\n\n    # Try to find the output text\n    output_text = \"\"\n    if \"output\" in response:\n        output = response[\"output\"]\n        if isinstance(output, str):\n            output_text = output\n        elif isinstance(output, list):\n            for item in output:\n                if isinstance(item, dict):\n                    if item.get(\"type\") == \"message\":\n                        content = item.get(\"content\", [])\n                        for c in content:\n                            if isinstance(c, dict) and c.get(\"type\") == \"output_text\":\n                                output_text = c.get(\"text\", \"\")","sourceCodeStart":114,"sourceCodeEnd":150,"githubUrl":"https://github.com/sickn33/agentic-awesome-skills/blob/58d857988fcfac6986206bca2b2fe223aa437e4b/skills/last30days/scripts/lib/xai_x.py#L114-L150","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["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).","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.","Check the --model value against xAI's current model list; fix typos or switch to a model that supports x_search.","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.","Treat empty output as a possible failure: check for the 'error' key and propagate it instead of reporting an empty X section."],"exampleFix":"# before: empty list hides the failure\nif \"error\" in response and response[\"error\"]:\n    _log_error(f\"xAI API error: {err_msg}\")\n    return items\n\n# after: raise a typed error for the caller\nif \"error\" in response and response[\"error\"]:\n    raise RuntimeError(f\"xAI API error: {err_msg}\")","handlingStrategy":"try-catch","validationCode":"# Validate key and model before calling the xAI API\nimport re\n\ndef precheck_xai(api_key: str, model: str) -> None:\n    if not api_key or not re.fullmatch(r'xai-[A-Za-z0-9_-]+', api_key):\n        raise ValueError('XAI_API_KEY is missing or malformed')\n    if not model:\n        raise ValueError('xAI model name is required')","typeGuard":"from typing import Any, Dict\n\ndef is_xai_error_response(response: Dict[str, Any]) -> bool:\n    \"\"\"True when the xAI API returned an error body.\"\"\"\n    return bool(response.get(\"error\"))\n\ndef has_output_text(response: Dict[str, Any]) -> bool:\n    return isinstance(response.get(\"output\"), (str, list)) and bool(response[\"output\"])","tryCatchPattern":"if response.get(\"error\"):\n    msg = response[\"error\"].get(\"message\", str(response[\"error\"]))\n    if any(k in msg for k in ('rate_limit', 'quota', 'credit')):\n        time.sleep(backoff)  # then retry once\n    else:\n        raise RuntimeError(f'xAI API error: {msg}')  # never silently return []","preventionTips":["Verify XAI_API_KEY and remaining credits in the xAI console before long report runs.","Pin the model to a version xAI documents as supporting x_search; update when the API changes.","Enable DEBUG during development to capture full error bodies.","Check for an 'error' key before treating empty output as 'no X posts found'.","Propagate API errors to the caller so a failed source is visibly missing from the final report."],"tags":["python","xai","grok","api-error","x-search","last30days"],"backgroundTag":"llm-api-error-response","analyzedSha":"58d857988fcfac6986206bca2b2fe223aa437e4b","analyzedAt":"2026-08-26T11:55:59.350Z","schemaVersion":2},"datasetVersion":"2026-08-26T14:46:13.012Z"}