{"record":{"id":"424ceadfd451f6ff","repo":"hsliuping/TradingAgents-CN","slug":"failed-to-parse-alpha-vantage-api-response-e","errorCode":null,"errorMessage":"Failed to parse Alpha Vantage API response: {e}","messagePattern":"Failed to parse Alpha Vantage API response: (.+?)","errorType":"error_code","errorClass":"AlphaVantageAPIError","httpStatus":null,"severity":"error","filePath":"tradingagents/dataflows/providers/us/alpha_vantage_common.py","lineNumber":264,"sourceCode":"        except requests.exceptions.Timeout:\n            logger.warning(f\"⚠️ [Alpha Vantage] 请求超时 (尝试 {attempt + 1}/{max_retries})\")\n            if attempt < max_retries - 1:\n                time.sleep(retry_delay)\n                continue\n            else:\n                raise AlphaVantageAPIError(\"Alpha Vantage API request timeout\")\n                \n        except requests.exceptions.RequestException as e:\n            logger.error(f\"❌ [Alpha Vantage] 请求失败: {e}\")\n            if attempt < max_retries - 1:\n                time.sleep(retry_delay)\n                continue\n            else:\n                raise AlphaVantageAPIError(f\"Alpha Vantage API request failed: {e}\")\n        \n        except json.JSONDecodeError as e:\n            logger.error(f\"❌ [Alpha Vantage] JSON 解析失败: {e}\")\n            raise AlphaVantageAPIError(f\"Failed to parse Alpha Vantage API response: {e}\")\n    \n    # 所有重试都失败\n    raise AlphaVantageAPIError(f\"Failed to get data from Alpha Vantage after {max_retries} attempts\")\n\n\ndef format_response_as_string(data: Dict[str, Any], title: str = \"Alpha Vantage Data\") -> str:\n    \"\"\"\n    将 API 响应格式化为字符串\n    \n    Args:\n        data: API 响应数据\n        title: 数据标题\n        \n    Returns:\n        格式化后的字符串\n    \"\"\"\n    try:\n        # 添加头部信息","sourceCodeStart":246,"sourceCodeEnd":282,"githubUrl":"https://github.com/hsliuping/TradingAgents-CN/blob/74783e8817d6cf6de29867880631cc555153f36b/tradingagents/dataflows/providers/us/alpha_vantage_common.py#L246-L282","documentation":"Raised as AlphaVantageAPIError when the response body is not valid JSON (json.JSONDecodeError). Unlike network failures, this is not retried — it fails immediately, since a malformed payload usually means HTML error pages or captive portals.","triggerScenarios":"A proxy/firewall returning an HTML login page instead of JSON, Alpha Vantage returning an empty or truncated body under load, or response corrupted by a middleware.","commonSituations":"Captive-portal WiFi, corporate SSL inspection rewriting responses, CDN error pages (502 HTML) with 200-ish handling, or truncation on flaky links.","solutions":["Inspect what's actually returned: log response.text[:200] before .json()","Bypass/whitelist alphavantage.co in the proxy or SSL-inspection layer","Retry once manually — transient truncation may pass","If persistent, switch datasource until the network path is fixed"],"exampleFix":"# before\ndata = response.json()  # JSONDecodeError path\n# after\ntry:\n    data = response.json()\nexcept json.JSONDecodeError:\n    logger.error('Non-JSON body: %r', response.text[:200])\n    raise","handlingStrategy":"try-catch","validationCode":"# preflight: confirm the endpoint returns JSON from this network\nimport requests\nr = requests.get('https://www.alphavantage.co/query',\n                 params={'function':'GLOBAL_QUOTE','symbol':'IBM','apikey':'demo'}, timeout=10)\nr.raise_for_status()\nassert r.headers.get('content-type','').startswith('application/json'), f'non-JSON: {r.text[:100]}'","typeGuard":null,"tryCatchPattern":"from tradingagents.dataflows.providers.us.alpha_vantage_common import AlphaVantageAPIError\ntry:\n    data = _make_api_request(params)\nexcept AlphaVantageAPIError as e:\n    if 'Failed to parse' in str(e):\n        logger.error('Non-JSON response — check proxy/captive portal')\n        data = None\n    else:\n        raise","preventionTips":["Whitelist alphavantage.co in proxies/SSL inspection","Sniff content-type before parsing in your own wrappers","Retry once on decode errors — truncation can be transient"],"tags":["python","alpha-vantage","json","parsing"],"backgroundTag":"invalid-json-response","analyzedSha":"74783e8817d6cf6de29867880631cc555153f36b","analyzedAt":"2026-08-28T11:39:07.729Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}