: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): carry the stop reason on pydantic-ai and traceloop generations (#90744)
Bernat Torres97fd1189389c
diff --git a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.tsindex 42319a902b2e..0ef26bf789e4 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts@@ -326,6 +326,37 @@ describe('mapOtelAttributes', () => {expect(event.properties!.events).toBeUndefined()})+ it('carries the choice-level finish_reason onto the flat output message', () => {+ const events = [+ {+ index: 0,+ finish_reason: 'length',+ message: { role: 'assistant', content: 'wrapped' },+ 'event.name': 'gen_ai.choice',+ },+ {+ role: 'assistant',+ content: 'bare',+ finish_reason: 'stop',+ 'event.name': 'gen_ai.choice',+ },+ {+ role: 'assistant',+ content: 'oversized',+ finish_reason: 'x'.repeat(129),+ 'event.name': 'gen_ai.choice',+ },+ ]+ const event = createEvent('$ai_generation', { events: JSON.stringify(events) })+ mapOtelAttributes(event)++ expect(event.properties!.$ai_output_choices).toEqual([+ { role: 'assistant', content: 'wrapped', finish_reason: 'length' },+ { role: 'assistant', content: 'bare', finish_reason: 'stop' },+ { role: 'assistant', content: 'oversized' },+ ])+ })+it('orders $ai_input by gen_ai.message.index when all entries have one', () => {const events = [{ role: 'assistant', 'gen_ai.message.index': 2, 'event.name': 'gen_ai.assistant.message' },diff --git a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.ts b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.tsindex c6752154653d..d4799c81df3f 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.ts@@ -7,6 +7,8 @@ import {} from '~/ingestion/pipelines/ai/metrics'import { PluginEvent } from '~/plugin-scaffold'+import { usableStopReason } from './middleware/stop-reason'+const ATTRIBUTE_MAP: Record<string, string> = {'gen_ai.input.messages': '$ai_input','gen_ai.output.messages': '$ai_output_choices',@@ -279,14 +281,19 @@ function reconstructInputMessage(entry: Record<string, unknown>, eventName: stri}function reconstructOutputChoice(entry: Record<string, unknown>): Record<string, unknown> | null {- // Emit flat messages (matching newer-spec `gen_ai.output.messages`) so the- // frontend renderer picks them up directly. A `{ index, message }` wrapper- // would only be unwrapped by `isLiteLLMChoice`, which requires a- // `finish_reason` field we don't have.+ // Emit flat messages (matching newer-spec `gen_ai.output.messages`) so the frontend renderer+ // picks them up directly. The older spec reports `finish_reason` on the choice rather than on+ // the message, so carry it onto the flat message, which is where the middlewares' stop-reason+ // lift reads it.+ const finishReason = usableStopReason(entry.finish_reason)if (typeof entry.message === 'object' && entry.message !== null && !Array.isArray(entry.message)) {// Shallow-copy so the downstream $ai_output_choices array does not// share references with the transient parsed `events` payload.- return { ...(entry.message as Record<string, unknown>) }+ const message = { ...(entry.message as Record<string, unknown>) }+ if (finishReason !== undefined && message.finish_reason === undefined) {+ message.finish_reason = finishReason+ }+ return message}if ('role' in entry || 'content' in entry || 'tool_calls' in entry) {const message: Record<string, unknown> = {}@@ -299,6 +306,9 @@ function reconstructOutputChoice(entry: Record<string, unknown>): Record<string,if ('tool_calls' in entry) {message.tool_calls = entry.tool_calls}+ if (finishReason !== undefined) {+ message.finish_reason = finishReason+ }return message}return nulldiff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.test.tsindex bb77cc46e4fa..0ebda4a63920 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.test.ts@@ -356,6 +356,44 @@ describe('pydantic-ai middleware', () => {})})+ // pydantic-ai carries the finish reason on each output message. The generic mapping turns+ // `gen_ai.output.messages` into $ai_output_choices before this middleware runs, and that step is+ // covered in attribute-mapping.test.ts, so these start from the post-mapping shape.+ describe('sets $ai_stop_reason', () => {+ it.each<[string, unknown[], string | undefined]>([+ [+ 'the first choice that names one',+ [+ { role: 'assistant', content: 'first', finish_reason: 'stop' },+ { role: 'assistant', content: 'second', finish_reason: 'length' },+ ],+ 'stop',+ ],+ [+ 'past choices that name none',+ [+ { role: 'assistant', content: 'first' },+ { role: 'assistant', content: 'second', finish_reason: 'content_filter' },+ ],+ 'content_filter',+ ],+ ['nothing when no message names one', [{ role: 'assistant', content: 'only' }], undefined],+ [+ 'nothing when the only named reason is longer than any real value',+ [{ role: 'assistant', content: 'only', finish_reason: 'x'.repeat(129) }],+ undefined,+ ],+ ])('reads %s', (_label, outputChoices, expected) => {+ const event = createEvent('$ai_generation', {+ 'logfire.msg': 'chat',+ $ai_output_choices: outputChoices,+ })+ convertOtelEvent(event)++ expect(event.properties!['$ai_stop_reason']).toBe(expected)+ })+ })+describe('sets $ai_lib', () => {it.each(['$ai_generation', '$ai_span', '$ai_trace'])('sets $ai_lib to opentelemetry/pydantic-ai on %s events',diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.tsindex cd5c45a0e97f..74381f8849c4 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/pydantic-ai.ts@@ -1,6 +1,7 @@import { parseJSON } from '~/common/utils/json-parse'import { PluginEvent } from '~/plugin-scaffold'+import { liftStopReasonFromOutputChoices } from './stop-reason'import { OtelLibraryMiddleware } from './types'const LOGFIRE_STRIP_KEYS = [@@ -26,6 +27,10 @@ function process(event: PluginEvent, next: () => void): void {props['$ai_span_name'] = props['logfire.msg']}+ // pydantic-ai reports the finish reason inside each `gen_ai.output.messages` entry, and the+ // generic mapping in next() renamed that attribute to $ai_output_choices.+ liftStopReasonFromOutputChoices(props)+const isAgentRun = event.event === '$ai_trace' || props['pydantic_ai.all_messages'] !== undefinedif (isAgentRun) {let messages: Record<string, unknown>[] | undefineddiff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/stop-reason.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/stop-reason.tsnew file mode 100644index 000000000000..036a9f7b4780--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/stop-reason.ts@@ -0,0 +1,32 @@+// pydantic-ai and newer OpenLLMetry report the finish reason inside each output message rather+// than as its own span attribute. The generic mapping (or traceloop's reassembly) lands those+// messages in `$ai_output_choices`, so the reason has to be lifted out to survive as a property.++// Real finish reasons are short enum-like strings. The cap keeps a malformed or hostile attribute+// from landing a blob in $ai_stop_reason, matching the size guards on other parsed OTel payloads.+const MAX_STOP_REASON_LENGTH = 128++export function usableStopReason(value: unknown): string | undefined {+ return typeof value === 'string' && value !== '' && value.length <= MAX_STOP_REASON_LENGTH ? value : undefined+}++function finishReasonOf(message: unknown): string | undefined {+ if (typeof message !== 'object' || message === null) {+ return undefined+ }+ return usableStopReason((message as { finish_reason?: unknown }).finish_reason)+}++export function liftStopReasonFromOutputChoices(props: Record<string, unknown>): void {+ if (props['$ai_stop_reason'] !== undefined || !Array.isArray(props['$ai_output_choices'])) {+ return+ }+ // Every carrier that lands here holds one entry per choice, never sequential parts of one+ // response: the GenAI semconv defines output messages as choices, and pydantic-ai asserts a+ // single one per span. Take the first named reason, the choice the trace view renders first,+ // matching the flat `finish_reasons[0]` reads.+ const reason = props['$ai_output_choices'].map(finishReasonOf).find((r) => r !== undefined)+ if (reason !== undefined) {+ props['$ai_stop_reason'] = reason+ }+}diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.test.tsindex b71928ecd42d..c1612df8195a 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.test.ts@@ -239,5 +239,53 @@ describe('traceloop middleware', () => {expect(event.properties!['$ai_stop_reason']).toBeUndefined()})++ it('lifts the per-completion finish reason from indexed attributes', () => {+ const event = createEvent('$ai_generation', {+ 'llm.request.type': 'chat',+ 'gen_ai.completion.0.role': 'assistant',+ 'gen_ai.completion.0.content': 'hi',+ 'gen_ai.completion.0.finish_reason': 'length',+ })+ traceloop.process(event, () => mapOtelAttributes(event))++ expect(event.properties!['$ai_stop_reason']).toBe('length')+ expect(event.properties!['$ai_output_choices']).toEqual([+ { role: 'assistant', content: 'hi', finish_reason: 'length' },+ ])+ })++ it('ignores an oversized stop reason and falls through to the next source', () => {+ const event = createEvent('$ai_generation', {+ 'llm.request.type': 'chat',+ 'llm.response.stop_reason': 'x'.repeat(129),+ 'gen_ai.response.finish_reasons': ['stop'],+ })+ traceloop.process(event, () => mapOtelAttributes(event))++ expect(event.properties!['$ai_stop_reason']).toBe('stop')+ })++ it('maps gen_ai.response.finish_reasons when the llm.* names are absent', () => {+ const event = createEvent('$ai_generation', {+ 'llm.request.type': 'chat',+ 'gen_ai.response.finish_reasons': ['length'],+ })+ traceloop.process(event, () => mapOtelAttributes(event))++ expect(event.properties!['gen_ai.response.finish_reasons']).toBeUndefined()+ expect(event.properties!['$ai_stop_reason']).toBe('length')+ })++ it('prefers the llm.* reason over gen_ai.response.finish_reasons', () => {+ const event = createEvent('$ai_generation', {+ 'llm.request.type': 'chat',+ 'llm.response.stop_reason': 'end_turn',+ 'gen_ai.response.finish_reasons': ['length'],+ })+ traceloop.process(event, () => mapOtelAttributes(event))++ expect(event.properties!['$ai_stop_reason']).toBe('end_turn')+ })})})diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.tsindex eb65425e3edd..bda8958579a7 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/traceloop.ts@@ -1,6 +1,7 @@import { PluginEvent } from '~/plugin-scaffold'import { promotePosthogCustomMetadata } from './custom-metadata'+import { liftStopReasonFromOutputChoices, usableStopReason } from './stop-reason'import { OtelLibraryMiddleware } from './types'const STRIP_KEYS = [@@ -138,7 +139,12 @@ function process(event: PluginEvent, next: () => void): void {}if (props['$ai_output_choices'] === undefined) {- const completions = reassembleIndexedAttributes(props, 'gen_ai.completion.', ['role', 'content'], [])+ const completions = reassembleIndexedAttributes(+ props,+ 'gen_ai.completion.',+ ['role', 'content', 'finish_reason'],+ []+ )if (completions) {props['$ai_output_choices'] = completions}@@ -156,15 +162,26 @@ function process(event: PluginEvent, next: () => void): void {}}- // Map stop/finish reason to $ai_stop_reason before stripping+ // Map the stop/finish reason to $ai_stop_reason before stripping. OpenLLMetry writes it in up+ // to three places: the legacy flat `llm.response.*` names, the `gen_ai.response.finish_reasons`+ // array, which it sets even when content capture is off, and on each output message, which the+ // reassembly above lands in $ai_output_choices.if (props['$ai_stop_reason'] === undefined) {- const stopReason = props['llm.response.stop_reason'] ?? props['llm.response.finish_reason']+ const stopReason =+ usableStopReason(props['llm.response.stop_reason']) ?? usableStopReason(props['llm.response.finish_reason'])+ const genAiReasons = props['gen_ai.response.finish_reasons']+ // One reason per choice. The first choice is the one the trace view renders first.+ const firstGenAiReason = Array.isArray(genAiReasons) ? usableStopReason(genAiReasons[0]) : undefinedif (stopReason !== undefined) {props['$ai_stop_reason'] = stopReason+ } else if (firstGenAiReason !== undefined) {+ props['$ai_stop_reason'] = firstGenAiReason}}+ liftStopReasonFromOutputChoices(props)delete props['llm.response.stop_reason']delete props['llm.response.finish_reason']+ delete props['gen_ai.response.finish_reasons']props['$ai_lib'] = 'opentelemetry/traceloop'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 aa4de524f128..9ffbfe9858f0 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@@ -215,6 +215,17 @@ describe('vercel-ai middleware', () => {expect(event.properties!['$ai_stop_reason']).toBe('length')})+ it('ignores an oversized stop reason and falls through to the next source', () => {+ const event = createEvent('$ai_generation', {+ 'ai.operationId': 'ai.generateText.doGenerate',+ 'ai.response.finishReason': 'x'.repeat(129),+ 'gen_ai.response.finish_reasons': ['stop'],+ })+ convertOtelEvent(event)++ expect(event.properties!['$ai_stop_reason']).toBe('stop')+ })+it('normalizes AI SDK v7 detailed usage without relying on global cache semantics', () => {const event = createEvent('$ai_generation', {'ai.operationId': 'ai.streamText.doStream',diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.tsindex e97d0bce3f78..0c7576b5e8ce 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts@@ -5,6 +5,7 @@ import { mustAddReasoningCost } from '~/ingestion/pipelines/ai/costs/output-costimport { PluginEvent } from '~/plugin-scaffold'import { promotePosthogCustomMetadata } from './custom-metadata'+import { usableStopReason } from './stop-reason'import { OtelLibraryMiddleware } from './types'// Provider-specific and standard attributes to strip after processing.@@ -366,14 +367,17 @@ function process(event: PluginEvent, next: () => void): void {stripProcessedContext(props)- // Map finish reason to $ai_stop_reason before stripping+ // Map finish reason to $ai_stop_reason before stripping. An unusable value falls through to+ // the next source instead of winning by position.if (props['$ai_stop_reason'] === undefined) {- const vercelReason = props['ai.response.finishReason']+ const vercelReason = usableStopReason(props['ai.response.finishReason'])const genAiReasons = props['gen_ai.response.finish_reasons']+ // One reason per choice. The first choice is the one the trace view renders first.+ const firstGenAiReason = Array.isArray(genAiReasons) ? usableStopReason(genAiReasons[0]) : undefinedif (vercelReason !== undefined) {props['$ai_stop_reason'] = vercelReason- } else if (Array.isArray(genAiReasons) && genAiReasons.length > 0) {- props['$ai_stop_reason'] = genAiReasons[0]+ } else if (firstGenAiReason !== undefined) {+ props['$ai_stop_reason'] = firstGenAiReason}}delete props['ai.response.finishReason']