diff --git a/README.md b/README.md index bc7606bf28..ffcf3520af 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ Each guide is the full reference for its topic. Open the one you need. | boxd machines, bounded output copies and cleanup retries | [boxd sandbox provider](backend/packages/harness/deerflow/community/boxd_sandbox/README.md) | | BytePlus veFaaS cloud sandboxes, SigV4 control plane and optional TOS mounts | [veFaaS sandbox provider](backend/packages/harness/deerflow/community/vefaas_sandbox/README.md) | | Skills, built-in tools, script workflows, Claude Code integration | [Skills & Tools](docs/guide/skills-and-tools.md) | -| MCP servers | [MCP Server](docs/guide/mcp.md) | +| MCP servers and model-specific image handling | [MCP Server](docs/guide/mcp.md), [Image results](backend/docs/MCP_SERVER.md#image-results-and-model-capabilities) | | Sub-agents, task delegation and optional SQLite checkpoint history | [Sub-Agents](docs/guide/subagents.md), [Inspect one thread's child history](docs/guide/subagents.md#inspect-one-threads-child-history), [Tool restrictions](docs/guide/subagents.md#tool-restrictions) | | Agent teams, SQLite/PostgreSQL persistence and shutdown behavior | [Agent teams extension](examples/deerflow-extension-agent-teams/README.md) | | Long-term memory | [Long-Term Memory](docs/guide/memory.md) | diff --git a/backend/docs/MCP_SERVER.md b/backend/docs/MCP_SERVER.md index 34a64c8062..8370676ded 100644 --- a/backend/docs/MCP_SERVER.md +++ b/backend/docs/MCP_SERVER.md @@ -14,6 +14,20 @@ DeerFlow supports configurable MCP servers and skills to extend its capabilities 3. Configure each server’s command, arguments, and environment variables as needed. 4. Restart the application to load and register MCP tools. +## Image results and model capabilities + +For a model configured with `supports_vision: false`, image blocks returned by +MCP tools become text placeholders in the model request. This covers standard +`image` blocks, legacy `image_url` blocks, and native OpenAI Responses +`input_image` blocks. Other result text remains available, and the original +images stay in tool messages and checkpoints. Models configured with +`supports_vision: true` continue to receive images. Direct SDK factories without +a model capability profile retain their existing image handling. + +When the compatibility middleware rewrites history, the OpenAI Responses API +request replays the projected messages. After a switch to a text-only model, +this lets the provider see the placeholders and surrounding tool text. + ## Stdio Working Directory Set `cwd` when a stdio server needs to resolve its entrypoint or data files diff --git a/backend/packages/harness/deerflow/agents/lead_agent/agent.py b/backend/packages/harness/deerflow/agents/lead_agent/agent.py index 6adfd44f11..c7cad43a7a 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/agent.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/agent.py @@ -756,7 +756,7 @@ def build_middlewares( # after every built-in content transform so it sanitizes the near-final # message list, and outer of the MODEL_PHYSICAL extension anchor so # extensions placed there keep their final-request guarantee. - middlewares.append(ModelContentCompatibilityMiddleware()) + middlewares.append(ModelContentCompatibilityMiddleware(supports_vision=model_config.supports_vision if model_config is not None else True)) # Inject custom middlewares before ClarificationMiddleware if custom_middlewares: diff --git a/backend/packages/harness/deerflow/agents/middlewares/AGENTS.md b/backend/packages/harness/deerflow/agents/middlewares/AGENTS.md index a09bcc762f..fca3ddf9b5 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/AGENTS.md +++ b/backend/packages/harness/deerflow/agents/middlewares/AGENTS.md @@ -53,6 +53,9 @@ make test-blocking-io - **State and UI keep the raw result.** The model-facing projection of a tool result (metadata envelope, shortening) is built per request. Receipt hashes and the UI read the stored value. +- **Content compatibility rewrites replay Responses history.** Clear OpenAI + response chain IDs from the model request copy so the provider sees the + projected messages. Checkpoints retain the original content and IDs. - **Persisted metadata is untrusted.** Checkpoints written by older versions and by direct integrations contain malformed values. Every history reader validates what it reads, and a bad value must not abort compaction or a model call. diff --git a/backend/packages/harness/deerflow/agents/middlewares/model_content_compatibility_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/model_content_compatibility_middleware.py index 3ad2811599..ed255fa8ee 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/model_content_compatibility_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/model_content_compatibility_middleware.py @@ -28,7 +28,11 @@ rewriting the *request view* at the model boundary: placeholder — local images are meant to reach the model through the ``view_image`` tool, not as unresolvable URLs. -Placeholder text comes from ``resource_placeholder_text`` in +Configured text-only models also receive text placeholders for standard, legacy, +and native OpenAI Responses image blocks. Original messages retain their image +payloads so a later vision-capable turn can still consume them. + +Resource-link placeholder text comes from ``resource_placeholder_text`` in ``deerflow.tools.resource_placeholder`` — the same formatter the conversion layer uses — so a thread healed at read time shows the model the exact placeholder shape a fresh conversion would have produced. The location segment @@ -84,6 +88,7 @@ from langchain_anthropic import ChatAnthropic from langchain_core.messages import AnyMessage from deerflow.agents.middlewares.input_sanitization_middleware import neutralize_untrusted_tags +from deerflow.agents.middlewares.tool_call_args import without_response_chain_id from deerflow.tools.resource_placeholder import model_visible_location, resource_placeholder_text logger = logging.getLogger(__name__) @@ -132,7 +137,7 @@ def _accepts_http_file_urls(model: Any) -> bool: return isinstance(model, ChatAnthropic) -def _sanitize_block(block: Any, model: Any) -> Any: +def _sanitize_block(block: Any, model: Any, supports_vision: bool) -> Any: """Return *block* unchanged, or its text-placeholder replacement. Identity is the unchanged signal for the caller: the same object comes back @@ -141,6 +146,8 @@ def _sanitize_block(block: Any, model: Any) -> Any: if not isinstance(block, dict): return block block_type = block.get("type") + if block_type in ("image", "image_url", "input_image") and not supports_vision: + return {"type": "text", "text": "[Image omitted: the selected model does not support image inputs]"} if block_type == "file": # URL-sourced file blocks are rejected by Chat Completions whenever a # ``url`` KEY is present — langchain-core raises even for an empty @@ -175,7 +182,7 @@ def _sanitize_block(block: Any, model: Any) -> Any: return block -def _sanitize_message(message: AnyMessage, model: Any) -> AnyMessage: +def _sanitize_message(message: AnyMessage, model: Any, supports_vision: bool) -> AnyMessage: """Return *message* unchanged, or a copy with incompatible blocks replaced. Role-agnostic on purpose: any message with list-form content can carry a @@ -184,18 +191,18 @@ def _sanitize_message(message: AnyMessage, model: Any) -> AnyMessage: content = message.content if not isinstance(content, list): return message - patched = [_sanitize_block(block, model) for block in content] + patched = [_sanitize_block(block, model, supports_vision) for block in content] if all(new is old for new, old in zip(patched, content, strict=True)): return message return message.model_copy(update={"content": patched}) -def _sanitize_messages(messages: list[AnyMessage], model: Any) -> list[AnyMessage] | None: +def _sanitize_messages(messages: list[AnyMessage], model: Any, supports_vision: bool) -> list[AnyMessage] | None: """Rewrite *messages* for the model request, or ``None`` when nothing changed.""" updated: list[AnyMessage] = [] changed = False for message in messages: - patched = _sanitize_message(message, model) + patched = _sanitize_message(message, model, supports_vision) changed = changed or patched is not message updated.append(patched) return updated if changed else None @@ -205,11 +212,18 @@ class ModelContentCompatibilityMiddleware(AgentMiddleware[AgentState]): """Downgrades persisted URL-sourced content blocks the model cannot accept. Request-view-only rewrite at the model boundary; see the module docstring - for the failure mode and the contract. Stateless and config-free aside - from the selected model's serializer capabilities, which gate only the - http(s) file-URL preserve; the downgrade itself is unconditional. + for the failure mode and the contract. Configured text-only models also + receive text placeholders for image blocks. When model capabilities are + unknown, image inputs retain the existing serializer-based behavior. """ + def __init__(self, *, supports_vision: bool = True) -> None: + super().__init__() + self._supports_vision = supports_vision + + def release_policy_parameters(self) -> dict[str, object]: + return {"supports_vision": self._supports_vision} + @override def wrap_model_call( self, @@ -227,9 +241,10 @@ class ModelContentCompatibilityMiddleware(AgentMiddleware[AgentState]): # Pure in-memory rewrite: no sandbox or file I/O, so it stays on the loop. return await handler(self._sanitize_request(request)) - @staticmethod - def _sanitize_request(request: ModelRequest) -> ModelRequest: - patched = _sanitize_messages(request.messages, request.model) + def _sanitize_request(self, request: ModelRequest) -> ModelRequest: + patched = _sanitize_messages(request.messages, request.model, self._supports_vision) if patched is None: return request - return request.override(messages=patched) + # An OpenAI response ID references the provider's original history. + # Drop every chain ID so the adapter sends the projected history. + return request.override(messages=[without_response_chain_id(message) for message in patched]) diff --git a/backend/packages/harness/deerflow/agents/middlewares/tool_call_args.py b/backend/packages/harness/deerflow/agents/middlewares/tool_call_args.py index c22463a3f4..f655497fb5 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/tool_call_args.py +++ b/backend/packages/harness/deerflow/agents/middlewares/tool_call_args.py @@ -99,7 +99,7 @@ def rewrite_messages_tool_call_args(messages: list[Any], replacement_for: Replac updated.append(patched) if not changed: return None - return [_without_response_chain_id(message) for message in updated] + return [without_response_chain_id(message) for message in updated] def _duplicated_call_ids(tool_calls: Sequence[Any]) -> set[str]: @@ -174,7 +174,7 @@ def pair_tool_call_results(messages: Sequence[Any]) -> list[ToolCallOccurrence]: return occurrences -def _without_response_chain_id(message: Any) -> Any: +def without_response_chain_id(message: Any) -> Any: """Drop an OpenAI ``resp_`` response id so the adapter replays history instead of chaining to it.""" if not isinstance(message, AIMessage): return message diff --git a/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py index cf7d587abc..8e0a039a31 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py @@ -895,7 +895,7 @@ def build_subagent_runtime_middlewares( # checkpoints are never written. from deerflow.agents.middlewares.model_content_compatibility_middleware import ModelContentCompatibilityMiddleware - middlewares.append(ModelContentCompatibilityMiddleware()) + middlewares.append(ModelContentCompatibilityMiddleware(supports_vision=model_config.supports_vision if model_config is not None else True)) # SubagentDateContextMiddleware (#4781) — inject framework-owned temporal # context before the first model call without registering the lead agent's diff --git a/backend/tests/test_model_content_compatibility_middleware.py b/backend/tests/test_model_content_compatibility_middleware.py index ccb85a91ec..6c9bb4c58b 100644 --- a/backend/tests/test_model_content_compatibility_middleware.py +++ b/backend/tests/test_model_content_compatibility_middleware.py @@ -550,3 +550,153 @@ class TestAsyncParity: prepared = await _run_async(ModelContentCompatibilityMiddleware(), request) assert prepared is request + + +@pytest.mark.parametrize("supports_vision", [False, True], ids=["text-only", "vision"]) +@pytest.mark.parametrize( + "image", + [ + pytest.param({"type": "image", "base64": "iVBORw0KGgo=", "mime_type": "image/png"}, id="standard"), + pytest.param({"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo="}, id="native-responses"), + ], +) +def test_responses_api_replays_projected_image_history(supports_vision, image): + import json + + import httpx + from langchain.agents import create_agent + from langchain_openai import ChatOpenAI + from langgraph.checkpoint.memory import InMemorySaver + + payloads = [] + + def respond(request): + assert request.url.path == "/v1/responses" + payloads.append(json.loads(request.content)) + return httpx.Response( + 200, + json={ + "id": "resp_followup", + "object": "response", + "model": "gpt-4.1", + "created_at": 0, + "status": "completed", + "output": [{"type": "message", "id": "msg_followup", "role": "assistant", "status": "completed", "content": [{"type": "output_text", "text": "Done", "annotations": []}]}], + }, + ) + + result = _tool_message([{"type": "text", "text": "Screenshot captured"}, image]) + call = AIMessage(content="", tool_calls=[{"name": "some_tool", "args": {}, "id": result.tool_call_id}], response_metadata={"id": "resp_call"}) + previous = AIMessage(content="The page was captured", response_metadata={"id": "resp_vision"}) + followup = HumanMessage(content="Describe the screenshot") + config = {"configurable": {"thread_id": "responses-image-history"}} + + with httpx.Client(transport=httpx.MockTransport(respond)) as client: + model = ChatOpenAI(model="gpt-4.1", api_key="test-key", http_client=client, use_responses_api=True, use_previous_response_id=True) + graph = create_agent(model, middleware=[ModelContentCompatibilityMiddleware(supports_vision=supports_vision)], checkpointer=InMemorySaver()) + graph.update_state(config, {"messages": [HumanMessage(content="Capture the page"), call, result, previous]}, as_node="model") + graph.invoke({"messages": [followup]}, config=config) + stored = graph.get_state(config).values["messages"] + + assert stored[1].response_metadata == {"id": "resp_call"} + assert stored[2].content == [{"type": "text", "text": "Screenshot captured"}, image] + assert stored[3].response_metadata == {"id": "resp_vision"} + + (payload,) = payloads + if supports_vision: + assert payload["previous_response_id"] == "resp_vision" + assert payload["input"] == [{"type": "message", "role": "user", "content": followup.content}] + else: + assert "previous_response_id" not in payload + (output,) = [item for item in payload["input"] if item.get("type") == "function_call_output"] + assert output["call_id"] == result.tool_call_id + assert output["output"] == [ + {"type": "input_text", "text": "Screenshot captured"}, + {"type": "input_text", "text": "[Image omitted: the selected model does not support image inputs]"}, + ] + + +@pytest.mark.parametrize( + "block", + [ + pytest.param({"type": "image", "base64": "synthetic-image-payload", "mime_type": "image/png"}, id="standard"), + pytest.param({"type": "image_url", "image_url": {"url": "data:image/png;base64,synthetic-image-payload"}}, id="legacy"), + pytest.param({"type": "input_image", "image_url": "data:image/png;base64,synthetic-image-payload"}, id="native-responses"), + ], +) +async def test_text_only_image_projection_is_transient_and_idempotent(block): + from deerflow_extension_api import collect_release_policies + + message = _tool_message([{"type": "text", "text": "Image description"}, block]) + request = _model_request([message]) + middleware = ModelContentCompatibilityMiddleware(supports_vision=False) + prepared = await _run_async(middleware, request) + assert prepared.messages[0].content[0] == message.content[0] + assert prepared.messages[0].content[1]["type"] == "text" + assert "synthetic-image-payload" not in str(prepared.messages[0].content) + assert message.content[1] == block + assert request.state["messages"][0] is message + assert await _run_async(middleware, prepared) is prepared + assert collect_release_policies([middleware]) != collect_release_policies([ModelContentCompatibilityMiddleware(supports_vision=True)]) + + +@pytest.mark.parametrize("chain", ["lead", "subagent"]) +@pytest.mark.parametrize("supports_vision", [False, True]) +def test_mcp_image_result_reaches_configured_model_as_supported_content(chain, supports_vision): + import httpx + from langchain.agents import create_agent + from langchain_core.tools import StructuredTool + from langchain_openai import ChatOpenAI + from langgraph.checkpoint.memory import InMemorySaver + from mcp.types import CallToolResult, ImageContent, TextContent + + from deerflow.config.app_config import AppConfig + from deerflow.config.sandbox_config import SandboxConfig + from deerflow.mcp.tools import _convert_call_tool_result + + app_config = AppConfig(models=[{"name": "configured", "use": "langchain_openai:ChatOpenAI", "model": "configured", "supports_vision": supports_vision}], sandbox=SandboxConfig(use="test")) + if chain == "lead": + from deerflow.agents.lead_agent.agent import build_middlewares + + middlewares = build_middlewares(config={"configurable": {}}, model_name="configured", app_config=app_config) + else: + from deerflow.agents.middlewares.tool_error_handling_middleware import build_subagent_runtime_middlewares + + middlewares = build_subagent_runtime_middlewares(app_config=app_config, model_name="configured") + compatibility = next(m for m in middlewares if isinstance(m, ModelContentCompatibilityMiddleware)) + image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lH0AAAAASUVORK5CYII=" + content, artifact = _convert_call_tool_result(CallToolResult(content=[TextContent(type="text", text="Screenshot captured"), ImageContent(type="image", data=image, mimeType="image/png")])) + + def capture(): + """Capture a screenshot through MCP.""" + return content, artifact + + payloads = [] + + def respond(request): + import json + + payload = json.loads(request.content) + payloads.append(payload) + if len(payloads) == 1: + message = {"role": "assistant", "content": None, "tool_calls": [{"id": "call_capture", "type": "function", "function": {"name": "capture", "arguments": "{}"}}]} + else: + images = [block for message in payload["messages"] if isinstance(message.get("content"), list) for block in message["content"] if block.get("type") == "image_url"] + if images and not supports_vision: + return httpx.Response(400, json={"error": {"message": "This model does not support image inputs", "type": "invalid_request_error"}}) + assert bool(images) is supports_vision + assert "Screenshot captured" in str(payload["messages"]) + message = {"role": "assistant", "content": "Image result handled"} + return httpx.Response( + 200, json={"id": "chatcmpl-test", "object": "chat.completion", "created": 0, "model": "configured", "choices": [{"index": 0, "message": message, "finish_reason": "tool_calls" if len(payloads) == 1 else "stop"}]} + ) + + with httpx.Client(transport=httpx.MockTransport(respond)) as client: + model = ChatOpenAI(model="configured", api_key="synthetic-test-key", http_client=client, max_retries=0, use_responses_api=False) + graph = create_agent(model, tools=[StructuredTool.from_function(capture, response_format="content_and_artifact")], middleware=[compatibility], checkpointer=InMemorySaver()) + config = {"configurable": {"thread_id": "mcp-image"}} + result = graph.invoke({"messages": [HumanMessage(content="Capture the page")]}, config=config) + assert result["messages"][-1].content == "Image result handled" + stored = graph.get_state(config).values["messages"] + assert next(message for message in stored if isinstance(message, ToolMessage)).content == content + assert len(payloads) == 2