: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): keep AI SDK 7 gen_ai-native spans as generations (#91775)
posthog[bot]8b380d2e084f
diff --git a/nodejs/src/ingestion/pipelines/ai/otel/index.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/index.test.tsindex 9ce594d966cc..7ea557003ed8 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/index.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/index.test.ts@@ -96,6 +96,17 @@ describe('convertOtelEvent', () => {expect(event.properties!['$ai_lib']).toBe('opentelemetry/pydantic-ai')})+ // vercel-ai matches the whole ai.* namespace, so it only stays off+ // traceloop spans because it is last in the registry.+ it('traceloop markers take priority over an ai.* attribute', () => {+ const event = createEvent('$ai_span', {+ 'traceloop.span.kind': 'workflow',+ 'ai.usage.outputTokenDetails.reasoningTokens': 5,+ })+ convertOtelEvent(event)+ expect(event.properties!['$ai_lib']).toBe('opentelemetry/traceloop')+ })+it('does not detect traceloop when no marker keys present', () => {const event = createEvent('$ai_generation', { 'gen_ai.system': 'openai' })convertOtelEvent(event)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 9ffbfe9858f0..af5f48461495 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@@ -699,6 +699,30 @@ describe('vercel-ai middleware', () => {})})+ describe('AI SDK 7 gen_ai-native spans', () => {+ it('processes a gen_ai-native generation that carries only ai.usage.* and ai.telemetry.metadata.*', () => {+ // @ai-sdk/otel's OpenTelemetry integration drops ai.operationId and+ // emits standard gen_ai.* plus supplemental ai.usage.* / ai.telemetry.metadata.*.+ // The middleware must still run so attribution and usage normalization happen.+ const event = createEvent('$ai_generation', {+ 'gen_ai.operation.name': 'chat',+ 'gen_ai.response.model': 'gemini-2.5-pro',+ 'gen_ai.usage.output_tokens': 20,+ 'ai.usage.outputTokenDetails.reasoningTokens': 5,+ 'ai.telemetry.metadata.$ai_session_id': 'session-abc',+ $ai_parent_id: 'parent-span',+ })+ convertOtelEvent(event)++ expect(event.properties!['$ai_session_id']).toBe('session-abc')+ expect(event.properties!['$ai_reasoning_tokens']).toBe(5)+ expect(event.properties!['$ai_framework']).toBe('vercel')+ expect(event.properties!['$ai_lib']).toBe('opentelemetry/vercel-ai')+ expect(event.properties!['ai.telemetry.metadata.$ai_session_id']).toBeUndefined()+ expect(event.properties!['ai.usage.outputTokenDetails.reasoningTokens']).toBeUndefined()+ })+ })+describe('Eve', () => {it('normalizes Eve attributes from AI SDK runtime context', () => {const event = createEvent('$ai_span', {diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.tsindex 0c7576b5e8ce..a0d9ad195cc1 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts@@ -23,6 +23,7 @@ const STRIP_KEYS = ['ai.usage.tokens','ai.usage.inputTokenDetails.noCacheTokens','ai.usage.outputTokenDetails.textTokens',+ 'ai.usage.outputTokenDetails.reasoningTokens','ai.response.id','ai.response.model','ai.response.timestamp',@@ -429,15 +430,18 @@ function process(event: PluginEvent, next: () => void): void {}}-const MARKER_KEYS = [- 'ai.operationId',- 'ai.telemetry.functionId',- ...EVE_MARKER_KEYS,- ...EVE_MARKER_KEYS.map((key) => `${AI_RUNTIME_CONTEXT_PREFIX}${key}`),-]+// Match any Vercel AI SDK or Eve span by attribute namespace. AI SDK 7's+// gen_ai-native integration drops ai.operationId but still emits ai.*+// supplemental attributes (ai.usage.*, ai.telemetry.metadata.*), so an exact+// key list would miss those spans and skip attribution and usage normalization.+// The other middlewares (pydantic-ai, traceloop) run first and own their own+// namespaces, so a prefix match here cannot steal their spans.+const MARKER_PREFIXES = ['ai.', 'eve.']export const vercelAi: OtelLibraryMiddleware = {name: 'vercel-ai',- matches: (event) => MARKER_KEYS.some((key) => event.properties?.[key] !== undefined),+ matches: (event) =>+ event.properties !== undefined &&+ Object.keys(event.properties).some((key) => MARKER_PREFIXES.some((prefix) => key.startsWith(prefix))),process,}diff --git a/rust/capture/src/otel/providers.rs b/rust/capture/src/otel/providers.rsindex 962b6757934a..eabddbc1e82c 100644--- a/rust/capture/src/otel/providers.rs+++ b/rust/capture/src/otel/providers.rs@@ -25,28 +25,37 @@ fn classify_by_key(.unwrap_or("$ai_span")}+/// Maps the standard OTel GenAI `gen_ai.operation.name` value to a PostHog event+/// type. Shared so the Vercel provider can reuse it for AI SDK 7 spans.+fn classify_gen_ai_operation(op: &str) -> &'static str {+ match op {+ "chat" => "$ai_generation",+ "embeddings" => "$ai_embedding",+ _ => "$ai_span",+ }+}+/// OpenAI-style semantic conventions (`gen_ai.*`).const GEN_AI: SupportedProvider = SupportedProvider {prefixes: &["gen_ai."],- classify: |attrs| {- classify_by_key(attrs, "gen_ai.operation.name", |op| match op {- "chat" => "$ai_generation",- "embeddings" => "$ai_embedding",- _ => "$ai_span",- })- },+ classify: |attrs| classify_by_key(attrs, "gen_ai.operation.name", classify_gen_ai_operation),};/// Vercel AI SDK (`ai.*`) and Eve (`eve.*`). Eve root turn spans can omit/// `ai.*` attributes, so its namespace must be accepted by the same provider.const VERCEL_AI: SupportedProvider = SupportedProvider {prefixes: &["ai.", "eve."],- classify: |attrs| {- classify_by_key(attrs, "ai.operationId", |op_id| match op_id {+ classify: |attrs| match attrs.get("ai.operationId").and_then(|v| v.as_str()) {+ Some(op_id) => match op_id {s if s.ends_with(".doGenerate") || s.ends_with(".doStream") => "$ai_generation",s if s == "ai.embed.doEmbed" || s == "ai.embedMany.doEmbed" => "$ai_embedding",_ => "$ai_span",- })+ },+ // AI SDK 7's gen_ai-native integration emits standard gen_ai.* semconv+ // plus supplemental ai.usage.* details, but no ai.operationId. Those ai.*+ // keys make this provider match first, so classify by the standard+ // operation name instead of defaulting the span to $ai_span.+ None => classify_by_key(attrs, "gen_ai.operation.name", classify_gen_ai_operation),},};@@ -212,6 +221,35 @@ mod tests {assert_eq!(get_event_name(&attrs), Some("$ai_generation"));}+ #[test]+ fn test_ai_sdk_7_gen_ai_native_spans_classify_by_operation_name() {+ // AI SDK 7's @ai-sdk/otel integration emits standard gen_ai.* semconv+ // plus supplemental ai.usage.* details, but no ai.operationId. The+ // ai.usage.* keys make VERCEL_AI match first, so it must fall back to+ // gen_ai.operation.name. Operations that are not inference stay+ // $ai_span, or a tool-call span becomes a second priced generation.+ for (operation, expected) in [+ ("chat", "$ai_generation"),+ ("embeddings", "$ai_embedding"),+ ("execute_tool", "$ai_span"),+ ] {+ let mut attrs = serde_json::Map::new();+ attrs.insert(+ "gen_ai.operation.name".to_string(),+ Value::String(operation.to_string()),+ );+ attrs.insert(+ "ai.usage.outputTokenDetails.reasoningTokens".to_string(),+ Value::Number(5.into()),+ );+ assert_eq!(+ get_event_name(&attrs),+ Some(expected),+ "gen_ai.operation.name={operation}"+ );+ }+ }+#[test]fn test_supported_provider_prefix_defaults_to_ai_span() {assert_eq!(