🐛 Bug Report: Gemini streaming raises TypeError after the last chunk when usage metadata has no candidates_token_count

Abierto
#4,711 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@prassu017 ya está trabajando en esto.

Desde el 17/11/2026.

  • #4712 de @prassu017 — abierto

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
35/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
python

Línea de trabajo

Start with the usage calculation and histogram recording in packages/opentelemetry-instrumentation-google-generativeai/opentelemetry/instrumentation/google_generativeai/span_utils.py and the sync and async stream finalization in __init__.py. Reproduce the issue with the synthetic response described here, then check the Google Generative AI instrumentation tests for coverage of both wrappers. Done means streams finish normally and spans end when candidate token counts are absent; linked PR #4712 is already open.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Hullo folks,

I’m doing some research for Tessl Code Review and we ran it against your repo. It flagged a potential issue, and I figured it made sense to share it with you:

Which component is this bug for?

Google Generative AI Instrumentation

📜 Description

With metrics enabled, a Gemini stream whose last chunk has usage metadata but no candidates_token_count raises TypeError when the caller tries to finish iterating.

The last chunk has already been yielded. The failure occurs while recording the output-token histogram, and span.end() is not reached. Both sync and async stream wrappers reproduce this.

👟 Reproduction steps

This uses real SDK response objects and a real OpenTelemetry histogram, with a synthetic stream and no Gemini API call:

from google.genai.types import (
    GenerateContentResponse, GenerateContentResponseUsageMetadata,
)
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.instrumentation.google_generativeai import (
    _build_from_streaming_response,
)

tracer = TracerProvider().get_tracer("repro")
meter = MeterProvider().get_meter("repro")
histogram = meter.create_histogram("gen_ai.client.token.usage")
chunk = GenerateContentResponse(
    usage_metadata=GenerateContentResponseUsageMetadata(
        prompt_token_count=2, total_token_count=2,
    )
)
span = tracer.start_span("repro")
stream = _build_from_streaming_response(
    span, iter([chunk]), "gemini-test", None, histogram,
)
assert next(stream) is chunk
try:
    next(stream)  # Expected: StopIteration
finally:
    print("span still recording:", span.is_recording())
    span.end()
👍 Expected behavior

The stream ends normally, the span ends, and missing token counts do not become non-numeric histogram measurements.

👎 Actual Behavior
span still recording: True
TypeError: must be real number, not NoneType

Controls tested:

Final usage / metrics Result
Missing candidate count, no thoughts, metrics on TypeError
Candidate count 0, metrics on Clean end
Missing candidate count, thoughts count 3, metrics on Clean end
Missing candidate count, metrics off Clean end

The async wrapper produced the same TypeError after yielding its final chunk.

🤖 Python Version

3.13.11 on macOS arm64.

📃 Additional context

Tested installed versions:

  • opentelemetry-instrumentation-google-generativeai==0.63.1
  • google-genai==3.4.0
  • opentelemetry-sdk==1.45.2

The current source at 864f8591081251a40a40e0bb06a4d8084c3664d2 retains the same path:

This is a local wrapper reproduction with synthetic response data, not a live provider reproduction. #4603 handles thinking tokens, but when both candidate and thinking counts are absent, output_tokens still stays None. Skipping absent metrics or normalizing them according to the intended usage semantics would avoid the exception.

👀 Duplicate check
  • Checked existing issues and related token-usage PRs; did not find this exact report.

I’m with Tessl. Tessl reviews code using repository-level context and specific review lenses that improve over time through feedback. That’s how this finding surfaced. We’re just getting started and want to offer the tool free to open-source projects. If this is useful, happy to give you access.

Baptiste

Lenguaje dominante
Python
Estrellas
7.5k
Forks
1.2k
Merge medio
1 d 23 h
PR fusionados (30 d)
3

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de traceloop/openllmetry

Todos los issues de traceloop/openllmetry

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.