Skip to content

fix(gemini): normalize tool call/response parts in captured input - #823

Open
marco-g-pm wants to merge 1 commit into
mainfrom
claude/posthog-python-issue-725-573c16
Open

fix(gemini): normalize tool call/response parts in captured input#823
marco-g-pm wants to merge 1 commit into
mainfrom
claude/posthog-python-issue-725-573c16

Conversation

@marco-g-pm

@marco-g-pm marco-g-pm commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Fixes #725.

The Gemini wrapper copied function calls and their responses into $ai_input, in the raw form the google-genai SDK emits:

{"type": "function_call",     "function_call": {"name": "...", "args": {}}}
{"type": "function_response", "function_response": {"name": "...", "response": {}}}

No PostHog consumer knows those two shapes. The trace view matches four other tool-result shapes, so it never showed the tool response. The eval formatter found no text key and no content key, so it fell back to a raw repr() dump. Evals then flagged correct answers as hallucinations.

The response path already emitted the shared shape. That is why a tool call showed in the output, then vanished from the next request's history.

Changes

_format_part now emits the shared shapes:

  • function_call becomes {"type": "function", "function": {name, arguments}}
  • function_response becomes {"type": "function", "tool_name": ..., "content": ...}

Tool results carry tool_name, not a call id. Gemini pairs a response to a call by name and has no id to pass through.

$ai_output_choices does not change.

Out of scope

Automatic function calling. google-genai runs that tool loop inside generate_content. The turns live only on response.automatic_function_calling_history, which this wrapper never reads. I wrote and tested that fix, then dropped it to keep this change small. It needs its own issue.

Backward compatibility

The old shape shipped in 7.30.1, four days before this fix. Before 7.30.1 the input path dropped these parts. Nothing reads the old shape. The whole ai_observability product has no match for function_response.

Two points for a reviewer:

  • format_gemini_input sits in __all__, so its return shape is public. The Public API snapshot check still passes, because the signature did not change.
  • The new tool result has no nested function key. That is what stops isToolStepItem from reading it as a call.

💚 How did you test it?

  • I updated test_function_call_and_response_turns_preserved for both new shapes.
  • posthog/test/ai/: 438 pass, 61 skip. I left out otel/, which needs two packages my local env lacks.
  • I ran format_gemini_input over a real google-genai function-calling turn.
  • I ran the monorepo eval formatter against both shapes. The old shape gave a repr() dump. The new shape gives [FUNCTION] and the tool output, the same as Anthropic tool_result.

I did not test against a live Gemini key or a real project.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

Follow-up

PostHog/posthog#76028 teaches the trace view the old shape, so traces already stored render too. That fix covers the view only. Those traces still feed evals a repr() dump, because the eval path is a separate Python formatter.

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Written with Claude Code (Opus 5), directed by @marco-g-pm.

I first assumed a frontend patch would also fix the evals. It does not. Evals run through a separate Python formatter, which I checked by running it against both shapes. That result is what made the SDK the right place to fix this.

@marco-g-pm marco-g-pm self-assigned this Jul 31, 2026
@github-actions

github-actions Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-07-31 16:23:25 UTC
Duration: 338385ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 518ms
Endpoint And Method.Does Not Use Legacy Endpoints 1009ms
Required Headers.Has Authorization Bearer Header 1009ms
Required Headers.Has Content Type Json 1009ms
Required Headers.Has Posthog Sdk Info Format 1009ms
Required Headers.Has Posthog Attempt Header 1009ms
Required Headers.Has Posthog Request Id 1010ms
Required Headers.Has Posthog Request Timestamp 1009ms
Required Headers.Has User Agent 1009ms
Body Format.Body Has Created At And Batch 1009ms
Body Format.No Api Key In Body 1009ms
Body Format.No Sent At In Body 1009ms
Event Format.Event Has Required Root Fields 1009ms
Event Format.Event Uuid Is Valid 1010ms
Event Format.Event Timestamp Is Rfc3339 1009ms
Event Format.Distinct Id Is String 1010ms
Event Format.Distinct Id At Root Not Properties 1009ms
Event Format.Custom Properties Preserved 1009ms
Event Format.Set Properties Preserved 1009ms
Event Format.Set Once Properties Preserved 1010ms
Event Format.Groups Properties Preserved 1009ms
Event Format.Sdk Generates Uuid If Not Provided 1009ms
Event Format.Event Has Required Root Fields Batch 1012ms
Event Format.Event Uuid Is Valid Batch 1014ms
Event Format.Event Timestamp Is Rfc3339 Batch 1013ms
Event Format.Distinct Id Is String Batch 1012ms
Event Format.Distinct Id At Root Not Properties Batch 1013ms
Event Format.Custom Properties Preserved Batch 1013ms
Event Format.Set Properties Preserved Batch 1012ms
Event Format.Set Once Properties Preserved Batch 1013ms
Event Format.Groups Properties Preserved Batch 1013ms
Event Format.Sdk Generates Uuid If Not Provided Batch 1012ms
Batch Behavior.Multiple Events In Single Batch 1507ms
Batch Behavior.Batch Envelope Smoke 1014ms
Batch Behavior.Flush With No Events Sends Nothing 1005ms
Batch Behavior.Flush At Triggers Batch 1509ms
Batch Behavior.Created At Reflects Batch Creation Time 1011ms
Deduplication.Generates Unique Uuids 1506ms
Deduplication.Different Events Same Content Different Uuids 1507ms
Deduplication.Preserves Uuid On Retry 7515ms
Deduplication.Preserves Timestamp On Retry 7513ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 7513ms
Deduplication.No Duplicate Events In Batch 1504ms
Header Behavior On Retry.Attempt Header Starts At One 1009ms
Header Behavior On Retry.Attempt Header Increments On Retry 14515ms
Header Behavior On Retry.Request Id Preserved On Retry 7018ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3516ms
Header Behavior On Retry.Request Timestamp Changes On Retry 7514ms
Response Format Validation.Success Response Has Uuid Keyed Results 1007ms
Response Format Validation.Success Response Has Ok For Each Event 1507ms
Response Format Validation.Success No Retry After When All Ok 1508ms
Response Format Validation.Success Retry After Present When Retry Events 2511ms
Response Format Validation.Success No Retry After When Drop Only 1508ms
Response Format Validation.Response Echoes Request Id 1009ms
Retry Behavior.Retries On 408 7511ms
Retry Behavior.Retries On 500 7512ms
Retry Behavior.Retries On 503 9521ms
Retry Behavior.Retries On 504 7510ms
Retry Behavior.Retryable Errors Have Retry After 4512ms
Retry Behavior.Respects Retry After On Retryable Error 12517ms
Retry Behavior.Does Not Retry On 400 3504ms
Retry Behavior.Does Not Retry On 401 3508ms
Retry Behavior.Does Not Retry On 402 3507ms
Retry Behavior.Does Not Retry On 413 3509ms
Retry Behavior.Does Not Retry On 415 3507ms
Retry Behavior.Non Retryable Errors Have No Retry After 3509ms
Retry Behavior.Implements Backoff 23520ms
Retry Behavior.Max Retries Respected 23534ms
Partial Batch Handling.Handles 200 Full Success 2999ms
Partial Batch Handling.Handles 200 With All Ok 4511ms
Partial Batch Handling.Does Not Retry Dropped Events 4505ms
Partial Batch Handling.Does Not Retry Limited Events 4512ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 7514ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 7511ms
Partial Batch Handling.Retries Only Retry Events From Partial 7514ms
Partial Batch Handling.Partial Retry Preserves Uuids 7511ms
Partial Batch Handling.Partial Retry Attempt Header Increments 7509ms
Partial Batch Handling.Partial Retry Request Id Preserved 7513ms
Partial Batch Handling.Respects Retry After On Partial 9517ms
Partial Batch Handling.Unknown Result Treated As Terminal 4506ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 4507ms
Compression.Sends Gzip Content Encoding 1010ms
Compression.No Content Encoding When Disabled 1009ms
Compression.Compressed Body Is Decompressible 1009ms
Error Handling.Does Not Retry On Unknown 4Xx 3510ms
Event Options.Cookieless Mode Override 1008ms
Event Options.Disable Skew Correction Override 1009ms
Event Options.Process Person Profile Override 1009ms
Event Options.Product Tour Id Override 1009ms
Event Options.Unset Options Omitted 1010ms
Event Options.Options Override In Batch 1012ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 1010ms
Geoip And Historical Migration.Historical Migration Set In Body 1009ms
Geoip And Historical Migration.Historical Migration Absent By Default 1009ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 1006ms
Request Payload.Flags Request Uses V2 Query Param 1008ms
Request Payload.Flags Request Hits Flags Path Not Decide 1008ms
Request Payload.Flags Request Omits Authorization Header 1006ms
Request Payload.Token In Flags Body Matches Init 1007ms
Request Payload.Groups Round Trip 1008ms
Request Payload.Groups Default To Empty Object 1006ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 1007ms
Request Payload.Disable Geoip Omitted Defaults To False 1008ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 1007ms
Request Lifecycle.No Flags Request On Init Alone 503ms
Request Lifecycle.No Flags Request On Normal Capture 1507ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 1011ms
Request Lifecycle.Mock Response Value Is Returned To Caller 1003ms
Retry Behavior.Retries Flags On 502 1007ms
Retry Behavior.Retries Flags On 504 1007ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 1510ms

marco-g-pm added a commit to PostHog/posthog that referenced this pull request Jul 31, 2026
posthog-python 7.30.1-7.35.x wrote Gemini's native part shapes to
`$ai_input` verbatim:

    {"type": "function_call",     "function_call": {name, args}}
    {"type": "function_response", "function_response": {name, response}}

Neither matches any shape `isToolResult`/`isToolStepItem` know, so
traces captured in that window misclassify their tool loop three ways:

- `isToolMessage` computes `hasText` from content items that are neither
  a tool step nor a tool result, so a message carrying only a tool
  response counts as having real text and gets surfaced in the traces
  list as the human-readable answer.
- `isInternalToolResultUserMessage` requires every content item to be a
  tool result, so the framework-appended tool-response user message
  isn't classified internal and leaks as a visible user bubble.
- `isUnrenderableContentItem` treats the block as non-text content the
  transcript can't render.

The SDK now normalizes both kinds (PostHog/posthog-python#823), but
already-ingested traces keep the old shape, so match it here too.

`function_call` needs its nested object checked: OpenAI's Responses API
uses the same `type` with `name`/`call_id` at the top level, and
`isOpenAIResponsesFunctionCall` already owns that case.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Gemini's native `function_call`/`function_response` parts were passed
through to `$ai_input` verbatim, in a shape no PostHog consumer
recognizes. The trace renderer matches tool results against Anthropic
`tool_result`, Vercel `tool-result`, OpenAI Responses
`function_call_output`, and `{type: "function", tool_name, content}` —
none of which match — so tool responses never rendered, and the eval
formatter fell through to a raw `repr()` dump instead of a labeled tool
result.

The same SDK already normalized tool calls on the response path to
`{type: "function", function: {...}}`, which is why a call rendered in
the output but vanished once it appeared in the next request's history.

Normalize both part kinds in `_format_part`. Tool results use
`tool_name`/`content` rather than an id-carrying shape because Gemini
matches responses to calls by name and has no call ids to thread.

`$ai_output_choices` is unaffected: `format_gemini_response` hits its
explicit `function_call` branch before the `_format_part` fallback and
already emitted the normalized shape.

Fixes #725

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@marco-g-pm
marco-g-pm force-pushed the claude/posthog-python-issue-725-573c16 branch from 517694e to 5b65166 Compare July 31, 2026 16:16
marco-g-pm added a commit to PostHog/posthog that referenced this pull request Jul 31, 2026
posthog-python 7.30.1-7.35.x wrote Gemini's native part shapes to
`$ai_input` verbatim:

    {"type": "function_call",     "function_call": {name, args}}
    {"type": "function_response", "function_response": {name, response}}

Neither matches any shape `isToolResult`/`isToolStepItem` know, so
traces captured in that window misclassify their tool loop three ways:

- `isToolMessage` computes `hasText` from content items that are neither
  a tool step nor a tool result, so a message carrying only a tool
  response counts as having real text and gets surfaced in the traces
  list as the human-readable answer.
- `isInternalToolResultUserMessage` requires every content item to be a
  tool result, so the framework-appended tool-response user message
  isn't classified internal and leaks as a visible user bubble.
- `isUnrenderableContentItem` treats the block as non-text content the
  transcript can't render.

The SDK now normalizes both kinds (PostHog/posthog-python#823), but
already-ingested traces keep the old shape, so match it here too.

`function_call` needs its nested object checked: OpenAI's Responses API
uses the same `type` with `name`/`call_id` at the top level, and
`isOpenAIResponsesFunctionCall` already owns that case.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
marco-g-pm added a commit to PostHog/posthog that referenced this pull request Jul 31, 2026
posthog-python 7.30.1-7.35.x copied Gemini function calls and their
responses into `$ai_input` in the raw form the google-genai SDK emits:

    {"type": "function_call",     "function_call": {name, args}}
    {"type": "function_response", "function_response": {name, response}}

Neither matches any shape `isToolResult`/`isToolStepItem` know, so
traces captured in that window misclassify their tool loop three ways:

- `isToolMessage` computes `hasText` from content items that are neither
  a tool step nor a tool result, so a message carrying only a tool
  response counts as having real text and gets surfaced in the traces
  list as the human-readable answer.
- `isInternalToolResultUserMessage` requires every content item to be a
  tool result, so the framework-appended tool-response user message
  isn't classified internal and leaks as a visible user bubble.
- `isUnrenderableContentItem` treats the block as non-text content the
  transcript can't render.

The SDK now converts both kinds (PostHog/posthog-python#823), but
already-ingested traces keep the old form, so match it here too.

`function_call` needs its nested object checked: OpenAI's Responses API
uses the same `type` with `name`/`call_id` at the top level, and
`isOpenAIResponsesFunctionCall` already owns that case.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@marco-g-pm
marco-g-pm marked this pull request as ready for review July 31, 2026 21:19
@marco-g-pm
marco-g-pm requested a review from a team as a code owner July 31, 2026 21:19
@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "fix(gemini): normalize tool call/respons..." | Re-trigger Greptile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Missing tool call responses in traces

2 participants