Skip to content

Commit 3ef737e

Browse files
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#3051
1 parent 83e43ea commit 3ef737e

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

‎google/genai/chats.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,9 @@ def _extract_curated_history(
117117
i += 1
118118
if is_valid:
119119
curated_history.extend(current_output)
120-
elif curated_history:
121-
curated_history.pop()
120+
else:
121+
while curated_history and curated_history[-1].role == 'user':
122+
curated_history.pop()
122123
return curated_history
123124

124125

‎google/genai/tests/chats/test_get_history.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,25 @@ def test_history_with_valid_and_invalid_model_output():
237237
assert chat.get_history(curated=True) == []
238238

239239

240+
def test_history_with_consecutive_user_inputs_and_invalid_model_turn():
241+
history = [
242+
types.Content(
243+
role='user',
244+
parts=[types.Part.from_text(text='user input 1')],
245+
),
246+
types.Content(
247+
role='user',
248+
parts=[types.Part.from_text(text='user input 2')],
249+
),
250+
types.Content(
251+
role='model',
252+
parts=[], # invalid content
253+
),
254+
]
255+
256+
assert chats._extract_curated_history(history) == []
257+
258+
240259
def test_history_end_with_user_input():
241260
history = [
242261
types.Content(

0 commit comments

Comments
 (0)