{"record":{"id":"a9192a0b6de55615","repo":"datawhalechina/hello-agents","slug":"llm-api-key","errorCode":null,"errorMessage":"LLM_API_KEY 环境变量未设置","messagePattern":"LLM_API_KEY 环境变量未设置","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"critical","filePath":"Co-creation-projects/lcyting-StockSage-agent/agents/advisor_agent.py","lineNumber":258,"sourceCode":"\n    except Exception as e:\n        parts.append(f\"## 数据收集错误\\n{str(e)}\")\n\n    return \"\\n\\n\".join(parts) if parts else \"暂无可用数据\"\n\n\ndef _truncate(text: str, max_len: int) -> str:\n    return truncate_at_natural_boundary(text or \"\", max_len, \"...[已截断]\")\n\n\ndef _create_default_llm() -> HelloAgentsLLM:\n    model = os.getenv(\"LLM_MODEL_ID\")\n    api_key = os.getenv(\"LLM_API_KEY\")\n    base_url = os.getenv(\"LLM_BASE_URL\")\n    provider = os.getenv(\"LLM_PROVIDER\", \"auto\")\n\n    if not api_key:\n        raise RuntimeError(\"LLM_API_KEY 环境变量未设置\")\n\n    raw_timeout = int(os.getenv(\"LLM_TIMEOUT\", \"60\"))\n    buffett_timeout = max(raw_timeout, 180)\n\n    return HelloAgentsLLM(\n        model=model,\n        api_key=api_key,\n        base_url=base_url,\n        provider=provider,\n        temperature=0.4,\n        max_tokens=6144,\n        timeout=buffett_timeout,\n    )\n","sourceCodeStart":240,"sourceCodeEnd":272,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/lcyting-StockSage-agent/agents/advisor_agent.py#L240-L272","documentation":"advisor_agent's default-LLM factory raises RuntimeError when the LLM_API_KEY environment variable is missing. The agent lazily constructs its Buffett-style advisor LLM from env (LLM_MODEL_ID, LLM_API_KEY, LLM_BASE_URL, LLM_PROVIDER), and only the key is mandatory — model/base_url may default downstream.","triggerScenarios":"Instantiating the advisor agent without LLM_API_KEY exported and without passing an llm= argument; .env not loaded in the process (web server, cron, container) that runs the agent.","commonSituations":"Deploying the Streamlit/app server from a shell that lacks the env; docker exec/cron contexts dropping env; forgetting load_dotenv() in the entrypoint.","solutions":["export LLM_API_KEY=... (or add it to .env and ensure the entrypoint loads it) before starting the app.","Or inject a preconfigured llm: HelloAgentsLLM(...) into the agent so no env lookup is needed.","For containers, pass -e LLM_API_KEY or use env_file in compose.","Add a startup preflight that checks required env vars and fails with a clear message."],"exampleFix":"# before\nagent = AdvisorAgent()  # RuntimeError if env missing\n\n# after\nllm = HelloAgentsLLM(api_key=os.environ[\"LLM_API_KEY\"], ...) if os.getenv(\"LLM_API_KEY\") else None\nagent = AdvisorAgent(llm=llm) if llm else fail_fast(\"LLM_API_KEY not set\")","handlingStrategy":"validation","validationCode":"if not os.getenv(\"LLM_API_KEY\"):\n    raise SystemExit(\"LLM_API_KEY not set — add it to .env or export before starting the advisor\")\nagent = AdvisorAgent()","typeGuard":"def advisor_llm_ready() -> bool:\n    return bool(os.getenv(\"LLM_API_KEY\"))","tryCatchPattern":"try:\n    agent = AdvisorAgent()\nexcept RuntimeError as e:\n    if \"LLM_API_KEY\" in str(e):\n        agent = AdvisorAgent(llm=shared_llm)  # inject preconfigured instance\n    else:\n        raise","preventionTips":["Run one shared env preflight for all agents at app startup.","Inject a preconfigured llm instance in tests and deployments instead of relying on env.","Export env vars in the exact process that runs the agent (server, cron, container)."],"tags":["env-vars","configuration","llm-client","python"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}