Skip to content

fix(openai): multiply image cost by number of images returned - #1974

Open
todkarsant wants to merge 2 commits into
openlit:mainfrom
todkarsant:fix/openai-image-cost-n
Open

todkarsant wants to merge 2 commits into
openlit:mainfrom
todkarsant:fix/openai-image-cost-n

Conversation

@todkarsant

@todkarsant todkarsant commented Nov 20, 2026 •

Copy link
Copy Markdown

Summary

  • common_image_logic computed the per-image cost but set it directly on the span without multiplying by len(response.data)
  • Requests with n > 1 reported 1/n of the actual cost on both the span and the gen_ai.usage.cost metric

Fixes #1933

Summary by Sourcery

Bug Fixes:

  • Correct image operation cost reporting by multiplying the per-image price by the number of images returned, including requests that return multiple images.

common_image_logic computed the per-image cost but set it on the span
without multiplying by len(response.data). Requests with n > 1
reported 1/n of the actual cost.

Fixes openlit#1933
@todkarsant
todkarsant requested review from a team and ishanjainn as code owners November 20, 2026 09:37
@sourcery-ai

sourcery-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Compute image operation cost by multiplying the per-image price by the actual number of images returned.

  • sdk/python/src/openlit/instrumentation/openai/utils.py L2001-2002, L2008-2009

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 20, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix OpenAI image cost for multi-image responses

🐞 Bug fix 🕐 Less than 10 minutes

Grey Divider

AI Description

• Multiply the per-image price by the number of returned images to correct reported costs.
• Apply the corrected total to both the span and the image cost metric.
Merge Risk 🟢 Low

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • Synchronous and asynchronous image generation, variation, and editing wrappers all converge on process_image_response and common_image_logic.
  • The changed value is emitted both as a span cost attribute and through the image metric recorder, which are two telemetry surfaces for the same end-to-end image cost-reporting behavior rather than independent user capabilities.
Behavioral complexity 🟢 Low 🧩 Straightforward

  • Before: one configured image-model price was used as the request cost.
  • After: the same established pricing lookup is multiplied by len(response data).
  • New correctness condition: the response data cardinality must correspond to the number of returned/billable images, while empty data must remain safe.
  • This is a direct arithmetic transformation using existing pricing and telemetry infrastructure; no new branches, compatibility protocol, concurrency ordering, or coordinated invariant was introduced.
Potential damage 🟡 Medium 🩹 Incorrect results

  • The concrete consequence is incorrect cost data in spans and metrics for OpenAI image operations.
  • This can distort observability, usage aggregation, or internal cost reporting, but the inspected code does not charge customers, modify provider billing, or persist application data.
  • Recovery is to deploy corrected code and, where needed, recompute or annotate affected telemetry; a revert prevents new errors but does not repair already exported records.
  • Revert or patch the instrumentation to stop future incorrect values.
  • Existing spans and metric points are not automatically repaired; recovery of historical reporting requires retention access and recomputation or manual adjustment.
  • No automatic repair worker or state migration was found.
Assessed commit 38e24c0
Diagram

graph TD
  Response["Returned images"] --> Cost["Total cost"] --> Span["Cost attribute"]
  Pricing["Per-image price"] --> Cost
  Cost --> Metric["Cost metric"]
Loading
High-Level Assessment

Use the returned image count rather than the requested count: it reflects what was actually produced and corrects both telemetry outputs through their shared cost value. A requested-count calculation would be less reliable if fewer images were returned.

Files changed (1) +4 / -2

Bug fix (1) +4 / -2
utils.pyCalculate total cost from returned image count +4/-2

Calculate total cost from returned image count

• Treats the pricing lookup as a per-image cost and multiplies it by the number of images in the response. Retains a minimum count of one when response image data is absent; the resulting total feeds the existing span attribute and image metrics.

sdk/python/src/openlit/instrumentation/openai/utils.py

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can turn on the rule miner and Qodo learns your standards from review history

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai

sourcery-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit 38e24c0

#1933 Bug: OpenAI image spans price only one image when `n > 1` · 1 of 1 met

# Requirement Status Notes
1 Report image cost as the per-image price multiplied by the number of images returned, on the span and cost metric. ✅ Met common_image_logic counts response.data, multiplies the per-image price by that count, and uses the result for both the span cost attribute and the cost metric.

@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 1 issue

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

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/openai/utils.py" line_range="2009" />
<code_context>
         scope._kwargs.get("quality", "standard"),
     )
+    image_count = len(scope._response_dict.get("data", []) or [])
+    cost = per_image_cost * max(image_count, 1)

     # Common Span Attributes
</code_context>
<issue_to_address>
**Empty results show image charges**

When a successful image response has missing, null, or empty `data`, `max(image_count, 1)` charges for one image, so the span and cost metric report a positive charge despite zero images being returned.

Calculate `cost` using `image_count` without a minimum of one.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the image count or per-image price is wrong, the SDK will emit an incorrect total cost in telemetry for those requests. Reverting stops future misreporting, but already-emitted span data remains and may need correction or recomputation.

Blocking findings: sdk/python/src/openlit/instrumentation/openai/utils.py:2009


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

This branch was previously deployed

1 inactive (outdated) deployment
release-notes — bd719f49 Deployed Nov 20, 2026 by todkarsant via Normalize / Conventional title #871
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: OpenAI image spans price only one image when n > 1

1 participant