[BUG] GeminiModel reports `tool_use` instead of `max_tokens` / `guardrail_intervened` when the turn already contains a function call
Human Overview
Strands has a safeguard: when a turn ends with MAX_TOKENS, it skips that turn's actions and raises an error so the caller can handle it, e.g. retry with a higher limit. But in the Gemini provider, if the turn contains a tool call, the code reports tool_use instead, hiding the truncation, so the tool still runs.
Checks
- [x] I have updated to the lastest minor and patch version of Strands
- [x] I have checked the documentation and this is not expected behavior
- [x] I have searched ./issues and there are no duplicates of my issue
SDK Language
Python
Strands Version
1.64.0 (also reproduced on main at b17ae40f3)
Language Runtime Version
Python 3.14
Operating System
macOS
Installation Method
pip
Steps to Reproduce
Offline repro: pip install strands-agents google-genai pytest pytest-asyncio. Only HTTP is mocked; the Google SDK and GeminiModel run as normal.
import asyncio, json
import httpx
from google import genai
from google.genai import types
from strands.models.gemini import GeminiModel
def handler(request):
events = [
{"candidates": [{"index": 0, "content": {"role": "model", "parts": [
{"functionCall": {"name": "record_city", "id": "call_1", "args": {"city": "Paris"}}}]}}]},
{"candidates": [{"index": 0, "finishReason": "MAX_TOKENS"}], # also try "SAFETY"
"usageMetadata": {"promptTokenCount": 20, "candidatesTokenCount": 128, "totalTokenCount": 148}},
]
body = "".join("data: " + json.dumps(e) + "\n\n" for e in events)
return httpx.Response(200, headers={"Content-Type": "text/event-stream"}, content=body)
async def main():
transport = httpx.MockTransport(handler)
client = genai.Client(api_key="offline", http_options=types.HttpOptions(
base_url="https://gemini.invalid",
httpx_client=httpx.Client(transport=transport),
httpx_async_client=httpx.AsyncClient(transport=transport)))
model = GeminiModel(model_id="gemini-2.5-flash", client=client, params={"max_output_tokens": 128})
tool_spec = {"name": "record_city", "description": "Record a city.", "inputSchema": {"json": {
"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}
events = [e async for e in model.stream(
[{"role": "user", "content": [{"text": "Record Paris and London."}]}], tool_specs=[tool_spec])]
print([e["messageStop"]["stopReason"] for e in events if "messageStop" in e])
asyncio.run(main())
Expected Behavior
['max_tokens'] for MAX_TOKENS and ['guardrail_intervened'] for SAFETY: the same results you get when the turn has no function call. With an Agent, the truncated turn should raise MaxTokensReachedException and its tools should not run.
Actual Behavior
Both cases print ['tool_use']. With an Agent and a real @tool, the tool from the truncated turn runs, a second model request is sent, and the run ends with end_turn. No MaxTokensReachedException is raised, so the truncation is never reported.
Results of the full matrix:
| server response | stopReason |
Agent behavior |
|---|---|---|
text + STOP |
end_turn |
ok |
text + MAX_TOKENS |
max_tokens |
raises MaxTokensReachedException (ok) |
function call + STOP |
tool_use |
runs the tool (ok) |
function call + MAX_TOKENS |
tool_use |
runs the tool, continues, ends with end_turn |
function call + SAFETY |
tool_use |
treated as a normal tool call |
Possible Solution
In strands-py/src/strands/models/gemini.py, the final message_stop chunk is built with
"data": "TOOL_USE" if tool_used else (candidate.finish_reason if candidate else "STOP"),
(source). Because tool_used is checked first, it overrides every server finish reason, so the existing MAX_TOKENS / SAFETY mappings in _format_chunk never run for a turn that contains a function call. The proposed fix is to convert to TOOL_USE only when the server reported a normal finish (STOP, or no reason), and keep every other finish reason as it is. This matches #4139 and how OpenAIModel already treats length. I'm happy to open a PR with regression tests.
Additional Context
- Related: #4139 (same fix for the OpenAI Responses provider), #4722 / #4778 (missing finish reason). Neither covers this case.
- AI disclosure: I used an AI assistant to help investigate this issue and draft parts of this report. I ran the reproduction myself and verified the results.
Related Issues
No response
@HYYAlex, are you already preparing a fix for this? I'd be happy to help if it's available and maintainers welcome the contribution.
A local reproduction on current main (50a391e) confirms both cases: with a function call present, MAX_TOKENS and SAFETY become tool_use, and the Agent runs an in-memory tool and continues. The text-only controls preserve the expected stop reasons. This used the real Gemini provider and Google SDK with mocked HTTP, not hosted inference.
The proposed scope is to preserve abnormal finish reasons and keep normal tool-call completion working, with focused tests in the existing Gemini test file. Could a maintainer confirm that approach before I start a patch?
AI assistance: Codex helped run the reproduction and draft this comment.
Thanks for confirming the repro! Yes, I'm already working on a fix and plan to open a PR shortly, with focused tests in the existing Gemini test file (MAX_TOKENS/SAFETY with a function call, plus the normal tool-call case).