mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(agents): keep an unrenderable summary_prompt from failing the run (#7667)
* fix(agents): keep an unrenderable summary_prompt from failing the run
summary_prompt is a str.format template with a {messages} slot, so a
literal brace has to be doubled. The render runs outside the try that
guards the model call, so an unescaped brace raised KeyError out of
abefore_model and failed the turn instead of skipping compaction.
The middleware already documents the opposite: the automatic path
swallows a summary failure and leaves compaction state unchanged, and
raise_on_failure reports a real failure as SummaryGenerationError so
/compact can tell it from "nothing to compact". Route the render through
_render_summary_prompt, which turns a failure into None with a warning
naming the brace rule, and let the existing None path apply.
docs/summarization.md now states the template syntax.
* fix(agents): cover attribute and index template failures in summary_prompt rendering
Expand the render exception tuple to include AttributeError and TypeError so
{messages.foo} and {messages[missing]} share the same fail-open boundary as
literal braces and unknown placeholders. Add summary_prompt_hash to the
warning so operators can correlate the log line with the offending config
without the template or history appearing in logs.
Rewrite the regression suite around a real create_agent graph with
InMemorySaver: template failures preserve history and the checkpoint, the
summary model is never reached, and a repaired template recovers on the next
attempt. Document the template syntax and failure contract in
summarization.md, the middleware AGENTS.md, and the root README.
* fix(agents): log summary template error types only
---------
Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
This commit is contained in:
parent
adba516884
commit
126ad9dc37
@ -249,6 +249,7 @@ keep:
|
||||
- **Type**: String or null
|
||||
- **Default**: `null` (uses DeerFlow's built-in prompt)
|
||||
- **Description**: Custom prompt template for generating summaries. The prompt should guide the model to extract the most important context.
|
||||
- **Template syntax**: The value is a Python `str.format` template with one slot, `{messages}`, which receives the history selected for summarization. Literal braces must be doubled, so a JSON-shaped prompt is written `{{"summary": "..."}}`. Formatting and field-lookup errors skip automatic compaction without changing history or the previous summary. The warning includes `summary_prompt_hash`, matching the middleware's release-policy fingerprint, without logging the template or history. Manual `/compact` reports the existing summary-generation failure instead of treating the attempt as unnecessary compaction; its HTTP error status is unchanged.
|
||||
|
||||
#### `skill_file_read_tool_names`
|
||||
- **Type**: List of strings
|
||||
|
||||
@ -797,7 +797,22 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware):
|
||||
body = self._build_summary_input_text(source[cursor:end], previous)
|
||||
if body is None:
|
||||
return None
|
||||
return self.summary_prompt.format(messages=body).rstrip(), end
|
||||
prompt = self._render_summary_prompt(body)
|
||||
if prompt is None:
|
||||
return None
|
||||
return prompt, end
|
||||
|
||||
def _render_summary_prompt(self, body: str) -> str | None:
|
||||
"""Keep template-authoring failures inside the compaction failure boundary."""
|
||||
try:
|
||||
return self.summary_prompt.format(messages=body).rstrip()
|
||||
except (AttributeError, IndexError, KeyError, TypeError, ValueError) as exc:
|
||||
logger.warning(
|
||||
"Summarization template failed to render; keeping history. Use {messages} for history and double literal braces ({{ }}). summary_prompt_hash=%s error_type=%s",
|
||||
canonical_hash(self.summary_prompt),
|
||||
type(exc).__name__,
|
||||
)
|
||||
return None
|
||||
|
||||
def _build_summary_input_text(self, formatted_messages: str, previous_summary: str | None = None) -> str | None:
|
||||
"""Wrap complete raw sections; never trim material selected for removal.
|
||||
@ -820,7 +835,7 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware):
|
||||
source = self._summary_source_text(messages_to_summarize)
|
||||
previous = redact_text(previous_summary, getattr(self._app_config, "pii_redaction", None)) if previous_summary else None
|
||||
body = self._build_summary_input_text(source, previous)
|
||||
return self.summary_prompt.format(messages=body).rstrip() if body else None
|
||||
return self._render_summary_prompt(body) if body else None
|
||||
|
||||
def before_model(self, state: AgentState, runtime: Runtime) -> dict | None:
|
||||
return self._maybe_summarize(state, runtime)
|
||||
|
||||
249
backend/tests/test_summarization_template_render.py
Normal file
249
backend/tests/test_summarization_template_render.py
Normal file
@ -0,0 +1,249 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from deerflow_extension_api import canonical_hash
|
||||
from langchain.agents import create_agent
|
||||
from langchain_core.language_models import BaseChatModel
|
||||
from langchain_core.messages import AIMessage, HumanMessage
|
||||
from langchain_core.outputs import ChatGeneration, ChatResult
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from deerflow.agents.middlewares.summarization_middleware import (
|
||||
DeerFlowSummarizationMiddleware,
|
||||
SummaryGenerationError,
|
||||
create_summarization_middleware,
|
||||
)
|
||||
from deerflow.agents.thread_state import ThreadState
|
||||
from deerflow.config.app_config import AppConfig
|
||||
|
||||
_BRACE_TEMPLATE = 'Summarize as JSON: {"summary": "..."} {messages}'
|
||||
_INVALID_TEMPLATES = [
|
||||
pytest.param(_BRACE_TEMPLATE, id="literal-braces"),
|
||||
pytest.param("{messages} {nope}", id="unknown-name"),
|
||||
pytest.param("{}", id="positional-field"),
|
||||
pytest.param("{messages:unknown}", id="format-specifier"),
|
||||
pytest.param("{messages.foo}", id="attribute-field"),
|
||||
pytest.param("{messages[missing]}", id="string-index"),
|
||||
]
|
||||
|
||||
|
||||
class _StaticChatModel(BaseChatModel):
|
||||
text: str = "ok"
|
||||
calls: int = 0
|
||||
|
||||
@property
|
||||
def _llm_type(self) -> str:
|
||||
return "static-test-chat-model"
|
||||
|
||||
def bind_tools(self, tools, **kwargs):
|
||||
return self
|
||||
|
||||
def _generate(self, messages, stop=None, run_manager=None, **kwargs):
|
||||
self.calls += 1
|
||||
return ChatResult(generations=[ChatGeneration(message=AIMessage(content=self.text))])
|
||||
|
||||
async def _agenerate(self, messages, stop=None, run_manager=None, **kwargs):
|
||||
return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
|
||||
|
||||
|
||||
def _middleware(model, summary_prompt: str, **kwargs):
|
||||
options = {
|
||||
"trigger": ("messages", 4),
|
||||
"keep": ("messages", 2),
|
||||
"summary_prompt": summary_prompt,
|
||||
"token_counter": lambda ms: sum(len(str(m.content)) for m in ms),
|
||||
"trim_tokens_to_summarize": 9999,
|
||||
}
|
||||
options.update(kwargs)
|
||||
return DeerFlowSummarizationMiddleware(model=model, **options)
|
||||
|
||||
|
||||
def _state() -> dict:
|
||||
return {
|
||||
"messages": [
|
||||
HumanMessage(content="a" * 50, id="h1"),
|
||||
AIMessage(content="b" * 50, id="a1"),
|
||||
HumanMessage(content="c" * 50, id="h2"),
|
||||
AIMessage(content="d" * 50, id="a2"),
|
||||
],
|
||||
"summary_text": "previous summary",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("summary_prompt", _INVALID_TEMPLATES)
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
@pytest.mark.parametrize("raise_on_failure", [False, True], ids=["automatic", "manual"])
|
||||
async def test_invalid_template_preserves_compaction_state(summary_prompt, asynchronous, raise_on_failure):
|
||||
model = _StaticChatModel(text="must not replace history")
|
||||
events = []
|
||||
middleware = _middleware(model, summary_prompt, before_summarization=[events.append])
|
||||
state = _state()
|
||||
original = copy.deepcopy(state)
|
||||
runtime = SimpleNamespace(context={})
|
||||
|
||||
with pytest.raises(SummaryGenerationError) if raise_on_failure else nullcontext():
|
||||
if asynchronous:
|
||||
result = await middleware.acompact_state(
|
||||
state,
|
||||
runtime,
|
||||
force=raise_on_failure,
|
||||
raise_on_failure=raise_on_failure,
|
||||
)
|
||||
else:
|
||||
result = middleware.compact_state(
|
||||
state,
|
||||
runtime,
|
||||
force=raise_on_failure,
|
||||
raise_on_failure=raise_on_failure,
|
||||
)
|
||||
assert result is None
|
||||
|
||||
assert state == original
|
||||
assert model.calls == 0
|
||||
assert events == []
|
||||
assert middleware.summary_call_count == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("summary_prompt", _INVALID_TEMPLATES)
|
||||
def test_unrenderable_template_never_reaches_the_model(summary_prompt):
|
||||
model = _StaticChatModel()
|
||||
middleware = _middleware(model, summary_prompt)
|
||||
|
||||
assert middleware._build_summary_prompt([HumanMessage(content="hi", id="h1")]) is None
|
||||
assert model.calls == 0
|
||||
|
||||
|
||||
def test_doubled_literal_braces_still_render():
|
||||
middleware = _middleware(_StaticChatModel(), 'JSON: {{"a": 1}} {messages}')
|
||||
|
||||
prompt = middleware._build_summary_prompt([HumanMessage(content="hi", id="h1")])
|
||||
|
||||
assert prompt is not None
|
||||
assert 'JSON: {"a": 1}' in prompt
|
||||
assert "hi" in prompt
|
||||
|
||||
|
||||
def test_valid_template_still_compacts():
|
||||
model = _StaticChatModel(text="SUMMARY")
|
||||
middleware = _middleware(model, "{messages}")
|
||||
|
||||
result = middleware.compact_state(_state(), SimpleNamespace(context={}), force=True)
|
||||
|
||||
assert result is not None
|
||||
assert result.summary_text == "SUMMARY"
|
||||
assert model.calls == 1
|
||||
|
||||
|
||||
def test_unexpected_formatter_failure_is_not_swallowed():
|
||||
class BrokenTemplate(str):
|
||||
def format(self, *args, **kwargs):
|
||||
raise RuntimeError("unexpected formatter failure")
|
||||
|
||||
middleware = _middleware(_StaticChatModel(), BrokenTemplate("{messages}"))
|
||||
|
||||
with pytest.raises(RuntimeError, match="unexpected formatter failure"):
|
||||
middleware._build_summary_prompt([HumanMessage(content="hi", id="h1")])
|
||||
|
||||
|
||||
def test_render_warning_identifies_template_without_logging_content(caplog):
|
||||
template = "private configuration {messages.foo}"
|
||||
middleware = _middleware(_StaticChatModel(), template)
|
||||
|
||||
assert middleware._build_summary_prompt([HumanMessage(content="private history", id="h1")]) is None
|
||||
|
||||
assert middleware.release_policy_parameters()["summary_prompt_hash"] == canonical_hash(template)
|
||||
assert canonical_hash(template) in caplog.text
|
||||
assert template not in caplog.text
|
||||
assert "private history" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("template", "leaked_text", "error_type"),
|
||||
[
|
||||
("private {messages.private_token}", "private_token", "AttributeError"),
|
||||
("private {messages:secret_spec}", "secret_spec", "ValueError"),
|
||||
],
|
||||
)
|
||||
def test_render_warning_logs_error_type_without_exception_text(caplog, template, leaked_text, error_type):
|
||||
middleware = _middleware(_StaticChatModel(), template)
|
||||
|
||||
assert middleware._build_summary_prompt([HumanMessage(content="private history", id="h1")]) is None
|
||||
|
||||
assert canonical_hash(template) in caplog.text
|
||||
assert error_type in caplog.text
|
||||
assert leaked_text not in caplog.text
|
||||
assert "private history" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("summary_prompt", ["{messages.foo}", "{messages[missing]}"])
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
async def test_configured_agent_keeps_history_and_recovers_after_template_repair(monkeypatch, caplog, summary_prompt, asynchronous):
|
||||
summary_model = _StaticChatModel(text="SUMMARY")
|
||||
chat_model = _StaticChatModel(text="ordinary reply")
|
||||
monkeypatch.setattr(
|
||||
"deerflow.agents.middlewares.summarization_middleware.create_chat_model",
|
||||
lambda **kwargs: summary_model,
|
||||
)
|
||||
app_config = AppConfig.model_validate(
|
||||
{
|
||||
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
|
||||
"models": [
|
||||
{
|
||||
"name": "run-model",
|
||||
"use": "langchain_openai:ChatOpenAI",
|
||||
"model": "test-model",
|
||||
}
|
||||
],
|
||||
"memory": {"enabled": False},
|
||||
"summarization": {
|
||||
"enabled": True,
|
||||
"summary_prompt": summary_prompt,
|
||||
"trigger": {"type": "messages", "value": 4},
|
||||
"keep": {"type": "messages", "value": 2},
|
||||
"trim_tokens_to_summarize": 9999,
|
||||
},
|
||||
}
|
||||
)
|
||||
middleware = create_summarization_middleware(app_config=app_config, run_model_name="run-model", skip_memory_flush=True)
|
||||
assert middleware is not None
|
||||
graph = create_agent(
|
||||
model=chat_model,
|
||||
tools=[],
|
||||
middleware=[middleware],
|
||||
state_schema=ThreadState,
|
||||
checkpointer=InMemorySaver(),
|
||||
)
|
||||
config = {"configurable": {"thread_id": "template-render"}}
|
||||
original = _state()
|
||||
if asynchronous:
|
||||
first = await graph.ainvoke(original, config=config)
|
||||
second = await graph.ainvoke({"messages": [HumanMessage(content="continue", id="h3")]}, config=config)
|
||||
checkpoint = await graph.aget_state(config)
|
||||
else:
|
||||
first = graph.invoke(original, config=config)
|
||||
second = graph.invoke({"messages": [HumanMessage(content="continue", id="h3")]}, config=config)
|
||||
checkpoint = graph.get_state(config)
|
||||
|
||||
assert first["messages"][:-1] == original["messages"]
|
||||
assert second["messages"][:-2] == first["messages"]
|
||||
assert second["messages"][-1].content == "ordinary reply"
|
||||
assert checkpoint.values["messages"] == second["messages"]
|
||||
assert checkpoint.values["summary_text"] == original["summary_text"]
|
||||
assert summary_model.calls == 0
|
||||
assert chat_model.calls == 2
|
||||
warnings = [r for r in caplog.records if "Summarization template failed to render" in r.getMessage()]
|
||||
assert len(warnings) == 2
|
||||
|
||||
middleware.summary_prompt = "{messages}"
|
||||
next_turn = {"messages": [HumanMessage(content="continue after repair", id="h4")]}
|
||||
repaired = await graph.ainvoke(next_turn, config=config) if asynchronous else graph.invoke(next_turn, config=config)
|
||||
assert repaired["summary_text"] == "SUMMARY"
|
||||
assert summary_model.calls == 1
|
||||
assert chat_model.calls == 3
|
||||
assert "h1" not in {message.id for message in repaired["messages"]}
|
||||
Loading…
x
Reference in New Issue
Block a user