Hyeonsang Cho cb24bc2699
perf(middleware): stop checkpointing view_image base64 payloads (#5014)
ViewImageMiddleware injected the viewed-image message from before_model and
removed it again from after_model. before_model, model, and after_model are
separate graph nodes, so every view_image turn cost two extra nodes and two
state writes, and up to 20MB of base64 sat in two checkpoints for the duration
of the model call. A run interrupted in that window (user cancel, restart)
stranded the payload in history for good.

Inject from wrap_model_call instead, so the message lives only in
ModelRequest.messages and is never returned as a state update:

- before_model/after_model (and the async pair) are replaced by
  wrap_model_call/awrap_model_call; _remove_image_context_messages and its
  RemoveMessage bookkeeping go with them. The async hook keeps the existing
  asyncio.to_thread offload for the file read and base64 encode.
- _should_inject_image_message gates on request.messages rather than state, so
  the decision is made against what the model will actually see.
- _inject sweeps this middleware's own message out of the request before
  rebuilding it. Dropping after_model also drops the cleanup it did on every
  call, so without the sweep a payload stranded by an older interrupted run
  would ride along in every later request for the life of the thread. Matching
  requires both the reserved id prefix and the server-owned marker, and Gateway
  strips that marker from client input, so a user message is never dropped.

Chain position is unchanged, and wrap_model_call nests first-registered
outermost, so TokenBudgetMiddleware still sees the image message and enforces
the input budget against it.

Checkpoint rows that already hold a stranded payload keep it on disk. It is
inert -- never sent to a provider, and strip_data_url_image_blocks keeps it off
the wire -- and reclaiming it would mean keeping the node this change removes.

tests/test_view_image_middleware.py is rewritten around the new hook (43
tests): sync/async at unit and graph level, the stranded sweep, and the
client-message protection. Docs: middleware chain entry 23, Vision Support, the
middleware-execution-flow hook matrix and diagrams, and the
strip_data_url_image_blocks docstring.
2026-08-27 09:12:37 +08:00

149 lines
5.6 KiB
Python

"""Canonical serialization for LangChain / LangGraph objects.
Provides a single source of truth for converting LangChain message
objects, Pydantic models, and LangGraph state dicts into plain
JSON-serialisable Python structures.
Consumers: ``deerflow.runtime.runs.worker`` (SSE publishing) and
``app.gateway.routers.threads`` (REST responses).
"""
from __future__ import annotations
from typing import Any
def serialize_lc_object(obj: Any) -> Any:
"""Recursively serialize a LangChain object to a JSON-serialisable dict."""
if obj is None:
return None
if isinstance(obj, (str, int, float, bool)):
return obj
if isinstance(obj, dict):
return {k: serialize_lc_object(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [serialize_lc_object(item) for item in obj]
# Pydantic v2
if hasattr(obj, "model_dump"):
try:
return obj.model_dump()
except Exception:
pass
# Pydantic v1 / older objects
if hasattr(obj, "dict"):
try:
return obj.dict()
except Exception:
pass
# Interrupt is a __slots__ class — no model_dump/dict/__dict__, so it
# would reach str() and produce a malformed payload.
try:
from langgraph.types import Interrupt
except ImportError:
pass
else:
if isinstance(obj, Interrupt):
return serialize_lc_object(
{
"value": obj.value,
"id": getattr(obj, "id", None),
}
)
# Last resort
try:
return str(obj)
except Exception:
return repr(obj)
def serialize_channel_values(channel_values: dict[str, Any]) -> dict[str, Any]:
"""Serialize channel values, stripping internal LangGraph keys.
Only ``__pregel_*`` keys are removed — ``__interrupt__`` is deliberately
preserved so the LangGraph SDK can detect interrupt events from values
chunks (see issue #3595).
"""
result: dict[str, Any] = {}
for key, value in channel_values.items():
if key.startswith("__pregel_"):
continue
result[key] = serialize_lc_object(value)
return result
def strip_data_url_image_blocks(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Remove ``data:``-scheme ``image_url`` blocks from *hide_from_ui* messages.
The history and run-wait endpoints return checkpoint-persisted messages to
the frontend. ``ViewImageMiddleware`` now keeps its base64 image payloads
inside the model request, but threads checkpointed by earlier versions still
hold them in ``hide_from_ui`` human messages — these are internal model
context and must not be sent over the wire (huge response bodies, no UI
value).
Only content blocks of type ``image_url`` whose URL starts with ``data:``
are stripped. Text blocks, ``https://`` image URLs, and non-hidden
messages are left untouched so that message ordering and count are
preserved.
"""
result: list[dict[str, Any]] = []
for msg in messages:
if not isinstance(msg, dict):
result.append(msg)
continue
# Only touch messages explicitly flagged as hidden from the UI.
additional_kwargs = msg.get("additional_kwargs")
if not (isinstance(additional_kwargs, dict) and additional_kwargs.get("hide_from_ui") is True):
result.append(msg)
continue
content = msg.get("content")
if not isinstance(content, list):
result.append(msg)
continue
# Filter out image_url blocks with data: scheme.
filtered = [block for block in content if not (isinstance(block, dict) and block.get("type") == "image_url" and isinstance(block.get("image_url"), dict) and str(block["image_url"].get("url", "")).startswith("data:"))]
result.append({**msg, "content": filtered})
return result
def serialize_channel_values_for_api(channel_values: dict[str, Any]) -> dict[str, Any]:
"""Serialize channel values and strip base64 image data from messages.
Convenience wrapper combining :func:`serialize_channel_values` with
:func:`strip_data_url_image_blocks`. Use this in all REST endpoints
that return channel values to the frontend so that ``data:``-scheme
base64 image payloads are never sent over the wire.
"""
result = serialize_channel_values(channel_values)
if isinstance(result.get("messages"), list):
result["messages"] = strip_data_url_image_blocks(result["messages"])
return result
def serialize_messages_tuple(obj: Any) -> Any:
"""Serialize a messages-mode tuple ``(chunk, metadata)``."""
if isinstance(obj, tuple) and len(obj) == 2:
chunk, metadata = obj
return [serialize_lc_object(chunk), metadata if isinstance(metadata, dict) else {}]
return serialize_lc_object(obj)
def serialize(obj: Any, *, mode: str = "") -> Any:
"""Serialize LangChain objects with mode-specific handling.
* ``messages`` — obj is ``(message_chunk, metadata_dict)``
* ``values`` — obj is the full state dict; ``__pregel_*`` keys stripped and
base64 ``data:`` image blocks dropped from hide_from_ui messages
* everything else — recursive ``model_dump()`` / ``dict()`` fallback
"""
if mode == "messages":
return serialize_messages_tuple(obj)
if mode == "values":
# ``values`` snapshots stream the full state to the frontend, so they
# must drop base64 image payloads the same way the REST endpoints do.
return serialize_channel_values_for_api(obj) if isinstance(obj, dict) else serialize_lc_object(obj)
return serialize_lc_object(obj)