sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[BUG] GeminiModel loses the RECITATION finish reason by mapping it to end_turn

Open abdes opened this issue 2 months ago • 1 comments

Human Overview

Gemini Recitation Reason Is Lost

Summary

Gemini finishReason: RECITATION becomes the same public messageStop: end_turn as ordinary STOP. The provider's distinct termination reason is lost in normalization.

Environment

  • SDK: Python; strands-agents==1.57.1 (latest PyPI release checked 2026-09-30).
  • Runtime: Python 3.12.14; Windows 11, build 26200.
  • Installation: published PyPI package in an isolated environment; SDK source unmodified.
  • Reproduction: deterministic local fixtures, no API key or network calls required.

Steps to Reproduce

The injected client returns real typed GenerateContentResponse objects with identical text and usage, varying only finishReason across STOP, RECITATION, and SAFETY. The installed public GeminiModel.stream() and formatter run unchanged. The other reasons serve as controls.

Install in a fresh Python 3.12 virtual environment:

python -m pip install "strands-agents[gemini]==1.57.1" "google-genai==2.25.0" "pydantic==2.13.5"

Save the following as repro_003.py and run python repro_003.py.

Complete runnable reproduction
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock

from google.genai import types
from strands.models.gemini import GeminiModel


async def response_stream(reason):
    yield types.GenerateContentResponse.model_validate({
        "candidates": [{
            "content": {"role": "model", "parts": [{"text": "Hello"}]},
            "finishReason": reason,
        }],
        "usageMetadata": {
            "promptTokenCount": 2, "candidatesTokenCount": 1, "totalTokenCount": 3,
        },
    })


async def main():
    for reason in ("STOP", "RECITATION", "SAFETY"):
        client = SimpleNamespace(aio=SimpleNamespace(models=SimpleNamespace(
            generate_content_stream=AsyncMock(return_value=response_stream(reason)),
        )))
        model = GeminiModel(model_id="gemini-2.5-flash", client=client)
        events = [event async for event in model.stream([
            {"role": "user", "content": [{"text": "Hi"}]},
        ])]
        print(reason)
        print("  stops:", [e["messageStop"] for e in events if "messageStop" in e])
        print("  usage:", [e["metadata"]["usage"] for e in events if "metadata" in e])


asyncio.run(main())

Actual Behavior and Impact

STOP and RECITATION both emit end_turn; SAFETY emits guardrail_intervened. All three retain usage. Hooks or other Model-stream consumers relying on the normalized stop reason cannot distinguish an ordinary completion from a recitation restriction, preventing application-specific acceptance or retry decisions based on that distinction.

Observed output (verified locally on 2026-09-30)
STOP
  stops: [{'stopReason': 'end_turn'}]
  usage: [{'inputTokens': 2, 'outputTokens': 1, 'totalTokens': 3}]
RECITATION
  stops: [{'stopReason': 'end_turn'}]
  usage: [{'inputTokens': 2, 'outputTokens': 1, 'totalTokens': 3}]
SAFETY
  stops: [{'stopReason': 'guardrail_intervened'}]
  usage: [{'inputTokens': 2, 'outputTokens': 1, 'totalTokens': 3}]

Expected Behavior

Preserve RECITATION distinctly through the public normalized interface, either as an appropriate stop reason or accompanying termination metadata. Maintainers should choose the representation. Applications retain responsibility for acceptance and task/session disposition; this does not imply all non-STOP reasons should have identical handling.

Source

gemini.py:471–480 recognizes TOOL_USE, MAX_TOKENS, and SAFETY; RECITATION reaches the catch-all end_turn branch.

Related Issues

#2347 / #2353 added the SAFETY → guardrail_intervened mapping but did not address RECITATION. No issue or PR matching RECITATION was found in the repository on 2026-09-30. This is distinct from missing-terminal handling: this response has an explicit provider finish reason and supplied usage.


AI assistance: Codex drafted this technical report and ran the included reproduction from reporter-supplied findings. No live provider request was made.

abdes avatar Sep 30 '26 05:09 abdes

Hey, I'd like to pick this up.

Plan: add a RECITATION case to the finish-reason mapping in strands-py/src/strands/models/gemini.py so it no longer falls through to end_turn, plus a test in tests/strands/models/test_gemini.py using the same fake-response approach as the repro.

Two quick questions before I start:

  1. Should it map to content_filtered or guardrail_intervened (to match how SAFETY is handled)? I'd lean content_filtered since recitation isn't really a safety issue, but happy to match SAFETY if you'd prefer.
  2. The TS Google adapter (strands-ts/src/models/google/adapters.ts) only maps MAX_TOKENS, so SAFETY and RECITATION both become endTurn there too. Want that fixed in the same PR, or kept separate?

idhanth avatar Sep 30 '26 22:09 idhanth