hsliuping/TradingAgents-CN · critical · ValueError

QIANFAN_API_KEY格式错误,应为: bce-v3/ALTAK-xxx/xxx

Error message

QIANFAN_API_KEY格式错误,应为: bce-v3/ALTAK-xxx/xxx

What it means

The Qianfan branch of OpenAICompatibleBase.__init__ raises this when a key IS present but does not start with the required 'bce-v3/' prefix. Baidu Qianfan API keys are composite tokens whose format encodes the version, key id, and secret; anything else (an AK, a random string, or whitespace-padded values after prefix check) is rejected before the client is built.

Source

Thrown at tradingagents/llm_adapters/openai_compatible_base.py:290

                    return True

            env_api_key = os.getenv('QIANFAN_API_KEY')
            if env_api_key and is_valid_api_key(env_api_key):
                qianfan_api_key = env_api_key
            else:
                qianfan_api_key = None
        else:
            qianfan_api_key = api_key

        if not qianfan_api_key:
            raise ValueError(
                "千帆模型需要配置 API Key。"
                "请在 Web 界面配置 (设置 -> 大模型厂家) 或设置 QIANFAN_API_KEY 环境变量,"
                "格式为: bce-v3/ALTAK-xxx/xxx"
            )

        if not qianfan_api_key.startswith('bce-v3/'):
            raise ValueError(
                "QIANFAN_API_KEY格式错误,应为: bce-v3/ALTAK-xxx/xxx"
            )
        
        super().__init__(
            provider_name="qianfan",
            model=model,
            api_key_env_var="QIANFAN_API_KEY",
            base_url="https://qianfan.baidubce.com/v2",
            api_key=qianfan_api_key,
            temperature=temperature,
            max_tokens=max_tokens,
            **kwargs
        )
    
    def _estimate_tokens(self, text: str) -> int:
        """估算文本的token数量(千帆模型专用)"""
        # 千帆模型的token估算:中文约1.5字符/token,英文约4字符/token
        # 保守估算:2字符/token

View on GitHub (pinned to 74783e8817)

Solutions

  1. Regenerate/copy the API key from Qianfan console ensuring it starts with bce-v3/ and export the full string
  2. Strip stray quotes/whitespace: export QIANFAN_API_KEY=$(printf '%s' "$RAW") or verify with startswith('bce-v3/')
  3. If authenticating with AK/SK instead, use the official Qianfan SDK rather than this OpenAI-compatible adapter

Example fix

# before
# export QIANFAN_API_KEY='ALTAK-nnn'   # wrong: missing bce-v3/ prefix
llm = create_llm_client(provider="qianfan", model="ernie-4.0")

# after
# export QIANFAN_API_KEY='bce-v3/ALTAK-nnn/sss'
llm = create_llm_client(provider="qianfan", model="ernie-4.0")
Defensive patterns

Strategy: type-guard

Validate before calling

import os
k = (api_key or os.getenv("QIANFAN_API_KEY") or '').strip()
if not k.startswith("bce-v3/"):
    raise SystemExit("QIANFAN_API_KEY must look like bce-v3/ALTAK-xxx/xxx")

Type guard

def is_valid_qianfan_key(k: str | None) -> bool:
    k = (k or '').strip()
    return k.startswith("bce-v3/") and k.count('/') >= 3 and len(k) > len("bce-v3/")

Try / catch

try:
    llm = create_llm_client(provider="qianfan", model=m)
except ValueError as e:
    if "格式错误" in str(e):
        raise SystemExit("Re-copy the full bce-v3 key from the Qianfan console") from e
    raise

Prevention

When it happens

Trigger: QIANFAN_API_KEY set to a legacy AccessKey, an OpenAI-style sk- key, or a value with leading whitespace/quotes that breaks the prefix check — the format guard fires right after the presence check.

Common situations: Pasting a Qianfan AK instead of a bce-v3 API key; shell quoting artifacts (quotes included in the exported value); using an OAuth token from another Baidu product; truncated key from manual copy.

Related errors


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