From afe7ea870faf45a8844cd51b96abff7c435d5dd3 Mon Sep 17 00:00:00 2001 From: lforst <8118419+lforst@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:17:55 +0000 Subject: [PATCH 1/3] feat(ai-sdk): Trace extraction calls --- .agents/skills/e2e-tests/SKILL.md | 2 +- .../ai-sdk-v7-latest.cassette.json | 111 ++++++++++++++++++ .../__cassettes__/ai-sdk-v7.cassette.json | 111 ++++++++++++++++++ .../ai-sdk-v7-auto-hook.span-tree.json | 52 ++++++++ .../ai-sdk-v7-auto-hook.span-tree.txt | 44 +++++++ .../ai-sdk-v7-explicit.span-tree.json | 52 ++++++++ .../ai-sdk-v7-explicit.span-tree.txt | 44 +++++++ .../ai-sdk-v7-latest-auto-hook.span-tree.json | 52 ++++++++ .../ai-sdk-v7-latest-auto-hook.span-tree.txt | 44 +++++++ .../ai-sdk-v7-latest-explicit.span-tree.json | 104 ++++++++++++++++ .../ai-sdk-v7-latest-explicit.span-tree.txt | 88 ++++++++++++++ .../ai-sdk-instrumentation/assertions.ts | 33 ++++++ .../ai-sdk-instrumentation/package.json | 1 + .../ai-sdk-instrumentation/pnpm-lock.yaml | 43 +++++++ .../scenario.ai-sdk-v7-explicit.mjs | 1 + .../scenario.ai-sdk-v7.ts | 1 + .../ai-sdk-instrumentation/scenario.impl.mjs | 32 +++++ .../auto-instrumentations/configs/ai-sdk.ts | 13 ++ .../providers/ai-sdk-instrumentation.ts | 63 ++++++++-- .../providers/ai-sdk-interceptors.ts | 7 ++ js/src/vendor-sdk-types/ai-sdk-common.ts | 20 ++++ .../vendor-sdk-types/ai-sdk-v7-telemetry.ts | 11 ++ js/src/vendor-sdk-types/ai-sdk.ts | 6 + js/src/wrappers/ai-sdk-extract.test.ts | 68 +++++++++++ js/src/wrappers/ai-sdk/ai-sdk.ts | 18 +++ js/src/wrappers/ai-sdk/telemetry.ts | 65 ++++++++-- 26 files changed, 1066 insertions(+), 20 deletions(-) create mode 100644 js/src/wrappers/ai-sdk-extract.test.ts diff --git a/.agents/skills/e2e-tests/SKILL.md b/.agents/skills/e2e-tests/SKILL.md index 77484240f..847967b1a 100644 --- a/.agents/skills/e2e-tests/SKILL.md +++ b/.agents/skills/e2e-tests/SKILL.md @@ -18,7 +18,7 @@ Read first: ## Workflow -1. Start from the closest existing scenario and keep its structure unless the new case clearly needs a new pattern. +1. Look for an existing scenario that covers the provider, integration, or feature. Add new tests and cases to its runner, assertions, and version matrix when available. Create a scenario directory only when no existing scenario fits. 2. Default to module-scope setup with `prepareScenarioDir({ scenarioDir: resolveScenarioDir(import.meta.url) })`. This copies the scenario into an isolated temp directory and installs any scenario-local dependencies before the test bodies run. 3. Use `withScenarioHarness(...)` for every scenario test. Pick the runner that matches the real entrypoint: - `runScenarioDir()` for default `tsx`-driven TypeScript scenarios diff --git a/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7-latest.cassette.json b/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7-latest.cassette.json index 16699f073..7c8d5154d 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7-latest.cassette.json +++ b/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7-latest.cassette.json @@ -6216,6 +6216,117 @@ }, "status": 200 } + }, + { + "callIndex": 0, + "id": "fd8f228895da2337", + "matchKey": "POST ai-gateway.vercel.sh/v4/ai/extraction-model", + "recordedAt": "2026-12-01T14:11:11.406Z", + "request": { + "body": { + "kind": "json", + "value": { + "fields": { + "invoice": { + "instructions": "The invoice number", + "type": "text" + } + }, + "providerOptions": {}, + "stateParts": [ + { + "text": "Invoice number: INV-2041.", + "type": "text" + } + ] + } + }, + "headers": {}, + "method": "POST", + "url": "https://ai-gateway.vercel.sh/v4/ai/extraction-model" + }, + "response": { + "body": { + "kind": "json", + "value": { + "answers": { + "invoice": { + "confidence": 1, + "source": { + "end": 24, + "part": 0, + "start": 16, + "type": "text" + }, + "type": "text", + "value": "INV-2041" + } + }, + "model": "scaledown/extract-1", + "providerMetadata": { + "gateway": { + "cost": "0.00001045", + "gatewayCost": "0.00001045", + "generationId": "gen_01M8RZ3XNYHAMG12F2ATY3VGG5", + "inferenceCost": "0.00001045", + "inputInferenceCost": "0.00001045", + "marketCost": "0.00001045", + "outputInferenceCost": "0", + "routing": { + "canonicalSlug": "scaledown/extract-1", + "fallbacksAvailable": [], + "finalProvider": "scaledown", + "modelAttemptCount": 1, + "modelAttempts": [ + { + "canonicalSlug": "scaledown/extract-1", + "providerAttemptCount": 1, + "providerAttempts": [ + { + "credentialType": "system", + "endTime": 1796134271389, + "provider": "scaledown", + "startTime": 1796134270685, + "statusCode": 200, + "success": true + } + ], + "success": true + } + ], + "originalModelId": "scaledown/extract-1", + "resolvedProvider": "scaledown", + "totalProviderAttemptCount": 1 + }, + "surchargeCost": "0" + } + }, + "usage": { + "inputTokens": 209, + "outputTokens": 0 + }, + "warnings": [] + } + }, + "headers": { + "access-control-allow-headers": "Content-Type, Content-Encoding, Authorization, ai-gateway-auth-method, ai-gateway-protocol-version, ai-model-id, ai-language-model-id, ai-language-model-specification-version, ai-image-model-specification-version, ai-embedding-model-specification-version, ai-decision-model-specification-version, ai-evaluation-model-specification-version, ai-extraction-model-specification-version, ai-language-model-streaming, ai-reporting-tags, ai-reporting-user, http-referer, x-title, x-ai-gateway-api-key, x-api-key, anthropic-beta, anthropic-version, idempotency-key, x-vercel-ai-gateway-team, x-vercel-gateway-extended-time, x-session-id, x-session-affinity, TypeSafe-Danger-Zone-Images, TypeSafe-Danger-Zone-Long-Context", + "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS", + "access-control-allow-origin": "*", + "access-control-expose-headers": "retry-after, x-ai-gateway-token-count, x-should-retry", + "cache-control": "public, max-age=0, must-revalidate", + "content-encoding": "gzip", + "content-type": "application/json", + "date": "Tue, 01 Dec 2026 14:11:11 GMT", + "server": "Vercel", + "strict-transport-security": "max-age=63072000; includeSubDomains; preload", + "transfer-encoding": "chunked", + "x-matched-path": "/v4/ai/extraction-model", + "x-vercel-cache": "MISS", + "x-vercel-id": "cdg1::cdg1::l7xcb-1796134270569-0b45a841be7c" + }, + "status": 200, + "statusText": "OK" + } } ], "meta": { diff --git a/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7.cassette.json b/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7.cassette.json index 587d26ef9..57af74d69 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7.cassette.json +++ b/e2e/scenarios/ai-sdk-instrumentation/__cassettes__/ai-sdk-v7.cassette.json @@ -6874,6 +6874,117 @@ }, "status": 200 } + }, + { + "callIndex": 0, + "id": "fd8f228895da2337", + "matchKey": "POST ai-gateway.vercel.sh/v4/ai/extraction-model", + "recordedAt": "2026-12-01T14:11:05.326Z", + "request": { + "body": { + "kind": "json", + "value": { + "fields": { + "invoice": { + "instructions": "The invoice number", + "type": "text" + } + }, + "providerOptions": {}, + "stateParts": [ + { + "text": "Invoice number: INV-2041.", + "type": "text" + } + ] + } + }, + "headers": {}, + "method": "POST", + "url": "https://ai-gateway.vercel.sh/v4/ai/extraction-model" + }, + "response": { + "body": { + "kind": "json", + "value": { + "answers": { + "invoice": { + "confidence": 1, + "source": { + "end": 24, + "part": 0, + "start": 16, + "type": "text" + }, + "type": "text", + "value": "INV-2041" + } + }, + "model": "scaledown/extract-1", + "providerMetadata": { + "gateway": { + "cost": "0.00001045", + "gatewayCost": "0.00001045", + "generationId": "gen_01M8RZ3QZ5VPWNB1GTR9C9E478", + "inferenceCost": "0.00001045", + "inputInferenceCost": "0.00001045", + "marketCost": "0.00001045", + "outputInferenceCost": "0", + "routing": { + "canonicalSlug": "scaledown/extract-1", + "fallbacksAvailable": [], + "finalProvider": "scaledown", + "modelAttemptCount": 1, + "modelAttempts": [ + { + "canonicalSlug": "scaledown/extract-1", + "providerAttemptCount": 1, + "providerAttempts": [ + { + "credentialType": "system", + "endTime": 1796134265307, + "provider": "scaledown", + "startTime": 1796134264826, + "statusCode": 200, + "success": true + } + ], + "success": true + } + ], + "originalModelId": "scaledown/extract-1", + "resolvedProvider": "scaledown", + "totalProviderAttemptCount": 1 + }, + "surchargeCost": "0" + } + }, + "usage": { + "inputTokens": 209, + "outputTokens": 0 + }, + "warnings": [] + } + }, + "headers": { + "access-control-allow-headers": "Content-Type, Content-Encoding, Authorization, ai-gateway-auth-method, ai-gateway-protocol-version, ai-model-id, ai-language-model-id, ai-language-model-specification-version, ai-image-model-specification-version, ai-embedding-model-specification-version, ai-decision-model-specification-version, ai-evaluation-model-specification-version, ai-extraction-model-specification-version, ai-language-model-streaming, ai-reporting-tags, ai-reporting-user, http-referer, x-title, x-ai-gateway-api-key, x-api-key, anthropic-beta, anthropic-version, idempotency-key, x-vercel-ai-gateway-team, x-vercel-gateway-extended-time, x-session-id, x-session-affinity, TypeSafe-Danger-Zone-Images, TypeSafe-Danger-Zone-Long-Context", + "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS", + "access-control-allow-origin": "*", + "access-control-expose-headers": "retry-after, x-ai-gateway-token-count, x-should-retry", + "cache-control": "public, max-age=0, must-revalidate", + "content-encoding": "gzip", + "content-type": "application/json", + "date": "Tue, 01 Dec 2026 14:11:05 GMT", + "server": "Vercel", + "strict-transport-security": "max-age=63072000; includeSubDomains; preload", + "transfer-encoding": "chunked", + "x-matched-path": "/v4/ai/extraction-model", + "x-vercel-cache": "MISS", + "x-vercel-id": "cdg1::cdg1::wvzng-1796134264768-b44635f0fe7a" + }, + "status": 200, + "statusText": "OK" + } } ], "meta": { diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.json b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.json index d95bddea6..727979009 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.json +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.json @@ -2403,6 +2403,58 @@ "testRunId": "" } }, + { + "name": "ai-sdk-extract-operation", + "children": [ + { + "name": "extract", + "type": "extraction", + "children": [], + "input": { + "fields": [ + { + "instructions": "The invoice number", + "type": "text" + } + ], + "state": "Invoice number: INV-2041." + }, + "output": { + "answers": [ + { + "confidence": 1, + "source": { + "end": 0, + "part": 0, + "start": 0, + "type": "text" + }, + "type": "text", + "value": "INV-2041" + } + ] + }, + "metadata": { + "braintrust": { + "integration_name": "ai-sdk", + "sdk_language": "typescript" + }, + "model": "extract-1", + "provider": "scaledown" + }, + "metrics": { + "completion_tokens": 0, + "estimated_cost": 0.00001045, + "prompt_tokens": 209, + "tokens": 209 + } + } + ], + "metadata": { + "operation": "extract", + "testRunId": "" + } + }, { "name": "ai-sdk-evaluate-operation", "children": [ diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.txt b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.txt index 7c277f42a..3b956b2c3 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.txt +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-auto-hook.span-tree.txt @@ -2346,6 +2346,50 @@ span_tree: │ "toolCallId": "", │ "toolName": "web_search" │ } + ├── ai-sdk-extract-operation + │ metadata: { + │ "operation": "extract", + │ "testRunId": "" + │ } + │ └── extract [extraction] + │ input: { + │ "fields": [ + │ { + │ "instructions": "The invoice number", + │ "type": "text" + │ } + │ ], + │ "state": "Invoice number: INV-2041." + │ } + │ output: { + │ "answers": [ + │ { + │ "confidence": 1, + │ "source": { + │ "end": 0, + │ "part": 0, + │ "start": 0, + │ "type": "text" + │ }, + │ "type": "text", + │ "value": "INV-2041" + │ } + │ ] + │ } + │ metadata: { + │ "braintrust": { + │ "integration_name": "ai-sdk", + │ "sdk_language": "typescript" + │ }, + │ "model": "extract-1", + │ "provider": "scaledown" + │ } + │ metrics: { + │ "completion_tokens": 0, + │ "estimated_cost": 0.00001045, + │ "prompt_tokens": 209, + │ "tokens": 209 + │ } ├── ai-sdk-evaluate-operation │ metadata: { │ "operation": "evaluate", diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.json b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.json index ab50818ca..93044609e 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.json +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.json @@ -2403,6 +2403,58 @@ "testRunId": "" } }, + { + "name": "ai-sdk-wrapped-extract-operation", + "children": [ + { + "name": "extract", + "type": "extraction", + "children": [], + "input": { + "fields": [ + { + "instructions": "The invoice number", + "type": "text" + } + ], + "state": "Invoice number: INV-2041." + }, + "output": { + "answers": [ + { + "confidence": 1, + "source": { + "end": 0, + "part": 0, + "start": 0, + "type": "text" + }, + "type": "text", + "value": "INV-2041" + } + ] + }, + "metadata": { + "braintrust": { + "integration_name": "ai-sdk", + "sdk_language": "typescript" + }, + "model": "extract-1", + "provider": "scaledown" + }, + "metrics": { + "completion_tokens": 0, + "estimated_cost": 0.00001045, + "prompt_tokens": 209, + "tokens": 209 + } + } + ], + "metadata": { + "operation": "wrapped-extract", + "testRunId": "" + } + }, { "name": "ai-sdk-evaluate-operation", "children": [ diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.txt b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.txt index 5cfc81248..0eef1140e 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.txt +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-explicit.span-tree.txt @@ -2346,6 +2346,50 @@ span_tree: │ "toolCallId": "", │ "toolName": "web_search" │ } + ├── ai-sdk-wrapped-extract-operation + │ metadata: { + │ "operation": "wrapped-extract", + │ "testRunId": "" + │ } + │ └── extract [extraction] + │ input: { + │ "fields": [ + │ { + │ "instructions": "The invoice number", + │ "type": "text" + │ } + │ ], + │ "state": "Invoice number: INV-2041." + │ } + │ output: { + │ "answers": [ + │ { + │ "confidence": 1, + │ "source": { + │ "end": 0, + │ "part": 0, + │ "start": 0, + │ "type": "text" + │ }, + │ "type": "text", + │ "value": "INV-2041" + │ } + │ ] + │ } + │ metadata: { + │ "braintrust": { + │ "integration_name": "ai-sdk", + │ "sdk_language": "typescript" + │ }, + │ "model": "extract-1", + │ "provider": "scaledown" + │ } + │ metrics: { + │ "completion_tokens": 0, + │ "estimated_cost": 0.00001045, + │ "prompt_tokens": 209, + │ "tokens": 209 + │ } ├── ai-sdk-evaluate-operation │ metadata: { │ "operation": "evaluate", diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.json b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.json index ecd54725c..359bdb233 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.json +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.json @@ -3233,6 +3233,58 @@ "testRunId": "" } }, + { + "name": "ai-sdk-extract-operation", + "children": [ + { + "name": "extract", + "type": "extraction", + "children": [], + "input": { + "fields": [ + { + "instructions": "The invoice number", + "type": "text" + } + ], + "state": "Invoice number: INV-2041." + }, + "output": { + "answers": [ + { + "confidence": 1, + "source": { + "end": 0, + "part": 0, + "start": 0, + "type": "text" + }, + "type": "text", + "value": "INV-2041" + } + ] + }, + "metadata": { + "braintrust": { + "integration_name": "ai-sdk", + "sdk_language": "typescript" + }, + "model": "extract-1", + "provider": "scaledown" + }, + "metrics": { + "completion_tokens": 0, + "estimated_cost": 0.00001045, + "prompt_tokens": 209, + "tokens": 209 + } + } + ], + "metadata": { + "operation": "extract", + "testRunId": "" + } + }, { "name": "ai-sdk-evaluate-operation", "children": [ diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.txt b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.txt index e02be0f83..eb2a1a19a 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.txt +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-auto-hook.span-tree.txt @@ -3175,6 +3175,50 @@ span_tree: │ "toolCallId": "", │ "toolName": "web_search" │ } + ├── ai-sdk-extract-operation + │ metadata: { + │ "operation": "extract", + │ "testRunId": "" + │ } + │ └── extract [extraction] + │ input: { + │ "fields": [ + │ { + │ "instructions": "The invoice number", + │ "type": "text" + │ } + │ ], + │ "state": "Invoice number: INV-2041." + │ } + │ output: { + │ "answers": [ + │ { + │ "confidence": 1, + │ "source": { + │ "end": 0, + │ "part": 0, + │ "start": 0, + │ "type": "text" + │ }, + │ "type": "text", + │ "value": "INV-2041" + │ } + │ ] + │ } + │ metadata: { + │ "braintrust": { + │ "integration_name": "ai-sdk", + │ "sdk_language": "typescript" + │ }, + │ "model": "extract-1", + │ "provider": "scaledown" + │ } + │ metrics: { + │ "completion_tokens": 0, + │ "estimated_cost": 0.00001045, + │ "prompt_tokens": 209, + │ "tokens": 209 + │ } ├── ai-sdk-evaluate-operation │ metadata: { │ "operation": "evaluate", diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.json b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.json index 8d532eecc..7d064f4f3 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.json +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.json @@ -3233,6 +3233,110 @@ "testRunId": "" } }, + { + "name": "ai-sdk-wrapped-extract-operation", + "children": [ + { + "name": "extract", + "type": "extraction", + "children": [], + "input": { + "fields": [ + { + "instructions": "The invoice number", + "type": "text" + } + ], + "state": "Invoice number: INV-2041." + }, + "output": { + "answers": [ + { + "confidence": 1, + "source": { + "end": 0, + "part": 0, + "start": 0, + "type": "text" + }, + "type": "text", + "value": "INV-2041" + } + ] + }, + "metadata": { + "braintrust": { + "integration_name": "ai-sdk", + "sdk_language": "typescript" + }, + "model": "extract-1", + "provider": "scaledown" + }, + "metrics": { + "completion_tokens": 0, + "estimated_cost": 0.00001045, + "prompt_tokens": 209, + "tokens": 209 + } + } + ], + "metadata": { + "operation": "wrapped-extract", + "testRunId": "" + } + }, + { + "name": "ai-sdk-extract-operation", + "children": [ + { + "name": "extract", + "type": "extraction", + "children": [], + "input": { + "fields": [ + { + "instructions": "The invoice number", + "type": "text" + } + ], + "state": "Invoice number: INV-2041." + }, + "output": { + "answers": [ + { + "confidence": 1, + "source": { + "end": 0, + "part": 0, + "start": 0, + "type": "text" + }, + "type": "text", + "value": "INV-2041" + } + ] + }, + "metadata": { + "braintrust": { + "integration_name": "ai-sdk", + "sdk_language": "typescript" + }, + "model": "extract-1", + "provider": "scaledown" + }, + "metrics": { + "completion_tokens": 0, + "estimated_cost": 0.00001045, + "prompt_tokens": 209, + "tokens": 209 + } + } + ], + "metadata": { + "operation": "extract", + "testRunId": "" + } + }, { "name": "ai-sdk-evaluate-operation", "children": [ diff --git a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.txt b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.txt index 54e5bd384..4bb2bd474 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.txt +++ b/e2e/scenarios/ai-sdk-instrumentation/__snapshots__/ai-sdk-v7-latest-explicit.span-tree.txt @@ -3175,6 +3175,94 @@ span_tree: │ "toolCallId": "", │ "toolName": "web_search" │ } + ├── ai-sdk-wrapped-extract-operation + │ metadata: { + │ "operation": "wrapped-extract", + │ "testRunId": "" + │ } + │ └── extract [extraction] + │ input: { + │ "fields": [ + │ { + │ "instructions": "The invoice number", + │ "type": "text" + │ } + │ ], + │ "state": "Invoice number: INV-2041." + │ } + │ output: { + │ "answers": [ + │ { + │ "confidence": 1, + │ "source": { + │ "end": 0, + │ "part": 0, + │ "start": 0, + │ "type": "text" + │ }, + │ "type": "text", + │ "value": "INV-2041" + │ } + │ ] + │ } + │ metadata: { + │ "braintrust": { + │ "integration_name": "ai-sdk", + │ "sdk_language": "typescript" + │ }, + │ "model": "extract-1", + │ "provider": "scaledown" + │ } + │ metrics: { + │ "completion_tokens": 0, + │ "estimated_cost": 0.00001045, + │ "prompt_tokens": 209, + │ "tokens": 209 + │ } + ├── ai-sdk-extract-operation + │ metadata: { + │ "operation": "extract", + │ "testRunId": "" + │ } + │ └── extract [extraction] + │ input: { + │ "fields": [ + │ { + │ "instructions": "The invoice number", + │ "type": "text" + │ } + │ ], + │ "state": "Invoice number: INV-2041." + │ } + │ output: { + │ "answers": [ + │ { + │ "confidence": 1, + │ "source": { + │ "end": 0, + │ "part": 0, + │ "start": 0, + │ "type": "text" + │ }, + │ "type": "text", + │ "value": "INV-2041" + │ } + │ ] + │ } + │ metadata: { + │ "braintrust": { + │ "integration_name": "ai-sdk", + │ "sdk_language": "typescript" + │ }, + │ "model": "extract-1", + │ "provider": "scaledown" + │ } + │ metrics: { + │ "completion_tokens": 0, + │ "estimated_cost": 0.00001045, + │ "prompt_tokens": 209, + │ "tokens": 209 + │ } ├── ai-sdk-evaluate-operation │ metadata: { │ "operation": "evaluate", diff --git a/e2e/scenarios/ai-sdk-instrumentation/assertions.ts b/e2e/scenarios/ai-sdk-instrumentation/assertions.ts index df854483b..7de784392 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/assertions.ts +++ b/e2e/scenarios/ai-sdk-instrumentation/assertions.ts @@ -990,6 +990,39 @@ export function defineAISDKInstrumentationAssertions(options: { }); } + if (options.sdkMajorVersion === 7) { + test("captures one extraction span per invoice", testConfig, () => { + const operations = events.filter((event) => + [ + "ai-sdk-extract-operation", + "ai-sdk-wrapped-extract-operation", + ].includes(event.span.name ?? ""), + ); + expect(operations.length).toBeGreaterThan(0); + for (const operation of operations) { + expectOperationParentedByRoot( + operation, + findLatestSpan(events, ROOT_NAME), + ); + const spans = findChildSpans(events, "extract", operation.span.id); + expect(spans).toHaveLength(1); + expect(spans[0].span.type).toBe("extraction"); + expect(spans[0].input).toMatchObject({ + fields: [{ id: "invoice", type: "text" }], + }); + expect(spans[0].output).toMatchObject({ + answers: [ + { + id: "invoice", + value: "INV-2041", + confidence: expect.any(Number), + }, + ], + }); + } + }); + } + if (options.supportsEvaluate) { test( "captures native evaluation answers and confidence", diff --git a/e2e/scenarios/ai-sdk-instrumentation/package.json b/e2e/scenarios/ai-sdk-instrumentation/package.json index bb2a70681..b2007c26e 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/package.json +++ b/e2e/scenarios/ai-sdk-instrumentation/package.json @@ -91,6 +91,7 @@ "ai-sdk-cohere-v6": "npm:@ai-sdk/cohere@3.0.7", "ai-sdk-cohere-v6-latest": "npm:@ai-sdk/cohere@3.0.51", "ai-sdk-v7": "npm:ai@7.0.103", + "ai-sdk-v7-extraction": "npm:ai@7.0.176", "ai-sdk-v7-latest": "npm:ai@7.0.179", "ai-sdk-openai-v7": "npm:@ai-sdk/openai@4.0.0", "ai-sdk-openai-v7-latest": "npm:@ai-sdk/openai@4.0.93", diff --git a/e2e/scenarios/ai-sdk-instrumentation/pnpm-lock.yaml b/e2e/scenarios/ai-sdk-instrumentation/pnpm-lock.yaml index d26bc091a..59888ea40 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/pnpm-lock.yaml +++ b/e2e/scenarios/ai-sdk-instrumentation/pnpm-lock.yaml @@ -107,6 +107,9 @@ importers: ai-sdk-v7: specifier: npm:ai@7.0.103 version: ai@7.0.103(zod@3.25.76) + ai-sdk-v7-extraction: + specifier: npm:ai@7.0.176 + version: ai@7.0.176(zod@3.25.76) ai-sdk-v7-latest: specifier: npm:ai@7.0.179 version: ai@7.0.179(zod@3.25.76) @@ -233,6 +236,12 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/gateway@4.0.149': + resolution: {integrity: sha512-xUDEBEU/3I4+8vAKomK3qCIIYHlWv0YF23EWxO+Th6lVAGWYNcdVn5uj5cV5Zp6W1PGdBVT+MQqO9sNoY3fY/g==} + engines: {node: '>=22'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/gateway@4.0.152': resolution: {integrity: sha512-8LYMe0uMPbT3XW/Urhca52TSgHXAlQok74EUkWL3qXWJI7naTxJGSF6B7hvIHur+V6ttSyLLZN0rJk+Qu9psqA==} engines: {node: '>=22'} @@ -401,6 +410,12 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/provider-utils@5.0.82': + resolution: {integrity: sha512-9s3Le9LsTR0exy14H8SERw4uMgFhiP0yJVoLefzfQCnnptj71noYh1AoVEsjfJjmMH1y16+1OqBVTDpTpU6M3Q==} + engines: {node: '>=22'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/provider-utils@5.0.83': resolution: {integrity: sha512-5lInsmNnh64eKi2L3fQjPy5VnV2y69lwyGnZ3vfz82Tlkgy8pWsvYueUrSJGxi8gXOM67jB9tN7LtDjjEFsNLQ==} engines: {node: '>=22'} @@ -576,6 +591,12 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 + ai@7.0.176: + resolution: {integrity: sha512-zIbiX58LQx3NB3+e0vYFcn4fipIqkVG9FHtWj7HVBCjh5f7GfWz5WVDeKmQ+M89RHAw9MU9pzfkFIAYEBeQi0g==} + engines: {node: '>=22'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + ai@7.0.179: resolution: {integrity: sha512-WT2ad3qEQPLne/5RDE/utNMSKYUuNpnGkI46AO/6Lv+IbEJ3kRwbatLX3HNfk25Y7N8LpdqOcSnMLcdw11VyIQ==} engines: {node: '>=22'} @@ -794,6 +815,13 @@ snapshots: '@vercel/oidc': 3.2.0 zod: 3.25.76 + '@ai-sdk/gateway@4.0.149(zod@3.25.76)': + dependencies: + '@ai-sdk/provider': 4.0.39 + '@ai-sdk/provider-utils': 5.0.82(zod@3.25.76) + '@vercel/oidc': 3.2.0 + zod: 3.25.76 + '@ai-sdk/gateway@4.0.152(zod@3.25.76)': dependencies: '@ai-sdk/provider': 4.0.39 @@ -997,6 +1025,14 @@ snapshots: undici: 7.29.1 zod: 3.25.76 + '@ai-sdk/provider-utils@5.0.82(zod@3.25.76)': + dependencies: + '@ai-sdk/provider': 4.0.39 + '@standard-schema/spec': 1.1.0 + '@workflow/serde': 4.1.0 + eventsource-parser: 3.0.8 + zod: 3.25.76 + '@ai-sdk/provider-utils@5.0.83(zod@3.25.76)': dependencies: '@ai-sdk/provider': 4.0.39 @@ -1176,6 +1212,13 @@ snapshots: '@ai-sdk/provider-utils': 5.0.62(zod@3.25.76) zod: 3.25.76 + ai@7.0.176(zod@3.25.76): + dependencies: + '@ai-sdk/gateway': 4.0.149(zod@3.25.76) + '@ai-sdk/provider': 4.0.39 + '@ai-sdk/provider-utils': 5.0.82(zod@3.25.76) + zod: 3.25.76 + ai@7.0.179(zod@3.25.76): dependencies: '@ai-sdk/gateway': 4.0.152(zod@3.25.76) diff --git a/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7-explicit.mjs b/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7-explicit.mjs index ce45d9337..4d75d634a 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7-explicit.mjs +++ b/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7-explicit.mjs @@ -44,6 +44,7 @@ runMain(async () => { createCohere, createOpenAI, directModelWrapping: true, + explicitTelemetry: true, maxTokensKey: "maxOutputTokens", openai, sdkVersion: await getInstalledPackageVersion( diff --git a/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7.ts b/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7.ts index 70b8ebf9f..fac3065c9 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7.ts +++ b/e2e/scenarios/ai-sdk-instrumentation/scenario.ai-sdk-v7.ts @@ -30,6 +30,7 @@ runMain(async () => { createCohere, createOpenAI, directModelWrapping: true, + explicitTelemetry: true, maxTokensKey: "maxOutputTokens", openai, sdkVersion: await getInstalledPackageVersion( diff --git a/e2e/scenarios/ai-sdk-instrumentation/scenario.impl.mjs b/e2e/scenarios/ai-sdk-instrumentation/scenario.impl.mjs index 9965cb0a8..c89d30a0f 100644 --- a/e2e/scenarios/ai-sdk-instrumentation/scenario.impl.mjs +++ b/e2e/scenarios/ai-sdk-instrumentation/scenario.impl.mjs @@ -659,6 +659,38 @@ async function runAISDKInstrumentationScenario( }, ); } + + // The general v7 pin predates extraction. Keep its other coverage intact. + const extractionAI = options.ai.experimental_extract + ? options.ai + : await import("ai-sdk-v7-extraction"); + const gateway = extractionAI.createGateway({ + baseURL: process.env.BRAINTRUST_E2E_AI_GATEWAY_BASE_URL, + apiKey: process.env.AI_GATEWAY_API_KEY ?? "cassette-placeholder", + }); + const calls = []; + if (options.explicitTelemetry) { + calls.push(["wrapped-extract", wrapAISDK(extractionAI)]); + } + if (!options.explicitTelemetry || options.ai.experimental_extract) { + calls.push(["extract", extractionAI]); + } + for (const [operation, sdk] of calls) { + await runOperation( + `ai-sdk-${operation}-operation`, + operation, + async () => { + const result = await sdk.experimental_extract({ + model: gateway.extractionModel("scaledown/extract-1"), + state: "Invoice number: INV-2041.", + fields: { + invoice: { type: "text", instructions: "The invoice number" }, + }, + }); + assert.equal(result.answers.invoice.value, "INV-2041"); + }, + ); + } } if (options.supportsEvaluate) { diff --git a/js/src/auto-instrumentations/configs/ai-sdk.ts b/js/src/auto-instrumentations/configs/ai-sdk.ts index e3da0a50b..9bfe2c6ac 100644 --- a/js/src/auto-instrumentations/configs/ai-sdk.ts +++ b/js/src/auto-instrumentations/configs/ai-sdk.ts @@ -37,6 +37,19 @@ export const aiSDKConfigs: InstrumentationConfig[] = [ }, functionQuery: { functionName: "runCodeMode" }, }, + // Extraction gained telemetry callbacks in 7.0.178. + { + channelName: aiSDKChannels.extract.channelName, + module: { + name: "ai", + versionRange: ">=7.0.176 <7.0.178", + filePath: "dist/index.js", + }, + functionQuery: { + functionName: "experimental_extract", + isExportAlias: true, + }, + }, // Older evaluation releases have no telemetry callbacks. Newer versions use // the telemetry dispatcher below, including the renamed decision API. { diff --git a/js/src/instrumentation/providers/ai-sdk-instrumentation.ts b/js/src/instrumentation/providers/ai-sdk-instrumentation.ts index 409e64892..f3b72fbbb 100644 --- a/js/src/instrumentation/providers/ai-sdk-instrumentation.ts +++ b/js/src/instrumentation/providers/ai-sdk-instrumentation.ts @@ -79,6 +79,8 @@ import type { AISDK, AISDKCallParams, AISDKEmbedParams, + AISDKExtractionInput, + AISDKExtractionResult, AISDKEvaluateParams, AISDKEvaluationResult, AISDKEmbeddingResult, @@ -186,6 +188,8 @@ const AI_SDK_V7_TELEMETRY_CALLBACKS = [ "onEmbedEnd", "onRerankStart", "onRerankEnd", + "experimental_onExtractStart", + "experimental_onExtractEnd", "experimental_onEvaluateStart", "experimental_onEvaluateEnd", "experimental_onDecideStart", @@ -251,6 +255,37 @@ class AISDKInstrumentationConsumer { ); interceptAISDKV7TelemetryDispatcher(); interceptAISDKEvaluate(denyOutputPaths); + aiSDKChannels.extract.intercept((target, receiver, args, additional) => + traceAsyncCall( + () => + runWithAutoInstrumentationSuppressed(() => + Reflect.apply(target, receiver, args), + ), + { ...additional, arguments: args, self: receiver }, + { + instrumentationName: INSTRUMENTATION_NAMES.AI_SDK, + name: "extract", + type: SpanTypeAttribute.EXTRACTION, + shouldTrace: () => args[0].telemetry?.isEnabled !== false, + extractInput: ([params]) => ({ + input: + params.telemetry?.recordInputs === false + ? undefined + : processAISDKExtractionInput(params), + metadata: extractBaseMetadata(params.model), + }), + extractOutput: (result, event) => + args[0].telemetry?.recordOutputs === false + ? undefined + : processAISDKExtractionOutput( + result, + resolveDenyOutputPaths(event, denyOutputPaths), + ), + extractMetrics: (result) => extractTokenMetrics(result), + extractMetadata: (result) => extractGatewayRoutingInfo(result), + }, + ), + ); interceptAISDKModelGenerate(denyOutputPaths); interceptAISDKModelStream(denyOutputPaths); subscribeToHarnessAgentCreateSession(); @@ -986,13 +1021,30 @@ function interceptAISDKEvaluate(defaultDenyOutputPaths: string[]): () => void { ); } +export function processAISDKExtractionInput(params: AISDKExtractionInput) { + return prepareTypedAttachments({ + state: params.state, + fields: addFieldIds(params.fields), + referenceDate: params.referenceDate, + reasoning: params.reasoning, + maxOutputTokens: params.maxOutputTokens, + }); +} + +export function processAISDKExtractionOutput( + result: AISDKExtractionResult, + denyOutputPaths: string[], +) { + return omit({ answers: addFieldIds(result.answers) }, denyOutputPaths); +} + /** Keep the decision envelope intact; automatic uploads run after customizers. */ export function processAISDKDecisionInput( params: Pick, ) { return prepareTypedAttachments({ state: params.state, - questions: addEvaluationIds(params.questions), + questions: addFieldIds(params.questions), }) as { state: unknown; questions: unknown }; } @@ -1018,7 +1070,7 @@ export function processAISDKDecisionResult( return { output: prepareTypedAttachments( omit( - { answers: addEvaluationIds(value.answers, confidence) }, + { answers: addFieldIds(value.answers, confidence) }, denyOutputPaths, ), ), @@ -1031,10 +1083,7 @@ export function processAISDKDecisionResult( }; } -function addEvaluationIds( - value: unknown, - confidence: unknown = undefined, -): unknown { +function addFieldIds(value: unknown, confidence: unknown = undefined): unknown { if (!isObject(value)) { return value; } @@ -4921,7 +4970,7 @@ function parseGatewayModelString(modelString: string): { return { model: modelString }; } -function extractGatewayRoutingInfo(result: AISDKResult): { +export function extractGatewayRoutingInfo(result: AISDKResult): { model?: string; provider?: string; } | null { diff --git a/js/src/instrumentation/providers/ai-sdk-interceptors.ts b/js/src/instrumentation/providers/ai-sdk-interceptors.ts index 36ec7cf2b..68d68c1f3 100644 --- a/js/src/instrumentation/providers/ai-sdk-interceptors.ts +++ b/js/src/instrumentation/providers/ai-sdk-interceptors.ts @@ -6,6 +6,8 @@ import type { AISDKCallParams, AISDKEmbedParams, AISDKEmbeddingResult, + AISDKExtractParams, + AISDKExtractionResult, AISDKEvaluateParams, AISDKEvaluationResult, AISDKGenerateImageParams, @@ -62,6 +64,11 @@ export const aiSDKChannels = defineInterceptor("ai", { >({ channelName: "model.doStream", }), + extract: channel< + [AISDKExtractParams], + PromiseLike, + AISDKChannelContext + >({ channelName: "extract" }), evaluate: channel< [AISDKEvaluateParams], PromiseLike, diff --git a/js/src/vendor-sdk-types/ai-sdk-common.ts b/js/src/vendor-sdk-types/ai-sdk-common.ts index 199233bdd..4949d61ea 100644 --- a/js/src/vendor-sdk-types/ai-sdk-common.ts +++ b/js/src/vendor-sdk-types/ai-sdk-common.ts @@ -79,6 +79,23 @@ export interface AISDKGeneratedFile { [key: string]: unknown; } +export interface AISDKExtractionInput { + state: unknown; + fields: Record; + referenceDate?: string; + maxOutputTokens?: number; + reasoning?: string; +} + +export interface AISDKExtractParams extends AISDKExtractionInput { + model: string | { modelId: string; provider: string }; + telemetry?: AISDKEvaluateParams["telemetry"]; +} + +export interface AISDKExtractionResult extends AISDKResult { + answers: Record; +} + export interface AISDKEvaluateParams { telemetry?: { isEnabled?: boolean; @@ -446,6 +463,9 @@ export interface AISDKNamespaceBase { Agent?: AISDKAgentClass; Experimental_Agent?: AISDKAgentClass; ToolLoopAgent?: AISDKAgentClass; + experimental_extract?: ( + params: AISDKExtractParams, + ) => Promise; experimental_evaluate?: AISDKEvaluateFunction; experimental_decide?: AISDKEvaluateFunction; generateText: AISDKGenerateFunction; diff --git a/js/src/vendor-sdk-types/ai-sdk-v7-telemetry.ts b/js/src/vendor-sdk-types/ai-sdk-v7-telemetry.ts index 1c6b6d361..37e2bb29b 100644 --- a/js/src/vendor-sdk-types/ai-sdk-v7-telemetry.ts +++ b/js/src/vendor-sdk-types/ai-sdk-v7-telemetry.ts @@ -1,4 +1,6 @@ import type { + AISDKExtractionInput, + AISDKExtractionResult, AISDKEvaluateParams, AISDKEvaluationResult, } from "./ai-sdk-common"; @@ -192,7 +194,16 @@ export interface AISDKV7DecisionStartEvent extends AISDKV7OperationEvent { export interface AISDKV7DecisionEndEvent extends AISDKV7DecisionStartEvent, AISDKEvaluationResult {} +export interface AISDKV7ExtractionStartEvent + extends AISDKV7OperationEvent, AISDKExtractionInput {} + export interface AISDKV7Telemetry { + experimental_onExtractStart?: ( + event: AISDKV7ExtractionStartEvent, + ) => void | PromiseLike; + experimental_onExtractEnd?: ( + event: AISDKV7ExtractionStartEvent & AISDKExtractionResult, + ) => void | PromiseLike; experimental_onEvaluateStart?: ( event: AISDKV7DecisionStartEvent, ) => void | PromiseLike; diff --git a/js/src/vendor-sdk-types/ai-sdk.ts b/js/src/vendor-sdk-types/ai-sdk.ts index 8e29f2ea6..b9f8abf11 100644 --- a/js/src/vendor-sdk-types/ai-sdk.ts +++ b/js/src/vendor-sdk-types/ai-sdk.ts @@ -1,4 +1,7 @@ import type { + AISDKExtractParams, + AISDKExtractionResult, + AISDKExtractionInput, AISDKEvaluateParams, AISDKEvaluationResult, AISDKAgentClass, @@ -42,6 +45,9 @@ import type { export type AISDK = AISDKNamespaceBase; export type { + AISDKExtractParams, + AISDKExtractionResult, + AISDKExtractionInput, AISDKEvaluateParams, AISDKEvaluationResult, AISDKAgentClass, diff --git a/js/src/wrappers/ai-sdk-extract.test.ts b/js/src/wrappers/ai-sdk-extract.test.ts new file mode 100644 index 000000000..00808c390 --- /dev/null +++ b/js/src/wrappers/ai-sdk-extract.test.ts @@ -0,0 +1,68 @@ +import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; +import { initLogger, type TestBackgroundLogger } from "../logger/core"; +import { _exportsForTestingOnly } from "../logger/testing"; +import { configureNode } from "../node/config"; +import { wrapAISDK } from "./ai-sdk/ai-sdk"; + +configureNode(); + +let logger: TestBackgroundLogger; +beforeEach(async () => { + await _exportsForTestingOnly.simulateLoginForTests(); + logger = _exportsForTestingOnly.useTestBackgroundLogger(); + initLogger({ projectName: "ai-sdk-extract", projectId: "test-project-id" }); +}); +afterEach(() => { + _exportsForTestingOnly.clearTestBackgroundLogger(); + vi.unstubAllEnvs(); +}); + +test("keeps list and missing answers and omits inline document bytes", async () => { + vi.stubEnv("BRAINTRUST_AUTO_CAPTURE_ATTACHMENTS", "false"); + const params = { + model: "scaledown/extract-1", + state: [ + { + type: "file", + data: new Uint8Array([1, 2]), + mediaType: "application/pdf", + }, + ], + fields: { + contacts: { type: "list", items: "text" }, + vendor: { type: "text" }, + }, + headers: { authorization: "private" }, + }; + const result = { + answers: { + contacts: { + type: "list", + value: ["Ana"], + items: [{ value: "Ana", confidence: 0.9 }], + }, + vendor: { type: "text", value: null }, + }, + }; + const promise = Promise.resolve(result); + const extract = vi.fn((_params: typeof params) => promise); + const wrapped = wrapAISDK({ experimental_extract: extract }); + expect(wrapped.experimental_extract(params)).toBe(promise); + await promise; + expect(extract.mock.calls[0][0]).toBe(params); + const [span] = await logger.drain(); + expect(span).toMatchObject({ + input: { + state: [ + { type: "file", data: "", mediaType: "application/pdf" }, + ], + }, + output: { + answers: [ + { ...result.answers.contacts, id: "contacts" }, + { ...result.answers.vendor, id: "vendor" }, + ], + }, + }); + expect(JSON.stringify(span)).not.toContain("private"); +}); diff --git a/js/src/wrappers/ai-sdk/ai-sdk.ts b/js/src/wrappers/ai-sdk/ai-sdk.ts index 394187f21..286358c13 100644 --- a/js/src/wrappers/ai-sdk/ai-sdk.ts +++ b/js/src/wrappers/ai-sdk/ai-sdk.ts @@ -15,6 +15,7 @@ import type { AISDKCallParams, AISDKEmbedFunction, AISDKEmbedParams, + AISDKExtractParams, AISDKEvaluateParams, AISDKGenerateFunction, AISDKGenerateImageFunction, @@ -161,6 +162,23 @@ export function wrapAISDK(aiSDK: T, options: WrapAISDKOptions = {}): T { ); } : original; + case "experimental_extract": { + const extract = typedAISDK.experimental_extract; + return typeof extract === "function" + ? function ( + this: unknown, + allParams: AISDKExtractParams & SpanInfo, + ) { + const { span_info, ...params } = allParams; + return aiSDKChannels.extract.invoke( + extract, + this, + ["span_info" in allParams ? params : allParams], + { denyOutputPaths: options.denyOutputPaths, span_info }, + ); + } + : original; + } case "experimental_decide": case "experimental_evaluate": { const evaluate = typedAISDK[prop]; diff --git a/js/src/wrappers/ai-sdk/telemetry.ts b/js/src/wrappers/ai-sdk/telemetry.ts index 57d689dda..265999c18 100644 --- a/js/src/wrappers/ai-sdk/telemetry.ts +++ b/js/src/wrappers/ai-sdk/telemetry.ts @@ -28,7 +28,10 @@ import { DEFAULT_DENY_OUTPUT_PATHS, extractWorkflowMetadataFromCallParams, extractTokenMetrics, + extractGatewayRoutingInfo, processAISDKCallInput, + processAISDKExtractionInput, + processAISDKExtractionOutput, processAISDKDecisionInput, processAISDKDecisionResult, processAISDKEmbeddingOutput, @@ -40,6 +43,7 @@ import { } from "../../instrumentation/providers/ai-sdk-instrumentation"; import type { AISDKCallParams, + AISDKExtractionResult, AISDKEvaluationResult, AISDKEmbeddingResult, AISDKModel, @@ -48,6 +52,7 @@ import type { } from "../../vendor-sdk-types/ai-sdk"; import type { AISDKV7LanguageModelCallStartEvent, + AISDKV7ExtractionStartEvent, AISDKV7DecisionStartEvent, AISDKV7OperationEvent, AISDKV7ProviderToolPart, @@ -485,6 +490,25 @@ export function braintrustAISDKTelemetry(): any { return; } + if (state.operationName === "extract") { + const result = event as AISDKV7OperationEvent & AISDKExtractionResult; + state.span.log({ + ...(state.recordOutputs !== false && shouldRecordOutputs(event) + ? { + output: processAISDKExtractionOutput( + result, + DEFAULT_DENY_OUTPUT_PATHS, + ), + } + : {}), + metrics: extractTokenMetrics(result), + metadata: extractGatewayRoutingInfo(result) ?? undefined, + }); + state.span.end(); + deleteOperation(state.operationKey); + return; + } + if (state.operationName === "evaluate") { const { output, ...resultLog } = processAISDKDecisionResult( event as AISDKV7OperationEvent & AISDKEvaluationResult, @@ -544,24 +568,34 @@ export function braintrustAISDKTelemetry(): any { }); }; - const onDecisionStart = (event: AISDKV7DecisionStartEvent) => { + const onTypedStart = ( + event: AISDKV7OperationEvent, + operationName: "extract" | "evaluate", + input: () => unknown, + ) => { if (isAutoInstrumentationSuppressed()) return; - runSafely("onDecisionStart", () => { - // Keep question span names stable across the evaluate -> decide rename. - const operationKey = createOperationKey(event, "evaluate"); + runSafely(operationName, () => { + const operationKey = createOperationKey(event, operationName); const span = startSpan( withSpanInstrumentationName( { - name: "evaluate", - spanAttributes: { type: "question" }, + name: operationName, + spanAttributes: { + type: + operationName === "extract" + ? SpanTypeAttribute.EXTRACTION + : "question", + }, event: { - ...(shouldRecordInputs(event) - ? { input: processAISDKDecisionInput(event) } - : {}), + ...(shouldRecordInputs(event) ? { input: input() } : {}), metadata: { ...createAISDKIntegrationMetadata(), - model: event.modelId, - provider: event.provider, + ...(operationName === "extract" + ? serializeModelWithProvider({ + modelId: event.modelId, + provider: event.provider, + }) + : { model: event.modelId, provider: event.provider }), }, }, }, @@ -571,7 +605,7 @@ export function braintrustAISDKTelemetry(): any { registerOperation({ callId: event.callId, operationKey, - operationName: "evaluate", + operationName, ownsSpan: true, span, hadModelChild: false, @@ -584,7 +618,14 @@ export function braintrustAISDKTelemetry(): any { }); }; + // Keep question span names stable across the evaluate -> decide rename. + const onDecisionStart = (event: AISDKV7DecisionStartEvent) => + onTypedStart(event, "evaluate", () => processAISDKDecisionInput(event)); + return { + experimental_onExtractStart: (event: AISDKV7ExtractionStartEvent) => + onTypedStart(event, "extract", () => processAISDKExtractionInput(event)), + experimental_onExtractEnd: onEnd, [BRAINTRUST_AI_SDK_V7_TELEMETRY]: true, experimental_onEvaluateStart: onDecisionStart, experimental_onEvaluateEnd: onEnd, From be4423845b745df53e76ce489ce73b8989be642b Mon Sep 17 00:00:00 2001 From: lforst <8118419+lforst@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:40:04 +0000 Subject: [PATCH 2/3] Update PR #2883 --- .changeset/ai-sdk-extraction.md | 5 ++ .../providers/ai-sdk-instrumentation.ts | 84 ++++++++++++++++--- .../providers/extraction-properties.ts | 13 +++ .../providers/workers-ai-plugin.ts | 13 +-- js/src/typed-attachments.ts | 16 ++++ js/src/vendor-sdk-types/ai-sdk-common.ts | 2 - js/src/wrappers/ai-sdk-extract.test.ts | 67 +++++++++++++-- js/src/wrappers/ai-sdk/telemetry.ts | 4 +- 8 files changed, 171 insertions(+), 33 deletions(-) create mode 100644 .changeset/ai-sdk-extraction.md create mode 100644 js/src/instrumentation/providers/extraction-properties.ts diff --git a/.changeset/ai-sdk-extraction.md b/.changeset/ai-sdk-extraction.md new file mode 100644 index 000000000..9c61b815a --- /dev/null +++ b/.changeset/ai-sdk-extraction.md @@ -0,0 +1,5 @@ +--- +"braintrust": minor +--- + +feat(ai-sdk): Trace extraction calls diff --git a/js/src/instrumentation/providers/ai-sdk-instrumentation.ts b/js/src/instrumentation/providers/ai-sdk-instrumentation.ts index f3b72fbbb..066ddfd3c 100644 --- a/js/src/instrumentation/providers/ai-sdk-instrumentation.ts +++ b/js/src/instrumentation/providers/ai-sdk-instrumentation.ts @@ -1,3 +1,4 @@ +import { pickExtractionProperties } from "./extraction-properties"; import { serviceTierMetadata } from "../core/service-tier"; import { aiSDKServiceTierMetadata } from "./ai-sdk-service-tier"; import { traceAISDKCodeMode } from "./ai-sdk-code-mode"; @@ -282,7 +283,7 @@ class AISDKInstrumentationConsumer { resolveDenyOutputPaths(event, denyOutputPaths), ), extractMetrics: (result) => extractTokenMetrics(result), - extractMetadata: (result) => extractGatewayRoutingInfo(result), + extractMetadata: extractionResultMetadata, }, ), ); @@ -1024,10 +1025,20 @@ function interceptAISDKEvaluate(defaultDenyOutputPaths: string[]): () => void { export function processAISDKExtractionInput(params: AISDKExtractionInput) { return prepareTypedAttachments({ state: params.state, - fields: addFieldIds(params.fields), - referenceDate: params.referenceDate, - reasoning: params.reasoning, - maxOutputTokens: params.maxOutputTokens, + fields: Object.entries(params.fields).map(([id, field]) => ({ + id, + ...pickExtractionProperties(field, [ + "type", + "instructions", + "unit", + "integer", + "decimals", + "items", + ]), + })), + ...(params.referenceDate !== undefined + ? { reference_date: params.referenceDate } + : {}), }); } @@ -1035,7 +1046,57 @@ export function processAISDKExtractionOutput( result: AISDKExtractionResult, denyOutputPaths: string[], ) { - return omit({ answers: addFieldIds(result.answers) }, denyOutputPaths); + const answers = Object.entries(result.answers).map(([id, answer]) => { + const properties = pickExtractionProperties(answer, [ + "type", + "value", + "confidence", + ]); + if (!isObject(answer)) return { id, ...properties }; + if (answer.pNull !== undefined) properties.p_null = answer.pNull; + if (answer.type === "list") { + if (answer.items !== undefined) { + properties.items = Array.isArray(answer.items) + ? answer.items.map((item) => { + if (!isObject(item)) return item; + return { + ...pickExtractionProperties(item, ["confidence"]), + ...(item.source !== undefined + ? { source: extractionSource(item.source) } + : {}), + }; + }) + : answer.items; + } + } else { + if (answer.guess !== undefined) properties.guess = answer.guess; + if (answer.source !== undefined) + properties.source = extractionSource(answer.source); + } + return { id, ...properties }; + }); + return omit({ answers }, denyOutputPaths); +} + +function extractionSource(source: unknown): unknown { + if (!isObject(source)) return source; + return pickExtractionProperties( + source, + source.type === "file" + ? ["type", "part"] + : ["type", "part", "start", "end"], + ); +} + +export function extractionResultMetadata(result: AISDKExtractionResult) { + const routing = extractGatewayRoutingInfo(result); + const modelId = routing?.model ?? result.response?.modelId; + return { + ...(typeof modelId === "string" + ? { model: serializeModelWithProvider(modelId).model } + : {}), + ...(routing?.provider ? { provider: routing.provider } : {}), + }; } /** Keep the decision envelope intact; automatic uploads run after customizers. */ @@ -1044,7 +1105,7 @@ export function processAISDKDecisionInput( ) { return prepareTypedAttachments({ state: params.state, - questions: addFieldIds(params.questions), + questions: addEvaluationIds(params.questions), }) as { state: unknown; questions: unknown }; } @@ -1070,7 +1131,7 @@ export function processAISDKDecisionResult( return { output: prepareTypedAttachments( omit( - { answers: addFieldIds(value.answers, confidence) }, + { answers: addEvaluationIds(value.answers, confidence) }, denyOutputPaths, ), ), @@ -1083,7 +1144,10 @@ export function processAISDKDecisionResult( }; } -function addFieldIds(value: unknown, confidence: unknown = undefined): unknown { +function addEvaluationIds( + value: unknown, + confidence: unknown = undefined, +): unknown { if (!isObject(value)) { return value; } @@ -4970,7 +5034,7 @@ function parseGatewayModelString(modelString: string): { return { model: modelString }; } -export function extractGatewayRoutingInfo(result: AISDKResult): { +function extractGatewayRoutingInfo(result: AISDKResult): { model?: string; provider?: string; } | null { diff --git a/js/src/instrumentation/providers/extraction-properties.ts b/js/src/instrumentation/providers/extraction-properties.ts new file mode 100644 index 000000000..2fe69d21e --- /dev/null +++ b/js/src/instrumentation/providers/extraction-properties.ts @@ -0,0 +1,13 @@ +import { isObject } from "../../../util/index"; + +export function pickExtractionProperties( + value: unknown, + keys: readonly string[], +): Record { + if (!isObject(value)) return {}; + return Object.fromEntries( + keys + .filter((key) => Object.hasOwn(value, key) && value[key] !== undefined) + .map((key) => [key, value[key]]), + ); +} diff --git a/js/src/instrumentation/providers/workers-ai-plugin.ts b/js/src/instrumentation/providers/workers-ai-plugin.ts index 639c73773..9cdcdb076 100644 --- a/js/src/instrumentation/providers/workers-ai-plugin.ts +++ b/js/src/instrumentation/providers/workers-ai-plugin.ts @@ -1,3 +1,4 @@ +import { pickExtractionProperties } from "./extraction-properties"; import { isObject } from "../../../util/index"; import { prepareTypedAttachments } from "../../typed-attachments"; import { INSTRUMENTATION_NAMES } from "../../span-origin"; @@ -52,18 +53,6 @@ const EXTRACTION_RESULT_PROPERTIES = new Map([ ["forecast", ESTIMATE_RESULT_PROPERTIES], ]); -function pickExtractionProperties( - value: unknown, - keys: readonly string[], -): Record { - if (!isObject(value)) return {}; - return Object.fromEntries( - keys - .filter((key) => Object.hasOwn(value, key) && value[key] !== undefined) - .map((key) => [key, value[key]]), - ); -} - function extractWorkersAIExtraction(result: WorkersAIResult): unknown { return { answers: Object.entries(result.answers ?? {}).map(([id, answer]) => ({ diff --git a/js/src/typed-attachments.ts b/js/src/typed-attachments.ts index 425815a7a..e3562d2c4 100644 --- a/js/src/typed-attachments.ts +++ b/js/src/typed-attachments.ts @@ -85,6 +85,22 @@ function mapTypedPayload( ...("images" in value ? { images: mapTypedMedia(value.images, media, omitDeepValues) } : {}), + ...(Array.isArray(value.fields) + ? { + fields: value.fields.map((field) => + isObject(field) && "instructions" in field + ? { + ...field, + instructions: mapTypedMedia( + field.instructions, + media, + omitDeepValues, + ), + } + : field, + ), + } + : {}), ...(Array.isArray(value.questions) ? { questions: value.questions.map((question) => { diff --git a/js/src/vendor-sdk-types/ai-sdk-common.ts b/js/src/vendor-sdk-types/ai-sdk-common.ts index 4949d61ea..dd952c1df 100644 --- a/js/src/vendor-sdk-types/ai-sdk-common.ts +++ b/js/src/vendor-sdk-types/ai-sdk-common.ts @@ -83,8 +83,6 @@ export interface AISDKExtractionInput { state: unknown; fields: Record; referenceDate?: string; - maxOutputTokens?: number; - reasoning?: string; } export interface AISDKExtractParams extends AISDKExtractionInput { diff --git a/js/src/wrappers/ai-sdk-extract.test.ts b/js/src/wrappers/ai-sdk-extract.test.ts index 00808c390..5dd2b68e7 100644 --- a/js/src/wrappers/ai-sdk-extract.test.ts +++ b/js/src/wrappers/ai-sdk-extract.test.ts @@ -27,21 +27,44 @@ test("keeps list and missing answers and omits inline document bytes", async () data: new Uint8Array([1, 2]), mediaType: "application/pdf", }, + { type: "text", text: "A😀" }, ], + referenceDate: "2026-12-01", + reasoning: "low", + maxOutputTokens: 10, fields: { contacts: { type: "list", items: "text" }, - vendor: { type: "text" }, + vendor: { + type: "text", + private: "private", + instructions: { example: "data:image/png;base64,AQID" }, + }, }, headers: { authorization: "private" }, }; const result = { + response: { modelId: "scaledown/resolved-model" }, answers: { contacts: { type: "list", - value: ["Ana"], - items: [{ value: "Ana", confidence: 0.9 }], + value: ["Ana", "Bo", "Jo"], + items: [ + { + value: "private", + confidence: 0, + source: { type: "file", part: 0, private: "private" }, + }, + {}, + { source: null }, + ], + }, + vendor: { + type: "text", + value: null, + pNull: 0, + guess: "A😀", + source: { type: "text", part: 1, start: 0, end: 3 }, }, - vendor: { type: "text", value: null }, }, }; const promise = Promise.resolve(result); @@ -52,17 +75,47 @@ test("keeps list and missing answers and omits inline document bytes", async () expect(extract.mock.calls[0][0]).toBe(params); const [span] = await logger.drain(); expect(span).toMatchObject({ + metadata: { model: "resolved-model" }, input: { + reference_date: "2026-12-01", + fields: [ + { id: "contacts", type: "list", items: "text" }, + { id: "vendor", type: "text", instructions: { example: "" } }, + ], state: [ { type: "file", data: "", mediaType: "application/pdf" }, + { type: "text", text: "A😀" }, ], }, output: { answers: [ - { ...result.answers.contacts, id: "contacts" }, - { ...result.answers.vendor, id: "vendor" }, + { + type: "list", + id: "contacts", + value: ["Ana", "Bo", "Jo"], + items: [ + { confidence: 0, source: { type: "file", part: 0 } }, + {}, + { source: null }, + ], + }, + { + type: "text", + id: "vendor", + value: null, + guess: "A😀", + p_null: 0, + source: { type: "text", part: 1, start: 0, end: 3 }, + }, ], }, }); - expect(JSON.stringify(span)).not.toContain("private"); + for (const key of [ + "private", + "referenceDate", + "maxOutputTokens", + "reasoning", + "pNull", + ]) + expect(JSON.stringify(span)).not.toContain(key); }); diff --git a/js/src/wrappers/ai-sdk/telemetry.ts b/js/src/wrappers/ai-sdk/telemetry.ts index 265999c18..91e89d501 100644 --- a/js/src/wrappers/ai-sdk/telemetry.ts +++ b/js/src/wrappers/ai-sdk/telemetry.ts @@ -28,7 +28,7 @@ import { DEFAULT_DENY_OUTPUT_PATHS, extractWorkflowMetadataFromCallParams, extractTokenMetrics, - extractGatewayRoutingInfo, + extractionResultMetadata, processAISDKCallInput, processAISDKExtractionInput, processAISDKExtractionOutput, @@ -502,7 +502,7 @@ export function braintrustAISDKTelemetry(): any { } : {}), metrics: extractTokenMetrics(result), - metadata: extractGatewayRoutingInfo(result) ?? undefined, + metadata: extractionResultMetadata(result), }); state.span.end(); deleteOperation(state.operationKey); From ccab5dba0e8ee562c25fab0d352e0c7962ddd17e Mon Sep 17 00:00:00 2001 From: lforst <8118419+lforst@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:12:03 +0000 Subject: [PATCH 3/3] Update PR #2883 --- .../api-compatibility.test.ts | 117 +++++++++++------- 1 file changed, 74 insertions(+), 43 deletions(-) diff --git a/js/tests/api-compatibility/api-compatibility.test.ts b/js/tests/api-compatibility/api-compatibility.test.ts index 6aed1f5ae..65b9e6cf3 100644 --- a/js/tests/api-compatibility/api-compatibility.test.ts +++ b/js/tests/api-compatibility/api-compatibility.test.ts @@ -165,13 +165,10 @@ function getChangesetBumpType( * For bulk exports (export { A, B, C }), looks up the actual declaration * of each symbol to get its true signature, rather than using the export statement. */ -function extractExportsFromDts(filePath: string): Map { - const program = ts.createProgram([filePath], { - target: ts.ScriptTarget.ES2022, - module: ts.ModuleKind.ESNext, - moduleResolution: ts.ModuleResolutionKind.Bundler, - skipLibCheck: true, - }); +function extractExportsFromDts( + program: ts.Program, + filePath: string, +): Map { const checker = program.getTypeChecker(); const source = program.getSourceFile(filePath); if (!source) throw new Error(`Missing declarations: ${filePath}`); @@ -212,14 +209,10 @@ function getNodeKind(node: ts.Node): string { /** * Extracts actual runtime exports from a JavaScript module file */ -async function extractRuntimeExports(modulePath: string): Promise> { - // Inspect ESM exports without executing setup entrypoints or test-runner integrations. - const program = ts.createProgram([modulePath], { - allowJs: true, - module: ts.ModuleKind.ESNext, - moduleResolution: ts.ModuleResolutionKind.Bundler, - target: ts.ScriptTarget.ES2022, - }); +function extractRuntimeExports( + program: ts.Program, + modulePath: string, +): Set { const source = program.getSourceFile(modulePath); if (!source) throw new Error(`Missing runtime entrypoint: ${modulePath}`); const checker = program.getTypeChecker(); @@ -2668,27 +2661,6 @@ describe("areConstArraySignaturesCompatible", () => { }); }); -/** - * Gets exports from main branch for baseline comparison. - * Since dist/ files aren't in git, we need to build main first in CI. - * This checks if a pre-built baseline exists from CI, otherwise returns null. - */ -async function getMainBranchExports( - entrypoint: Entrypoint, -): Promise | null> { - const baselineRoot = path.join( - process.env.BASELINE_DIR || path.join(os.tmpdir(), "braintrust-baseline"), - "js", - ); - if (!fs.existsSync(path.join(baselineRoot, "package.json"))) return null; - const baseline = getEntrypointsFromPackageExports(baselineRoot).find( - ({ name }) => name === entrypoint.name, - ); - return baseline - ? extractExportsFromDts(path.join(baselineRoot, baseline.typesPath)) - : null; -} - interface BreakingChanges { removed: ExportedSymbol[]; modified: Array<{ @@ -2908,7 +2880,7 @@ describe("API Compatibility", () => { ); }); - test("should not regress public API surface for all entrypoints", async () => { + test("should not regress public API surface for all entrypoints", () => { if (!publishedVersion) { console.log("Skipping test: No published version available"); return; @@ -2917,9 +2889,51 @@ describe("API Compatibility", () => { // Track any failures to report them all at once const failures: string[] = []; + const currentRoot = path.join(__dirname, "../.."); + const publishedRoot = path.join(tempDir, "package"); + const baselineRoot = path.join( + process.env.BASELINE_DIR || path.join(os.tmpdir(), "braintrust-baseline"), + "js", + ); + const publishedEntrypoints = + getEntrypointsFromPackageExports(publishedRoot); + const baselineEntrypoints = fs.existsSync( + path.join(baselineRoot, "package.json"), + ) + ? getEntrypointsFromPackageExports(baselineRoot) + : []; + + // Share dependency parsing across entrypoints, keeping each version's types isolated. + const compilerOptions = { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + skipLibCheck: true, + }; + const declarationProgram = (root: string, entrypoints: Entrypoint[]) => + ts.createProgram( + entrypoints.map(({ typesPath }) => path.join(root, typesPath)), + compilerOptions, + ); + const currentProgram = declarationProgram(currentRoot, ENTRYPOINTS); + const publishedProgram = declarationProgram( + publishedRoot, + publishedEntrypoints, + ); + const baselineProgram = declarationProgram( + baselineRoot, + baselineEntrypoints, + ); + // Inspect runtime exports without executing the modules. + const runtimeProgram = ts.createProgram( + ENTRYPOINTS.map(({ runtimePath }) => + path.join(currentRoot, runtimePath), + ).filter((file) => fs.existsSync(file)), + { ...compilerOptions, allowJs: true }, + ); + for (const entrypoint of ENTRYPOINTS) { - const publishedRoot = path.join(tempDir, "package"); - const published = getEntrypointsFromPackageExports(publishedRoot).find( + const published = publishedEntrypoints.find( ({ name }) => name === entrypoint.name, ); if (!published) continue; // A new subpath has no previous contract to compare. @@ -2945,8 +2959,14 @@ describe("API Compatibility", () => { } // Extract exports from both versions - const publishedExports = extractExportsFromDts(publishedTypesPath); - const currentExports = extractExportsFromDts(currentTypesPath); + const publishedExports = extractExportsFromDts( + publishedProgram, + publishedTypesPath, + ); + const currentExports = extractExportsFromDts( + currentProgram, + currentTypesPath, + ); console.log( `${entrypoint.name}: Published exports: ${publishedExports.size}, Current exports: ${currentExports.size}`, @@ -2959,7 +2979,10 @@ describe("API Compatibility", () => { entrypoint.runtimePath, ); if (fs.existsSync(currentMjsPath)) { - const runtimeExports = await extractRuntimeExports(currentMjsPath); + const runtimeExports = extractRuntimeExports( + runtimeProgram, + currentMjsPath, + ); const runtimeErrors = verifyRuntimeMatchesTypes( currentExports, runtimeExports, @@ -2974,7 +2997,15 @@ describe("API Compatibility", () => { } // Try to get main branch exports for baseline comparison - const mainExports = await getMainBranchExports(entrypoint); + const baseline = baselineEntrypoints.find( + ({ name }) => name === entrypoint.name, + ); + const mainExports = baseline + ? extractExportsFromDts( + baselineProgram, + path.join(baselineRoot, baseline.typesPath), + ) + : null; if (mainExports) { // Three-way comparison: compare both current and main against published