- title: 标题模型用隔离 config(不继承父级 streaming callbacks),force_disable_thinking,<think> 块清洗,避免推理 token 进入实时流/运行日志 - uploads: 无文件的普通对话轮次直接跳过,不再解析线程归属(避免命中 DB) - thread_data: ephemeral 会话用当前登录用户解析数据目录 - thread_paths: open-/__skill-review__ 等合成线程视为 local-only,直接用当前用户 - frontend: 新增 build:test 构建脚本 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
271 lines
12 KiB
Python
271 lines
12 KiB
Python
"""Middleware for automatic thread title generation."""
|
|
|
|
import logging
|
|
import re
|
|
from typing import TYPE_CHECKING, Any, NotRequired, override
|
|
|
|
from langchain.agents import AgentState
|
|
from langchain.agents.middleware import AgentMiddleware
|
|
from langgraph.runtime import Runtime
|
|
|
|
from deerflow.config.title_config import get_title_config
|
|
from deerflow.models import create_chat_model
|
|
|
|
if TYPE_CHECKING:
|
|
from deerflow.config.app_config import AppConfig
|
|
from deerflow.config.title_config import TitleConfig
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class TitleMiddlewareState(AgentState):
|
|
"""Compatible with the `ThreadState` schema."""
|
|
|
|
title: NotRequired[str | None]
|
|
title_provisional: NotRequired[bool]
|
|
|
|
|
|
class TitleMiddleware(AgentMiddleware[TitleMiddlewareState]):
|
|
"""Automatically generate a title for the thread after the first user message."""
|
|
|
|
state_schema = TitleMiddlewareState
|
|
|
|
def __init__(self, *, app_config: "AppConfig | None" = None, title_config: "TitleConfig | None" = None):
|
|
super().__init__()
|
|
self._app_config = app_config
|
|
self._title_config = title_config
|
|
|
|
def _get_title_config(self):
|
|
if self._title_config is not None:
|
|
return self._title_config
|
|
if self._app_config is not None:
|
|
return self._app_config.title
|
|
return get_title_config()
|
|
|
|
def _normalize_content(self, content: object) -> str:
|
|
if isinstance(content, str):
|
|
return content
|
|
|
|
if isinstance(content, list):
|
|
parts = [self._normalize_content(item) for item in content]
|
|
return "\n".join(part for part in parts if part)
|
|
|
|
if isinstance(content, dict):
|
|
text_value = content.get("text")
|
|
if isinstance(text_value, str):
|
|
return text_value
|
|
|
|
nested_content = content.get("content")
|
|
if nested_content is not None:
|
|
return self._normalize_content(nested_content)
|
|
|
|
return ""
|
|
|
|
def _should_set_provisional_title(self, state: TitleMiddlewareState) -> bool:
|
|
"""Check if we should set an instant, question-derived placeholder title.
|
|
|
|
Runs in ``before_model`` so the thread shows a sensible title the moment
|
|
the user sends their first message — eliminating the "untitled" window
|
|
while the (possibly long) first answer streams. No LLM call, no latency.
|
|
"""
|
|
config = self._get_title_config()
|
|
if not config.enabled:
|
|
return False
|
|
|
|
# Already has a title (provisional or final) — nothing to do.
|
|
if state.get("title"):
|
|
return False
|
|
|
|
# Only on the very first turn, as soon as the user message arrives.
|
|
messages = state.get("messages", [])
|
|
user_messages = [m for m in messages if m.type == "human"]
|
|
return len(user_messages) == 1
|
|
|
|
def _should_generate_title(self, state: TitleMiddlewareState) -> bool:
|
|
"""Check if we should generate the final LLM title for this thread."""
|
|
config = self._get_title_config()
|
|
if not config.enabled:
|
|
return False
|
|
|
|
# Skip only if we already have a *finalized* title. A provisional
|
|
# placeholder set in before_model should still be upgraded by the LLM.
|
|
if state.get("title") and not state.get("title_provisional"):
|
|
return False
|
|
|
|
# Check if this is the first turn (has at least one user message and one assistant response)
|
|
messages = state.get("messages", [])
|
|
if len(messages) < 2:
|
|
return False
|
|
|
|
# Count user and assistant messages
|
|
user_messages = [m for m in messages if m.type == "human"]
|
|
assistant_messages = [m for m in messages if m.type == "ai"]
|
|
|
|
# Generate title after first complete exchange
|
|
return len(user_messages) == 1 and len(assistant_messages) >= 1
|
|
|
|
def _build_title_prompt(self, state: TitleMiddlewareState) -> tuple[str, str]:
|
|
"""Extract user/assistant messages and build the title prompt.
|
|
|
|
Returns (prompt_string, user_msg) so callers can use user_msg as fallback.
|
|
"""
|
|
config = self._get_title_config()
|
|
messages = state.get("messages", [])
|
|
|
|
user_msg_content = next((m.content for m in messages if m.type == "human"), "")
|
|
assistant_msg_content = next((m.content for m in messages if m.type == "ai"), "")
|
|
|
|
user_msg = self._normalize_content(user_msg_content)
|
|
assistant_msg = self._strip_think_tags(self._normalize_content(assistant_msg_content))
|
|
|
|
prompt = config.prompt_template.format(
|
|
max_words=config.max_words,
|
|
user_msg=user_msg[:500],
|
|
assistant_msg=assistant_msg[:500],
|
|
)
|
|
return prompt, user_msg
|
|
|
|
def _strip_think_tags(self, text: str) -> str:
|
|
"""Remove <think>...</think> blocks emitted by reasoning models (e.g. minimax, GLM, DeepSeek-R1).
|
|
|
|
Also handles malformed cases: an unclosed `<think>` (response truncated mid-reasoning)
|
|
or a stray `</think>` (open tag eaten by upstream parsing) — both can otherwise leak
|
|
raw reasoning into the title.
|
|
"""
|
|
text = re.sub(r"<think>[\s\S]*?</think>", "", text, flags=re.IGNORECASE)
|
|
text = re.sub(r"<think>[\s\S]*$", "", text, flags=re.IGNORECASE)
|
|
text = re.sub(r"^[\s\S]*?</think>", "", text, flags=re.IGNORECASE)
|
|
return text.strip()
|
|
|
|
def _parse_title(self, content: object) -> str:
|
|
"""Normalize model output into a clean title string (strips <think> blocks)."""
|
|
config = self._get_title_config()
|
|
title_content = self._strip_think_tags(self._normalize_content(content))
|
|
title = title_content.strip().strip('"').strip("'")
|
|
return title[: config.max_chars] if len(title) > config.max_chars else title
|
|
|
|
def _isolated_config(self) -> dict[str, Any]:
|
|
"""Build a RunnableConfig that does NOT inherit the parent's streaming callbacks.
|
|
|
|
The leak that pushed title-generation reasoning into the live UI stream came
|
|
from inheriting the parent RunnableConfig (and with it the SSE/streaming
|
|
callbacks) for the title model call. Here we deliberately start from an empty
|
|
config with ``callbacks: []`` so the title model's tokens — including any
|
|
``<think>`` reasoning from a reasoning-only deployment — never reach the
|
|
frontend stream or the run journal as conversation output. The stored title
|
|
is additionally cleaned by ``_parse_title``/``_strip_think_tags``.
|
|
"""
|
|
return {
|
|
"run_name": "title_agent",
|
|
"tags": ["middleware:title"],
|
|
"callbacks": [],
|
|
}
|
|
|
|
def _fallback_title(self, user_msg: str) -> str:
|
|
config = self._get_title_config()
|
|
fallback_chars = min(config.max_chars, 50)
|
|
if len(user_msg) > fallback_chars:
|
|
return user_msg[:fallback_chars].rstrip() + "..."
|
|
return user_msg if user_msg else "New Conversation"
|
|
|
|
def _provisional_title_result(self, state: TitleMiddlewareState) -> dict | None:
|
|
"""Set an instant placeholder title from the first user message (no LLM)."""
|
|
if not self._should_set_provisional_title(state):
|
|
return None
|
|
|
|
messages = state.get("messages", [])
|
|
user_msg_content = next((m.content for m in messages if m.type == "human"), "")
|
|
user_msg = self._normalize_content(user_msg_content)
|
|
if not user_msg.strip():
|
|
return None
|
|
title = self._fallback_title(user_msg)
|
|
logger.debug("TitleMiddleware: set provisional title %r before first model call", title)
|
|
return {"title": title, "title_provisional": True}
|
|
|
|
def _generate_title_result(self, state: TitleMiddlewareState) -> dict | None:
|
|
"""Generate a local fallback title without blocking on an LLM call."""
|
|
if not self._should_generate_title(state):
|
|
return None
|
|
|
|
_, user_msg = self._build_title_prompt(state)
|
|
return {"title": self._fallback_title(user_msg), "title_provisional": False}
|
|
|
|
def _force_disable_thinking(self, model: object) -> None:
|
|
"""Force-disable thinking on the title model via `extra_body` overrides.
|
|
|
|
Title generation never needs reasoning. The model factory only emits
|
|
disable params when the model config declares `when_thinking_disabled`
|
|
or a matching `when_thinking_enabled` shape — many user-added reasoning
|
|
models (e.g. GLM-4.5/5) only set `supports_thinking: true` and would
|
|
otherwise keep thinking on, which is slow and leaks <think> tags into
|
|
the title prompt response. Injecting both common OpenAI-compatible
|
|
disable shapes covers Zhipu GLM (`thinking.type`) and Qwen/vLLM
|
|
(`chat_template_kwargs.enable_thinking`); other providers ignore
|
|
unknown body fields.
|
|
"""
|
|
if not hasattr(model, "extra_body"):
|
|
return
|
|
current = getattr(model, "extra_body", None) or {}
|
|
merged_chat_template_kwargs = {
|
|
**(current.get("chat_template_kwargs") or {}),
|
|
"enable_thinking": False,
|
|
}
|
|
merged = {
|
|
**current,
|
|
"thinking": {**(current.get("thinking") or {}), "type": "disabled"},
|
|
"chat_template_kwargs": merged_chat_template_kwargs,
|
|
}
|
|
try:
|
|
model.extra_body = merged
|
|
except Exception:
|
|
logger.debug("Could not override extra_body to disable thinking on title model", exc_info=True)
|
|
|
|
async def _agenerate_title_result(self, state: TitleMiddlewareState) -> dict | None:
|
|
"""Polish the title with an LLM, without leaking its reasoning to the UI.
|
|
|
|
The title model is invoked with an *isolated* config (``_isolated_config``)
|
|
that does not inherit the parent's streaming callbacks, so even a
|
|
reasoning-only deployment's ``<think>`` tokens never reach the live UI
|
|
stream or the run journal. Thinking is also force-disabled on the model,
|
|
and the final stored title is stripped of any residual ``<think>`` blocks.
|
|
On any failure we fall back to the local question-derived title.
|
|
"""
|
|
if not self._should_generate_title(state):
|
|
return None
|
|
|
|
config = self._get_title_config()
|
|
prompt, user_msg = self._build_title_prompt(state)
|
|
|
|
try:
|
|
model_kwargs: dict[str, Any] = {"thinking_enabled": False, "force_disable_thinking": True}
|
|
if self._app_config is not None:
|
|
model_kwargs["app_config"] = self._app_config
|
|
if config.model_name:
|
|
model = create_chat_model(name=config.model_name, **model_kwargs)
|
|
else:
|
|
model = create_chat_model(**model_kwargs)
|
|
self._force_disable_thinking(model)
|
|
response = await model.ainvoke(prompt, config=self._isolated_config())
|
|
title = self._parse_title(response.content)
|
|
if title:
|
|
return {"title": title, "title_provisional": False}
|
|
except Exception:
|
|
logger.debug("Failed to generate async title via LLM; falling back to local title", exc_info=True)
|
|
return {"title": self._fallback_title(user_msg), "title_provisional": False}
|
|
|
|
@override
|
|
def before_model(self, state: TitleMiddlewareState, runtime: Runtime) -> dict | None:
|
|
return self._provisional_title_result(state)
|
|
|
|
@override
|
|
async def abefore_model(self, state: TitleMiddlewareState, runtime: Runtime) -> dict | None:
|
|
return self._provisional_title_result(state)
|
|
|
|
@override
|
|
def after_model(self, state: TitleMiddlewareState, runtime: Runtime) -> dict | None:
|
|
return self._generate_title_result(state)
|
|
|
|
@override
|
|
async def aafter_model(self, state: TitleMiddlewareState, runtime: Runtime) -> dict | None:
|
|
return await self._agenerate_title_result(state)
|