Skip to content

Commit 936af2f

Browse files
MaxFreedomPollardteknium1
authored andcommitted
Merge consecutive same-role contents for native Gemini
_build_gemini_contents emitted one contents entry per source message and never merged adjacent same-role entries. Gemini's generateContent requires strict user/model alternation and rejects consecutive same-role turns with HTTP 400 ("Please ensure that multiturn requests alternate between user and model"). A parallel tool call turns into two tool results in a row, which become two consecutive user functionResponse contents, so every multi-tool turn produced an unsendable history. Fold adjacent same-role contents into one by concatenating their parts after the per-message loop, matching the Anthropic and Bedrock converters. For a parallel call this yields the grouped multi-functionResponse user turn Gemini expects.
1 parent 885e80d commit 936af2f

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

‎agent/gemini_native_adapter.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,22 @@ def _build_gemini_contents(messages: List[Dict[str, Any]]) -> tuple[List[Dict[st
337337
if parts:
338338
contents.append({"role": gemini_role, "parts": parts})
339339

340+
# Gemini's generateContent requires strict user/model alternation;
341+
# consecutive same-role contents are rejected with HTTP 400 "Please ensure
342+
# that multiturn requests alternate between user and model". The loop above
343+
# emits one content per source message, so parallel tool calls (N tool
344+
# results become N user functionResponse contents), back-to-back user turns,
345+
# or merged assistant turns would each violate that. Merge adjacent
346+
# same-role contents by concatenating their parts. For parallel calls this
347+
# also produces the grouped multi-functionResponse turn Gemini expects.
348+
merged_contents: List[Dict[str, Any]] = []
349+
for content in contents:
350+
if merged_contents and merged_contents[-1]["role"] == content["role"]:
351+
merged_contents[-1]["parts"].extend(content["parts"])
352+
else:
353+
merged_contents.append(content)
354+
contents = merged_contents
355+
340356
system_instruction = None
341357
joined_system = "\n".join(part for part in system_text_parts if part).strip()
342358
if joined_system:

‎tests/agent/test_gemini_native_adapter.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,59 @@ def test_build_native_request_uses_original_function_name_for_tool_result():
8585
assert tool_response["name"] == "get_weather"
8686

8787

88+
def test_parallel_tool_results_merge_into_one_user_content():
89+
"""Gemini requires strict user/model alternation; two consecutive `user`
90+
contents are rejected with HTTP 400. Parallel tool calls produce two tool
91+
results in a row, so their functionResponses must be grouped into a single
92+
user content instead of two consecutive ones."""
93+
from agent.gemini_native_adapter import _build_gemini_contents
94+
95+
messages = [
96+
{"role": "user", "content": "Read a.txt and b.txt"},
97+
{
98+
"role": "assistant",
99+
"content": "",
100+
"tool_calls": [
101+
{"id": "call_1", "type": "function",
102+
"function": {"name": "read_file", "arguments": '{"path": "a.txt"}'}},
103+
{"id": "call_2", "type": "function",
104+
"function": {"name": "read_file", "arguments": '{"path": "b.txt"}'}},
105+
],
106+
},
107+
{"role": "tool", "tool_call_id": "call_1", "content": "AAA"},
108+
{"role": "tool", "tool_call_id": "call_2", "content": "BBB"},
109+
]
110+
111+
contents, _ = _build_gemini_contents(messages)
112+
roles = [c["role"] for c in contents]
113+
114+
# No two adjacent contents may share a role.
115+
assert all(roles[i] != roles[i - 1] for i in range(1, len(roles))), roles
116+
assert roles == ["user", "model", "user"]
117+
118+
# Both parallel functionResponses land in the single trailing user content.
119+
response_parts = [
120+
p for p in contents[2]["parts"] if "functionResponse" in p
121+
]
122+
outputs = [p["functionResponse"]["response"]["output"] for p in response_parts]
123+
assert outputs == ["AAA", "BBB"]
124+
125+
126+
def test_consecutive_user_messages_merge_for_gemini_alternation():
127+
"""Back-to-back user messages must also be merged, not sent as two
128+
consecutive user contents."""
129+
from agent.gemini_native_adapter import _build_gemini_contents
130+
131+
messages = [
132+
{"role": "user", "content": "first"},
133+
{"role": "user", "content": "second"},
134+
{"role": "assistant", "content": "ok"},
135+
]
136+
contents, _ = _build_gemini_contents(messages)
137+
roles = [c["role"] for c in contents]
138+
assert roles == ["user", "model"], roles
139+
140+
88141
def test_build_native_request_strips_json_schema_only_fields_from_tool_parameters():
89142
from agent.gemini_native_adapter import build_gemini_request
90143

0 commit comments

Comments
 (0)