Skip to content
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@

Adds instrumentation for the Google GenAI [`embedContent`](https://ai.google.dev/gemini-api/docs/embeddings) API, creating `gen_ai.embeddings` spans.

- feat(langchain): Support embeddings APIs in LangChain ([#20017](https://github.com/getsentry/sentry-javascript/pull/20017))

Adds instrumentation for LangChain embeddings (`embedQuery`, `embedDocuments`), creating `gen_ai.embeddings` spans. In Node.js, embedding classes from `@langchain/openai`, `@langchain/google-genai`, `@langchain/mistralai`, and `@langchain/google-vertexai` are auto-instrumented. For other runtimes, use the new `instrumentLangChainEmbeddings` API:

```javascript
import * as Sentry from '@sentry/cloudflare';
import { OpenAIEmbeddings } from '@langchain/openai';

const embeddings = Sentry.instrumentLangChainEmbeddings(
new OpenAIEmbeddings({ model: 'text-embedding-3-small' }),
);

await embeddings.embedQuery('Hello world');
```

## 10.46.0

### Important Changes
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
// Mock LangChain Embeddings for browser testing
export class MockOpenAIEmbeddings {
constructor(params) {
this.model = params.model;
this.dimensions = params.dimensions;
}

async embedQuery(_text) {
await new Promise(resolve => setTimeout(resolve, 10));
return [0.1, 0.2, 0.3];
}

async embedDocuments(documents) {
await new Promise(resolve => setTimeout(resolve, 10));
return documents.map(() => [0.1, 0.2, 0.3]);
}
}

// Mock LangChain Chat Model for browser testing
export class MockChatAnthropic {
constructor(params) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createLangChainCallbackHandler } from '@sentry/browser';
import { MockChatAnthropic } from './mocks.js';
import { createLangChainCallbackHandler, instrumentLangChainEmbeddings } from '@sentry/browser';
import { MockChatAnthropic, MockOpenAIEmbeddings } from './mocks.js';

const callbackHandler = createLangChainCallbackHandler({
recordInputs: false,
Expand All @@ -20,3 +20,11 @@ const response = await chatModel.invoke('What is the capital of France?', {
});

console.log('Received response', response);

// Test embeddings instrumentation
const embeddings = instrumentLangChainEmbeddings(
new MockOpenAIEmbeddings({ model: 'text-embedding-3-small', dimensions: 1536 }),
);

const embedding = await embeddings.embedQuery('Hello world');
console.log('Received embedding', embedding);
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,29 @@ sentryTest('manual LangChain instrumentation sends gen_ai transactions', async (
'gen_ai.usage.total_tokens': 25,
});
});

sentryTest(
'manual LangChain embeddings instrumentation sends gen_ai transactions',
async ({ getLocalTestUrl, page }) => {
const transactionPromise = waitForTransactionRequest(page, event => {
return !!event.transaction?.includes('text-embedding-3-small');
});

const url = await getLocalTestUrl({ testDir: __dirname });
await page.goto(url);

const req = await transactionPromise;

const eventData = envelopeRequestParser(req);

expect(eventData.transaction).toBe('embeddings text-embedding-3-small');
expect(eventData.contexts?.trace?.op).toBe('gen_ai.embeddings');
expect(eventData.contexts?.trace?.origin).toBe('auto.ai.langchain');
expect(eventData.contexts?.trace?.data).toMatchObject({
'gen_ai.operation.name': 'embeddings',
'gen_ai.system': 'openai',
'gen_ai.request.model': 'text-embedding-3-small',
'gen_ai.request.dimensions': 1536,
});
},
);
1 change: 1 addition & 0 deletions dev-packages/node-integration-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@hono/node-server": "^1.19.10",
"@langchain/anthropic": "^0.3.10",
"@langchain/core": "^0.3.80",
"@langchain/openai": "^0.5.0",
"@langchain/langgraph": "^0.2.32",
"@nestjs/common": "^11",
"@nestjs/core": "^11",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Sentry.init({
transport: loggingTransport,
beforeSendTransaction: event => {
// Filter out mock express server transactions
if (event.transaction.includes('/v1/messages')) {
if (event.transaction.includes('/v1/messages') || event.transaction.includes('/v1/embeddings')) {
return null;
}
return event;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Sentry.init({
transport: loggingTransport,
beforeSendTransaction: event => {
// Filter out mock express server transactions
if (event.transaction.includes('/v1/messages')) {
if (event.transaction.includes('/v1/messages') || event.transaction.includes('/v1/embeddings')) {
return null;
}
return event;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { OpenAIEmbeddings } from '@langchain/openai';
import * as Sentry from '@sentry/node';
import express from 'express';

function startMockOpenAIServer() {
const app = express();
app.use(express.json());

app.post('/v1/embeddings', (req, res) => {
const { model, input } = req.body;

if (model === 'error-model') {
res.status(400).json({
error: {
message: 'Model not found',
type: 'invalid_request_error',
},
});
return;
}

const inputs = Array.isArray(input) ? input : [input];
res.json({
object: 'list',
data: inputs.map((_, i) => ({
object: 'embedding',
embedding: [0.1, 0.2, 0.3],
index: i,
})),
model: model,
usage: {
prompt_tokens: 10,
total_tokens: 10,
},
});
});

return new Promise(resolve => {
const server = app.listen(0, () => {
resolve(server);
});
});
}

async function run() {
const server = await startMockOpenAIServer();
const baseUrl = `http://localhost:${server.address().port}/v1`;

await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
// Test 1: embedQuery
const embeddings = new OpenAIEmbeddings({
model: 'text-embedding-3-small',
dimensions: 1536,
apiKey: 'mock-api-key',
configuration: { baseURL: baseUrl },
});

await embeddings.embedQuery('Hello world');

// Test 2: embedDocuments
await embeddings.embedDocuments(['First document', 'Second document']);

// Test 3: Error handling
const errorEmbeddings = new OpenAIEmbeddings({
model: 'error-model',
apiKey: 'mock-api-key',
configuration: { baseURL: baseUrl },
});

try {
await errorEmbeddings.embedQuery('This will fail');
} catch {
// Expected error
}
});

await Sentry.flush(2000);

server.close();
}

run();
119 changes: 119 additions & 0 deletions dev-packages/node-integration-tests/suites/tracing/langchain/test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
import { afterAll, describe, expect } from 'vitest';
import {
GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE,
GEN_AI_INPUT_MESSAGES_ATTRIBUTE,
GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,
GEN_AI_OPERATION_NAME_ATTRIBUTE,
GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,
GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,
GEN_AI_REQUEST_MODEL_ATTRIBUTE,
GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,
Expand Down Expand Up @@ -430,4 +433,120 @@ describe('LangChain integration', () => {
.completed();
});
});

// =========================================================================
// Embeddings tests
// =========================================================================

const EXPECTED_TRANSACTION_EMBEDDINGS = {
transaction: 'main',
spans: expect.arrayContaining([
// embedQuery span
expect.objectContaining({
data: expect.objectContaining({
[GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain',
[GEN_AI_SYSTEM_ATTRIBUTE]: 'openai',
[GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'text-embedding-3-small',
[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE]: 1536,
}),
description: 'embeddings text-embedding-3-small',
op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
origin: 'auto.ai.langchain',
status: 'ok',
}),
// embedDocuments span
expect.objectContaining({
data: expect.objectContaining({
[GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain',
[GEN_AI_SYSTEM_ATTRIBUTE]: 'openai',
[GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'text-embedding-3-small',
}),
description: 'embeddings text-embedding-3-small',
op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
origin: 'auto.ai.langchain',
status: 'ok',
}),
// Error span
expect.objectContaining({
data: expect.objectContaining({
[GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain',
[GEN_AI_SYSTEM_ATTRIBUTE]: 'openai',
[GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'error-model',
}),
description: 'embeddings error-model',
op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
origin: 'auto.ai.langchain',
status: 'internal_error',
}),
]),
};

const EXPECTED_TRANSACTION_EMBEDDINGS_PII = {
transaction: 'main',
spans: expect.arrayContaining([
// embedQuery span with input recorded
expect.objectContaining({
data: expect.objectContaining({
[GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain',
[GEN_AI_SYSTEM_ATTRIBUTE]: 'openai',
[GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'text-embedding-3-small',
[GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE]: 'Hello world',
}),
description: 'embeddings text-embedding-3-small',
op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
origin: 'auto.ai.langchain',
status: 'ok',
}),
// embedDocuments span with input recorded
expect.objectContaining({
data: expect.objectContaining({
[GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings',
[GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE]: JSON.stringify(['First document', 'Second document']),
}),
description: 'embeddings text-embedding-3-small',
op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE,
origin: 'auto.ai.langchain',
status: 'ok',
}),
]),
};

createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument.mjs', (createRunner, test) => {
test('creates embedding spans with sendDefaultPii: false', async () => {
await createRunner().ignore('event').expect({ transaction: EXPECTED_TRANSACTION_EMBEDDINGS }).start().completed();
});

test('does not create duplicate embedding spans from double module patching', async () => {
await createRunner()
.ignore('event')
.expect({
transaction: event => {
const spans = event.spans || [];
const embeddingSpans = spans.filter(span => span.op === GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE);
// The scenario makes 3 embedding calls (2 successful + 1 error).
expect(embeddingSpans).toHaveLength(3);
},
})
.start()
.completed();
});
});

createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
test('creates embedding spans with sendDefaultPii: true', async () => {
await createRunner()
.ignore('event')
.expect({ transaction: EXPECTED_TRANSACTION_EMBEDDINGS_PII })
.start()
.completed();
});
});
});
1 change: 1 addition & 0 deletions packages/aws-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export {
getSentryRelease,
createGetModuleFromFilename,
createLangChainCallbackHandler,
instrumentLangChainEmbeddings,
httpHeadersToSpanAttributes,
winterCGHeadersToDict,
// eslint-disable-next-line deprecation/deprecation
Expand Down
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export {
instrumentGoogleGenAIClient,
instrumentLangGraph,
createLangChainCallbackHandler,
instrumentLangChainEmbeddings,
logger,
} from '@sentry/core';
export type { Span, FeatureFlagsIntegration } from '@sentry/core';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { instrumentLangChainEmbeddings } from '@sentry/core';
1 change: 1 addition & 0 deletions packages/bun/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export {
getSentryRelease,
createGetModuleFromFilename,
createLangChainCallbackHandler,
instrumentLangChainEmbeddings,
httpHeadersToSpanAttributes,
winterCGHeadersToDict,
// eslint-disable-next-line deprecation/deprecation
Expand Down
1 change: 1 addition & 0 deletions packages/cloudflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export {
consoleLoggingIntegration,
createConsolaReporter,
createLangChainCallbackHandler,
instrumentLangChainEmbeddings,
featureFlagsIntegration,
growthbookIntegration,
logger,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export { ANTHROPIC_AI_INTEGRATION_NAME } from './tracing/anthropic-ai/constants'
export { instrumentGoogleGenAIClient } from './tracing/google-genai';
export { GOOGLE_GENAI_INTEGRATION_NAME } from './tracing/google-genai/constants';
export type { GoogleGenAIResponse } from './tracing/google-genai/types';
export { createLangChainCallbackHandler } from './tracing/langchain';
export { createLangChainCallbackHandler, instrumentLangChainEmbeddings } from './tracing/langchain';
export { LANGCHAIN_INTEGRATION_NAME } from './tracing/langchain/constants';
export type { LangChainOptions, LangChainIntegration } from './tracing/langchain/types';
export { instrumentStateGraphCompile, instrumentLangGraph } from './tracing/langgraph';
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/tracing/ai/gen-ai-attributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,11 @@ export const GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE = 'gen_ai.stream
*/
export const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';

/**
* The span operation for embeddings
*/
export const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate constant with identical value adds confusion

Low Severity

GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE is a new constant with value 'gen_ai.embeddings', identical to the existing GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE and GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE. Having three exported constants with the same string value increases maintenance burden — a future change to the operation name would need to update all three, risking inconsistency.

Additional Locations (1)
Fix in Cursor Fix in Web

Copy link
Copy Markdown
Member Author

@nicohrubec nicohrubec Mar 31, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am aware, the others will be cleaned up in a follow up to keep this focused


/**
* The span operation name for embedding
*/
Expand Down
Loading
Loading