datawhalechina/hello-agents · error · AgentException

LLM思考失败: {str(e)}

Error message

LLM思考失败: {str(e)}

What it means

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.

Source

Thrown at Co-creation-projects/Apricity-InnocoreAI/agents/base.py:118

                full_prompt += f"\n\n历史记录:\n{history_str}"
            
            # 调用 HelloAgent LLM
            response = await asyncio.wait_for(
                self.llm.ainvoke(full_prompt),
                timeout=self.timeout
            )
            
            response_text = response.content if hasattr(response, 'content') else str(response)
            
            self._add_to_history(f"LLM prompt: {prompt}")
            self._add_to_history(f"LLM response: {response_text}")
            
            return response_text
            
        except asyncio.TimeoutError:
            raise TimeoutException("LLM思考超时")
        except Exception as e:
            raise AgentException(f"LLM思考失败: {str(e)}")
    
    def _add_to_history(self, message: str):
        """添加到历史记录"""
        timestamp = datetime.now().isoformat()
        self.history.append(f"[{timestamp}] {message}")
        
        # 限制历史记录长度
        if len(self.history) > 100:
            self.history = self.history[-50:]
    
    def get_history(self, limit: int = 10) -> List[str]:
        """获取历史记录"""
        return self.history[-limit:]
    
    def clear_history(self):
        """清空历史记录"""
        self.history = []
    

View on GitHub (pinned to 606a07d341)

Solutions

  1. Inspect the suffix after 'LLM思考失败:' — it names the provider error; fix that first (key, model name, quota).
  2. Verify environment: echo $OPENAI_API_KEY set, model id exists for your account, base_url reachable (curl the /models endpoint).
  3. Pin compatible langchain/langchain-core versions and re-test a one-line ainvoke in isolation.
  4. Handle provider rate limits with exponential backoff retry around ainvoke.
  5. Split the single except into typed branches (RateLimitError -> retry, AuthenticationError -> fail fast) to keep behavior explicit.

Example fix

# before
except Exception as e:
    raise AgentException(f"LLM思考失败: {str(e)}")

# after — typed handling with cause chaining
except RateLimitError:
    await asyncio.sleep(5)
    return await self.think(prompt, context)  # bounded by agent loop
except Exception as e:
    raise AgentException(f"LLM思考失败: {e}") from e
Defensive patterns

Strategy: try-catch

Validate before calling

# Pre-flight the LLM endpoint before running the agent
async def llm_reachable(llm) -> bool:
    try:
        await asyncio.wait_for(llm.ainvoke('ping'), timeout=15)
        return True
    except Exception:
        return False

Try / catch

try:
    answer = await agent.think(prompt, context)
except AgentException as e:
    msg = str(e)
    if 'rate' in msg.lower():
        await asyncio.sleep(20); return await agent.think(prompt, context)
    if 'auth' in msg.lower() or 'api key' in msg.lower():
        raise RuntimeError('LLM API key invalid — check .env')  # fail fast
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14). Data as JSON: /api/errors/3499996776afe764. Report an issue: GitHub.