:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): map tool messages to gemini function calls in the llm proxy (#111709)
Juraj Majerike19d9bf0cfa8
diff --git a/products/ai_observability/backend/llm/providers/gemini.py b/products/ai_observability/backend/llm/providers/gemini.pyindex c8b941208ebc..51fc393d094f 100644--- a/products/ai_observability/backend/llm/providers/gemini.py+++ b/products/ai_observability/backend/llm/providers/gemini.py@@ -22,6 +22,7 @@ from products.ai_observability.backend.llm.errors import (ModelNotFoundError,ModelPermissionError,ProviderConnectionError,+ ProviderRequestRejectedError,QuotaExceededError,RateLimitError,StructuredOutputParseError,@@ -34,7 +35,10 @@ from products.ai_observability.backend.llm.types import (StreamChunk,Usage,)-from products.ai_observability.backend.providers.formatters.gemini_formatter import convert_anthropic_messages_to_gemini+from products.ai_observability.backend.providers.formatters.gemini_formatter import (+ MessageConversionError,+ convert_anthropic_messages_to_gemini,+)logger = logging.getLogger(__name__)@@ -151,6 +155,9 @@ class GeminiAdapter:`complete` and `stream` both route through this, so the same provider failure reads thesame way whether the caller streamed it or not."""+ if isinstance(error, MessageConversionError):+ # The user authored the message that failed to convert, so show the reason.+ return ProviderRequestRejectedError(str(error))if isinstance(error, APIError):error_message = str(error).lower()status_code = getattr(error, "code", None) or getattr(error, "status_code", None)diff --git a/products/ai_observability/backend/providers/formatters/gemini_formatter.py b/products/ai_observability/backend/providers/formatters/gemini_formatter.pyindex 5b2f5d2f2359..904f7b28ee16 100644--- a/products/ai_observability/backend/providers/formatters/gemini_formatter.py+++ b/products/ai_observability/backend/providers/formatters/gemini_formatter.py@@ -1,19 +1,97 @@+import jsonimport base64from typing import Any, cast-from google.genai.types import Blob, Content, ContentListUnion, Part+from google.genai.types import Blob, Content, ContentListUnion, FunctionCall, FunctionResponse, Partfrom products.ai_observability.backend.providers.formatters.anthropic_typeguards import (is_base64_image_param,is_image_block_param,is_text_block_param,+ is_tool_result_param,+ is_tool_use_param,)+# Gemini 3 rejects a request when the first function call in a replayed model turn has no+# thought signature. Imported Anthropic-style blocks never carry one, so use the documented+# dummy that skips validation on both the Gemini API and Vertex:+# https://ai.google.dev/gemini-api/docs/thought-signatures#faqs+_SKIP_THOUGHT_SIGNATURE = b"skip_thought_signature_validator"+++class MessageConversionError(ValueError):+ """A message cannot be converted to the provider's wire format.++ The message carries the reason and is safe to show to the user. Defined here instead+ of `llm.errors` because `llm/__init__` imports the providers, which import this module,+ so the reverse import would be a cycle. The Gemini adapter maps this to+ `ProviderRequestRejectedError`.+ """+++def _tool_call_args(input_value: Any, tool_name: str) -> dict[str, Any]:+ if input_value is None:+ return {}+ if isinstance(input_value, dict):+ return input_value+ # Callers that aggregate streamed tool calls carry the arguments as a JSON string.+ # Anything that does not parse to an object gets rejected rather than silently+ # replaced, which would re-run the conversation with different arguments.+ if isinstance(input_value, str):+ try:+ parsed = json.loads(input_value)+ except json.JSONDecodeError:+ parsed = None+ if isinstance(parsed, dict):+ return parsed+ raise MessageConversionError(+ f"Tool call arguments for '{tool_name}' are not a JSON object. Fix the arguments, then run again."+ )+++def _tool_response_payload(content: Any, *, is_error: bool = False) -> dict[str, Any]:+ """Shape a tool result into the dict Gemini requires for a function response.++ A result marked `is_error` goes under the `error` key, which is how Gemini+ distinguishes a failed tool run from an ordinary result.+ """+ value: Any+ if isinstance(content, list):+ # A Gemini function response is a dict, so media blocks cannot cross as-is.+ # Leave a marker rather than silently dropping them, which would turn an+ # image-only result into an empty one.+ rendered: list[str] = []+ for block in content:+ if is_text_block_param(block):+ rendered.append(block["text"])+ elif is_image_block_param(block):+ rendered.append("[image omitted]")+ else:+ rendered.append("[unsupported content omitted]")+ content = "\n".join(rendered)+ if isinstance(content, dict):+ value = content+ elif isinstance(content, str):+ try:+ parsed = json.loads(content)+ except json.JSONDecodeError:+ parsed = None+ value = parsed if isinstance(parsed, dict) else content+ else:+ value = "" if content is None else str(content)+ if is_error:+ return {"error": value}+ return value if isinstance(value, dict) else {"result": value}+def convert_anthropic_messages_to_gemini(messages: list[dict[str, Any]]) -> ContentListUnion:contents: list[Content] = [] # Sticking to Content, as we don't support other formats yet+ # Gemini keys a function response by function name, but Anthropic-style tool_result+ # blocks only carry the call id, so resolve names from the earlier tool_use blocks.+ tool_name_by_call_id: dict[str, str] = {}for message in messages:parts: list[Part] = []+ is_first_function_call = Trueif isinstance(message["content"], str):parts.append(Part(text=message["content"]))elif isinstance(message["content"], list):@@ -31,6 +109,36 @@ def convert_anthropic_messages_to_gemini(messages: list[dict[str, Any]]) -> Cont)))+ elif is_tool_use_param(block):+ name = str(block["name"])+ call_id = block.get("id")+ if isinstance(call_id, str):+ tool_name_by_call_id[call_id] = name+ parts.append(+ Part(+ function_call=FunctionCall(+ id=call_id if isinstance(call_id, str) else None,+ name=name,+ args=_tool_call_args(block.get("input"), name),+ ),+ thought_signature=_SKIP_THOUGHT_SIGNATURE if is_first_function_call else None,+ )+ )+ is_first_function_call = False+ elif is_tool_result_param(block):+ call_id = block.get("tool_use_id")+ name = tool_name_by_call_id.get(cast(str, call_id), "") or str(call_id or "unknown")+ parts.append(+ Part(+ function_response=FunctionResponse(+ id=call_id if isinstance(call_id, str) else None,+ name=name,+ response=_tool_response_payload(+ block.get("content"), is_error=block.get("is_error") is True+ ),+ )+ )+ )else:raise ValueError(f"Unsupported content block type: {type(block)}")diff --git a/products/ai_observability/backend/providers/formatters/test/__init__.py b/products/ai_observability/backend/providers/formatters/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/ai_observability/backend/providers/formatters/test/test_gemini_formatter.py b/products/ai_observability/backend/providers/formatters/test/test_gemini_formatter.pynew file mode 100644index 000000000000..bca4b7dd194d--- /dev/null+++ b/products/ai_observability/backend/providers/formatters/test/test_gemini_formatter.py@@ -0,0 +1,139 @@+from typing import Any, cast++import pytest++from google.genai.types import Content, FunctionCall, FunctionResponse, Part+from parameterized import parameterized++from products.ai_observability.backend.providers.formatters.gemini_formatter import (+ MessageConversionError,+ convert_anthropic_messages_to_gemini,+)+++def _convert(messages: list[dict[str, Any]]) -> list[Content]:+ return cast(list[Content], convert_anthropic_messages_to_gemini(messages))+++def _part(content: Content, index: int) -> Part:+ assert content.parts is not None+ return content.parts[index]+++def _function_call(content: Content, index: int) -> FunctionCall:+ function_call = _part(content, index).function_call+ assert function_call is not None+ return function_call+++def _function_response(content: Content, index: int) -> FunctionResponse:+ function_response = _part(content, index).function_response+ assert function_response is not None+ return function_response+++class TestConvertAnthropicMessagesToGemini:+ @parameterized.expand(+ [+ ("dict_input", {"location": "Paris"}, {"location": "Paris"}),+ ("json_string_input", '{"location": "Paris"}', {"location": "Paris"}),+ ]+ )+ def test_tool_use_becomes_function_call(self, _name, input_value, expected_args):+ contents = _convert(+ [+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Checking the weather."},+ {"type": "tool_use", "id": "call_1", "name": "get_weather", "input": input_value},+ ],+ }+ ]+ )++ content = contents[0]+ assert content.role == "model"+ assert _part(content, 0).text == "Checking the weather."+ function_call = _function_call(content, 1)+ assert function_call.id == "call_1"+ assert function_call.name == "get_weather"+ assert function_call.args == expected_args++ @parameterized.expand(+ [+ ("plain_string", "Sunny, 21C", {"result": "Sunny, 21C"}),+ ("json_object_string", '{"temperature": 21}', {"temperature": 21}),+ ("text_block_list", [{"type": "text", "text": "Sunny, 21C"}], {"result": "Sunny, 21C"}),+ (+ "image_only_block_list",+ [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aGk="}}],+ {"result": "[image omitted]"},+ ),+ ]+ )+ def test_tool_result_becomes_function_response(self, _name, result_content, expected_response):+ contents = _convert(+ [+ {+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {}}],+ },+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": result_content}],+ },+ ]+ )++ assert contents[1].role == "user"+ function_response = _function_response(contents[1], 0)+ assert function_response.id == "call_1"+ assert function_response.name == "get_weather"+ assert function_response.response == expected_response++ def test_first_function_call_in_a_turn_gets_the_skip_signature(self):+ contents = _convert(+ [+ {+ "role": "assistant",+ "content": [+ {"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {}},+ {"type": "tool_use", "id": "call_2", "name": "get_weather", "input": {}},+ ],+ }+ ]+ )++ assert _part(contents[0], 0).thought_signature == b"skip_thought_signature_validator"+ assert _part(contents[0], 1).thought_signature is None++ def test_unparseable_tool_call_arguments_are_rejected(self):+ with pytest.raises(MessageConversionError, match="get_weather"):+ convert_anthropic_messages_to_gemini(+ [+ {+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "call_1", "name": "get_weather", "input": "not json"}],+ }+ ]+ )++ def test_errored_tool_result_becomes_error_response(self):+ contents = _convert(+ [+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "boom", "is_error": True}],+ }+ ]+ )++ assert _function_response(contents[0], 0).response == {"error": "boom"}++ def test_tool_result_without_matching_tool_use_falls_back_to_call_id(self):+ contents = _convert(+ [{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_9", "content": "ok"}]}]+ )++ assert _function_response(contents[0], 0).name == "call_9"diff --git a/products/ai_observability/backend/providers/formatters/test/test_openai_formatter.py b/products/ai_observability/backend/providers/formatters/test/test_openai_formatter.pynew file mode 100644index 000000000000..3ac878d120b9--- /dev/null+++ b/products/ai_observability/backend/providers/formatters/test/test_openai_formatter.py@@ -0,0 +1,35 @@+from products.ai_observability.backend.providers.formatters.openai_formatter import convert_to_openai_messages+++class TestConvertToOpenAIMessages:+ def test_tool_use_and_tool_result_round_trip(self):+ result = convert_to_openai_messages(+ [+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Checking the weather."},+ {"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {"location": "Paris"}},+ ],+ },+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "Sunny, 21C"}],+ },+ ]+ )++ assert result == [+ {+ "role": "assistant",+ "content": "Checking the weather.",+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "get_weather", "arguments": '{"location": "Paris"}'},+ }+ ],+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "Sunny, 21C"},+ ]