: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): support Eve runtime context attributes (#74329)
Radu Raicea8a89abc0c9a6
diff --git a/docs/onboarding/ai-observability/eve.tsx b/docs/onboarding/ai-observability/eve.tsxindex fc990aa86433..a496060eb9f1 100644--- a/docs/onboarding/ai-observability/eve.tsx+++ b/docs/onboarding/ai-observability/eve.tsx@@ -14,16 +14,22 @@ export const getEveSteps = (ctx: OnboardingComponentsContext): StepDefinition[]content: (<><Markdown>- Install the PostHog AI exporter, OpenTelemetry HTTP exporter, and Vercel's OpenTelemetry- package.+ Install PostHog AI, its OpenTelemetry peer dependencies, and Vercel's OpenTelemetry package.</Markdown><CodeBlocklanguage="bash"code={dedent`- npm install @posthog/ai @opentelemetry/exporter-trace-otlp-http @vercel/otel+ npm install @posthog/ai @opentelemetry/api @opentelemetry/exporter-trace-otlp-http @opentelemetry/sdk-trace-base @vercel/otel`}/>++ <Blockquote>+ <Markdown>+ **Version note:** This example uses `projectToken`, which is available in `@posthog/ai`+ 7.19.6 and later. Earlier 7.x versions use `apiKey`.+ </Markdown>+ </Blockquote></>),},@@ -51,12 +57,16 @@ export const getEveSteps = (ctx: OnboardingComponentsContext): StepDefinition[]<><Markdown>Create `agent/instrumentation.ts`. Eve discovers this file and starts the exporter when your- agent server starts.+ agent server starts. The optional `events` handler uses [Eve runtime+ context](https://eve.dev/docs/guides/instrumentation#runtime-context) to identify spans with the+ user who started the session, falling back to the caller for the current turn.</Markdown><CodeBlocklanguage="typescript"code={dedent`+ import { trace } from '@opentelemetry/api'+ import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'import { PostHogTraceExporter } from '@posthog/ai/otel'import { registerOTel } from '@vercel/otel'import { defineInstrumentation } from 'eve/instrumentation'@@ -65,11 +75,30 @@ export const getEveSteps = (ctx: OnboardingComponentsContext): StepDefinition[]setup: ({ agentName }) =>registerOTel({serviceName: agentName,- traceExporter: new PostHogTraceExporter({- projectToken: process.env.POSTHOG_PROJECT_TOKEN!,- host: process.env.POSTHOG_HOST,- }),+ spanProcessors: [+ new SimpleSpanProcessor(+ new PostHogTraceExporter({+ projectToken: process.env.POSTHOG_PROJECT_TOKEN!,+ host: process.env.POSTHOG_HOST,+ })+ ),+ ],}),+ // Optional: Link Eve and AI SDK spans to a PostHog user.+ events: {+ 'step.started'(input) {+ const distinctId =+ input.session.auth.initiator?.principalId ??+ input.session.auth.current?.principalId++ if (!distinctId) {+ return undefined+ }++ trace.getActiveSpan()?.setAttribute('posthog.distinct_id', distinctId)+ return { runtimeContext: { posthog_distinct_id: distinctId } }+ },+ },})`}/>@@ -77,11 +106,21 @@ export const getEveSteps = (ctx: OnboardingComponentsContext): StepDefinition[]<CalloutBox type="fyi" icon="IconInfo" title="How this works"><Markdown>Eve emits Vercel AI SDK OpenTelemetry spans. `PostHogTraceExporter` sends the AI spans to- PostHog's OTLP ingestion endpoint. PostHog keeps the trace hierarchy, identifies the- framework as Eve, and groups turns using `eve.session.id`.+ PostHog's OTLP ingestion endpoint. `SimpleSpanProcessor` starts exporting each span when it+ ends instead of waiting for a background batch, so export does not depend on a background+ timer in Vercel Workflow. PostHog keeps the trace hierarchy, identifies the framework as+ Eve, and groups turns using `eve.session.id`.</Markdown></CalloutBox>+ <Blockquote>+ <Markdown>+ **Note:** To capture LLM events anonymously, omit the `events` handler. See our docs on+ [anonymous vs identified+ events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.+ </Markdown>+ </Blockquote>+<Blockquote><Markdown>**Data capture:** Eve records full message history and model outputs by default. Setdiff --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 f1c73b1df25b..6ee06ffa16d3 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@@ -13,6 +13,14 @@ jest.mock('~/ingestion/pipelines/ai/otel/attribute-mapping', () => ({}))const mockedMapOtelAttributes = jest.mocked(mapOtelAttributes)+const AI_CONTEXT_PREFIXES = ['ai.telemetry.metadata.', 'ai.settings.context.']+const PROMOTED_CONTEXT_CASES: [string, string, string | number][] = AI_CONTEXT_PREFIXES.flatMap((prefix) => [+ [prefix, 'posthog_distinct_id', 'user-1'],+ [prefix, '$ai_session_id', 'session-123'],+ [prefix, '$ai_prompt_name', 'my-prompt'],+ [prefix, '$ai_prompt_version', 'v2'],+ [prefix, '$ai_prompt_version', 2],+])/*** Minimal mock that replicates the subset of mapOtelAttributes behavior@@ -243,45 +251,55 @@ describe('vercel-ai middleware', () => {expect(event.properties!['$ai_stop_reason']).toBeUndefined()})- it.each([- ['posthog_distinct_id', 'user-1'],- ['$ai_session_id', 'session-123'],- ['$ai_prompt_name', 'my-prompt'],- ['$ai_prompt_version', 'v2'],- ['$ai_prompt_version', 2],- ])('promotes ai.telemetry.metadata.%s to event properties', (key, value) => {+ it.each(PROMOTED_CONTEXT_CASES)('promotes %s%s value %p to event properties', (prefix, key, value) => {const event = createEvent('$ai_generation', {'ai.operationId': 'ai.generateText.doGenerate',- [`ai.telemetry.metadata.${key}`]: value,- 'ai.telemetry.metadata.org_id': 'org-456',+ [`${prefix}${key}`]: value,+ [`${prefix}org_id`]: 'org-456',})convertOtelEvent(event)expect(event.properties![key]).toBe(value)- expect(event.properties!['org_id']).toBeUndefined()- expect(event.properties![`ai.telemetry.metadata.${key}`]).toBeUndefined()+ expect(event.properties![`${prefix}org_id`]).toBeUndefined()+ expect(event.properties![`${prefix}${key}`]).toBeUndefined()})- it('promotes posthog_-prefixed telemetry metadata as a custom property', () => {+ it.each(AI_CONTEXT_PREFIXES)('promotes posthog_-prefixed values from %s', (prefix) => {const event = createEvent('$ai_generation', {'ai.operationId': 'ai.generateText.doGenerate',- 'ai.telemetry.metadata.posthog_tags': ['beta'],+ [`${prefix}posthog_tags`]: ['beta'],})convertOtelEvent(event)expect(event.properties!['tags']).toEqual(['beta'])- expect(event.properties!['ai.telemetry.metadata.posthog_tags']).toBeUndefined()+ expect(event.properties![`${prefix}posthog_tags`]).toBeUndefined()})- it('uses posthog_distinct_id as the event distinct_id without creating a bare distinct_id property', () => {+ it.each(AI_CONTEXT_PREFIXES)(+ 'uses posthog_distinct_id from %s as the event distinct_id without creating a bare distinct_id property',+ (prefix) => {+ const event = createEvent('$ai_generation', {+ 'ai.operationId': 'ai.generateText.doGenerate',+ [`${prefix}posthog_distinct_id`]: 'user-1',+ })+ convertOtelEvent(event)++ expect(event.distinct_id).toBe('user-1')+ expect(event.properties!['distinct_id']).toBeUndefined()+ }+ )++ it('prefers telemetry metadata over runtime context', () => {const event = createEvent('$ai_generation', {'ai.operationId': 'ai.generateText.doGenerate',- 'ai.telemetry.metadata.posthog_distinct_id': 'user-1',+ 'ai.telemetry.metadata.posthog_distinct_id': 'metadata-user',+ 'ai.settings.context.posthog_distinct_id': 'context-user',})convertOtelEvent(event)- expect(event.distinct_id).toBe('user-1')- expect(event.properties!['distinct_id']).toBeUndefined()+ expect(event.distinct_id).toBe('metadata-user')+ expect(event.properties!['ai.telemetry.metadata.posthog_distinct_id']).toBeUndefined()+ expect(event.properties!['ai.settings.context.posthog_distinct_id']).toBeUndefined()})it('ignores empty posthog_distinct_id metadata', () => {@@ -320,15 +338,15 @@ describe('vercel-ai middleware', () => {expect(event.properties!['ai.telemetry.metadata.$ai_prompt_version']).toBeUndefined()})- it('promotes ai.telemetry.metadata.$groups so the mapper can parse it', () => {+ it.each(AI_CONTEXT_PREFIXES)('promotes %s$groups so the mapper can parse it', (prefix) => {const event = createEvent('$ai_generation', {'ai.operationId': 'ai.generateText.doGenerate',- 'ai.telemetry.metadata.$groups': '{"organization":"org-1"}',+ [`${prefix}$groups`]: '{"organization":"org-1"}',})convertOtelEvent(event)expect(event.properties!['$groups']).toBe('{"organization":"org-1"}')- expect(event.properties!['ai.telemetry.metadata.$groups']).toBeUndefined()+ expect(event.properties![`${prefix}$groups`]).toBeUndefined()})it.each(['', 42, true, ['org-1']])('does not promote invalid groups metadata %p', (metadataGroups) => {@@ -598,6 +616,26 @@ describe('vercel-ai middleware', () => {})describe('Eve', () => {+ it('normalizes Eve attributes from AI SDK runtime context', () => {+ const event = createEvent('$ai_span', {+ 'ai.settings.context.eve.version': '0.27.8',+ 'ai.settings.context.eve.session.id': 'session-123',+ 'ai.settings.context.eve.turn.id': 'turn-1',+ 'ai.settings.context.posthog_distinct_id': 'user-1',+ $ai_parent_id: 'eve-turn-span',+ })+ convertOtelEvent(event)++ expect(event.event).toBe('$ai_span')+ expect(event.distinct_id).toBe('user-1')+ expect(event.properties!['$ai_framework']).toBe('eve')+ expect(event.properties!['$ai_session_id']).toBe('session-123')+ expect(event.properties!['eve.turn.id']).toBe('turn-1')+ expect(event.properties!['ai.settings.context.eve.version']).toBeUndefined()+ expect(event.properties!['ai.settings.context.eve.session.id']).toBeUndefined()+ expect(event.properties!['ai.settings.context.eve.turn.id']).toBeUndefined()+ })+it('normalizes Eve turns with filtered Workflow parents as trace roots', () => {const event = createEvent('$ai_span', {'eve.version': '0.27.8',diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.tsindex 1d17c1d2502f..e50a453a88f6 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts@@ -48,9 +48,11 @@ const STRIP_KEYS = ['gen_ai.response.id',]-// Metadata properties to promote to event properties-const STRING_AI_METADATA_KEYS = ['$ai_session_id', '$ai_prompt_name']+const STRING_AI_CONTEXT_KEYS = ['$ai_session_id', '$ai_prompt_name']const AI_PROMPT_VERSION_KEY = '$ai_prompt_version'+const AI_TELEMETRY_METADATA_PREFIX = 'ai.telemetry.metadata.'+const AI_RUNTIME_CONTEXT_PREFIX = 'ai.settings.context.'+const AI_CONTEXT_PREFIXES = [AI_TELEMETRY_METADATA_PREFIX, AI_RUNTIME_CONTEXT_PREFIX]const EVE_MARKER_KEYS = ['eve.version', 'eve.session.id']const EVE_TURN_SPAN_NAME = 'ai.eve.turn'@@ -62,6 +64,46 @@ function isPromptVersion(value: unknown): value is string | number {return isNonEmptyString(value) || (typeof value === 'number' && Number.isInteger(value) && value > 0)}+function getAiContextValue(props: Record<string, unknown>, key: string): unknown {+ for (const prefix of AI_CONTEXT_PREFIXES) {+ const value = props[`${prefix}${key}`]+ if (value !== undefined) {+ return value+ }+ }+ return undefined+}++function normalizeEveRuntimeContext(props: Record<string, unknown>): void {+ const eveRuntimeContextPrefix = `${AI_RUNTIME_CONTEXT_PREFIX}eve.`+ for (const key of Object.keys(props)) {+ if (!key.startsWith(eveRuntimeContextPrefix)) {+ continue+ }+ const eveKey = key.slice(AI_RUNTIME_CONTEXT_PREFIX.length)+ props[eveKey] ??= props[key]+ delete props[key]+ }+}++function promotePosthogContext(props: Record<string, unknown>): void {+ for (const prefix of AI_CONTEXT_PREFIXES) {+ promotePosthogCustomMetadata(props, prefix)+ }+}++function stripProcessedContext(props: Record<string, unknown>): void {+ for (const key of Object.keys(props)) {+ if (+ key.startsWith(AI_TELEMETRY_METADATA_PREFIX) ||+ key.startsWith(AI_RUNTIME_CONTEXT_PREFIX) ||+ key.startsWith('ai.request.headers.')+ ) {+ delete props[key]+ }+ }+}+function isEveSpan(props: Record<string, unknown>): boolean {return EVE_MARKER_KEYS.some((key) => props[key] !== undefined)}@@ -117,6 +159,7 @@ function process(event: PluginEvent, next: () => void): void {return next()}const props = event.properties+ normalizeEveRuntimeContext(props)const eveSpan = isEveSpan(props)// Eve's Workflow parent is filtered before ingestion, so the turn must become the logical trace root.@@ -170,10 +213,8 @@ function process(event: PluginEvent, next: () => void): void {}delete props['ai.response.text']- // Promote a groups map supplied via telemetry metadata before next(), so the- // generic mapper's normalizeGroups() can parse the JSON string and attach it.- // Skip if a $groups span attribute was already set directly.- const groupsMetadata = props['ai.telemetry.metadata.$groups']+ // 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)) {props['$groups'] = groupsMetadata}@@ -250,7 +291,7 @@ function process(event: PluginEvent, next: () => void): void {props['$ai_span_name'] = functionId}- const posthogDistinctId = props['ai.telemetry.metadata.posthog_distinct_id']+ const posthogDistinctId = getAiContextValue(props, 'posthog_distinct_id')if (typeof posthogDistinctId === 'string' && posthogDistinctId) {if (props['posthog_distinct_id'] === undefined) {props['posthog_distinct_id'] = posthogDistinctId@@ -258,36 +299,27 @@ function process(event: PluginEvent, next: () => void): void {event.distinct_id = posthogDistinctId}- for (const aiKey of STRING_AI_METADATA_KEYS) {- const value = props[`ai.telemetry.metadata.${aiKey}`]+ for (const aiKey of STRING_AI_CONTEXT_KEYS) {+ const value = getAiContextValue(props, aiKey)if (props[aiKey] === undefined && isNonEmptyString(value)) {props[aiKey] = value}}- const promptVersion = props[`ai.telemetry.metadata.${AI_PROMPT_VERSION_KEY}`]+ const promptVersion = getAiContextValue(props, AI_PROMPT_VERSION_KEY)if (props[AI_PROMPT_VERSION_KEY] === undefined && isPromptVersion(promptVersion)) {props[AI_PROMPT_VERSION_KEY] = promptVersion}- // Vercel repeats telemetry metadata across provider spans, so only use the- // custom call name for the top-level event.- const spanNameOverride = props['ai.telemetry.metadata.$ai_span_name']+ // Vercel repeats context across provider spans, so only rename the top-level event.+ const spanNameOverride = getAiContextValue(props, '$ai_span_name')if (isTopLevel && isNonEmptyString(spanNameOverride)) {props['$ai_span_name'] = spanNameOverride}- promotePosthogCustomMetadata(props, 'ai.telemetry.metadata.')+ promotePosthogContext(props)- // Strip Vercel-specific telemetry metadata and request headers after preserving- // the PostHog identifiers we rely on for event linkage and session grouping.- for (const key of Object.keys(props)) {- if (key.startsWith('ai.telemetry.metadata.')) {- delete props[key]- } else if (key.startsWith('ai.request.headers.')) {- delete props[key]- }- }+ stripProcessedContext(props)// Map finish reason to $ai_stop_reason before strippingif (props['$ai_stop_reason'] === undefined) {@@ -336,7 +368,12 @@ function process(event: PluginEvent, next: () => void): void {}}-const MARKER_KEYS = ['ai.operationId', 'ai.telemetry.functionId', ...EVE_MARKER_KEYS]+const MARKER_KEYS = [+ 'ai.operationId',+ 'ai.telemetry.functionId',+ ...EVE_MARKER_KEYS,+ ...EVE_MARKER_KEYS.map((key) => `${AI_RUNTIME_CONTEXT_PREFIX}${key}`),+]export const vercelAi: OtelLibraryMiddleware = {name: 'vercel-ai',diff --git a/rust/capture/src/otel/identity.rs b/rust/capture/src/otel/identity.rsindex a930ba2c1549..fb9973503647 100644--- a/rust/capture/src/otel/identity.rs+++ b/rust/capture/src/otel/identity.rs@@ -2,12 +2,11 @@ use opentelemetry_proto::tonic::common::v1::{any_value, KeyValue};use opentelemetry_proto::tonic::resource::v1::Resource;use uuid::Uuid;-/// Span-level keys checked in order. The Vercel AI SDK serializes-/// `experimental_telemetry.metadata.posthog_distinct_id` as-/// `ai.telemetry.metadata.posthog_distinct_id`, which is the canonical-/// per-call way to attribute an event to a user.+/// Span-level keys checked in order. AI SDK metadata and runtime context are+/// both per-call, so they can identify spans from multi-tenant processes.const SPAN_DISTINCT_ID_KEYS: &[&str] = &["ai.telemetry.metadata.posthog_distinct_id",+ "ai.settings.context.posthog_distinct_id","posthog.distinct_id","user.id",];@@ -96,6 +95,19 @@ mod tests {);}+ #[test]+ fn test_span_runtime_context_distinct_id_wins_over_resource() {+ let span_attrs = vec![string_kv(+ "ai.settings.context.posthog_distinct_id",+ "span-user",+ )];+ let resource = resource_with(vec![string_kv("posthog.distinct_id", "resource-user")]);+ assert_eq!(+ extract_distinct_id_for_span(&span_attrs, Some(&resource), "fallback"),+ "span-user"+ );+ }+#[test]fn test_span_posthog_distinct_id_wins_over_user_id() {let span_attrs = vec![