Skip to content

fix(litellm): record generated images under output.images so TraceConfig masks them - #3947

Open
Aasif-Simpplr wants to merge 3 commits into
Arize-ai:mainfrom
Aasif-Simpplr:fix-litellm-image-output-attributes
Open

Aasif-Simpplr wants to merge 3 commits into
Arize-ai:mainfrom
Aasif-Simpplr:fix-litellm-image-output-attributes

Conversation

@Aasif-Simpplr

@Aasif-Simpplr Aasif-Simpplr commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Description

For litellm.image_generation, _finalize_span records only result.data[0], and writes url or b64_json to the bare image.url key and to output.value. That bypasses the image privacy controls:

  • No TraceConfig mask rule matches the bare image.url key, so hide_outputs leaves it in place.
  • A raw b64_json payload has no data:image/ prefix, so base64_image_max_length never applies to it.
  • Every generated base64 image is exported in full (tens to hundreds of KB per image), and images after the first are dropped.

This PR records every image under output.images.<i>.image.url, which is what the span-kind-independent images spec asks for and what the openai instrumentor already emits for the Images API. b64_json is wrapped as a data URL using the response's output_format, mirroring image_b64_to_data_url from the openai instrumentor (a small local copy, since that helper is private to the openai package). The existing mask rules then apply: hide_outputs removes the images and base64_image_max_length redacts oversized base64.

The bare span-level image.url key is no longer written at all, since no mask rule matches it and hide_outputs would leak a hosted URL through it. A hosted URL in the first image still populates output.value, which hide_outputs masks. Raw base64 is no longer written to output.value, in line with the spec's note that output.value stays the textual output.

Tests: the existing URL tests also assert the new output.images.0 key, the b64 test now expects a data URL under output.images.0 and nothing raw elsewhere, and a new parametrized test covers default config, base64_image_max_length and hide_outputs with two images. 9 of the 11 image tests fail against main and all pass with the fix. The package's 129 tests pass, and ruff format --diff, ruff check --no-fix and mypy . are clean with the pinned dev versions.

Trace output before and after

Same script on both sides: litellm.image_generation returns one 60 KB base64 image and one hosted URL. litellm 1.84.0 on both sides.

Before (main @ 19363a0):

-- default TraceConfig()
   image.url                     80000 chars  raw base64
   output.value                  80000 chars  raw base64
-- TraceConfig(hide_outputs=True)
   image.url                     80000 chars  raw base64
   output.value                     12 chars  '__REDACTED__'

After (this branch @ be0223f):

-- default TraceConfig()
   output.images.0.image.url        12 chars  '__REDACTED__'   (over the default 32000 base64 budget)
   output.images.1.image.url        25 chars  'https://img.example/2.png'
-- TraceConfig(hide_outputs=True)
   (no image attributes)

Resolves #4206. Follows #3654 / #3695, which added output.images and its masking.

Checklist:

  • Follows OpenInference configuration to hide sensitive info
  • Spans properly inherit from context attributes (unchanged; the existing context-attribute image tests still pass)
  • Properly respects suppress tracing context (unchanged by this PR)

…fig masks them

Image generation output was written only for the first image, to the bare image.url
key and to output.value, with b64_json payloads copied in raw. No TraceConfig rule
matches those keys and raw base64 has no data: prefix, so hide_outputs and
base64_image_max_length never applied and every base64 image was exported in full.

Record every image under output.images.<i>.image.url, as the multimodal spec and
the openai instrumentor do, wrapping b64_json as a data URL. Hosted URLs keep
image.url and output.value for compatibility; raw base64 no longer goes there.
@Aasif-Simpplr
Aasif-Simpplr requested a review from a team as a code owner October 5, 2026 12:00
@mikeldking mikeldking added the factory-review to be reviewed by the software factory label Oct 31, 2026 — with Claude
@openinference-factory

Copy link
Copy Markdown
Contributor

The factory started a review of be0223f (session sesn_013UyNPsbwZhNTcAE1wrWJMa). It reports back here when the session ends.

@openinference-factory openinference-factory 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.

Factory review of be0223f: Request changes

A blocking finding decides the verdict: moving the decorator removes error suppression from _finalize_span, so an extractor error now raises into user litellm calls.

Criterion Result Notes
Fit Partial does what it claims, but also drops _finalize_span error suppression, which the PR does not claim
Checks Pass tox run -e ci-litellm (ruff format, ruff check, mypy, 129 tests)
Tests Pass added and updated image tests fail on base src, pass with the fix
Blocking findings 1 _finalize_span lost @_suppress_extractor_errors, litellm/__init__.py:731
Non-blocking findings 2 single-call-site helper, litellm/__init__.py:731; non-exhaustive attribute asserts, tests/test_instrumentor.py:3047
Risk Medium side effects: extractor errors propagate into every wrapped litellm call and can leak spans
Review depth Deep Risk is Medium
Details

Intent: For litellm.image_generation and aimage_generation, record every generated image under output.images.<i>.image.url, wrapping b64_json as a data URL, so that hide_outputs and base64_image_max_length apply. The bare image.url and output.value are kept only when the first image is a hosted URL, and raw base64 is never written there.
Fit: The ImageResponse branch does what the PR claims. The core mask rules match output.images.* (config.py _is_output_image, _is_image_url), and the new test drives this through OITracer.
Fit (extra change): Inserting the helper between @_suppress_extractor_errors and def _finalize_span moves the decorator off _finalize_span. That changes error handling for every result type, which the PR does not claim.
Fit (residual gap): For a hosted-URL first image, the retained bare image.url is still matched by no mask rule. Under hide_outputs that URL is still exported. This is pre-existing behavior, kept on purpose for compatibility, and not a finding of this PR.
Verified: tox run -e ci-litellm passed: ruff format, ruff check, mypy, and 129 pytest tests on Python 3.11.
Verified: With the base (19363a0) src checked out and the PR's tests, ci-litellm -k image_generation failed 4 tests before stopping: [default], [hide_outputs], test_image_generation_url, test_image_generation_b64json. Each failed on the missing output.images keys or the raw base64 in image.url. The PR states 9 of 11 fail on main.
Verified: I reproduced the blocking finding by forcing _set_cost_from_response to raise. On base, the call returns ImageResponse. On this commit, the call raises RuntimeError.
Verified: The PR merges cleanly into current main (git merge-tree). Its branch predates later litellm fixes such as #3948.
Not verified: The ci-litellm-latest env is disabled in python/tox.ini (compromised litellm releases).
Not verified: CI's py310 and py314 interpreters; the sandbox ran 3.11.
Not verified: The span leak on the responses-streaming and non-stream stream=True paths after a finalize error is inferred from the code, not run.
Findings without a diff line: none
Risk: side effects medium (extractor errors now reach callers through _finalize_span), performance none (one loop over the returned images), backwards compatibility medium (b64-only responses such as gpt-image-1 no longer set image.url or output.value, as the PR says and in line with spec/multimodal_attributes.md), from the language reviewers

Graded against the review criteria.



@_suppress_extractor_errors
def _image_b64_to_data_url(b64_json: str, image_format: Any = None) -> str:

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.

Blocking. The new helper sits between @_suppress_extractor_errors (line 730) and def _finalize_span (line 744). The decorator now wraps _image_b64_to_data_url, and _finalize_span no longer has it. Any exception raised while recording attributes now reaches the caller for every _finalize_span call site: completion, embedding, responses and images.

I reproduced it by forcing _set_cost_from_response to raise during litellm.image_generation:

  • On base 19363a0, the error is logged, the call returns the ImageResponse, and the span is UNSET.
  • On this commit, the user's call raises RuntimeError, and the span is ERROR.

On the paths that call _finalize_span(...) and then span.end() (lines 1234-1235, 1246-1247, 1476-1477), the raise also skips span.end(). That leaks the span.

This breaks two MUSTs in REVIEW.md § Always Check: instrumentation must not raise into the instrumented library, and every span must be ended. It also breaks python/AGENTS.md § Logging and Diagnostics. All 129 tests still pass, so nothing covers this.

Fix: put @_suppress_extractor_errors back directly above def _finalize_span. Then either inline the helper or leave it undecorated. Add a test that forces an extractor inside _finalize_span to raise, and assert that the call still returns its result and the span is exported.

Comment on lines +731 to +741
def _image_b64_to_data_url(b64_json: str, image_format: Any = None) -> str:
"""Wrap an image generation ``b64_json`` payload as an image data URL."""
if b64_json.startswith("data:image/"):
return b64_json
normalized = image_format.lower() if isinstance(image_format, str) else None
if normalized == "jpg":
normalized = "jpeg"
media_type = (
f"image/{normalized}" if normalized in ("png", "jpeg", "webp", "gif") else "image/png"
)
return f"data:{media_type};base64,{b64_json}"

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.

Non-blocking. _image_b64_to_data_url has a single call site (line 819). It breaks REVIEW.md § Patterns to Flag: "Abstractions with a single call site SHOULD NOT be introduced".

Fix: inline the media-type and data-URL lines into the ImageResponse branch. That also removes the decorator mix-up flagged above. If both instrumentors should share this logic, moving image_b64_to_data_url from the openai package into the core belongs in a separate PR.

Comment on lines +3038 to +3047
attributes = dict(cast(Mapping[str, AttributeValue], span.attributes))
output_images = {
index: attributes[key]
for index in range(2)
if (key := f"{SpanAttributes.OUTPUT_IMAGES}.{index}.{ImageAttributes.IMAGE_URL}")
in attributes
}
assert output_images == expected_images
assert ImageAttributes.IMAGE_URL not in attributes
assert SpanAttributes.OUTPUT_VALUE not in attributes

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.

Non-blocking. The new test reads output.images.{0,1} and checks that two keys are absent, so other attributes are never checked. Stray or unmasked keys could still pass, for example an output.images.2.* or a leftover raw base64 attribute. The same applies to the .get() assertions this PR adds to the existing image tests (near lines 2909, 2980 and 3130).

This breaks REVIEW.md § Style, which defers to the python-code-reviewer skill § 2.3: pop each expected attribute, then assert none remain.

Fix: pop every expected key, including the model, input, span kind and token-count keys, then assert not attributes.

@openinference-factory

Copy link
Copy Markdown
Contributor

The factory recommends Request changes for be0223f. Read the review.

@openinference-factory openinference-factory Bot removed the factory-review to be reviewed by the software factory label Oct 31, 2026
…ributes exhaustively

The image data URL helper was inserted between @_suppress_extractor_errors and
_finalize_span, so the decorator wrapped the helper instead. Any extractor error in
_finalize_span then raised into the user's litellm call and could skip span.end().

Restore the decorator on _finalize_span and inline the single-use helper into the
ImageResponse branch. Add a regression test that forces an extractor inside
_finalize_span to raise and checks the call still returns and the span is exported.
The image tests now pop every expected attribute and assert none remain.
@Aasif-Simpplr

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Fixed in 60b185a:

  • Blocking: @_suppress_extractor_errors is back directly on _finalize_span, and the single-use helper is inlined into the ImageResponse branch.
  • New test_image_generation_extractor_error_does_not_raise forces _set_cost_from_response to raise during litellm.image_generation and asserts the call still returns the ImageResponse and the span is exported. It fails on be0223f (RuntimeError: extractor failure) and passes on 60b185a.
  • The image tests now pop every expected attribute and assert not attributes.

tox run -e ci-litellm: ruff format, ruff check, mypy and 130 tests pass.

@openinference-factory

Copy link
Copy Markdown
Contributor

The factory started a review of 60b185a (session sesn_01EqtH7X41545LdBxAH298en). It reports back here when the session ends.

@openinference-factory openinference-factory 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.

Factory review of 60b185a: Request changes

A blocking finding decides the verdict: under hide_outputs, a hosted first image is still exported through the bare image.url, which is the #4206 leak this PR says it resolves.

Criterion Result Notes
Fit Partial "Resolves #4206", but its first bullet (bare image.url survives hide_outputs) remains for hosted URLs
Checks Pass tox run -e ci-litellm at 60b185a (130 tests) and merged into current main (169 tests)
Tests Pass 9 of 12 image tests fail on base src; the extractor-error test fails without the decorator
Blocking findings 1 hosted URL leaks via bare image.url under hide_outputs, litellm/__init__.py:809
Non-blocking findings 0 none
Risk Low backwards compatibility: b64-only responses no longer set image.url / output.value
Review depth Focused one instrumentor branch and its tests; no public API, core or semconv change
Details

Intent: For litellm image_generation and aimage_generation, record every generated image under output.images.<i>.image.url, with b64_json wrapped as a data URL, so that hide_outputs and base64_image_max_length apply (#4206).
Intent: Keep the bare image.url and output.value only for a hosted first image.
Fit: The output.images recording, the data-URL wrapping, the multi-image support and the base64_image_max_length redaction all work as claimed.
Fit: The prior round's blocking finding is fixed. @_suppress_extractor_errors is back on _finalize_span, and the helper is inlined.
Fit: The PR keeps writing a hosted first image to the bare image.url. No mask rule matches that key, so TraceConfig(hide_outputs=True) still exports the URL. That is the first bullet of #4206, and the PR also states "hide_outputs removes the images".
Verified: tox run -e ci-litellm at 60b185a passed: ruff format, ruff check, mypy, and 130 tests on Python 3.11 with the branch's pinned litellm.
Verified: Applied onto current main (ff40dc3, litellm 1.88.6), the patch merged cleanly and ci-litellm passed: 169 tests.
Verified: With the base (19363a0) instrumentor installed and the PR's tests, -k image_generation gave 9 failed and 3 passed. The failures were test_image_generation_url x2, test_image_generation_b64json x2, test_aimage_generation x2 and ..._respect_trace_config x3.
Verified: test_image_generation_extractor_error_does_not_raise passes on base and fails with RuntimeError when _finalize_span is undecorated (checked by the Python reviewer), so it guards the earlier regression.
Verified: Reproduced the leak: hide_outputs=True with one hosted image gives image.url='https://img.example/1.png' and output.value='__REDACTED__'.
Not verified: CI's py310 and py314 interpreters (the sandbox ran 3.11).
Not verified: ci-litellm-latest, which is disabled in python/tox.ini.
Not verified: Real provider responses. There is no cassette; the tests patch OpenAIChatCompletion.image_generation, as the existing tests do.
Findings without a diff line: none
Risk: side effects low (one extra attribute per image; the bare-URL leak is pre-existing and unchanged), performance low (one loop over the returned images), backwards compatibility low (b64-only responses no longer populate image.url / output.value, in line with spec/multimodal_attributes.md), from the language reviewers

Graded against the review criteria.

Comment on lines +809 to +810
if url and index == 0:
_set_span_attribute(span, ImageAttributes.IMAGE_URL, url)

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.

Blocking. With hide_outputs=True, a hosted URL is still exported through the bare image.url key. This is the first bullet of #4206, which this PR says it resolves.

  • Trigger: TraceConfig(hide_outputs=True) with ImageResponse(data=[ImageObject(url="https://img.example/1.png")]).
  • The span then has {'image.url': 'https://img.example/1.png', 'output.value': '__REDACTED__'} (reproduced at this commit).
  • TraceConfig.mask only hides output.images.* (_is_output_image) and output.value. Nothing matches the bare image.url key.
  • That makes output.images.0.image.url hidden while the same URL leaks through another attribute. REVIEW.md § Security says that MUST NOT happen.
  • The hide_outputs case in test_image_generation_output_images_respect_trace_config misses it, because image 0 there is b64_json.

Fix: stop writing the bare image.url. It is not a spec attribute, and the output.value write already redacts under hide_outputs. Then add a hide_outputs case where the first image is a URL, and assert that no image.url attribute remains. If the bare key has to stay for compatibility, mask it in core in a separate PR and change "Resolves #4206" to "Part of #4206".

@openinference-factory

Copy link
Copy Markdown
Contributor

The factory recommends Request changes for 60b185a and labeled this pull request factory-request-changes. Read the review.

@openinference-factory openinference-factory Bot added factory-request-changes The factory review recommends requesting changes and removed factory-review to be reviewed by the software factory labels Nov 5, 2026
… key

A hosted first image was still written to the span-level image.url key. No
TraceConfig mask rule matches that key, so hide_outputs exported the URL, which
is the first case in Arize-ai#4206.

The URL is already recorded under output.images.0.image.url and output.value,
both of which hide_outputs masks, and the spec defines image.url only as the leaf
under <input|output>.images.<i>. Drop the bare key and keep output.value.

Add a regression test: a hosted first image with hide_outputs=True leaves only
output.value as __REDACTED__ and no image URL. It fails with the bare write
restored.
@Aasif-Simpplr
Aasif-Simpplr requested a review from a team as a code owner November 25, 2026 19:58
@Aasif-Simpplr

Copy link
Copy Markdown
Contributor Author

Thanks, the factory was right. Fixed in 360c93d.

  • The span-level image.url key is gone. A hosted first image is now recorded only under output.images.0.image.url and output.value, and hide_outputs masks both. The spec defines image.url only as the leaf under <input|output>.images.<i>, so there was no mask-safe way to keep the bare key.
  • New test test_image_generation_hide_outputs_hides_hosted_first_image covers the trigger from the review: TraceConfig(hide_outputs=True) with one hosted image. It asserts that only output.value == "__REDACTED__" is left and no image URL. With the bare write restored it fails on {'image.url': 'https://dummy-url'}.
  • Two existing tests no longer expect the bare key. The PR description is updated to match.

tox run -e ci-litellm: ruff format, ruff check and mypy are clean, and 131 tests pass.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

factory-request-changes The factory review recommends requesting changes

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

[bug] litellm: generated images bypass TraceConfig masking (hide_outputs, base64_image_max_length)

2 participants