perf(client): skip values serialization in chat() (#8518)

* perf: 跳过 chat 中未使用的快照序列化

* fix: 保留绑定到其他客户端的 stream 委托

* fix: 保留包装后的 stream 调用
This commit is contained in:
Hazenix 2026-11-23 20:23:37 +08:00 committed by GitHub
parent 0877d9d4c9
commit 1e72197a5a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 87 additions and 26 deletions

View File

@ -26,6 +26,7 @@ import uuid
from collections.abc import Generator, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from types import MethodType
from typing import Any, Literal
from langchain.agents import create_agent
@ -873,6 +874,19 @@ class DeerFlowClient:
A caller that opened its own scope with ``request_trace_context`` keeps
that id; otherwise the turn gets a fresh one.
"""
yield from self._stream_with_trace(message, thread_id=thread_id, emit_values=True, overrides=kwargs)
# Keep the built-in implementation identifiable when the public method is replaced.
_default_stream = stream
def _stream_with_trace(
self,
message: str,
*,
thread_id: str | None,
emit_values: bool,
overrides: dict[str, Any],
) -> Generator[StreamEvent, None, None]:
# Resolve the id once, without mutating the caller's context.
trace_id = get_current_trace_id() or generate_trace_id()
@ -885,7 +899,7 @@ class DeerFlowClient:
# Per-step set/reset keeps LangGraph node execution and its log
# records inside the binding while returning control to the caller
# with the ContextVar restored.
inner = self._stream_turn(message, thread_id=thread_id, **kwargs)
inner = self._stream_turn(message, emit_values, thread_id=thread_id, **overrides)
_EXHAUSTED = object()
try:
while True:
@ -916,6 +930,8 @@ class DeerFlowClient:
def _stream_turn(
self,
message: str,
emit_values: bool,
/,
*,
thread_id: str | None = None,
**kwargs,
@ -940,15 +956,15 @@ class DeerFlowClient:
``chat()`` already does this for you.
Tool calls and tool results are still emitted once per logical
message. ``values`` events continue to carry full state snapshots
after each graph node finishes. On resumed threads, historical messages
remain in those snapshots, but are not emitted again as per-message
events or counted in this turn's usage. AI text already delivered via
the ``messages`` stream is **not** re-synthesized from the snapshot to
avoid duplicate deliveries. When a later node replaces a delivered AI
message under the same id and appends to its text (a guard's stop
notice), only the appended text is emitted, as one more delta for that
id; new ``additional_kwargs`` arrive as a metadata-only follow-up.
message. When ``emit_values`` is enabled, ``values`` events carry full
state snapshots after each graph node finishes. On resumed threads,
historical messages remain in those snapshots, but are not emitted again
as per-message events or counted in this turn's usage. AI text already
delivered via the ``messages`` stream is **not** re-synthesized from the
snapshot to avoid duplicate deliveries. When a later node appends text
to an already-delivered AI message under the same id (a guard's stop
notice), only that text is emitted as a new delta for the same id.
New ``additional_kwargs`` arrive as a metadata-only follow-up.
Why not reuse Gateway's ``run_agent``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -984,6 +1000,7 @@ class DeerFlowClient:
Args:
message: User message text.
emit_values: Serialize and emit full state snapshots for stream consumers.
thread_id: Thread ID for conversation context. Auto-generated if None.
**kwargs: Override client defaults (model_name, thinking_enabled,
plan_mode, subagent_enabled, recursion_limit). Trusted embedded
@ -1301,25 +1318,24 @@ class DeerFlowClient:
elif isinstance(msg, ToolMessage):
yield self._tool_message_event(msg)
# Emit a values event for each state snapshot
yield StreamEvent(
type="values",
data={
"title": chunk.get("title"),
"summary_text": chunk.get("summary_text"),
"messages": [self._serialize_message(m) for m in messages],
"artifacts": chunk.get("artifacts", []),
},
)
if emit_values:
yield StreamEvent(
type="values",
data={
"title": chunk.get("title"),
"summary_text": chunk.get("summary_text"),
"messages": [self._serialize_message(m) for m in messages],
"artifacts": chunk.get("artifacts", []),
},
)
yield StreamEvent(type="end", data={"usage": cumulative_usage})
def chat(self, message: str, *, thread_id: str | None = None, **kwargs) -> str:
"""Send a message and return the final text response.
Convenience wrapper around :meth:`stream` that accumulates delta
``messages-tuple`` events per ``id`` and returns the text of the
**last** AI message to complete. Intermediate AI messages (e.g.
Accumulates ``messages-tuple`` deltas per ``id`` and returns the text of
the **last** AI message to complete. Intermediate AI messages (e.g.
planner drafts) are discarded — only the final id's accumulated
text is returned. Use :meth:`stream` directly if you need every
delta as it arrives.
@ -1333,8 +1349,15 @@ class DeerFlowClient:
The accumulated text of the last AI message, or empty string
if no AI text was produced.
"""
stream = self.stream
# Callable wrappers can forward method attributes, including __class__.
if type(stream) is MethodType and stream.__self__ is self and stream.__func__ is DeerFlowClient._default_stream:
events = self._stream_with_trace(message, thread_id=thread_id, emit_values=False, overrides=kwargs)
else:
events = stream(message, thread_id=thread_id, **kwargs)
answer = _AIMessageAccumulator()
for event in self.stream(message, thread_id=thread_id, **kwargs):
for event in events:
answer.observe(event)
return answer.answer()

View File

@ -1343,14 +1343,50 @@ class TestChat:
"""The CLI and chat must agree on interleaved deltas and metadata-only events."""
from deerflow.tui.cli import _RunOutcome
with patch.object(client, "stream", return_value=iter(events)):
assert client.chat("q", thread_id="t-shared-answer") == expected
with patch.object(client, "stream", return_value=iter(events)) as stream:
assert client.chat("q", thread_id="t-shared-answer", thinking_enabled=True) == expected
stream.assert_called_once_with("q", thread_id="t-shared-answer", thinking_enabled=True)
outcome = _RunOutcome()
for event in events:
outcome.observe(event)
assert outcome.answer() == expected
def test_uses_stream_bound_to_another_client(self, client, mock_app_config):
from langchain.agents import create_agent
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
with patch("deerflow.client.get_app_config", return_value=mock_app_config):
delegate = DeerFlowClient()
outer_model = FakeMessagesListChatModel(responses=[AIMessage(content="OUTER MODEL")])
delegate_model = FakeMessagesListChatModel(responses=[AIMessage(content="DELEGATE MODEL")])
with (
patch.object(client, "_ensure_agent"),
patch.object(client, "_agent", create_agent(model=outer_model, state_schema=ThreadState)),
patch.object(delegate, "_ensure_agent"),
patch.object(delegate, "_agent", create_agent(model=delegate_model, state_schema=ThreadState)),
patch.object(client, "stream", delegate.stream),
):
assert client.chat("q", thread_id="t-delegated-stream") == "DELEGATE MODEL"
def test_uses_wrapper_around_bound_stream(self, client):
from langchain.agents import create_agent
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from wrapt import FunctionWrapper
model = FakeMessagesListChatModel(responses=[AIMessage(content="answer")])
graph = create_agent(model=model, state_schema=ThreadState)
wrapper = MagicMock(side_effect=lambda wrapped, instance, args, kwargs: wrapped(*args, **kwargs))
with (
patch.object(client, "_ensure_agent"),
patch.object(client, "_agent", graph),
patch.object(client, "stream", FunctionWrapper(client.stream, wrapper)),
):
assert client.chat("q", thread_id="t-wrapped-stream") == "answer"
wrapper.assert_called_once()
def test_returns_last_message(self, client):
"""chat() returns the last AI message text."""
ai1 = AIMessage(content="thinking...", id="ai-1")
@ -1397,11 +1433,13 @@ class TestChat:
with (
patch.object(client, "_ensure_agent"),
patch.object(client, "_agent", graph),
patch.object(client, "_serialize_message", wraps=client._serialize_message) as serialize_message,
):
result = client.chat("q", thread_id="t-loop-stop")
assert result.startswith("Checking again.")
assert "[FORCED STOP]" in result
serialize_message.assert_not_called()
def test_empty_response(self, client):
"""chat() returns empty string if no AI message produced."""