From 3ef737e473a68b1ba1640b02e737f3db21d3b1fc Mon Sep 17 00:00:00 2001 From: David <75064925+DavidLeeGarrett@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:10:41 -0500 Subject: [PATCH 1/2] Drop all trailing user turns when a model turn is invalid in _extract_curated_history Previously only a single user Content was popped after an invalid model turn, leaving orphaned user messages in the curated history when several user turns preceded it. Now all consecutive trailing user-role contents are removed. Fixes googleapis/python-genai#3051 --- google/genai/chats.py | 5 +++-- google/genai/tests/chats/test_get_history.py | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/google/genai/chats.py b/google/genai/chats.py index 3ba5f3c95..de1f04f1f 100644 --- a/google/genai/chats.py +++ b/google/genai/chats.py @@ -117,8 +117,9 @@ def _extract_curated_history( i += 1 if is_valid: curated_history.extend(current_output) - elif curated_history: - curated_history.pop() + else: + while curated_history and curated_history[-1].role == 'user': + curated_history.pop() return curated_history diff --git a/google/genai/tests/chats/test_get_history.py b/google/genai/tests/chats/test_get_history.py index 37d5eacac..73a243568 100644 --- a/google/genai/tests/chats/test_get_history.py +++ b/google/genai/tests/chats/test_get_history.py @@ -237,6 +237,25 @@ def test_history_with_valid_and_invalid_model_output(): assert chat.get_history(curated=True) == [] +def test_history_with_consecutive_user_inputs_and_invalid_model_turn(): + history = [ + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 1')], + ), + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 2')], + ), + types.Content( + role='model', + parts=[], # invalid content + ), + ] + + assert chats._extract_curated_history(history) == [] + + def test_history_end_with_user_input(): history = [ types.Content( From 71065cf6594407445ce78bbc2485ff93aa5f6894 Mon Sep 17 00:00:00 2001 From: David <75064925+DavidLeeGarrett@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:10:51 -0500 Subject: [PATCH 2/2] Drop all trailing user turns when a model turn is invalid in _extract_curated_history Previously only a single user Content was popped after an invalid model turn, leaving orphaned user messages in the curated history when several user turns preceded it. Now all consecutive trailing user-role contents are removed. Fixes googleapis/python-genai#3051