AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug]当 LLM API 请求超时时,`on_llm_response` 钩子不会被调用,导致插件无法捕获超时异常并进行处理(如自动切换模型)

Open DDZS987 opened this issue 1 year ago • 0 comments

发生了什么

在开发 LLM 模型自动切换插件时,发现当 LLM API 请求发生超时异常时,on_llm_response 钩子不会被调用,导致插件完全无法感知到超时发生,也就无法进行后续处理(如自动切换到备用模型、重试等)。

核心问题:异常在 llm_request.py 的 except Exception 中被捕获后,直接返回错误消息给用户,但没有触发 on_agent_done 事件,因此 on_llm_response 钩子不会被调用。

代码位置:astrbot/core/pipeline/process_stage/method/llm_request.py 第 343 行左右

except Exception as e:
    logger.error(f"发生了错误。Provider 配置如下: {provider.meta().__dict__}")
    logger.error(traceback.format_exc())
    
    # ❌ 这里直接返回错误消息,没有调用 on_agent_done
    return self.context.make_message_chain().message(
        f"AstrBot 请求失败。\n错误类型: {type(e).__name__}\n错误信息: {str(e)}\n\n请在控制台查看和分享错误详情。"
    )

对比正常流程(第 272-278 行):

# 只有正常响应时才会走这里,触发 on_llm_response 钩子
await self.context.event_bus.send_message_event(
    event_id=event_id,
    event_name="on_agent_done",
    chain=llm_response,
    ...
)

如何复现?

  1. 开发一个使用 @filter.on_llm_response() 钩子的插件:

    @filter.on_llm_response()
    async def on_llm_response(self, event, resp):
        logger.info("✅ 钩子被调用")
        # 这里可以检测响应并进行处理
    
  2. 配置一个超时时间较短的 LLM Provider(例如 10 秒)

  3. 发送一个需要长时间处理的复杂请求,等待超时发生

  4. 观察日志:

    • ✅ 可以看到核心代码的错误日志:openai.APITimeoutError: Request timed out.
    • ❌ 看不到插件的日志:✅ 钩子被调用
  5. 结论:on_llm_response 钩子在超时时不会被调用

AstrBot 版本、部署方式(如 Windows Docker Desktop 部署)、使用的提供商、使用的消息平台适配器

  • AstrBot 版本:v4.5.6
  • 部署方式:Linux 原生部署
  • 使用的提供商:OpenAI Compatible API(使用 openai_chat_completion 类型)
  • 使用的消息平台:Telegram

操作系统

Linux

报错日志

场景 1:正常响应(钩子被调用)✅

[01:23:44] [Plug] [INFO] [astrbot_plugin_llm_model_switcher.main:565]: 
    ⏱️ [超时监控] 请求已完成,已取消监控任务,模型: xxx

→ on_llm_response 被调用,插件正常工作


场景 2:超时异常(钩子未调用)❌

[01:30:45] [Core] [ERRO] [sources.openai_source:384]: 发生了错误。Provider 配置如下: {'id': 'openai', 'provider': 'openai', 'type': 'openai_chat_completion', 'provider_type': 'chat_completion', 'enable': True, 'key': ['sk-...'], 'api_base': 'https://iai.iisbo.com/v1', 'timeout': 60, 'model_config': {'model': '[bo]gemini-2.5-pro-09-25-1', 'temperature': 0.5}, 'custom_extra_body': {}, 'modalities': ['text', 'image'], 'hint': '也兼容所有与 OpenAI API 兼容的服务。'} 

[01:30:45] [Core] [ERRO] [method.llm_request:344]: Traceback (most recent call last):
  File "/home/AstrBot/.venv/lib/python3.10/site-packages/httpx/_transports/default.py", line 101, in map_httpcore_exceptions
    yield
  ...
  File "/home/AstrBot/.venv/lib/python3.10/site-packages/httpcore/_exceptions.py", line 14, in map_exceptions
    raise to_exc(exc) from exc
httpcore.ReadTimeout

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/AstrBot/.venv/lib/python3.10/site-packages/openai/_base_client.py", line 1529, in request
    response = await self._client.send(
  ...
httpx.ReadTimeout

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/AstrBot/astrbot/core/pipeline/process_stage/method/llm_request.py", line 303, in run_agent
    async for resp in agent_runner.step():
  ...
  File "/home/AstrBot/.venv/lib/python3.10/site-packages/openai/_base_client.py", line 1547, in request
    raise APITimeoutError(request=request) from err
openai.APITimeoutError: Request timed out.

[01:30:45] [Core] [INFO] [respond.stage:163]: Prepare to send - Unknown/7950744926: 

AstrBot 请求失败。
错误类型: APITimeoutError
错误信息: Request timed out.

请在控制台查看和分享错误详情。

→ ❌ 没有任何插件钩子日志,说明 on_llm_response 没有被调用


你愿意提交 PR 吗?

  • [ ] 是的,我愿意提交 PR!

Code of Conduct

  • [x] 我已阅读并同意遵守该项目的 行为准则。

DDZS987 avatar Nov 15 '25 18:11 DDZS987