Files
bot042/tests/test_flows_async.py
openbot 5da55f8d17 fix(flows): 步数预算与图硬上限分离,预算耗尽时优雅收尾
max_steps 以前同时充当软预算和 recursion_limit,于是预算耗尽的那一刻
必然触发 GraphRecursionError:模型连一句收尾都来不及说,用户只收到
「处理消息时出错,请稍后再试」,已产出的内容也不会落库。

- 新增 StepBudgetMiddleware:按模型调用轮数计账(agent_rounds =
  max_steps // 2),剩余 <=4 轮时注入一次「立刻停止调用工具、给出结论」
  的收尾提示,只提醒一次
- 新增 STEP_GRACE(20),recursion_limit = max_steps + STEP_GRACE,把余量
  留给收尾动作
- GraphRecursionError 统一转成 StepBudgetExceeded,ainvoke 与流式两条
  路径都覆盖
- AgentReply 把「步数用尽」渲染成可操作说明,接在已产出内容之后一并
  下发并落库;用 _reported 标记让 on_error 不再补发通用错误文案,任务
  状态仍如实记 failed
- 同步 README / docs/architecture.md / db/schema.py 中 max_steps 的语义

测试:新增 tests/test_budget.py(7 个用例),全量 241 passed。
2026-11-09 21:32:29 +08:00

145 lines
4.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""异步链路测试:run_task / run_session 走 ainvoke。"""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import Any
from bot042.channels.base import BaseChannel
from bot042.channels.models import ChannelSubject, InboundMessage, TextContent
from bot042.config import STEP_GRACE, Settings
from bot042.flows.agent_task import last_message_text, run_task
from bot042.flows.session import run_session
class FakeAgent:
"""只实现异步入口的假智能体;调用同步 invoke 视为失败。"""
def __init__(self, reply: str = "ok") -> None:
self.reply = reply
self.calls: list[tuple[dict[str, Any], dict[str, Any] | None]] = []
async def ainvoke(
self,
state: dict[str, Any],
config: dict[str, Any] | None = None,
) -> dict[str, Any]:
self.calls.append((state, config))
return {"messages": [{"role": "assistant", "content": self.reply}]}
def invoke(self, *args: Any, **kwargs: Any) -> dict[str, Any]: # pragma: no cover
raise AssertionError("不应调用同步 invoke")
class FakeChannel(BaseChannel):
"""测试用虚拟渠道:start() 时把全部输入入队并关闭会话。"""
channel_type = "fake"
def __init__(self, inputs: list[str | None]) -> None:
super().__init__()
self._inputs = [i for i in inputs if i is not None]
self.sent: list[str] = []
async def start(self) -> None:
for line in self._inputs:
if line.lower() in {"exit", "quit"}:
break
self.enqueue(line)
self.notify_closed()
async def stop(self) -> None:
pass
def should_batch_inbound(self, message: InboundMessage) -> bool:
return False
def parse_inbound(self, raw_payload: Any) -> InboundMessage:
if isinstance(raw_payload, InboundMessage):
return raw_payload
return InboundMessage(
channel_id=self.channel_id,
channel_type=self.channel_type,
channel_subject=ChannelSubject(subject_id="u1"),
channel_session_id="s1",
content=[TextContent(text=str(raw_payload))],
)
async def _send_text(self, subject: ChannelSubject, text: str) -> None:
self.sent.append(text)
async def _send_content(self, subject: ChannelSubject, parts: list) -> None:
pass
async def _send_media(self, subject: ChannelSubject, media: Any) -> None:
pass
def test_run_task_uses_async_ainvoke(monkeypatch) -> None:
fake = FakeAgent("done")
monkeypatch.setattr("bot042.flows.agent_task.create_agent", lambda settings=None: fake)
settings = Settings(max_steps=7)
result = asyncio.run(run_task("hi", settings))
assert last_message_text(result) == "done"
state, config = fake.calls[0]
assert state["messages"][-1] == {"role": "user", "content": "hi"}
# 硬步数上限 = 软预算 + 收尾余量(见 Settings.recursion_limit)
assert config == {"recursion_limit": 7 + STEP_GRACE}
def test_last_message_text_multimodal_content() -> None:
result = {
"messages": [
{
"role": "assistant",
"content": [
{"type": "text", "text": "你好"},
{"type": "image_url", "image_url": "https://example.com/a.png"},
],
}
]
}
assert last_message_text(result) == "你好"
assert last_message_text({"messages": []}) == ""
# 多个文本块之间用换行分隔,不粘连
multi = {"messages": [{"content": [{"text": "第一段"}, {"text": "第二段"}]}]}
assert last_message_text(multi) == "第一段\n第二段"
def test_run_session_reuses_agent(monkeypatch, tmp_path: Path) -> None:
"""会话内多条消息只构建一次智能体。"""
fake = FakeAgent("pong")
built: list[Any] = []
def factory(settings=None):
built.append(settings)
return fake
monkeypatch.setattr("bot042.flows.agent_task.create_agent", factory)
channel = FakeChannel(["a", "b", "c", "exit"])
asyncio.run(run_session(channel, db=tmp_path / "bot.db"))
assert len(built) == 1 # 只构建一次
assert len(fake.calls) == 3
def test_run_session_async_loop(monkeypatch, tmp_path: Path) -> None:
fake = FakeAgent("pong")
monkeypatch.setattr("bot042.flows.agent_task.create_agent", lambda settings=None: fake)
channel = FakeChannel(["ping", "again", "exit"])
asyncio.run(run_session(channel, db=tmp_path / "bot.db"))
assert channel.sent == ["pong", "pong"]
assert len(fake.calls) == 2
# 第二轮带上了第一轮的 messages 历史
history, _config = fake.calls[1]
assert [m["role"] for m in history["messages"]] == ["user", "assistant", "user"]
assert history["messages"][0] == {"role": "user", "content": "ping"}
assert history["messages"][-1] == {"role": "user", "content": "again"}