Skip to content

fix(google-genai): extract enum name for finish reason - #1975

Open
todkarsant wants to merge 1 commit into
openlit:mainfrom
todkarsant:fix/google-genai-finish-reason
Open

todkarsant wants to merge 1 commit into
openlit:mainfrom
todkarsant:fix/google-genai-finish-reason

Conversation

@todkarsant

@todkarsant todkarsant commented Nov 20, 2026 •

Copy link
Copy Markdown

Summary

  • FinishReason is a (str, Enum) subclass; str() on it gives "FinishReason.MAX_TOKENS" instead of "MAX_TOKENS"
  • The OTel finish_reason_map then misses and the raw repr leaks into gen_ai.response.finish_reasons and output messages
  • Fix uses the enum's .name attribute, with a fallback for plain strings

Fixes #1899

Summary by Sourcery

Bug Fixes:

  • Normalize Google GenAI finish reasons from enum values so OpenTelemetry mappings and response metadata use the plain reason name.

FinishReason is a (str, Enum) subclass; str() on it gives
"FinishReason.MAX_TOKENS" instead of "MAX_TOKENS".  The OTel
finish_reason_map then misses and the raw repr leaks into spans
and output messages.  Use the enum's .name attribute instead.

Fixes openlit#1899
@sourcery-ai

sourcery-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Add a helper that extracts an enum’s plain name (or falls back to its string value), then use it to normalize finish reasons in streamed and chat responses.

  • sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py L28-44, L579, L967

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 Google GenAI finish-reason enum handling

🐞 Bug fix 🕐 10-20 Minutes

Grey Divider

AI Description

• Extract enum names from Google GenAI finish reasons so OpenTelemetry mappings recognize them.
• Preserve plain-string reasons and handle missing values in streaming and non-streaming responses.
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.
  • The changed streaming and non-streaming paths produce the same end-to-end outcome: a Google AI Studio response finish reason is normalized, mapped for OTel output messages when applicable, and attached to the response span.
  • They are separate delivery modes within one bounded integration, not independent functional scopes.
  • The span consumer is the shared telemetry path shown by the finish-reason span attribute assignment.
Behavioral complexity 🟢 Low 🧩 Straightforward

  • The changed logic is a direct normalization rule: preserve empty values, use an enum's existing name when available, otherwise stringify the value.
  • The existing finish-reason mapping and telemetry pipeline are reused unchanged.
  • No new branches interact across requests, no persistent state is written, and no concurrency or ordering protocol is introduced.
Sources

sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py[28-42]

def _finish_reason_name(value):
    """Return the plain name of a finish-reason value.

    google-genai returns ``FinishReason`` enum members from
    ``response_as_dict`` / ``model_dump``.  ``str()`` on such a member
    gives ``"FinishReason.MAX_TOKENS"``; we need ``"MAX_TOKENS"`` so the
    OTel finish-reason map matches.
    """
    if value is None:
        return ""
    # Enum instances expose .name ("MAX_TOKENS")
    name = getattr(value, "name", None)
    if name is not None:
        return str(name)
    return str(value)
Potential damage 🟢 Low 🩹 Cosmetic

  • The plausible fault is an incorrect observability label or OTel finish-reason mapping.
  • It does not alter the model request, generated response text, tool execution, application state, or external effects; the value is consumed as telemetry on the span and optional output-message representation.
  • Updating or reverting the instrumentation restores future telemetry.
  • Previously emitted spans retain their incorrect label and must be recollected if accurate historical telemetry is required; there is no persistent application-state repair or external compensation prerequisite.
Assessed commit 70bc5b2
Diagram

graph TD
  A["Google response"] --> B["Response conversion"] --> C["Response handlers"] --> D["Reason normalization"] --> E["Chat telemetry"] --> F["Span attribute"]
  E --> G["Output messages"]
Loading
High-Level Assessment

The shared, Google-specific normalization helper is appropriately scoped: it fixes both response paths without changing response conversion for other integrations. Global enum conversion would have a broader compatibility risk. Add an enum-valued regression test for each path to verify the intended telemetry.

Files changed (1) +19 / -2

Bug fix (1) +19 / -2
utils.pyNormalize Google GenAI finish reasons before telemetry +19/-2

Normalize Google GenAI finish reasons before telemetry

• Adds a helper that returns an enum member’s name, preserves plain strings, and returns an empty string for missing values. Both streamed chunks and non-streaming chat responses use it when storing the finish reason, allowing output-message mapping to recognize enum-valued reasons.

sdk/python/src/openlit/instrumentation/google_ai_studio/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 70bc5b2

#1899 Bug: google-genai spans record the finish reason as "FinishReason.MAX_TOKENS" instead of its value · 3 of 3 met

# Requirement Status Notes
1 Record enum finish reasons by their plain name, with a fallback for plain strings. ✅ Met The helper uses .name when available and falls back to str(value).
2 Map MAX_TOKENS to length in the output message finish reason. ✅ Met The normalized reason is passed into the existing output-message finish-reason mapping.
3 Leave a chunk's missing finish reason empty so an abandoned stream is recorded as incomplete. ✅ Met The helper returns an empty string for None, allowing the stream finalizers' existing incomplete-stream handling to apply.

@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 reviewed your changes and they look great!

Sourcery assessment

Needs a human reviewer. If the conversion is wrong, spans will carry an incorrect finish-reason value in exported telemetry. Reverting restores future spans, but it cannot correct telemetry already recorded; the impact is limited to those records.


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

This branch was previously deployed

1 inactive deployment
release-notes — 70bc5b2c Deployed Nov 20, 2026 by todkarsant via Normalize / Conventional title #872
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: google-genai spans record the finish reason as "FinishReason.MAX_TOKENS" instead of its value

1 participant