datawhalechina/hello-agents · error · HelloAgentsException

LLM调用失败: {str(e)}

Error message

LLM调用失败: {str(e)}

What it means

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.

Source

Thrown at Co-creation-projects/YYHDBL-HelloCodeAgentCli/core/llm.py:296

                model=self.model,
                messages=messages,
                temperature=temperature if temperature is not None else self.temperature,
                max_tokens=self.max_tokens,
                stream=True,
            )

            # 处理流式响应
            print("✅ 大语言模型响应成功:")
            for chunk in response:
                content = chunk.choices[0].delta.content or ""
                if content:
                    print(content, end="", flush=True)
                    yield content
            print()  # 在流式输出结束后换行

        except Exception as e:
            print(f"❌ 调用LLM API时发生错误: {e}")
            raise HelloAgentsException(f"LLM调用失败: {str(e)}")

    def invoke(self, messages: list[dict[str, str]], **kwargs) -> str:
        """
        非流式调用LLM,返回完整响应。
        适用于不需要流式输出的场景。
        """
        try:
            response = self._client.chat.completions.create(
                model=self.model,
                messages=messages,
                temperature=kwargs.get('temperature', self.temperature),
                max_tokens=kwargs.get('max_tokens', self.max_tokens),
                **{k: v for k, v in kwargs.items() if k not in ['temperature', 'max_tokens']}
            )
            return response.choices[0].message.content
        except Exception as e:
            raise HelloAgentsException(f"LLM调用失败: {str(e)}")

View on GitHub (pinned to 606a07d341)

Solutions

  1. Read the embedded SDK message — it names the real cause (auth vs quota vs model).
  2. For 401/403: refresh the API key in .env and retry.
  3. For 429: back off and retry, or reduce request rate / max_tokens.
  4. For connection errors: verify base_url reachability (curl) and DNS/proxy settings.
  5. Verify the model name exists for the configured provider.

Example fix

# before
for token in llm.think(messages):
    print(token, end='')

# after
try:
    for token in llm.think(messages):
        print(token, end='')
except HelloAgentsException as e:
    msg = str(e)
    if '429' in msg:
        time.sleep(5); retry()
    elif '401' in msg:
        raise SystemExit('bad api key')
    else:
        raise
Defensive patterns

Strategy: retry

Try / catch

from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_message

@retry(wait=wait_exponential(multiplier=1, max=10),
       stop=stop_after_attempt(3),
       retry=retry_if_exception_message(regex=r'(429|timeout|connection)'))
def stream(messages):
    try:
        return ''.join(llm.think(messages))
    except HelloAgentsException as e:
        if '401' in str(e) or '403' in str(e):
            raise SystemExit('invalid api key')  # not retryable
        raise

Prevention

When it happens

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

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

Related errors


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