{"record":{"id":"3499996776afe764","repo":"datawhalechina/hello-agents","slug":"llm-str-e","errorCode":null,"errorMessage":"LLM思考失败: {str(e)}","messagePattern":"LLM思考失败: (.+?)","errorType":"exception","errorClass":"AgentException","httpStatus":500,"severity":"error","filePath":"Co-creation-projects/Apricity-InnocoreAI/agents/base.py","lineNumber":118,"sourceCode":"                full_prompt += f\"\\n\\n历史记录:\\n{history_str}\"\n            \n            # 调用 HelloAgent LLM\n            response = await asyncio.wait_for(\n                self.llm.ainvoke(full_prompt),\n                timeout=self.timeout\n            )\n            \n            response_text = response.content if hasattr(response, 'content') else str(response)\n            \n            self._add_to_history(f\"LLM prompt: {prompt}\")\n            self._add_to_history(f\"LLM response: {response_text}\")\n            \n            return response_text\n            \n        except asyncio.TimeoutError:\n            raise TimeoutException(\"LLM思考超时\")\n        except Exception as e:\n            raise AgentException(f\"LLM思考失败: {str(e)}\")\n    \n    def _add_to_history(self, message: str):\n        \"\"\"添加到历史记录\"\"\"\n        timestamp = datetime.now().isoformat()\n        self.history.append(f\"[{timestamp}] {message}\")\n        \n        # 限制历史记录长度\n        if len(self.history) > 100:\n            self.history = self.history[-50:]\n    \n    def get_history(self, limit: int = 10) -> List[str]:\n        \"\"\"获取历史记录\"\"\"\n        return self.history[-limit:]\n    \n    def clear_history(self):\n        \"\"\"清空历史记录\"\"\"\n        self.history = []\n    ","sourceCodeStart":100,"sourceCodeEnd":136,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/Apricity-InnocoreAI/agents/base.py#L100-L136","documentation":"Catch-all AgentException from BaseAgent.think for any non-timeout failure of the LLM call. The original message is appended, and typical roots are authentication errors (invalid OPENAI_API_KEY), model-not-found (wrong model name), provider 429 rate limits, or response objects lacking .content. Because response.content is read via hasattr/str, schema mismatches with the installed langchain-core version also surface here.","triggerScenarios":"ainvoke raising AuthenticationError/NotFoundError/RateLimitError from the provider; ChatOpenAI constructed with a model name the key has no access to; langchain version bump changing AIMessage internals so hasattr(response,'content') falls to str(response); base_url pointing at a dead local inference server.","commonSituations":"API key missing from .env in a fresh clone; free-tier keys hitting RPM limits during batch paper analysis; model deprecated by provider; mixing langchain/langchain-core versions.","solutions":["Inspect the suffix after 'LLM思考失败:' — it names the provider error; fix that first (key, model name, quota).","Verify environment: echo $OPENAI_API_KEY set, model id exists for your account, base_url reachable (curl the /models endpoint).","Pin compatible langchain/langchain-core versions and re-test a one-line ainvoke in isolation.","Handle provider rate limits with exponential backoff retry around ainvoke.","Split the single except into typed branches (RateLimitError -> retry, AuthenticationError -> fail fast) to keep behavior explicit."],"exampleFix":"# before\nexcept Exception as e:\n    raise AgentException(f\"LLM思考失败: {str(e)}\")\n\n# after — typed handling with cause chaining\nexcept RateLimitError:\n    await asyncio.sleep(5)\n    return await self.think(prompt, context)  # bounded by agent loop\nexcept Exception as e:\n    raise AgentException(f\"LLM思考失败: {e}\") from e","handlingStrategy":"try-catch","validationCode":"# Pre-flight the LLM endpoint before running the agent\nasync def llm_reachable(llm) -> bool:\n    try:\n        await asyncio.wait_for(llm.ainvoke('ping'), timeout=15)\n        return True\n    except Exception:\n        return False","typeGuard":null,"tryCatchPattern":"try:\n    answer = await agent.think(prompt, context)\nexcept AgentException as e:\n    msg = str(e)\n    if 'rate' in msg.lower():\n        await asyncio.sleep(20); return await agent.think(prompt, context)\n    if 'auth' in msg.lower() or 'api key' in msg.lower():\n        raise RuntimeError('LLM API key invalid — check .env')  # fail fast\n    raise","preventionTips":["Verify API key, model name, and base_url with a one-line ainvoke before long runs.","Pin langchain/langchain-core versions to avoid response-shape drift.","Keep provider errors typed by re-raising rather than string-wrapping them."],"tags":["python","llm","error-wrapping","auth","rate-limit"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}