: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
fix(aio): render all otel genai part types and map tool definitions (#83258)
Carlos Marchal6c8c5cccfc93
diff --git a/nodejs/src/ingestion/pipelines/ai/metrics.ts b/nodejs/src/ingestion/pipelines/ai/metrics.tsindex 78104e0b8ba6..3116a2f312e6 100644--- a/nodejs/src/ingestion/pipelines/ai/metrics.ts+++ b/nodejs/src/ingestion/pipelines/ai/metrics.ts@@ -69,6 +69,12 @@ export const aiCacheExclusiveFallbackCounter = new Counter({labelNames: ['prior'], // prior: inclusive | anthropic_inclusive})+export const aiOtelUnknownPartTypeCounter = new Counter({+ name: 'aio_ai_otel_unknown_part_type_total',+ help: 'OTel GenAI message parts whose type no renderer handles, bucketed into a fixed label set, so new semconv part types surface here instead of as blank output',+ labelNames: ['part_type'],+})+export const aiBlobOffloadS3Duration = new Histogram({name: 'aio_blob_offload_s3_request_duration_seconds',help: 'Latency of S3 requests made by the AI blob offload store',diff --git a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.tsindex fc7c80f7e1da..42319a902b2e 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts@@ -1,4 +1,5 @@import { parseJSON } from '~/common/utils/json-parse'+import { aiOtelUnknownPartTypeCounter } from '~/ingestion/pipelines/ai/metrics'import { extractToolCallNames } from '~/ingestion/pipelines/ai/tools/extract-tool-calls'import { PluginEvent } from '~/plugin-scaffold'@@ -56,6 +57,55 @@ describe('mapOtelAttributes', () => {expect(event.properties!.$ai_input).toBe('not valid json')})+ it('JSON-parses gen_ai.tool.definitions into $ai_tools', () => {+ const tools = [{ type: 'function', name: 'get_weather', parameters: { type: 'object' } }]+ const event = createEvent('$ai_generation', {+ 'gen_ai.tool.definitions': JSON.stringify(tools),+ })+ mapOtelAttributes(event)+ expect(event.properties!.$ai_tools).toEqual(tools)+ expect(event.properties!['gen_ai.tool.definitions']).toBeUndefined()+ })++ describe('unknown message part types', () => {+ beforeEach(() => {+ aiOtelUnknownPartTypeCounter.reset()+ })++ const partCount = async (partType: string): Promise<number> => {+ const data = await aiOtelUnknownPartTypeCounter.get()+ return data.values.find((v) => v.labels.part_type === partType)?.value ?? 0+ }++ it('counts parts no renderer handles, bucketing producer-controlled labels into a fixed set', async () => {+ const event = createEvent('$ai_generation', {+ 'gen_ai.input.messages': JSON.stringify([+ {+ role: 'user',+ parts: [+ { type: 'text', content: 'hi' },+ { type: 'tool_approval_response', approved: true },+ { type: 'made-up-type-1', x: 1 },+ { type: 'made-up-type-2', x: 2 },+ { content: 'no type at all' },+ ],+ },+ ]),+ 'gen_ai.output.messages': JSON.stringify([+ { role: 'assistant', parts: [{ type: 'reasoning', content: 'hmm' }] },+ ]),+ })+ mapOtelAttributes(event)++ expect(await partCount('tool_approval_response')).toBe(1)+ expect(await partCount('other')).toBe(2)+ expect(await partCount('invalid')).toBe(1)+ expect(await partCount('made-up-type-1')).toBe(0)+ expect(await partCount('text')).toBe(0)+ expect(await partCount('reasoning')).toBe(0)+ })+ })+it('does not JSON-parse already-parsed objects', () => {const parsed = [{ role: 'user', content: 'Hello' }]const event = createEvent('$ai_generation', {diff --git a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.ts b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.tsindex b6b1509eec61..c6752154653d 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.ts@@ -3,12 +3,14 @@ import {aiOtelGroupsCounter,aiOtelOlderSpecEventsCounter,aiOtelSystemInstructionsCounter,+ aiOtelUnknownPartTypeCounter,} from '~/ingestion/pipelines/ai/metrics'import { PluginEvent } from '~/plugin-scaffold'const ATTRIBUTE_MAP: Record<string, string> = {'gen_ai.input.messages': '$ai_input','gen_ai.output.messages': '$ai_output_choices',+ 'gen_ai.tool.definitions': '$ai_tools','gen_ai.usage.input_tokens': '$ai_input_tokens','gen_ai.usage.output_tokens': '$ai_output_tokens','gen_ai.usage.cache_read.input_tokens': '$ai_cache_read_input_tokens',@@ -37,7 +39,7 @@ const STRIP_ATTRIBUTES = new Set(['llm.request.type',])-const JSON_PARSE_PROPERTIES = new Set(['$ai_input', '$ai_output_choices'])+const JSON_PARSE_PROPERTIES = new Set(['$ai_input', '$ai_output_choices', '$ai_tools'])// Older OTel GenAI spec emits messages as span events rather than// `gen_ai.input.messages` / `gen_ai.output.messages` attributes. Logfire@@ -110,6 +112,7 @@ export function mapOtelAttributes(event: PluginEvent): void {convertOlderSpecEvents(event)convertSystemInstructions(event)normalizeGroups(event)+ countUnknownMessageParts(event)computeLatency(event)promoteRootSpanToTrace(event)@@ -119,6 +122,63 @@ export function mapOtelAttributes(event: PluginEvent): void {}}+// Part types the trace view (llm-normalizer otel recipe) and the judge input+// flattener (posthog/temporal/ai_observability/message_utils.py) both render.+// Anything else is invisible to users, so it is counted rather than silently+// dropped: a spike in the counter means the semconv grew a part type (or a+// producer invented one) before we handle it.+const KNOWN_MESSAGE_PART_TYPES = new Set([+ 'text',+ 'reasoning',+ 'tool_call',+ 'tool_call_response',+ 'server_tool_call',+ 'server_tool_call_response',+ 'blob',+ 'file',+ 'uri',+ 'compaction',+])++// Part types real producers emit today that no renderer handles yet (the Vercel+// AI SDK emits both). They get their own label so a volume spike is attributable.+const EXPECTED_UNKNOWN_PART_TYPES = new Set(['tool_approval_response', 'custom'])++// The part type is producer-controlled and becomes a Prometheus label value, so+// it must map into a fixed set of buckets: a label per distinct string would let+// one sender mint unbounded series and grow ingestion memory without limit.+function partTypeLabel(type: unknown): string {+ if (typeof type !== 'string' || type.length === 0) {+ return 'invalid'+ }+ return EXPECTED_UNKNOWN_PART_TYPES.has(type) ? type : 'other'+}++function countUnknownMessageParts(event: PluginEvent): void {+ for (const key of ['$ai_input', '$ai_output_choices']) {+ const messages = event.properties![key]+ if (!Array.isArray(messages)) {+ continue+ }+ for (const message of messages) {+ if (typeof message !== 'object' || message === null) {+ continue+ }+ const parts = (message as { parts?: unknown }).parts+ if (!Array.isArray(parts)) {+ continue+ }+ for (const part of parts) {+ const type = typeof part === 'object' && part !== null ? (part as { type?: unknown }).type : undefined+ if (typeof type === 'string' && KNOWN_MESSAGE_PART_TYPES.has(type)) {+ continue+ }+ aiOtelUnknownPartTypeCounter.labels({ part_type: partTypeLabel(type) }).inc()+ }+ }+ }+}+type GroupsOutcome = 'parsed' | 'non_object' | 'malformed' | 'too_large'function normalizeGroups(event: PluginEvent): void {diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.tsindex 6ee06ffa16d3..5b16e909dd2b 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.ts@@ -89,6 +89,23 @@ describe('vercel-ai middleware', () => {expect(event.properties!['ai.operationId']).toBeUndefined()})+ it('parses legacy ai.prompt.tools entries into gen_ai.tool.definitions', () => {+ const event = createEvent('$ai_generation', {+ 'ai.operationId': 'ai.generateText.doGenerate',+ 'ai.prompt.tools': [+ JSON.stringify({ type: 'function', name: 'get_weather', parameters: { type: 'object' } }),+ 'not json {',+ ],+ })+ convertOtelEvent(event)++ expect(event.properties!['gen_ai.tool.definitions']).toEqual([+ { type: 'function', name: 'get_weather', parameters: { type: 'object' } },+ 'not json {',+ ])+ expect(event.properties!['ai.prompt.tools']).toBeUndefined()+ })+it('strips Vercel-specific attributes', () => {const event = createEvent('$ai_generation', {'ai.operationId': 'ai.generateText.doGenerate',diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.tsindex e50a453a88f6..79af8a6957bb 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts@@ -213,6 +213,26 @@ function process(event: PluginEvent, next: () => void): void {}delete props['ai.response.text']+ // Legacy AI SDK telemetry sends the tool catalog as ai.prompt.tools, an+ // array of individually stringified tool definitions. Parse each entry so+ // $ai_tools ends up carrying objects, like the current+ // gen_ai.tool.definitions attribute does.+ if (props['ai.prompt.tools'] !== undefined && props['gen_ai.tool.definitions'] === undefined) {+ const tools = props['ai.prompt.tools']+ if (Array.isArray(tools)) {+ props['gen_ai.tool.definitions'] = tools.map((tool) => {+ if (typeof tool !== 'string') {+ return tool+ }+ try {+ return parseJSON(tool)+ } catch {+ return tool+ }+ })+ }+ }+// Promote groups before the generic mapper runs so it can parse the JSON value.const groupsMetadata = getAiContextValue(props, '$groups')if (props['$groups'] === undefined && isNonEmptyString(groupsMetadata)) {diff --git a/packages/llm-normalizer/src/normalizer/recipe/default_recipes/otel.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/otel.yamlindex 49a19ea5ffe6..b046be9f40c6 100644--- a/packages/llm-normalizer/src/normalizer/recipe/default_recipes/otel.yaml+++ b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/otel.yaml@@ -1,11 +1,17 @@# OTel parts format: `{role, parts: [...]}`. text parts become content,-# tool_call parts become tool_calls, and each tool_call_response part spawns its-# own follow-up tool message. The GenAI semconv schema requires `response` for the+# tool_call parts become tool_calls, and each remaining part type spawns its+# own follow-up message. The GenAI semconv schema requires `response` for the# tool result, but its example showed `result` for ten months, so producers followed# both. Both keys are read, with `response` winning.## `if_empty: ~` drops the primary only when followups exist, so a message whose# parts produce nothing at all still emits one empty-content message (legacy parity).+#+# server_tool_call(_response) parts are provider-executed tools (web_search,+# code_interpreter); they render exactly like client tool calls so the call/result+# correlation by id still applies. blob/uri parts with image modality become+# renderable image items; other modalities and file references (no data to render)+# become bracketed text markers so the turn doesn't read as empty.id: otel@@ -28,16 +34,19 @@ rules:toolCalls:select:from: $.parts- where: { type: tool_call }+ where: { type: { in: [tool_call, server_tool_call] } }pluck:id: $.idname: $.name- args: $.arguments+ args:+ coalesce:+ - $.arguments+ - $.server_tool_callfollowups:- from:select:from: $.parts- where: { type: tool_call_response }+ where: { type: { in: [tool_call_response, server_tool_call_response] } }each:role: tooltoolCallId: $.id@@ -46,3 +55,54 @@ rules:coalesce:- $.response- $.result+ - $.server_tool_call_response+ - from:+ select:+ from: $.parts+ where: { type: reasoning, content: { is: string } }+ each:+ role: thinking+ content: $.content+ - from:+ select:+ from: $.parts+ where: { type: blob, modality: image }+ each:+ content:+ - type: image+ image: 'data:$.mime_type;base64,$.content'+ - from:+ select:+ from: $.parts+ where: { type: blob, modality: { in: [video, audio, document] } }+ each:+ content: '[$.modality]'+ - from:+ select:+ from: $.parts+ where: { type: uri, modality: image }+ each:+ content:+ - type: image+ image: $.uri+ - from:+ select:+ from: $.parts+ where: { type: uri, modality: { in: [video, audio, document] } }+ each:+ content: '[$.modality: $.uri]'+ - from:+ select:+ from: $.parts+ where: { type: file }+ each:+ content: '[file: $.file_id]'+ - from:+ select:+ from: $.parts+ where: { type: compaction }+ each:+ content:+ coalesce:+ - $.content+ - '[conversation compacted]'diff --git a/posthog/temporal/ai_observability/message_utils.py b/posthog/temporal/ai_observability/message_utils.pyindex 8e34feaf4d9d..73cea019ca02 100644--- a/posthog/temporal/ai_observability/message_utils.py+++ b/posthog/temporal/ai_observability/message_utils.py@@ -61,13 +61,22 @@ def _flatten_parts_message(msg: dict) -> list[dict]:Mirrors the trace UI's `otel.yaml` normalizer recipe so the judge sees the sameconversation the trace view renders:- `{"type": "text", "content": ...}` parts join into the message's `content`- - `{"type": "tool_call", "id", "name", "arguments"}` parts become `tool_calls`+ - `{"type": "tool_call", "id", "name", "arguments"}` parts become `tool_calls`,+ and so do `server_tool_call` parts (provider-executed tools like web_search),+ with the polymorphic `server_tool_call` payload as the arguments- each `{"type": "tool_call_response", "id", "response"}` part becomes its ownfollow-up `role: "tool"` message so the existing `tool[<id>]:` correlation applies.`response` is the field the GenAI semconv schema requires. The spec's own exampleshowed `result` for its first ten months, so producers that followed the example- are in the wild too, and both keys are read with `response` winning- - `reasoning` and other non-text parts are dropped, matching the trace view+ are in the wild too, and all of `response`/`result`/`server_tool_call_response`+ are read in that order, which also folds `server_tool_call_response` parts in+ - `reasoning` parts become follow-up `role: "thinking"` messages+ - `blob`/`uri`/`file` parts become bracketed text markers (`[image]`,+ `[image: <uri>]`, `[file: <id>]`). The trace view renders image blobs and uris+ as actual images; the judge gets markers instead because base64 payloads are+ token noise to an LLM+ - `compaction` parts become follow-up messages carrying the compacted summary,+ or a `[conversation compacted]` marker when the summary is absentLike the recipe, this only applies to dicts with a string `role` alongside the`parts` list, so a structured-output payload that happens to have its own `parts`@@ -84,7 +93,7 @@ def _flatten_parts_message(msg: dict) -> list[dict]:text_chunks: list[str] = []tool_calls: list[dict] = []- tool_results: list[dict] = []+ followups: list[dict] = []for part in parts:if not isinstance(part, dict):continue@@ -93,18 +102,33 @@ def _flatten_parts_message(msg: dict) -> list[dict]:content = part.get("content")if isinstance(content, str) and content:text_chunks.append(content)- elif part_type == "tool_call":+ elif part_type in ("tool_call", "server_tool_call"):+ arguments_key = "arguments" if part_type == "tool_call" else "server_tool_call"tool_calls.append({"id": part.get("id"),- "function": {"name": part.get("name", ""), "arguments": part.get("arguments", "")},+ "function": {"name": part.get("name", ""), "arguments": part.get(arguments_key, "")},})- elif part_type == "tool_call_response":- tool_response = next((part[key] for key in ("response", "result") if part.get(key) is not None), "")+ elif part_type in ("tool_call_response", "server_tool_call_response"):+ tool_response = next(+ (part[key] for key in ("response", "result", "server_tool_call_response") if part.get(key) is not None),+ "",+ )if not isinstance(tool_response, str):tool_response = json.dumps(tool_response, default=str)- tool_results.append({"role": "tool", "content": tool_response, "tool_call_id": part.get("id")})+ followups.append({"role": "tool", "content": tool_response, "tool_call_id": part.get("id")})+ elif part_type == "reasoning":+ reasoning = part.get("content")+ if isinstance(reasoning, str) and reasoning:+ followups.append({"role": "thinking", "content": reasoning})+ elif part_type in ("blob", "uri", "file"):+ followups.append({"role": msg["role"], "content": _media_part_marker(part_type, part)})+ elif part_type == "compaction":+ summary = part.get("content")+ if not (isinstance(summary, str) and summary):+ summary = "[conversation compacted]"+ followups.append({"role": msg["role"], "content": summary})primary = {key: value for key, value in msg.items() if key != "parts"}if text_chunks:@@ -112,17 +136,30 @@ def _flatten_parts_message(msg: dict) -> list[dict]:if tool_calls:primary["tool_calls"] = tool_calls- # Keep an empty primary only when there are no follow-up tool results, so a+ # Keep an empty primary only when there are no follow-up messages, so a# message whose parts produce nothing still holds its `role:` conversation slot# (matching how empty flat messages render) without adding a stray blank line- # in front of every tool result.+ # in front of every follow-up.flattened: list[dict] = []- if text_chunks or tool_calls or not tool_results:+ if text_chunks or tool_calls or not followups:flattened.append(primary)- flattened.extend(tool_results)+ flattened.extend(followups)return flattened+def _media_part_marker(part_type: str, part: dict) -> str:+ modality = part.get("modality")+ if not isinstance(modality, str) or not modality:+ modality = "media"+ if part_type == "blob":+ return f"[{modality}]"+ if part_type == "uri":+ uri = part.get("uri")+ return f"[{modality}: {uri}]" if isinstance(uri, str) and uri else f"[{modality}]"+ file_id = part.get("file_id")+ return f"[file: {file_id}]" if isinstance(file_id, str) and file_id else "[file]"++def _render_message(msg: dict) -> str | None:"""Render a single message dict into a `role: body` line.diff --git a/posthog/temporal/ai_observability/test_message_utils.py b/posthog/temporal/ai_observability/test_message_utils.pyindex 62bc9a86d552..99bce708483e 100644--- a/posthog/temporal/ai_observability/test_message_utils.py+++ b/posthog/temporal/ai_observability/test_message_utils.py@@ -357,7 +357,10 @@ class TestExtractTextFromMessages:],}]- assert extract_text_from_messages(messages) == "assistant: The warranty lasts three years."+ result = extract_text_from_messages(messages)+ assert result.splitlines()[0] == "assistant: The warranty lasts three years."+ assert "thinking: thinking it through" in result+ assert "thinking: more thinking" in resultdef test_otel_parts_multiple_text_parts_join(self):messages = [@@ -403,7 +406,7 @@ class TestExtractTextFromMessages:assert '[tool_call call_1: get_weather({"location": "Montreal"})]' in resultassert "tool[call_1]: -10C" in resultassert "assistant: It is -10C." in result- assert "need the weather tool" not in result+ assert "thinking: need the weather tool" in resultassert "stale" not in result@pytest.mark.parametrize(@@ -434,15 +437,84 @@ class TestExtractTextFromMessages:messages = [{"role": "user", "content": "flat wins", "parts": [{"type": "text", "content": "ignored"}]}]assert extract_text_from_messages(messages) == "user: flat wins"- def test_otel_parts_only_reasoning_preserves_role_slot(self):+ def test_otel_parts_only_reasoning_renders_thinking_without_empty_slot(self):messages = [{"role": "user", "parts": [{"type": "text", "content": "hi"}]},{"role": "assistant", "parts": [{"type": "reasoning", "content": "hmm"}]},]+ assert extract_text_from_messages(messages) == "user: hi\nthinking: hmm"++ def test_otel_parts_server_tool_conversation_correlates_calls_and_results(self):+ messages = [+ {"role": "user", "parts": [{"type": "text", "content": "Weather in Montreal?"}]},+ {+ "role": "assistant",+ "parts": [+ {+ "type": "server_tool_call",+ "id": "st_1",+ "name": "web_search",+ "server_tool_call": {"type": "web_search", "query": "Montreal weather"},+ }+ ],+ },+ {+ "role": "assistant",+ "parts": [+ {+ "type": "server_tool_call_response",+ "id": "st_1",+ "server_tool_call_response": {"type": "web_search", "status": "completed"},+ }+ ],+ },+ {"role": "assistant", "parts": [{"type": "text", "content": "It is -10C."}]},+ ]result = extract_text_from_messages(messages)- assert "user: hi" in result- assert "assistant:" in result- assert "hmm" not in result+ assert '[tool_call st_1: web_search({"type": "web_search", "query": "Montreal weather"})]' in result+ assert 'tool[st_1]: {"type": "web_search", "status": "completed"}' in result+ assert "assistant: It is -10C." in result++ @pytest.mark.parametrize(+ ("part", "marker"),+ [+ pytest.param(+ {"type": "blob", "modality": "image", "mime_type": "image/png", "content": "aGVsbG8="},+ "[image]",+ id="image_blob_renders_marker_not_base64",+ ),+ pytest.param(+ {"type": "uri", "modality": "image", "uri": "https://example.com/cat.jpg"},+ "[image: https://example.com/cat.jpg]",+ id="image_uri",+ ),+ pytest.param(+ {"type": "uri", "modality": "document", "uri": "https://example.com/doc.pdf"},+ "[document: https://example.com/doc.pdf]",+ id="document_uri",+ ),+ pytest.param({"type": "file", "file_id": "file_123"}, "[file: file_123]", id="file_reference"),+ pytest.param({"type": "blob", "content": "aGVsbG8="}, "[media]", id="blob_without_modality"),+ ],+ )+ def test_otel_parts_media_render_markers(self, part, marker):+ messages = [{"role": "user", "parts": [{"type": "text", "content": "Look at this."}, part]}]+ assert extract_text_from_messages(messages) == f"user: Look at this.\nuser: {marker}"++ @pytest.mark.parametrize(+ ("compaction_part", "expected"),+ [+ pytest.param(+ {"type": "compaction", "id": "c1", "content": "Earlier turns covered pricing."},+ "user: Earlier turns covered pricing.",+ id="summary_present",+ ),+ pytest.param({"type": "compaction", "id": "c1"}, "user: [conversation compacted]", id="summary_absent"),+ ],+ )+ def test_otel_parts_compaction_renders_summary(self, compaction_part, expected):+ messages = [{"role": "user", "parts": [compaction_part]}]+ assert extract_text_from_messages(messages) == expected@pytest.mark.parametrize("parts",@@ -451,7 +523,7 @@ class TestExtractTextFromMessages:pytest.param([{"type": "text"}], id="text_part_without_content"),pytest.param([{"type": "tool_call"}], id="tool_call_without_name"),pytest.param([{"no_type": True}], id="part_without_type"),- pytest.param([{"type": "file", "data": "aGVsbG8="}], id="unknown_part_type"),+ pytest.param([{"type": "tool_approval_response", "approved": True}], id="unknown_part_type"),],)def test_malformed_or_unknown_parts_do_not_crash(self, parts):diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.tsindex c0784d8883e0..037c95ffe225 100644--- a/products/ai_observability/frontend/utils.test.ts+++ b/products/ai_observability/frontend/utils.test.ts@@ -2311,6 +2311,143 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, normexpect(normalizeMessage(message, 'user')).toEqual([{ role: 'assistant', content: '' }])})++ it('normalizes reasoning parts into thinking messages without an empty primary', () => {+ const message = {+ role: 'assistant',+ parts: [+ { type: 'reasoning', content: 'The user wants the forecast.' },+ { type: 'text', content: 'Here is the forecast.' },+ ],+ }++ expect(normalizeMessage(message, 'user')).toEqual([+ { role: 'assistant', content: 'Here is the forecast.' },+ { role: 'assistant (thinking)', content: 'The user wants the forecast.' },+ ])+ })++ it('normalizes a reasoning-only message into just a thinking message', () => {+ const message = {+ role: 'assistant',+ parts: [{ type: 'reasoning', content: 'Considering options.' }],+ }++ expect(normalizeMessage(message, 'user')).toEqual([+ { role: 'assistant (thinking)', content: 'Considering options.' },+ ])+ })++ it('normalizes server_tool_call parts into tool calls', () => {+ const message = {+ role: 'assistant',+ parts: [+ {+ type: 'server_tool_call',+ id: 'st_1',+ name: 'web_search',+ server_tool_call: { type: 'web_search', query: 'weather in Montreal' },+ },+ ],+ }++ expect(normalizeMessage(message, 'user')).toEqual([+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ type: 'function',+ id: 'st_1',+ function: {+ name: 'web_search',+ arguments: { type: 'web_search', query: 'weather in Montreal' },+ },+ },+ ],+ },+ ])+ })++ it('normalizes server_tool_call_response parts into tool messages', () => {+ const message = {+ role: 'assistant',+ parts: [+ {+ type: 'server_tool_call_response',+ id: 'st_1',+ server_tool_call_response: { type: 'web_search', status: 'completed' },+ },+ ],+ }++ expect(normalizeMessage(message, 'user')).toEqual([+ {+ role: 'tool',+ content: '{"type":"web_search","status":"completed"}',+ tool_call_id: 'st_1',+ },+ ])+ })++ it('normalizes image blob parts into data-URI image items', () => {+ const message = {+ role: 'user',+ parts: [+ { type: 'text', content: 'What is in this picture?' },+ { type: 'blob', modality: 'image', mime_type: 'image/png', content: 'aGVsbG8=' },+ ],+ }++ expect(normalizeMessage(message, 'user')).toEqual([+ { role: 'user', content: 'What is in this picture?' },+ { role: 'user', content: [{ type: 'image', image: 'data:image/png;base64,aGVsbG8=' }] },+ ])+ })++ it('normalizes image uri parts into image items', () => {+ const message = {+ role: 'user',+ parts: [+ { type: 'uri', modality: 'image', mime_type: 'image/jpeg', uri: 'https://example.com/cat.jpg' },+ ],+ }++ expect(normalizeMessage(message, 'user')).toEqual([+ { role: 'user', content: [{ type: 'image', image: 'https://example.com/cat.jpg' }] },+ ])+ })++ it.each([+ [+ 'a non-image blob',+ { type: 'blob', modality: 'audio', mime_type: 'audio/mp3', content: 'aGVsbG8=' },+ '[audio]',+ ],+ [+ 'a non-image uri',+ { type: 'uri', modality: 'document', mime_type: 'application/pdf', uri: 'https://example.com/doc.pdf' },+ '[document: https://example.com/doc.pdf]',+ ],+ ['a file reference', { type: 'file', modality: 'document', file_id: 'file_123' }, '[file: file_123]'],+ ])('normalizes %s into a text marker', (_label, part, expectedContent) => {+ const message = { role: 'user', parts: [part] }++ expect(normalizeMessage(message, 'user')).toEqual([{ role: 'user', content: expectedContent }])+ })++ it.each([+ [+ 'its summary when present',+ { type: 'compaction', id: 'c1', content: 'Earlier turns covered pricing.' },+ 'Earlier turns covered pricing.',+ ],+ ['a marker when the summary is absent', { type: 'compaction', id: 'c1' }, '[conversation compacted]'],+ ])('normalizes compaction parts into %s', (_label, part, expectedContent) => {+ const message = { role: 'user', parts: [part] }++ expect(normalizeMessage(message, 'user')).toEqual([{ role: 'user', content: expectedContent }])+ })})describe('getSessionID', () => {