Skip to content

Build and run agents you can see, understand and trust.

fix(formatter): drop empty thinking blocks for Gemini API (#2013)

nolanchic942c004f7bd4
diff --git a/src/agentscope/formatter/_gemini_formatter.py b/src/agentscope/formatter/_gemini_formatter.py
index 6bb2f92f6..e495d38ee 100644
--- a/src/agentscope/formatter/_gemini_formatter.py
+++ b/src/agentscope/formatter/_gemini_formatter.py
@@ -157,7 +157,14 @@ class GeminiChatFormatter(_GeminiFormatterBase):
# Gemini API requires `thought: true` to mark a part as a
# thinking/reasoning block so the model can distinguish it
# from normal text and maintain reasoning continuity.
- parts.append({"thought": True, "text": block.thinking})
+ # Skip empty thinking — Gemini rejects a thought part
+ # whose text is empty with a 400
+ # ("contents.parts must not be empty"). Empty thinking
+ # occurs when a reasoning model returns no summary.
+ if block.thinking:
+ parts.append(
+ {"thought": True, "text": block.thinking},
+ )
elif isinstance(block, HintBlock):
if parts:
diff --git a/tests/formatter_gemini_test.py b/tests/formatter_gemini_test.py
index fc4969340..b43fabbd6 100644
--- a/tests/formatter_gemini_test.py
+++ b/tests/formatter_gemini_test.py
@@ -307,6 +307,36 @@ class TestGeminiFormatter(IsolatedAsyncioTestCase):
res,
)
+ async def test_empty_thinking_block_is_dropped(self) -> None:
+ """An empty ``ThinkingBlock`` must be skipped, not forwarded.
+
+ Gemini rejects a thought part whose text is empty with a 400
+ ("contents.parts must not be empty"). Empty thinking blocks occur
+ when a reasoning model returns no summary, so the formatter must
+ drop them rather than emit ``{"thought": True, "text": ""}``.
+ """
+ fmt = GeminiChatFormatter()
+ msgs = [
+ AssistantMsg(
+ name="assistant",
+ content=[
+ ThinkingBlock(thinking=""),
+ TextBlock(text="reply"),
+ ],
+ ),
+ ]
+
+ res = await fmt.format(msgs)
+
+ # Only the text part remains — no empty thought part.
+ self.assertEqual(len(res), 1)
+ self.assertEqual(res[0]["role"], "model")
+ thought_parts = [
+ p for p in res[0]["parts"] if p.get("thought") is True
+ ]
+ self.assertEqual(thought_parts, [])
+ self.assertEqual(res[0]["parts"], [{"text": "reply"}])
+
@patch(
"agentscope.formatter._formatter_base.shortuuid.uuid",
return_value=_FIXED_ID,