{"record":{"id":"f14fb2c5e5bf3fc9","repo":"datawhalechina/hello-agents","slug":"llm-str-e-f14fb2","errorCode":null,"errorMessage":"LLM调用失败: {str(e)}","messagePattern":"LLM调用失败: (.+?)","errorType":"exception","errorClass":"HelloAgentsException","httpStatus":null,"severity":"error","filePath":"Co-creation-projects/YYHDBL-HelloCodeAgentCli/core/llm.py","lineNumber":296,"sourceCode":"                model=self.model,\n                messages=messages,\n                temperature=temperature if temperature is not None else self.temperature,\n                max_tokens=self.max_tokens,\n                stream=True,\n            )\n\n            # 处理流式响应\n            print(\"✅ 大语言模型响应成功:\")\n            for chunk in response:\n                content = chunk.choices[0].delta.content or \"\"\n                if content:\n                    print(content, end=\"\", flush=True)\n                    yield content\n            print()  # 在流式输出结束后换行\n\n        except Exception as e:\n            print(f\"❌ 调用LLM API时发生错误: {e}\")\n            raise HelloAgentsException(f\"LLM调用失败: {str(e)}\")\n\n    def invoke(self, messages: list[dict[str, str]], **kwargs) -> str:\n        \"\"\"\n        非流式调用LLM，返回完整响应。\n        适用于不需要流式输出的场景。\n        \"\"\"\n        try:\n            response = self._client.chat.completions.create(\n                model=self.model,\n                messages=messages,\n                temperature=kwargs.get('temperature', self.temperature),\n                max_tokens=kwargs.get('max_tokens', self.max_tokens),\n                **{k: v for k, v in kwargs.items() if k not in ['temperature', 'max_tokens']}\n            )\n            return response.choices[0].message.content\n        except Exception as e:\n            raise HelloAgentsException(f\"LLM调用失败: {str(e)}\")\n","sourceCodeStart":278,"sourceCodeEnd":314,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/YYHDBL-HelloCodeAgentCli/core/llm.py#L278-L314","documentation":"HelloAgentsException raised in LLM.think (streaming path) that wraps any exception thrown by the OpenAI SDK during a streaming chat completion — network failures, 401/403 auth errors, 429 rate limits, invalid model names, malformed messages. The original message is preserved in the string, but the exception type and the print side-effect ('❌ 调用LLM API时发生错误') mark the streaming entry point.","triggerScenarios":"Calling think()/stream_invoke() with an invalid model id; expired or wrong api_key causing 401; hitting rate limits (429); no network / DNS failure to base_url; messages list not matching the OpenAI schema.","commonSituations":"Deployments where the key rotated but .env was not updated; proxy/base_url typo; long sessions exceeding quota; streaming behind a firewall that buffers or cuts SSE connections.","solutions":["Read the embedded SDK message — it names the real cause (auth vs quota vs model).","For 401/403: refresh the API key in .env and retry.","For 429: back off and retry, or reduce request rate / max_tokens.","For connection errors: verify base_url reachability (curl) and DNS/proxy settings.","Verify the model name exists for the configured provider."],"exampleFix":"# before\nfor token in llm.think(messages):\n    print(token, end='')\n\n# after\ntry:\n    for token in llm.think(messages):\n        print(token, end='')\nexcept HelloAgentsException as e:\n    msg = str(e)\n    if '429' in msg:\n        time.sleep(5); retry()\n    elif '401' in msg:\n        raise SystemExit('bad api key')\n    else:\n        raise","handlingStrategy":"retry","validationCode":null,"typeGuard":null,"tryCatchPattern":"from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_message\n\n@retry(wait=wait_exponential(multiplier=1, max=10),\n       stop=stop_after_attempt(3),\n       retry=retry_if_exception_message(regex=r'(429|timeout|connection)'))\ndef stream(messages):\n    try:\n        return ''.join(llm.think(messages))\n    except HelloAgentsException as e:\n        if '401' in str(e) or '403' in str(e):\n            raise SystemExit('invalid api key')  # not retryable\n        raise","preventionTips":["Classify by embedded status code: 429/5xx/timeouts retry, 4xx abort.","Keep a small prompt-side budget so responses stream within limits.","Log the raw wrapped message; it carries the provider's diagnosis."],"tags":["llm","network","api","runtime"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}