{"record":{"id":"11596c84203c0e4b","repo":"datawhalechina/hello-agents","slug":"env-llm-model-id-llm-api-key-llm-base-ur","errorCode":null,"errorMessage":"请在 .env 中配置 LLM_MODEL_ID, LLM_API_KEY, LLM_BASE_URL","messagePattern":"请在 \\.env 中配置 LLM_MODEL_ID, LLM_API_KEY, LLM_BASE_URL","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"critical","filePath":"Co-creation-projects/CC1227871-StockInsightAgent/llm_client.py","lineNumber":19,"sourceCode":"\"\"\"Step 1: LLM 客户端 — 兼容 OpenAI 接口，支持流式响应\"\"\"\nimport os\nfrom openai import OpenAI\nfrom dotenv import load_dotenv\nfrom typing import List, Dict\n\nload_dotenv()\n\n\nclass HelloAgentsLLM:\n    def __init__(self, model: str = None, apiKey: str = None,\n                 baseUrl: str = None, timeout: int = None):\n        self.model = model or os.getenv(\"LLM_MODEL_ID\")\n        apiKey = apiKey or os.getenv(\"LLM_API_KEY\")\n        baseUrl = baseUrl or os.getenv(\"LLM_BASE_URL\")\n        timeout = timeout or int(os.getenv(\"LLM_TIMEOUT\", 60))\n\n        if not all([self.model, apiKey, baseUrl]):\n            raise ValueError(\"请在 .env 中配置 LLM_MODEL_ID, LLM_API_KEY, LLM_BASE_URL\")\n\n        self.client = OpenAI(api_key=apiKey, base_url=baseUrl, timeout=timeout)\n\n    def think(self, messages: List[Dict[str, str]], temperature: float = 0) -> str:\n        print(f\"\\n[{self.model}] 思考中...\")\n        try:\n            response = self.client.chat.completions.create(\n                model=self.model, messages=messages,\n                temperature=temperature, stream=True,\n            )\n            collected = []\n            for chunk in response:\n                if not chunk.choices:\n                    continue\n                content = chunk.choices[0].delta.content or \"\"\n                # 过滤无效代理字符 (surrogates)\n                clean = content.encode(\"utf-8\", errors=\"surrogateescape\").decode(\"utf-8\", errors=\"replace\")\n                print(clean, end=\"\", flush=True)","sourceCodeStart":1,"sourceCodeEnd":37,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/CC1227871-StockInsightAgent/llm_client.py#L1-L37","documentation":"HelloAgentsLLM.__init__ raises ValueError when any of model id, API key, or base URL is missing after checking constructor args and the LLM_MODEL_ID / LLM_API_KEY / LLM_BASE_URL environment variables (loaded via python-dotenv from .env). It is a startup-time configuration guard: the OpenAI client cannot be constructed meaningfully without all three.","triggerScenarios":"Instantiating HelloAgentsLLM() with no .env file in the working directory, a .env missing one of the three variables, or a variable set to an empty string (falsy). Note load_dotenv() only fills vars not already in the environment and depends on cwd for .env discovery.","commonSituations":"Fresh clone without copying .env.example; running from a different directory so the .env is not found; CI/containers where the env file was not copied into the image; typo'd variable names (e.g. LLM_MODEL instead of LLM_MODEL_ID).","solutions":["Create a .env next to the project root / the directory you run from, defining LLM_MODEL_ID, LLM_API_KEY and LLM_BASE_URL.","Or export the three variables in the shell/container environment before starting the app.","Alternatively pass them explicitly: HelloAgentsLLM(model='...', apiKey='...', baseUrl='...').","Verify with: python -c \"import os; from dotenv import load_dotenv; load_dotenv(); print([k for k in ('LLM_MODEL_ID','LLM_API_KEY','LLM_BASE_URL') if not os.getenv(k)])\" — an empty list means fixed."],"exampleFix":"# before: no .env\nclient = HelloAgentsLLM()  # ValueError\n\n# after: .env contains\n# LLM_MODEL_ID=gpt-4o-mini\n# LLM_API_KEY=sk-...\n# LLM_BASE_URL=https://api.openai.com/v1\nclient = HelloAgentsLLM()","handlingStrategy":"validation","validationCode":"import os\nfrom dotenv import load_dotenv\nload_dotenv()\nmissing = [k for k in ('LLM_MODEL_ID', 'LLM_API_KEY', 'LLM_BASE_URL') if not os.getenv(k)]\nassert not missing, f'missing env vars: {missing}'\nclient = HelloAgentsLLM()","typeGuard":null,"tryCatchPattern":"try:\n    client = HelloAgentsLLM()\nexcept ValueError as e:\n    if 'LLM_MODEL_ID' in str(e):\n        sys.exit('Configuration incomplete: create .env with LLM_MODEL_ID, LLM_API_KEY, LLM_BASE_URL')","preventionTips":["Ship a .env.example and document the three required variables.","Run the missing-vars check above at process start (fail fast before any work begins).","In containers, inject the three variables as environment variables instead of relying on .env discovery from cwd."],"tags":["config","env","llm-client","startup"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}