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

  1. Inspect what's actually returned: log response.text[:200] before .json()
  2. Bypass/whitelist alphavantage.co in the proxy or SSL-inspection layer
  3. Retry once manually — transient truncation may pass
  4. 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

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.

Related errors


AI-assisted analysis of hsliuping/TradingAgents-CN@74783e8817 (2026-08-28). Data as JSON: /api/errors/424ceadfd451f6ff. Report an issue: GitHub.