Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions backend/test/unit/middlewares/test_summary_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
from langchain.agents.middleware.types import ExtendedModelResponse, ModelRequest, ModelResponse
from langchain_core.exceptions import ContextOverflowError
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage, get_buffer_string

from yuxi.modules.agents.runtime.middlewares.summary import YuxiSummarizationMiddleware, create_summary_middleware
from yuxi.modules.agents.tool_results import SAVED_MEDIA_KEY
from yuxi.modules.workspace.runtime_paths import workdir_runtime_paths

WORKDIR_PATH = "/home/user/workspace/projects/11111111-1111-4111-8111-111111111111"
Expand Down Expand Up @@ -1055,6 +1057,53 @@ async def test_compaction_preserves_and_archives_multimodal_content(tmp_path) ->
assert message.content == original


@pytest.mark.unit
@pytest.mark.parametrize("overflow", [False, True], ids=["large-tool-result", "overflow-tail"])
async def test_compaction_keeps_saved_paths_on_their_original_images(tmp_path, overflow: bool) -> None:
"""压缩合并多个文本块后,落盘路径仍只指向对应的截图。"""
blocks = [
{"type": "text", "text": "第一段" * 3000},
{"type": "text", "text": "第二段"},
{"type": "image", "base64": "YQ==", "mime_type": "image/png"},
{"type": "image_url", "image_url": {"url": "https://example.com/unsaved.png"}},
{"type": "image", "base64": "Yg==", "mime_type": "image/png"},
]
saved = [
{"index": 2, "path": f"{WORKDIR_PATH}/outputs/tool_media/first.png", "mime_type": "image/png"},
{"index": 4, "path": f"{WORKDIR_PATH}/outputs/tool_media/second.png", "mime_type": "image/png"},
]
message = ToolMessage(content=blocks, tool_call_id="screenshot", additional_kwargs={SAVED_MEDIA_KEY: saved})

backend = FilesystemBackend(root_dir=tmp_path, virtual_mode=True)
if overflow:
middleware, _ = _make_compressing_middleware(backend)
middleware._trigger_tokens = 100_000
middleware.tool_result_offload_token_limit = None
history = [HumanMessage("第一轮"), AIMessage("已完成"), HumanMessage("第二轮")]
call = AIMessage("", tool_calls=[{"name": "observe", "id": "screenshot", "args": {}}])
attempts = []

async def handler(request):
"""首次模拟 provider 溢出,记录重试时实际发送的截图消息。"""
attempts.append(request.messages[-1])
if len(attempts) == 1:
raise ContextOverflowError("context overflow")
return ModelResponse(result=[AIMessage("ok")])

await middleware.awrap_model_call(_model_request([*history, call, message]), handler)
_, compacted = attempts
else:
[compacted] = await _compact_messages([message], backend, token_limit=1)

records = compacted.additional_kwargs[SAVED_MEDIA_KEY]
assert [record["index"] for record in records] == [1, 3]
assert [(record["path"], compacted.content[record["index"]]) for record in records] == [
(saved[0]["path"], blocks[2]),
(saved[1]["path"], blocks[4]),
]
assert [record["index"] for record in message.additional_kwargs[SAVED_MEDIA_KEY]] == [2, 4]


@pytest.mark.unit
async def test_failed_media_archive_aborts_summary_before_model(monkeypatch, compression_events) -> None:
backend = _MemoryBackend()
Expand Down
86 changes: 83 additions & 3 deletions backend/test/unit/middlewares/test_tool_media_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@
from types import SimpleNamespace

import pytest
from langchain.agents.middleware.types import ToolCallRequest
from langchain_core.messages import ToolMessage
from langchain.agents.middleware.types import ModelRequest, ToolCallRequest
from langchain_core.messages import AIMessage, ToolMessage
from langchain_openai import ChatOpenAI
from langgraph.types import Command

from yuxi.modules.agents.runtime.middlewares import ToolErrorGuardMiddleware
from yuxi.modules.agents.runtime.middlewares.model_input import ImageInputCompatibilityMiddleware
from yuxi.modules.agents.runtime.middlewares.tool_media import SAVED_MEDIA_KEY, ToolMediaPersistMiddleware, create_tool_media_middleware
from yuxi.modules.extensions.tools.builtin.ocr_parse_file import ocr_parse_file
from yuxi.modules.workspace.paths import ensure_user_workspace, user_workspace_dir
from yuxi.modules.workspace.runtime_paths import WORKSPACE_PATH

Expand Down Expand Up @@ -89,7 +92,8 @@ async def test_persists_image_block_and_annotates_path(middleware):
assert isinstance(result, ToolMessage)
digest = hashlib.sha256(b"fake-png-bytes").hexdigest()[:16]
path = f"{_MEDIA_DIR}/computer_observe-{digest}.png"
assert (user_workspace_dir("media-user") / "projects/p1/outputs/tool_media" / f"computer_observe-{digest}.png").read_bytes() == b"fake-png-bytes"
saved_file = user_workspace_dir("media-user") / "projects/p1/outputs/tool_media" / f"computer_observe-{digest}.png"
assert saved_file.read_bytes() == b"fake-png-bytes"
# image 块保留供模型视觉使用,末尾追加路径注记。
assert result.content[0] == {"type": "text", "text": '{"status":"executed"}'}
assert result.content[1] == {"type": "image", "base64": _PNG_B64, "mime_type": "image/png"}
Expand All @@ -109,6 +113,82 @@ async def test_sync_wrap_persists_image_block(middleware):
assert result.content[-1]["text"].startswith("[Tool result images saved to sandbox]")


@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("name", ["computer_observe", "read_file"])
async def test_persisted_image_uses_source_or_saved_path_for_ocr(middleware, name, asynchronous):
"""工具截图使用落盘路径;read_file 已知的源路径仍优先。"""
image = _image_message().model_copy(update={"name": name})
source_path = f"{WORKSPACE_PATH}/projects/p1/input.png"
if name == "read_file":
image.additional_kwargs["read_file_path"] = source_path
result = await _persist(middleware, _request(name=name), image)
[record] = result.additional_kwargs[SAVED_MEDIA_KEY]
expected = source_path if name == "read_file" else record["path"]
request = ModelRequest(model=SimpleNamespace(), messages=[result], tools=[ocr_parse_file])

def reject(_request):
"""模拟文本模型拒绝有效的图片输入。"""
raise ValueError("This model does not support image input")

async def async_reject(request):
"""通过异步模型入口返回相同的拒图结果。"""
return reject(request)

bridge = ImageInputCompatibilityMiddleware()
response = await bridge.awrap_model_call(request, async_reject) if asynchronous else bridge.wrap_model_call(request, reject)
[call] = response.result[0].tool_calls
assert (call["name"], call["args"]) == ("ocr_parse_file", {"file_path": expected})


@pytest.mark.parametrize("bridge_images", [False, True])
async def test_partial_ocr_of_saved_images_only_resends_remaining_image(middleware, bridge_images):
"""同一工具结果中仅第一张图请求过 OCR 时,模型和下次回退都只收到第二张图。"""
image = _image_message()
image.content.append({"type": "image", "base64": _JPG_B64, "mime_type": "image/jpeg"})
result = await _persist(middleware, _request(), image)
first, second = result.additional_kwargs[SAVED_MEDIA_KEY]
history = [
result,
AIMessage(content="", tool_calls=[{"name": "ocr_parse_file", "args": {"file_path": first["path"]}, "id": "ocr-1"}]),
ToolMessage(content="first screenshot text", tool_call_id="ocr-1"),
]
model = ChatOpenAI(model="test-model", api_key="test-key", base_url="https://example.com/v1") if bridge_images else SimpleNamespace()

def reject(request):
"""从原生和桥接视图分别核对模型实际收到的图片。"""
images = []
for message in request.messages:
images.extend(block["base64"] for block in message.content_blocks if block["type"] == "image")
assert images == [_JPG_B64]
raise ValueError("This model does not support image input")

request = ModelRequest(model=model, messages=history, tools=[ocr_parse_file])
response = ImageInputCompatibilityMiddleware().wrap_model_call(request, reject)
[call] = response.result[0].tool_calls
assert (call["name"], call["args"]) == ("ocr_parse_file", {"file_path": second["path"]})
assert [b["base64"] for b in result.content_blocks if b["type"] == "image"] == [_PNG_B64, _JPG_B64]


async def test_ocr_ignores_saved_records_without_a_matching_image_path():
"""旧消息缺少有效落盘记录时保留图片,并提示没有可供 OCR 的路径。"""
message = _image_message()
message.additional_kwargs[SAVED_MEDIA_KEY] = [
{"index": 0, "path": "/text-block.png"},
{"index": 2, "path": "/missing-block.png"},
{"index": 1, "path": None},
]

def reject(request):
"""确认提供方仍收到原工具结果。"""
assert request.messages[0] is message
raise ValueError("This model does not support image input")

request = ModelRequest(model=SimpleNamespace(), messages=[message], tools=[ocr_parse_file])
response = ImageInputCompatibilityMiddleware().wrap_model_call(request, reject)
assert response.result[0].tool_calls == []
assert "没有可供 OCR" in response.result[0].content


async def test_rebuilds_command_result_in_place(middleware):
"""Command 结果只替换本次调用的 ToolMessage,其他消息保持原样。"""
other = ToolMessage(content="other", tool_call_id="other-call")
Expand Down
45 changes: 38 additions & 7 deletions backend/yuxi/modules/agents/runtime/middlewares/model_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langchain_openai import ChatOpenAI

_TOOL_IMAGE_USER_TEXT = "Images returned by read_file are attached below. Inspect them when answering."
from yuxi.modules.agents.tool_results import SAVED_MEDIA_KEY

_TOOL_IMAGE_USER_TEXT = "Images returned by tools are attached below. Inspect them when answering."
_IMAGE_ERROR_TERMS = ("image", "vision", "multimodal", "multi-modal")
_REJECTION_TERMS = (
"does not support",
Expand Down Expand Up @@ -84,12 +86,15 @@ def flush_pending_images() -> None:
bridged_messages.append(message)
continue

image_blocks = [block for block in message.content_blocks if block.get("type") == "image"]
image_path = message.additional_kwargs.get("read_file_path")
if not isinstance(image_path, str) or not image_path:
message = _prepare_saved_images_for_ocr(message, index, latest_ocr_call_by_path, image_paths)
blocks = message.content_blocks
image_blocks = [block for block in blocks if block.get("type") == "image"]
if not image_blocks:
bridged_messages.append(message)
continue

image_path = message.additional_kwargs.get("read_file_path")
ocr_fallback_requested = isinstance(image_path, str) and latest_ocr_call_by_path.get(image_path, -1) > index
if isinstance(image_path, str) and image_path and not ocr_fallback_requested:
image_paths.setdefault(image_path, None)
Expand All @@ -98,15 +103,13 @@ def flush_pending_images() -> None:
continue
if not ocr_fallback_requested:
pending_images.extend(image_blocks)
text = "\n".join(
block["text"] for block in message.content_blocks if block.get("type") == "text" and isinstance(block.get("text"), str)
)
text = "\n".join(block["text"] for block in blocks if block.get("type") == "text" and isinstance(block.get("text"), str))
bridged_messages.append(
message.model_copy(
update={
"content": text
or (
f"read_file returned {len(image_blocks)} image(s). "
f"{message.name or 'Tool'} returned {len(image_blocks)} image(s). "
+ (
"OCR fallback was requested for this image."
if ocr_fallback_requested
Expand All @@ -123,6 +126,34 @@ def flush_pending_images() -> None:
return request.override(messages=bridged_messages), list(image_paths)


def _prepare_saved_images_for_ocr(
message: ToolMessage, index: int, latest_ocr_call_by_path: dict[str, int], image_paths: dict[str, None]
) -> ToolMessage:
"""按落盘时的原始块位置收集 OCR 路径,仅从模型视图移除已请求的图。"""
records = message.additional_kwargs.get(SAVED_MEDIA_KEY)
if not isinstance(records, list) or not isinstance(message.content, list):
return message

processed = set()
for record in records:
if not isinstance(record, dict):
continue
position, path = record.get("index"), record.get("path")
if type(position) is not int or not 0 <= position < len(message.content) or not isinstance(path, str) or not path:
continue
block = message.content[position]
if not isinstance(block, dict) or block.get("type") != "image":
continue
if latest_ocr_call_by_path.get(path, -1) > index:
processed.add(position)
else:
image_paths.setdefault(path, None)

if not processed:
return message
return message.model_copy(update={"content": [block for pos, block in enumerate(message.content) if pos not in processed]})


def _ocr_tool_enabled(request: ModelRequest) -> bool:
"""以本次模型请求的工具集决定是否允许 OCR 回退。"""
return any(getattr(tool, "name", None) == "ocr_parse_file" for tool in request.tools)
Expand Down
30 changes: 28 additions & 2 deletions backend/yuxi/modules/agents/runtime/middlewares/summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
DEFAULT_SUMMARY_TOOL_RESULT_TOKEN_LIMIT,
DEFAULT_YUXI_SUMMARY_PROMPT,
)
from yuxi.modules.agents.tool_results import SAVED_MEDIA_KEY
from yuxi.modules.models.chat import load_chat_model, resolve_chat_model_spec

_APPROX_CHARS_PER_TOKEN = 4
Expand Down Expand Up @@ -150,14 +151,18 @@ async def _awrap_model_call_with_compaction(
request.state, effective_messages, compacted_messages, cutoff_index
)
if overflow_triggered:
preserved_messages, _ = await _aclip_overflow_tail(
clipped_messages, _ = await _aclip_overflow_tail(
preserved_messages,
self._backend,
keep=self._lc_helper.keep,
max_input_tokens=self._get_profile_limits(),
token_counter=self.token_counter,
large_tool_results_prefix=self._large_tool_results_prefix,
)
preserved_messages = [
_reindex_saved_media(original, clipped) if original is not clipped and isinstance(original, ToolMessage) else clipped
for original, clipped in zip(preserved_messages, clipped_messages, strict=True)
]
file_path = new_event["file_path"]
response = await handler(request.override(messages=[*new_messages, *preserved_messages]))
return ExtendedModelResponse(
Expand Down Expand Up @@ -472,7 +477,28 @@ async def _replace_tool_message_content(
if isinstance(message.content, list):
non_text = [block for block in message.content if isinstance(block, dict) and block.get("type") not in {"text", "output_text"}]
preview_content = [{"type": "text", "text": preview_content}, *non_text]
return message.model_copy(update={"content": preview_content, "additional_kwargs": additional_kwargs})
compacted = message.model_copy(update={"content": preview_content, "additional_kwargs": additional_kwargs})
return _reindex_saved_media(message, compacted)


def _reindex_saved_media(original: ToolMessage, compacted: ToolMessage) -> ToolMessage:
"""两种压缩都保持图片顺序;按该顺序将原始落盘记录移到压缩后的块位置。"""
saved = original.additional_kwargs.get(SAVED_MEDIA_KEY)
if not isinstance(saved, list) or not saved or not isinstance(original.content, list):
return compacted
old_images = [i for i, block in enumerate(original.content_blocks) if block["type"] == "image"]
new_images = [i for i, block in enumerate(compacted.content_blocks) if block["type"] == "image"]
positions = dict(zip(old_images, new_images, strict=False))
remapped = []
for record in saved:
index = record.get("index") if isinstance(record, dict) else None
if type(index) is int and index in positions:
block = original.content[index]
if isinstance(block, dict) and block.get("type") == "image":
remapped.append({**record, "index": positions[index]})
if remapped == saved:
return compacted
return compacted.model_copy(update={"additional_kwargs": {**compacted.additional_kwargs, SAVED_MEDIA_KEY: remapped}})


def _generic_tool_result_preview(text: str, max_chars: int) -> str:
Expand Down
2 changes: 1 addition & 1 deletion docs/agents/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
| 11 | `NetworkRetryMiddleware` | 网络错误按预算、其他可重试模型错误按次数重试,耗尽后抛出异常 |
| 12 | 工具审批 middleware | 默认模式下审批 Project 外的文件写入和命令执行;当前 Project 内的写/编辑自动放行 |
| 13 | `RuntimeAuthorizationMiddleware` | 准备模型输入时刷新资源,实际请求前同步投影;返回时先于审批复查身份 |
| 14 | `ImageInputCompatibilityMiddleware` | 桥接工具读取图片与模型输入格式;必要时回退 OCR |
| 14 | `ImageInputCompatibilityMiddleware` | 桥接工具图片。模型拒绝图片且已启用 OCR 时,使用读取的原文件或工具已保存的截图进行识别 |
| 15 | `TokenUsageMiddleware` | 记录授权和图片转换后的近似上下文及主模型实际用量 |

模型重试耗尽后,异常进入 Run 失败通道,持久化 `failed` 状态与错误原因;已有部分输出保留错误元数据。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@ ImageInputCompatibilityMiddleware 声明 tools 会让 create_agent 无条件向

after_model 仍先复查授权,再产生审批等待点;网络重试保持在授权与图片处理之外,每次重试重新授权。同步和异步图片回退使用相同工具判定。

回退沿用 `read_file` 的原文件路径。对于截图等工具,路径来自媒体落盘中间件写入的逐图记录。一条结果可以含多张图,模型视图按图排除后来已请求 OCR 的内容,保留其余图片供模型查看或继续识别。历史消息保留原图。

普通工具结果压缩和上下文溢出后的裁剪都会合并文本块。构造压缩视图时,摘要中间件同步更新保存记录中的图片位置,使每个路径仍指向原来的那张图。

## 替代方案

- 保留无条件注册、只在工具执行时拒绝,会向模型展示不可用能力并产生无意义调用。
- 再从配置或权限快照独立判定会重复解释授权,无法保证与本次实际请求一致。
- 从工具回复的文字提取路径无法区分普通文本和已保存的文件,也无法将每条路径与对应图片可靠配对。

## 后果

Expand All @@ -30,3 +35,5 @@ OCR 未启用或被运行时授权隐藏时,图片回退明确说明当前能
同步/异步 unit 覆盖启用和禁用两种工具集。生产中间件装配的组合测试独立记录最终模型请求工具,与回退生成的调用比较,覆盖注册了工具但授权过滤掉它的情况。授权、重试、工具异常隔离和构图的既有 unit 同时验证。相关 unit 集合 79 passed。独立进程恢复旧装配后,组合用例 1 failed、1 passed,失败对应模型工具已被授权隐藏但回退仍生成调用。未调用外部模型供应商或真实 ARQ Agent 链路。

关联修复:[xerrors/Yuxi PR #1093](https://github.com/xerrors/Yuxi/pull/1093)。

工具媒体测试将截图写入临时 Workdir,在模型拒绝图片时检查 OCR 调用的文件路径,并覆盖两张图中仅一张已请求 OCR 的后续模型输入。