- agent: 新增 base.py 执行基类、execution.py 执行器、web.py 网络工具, middlewares/steering.py 中间件;移除旧的 agent.py - channels: 新增 ChannelManager、registry、models 与 IM 渠道(企业微信), 扩展 base.py - flows: 新增 agent_task / bus / cron / scheduler / service / stream / rpc / processor / tasks / model_settings / builtin;移除旧的 task.py - db: 新增 sqlite schema 与 repo 层 - docs: 新增架构说明、Channel × EventBus 设计、任务编写教程 - 依赖新增 aiosqlite / httpx / langgraph / primp / pydantic / ripgrep / wecom-aibot-sdk;新增 bot 命令入口 - 测试:232 passed
144 lines
4.8 KiB
Python
144 lines
4.8 KiB
Python
"""异步链路测试: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 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"}
|
|
assert config == {"recursion_limit": 7}
|
|
|
|
|
|
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"}
|