hsliuping/TradingAgents-CN · error · AlphaVantageAPIError
Failed to parse Alpha Vantage API response: {e}
Error message
Failed to parse Alpha Vantage API response: {e} What it means
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.
Source
Thrown at tradingagents/dataflows/providers/us/alpha_vantage_common.py:264
except requests.exceptions.Timeout:
logger.warning(f"⚠️ [Alpha Vantage] 请求超时 (尝试 {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
time.sleep(retry_delay)
continue
else:
raise AlphaVantageAPIError("Alpha Vantage API request timeout")
except requests.exceptions.RequestException as e:
logger.error(f"❌ [Alpha Vantage] 请求失败: {e}")
if attempt < max_retries - 1:
time.sleep(retry_delay)
continue
else:
raise AlphaVantageAPIError(f"Alpha Vantage API request failed: {e}")
except json.JSONDecodeError as e:
logger.error(f"❌ [Alpha Vantage] JSON 解析失败: {e}")
raise AlphaVantageAPIError(f"Failed to parse Alpha Vantage API response: {e}")
# 所有重试都失败
raise AlphaVantageAPIError(f"Failed to get data from Alpha Vantage after {max_retries} attempts")
def format_response_as_string(data: Dict[str, Any], title: str = "Alpha Vantage Data") -> str:
"""
将 API 响应格式化为字符串
Args:
data: API 响应数据
title: 数据标题
Returns:
格式化后的字符串
"""
try:
# 添加头部信息View on GitHub (pinned to 74783e8817)
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
Example fix
# before
data = response.json() # JSONDecodeError path
# after
try:
data = response.json()
except json.JSONDecodeError:
logger.error('Non-JSON body: %r', response.text[:200])
raise Defensive patterns
Strategy: try-catch
Validate before calling
# preflight: confirm the endpoint returns JSON from this network
import requests
r = requests.get('https://www.alphavantage.co/query',
params={'function':'GLOBAL_QUOTE','symbol':'IBM','apikey':'demo'}, timeout=10)
r.raise_for_status()
assert r.headers.get('content-type','').startswith('application/json'), f'non-JSON: {r.text[:100]}' Try / catch
from tradingagents.dataflows.providers.us.alpha_vantage_common import AlphaVantageAPIError
try:
data = _make_api_request(params)
except AlphaVantageAPIError as e:
if 'Failed to parse' in str(e):
logger.error('Non-JSON response — check proxy/captive portal')
data = None
else:
raise Prevention
- 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
When it happens
Trigger: 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.
Common situations: Captive-portal WiFi, corporate SSL inspection rewriting responses, CDN error pages (502 HTML) with 200-ish handling, or truncation on flaky links.
Understand the failure class
Background: "Invalid JSON response" and "Failed to parse response" errors: when an API answers 200 but the body isn't the JSON your library expected — this error's family across 28 libraries.
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- ❌ Alpha Vantage API Key 未配置!\n请通过以下任一方式配置:\n1. Web 后台配置(推荐):
- Alpha Vantage API Error: {error_msg}
- Alpha Vantage API rate limit exceeded. Please wait a moment
- Alpha Vantage API limit: {info_msg}
- Alpha Vantage API request timeout
AI-assisted analysis of hsliuping/TradingAgents-CN@74783e8817 (2026-08-28).
Data as JSON: /api/errors/424ceadfd451f6ff.
Report an issue: GitHub.