Skip to content

: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.

fix(llma): populate playground from gemini otel traces (#58657)

Steven Shults6f32d4b26f1e
diff --git a/nodejs/src/ingestion/ai/metrics.ts b/nodejs/src/ingestion/ai/metrics.ts
index 4d34fe9d0ca2..16c2616db939 100644
--- a/nodejs/src/ingestion/ai/metrics.ts
+++ b/nodejs/src/ingestion/ai/metrics.ts
@@ -47,3 +47,9 @@ export const aiOtelOlderSpecEventsCounter = new Counter({
help: 'Outcome of decoding the older OTel GenAI span-events `events` attribute',
labelNames: ['outcome'],
})
+
+export const aiOtelSystemInstructionsCounter = new Counter({
+ name: 'llma_ai_otel_system_instructions_total',
+ help: 'Outcome of promoting `gen_ai.system_instructions` into a leading $ai_input system message',
+ labelNames: ['outcome'],
+})
diff --git a/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts b/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts
index 3e8ff2fb1697..9f3a97d4d7b9 100644
--- a/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts
+++ b/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts
@@ -483,6 +483,140 @@ describe('mapOtelAttributes', () => {
})
})
+ describe('gen_ai.system_instructions (Gemini OTel)', () => {
+ // Each row tests the same invariant — "given `gen_ai.system_instructions`
+ // of shape X with no existing `$ai_input`, produce `$ai_input` as a
+ // single leading system message with content Y, and strip the raw
+ // attribute." Cases with existing `$ai_input` state, no-op outcomes, or
+ // unrelated assertions live as their own `it()` blocks below.
+ it.each([
+ {
+ name: 'JSON-encoded parts array (Gemini default)',
+ value: JSON.stringify([{ type: 'text', content: 'You are a helpful assistant.' }]),
+ expectedContent: 'You are a helpful assistant.',
+ },
+ {
+ name: 'plain string',
+ value: 'Speak like a pirate.',
+ expectedContent: 'Speak like a pirate.',
+ },
+ {
+ name: 'already-parsed multi-part array (joined with \\n\\n)',
+ value: [
+ { type: 'text', content: 'Part one.' },
+ { type: 'text', content: 'Part two.' },
+ ],
+ expectedContent: 'Part one.\n\nPart two.',
+ },
+ {
+ name: 'invalid JSON kept as raw string',
+ value: 'not [valid json',
+ expectedContent: 'not [valid json',
+ },
+ {
+ name: 'unexpected object shape stringified',
+ value: { text: 'Speak softly.' },
+ expectedContent: '{"text":"Speak softly."}',
+ },
+ {
+ name: 'parts array with null/undefined entries filtered out',
+ value: [null, { type: 'text', content: 'Only this survives.' }, undefined],
+ expectedContent: 'Only this survives.',
+ },
+ ])('extracts system content from $name', ({ value, expectedContent }) => {
+ const event = createEvent('$ai_generation', { 'gen_ai.system_instructions': value })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toEqual([{ role: 'system', content: expectedContent }])
+ expect(event.properties!['gen_ai.system_instructions']).toBeUndefined()
+ })
+
+ it('prepends a system message in front of existing user-only $ai_input', () => {
+ const event = createEvent('$ai_generation', {
+ 'gen_ai.system_instructions': JSON.stringify([{ type: 'text', content: 'Be concise.' }]),
+ 'gen_ai.input.messages': JSON.stringify([{ role: 'user', content: 'Hi' }]),
+ })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toEqual([
+ { role: 'system', content: 'Be concise.' },
+ { role: 'user', content: 'Hi' },
+ ])
+ })
+
+ it('does not double-prepend when $ai_input already starts with a system message', () => {
+ const event = createEvent('$ai_generation', {
+ 'gen_ai.system_instructions': 'Ignored — already present.',
+ 'gen_ai.input.messages': JSON.stringify([
+ { role: 'system', content: 'Original system prompt.' },
+ { role: 'user', content: 'Hi' },
+ ]),
+ })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toEqual([
+ { role: 'system', content: 'Original system prompt.' },
+ { role: 'user', content: 'Hi' },
+ ])
+ expect(event.properties!['gen_ai.system_instructions']).toBeUndefined()
+ })
+
+ it('no-ops when the attribute is absent', () => {
+ const event = createEvent('$ai_generation', {
+ 'gen_ai.input.messages': JSON.stringify([{ role: 'user', content: 'Hi' }]),
+ })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toEqual([{ role: 'user', content: 'Hi' }])
+ })
+
+ it('strips the raw attribute even when the text is empty', () => {
+ const event = createEvent('$ai_generation', {
+ 'gen_ai.system_instructions': JSON.stringify([{ type: 'text', content: '' }]),
+ })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toBeUndefined()
+ expect(event.properties!['gen_ai.system_instructions']).toBeUndefined()
+ })
+
+ it('skips parsing when the string exceeds the size guard and still strips the attribute', () => {
+ const event = createEvent('$ai_generation', {
+ 'gen_ai.system_instructions': 'x'.repeat(500_001),
+ })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toBeUndefined()
+ expect(event.properties!['gen_ai.system_instructions']).toBeUndefined()
+ })
+
+ it('strips a null-valued attribute without touching existing $ai_input', () => {
+ const event = createEvent('$ai_generation', {
+ 'gen_ai.system_instructions': null,
+ 'gen_ai.input.messages': JSON.stringify([{ role: 'user', content: 'Hi' }]),
+ })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toEqual([{ role: 'user', content: 'Hi' }])
+ expect(event.properties!['gen_ai.system_instructions']).toBeUndefined()
+ })
+
+ it('does not overwrite an existing non-array $ai_input', () => {
+ // Upstream bug shape: `$ai_input` already set to a non-array value
+ // (e.g. a raw string from a malformed `gen_ai.input.messages` that
+ // failed JSON parsing). Don't clobber it — the `conflict` outcome
+ // surfaces this in prod via the counter.
+ const event = createEvent('$ai_generation', {
+ 'gen_ai.system_instructions': 'You are a helpful assistant.',
+ 'gen_ai.input.messages': 'not valid json',
+ })
+ mapOtelAttributes(event)
+
+ expect(event.properties!.$ai_input).toBe('not valid json')
+ expect(event.properties!['gen_ai.system_instructions']).toBeUndefined()
+ })
+ })
+
describe('older-spec span events composed with pydantic-ai middleware', () => {
it('reconstructs $ai_input/$ai_output_choices alongside pydantic-ai framework attributes', () => {
// Realistic runtime path: pydantic-ai middleware runs, calls
diff --git a/nodejs/src/ingestion/ai/otel/attribute-mapping.ts b/nodejs/src/ingestion/ai/otel/attribute-mapping.ts
index 13366b6a2f34..102afab03d82 100644
--- a/nodejs/src/ingestion/ai/otel/attribute-mapping.ts
+++ b/nodejs/src/ingestion/ai/otel/attribute-mapping.ts
@@ -1,7 +1,7 @@
import { PluginEvent } from '~/plugin-scaffold'
import { parseJSON } from '../../../utils/json-parse'
-import { aiOtelOlderSpecEventsCounter } from '../metrics'
+import { aiOtelOlderSpecEventsCounter, aiOtelSystemInstructionsCounter } from '../metrics'
const ATTRIBUTE_MAP: Record<string, string> = {
'gen_ai.input.messages': '$ai_input',
@@ -98,6 +98,7 @@ export function mapOtelAttributes(event: PluginEvent): void {
}
convertOlderSpecEvents(event)
+ convertSystemInstructions(event)
computeLatency(event)
promoteRootSpanToTrace(event)
@@ -203,6 +204,114 @@ function reconstructOutputChoice(entry: Record<string, unknown>): Record<string,
return null
}
+type SystemInstructionsOutcome =
+ | 'absent'
+ | 'too_large'
+ | 'empty'
+ | 'prepended'
+ | 'created'
+ | 'already_system'
+ | 'conflict'
+ | 'unexpected_error'
+
+// Gemini's OTel auto-instrumentor emits the system prompt as a top-level
+// `gen_ai.system_instructions` attribute (a string or a parts array like
+// `[{type:'text', content:'...'}]`) rather than as a `role:'system'` entry
+// inside `gen_ai.input.messages`. Promote it into `$ai_input` as a leading
+// system message so the conversation tab and the playground both see it.
+//
+// Mirrors the structure of `convertOlderSpecEvents`: skip entirely when the
+// attribute key is missing (no counter emitted), otherwise route every
+// branch through a single counter in `finally` so prod can observe how
+// often each outcome fires — including the `absent` case (key present but
+// value null/undefined), the silent-drop `empty`, and the unexpected
+// `conflict` case where `$ai_input` is set to a non-array value upstream.
+function convertSystemInstructions(event: PluginEvent): void {
+ const props = event.properties!
+ if (!('gen_ai.system_instructions' in props)) {
+ return
+ }
+
+ let outcome: SystemInstructionsOutcome = 'unexpected_error'
+ try {
+ const raw = props['gen_ai.system_instructions']
+ if (raw === undefined || raw === null) {
+ outcome = 'absent'
+ return
+ }
+
+ let value: unknown = raw
+ if (typeof value === 'string') {
+ // Same size ceiling as `convertOlderSpecEvents` — defensive against
+ // pathological payloads that would pressure the ingestion worker.
+ if (value.length > MAX_OLDER_SPEC_EVENTS_LENGTH) {
+ outcome = 'too_large'
+ return
+ }
+ try {
+ value = parseJSON(value)
+ } catch {
+ // Keep the original string — it's already the system text.
+ }
+ }
+
+ let text: string
+ if (typeof value === 'string') {
+ text = value
+ } else if (Array.isArray(value)) {
+ text = value
+ .filter(
+ (part): part is { type: string; content: unknown } =>
+ typeof part === 'object' &&
+ part !== null &&
+ 'type' in part &&
+ (part as { type: unknown }).type === 'text'
+ )
+ .map((part) => (typeof part.content === 'string' ? part.content : ''))
+ .filter((s) => s.length > 0)
+ .join('\n\n')
+ } else {
+ try {
+ text = JSON.stringify(value)
+ } catch {
+ text = String(value)
+ }
+ }
+
+ if (!text) {
+ outcome = 'empty'
+ return
+ }
+
+ const systemMessage = { role: 'system', content: text }
+ const existing = props.$ai_input
+ if (Array.isArray(existing)) {
+ const first = existing[0]
+ const firstIsSystem =
+ typeof first === 'object' && first !== null && (first as { role?: unknown }).role === 'system'
+ if (firstIsSystem) {
+ outcome = 'already_system'
+ } else {
+ props.$ai_input = [systemMessage, ...existing]
+ outcome = 'prepended'
+ }
+ } else if (existing === undefined) {
+ props.$ai_input = [systemMessage]
+ outcome = 'created'
+ } else {
+ // `$ai_input` was set to a non-array value (a string, a single
+ // object, etc.) — don't replace it, but flag the unexpected shape
+ // so prod can surface upstream bugs we'd otherwise silently absorb.
+ outcome = 'conflict'
+ }
+ } catch {
+ outcome = 'unexpected_error'
+ } finally {
+ delete props['gen_ai.system_instructions']
+ aiOtelSystemInstructionsCounter.labels({ outcome }).inc()
+ }
+}
+
function convertOlderSpecEvents(event: PluginEvent): void {
const props = event.properties!
if (!('events' in props)) {
diff --git a/products/llm_analytics/frontend/playground/llmPlaygroundLogic.test.ts b/products/llm_analytics/frontend/playground/llmPlaygroundLogic.test.ts
index 5aeeaaa1dc82..6a10f64b84cb 100644
--- a/products/llm_analytics/frontend/playground/llmPlaygroundLogic.test.ts
+++ b/products/llm_analytics/frontend/playground/llmPlaygroundLogic.test.ts
@@ -1324,6 +1324,59 @@ describe('llmPlaygroundLogic', () => {
expect(llmPlaygroundPromptsLogic.values.model).toBe('claude-3-opus')
})
+
+ it('should populate playground from Gemini OTel parts-shaped input', () => {
+ // Matches what opentelemetry-instrumentation-google-generativeai emits in gen_ai.input.messages.
+ const input = [
+ { role: 'user', parts: [{ type: 'text', content: 'What is the capital of France?' }] },
+ { role: 'model', parts: [{ type: 'text', content: 'The capital of France is Paris.' }] },
+ { role: 'user', parts: [{ type: 'text', content: 'And of Spain?' }] },
+ ]
+
+ llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })
+
+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([
+ { role: 'user', content: 'What is the capital of France?' },
+ { role: 'assistant', content: 'The capital of France is Paris.' },
+ { role: 'user', content: 'And of Spain?' },
+ ])
+ })
+
+ it('should populate system prompt + conversation from a Gemini OTel trace shape', () => {
+ // After Fix A (ingestion) prepends the system message synthesized from gen_ai.system_instructions,
+ // the playground sees a mix of standard `{role, content}` and OTel parts-shaped items.
+ const input = [
+ { role: 'system', content: 'You are a concise assistant.' },
+ { role: 'user', parts: [{ type: 'text', content: 'Tell me about Paris.' }] },
+ { role: 'model', parts: [{ type: 'text', content: 'Paris is the capital of France.' }] },
+ ]
+
+ llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })
+
+ expect(llmPlaygroundPromptsLogic.values.systemPrompt).toBe('You are a concise assistant.')
+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([
+ { role: 'user', content: 'Tell me about Paris.' },
+ { role: 'assistant', content: 'Paris is the capital of France.' },
+ ])
+ })
+
+ it('should join multi-part text content for OTel parts messages', () => {
+ const input = [
+ {
+ role: 'user',
+ parts: [
+ { type: 'text', content: 'First chunk.' },
+ { type: 'text', content: 'Second chunk.' },
+ ],
+ },
+ ]
+
+ llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })
+
+ const message = llmPlaygroundPromptsLogic.values.messages[0]
+ expect(message.role).toBe('user')
+ expect(message.content).toBe('First chunk.\n\nSecond chunk.')
+ })
})
describe('Multi-prompt state management', () => {
diff --git a/products/llm_analytics/frontend/playground/llmPlaygroundPromptsLogic.ts b/products/llm_analytics/frontend/playground/llmPlaygroundPromptsLogic.ts
index c14b9561c6be..0d5dd8f17c24 100644
--- a/products/llm_analytics/frontend/playground/llmPlaygroundPromptsLogic.ts
+++ b/products/llm_analytics/frontend/playground/llmPlaygroundPromptsLogic.ts
@@ -14,7 +14,7 @@ import { llmEvaluationLogic } from '../evaluations/llmEvaluationLogic'
import type { EvaluationConfig } from '../evaluations/types'
import { getApiErrorDetail, llmPromptLogic } from '../prompts/llmPromptLogic'
import { normalizeLLMProvider } from '../settings/llmProviderKeysLogic'
-import { normalizeRole, safeStringify } from '../utils'
+import { isOTelPartsMessage, normalizeMessage, normalizeRole, safeStringify } from '../utils'
import type { llmPlaygroundPromptsLogicType } from './llmPlaygroundPromptsLogicType'
import { isTraceLikeSelection } from './playgroundModelMatching'
@@ -974,9 +974,22 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
if (input) {
try {
+ // OTel `parts` messages (Gemini auto-instrumentor and any other gen_ai.* OTel
+ // provider that follows the OpenTelemetry AI semantic conventions) carry their
+ // text in `parts: [{type, content}]` instead of `content`. Expand only those
+ // entries via the shared normalizer the Conversation tab uses, so non-parts
+ // shapes keep their existing handling and we don't change behavior for
+ // OpenAI / Anthropic / Vercel / Traceloop / Pydantic traces.
+ const expandedInput = Array.isArray(input)
+ ? input.flatMap((msg) =>
+ isOTelPartsMessage(msg)
+ ? normalizeMessage(msg, normalizeRole(msg.role, 'user'))
+ : [msg]
+ )
+ : input
if (
- Array.isArray(input) &&
- input.every(
+ Array.isArray(expandedInput) &&
+ expandedInput.every(
(msg) =>
// Standard chat message: must have role + content/tool_calls
(msg.role && (msg.content != null || msg.tool_calls)) ||
@@ -985,7 +998,7 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
msg.type === 'function_call_output'
)
) {
- const systemContents = input
+ const systemContents = expandedInput
.filter((msg) => msg.role === 'system')
.map((msg) => msg.content)
.filter(
@@ -997,7 +1010,7 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
systemPromptContent = systemContents.join('\n\n')
}
- for (const msg of input as RawMessage[]) {
+ for (const msg of expandedInput as RawMessage[]) {
if (msg.role === 'system') {
continue
}