Skip to content

fix(hermes): handle Responses API input items, multimodal prompts and tool truncation - #2031

Open
mlubbad wants to merge 2 commits into
openlit:mainfrom
mlubbad:fix/hermes-responses-multimodal-truncation
Open

mlubbad wants to merge 2 commits into
openlit:mainfrom
mlubbad:fix/hermes-responses-multimodal-truncation

Conversation

@mlubbad

@mlubbad mlubbad commented Nov 28, 2026 •

Copy link
Copy Markdown

Issue number: Closes #2030

Change description:

Fixes three content-capture edge cases in the Hermes Agent observer plugin (plugins/hermes/__init__.py) and syncs the embedded CLI marketplace copy via cli/scripts/sync-plugins.sh:

  1. Responses API (codex_responses) input items: Parses role-less function_call / custom_tool_call, function_call_output / custom_tool_call_output, and reasoning items in request["body"]["input"] into OTel GenAI assistant (tool_call / reasoning) and tool (tool_call_response) messages instead of falling back to empty user text messages.
  2. Multimodal user_message on turn_start(): Formats user_message via _message("user", ...) instead of format_input_message("user", ...) so multimodal content-block lists emit structured parts without copying base64 image payloads or Python repr strings onto invoke_agent hermes spans.
  3. Tool span truncation: Applies truncate_content() to gen_ai.tool.call.arguments and gen_ai.tool.call.result in tool_call() so OpenlitConfig.max_content_length is honored consistently across turn, LLM, and tool spans.

Verified with pytest -q plugins/hermes/tests against both ./sdk/python and openlit==1.45.0 (72 passed), plus cli/scripts/sync-plugins.sh parity check.

Checklist

If your change doesn't seem to apply, please leave them unchecked.

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Summary by Sourcery

Improve Hermes observability by accurately representing Responses API content, safely handling multimodal prompts, and enforcing configurable content-capture controls.

Bug Fixes:

  • Correct Hermes tracing of Responses API reasoning, tool calls, and tool outputs as structured GenAI messages.
  • Preserve structured multimodal user prompts while excluding embedded image data from captured spans.
  • Honor content-length limits for tool arguments, results, and captured Responses API content.

Enhancements:

  • Gate Hermes content capture on the coding content-capture mode so non-full modes export metadata without message or tool bodies.

Tests:

  • Add coverage for Responses API items, multimodal prompts, content truncation, and content-capture modes.

Chores:

  • Keep the marketplace Hermes plugin synchronized with the primary plugin implementation.

@mlubbad
mlubbad requested a review from a team as a code owner November 28, 2026 11:24
@mlubbad
mlubbad deployed to release-notes November 28, 2026 11:24 — with GitHub Actions Active
@sourcery-ai

sourcery-ai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Normalize and truncate tool arguments, extract readable text from block outputs, and map role-less Responses API calls, outputs, and reasoning into GenAI messages.

  • plugins/hermes/__init__.py L100-123, L144-158, L206-266 (+4 small edits)

Apply the coding content-capture setting throughout observer hooks and span creation so message and tool bodies are exported only in full mode.

  • plugins/hermes/__init__.py L622-625 (+7 small edits)

Format turn-start user content as structured message parts and truncate captured tool arguments and results to the configured content limit.

  • plugins/hermes/__init__.py L572-579

Tests

Test Responses API item mapping, argument and result truncation, multimodal turn prompts, and capture-mode suppression and registration.

  • plugins/hermes/tests/test_openlit_plugin.py L610-732, L885, L963-976

Mirror the main plugin tests in the CLI marketplace test suite to verify that the synchronized copy behaves identically.

  • cli/internal/coding/install/marketplace/plugins/hermes/tests/test_openlit_plugin.py L610-732, L885, L963-976

Lock files and vendored code

Synchronize the embedded CLI marketplace Hermes plugin with the main implementation so both copies share the same capture and input-handling behavior.

  • cli/internal/coding/install/marketplace/plugins/hermes/__init__.py L100-123, L144-158, L206-266 (+13 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix Hermes Responses API capture, multimodal prompts, and tool truncation

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Preserve Responses API tool calls, tool outputs, and reasoning as structured GenAI messages.
• Capture multimodal turn prompts without copying image payloads into spans.
• Honor content-length limits on tool spans and add regression tests for all three fixes.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed gate, message conversion, LLM span population, and tool span population implement one bounded end-to-end behavior: exporting Hermes execution telemetry.
  • The CLI marketplace copy is a distribution variant of the same integration, not an independent functional scope.
  • Responses item conversion feeds the same Hermes telemetry export capability as the gate and span population changes; it does not create a separate user-facing model or tool capability.
Sources

plugins/hermes/init.py[100-103]

def _coding_capture_allows_content() -> bool:
    """Honor ``OPENLIT_CODING_CONTENT_CAPTURE`` when set; only ``full`` permits message/tool bodies."""
    mode = (os.getenv("OPENLIT_CODING_CONTENT_CAPTURE") or "full").strip().lower()
    return mode == "full"
Behavioral complexity 🟡 Medium 🧩 Compatibility cases, Interacting branches

  • Before, the existing OpenTelemetry capture flag directly enabled content paths and tool values were not consistently bounded here.
  • After, capture requires two environment conditions, is rechecked at hook time, and tool content is normalized and truncated.
  • The new correctness conditions are consistent enforcement across registration, hook selection, turn, LLM, and tool paths while preserving configured length limits.
Sources

plugins/hermes/init.py[100-103]

def _coding_capture_allows_content() -> bool:
    """Honor ``OPENLIT_CODING_CONTENT_CAPTURE`` when set; only ``full`` permits message/tool bodies."""
    mode = (os.getenv("OPENLIT_CODING_CONTENT_CAPTURE") or "full").strip().lower()
    return mode == "full"

plugins/hermes/init.py[622-626]

    capture = (
        os.getenv("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "").lower() == "true"
        and _coding_capture_allows_content()
    )
    observer = Observer(trace.get_tracer_provider(), capture_content=capture)
Potential damage 🔴 High 🩹 Confidentiality

  • If the new policy check or truncation path is wrong, sensitive prompts, reasoning, tool arguments, or tool results could be exported to the telemetry backend.
  • Reverting stops new exports, but already-exported telemetry requires retention cleanup or deletion; no automatic repair path is shown.
  • Reverting the plugin prevents further incorrect content export.
  • Previously exported bodies require backend deletion or retention remediation, so recovery is partial rather than automatic.
Sources

plugins/hermes/init.py[100-103]

def _coding_capture_allows_content() -> bool:
    """Honor ``OPENLIT_CODING_CONTENT_CAPTURE`` when set; only ``full`` permits message/tool bodies."""
    mode = (os.getenv("OPENLIT_CODING_CONTENT_CAPTURE") or "full").strip().lower()
    return mode == "full"
Assessed commit 29a61c9
Diagram

graph TD
  LLM["LLM request"] --> Items["Responses items"] --> Messages["GenAI messages"] --> Spans["OTel spans"]
  Turn["Turn start"] --> Parts["Multimodal parts"] --> Messages
  Tool["Tool call"] --> Cap["Length cap"] --> Spans
Loading
High-Level Assessment

Extending the existing message formatter and reusing its tool-call handling is proportionate to these capture fixes. A separate Responses API serialization pipeline would add duplication without a clear benefit for the supported items.

Files changed (4) +202 / -6

Bug fix (2) +88 / -6
__init__.pyMirror Hermes content-capture fixes in the CLI marketplace +44/-3

Mirror Hermes content-capture fixes in the CLI marketplace

• Syncs the embedded plugin with the Responses API item parser, multimodal turn-prompt formatting, and length-limited tool attributes. Keeps CLI-installed behavior aligned with the root plugin.

cli/internal/coding/install/marketplace/plugins/hermes/init.py

__init__.pyCorrect Hermes input formatting and tool-span truncation +44/-3

Correct Hermes input formatting and tool-span truncation

• Maps role-less Responses API tool calls, outputs, and reasoning to GenAI message parts. Formats multimodal turn prompts through the existing block formatter and truncates tool arguments and results before setting span attributes.

plugins/hermes/init.py

Tests (2) +114 / -0
test_openlit_plugin.pyMirror Hermes content-capture regression tests +57/-0

Mirror Hermes content-capture regression tests

• Syncs tests for structured Responses API inputs, omission of image payloads from turn spans, and configured tool-content truncation.

cli/internal/coding/install/marketplace/plugins/hermes/tests/test_openlit_plugin.py

test_openlit_plugin.pyCover Responses inputs, multimodal prompts, and tool limits +57/-0

Cover Responses inputs, multimodal prompts, and tool limits

• Adds regression tests for structured function-call inputs and outputs, image-data omission from turn spans, and max-content-length enforcement on tool attributes.

plugins/hermes/tests/test_openlit_plugin.py

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Model tool arguments evade content limits ✓ Resolved

Resolving commit: 29a61c9

Resolution reason
Added _tool_arguments helper that parses arguments and applies truncate_content to the serialized
form, returning {"raw": truncated} when truncation occurs. _tool_call_parts (used by the
function_call path in _responses_input_item) now calls _tool_arguments instead of using parsed JSON
directly, and the custom_tool_call path and _content_parts tool_use path also go through
_tool_arguments. So oversized valid-JSON arguments are truncated before being placed in the
tool_call part. A regression test (test_model_tool_call_arguments_respect_max_content_length) covers
the oversized case in both plugin copies, and the marketplace copy is kept in sync.
Description
_responses_input_item passes valid JSON tool-call arguments to _tool_call_parts, which parses
them into an object without applying truncate_content. When content capture is enabled for a
Responses API request, _set_llm_content serializes that entire object into the model span even if
max_content_length is set, so large or sensitive argument values remain in telemetry.


Informational

2. Null tool results appear empty ✓ Resolved

Resolving commit: 29a61c9

Resolution reason
The post-finding commit removes the None-to-"" conversion in tool_call: it now records
truncate_content(str(kwargs.get("result"))), so a None result is again serialized as "None" (the
prior behavior). A regression test
(test_tool_call_respects_max_content_length_and_preserves_none_result) asserts the "None" value.
This is the same fix as the suggested prompt in effect, applied in both plugin copies, though the
suggested prompt's regression-test requirement is met via a test extension in the same commit.
Description
tool_call now converts a None result to "" before passing it to truncate_content, rather
than recording the previous str(result) value of "None". When a tool returns None, its
captured result is indistinguishable from an empty-string result on the tool span.

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display > Comment parts

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai

sourcery-ai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit 29a61c9

#2030 Bug: Hermes plugin drops Responses API tool/reasoning items, stringifies multimodal user_message, and skips tool truncation · 3 of 3 met

# Requirement Status Notes
1 Map role-less Responses API function/custom tool calls, outputs, and reasoning to assistant/tool GenAI messages. ✅ Met _responses_input_item() handles these item types, and _input_messages() dispatches role-less items to it.
2 Format turn_start() user_message content blocks as structured parts without exporting image payloads. ✅ Met turn_start() calls _message("user", ...); _content_parts() records non-text blocks by type without copying their data.
3 Apply truncate_content() to gen_ai.tool.call.arguments and gen_ai.tool.call.result. ✅ Met tool_call() truncates both attributes before setting them.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="plugins/hermes/__init__.py" line_range="176-201" />
<code_context>
+def _responses_input_item(item: dict[str, Any]) -> dict[str, Any] | None:
</code_context>
<issue_to_address>
**Responses content bypasses capture mode**

When `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true` while `OPENLIT_CODING_CONTENT_CAPTURE` is `metadata_only` or `minimal`, hermes’s Responses-item parser adds tool arguments, tool results, and reasoning to input messages, but the capture setup only checks `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` and does not enforce `OPENLIT_CODING_CONTENT_CAPTURE`. With content capture enabled and coding capture set to `metadata_only` or `minimal`, those bodies reach exported spans despite the configured mode.

Gate these body-bearing message parts on the configured full capture mode before adding them to exported spans.

Also at `cli/internal/coding/install/marketplace/plugins/hermes/__init__.py:176-201`.
</issue_to_address>

### Comment 2
<location path="plugins/hermes/__init__.py" line_range="184" />
<code_context>
+        call = {
+            "id": item.get("call_id") or item.get("id") or "",
+            "name": item.get("name") or "",
+            "arguments": arguments,
+        }
+        return {"role": "assistant", "parts": _tool_call_parts([call])}
</code_context>
<issue_to_address>
**Tool arguments exceed the content limit**

When content capture is enabled and a valid JSON tool argument exceeds `max_content_length`, `_tool_call_parts()` parses the arguments without truncating them, and `_set_llm_content()` serializes the full message into `gen_ai.input.messages`; oversized arguments are exported in full.

Enforce `max_content_length` on the serialized message content, including parsed tool arguments, before exporting it.

Also at `cli/internal/coding/install/marketplace/plugins/hermes/__init__.py:184`, `cli/internal/coding/install/marketplace/plugins/hermes/__init__.py:186`, `plugins/hermes/__init__.py:185-186`.
</issue_to_address>

### Comment 3
<location path="plugins/hermes/__init__.py" line_range="179" />
<code_context>
+def _responses_input_item(item: dict[str, Any]) -> dict[str, Any] | None:
+    """OTel GenAI message for a role-less Responses API input item, or None for chat messages."""
+    kind = item.get("type")
+    if kind in ("function_call", "custom_tool_call"):
+        arguments = item.get("arguments") if kind == "function_call" else item.get("input")
+        call = {
</code_context>
<issue_to_address>
**Shell calls disappear from captured history**

When a Responses input contains a role-less `local_shell_call` or its corresponding output item, `_responses_input_item()` does not handle these items, so `_input_messages()` falls back to an empty user message and drops the shell command and output from captured history.

Handle role-less `local_shell_call` and its output item in `_responses_input_item()`.
</issue_to_address>

### Comment 4
<location path="plugins/hermes/__init__.py" line_range="180-184" />
<code_context>
+    """OTel GenAI message for a role-less Responses API input item, or None for chat messages."""
+    kind = item.get("type")
+    if kind in ("function_call", "custom_tool_call"):
+        arguments = item.get("arguments") if kind == "function_call" else item.get("input")
+        call = {
+            "id": item.get("call_id") or item.get("id") or "",
+            "name": item.get("name") or "",
+            "arguments": arguments,
+        }
+        return {"role": "assistant", "parts": _tool_call_parts([call])}
</code_context>
<issue_to_address>
**Custom tool inputs are altered**

When a custom tool sends input that is valid JSON, including a falsey value such as `false` or `0`, `_tool_call_parts()` parses `custom_tool_call.input` as JSON, changing JSON-looking text and replacing falsey decoded values with `{}`; telemetry records altered custom tool input.

Preserve `custom_tool_call.input` as its original string instead of parsing it as JSON.

Also at `cli/internal/coding/install/marketplace/plugins/hermes/__init__.py:180-184`.
</issue_to_address>

### Comment 5
<location path="plugins/hermes/tests/test_openlit_plugin.py" line_range="662-663" />
<code_context>
+    observer.tool_call(**tool_payload(args={"command": "0123456789abcdef"}, result="0123456789abcdef"))
+
+    span = by_name(exporter)["execute_tool terminal"]
+    assert span.attributes[SC.GEN_AI_TOOL_CALL_ARGUMENTS].endswith("...")
+    assert len(span.attributes[SC.GEN_AI_TOOL_CALL_ARGUMENTS]) == 13
+    assert span.attributes[SC.GEN_AI_TOOL_CALL_RESULT] == "0123456789..."
+
</code_context>
<issue_to_address>
**Wrong tool arguments pass truncation check**

When argument capture emits a 10-character string unrelated to the supplied arguments, followed by `...`, `test_tool_call_respects_max_content_length` accepts any 13-character argument value ending in `...`: its assertions at lines 662–663 never check that the prefix comes from the supplied `args`, so incorrect argument capture passes.

Assert the exact expected truncated serialized arguments, including their prefix.

Also at `cli/internal/coding/install/marketplace/plugins/hermes/tests/test_openlit_plugin.py:662-663`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and when content capture is enabled, this now exports tool arguments, tool results, and Responses API reasoning/output content into telemetry; those values can contain secrets or private data, and truncation only limits their length. Reverting stops future exports, but data already sent to an exporter cannot be recalled.

Blocking findings: plugins/hermes/__init__.py:201, plugins/hermes/__init__.py:184, plugins/hermes/__init__.py:179, plugins/hermes/__init__.py:184, plugins/hermes/tests/test_openlit_plugin.py:663


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread plugins/hermes/__init__.py Resolved
Comment thread plugins/hermes/__init__.py Resolved
Comment thread plugins/hermes/__init__.py Resolved
Comment thread plugins/hermes/__init__.py Resolved
…ll items, and None tool results

Signed-off-by: Dr. Mohammed Lubbad <[email protected]>
@mlubbad

mlubbad commented Nov 28, 2026

Copy link
Copy Markdown
Author

Addressed the review findings in commit 29a61c93:

  1. OPENLIT_CODING_CONTENT_CAPTURE enforcement: Gated body capture (Observer and register) so message, reasoning, and tool bodies are suppressed whenever OPENLIT_CODING_CONTENT_CAPTURE is set to metadata_only or minimal.
  2. Model tool-call argument truncation: Normalized tool arguments via _tool_arguments() across Chat Completions, Anthropic tool_use, and Responses function_call / shell calls so oversized valid JSON arguments respect OpenlitConfig.max_content_length while structured dicts within the limit are preserved.
  3. custom_tool_call.input preservation: Kept custom_tool_call.input as its raw string ({"input": truncate_content(...)}) instead of JSON-decoding it, preserving values such as "false", "0", and JSON-looking text verbatim.
  4. Role-less shell items: Added support for local_shell_call / local_shell_call_output (and shell_call / shell_call_output) in _responses_input_item().
  5. None tool results: Restored truncate_content(str(kwargs.get("result"))) in tool_call() so None tool results remain distinguishable from empty strings ("None" vs "").
  6. Tests & marketplace sync: Added exact prefix assertions and regression tests for all cases above, and synced cli/internal/coding/install/marketplace/plugins/hermes/ via cli/scripts/sync-plugins.sh.

This branch was successfully deployed

1 active (outdated) deployment
release-notes — bd9f698b Deployed Nov 28, 2026 by mlubbad via Normalize / Conventional title #923
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Hermes plugin drops Responses API tool/reasoning items, stringifies multimodal user_message, and skips tool truncation

1 participant