hsliuping/TradingAgents-CN · critical · ValueError

❌ Alpha Vantage API Key 未配置!\n请通过以下任一方式配置:\n1. Web 后台配置(推荐):

Error message

❌ Alpha Vantage API Key 未配置!\n请通过以下任一方式配置:\n1. Web 后台配置(推荐): http://localhost:3000/api/config/datasource\n2. 设置环境变量: ALPHA_VANTAGE_API_KEY\n3. 在配置文件中配置\n获取 API Key: https://www.alphavantage.co/support/#api-key

What it means

Raised by get_api_key in the Alpha Vantage provider when no API key is found via any of its lookup steps (web backend config API, ALPHA_VANTAGE_API_KEY env var, config file). The message lists the three supported configuration channels.

Source

Thrown at tradingagents/dataflows/providers/us/alpha_vantage_common.py:131

        logger.debug(f"✅ [步骤2] .env 中找到 API Key (长度: {len(api_key)})")
        return api_key
    else:
        logger.debug("⚠️ [步骤2] .env 中未找到 API Key")

    # 3. 从配置文件获取
    logger.debug("🔍 [步骤3] 读取配置文件中的 API Key...")
    try:
        from tradingagents.config.config_manager import ConfigManager
        config_manager = ConfigManager()
        api_key = config_manager.get("ALPHA_VANTAGE_API_KEY")
        if api_key:
            logger.debug(f"✅ [步骤3] 配置文件中找到 API Key (长度: {len(api_key)})")
            return api_key
    except Exception as e:
        logger.debug(f"⚠️ [步骤3] 无法从配置文件获取 Alpha Vantage API Key: {e}")

    # 所有方式都失败
    raise ValueError(
        "❌ Alpha Vantage API Key 未配置!\n"
        "请通过以下任一方式配置:\n"
        "1. Web 后台配置(推荐): http://localhost:3000/api/config/datasource\n"
        "2. 设置环境变量: ALPHA_VANTAGE_API_KEY\n"
        "3. 在配置文件中配置\n"
        "获取 API Key: https://www.alphavantage.co/support/#api-key"
    )

    return api_key


def format_datetime_for_api(date_str: str) -> str:
    """
    格式化日期时间为 Alpha Vantage API 要求的格式
    
    Args:
        date_str: 日期字符串,格式 YYYY-MM-DD
        

View on GitHub (pinned to 74783e8817)

Solutions

  1. export ALPHA_VANTAGE_API_KEY=yourkey (get one at https://www.alphavantage.co/support/#api-key)
  2. Or set the key via the web backend: http://localhost:3000/api/config/datasource
  3. Ensure load_dotenv() ran and the env var name matches exactly
  4. If using a config file, verify it is readable and the key field is populated

Example fix

# before
quote = _get_us_quote_from_alpha_vantage('AAPL')  # ValueError
# after
os.environ['ALPHA_VANTAGE_API_KEY'] = 'XXXX'
quote = _get_us_quote_from_alpha_vantage('AAPL')
Defensive patterns

Strategy: validation

Validate before calling

import os
if not os.getenv('ALPHA_VANTAGE_API_KEY'):
    raise SystemExit('Missing ALPHA_VANTAGE_API_KEY — get one at https://www.alphavantage.co/support/#api-key')
from tradingagents.dataflows.providers.us.alpha_vantage_common import get_api_key
key = get_api_key()

Try / catch

try:
    key = get_api_key()
except ValueError as e:
    if 'API Key 未配置' in str(e):
        key = None  # route requests to a non-AV datasource
    else:
        raise

Prevention

When it happens

Trigger: Calling any Alpha Vantage helper (_get_us_quote_from_alpha_vantage, check_api_key_valid, etc.) before configuring a key, or when the env var name is misspelled and the config file path is wrong.

Common situations: First run without setup, .env not loaded, key stored under a different variable name (e.g. ALPHAVANTAGE_KEY), or config file unreadable (permissions/JSON error swallowed by the try/except).

Understand the failure class

Background: "API key is required" / "API key not found" / "No API key was set": the missing-api-key error family across 16 libraries — this error's family across 16 libraries.

Related errors


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