mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-23 14:04:41 +00:00
fix(title-middleware): wait for the first complete exchange to generate a title (#8338)
* fix(agents): wait for the first complete exchange to generate a title * fix(agents): preserve default title timing in the SSE stream * fix(title-middleware): generate model titles at turn end * fix(title-middleware): preserve titles across live input and recursion caps * fix(runtime): recover first-turn titles from delta checkpoints --------- Co-authored-by: Houston <347629597+HoustonJia@users.noreply.github.com> Co-authored-by: Nan Gao <thunderggnn@gmail.com>
This commit is contained in:
parent
5bb4da91ea
commit
8113420c8f
@ -6,14 +6,18 @@
|
||||
|
||||
## 实现方式
|
||||
|
||||
使用 `TitleMiddleware` 在 `after_model` 钩子中:
|
||||
1. 检测是否是首次对话(1个用户消息 + 1个助手回复)
|
||||
使用 `TitleMiddleware` 按首轮对话的生命周期生成标题:
|
||||
1. 检测是否是首轮对话。默认本地标题在首个助手步骤后生成;显式配置标题模型时,在 `aafter_agent` 等待整轮结束,仅使用最终助手回复的可见文本。
|
||||
2. 检查 state 是否已有 title
|
||||
3. 默认从首条用户消息生成本地 fallback 标题,避免在流式回复结束前额外等待一次 LLM 调用;显式配置 `model_name` 时才调用 LLM 生成标题(默认最多6个词)
|
||||
4. 将 title 存储到 `ThreadState` 中(会被 checkpointer 持久化)
|
||||
|
||||
TitleMiddleware 会先把 LangChain message content 里的结构化 block/list 内容归一化为纯文本,再拼到 title prompt 里,避免把 Python/JSON 的原始 repr 泄漏到标题生成模型。
|
||||
|
||||
如果直接返回的工具结束了图执行,没有最终的助手回复,`after_agent` 使用首条用户消息或已验证的附件生成本地标题。
|
||||
|
||||
首轮运行被中断或达到步数上限时,若线程还没有标题,Gateway 会从首条用户消息或已验证的附件生成本地标题。`full` 和 `delta` 两种 checkpoint 模式都支持这一回退。
|
||||
|
||||
## ⚠️ 重要:存储机制
|
||||
|
||||
### Title 存储位置
|
||||
@ -161,6 +165,7 @@ sequenceDiagram
|
||||
alt title.model_name 为空(默认)
|
||||
TitleMiddleware->>TitleMiddleware: 从首条用户消息生成本地 fallback title
|
||||
else 显式配置 title.model_name
|
||||
LangGraph->>TitleMiddleware: 回合结束,aafter_agent()
|
||||
TitleMiddleware->>TitleModel: 生成 LLM title
|
||||
TitleModel-->>TitleMiddleware: 返回 title
|
||||
end
|
||||
@ -227,23 +232,8 @@ uv run pytest tests/test_title_middleware_core_logic.py tests/test_title_generat
|
||||
|
||||
### 实现细节
|
||||
|
||||
```python
|
||||
# TitleMiddleware 核心逻辑
|
||||
@override
|
||||
async def aafter_model(self, state: TitleMiddlewareState, runtime: Runtime) -> dict | None:
|
||||
return await self._agenerate_title_result(state)
|
||||
异步执行时,默认标题及纯附件标题在首个助手步骤即可写入。配置标题模型后,只有回合结束且最终回复包含可见文本时才调用模型。待办提醒不计入用户轮数,推理块不进入标题提示词。
|
||||
|
||||
async def _agenerate_title_result(self, state: TitleMiddlewareState) -> dict | None:
|
||||
if not self._should_generate_title(state):
|
||||
return None
|
||||
|
||||
config = self._get_title_config()
|
||||
if not config.model_name:
|
||||
return self._generate_title_result(state)
|
||||
|
||||
# 显式配置 title.model_name 时才调用标题模型;失败会回退到本地 title。
|
||||
...
|
||||
```
|
||||
|
||||
## 相关文件
|
||||
|
||||
|
||||
@ -9,11 +9,14 @@ from unicodedata import category
|
||||
|
||||
from langchain.agents import AgentState
|
||||
from langchain.agents.middleware import AgentMiddleware
|
||||
from langchain_core.messages import AIMessage, HumanMessage
|
||||
from langgraph.config import get_config
|
||||
from langgraph.constants import TAG_NOSTREAM
|
||||
from langgraph.runtime import Runtime
|
||||
|
||||
from deerflow.agents.middlewares.dynamic_context_middleware import is_dynamic_context_reminder
|
||||
from deerflow.agents.middlewares.message_utils import is_genuine_user_message
|
||||
from deerflow.agents.middlewares.model_response import has_tool_call_intent
|
||||
from deerflow.agents.middlewares.pii_redaction_middleware import redact_texts
|
||||
from deerflow.config.title_config import get_title_config
|
||||
from deerflow.models import create_chat_model
|
||||
@ -35,7 +38,7 @@ class TitleMiddlewareState(AgentState):
|
||||
|
||||
|
||||
class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
||||
"""Automatically generate a title for the thread after the first user message."""
|
||||
"""Generate a title when the agent finishes its first exchange."""
|
||||
|
||||
state_schema = TitleMiddlewareState
|
||||
|
||||
@ -109,11 +112,60 @@ class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
||||
|
||||
@staticmethod
|
||||
def _is_user_message_for_title(message: object) -> bool:
|
||||
return TitleMiddleware._message_type(message) == "human" and not TitleMiddleware._is_dynamic_context_reminder_message(message)
|
||||
if TitleMiddleware._message_type(message) != "human" or TitleMiddleware._is_dynamic_context_reminder_message(message):
|
||||
return False
|
||||
if isinstance(message, dict):
|
||||
# Apply the same authorship rules to checkpoint metadata.
|
||||
message = HumanMessage(content="", name=message.get("name"), additional_kwargs=message.get("additional_kwargs") or {})
|
||||
# RunInputControl stamps instructions appended while the current run is active.
|
||||
if isinstance(message, HumanMessage) and message.additional_kwargs.get("run_input_id") and message.additional_kwargs.get("run_input_source") == "user":
|
||||
return False
|
||||
return is_genuine_user_message(message)
|
||||
|
||||
@staticmethod
|
||||
def _has_tool_call_intent(message: object) -> bool:
|
||||
if isinstance(message, AIMessage):
|
||||
return has_tool_call_intent(message)
|
||||
if not isinstance(message, Mapping):
|
||||
return False
|
||||
raw = message.get("additional_kwargs")
|
||||
return bool(message.get("tool_calls") or message.get("invalid_tool_calls") or message.get("function_call") or (isinstance(raw, Mapping) and (raw.get("tool_calls") or raw.get("function_call"))))
|
||||
|
||||
def _first_exchange(self, state: TitleMiddlewareState) -> tuple[object | None, object | None]:
|
||||
"""Select the first user request and its latest assistant step.
|
||||
|
||||
The graph calls after_model once per model step. Earlier assistant
|
||||
messages may describe the plan or request tools. Only the latest step
|
||||
after the user request can complete that exchange. If a second user
|
||||
message is already present, this middleware no longer owns the title.
|
||||
"""
|
||||
user_message = None
|
||||
assistant_message = None
|
||||
for message in state.get("messages") or []:
|
||||
if self._is_user_message_for_title(message):
|
||||
if user_message is not None:
|
||||
return None, None
|
||||
user_message = message
|
||||
elif user_message is not None and self._message_type(message) == "ai":
|
||||
assistant_message = message
|
||||
return user_message, assistant_message
|
||||
|
||||
def _final_assistant_text(self, message: object | None) -> str:
|
||||
if message is None or self._has_tool_call_intent(message):
|
||||
return ""
|
||||
content = self._message_content(message)
|
||||
if isinstance(content, list):
|
||||
parts = []
|
||||
for block in content:
|
||||
if isinstance(block, str):
|
||||
parts.append(block)
|
||||
elif isinstance(block, dict) and block.get("type") in ("text", "output_text") and isinstance(block.get("text"), str):
|
||||
parts.append(block["text"])
|
||||
content = "\n".join(parts)
|
||||
return self._strip_think_tags(content) if isinstance(content, str) else ""
|
||||
|
||||
def _get_title_user_message(self, state: TitleMiddlewareState) -> str:
|
||||
messages = state.get("messages") or []
|
||||
user_message = next((m for m in messages if self._is_user_message_for_title(m)), None)
|
||||
user_message = next((message for message in state.get("messages") or [] if self._is_user_message_for_title(message)), None)
|
||||
if user_message is None:
|
||||
return ""
|
||||
if isinstance(user_message, dict):
|
||||
@ -186,23 +238,8 @@ class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
||||
if state.get("title"):
|
||||
return False
|
||||
|
||||
# Check if this is the first turn (has at least one user message and one assistant response).
|
||||
# Defensively coerce a None ``messages`` channel (possible when reading a
|
||||
# partially-initialized checkpoint) into an empty list so ``len()`` is safe.
|
||||
messages = state.get("messages") or []
|
||||
min_messages = 1 if allow_partial_exchange else 2
|
||||
if len(messages) < min_messages:
|
||||
return False
|
||||
|
||||
# Count user and assistant messages
|
||||
user_messages = [m for m in messages if self._is_user_message_for_title(m)]
|
||||
assistant_messages = [m for m in messages if self._message_type(m) == "ai"]
|
||||
|
||||
# Normal path: title only after first complete exchange. Interrupted path
|
||||
# (``allow_partial_exchange=True``) accepts a lone first-turn user message
|
||||
# so a fallback title can still be persisted when the run is cancelled
|
||||
# before any AI chunk reaches the checkpoint.
|
||||
return len(user_messages) == 1 and (len(assistant_messages) >= 1 or allow_partial_exchange)
|
||||
user_message, assistant_message = self._first_exchange(state)
|
||||
return user_message is not None and (assistant_message is not None or allow_partial_exchange)
|
||||
|
||||
def _build_title_prompt(self, state: TitleMiddlewareState) -> tuple[str, str]:
|
||||
"""Extract user/assistant messages and build the title prompt.
|
||||
@ -210,12 +247,9 @@ class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
||||
Returns (prompt_string, user_msg) so callers can use user_msg as fallback.
|
||||
"""
|
||||
config = self._get_title_config()
|
||||
messages = state.get("messages") or []
|
||||
|
||||
assistant_msg_content = next((self._message_content(m) for m in messages if self._message_type(m) == "ai"), "")
|
||||
|
||||
_, assistant_message = self._first_exchange(state)
|
||||
assistant_msg = self._final_assistant_text(assistant_message)
|
||||
user_msg = self._get_title_user_message(state)
|
||||
assistant_msg = self._strip_think_tags(self._normalize_content(assistant_msg_content))
|
||||
|
||||
# This model is invoked directly, outside the main model wrappers.
|
||||
# Redact complete fields before truncation can split an identifier.
|
||||
@ -318,10 +352,11 @@ class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
||||
self,
|
||||
state: TitleMiddlewareState,
|
||||
*,
|
||||
turn_ended: bool = True,
|
||||
task_store=None,
|
||||
) -> dict | None:
|
||||
"""Generate a configured LLM title asynchronously and fall back locally."""
|
||||
if not self._should_generate_title(state):
|
||||
if not self._should_generate_title(state, allow_partial_exchange=turn_ended):
|
||||
return None
|
||||
|
||||
attachment_title = self._attachment_only_title(state)
|
||||
@ -338,6 +373,14 @@ class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
||||
if not config.model_name:
|
||||
return {"title": self._fallback_title(user_msg)}
|
||||
|
||||
# Default and attachment titles use only the user request and retain
|
||||
# their early state update. A configured model also needs the answer.
|
||||
if not turn_ended:
|
||||
return None
|
||||
_, assistant_message = self._first_exchange(state)
|
||||
if not self._final_assistant_text(assistant_message):
|
||||
return {"title": self._fallback_title(user_msg)}
|
||||
|
||||
try:
|
||||
prompt, user_msg = self._build_title_prompt(state)
|
||||
# attach_tracing=False because ``_get_runnable_config()`` inherits
|
||||
@ -384,5 +427,18 @@ class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
||||
|
||||
return await self._agenerate_title_result(
|
||||
state,
|
||||
turn_ended=False,
|
||||
task_store=task_store_from_runtime(runtime),
|
||||
)
|
||||
|
||||
@override
|
||||
def after_agent(self, state: TitleMiddlewareState, runtime: Runtime) -> dict | None:
|
||||
# A return_direct tool can end the graph without one last model step.
|
||||
# Keep the local title fallback for that path, as for interrupted runs.
|
||||
return self._generate_title_result(state, allow_partial_exchange=True)
|
||||
|
||||
@override
|
||||
async def aafter_agent(self, state: TitleMiddlewareState, runtime: Runtime) -> dict | None:
|
||||
from deerflow_extension_api import task_store_from_runtime
|
||||
|
||||
return await self._agenerate_title_result(state, task_store=task_store_from_runtime(runtime))
|
||||
|
||||
@ -2259,11 +2259,12 @@ async def run_agent(
|
||||
except Exception:
|
||||
logger.warning("Could not finalize satisfied goal for thread %s", thread_id, exc_info=True)
|
||||
|
||||
if started and not record.ownership_lost and checkpointer is not None and record.status == RunStatus.interrupted and not _is_edit_replay_run(record):
|
||||
needs_local_title = record.status == RunStatus.interrupted or (record.status == RunStatus.error and getattr(record, "stop_reason", None) == _RECURSION_CAPPED_STOP_REASON)
|
||||
if started and not record.ownership_lost and checkpointer is not None and needs_local_title and not _is_edit_replay_run(record):
|
||||
try:
|
||||
await run_manager.wait_for_prior_finalizing(thread_id, run_id)
|
||||
if not await run_manager.has_later_started_run(thread_id, run_id):
|
||||
await _ensure_interrupted_title(checkpointer=checkpointer, thread_id=thread_id, app_config=ctx.app_config, graph_input=graph_input)
|
||||
await _ensure_interrupted_title(checkpointer=checkpointer, thread_id=thread_id, app_config=ctx.app_config, graph_input=graph_input, accessor=accessor)
|
||||
except Exception:
|
||||
logger.debug("Failed to generate interrupted title for thread %s (non-fatal)", thread_id)
|
||||
|
||||
@ -3779,8 +3780,8 @@ async def _persist_run_duration(
|
||||
)
|
||||
|
||||
|
||||
async def _ensure_interrupted_title(*, checkpointer: Any, thread_id: str, app_config: AppConfig | None, graph_input: Any | None = None) -> str | None:
|
||||
"""Persist a local fallback title for interrupted first-turn runs.
|
||||
async def _ensure_interrupted_title(*, checkpointer: Any, thread_id: str, app_config: AppConfig | None, graph_input: Any | None = None, accessor: CheckpointStateAccessor | None = None) -> str | None:
|
||||
"""Persist a local fallback title for interrupted or recursion-capped first turns.
|
||||
|
||||
Returns the title that is now persisted (existing or newly written), or
|
||||
``None`` when no checkpoint is available or no title text can be derived.
|
||||
@ -3800,6 +3801,10 @@ async def _ensure_interrupted_title(*, checkpointer: Any, thread_id: str, app_co
|
||||
if existing_title:
|
||||
return existing_title
|
||||
|
||||
if ckpt_tuple is not None and accessor is not None and accessor.mode == "delta":
|
||||
# Reconstruct messages at this exact checkpoint before checking which turn stopped.
|
||||
snapshot = await accessor.aget(ckpt_tuple.config)
|
||||
channel_values = snapshot.values
|
||||
result = middleware._generate_title_result(_title_generation_state(channel_values, graph_input), allow_partial_exchange=True)
|
||||
title = result.get("title") if isinstance(result, dict) else None
|
||||
if not title:
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"""Title generation must build its provider off the Gateway event loop.
|
||||
|
||||
Inside a graph run, ``aafter_model`` builds the configured title model inline.
|
||||
Inside a graph run, ``aafter_agent`` builds the configured title model inline.
|
||||
``create_chat_model`` can read local CLI credentials (Codex ``auth.json``,
|
||||
Claude Code credential files) while it is constructed, so every other request
|
||||
on the shared loop waited for that read. The real Codex provider is built under
|
||||
|
||||
@ -305,10 +305,8 @@ async def test_non_delta_writers_preserve_delta_messages_and_markers(saver_env:
|
||||
durations={"run-1": 7},
|
||||
)
|
||||
assert durations_written
|
||||
# Delta checkpoints carry no messages in channel_values, so the title
|
||||
# helper has nothing to derive from and must stay inert (no write).
|
||||
title = await _ensure_interrupted_title(checkpointer=saver_env.saver, thread_id=thread_id, app_config=None)
|
||||
assert title is None
|
||||
title = await _ensure_interrupted_title(checkpointer=saver_env.saver, thread_id=thread_id, app_config=None, accessor=accessor)
|
||||
assert title == "hello goal writer"
|
||||
|
||||
await saver_env.reopen()
|
||||
graph = _build_graph(DeltaThreadState, saver_env.saver)
|
||||
@ -319,6 +317,7 @@ async def test_non_delta_writers_preserve_delta_messages_and_markers(saver_env:
|
||||
|
||||
# Production materialized read path (same one the Gateway uses).
|
||||
snapshot = await accessor.aget(config)
|
||||
assert snapshot.values["title"] == title
|
||||
assert [m.id for m in snapshot.values["messages"]] == ["u1", "a1"]
|
||||
assert [m.content for m in snapshot.values["messages"]] == ["hello goal writer", "reply"]
|
||||
|
||||
|
||||
@ -342,7 +342,7 @@ async def test_title_middleware_uses_build_bound_snapshot_and_live_task_store(mo
|
||||
]
|
||||
}
|
||||
|
||||
result = await middleware.aafter_model(
|
||||
result = await middleware.aafter_agent(
|
||||
state,
|
||||
Runtime(context={EXTENSION_TASK_STORE_KEY: store}),
|
||||
)
|
||||
|
||||
@ -17,8 +17,9 @@ from langchain_core.tools import tool
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from deerflow.agents.thread_state import ThreadState
|
||||
from deerflow.agents.thread_state import get_thread_state_schema
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.config.database_config import CheckpointChannelMode
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.config.sandbox_config import SandboxConfig
|
||||
from deerflow.runtime.events.store.memory import MemoryRunEventStore
|
||||
@ -50,7 +51,7 @@ class _ToolLoopModel(BaseChatModel):
|
||||
return ChatResult(generations=[ChatGeneration(message=message)])
|
||||
|
||||
|
||||
async def _run_until_recursion_cap(tmp_path: Path, *, with_goal: bool) -> dict[str, Any]:
|
||||
async def _run_until_recursion_cap(tmp_path: Path, *, with_goal: bool, checkpoint_mode: CheckpointChannelMode = "full") -> dict[str, Any]:
|
||||
evaluator_calls: list[Any] = []
|
||||
published: list[tuple[str, Any]] = []
|
||||
|
||||
@ -80,21 +81,26 @@ async def _run_until_recursion_cap(tmp_path: Path, *, with_goal: bool) -> dict[s
|
||||
return f"wrote part-{n}.md"
|
||||
|
||||
model = _ToolLoopModel(calls=[])
|
||||
graph = create_agent(model=model, tools=[write_part], state_schema=ThreadState, context_schema=dict, checkpointer=saver)
|
||||
# Snapshot every delta write so the cap lands on a stored messages snapshot.
|
||||
state_schema = get_thread_state_schema(checkpoint_mode, snapshot_frequency=1)
|
||||
graph = create_agent(model=model, tools=[write_part], state_schema=state_schema, context_schema=dict, checkpointer=saver)
|
||||
app_config = AppConfig(sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"))
|
||||
app_config.title.enabled = app_config.memory.enabled = app_config.memory.injection_enabled = False
|
||||
app_config.title.enabled = True
|
||||
app_config.memory.enabled = app_config.memory.injection_enabled = False
|
||||
if with_goal:
|
||||
await write_thread_goal(saver, record.thread_id, build_goal_state("Write the report.", max_continuations=2), create_if_missing=True)
|
||||
await worker.run_agent(
|
||||
bridge,
|
||||
manager,
|
||||
record,
|
||||
ctx=worker.RunContext(checkpointer=saver, event_store=events, app_config=app_config),
|
||||
ctx=worker.RunContext(checkpointer=saver, event_store=events, app_config=app_config, checkpoint_channel_mode=checkpoint_mode),
|
||||
agent_factory=lambda config: graph,
|
||||
graph_input={"messages": [HumanMessage(content="Write the report in parts.")]},
|
||||
config={"configurable": {"thread_id": record.thread_id}, "recursion_limit": 6},
|
||||
stream_modes=["values"],
|
||||
)
|
||||
snapshot = await graph.aget_state({"configurable": {"thread_id": record.thread_id}})
|
||||
assert snapshot.values["title"] == "Write the report in parts."
|
||||
goal = await read_thread_goal(saver, record.thread_id)
|
||||
recorded = await events.list_events(record.thread_id, record.run_id)
|
||||
finally:
|
||||
@ -111,15 +117,21 @@ async def _run_until_recursion_cap(tmp_path: Path, *, with_goal: bool) -> dict[s
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_network(monkeypatch):
|
||||
def deny(*args, **kwargs):
|
||||
connect = socket.socket.connect
|
||||
|
||||
def deny(sock, address):
|
||||
# Windows asyncio uses a loopback socket pair to wake its event loop.
|
||||
if isinstance(address, tuple) and address[0] in ("127.0.0.1", "::1"):
|
||||
return connect(sock, address)
|
||||
raise AssertionError("this regression must not use the network")
|
||||
|
||||
monkeypatch.setattr(socket.socket, "connect", deny)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recursion_cap_reports_a_plain_stop_with_unpresented_outputs(tmp_path):
|
||||
result = await _run_until_recursion_cap(tmp_path, with_goal=False)
|
||||
@pytest.mark.parametrize("checkpoint_mode", ["full", "delta"])
|
||||
async def test_recursion_cap_reports_a_plain_stop_with_unpresented_outputs(tmp_path, checkpoint_mode):
|
||||
result = await _run_until_recursion_cap(tmp_path, with_goal=False, checkpoint_mode=checkpoint_mode)
|
||||
record = result["record"]
|
||||
|
||||
assert record.status == RunStatus.error
|
||||
|
||||
@ -5,16 +5,144 @@ from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from _agent_e2e_helpers import FakeToolCallingModel, build_single_tool_call_model
|
||||
from langchain.agents import create_agent
|
||||
from langchain_core.messages import AIMessage, HumanMessage
|
||||
from langchain_core.tools import tool
|
||||
from langgraph.constants import TAG_NOSTREAM
|
||||
|
||||
from deerflow.agents.middlewares import title_middleware as title_middleware_module
|
||||
from deerflow.agents.middlewares.dynamic_context_middleware import _DYNAMIC_CONTEXT_REMINDER_KEY
|
||||
from deerflow.agents.middlewares.title_middleware import TitleMiddleware
|
||||
from deerflow.agents.middlewares.todo_middleware import TodoMiddleware
|
||||
from deerflow.config.title_config import TitleConfig, get_title_config, set_title_config
|
||||
from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("tool_step_text", ["", "Let me look that up."])
|
||||
async def test_configured_title_model_receives_the_final_reply_after_tools(monkeypatch, tool_step_text):
|
||||
events = []
|
||||
|
||||
@tool
|
||||
def lookup() -> str:
|
||||
"""Get the requested information."""
|
||||
events.append("tool")
|
||||
return "lookup result"
|
||||
|
||||
async def title_model(prompt, **kwargs):
|
||||
events.append(prompt)
|
||||
return AIMessage(content="Resolved conversation title")
|
||||
|
||||
monkeypatch.setattr(title_middleware_module, "create_chat_model", lambda **_: SimpleNamespace(ainvoke=title_model))
|
||||
model = build_single_tool_call_model(tool_name="lookup", tool_args={}, final_text="The final answer is available.")
|
||||
model.responses[0].content = tool_step_text
|
||||
graph = create_agent(
|
||||
model=model,
|
||||
tools=[lookup],
|
||||
middleware=[TitleMiddleware(title_config=TitleConfig(model_name="test-title-model"))],
|
||||
)
|
||||
output = await graph.ainvoke({"messages": [HumanMessage(content="Please look up the result")]})
|
||||
|
||||
assert output["title"] == "Resolved conversation title"
|
||||
assert len(events) == 2
|
||||
assert events[0] == "tool"
|
||||
assert "The final answer is available." in events[1]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_return_direct_tool_end_keeps_local_title_without_calling_title_model(monkeypatch):
|
||||
@tool(return_direct=True)
|
||||
def lookup() -> str:
|
||||
"""Get the requested information."""
|
||||
return "lookup result"
|
||||
|
||||
create_title_model = MagicMock()
|
||||
monkeypatch.setattr(title_middleware_module, "create_chat_model", create_title_model)
|
||||
graph = create_agent(
|
||||
model=build_single_tool_call_model(tool_name="lookup", tool_args={}),
|
||||
tools=[lookup],
|
||||
middleware=[TitleMiddleware(title_config=TitleConfig(model_name="test-title-model"))],
|
||||
)
|
||||
state = await graph.ainvoke({"messages": [HumanMessage(content="Please look up the result")]})
|
||||
|
||||
assert state["title"] == "Please look up the result"
|
||||
assert state["messages"][-1].type == "tool"
|
||||
create_title_model.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_title_waits_for_todo_continuation_after_text_only_progress(monkeypatch):
|
||||
title_model = AsyncMock(return_value=AIMessage(content="Completed task"))
|
||||
monkeypatch.setattr(title_middleware_module, "create_chat_model", lambda **_: SimpleNamespace(ainvoke=title_model))
|
||||
todos = TodoMiddleware()
|
||||
monkeypatch.setattr(todos, "_MAX_COMPLETION_REMINDERS", 1)
|
||||
graph = create_agent(
|
||||
model=FakeToolCallingModel(responses=[AIMessage(content="Still working"), AIMessage(content="Finished report")]),
|
||||
middleware=[todos, TitleMiddleware(title_config=TitleConfig(model_name="test-title-model"))],
|
||||
)
|
||||
result = await graph.ainvoke(
|
||||
{"messages": [HumanMessage(content="Prepare report")], "todos": [{"content": "Prepare report", "status": "in_progress"}]},
|
||||
context={},
|
||||
)
|
||||
assert result["title"] == "Completed task"
|
||||
title_model.assert_awaited_once()
|
||||
prompt = title_model.await_args.args[0]
|
||||
assert "Finished report" in prompt
|
||||
assert "Still working" not in prompt
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("visible", [True, False])
|
||||
async def test_title_prompt_excludes_reasoning_blocks(monkeypatch, visible):
|
||||
title_model = AsyncMock(return_value=AIMessage(content="Model title"))
|
||||
monkeypatch.setattr(title_middleware_module, "create_chat_model", lambda **_: SimpleNamespace(ainvoke=title_model))
|
||||
blocks = [{"type": "reasoning", "text": "Private reasoning"}]
|
||||
if visible:
|
||||
blocks.append({"type": "text", "text": "Public answer"})
|
||||
middleware = TitleMiddleware(title_config=TitleConfig(model_name="title-model"))
|
||||
result = await middleware.aafter_agent({"messages": [HumanMessage(content="My question"), AIMessage(content=blocks)]}, MagicMock())
|
||||
if visible:
|
||||
assert result == {"title": "Model title"}
|
||||
prompt = title_model.await_args.args[0]
|
||||
assert "Public answer" in prompt
|
||||
assert "Private reasoning" not in prompt
|
||||
else:
|
||||
assert result == {"title": "My question"}
|
||||
title_model.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("serialized", [False, True])
|
||||
def test_compaction_reminder_preserves_first_user_turn_for_fallback(serialized):
|
||||
middleware = TitleMiddleware(title_config=TitleConfig())
|
||||
reminder = HumanMessage(name="todo_reminder", content="Pending todos", additional_kwargs={"hide_from_ui": True})
|
||||
messages = [HumanMessage(content="My task"), reminder.model_dump() if serialized else reminder]
|
||||
assert middleware.after_agent({"messages": messages}, MagicMock()) == {"title": "My task"}
|
||||
messages.append(HumanMessage(content="Another task"))
|
||||
assert middleware.after_agent({"messages": messages}, MagicMock()) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("serialized", [False, True])
|
||||
async def test_user_instruction_during_tool_execution_stays_in_first_turn(monkeypatch, serialized):
|
||||
title_model = AsyncMock(return_value=AIMessage(content="Report title"))
|
||||
monkeypatch.setattr(title_middleware_module, "create_chat_model", lambda **_: SimpleNamespace(ainvoke=title_model))
|
||||
middleware = TitleMiddleware(title_config=TitleConfig(model_name="title-model"))
|
||||
instruction = HumanMessage(content="Include totals", additional_kwargs={"run_input_id": "i1", "run_input_source": "user", "run_id": "r1"})
|
||||
messages = [
|
||||
HumanMessage(content="Prepare the report"),
|
||||
AIMessage(content="", tool_calls=[{"name": "lookup", "args": {}, "id": "tool1"}]),
|
||||
instruction.model_dump() if serialized else instruction,
|
||||
AIMessage(content="The total is ten"),
|
||||
]
|
||||
assert await middleware.aafter_agent({"messages": messages}, MagicMock()) == {"title": "Report title"}
|
||||
prompt = title_model.await_args.args[0]
|
||||
assert "Prepare the report" in prompt and "The total is ten" in prompt
|
||||
messages.append(HumanMessage(content="Start a different report"))
|
||||
assert await middleware.aafter_agent({"messages": messages}, MagicMock()) is None
|
||||
title_model.assert_awaited_once()
|
||||
|
||||
|
||||
def _clone_title_config(config: TitleConfig) -> TitleConfig:
|
||||
# Avoid mutating shared global config objects across tests.
|
||||
return TitleConfig(**config.model_dump())
|
||||
@ -482,17 +610,6 @@ class TestTitleMiddlewareCoreLogic:
|
||||
assert title.endswith("...")
|
||||
assert title.startswith("这是一个非常长的问题描述")
|
||||
|
||||
def test_aafter_model_delegates_to_async_helper(self, monkeypatch):
|
||||
_set_test_title_config(model_name="title-model")
|
||||
middleware = TitleMiddleware()
|
||||
|
||||
monkeypatch.setattr(middleware, "_agenerate_title_result", AsyncMock(return_value={"title": "异步标题"}))
|
||||
result = asyncio.run(middleware.aafter_model({"messages": []}, runtime=MagicMock()))
|
||||
assert result == {"title": "异步标题"}
|
||||
|
||||
monkeypatch.setattr(middleware, "_agenerate_title_result", AsyncMock(return_value=None))
|
||||
assert asyncio.run(middleware.aafter_model({"messages": []}, runtime=MagicMock())) is None
|
||||
|
||||
def test_aafter_model_uses_local_fallback_when_no_title_model_is_configured(self, monkeypatch):
|
||||
"""Default async path must not block stream completion on a second LLM call."""
|
||||
_set_test_title_config(max_chars=20, model_name=None)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user