Skip to content

feat(bot): support multimodal OpenViking resource reads - #4593

Merged
qin-ctx merged 6 commits into
mainfrom
feat/bot_support_multi_ov_file
Sep 4, 2026
Merged

qin-ctx merged 6 commits into
mainfrom
feat/bot_support_multi_ov_file

Conversation

@yeshion23333

Copy link
Copy Markdown
Collaborator

Description

让 VikingBot 的 openviking_multi_read 能根据 OpenViking 资源类型返回适合模型使用的内容,同时保持现有文本读取行为不变。

本次改动不新增 OpenViking SDK 或 API,也不通过 user message 注入媒体内容。

Human Involvement

  • A human participated in the implementation or review loop
  • This PR was generated entirely by AI agents without human participation in the loop

Related Issue

无。

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change or feature
  • Documentation update
  • Refactoring
  • Performance improvement
  • Test update

Changes Made

  • 增加轻量的 MultimodalToolResult,让工具结果可以同时包含模型可消费的多模态内容和用于日志、事件及执行记录的纯文本表示。
  • openviking_multi_read 识别图片资源后,通过 SDK 下载原始字节,校验大小和文件签名,并将 PNG、JPEG、GIF、WebP 作为 tool message 中的 image_url 内容返回给模型。
  • 音频和视频资源复用 OpenViking SDK 的 read_content(level="overview") 获取已有语义理解结果,不增加额外下载、转写或媒体理解链路。
  • 普通文本资源继续走原有 Read 逻辑;同步工具执行入口仍返回纯文本,避免多模态对象扩散到非 Agent 调用路径。
  • 增加图片数量、单图大小及格式限制,并补充 Agent 循环、OpenViking 多资源读取和图片格式识别测试。

Testing

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have tested this on the following platforms:
    • Linux
    • macOS
    • Windows

已通过:

9 passed
ruff check: passed
ruff format --check: passed
git diff --check: passed

完整运行三个受影响测试文件时结果为 178 passed, 4 failed。4 个失败分别涉及既有 Compile 提示词、token usage 额外字段和 commit hook 参数断言,与本次多模态读取改动无关。

Checklist

  • My code follows the projects coding style
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Screenshots

不适用。

Additional Notes

  • 单次工具结果最多内联 4 张图片,单图上限为 10 MiB。
  • 音视频返回的是 OpenViking 已生成的 overview,不是 VikingBot 新生成的逐字稿。
  • 未跟踪的 diagrams/ 目录未包含在本 PR 中。

@now-ing

now-ing commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Code Review — PR #4593: feat(bot): support multimodal OpenViking resource reads

  • PR: feat(bot): support multimodal OpenViking resource reads (author: yeshion23333)
  • Base: upstream/main (f6d9dec) → head 00364a2d (5 commits: feat + 3 hardening fixes + 1 serialization fix)
  • Scope: 19 files, +990/−34 — bot-side multimodal tool results, media budgets, provider capability gating, Codex Responses adapter, shared media limit constant.

Overall assessment

Strong PR. The architecture is clean and the safety story is unusually thorough for this kind of feature:

  • Clean separation of "what the model sees" vs. "what everything else sees." MultimodalToolResult(text=..., content=[...]) with __str__ -> text means every non-model consumer — bus events, [RESULT] logs, Langfuse tool spans (output=str(result)), tools_used records, token accounting (cal_str_tokens(result_text)), legacy ToolRegistry.execute() — automatically gets the text-only representation. No base64 ever leaks into logs or telemetry (Langfuse inputs additionally go through redact_image_data_urls).
  • Faithful mirror of the server-side MCP read tool design. The bot's image path (stat preflight → per-file cap → aggregate cap → download → changed-after-size-check → magic-byte sniff → structured per-URI error) matches openviking/server/mcp_endpoint.py::read almost case-for-case. Consistency here makes the behavior predictable across the two read surfaces.
  • Defense in depth on token/byte explosion: per-image cap (3.75 MiB raw), count cap (4 images/call), per-call aggregate cap, and a request-level budget in AgentLoop that counts all inline media (including user-attached images) across the whole message list and demotes oldest tool media first ("prefer recent"). Byte accounting decodes base64 length back to raw bytes (_base64_data_url_bytes), so the same raw-byte budget applies at every layer — no 4/3 base64 inflation surprises.
  • Conservative capability gating. supports_tool_result_media defaults to False; enabled only for the two paths that were verified (Anthropic via LiteLLM, openai-codex). Gateways, mixed failover pairs, and unknown providers degrade to text plus an explanatory note for the model. Good failure mode.
  • Constant unification. Hoisting MAX_INLINE_TOOL_RESULT_MEDIA_BYTES = 3_932_160 into openviking/utils/media_limits.py and having the MCP server import it removes a duplicate definition.

I verified the security-sensitive paths on the server side: GET /api/v1/content/download runs the same validate_request_viking_uri(...) + service.fs.read_file_bytes(uri, ctx=ctx) pipeline as text reads, and read_file_bytes performs resolve_uri → _ensure_access(uri, ctx) → _read_path_visible before returning bytes. So the new bot-side download_bytes usage introduces no new ACL bypass or URI-injection surface at the server — the model-controlled URI flows through the same validators as the text-read path. The findings below are about client-side consistency and wire-format assumptions, not about a server-side hole.

Findings, ordered by severity. None of them block the PR in my view, but #1 and #2 deserve answers before merge.


Findings

1. [Medium] Root-key mode: image downloads bypass the per-user client scoping that read_content applies

VikingClient.read_content (bot/vikingbot/openviking_mount/ov_server.py) explicitly narrows the client for user-namespace URIs in root-key/trusted mode:

scoped_user_id = user_id or self._owner_user_id_for_uri(uri)
if scoped_user_id:
    client, should_close = await self._get_user_scoped_client(scoped_user_id)

The new image path in VikingMultiReadTool.read_single_uri calls client.stat(uri) and client.download_bytes(uri) on self.client directly, with no such scoping. VikingClient.stat/download_bytes delegate to the unscoped root client, and the server enforces _ensure_access against the requesting identity — which, for a root key, can see all user namespaces.

Scenario: a multi-tenant deployment in trusted (root-key) mode with user namespace isolation. The model calls openviking_multi_read(["viking://user/<other-user>/resources/diagram.png"]). The text path for the sibling URI .../notes.md would be routed through the owner-scoped client (and denied or scoped accordingly), but the image bytes come back with root visibility. The isolation that the text path implements client-side is silently not applied to images.

Suggested fix: route media downloads through the same scoping — e.g. add VikingClient.download_scoped(uri) that mirrors read_content's _owner_user_id_for_uri/_get_user_scoped_client logic — or document/verify that the server independently enforces per-user isolation for /api/v1/content/download regardless of the caller being root, in which case this is fail-closed and only a UX inconsistency (permission errors surface as generic "Error reading from Viking: ..."). Either way, please add a test for viking://user/<uid>/... image reads in root-key mode.

2. [Medium] Codex: function_call_output.output becomes a content-part list — verified only against a mocked client

_convert_tool_output_for_responses returns a list of input_text/input_image parts when the tool output contains images. The public OpenAI Responses API documents function_call_output.output as a string; some SDK/server versions accept content arrays, but the new test (test_codex_preserves_images_in_function_call_output) mocks openai.OpenAI, so it only proves payload construction, not that the deployed Codex backend accepts a non-string output.

Scenario: if the live Codex backend (or an older pinned version) validates output as a string, every image-bearing tool round fails with a 400, which is worse than not sending the image at all — the loop would surface the provider error rather than the graceful text fallback.

Suggested fix: confirm this was exercised against the real gpt-5.3-codex backend (a one-line "verified against " comment would be enough), and/or add a defensive downgrade: if the Responses call rejects the request, retry once with _stringify_response_payload(content). Alternatively document the minimum backend version in the PR description.

3. [Low–Medium] Anthropic gating uses the bot's keyword registry, which can diverge from actual LiteLLM routing

LiteLLMProvider.supports_tool_result_media gates on vikingbot's own find_by_model(model) (kw in model_lower substring match, so any model string containing "claude" → anthropic spec → True), while the actual message conversion is done by LiteLLM's Anthropic handler, which routes by prefix/get_provider_info. The _gateway is not None check correctly disables gateway setups, but two residual mismatches remain:

  • A model like openai/claude-... or a Claude served through a generic OpenAI-compatible api_base (not a registered gateway) would be classified "anthropic" while the wire format is OpenAI chat completions, which does not accept image_url parts inside tool messages.
  • The whole path relies on the pinned LiteLLM (>=1.83.7,<1.91.2) converting OpenAI-style tool-message image parts into Anthropic tool_result image blocks. That support exists in modern LiteLLM, but a regression inside the pin range would turn into runtime 400s rather than the graceful text fallback.

Suggested fix: derive the decision from the same resolution LiteLLM will actually use (model prefix, then get_provider_info), or keep the keyword registry but exclude explicitly prefixed models. A short comment stating "requires LiteLLM's anthropic tool-result image conversion" would help future bisects.

4. [Low] Media extension sets drift between bot and MCP server

Bot (ov_file.py) vs. server (mcp_endpoint.py):

kind server bot delta
audio .flac .m4a .mp3 .oga .ogg .wav .aac .ac3 .flac .m4a .mp3 .ogg .opus .wav bot misses .oga; adds .aac .ac3 .opus
video .avi .m4v .mkv .mov .mp4 .webm .avi .flv .mkv .mov .mp4 .webm .wmv bot misses .m4v; adds .flv .wmv

Concretely: an .m4v resource in the bot is classified as non-media and goes down the text-read path (level="read" over video bytes) instead of the intended overview path, while the server's MCP read correctly treats it as video. The extras in the bot are harmless (they route to overview). Since media_limits.py already exists as the shared constants module, hoisting the three extension sets there and importing on both sides would prevent future drift. Same for _uri_suffix/_mcp_uri_suffix, which are currently identical duplicates.

5. [Low] A/V overview errors are flattened by read_content's exception swallowing

VikingClient.read_content catches every exception and returns "". For the new audio/video branch, a 403 (permission denied), a 404, a server 500, and a legitimately empty overview all produce the same model-facing message: "No OpenViking textual overview is available for this audio resource." The model can't distinguish "retry" from "you're not allowed" from "there is nothing here."

Suggested fix: for the A/V branch, either call client.overview(uri) directly (letting the exception flow into the structured per-URI error path), or have read_content return/log the error type. Low priority — but it's the one place where the new error semantics are less informative than the rest of the PR.

6. [Low] Demotion is all-or-nothing, and user-message media is never demotable — recency preference inverts in that edge

_demote_historical_tool_media returns 0 and demotes nothing unless reclaimable history covers the full overflow, and it only ever considers role == "tool" messages. When the budget is mostly consumed by user-attached images (not demotable) and history tool media can't cover the overflow, the new image is dropped while older tool media stays inline — the opposite of the "prefer recent tool media" intent (this is the one commit-message/code mismatch I found).

Scenario: user attaches a 2 MiB photo; a later round's openviking_multi_read returns a 2.5 MiB image; overflow ≈ 0.75 MiB; no tool-message candidates exist → new image dropped with the generic "would exceed the inline media limit" note, which doesn't tell the model that user attachments consumed the budget.

Suggested fix (pick one): (a) allow partial demotion — reclaim what's available, then attach if under budget; (b) mention in the drop note that existing media (including user attachments) occupies most of the budget. (a) also fixes the general case where reclaimable < overflow for other reasons. Low severity since the failure mode is still safe and explained.

7. Nits

  • VikingMultiReadTool._MAX_INLINE_MEDIA_BYTES = MAX_INLINE_TOOL_RESULT_MEDIA_BYTES binds at class-definition time. Runtime tuning of media_limits.MAX_INLINE_TOOL_RESULT_MEDIA_BYTES (or monkeypatching the module, as loop.py's tests do) silently won't affect the tool. Reading the module constant at call time, or a one-line comment, would prevent surprises.
  • The constant name MAX_INLINE_TOOL_RESULT_MEDIA_BYTES is now also used to budget user-attached images at the request level; slightly misleading, though the comment explains the intent.
  • OpenVikingPostCallHook (skill-read branch) converts a multimodal result to str when appending "Related Experiences". Correct today (SKILL.md reads are text), but if a skill read ever becomes multimodal, media is silently dropped there. A # text-only by design comment would prevent a future foot-gun.
  • _is_tool_result_success(MultimodalToolResult) is True even when every URI inside a multi-read failed (str() starts with "Multi-read results for ...", per-URI failures are ERROR: lines mid-text). Pre-existing semantics for multi-read, unchanged by this PR — noting only for completeness.
  • offset/limit are silently ignored for image URIs (the range note is correctly dropped via item_range_note); harmless, but the tool description could say so.
  • Good catch preserving legacy text serialization in 00364a2d (test_codex_preserves_legacy_text_tool_output_serialization asserts the "firstsecond" concatenation) — that's exactly the regression guard this adapter needed.

Test coverage gaps

The new tests are good quality and cover the core matrix: provider gating (both directions), parallel-tool-result budget, consecutive-round demotion, per-image attachment, TypeScript-stays-text, aggregate byte cap, A/V overview routing, sniff rejection, adapter text-serialization preservation, and adapter image conversion. Gaps I'd like to see closed (roughly in priority order):

  1. Permission-denied image read: stat/download_bytes raising a 403 → structured "Error reading from Viking: ..." per-URI result (currently untested; this is also the path finding Bump actions/download-artifact from 4 to 7 #1 rides on).
  2. Root-key cross-user URI (viking://user/<uid>/resources/x.png) — see finding Bump actions/download-artifact from 4 to 7 #1.
  3. Size-changed-after-check branch (len(data) > size) — the "Image changed after its size was checked" message has no test.
  4. _MAX_INLINE_IMAGES = 4 count cap — the ">4 images in one call" message has no test.
  5. User-attached media + tool media overflow — verifies the non-demotable-history edge in finding fix: fix_build #6.
  6. Extension/MIME mismatch — .png file whose bytes are actually JPEG: currently inlined as image/jpeg (sniff wins over extension). Probably intended, but worth pinning in a test.
  7. All-or-nothing demotion branch (reclaimable_bytes < bytes_needed → nothing demoted, new media dropped).
  8. A/V overview empty/error — the "No OpenViking textual overview" path (ties to finding Bump github/codeql-action from 3 to 4 #5).

Verdict

Approve-with-questions. The design is right, the guardrails are layered, and the text-path regression risk is well contained (legacy serialization is explicitly tested; Tool.execute return type widening is backward compatible; hooks were audited — only OpenVikingPostCallHook touches results and it was fixed in this PR). Please address finding #1 (user-scoping for image downloads in root-key mode — at minimum confirm server-side enforcement) and finding #2 (live-backend verification for list-typed function_call_output.output) before merge; the rest can be follow-ups.

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

整体方向没问题,但当前还有一个必须修复的问题:图片新路径没有复用文本读取的 user scoping,导致 root-key/trusted bot 下同一个工具对文本和图片的身份语义不同。先修这个再合;另外当前 CI 仍是 BLOCKED。

Comment thread bot/vikingbot/agent/tools/ov_file.py Resolved
@qin-ctx
qin-ctx merged commit 6020c62 into main Sep 4, 2026
5 of 6 checks passed
@qin-ctx
qin-ctx deleted the feat/bot_support_multi_ov_file branch September 4, 2026 06:52
@github-project-automation github-project-automation Bot moved this from Backlog to Done in OpenViking project Sep 4, 2026
skloxo pushed a commit to skloxo/OpenVikingStudio that referenced this pull request Sep 4, 2026
)

* feat(bot): support multimodal OpenViking reads

* fix(bot): harden multimodal OpenViking reads

* fix(bot): enforce multimodal request budgets

* fix(bot): prefer recent tool media

* fix(vlm): preserve text tool output serialization

* fix(bot): scope image reads to resource owner
skloxo pushed a commit to skloxo/OpenVikingStudio that referenced this pull request Nov 9, 2026
)

* feat(bot): support multimodal OpenViking reads

* fix(bot): harden multimodal OpenViking reads

* fix(bot): enforce multimodal request budgets

* fix(bot): prefer recent tool media

* fix(vlm): preserve text tool output serialization

* fix(bot): scope image reads to resource owner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants