The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gemini): embed images in Gemini 3.x functionResponse.parts for multimodal tool results
hbentel2673d5f5bdc0
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex 43d56464d0d..94558f87c81 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -391,6 +391,8 @@ def _translate_tool_result_to_gemini(message: Dict[str, Any],tool_name_by_call_id: Optional[Dict[str, str]] = None,include_ids: bool = False,+ *,+ is_gemini3: bool = False,) -> Dict[str, Any]:tool_name_by_call_id = tool_name_by_call_id or {}tool_call_id = str(message.get("tool_call_id") or "")@@ -404,7 +406,8 @@ def _translate_tool_result_to_gemini(or tool_call_idor "tool")- content = _coerce_content_to_text(message.get("content"))+ raw_content = message.get("content")+ content = _coerce_content_to_text(raw_content)try:parsed = json.loads(content) if content.strip().startswith(("{", "[")) else Noneexcept json.JSONDecodeError:@@ -424,12 +427,27 @@ def _translate_tool_result_to_gemini(}if include_ids and tool_call_id:function_response["id"] = tool_call_id+ # Gemini 3.x supports embedding images directly inside+ # functionResponse.parts (Google's recommended shape for multimodal tool+ # results — see "Multimodal function responses" in the Gemini docs).+ # Gemini 2.x rejects the field, so only attach inlineData when the target+ # model supports it — otherwise the vision tool result is silently+ # downgraded to text-only.+ if is_gemini3:+ image_parts = [+ p for p in _extract_multimodal_parts(raw_content)+ if "inlineData" in p+ ]+ if image_parts:+ function_response["parts"] = image_partsreturn {"functionResponse": function_response}def _build_gemini_contents(messages: List[Dict[str, Any]],include_tool_call_ids: bool = False,+ *,+ is_gemini3: bool = False,) -> tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]:system_text_parts: List[str] = []contents: List[Dict[str, Any]] = []@@ -453,6 +471,7 @@ def _build_gemini_contents(msg,tool_name_by_call_id=tool_name_by_call_id,include_ids=include_tool_call_ids,+ is_gemini3=is_gemini3,)],}@@ -650,9 +669,12 @@ def build_gemini_request(thinking_config: Any = None,model: str = "",) -> Dict[str, Any]:+ version = _gemini_major_version(model)+ is_gemini3 = version is not None and version >= 3contents, system_instruction = _build_gemini_contents(messages,include_tool_call_ids=gemini_requires_tool_call_ids(model),+ is_gemini3=is_gemini3,)request: Dict[str, Any] = {"contents": contents}if system_instruction:diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.pyindex 3adf1aa7e1e..c69ae3483e8 100644--- a/tests/agent/test_gemini_native_adapter.py+++ b/tests/agent/test_gemini_native_adapter.py@@ -567,3 +567,111 @@ class TestGemini3ToolCallIds:result = translate_gemini_response(resp, model="gemini-2.5-flash")tool_calls = result.choices[0].message.tool_callsassert tool_calls[0].id.startswith("call_")+++# ---------------------------------------------------------------------------+# Multimodal tool results: image embedding in functionResponse.parts+# ---------------------------------------------------------------------------++_PNG_DATA_URL = (+ "data:image/png;base64,"+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="+)+++def _vision_tool_messages():+ """Assistant tool_call + tool result carrying a text part and an image part."""+ return [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "vision_analyze", "arguments": "{}"},+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "name": "vision_analyze",+ "content": [+ {"type": "text", "text": "a red pixel"},+ {"type": "image_url", "image_url": {"url": _PNG_DATA_URL}},+ ],+ },+ ]+++ "model",+ [+ "gemini-3.5-flash",+ "gemini-3-flash-preview",+ "gemini-3-pro-preview",+ "gemini-3.1-flash-lite-preview",+ ],+)+def test_gemini_3x_embeds_image_in_function_response_parts(model):+ """Gemini 3.x multimodal tool results embed inlineData inside functionResponse.parts."""+ from agent.gemini_native_adapter import build_gemini_request++ request = build_gemini_request(+ messages=_vision_tool_messages(),+ model=model,+ tools=[],+ tool_choice=None,+ )+ fr = request["contents"][1]["parts"][0]["functionResponse"]+ assert "parts" in fr, "Gemini 3.x must embed image inlineData in functionResponse.parts"+ assert fr["parts"][0]["inlineData"]["mimeType"] == "image/png"+ assert fr["parts"][0]["inlineData"]["data"]+++def test_gemini_2x_does_not_embed_image_parts():+ """Gemini 2.x rejects functionResponse.parts — tool result stays text-only."""+ from agent.gemini_native_adapter import build_gemini_request++ request = build_gemini_request(+ messages=_vision_tool_messages(),+ model="gemini-2.5-flash",+ tools=[],+ tool_choice=None,+ )+ fr = request["contents"][1]["parts"][0]["functionResponse"]+ assert "parts" not in fr+++def test_text_only_tool_result_has_no_parts():+ """Text-only Gemini 3.x tool result does not add empty parts."""+ from agent.gemini_native_adapter import build_gemini_request++ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "read_file", "arguments": "{}"},+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "name": "read_file",+ "content": "file contents here",+ },+ ]+ request = build_gemini_request(+ messages=messages,+ model="gemini-3.6-flash",+ tools=[],+ tool_choice=None,+ )+ fr = request["contents"][1]["parts"][0]["functionResponse"]+ assert "parts" not in fr