Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
44 changes: 18 additions & 26 deletions packages/core/src/utils/openai/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getCurrentScope } from '../../currentScopes';
import { getClient } from '../../currentScopes';
import { captureException } from '../../exports';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';
import { SPAN_STATUS_ERROR } from '../../tracing';
Expand All @@ -19,13 +19,11 @@ import {
GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,
GEN_AI_SYSTEM_ATTRIBUTE,
} from '../ai/gen-ai-attributes';
import { OPENAI_INTEGRATION_NAME } from './constants';
import { instrumentStream } from './streaming';
import type {
ChatCompletionChunk,
InstrumentedMethod,
OpenAiChatCompletionObject,
OpenAiIntegration,
OpenAiOptions,
OpenAiResponse,
OpenAIResponseObject,
Expand Down Expand Up @@ -198,18 +196,6 @@ function addRequestAttributes(span: Span, params: Record<string, unknown>): void
}
}

function getOptionsFromIntegration(): OpenAiOptions {
const scope = getCurrentScope();
const client = scope.getClient();
const integration = client?.getIntegrationByName(OPENAI_INTEGRATION_NAME) as OpenAiIntegration | undefined;
const shouldRecordInputsAndOutputs = integration ? Boolean(client?.getOptions().sendDefaultPii) : false;

return {
recordInputs: integration?.options?.recordInputs ?? shouldRecordInputsAndOutputs,
recordOutputs: integration?.options?.recordOutputs ?? shouldRecordInputsAndOutputs,
};
}

/**
* Instrument a method with Sentry spans
* Following Sentry AI Agents Manual Instrumentation conventions
Expand All @@ -219,10 +205,9 @@ function instrumentMethod<T extends unknown[], R>(
originalMethod: (...args: T) => Promise<R>,
methodPath: InstrumentedMethod,
context: unknown,
options?: OpenAiOptions,
options: OpenAiOptions,
): (...args: T) => Promise<R> {
return async function instrumentedMethod(...args: T): Promise<R> {
const finalOptions = options || getOptionsFromIntegration();
const requestAttributes = extractRequestAttributes(args, methodPath);
const model = (requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] as string) || 'unknown';
const operationName = getOperationName(methodPath);
Expand All @@ -240,16 +225,16 @@ function instrumentMethod<T extends unknown[], R>(
},
async (span: Span) => {
try {
if (finalOptions.recordInputs && args[0] && typeof args[0] === 'object') {
addRequestAttributes(span, args[0] as Record<string, unknown>);
if (options.recordInputs && params) {
addRequestAttributes(span, params);
}

const result = await originalMethod.apply(context, args);

return instrumentStream(
result as OpenAIStream<ChatCompletionChunk | ResponseStreamingEvent>,
span,
finalOptions.recordOutputs ?? false,
options.recordOutputs ?? false,
) as unknown as R;
} catch (error) {
// For streaming requests that fail before stream creation, we still want to record
Expand Down Expand Up @@ -279,12 +264,12 @@ function instrumentMethod<T extends unknown[], R>(
},
async (span: Span) => {
try {
if (finalOptions.recordInputs && args[0] && typeof args[0] === 'object') {
addRequestAttributes(span, args[0] as Record<string, unknown>);
if (options.recordInputs && params) {
addRequestAttributes(span, params);
}

const result = await originalMethod.apply(context, args);
addResponseAttributes(span, result, finalOptions.recordOutputs);
addResponseAttributes(span, result, options.recordOutputs);
return result;
} catch (error) {
captureException(error, {
Expand All @@ -307,7 +292,7 @@ function instrumentMethod<T extends unknown[], R>(
/**
* Create a deep proxy for OpenAI client instrumentation
*/
function createDeepProxy<T extends object>(target: T, currentPath = '', options?: OpenAiOptions): T {
function createDeepProxy<T extends object>(target: T, currentPath = '', options: OpenAiOptions): T {
return new Proxy(target, {
get(obj: object, prop: string): unknown {
const value = (obj as Record<string, unknown>)[prop];
Expand Down Expand Up @@ -336,6 +321,13 @@ function createDeepProxy<T extends object>(target: T, currentPath = '', options?
* Instrument an OpenAI client with Sentry tracing
* Can be used across Node.js, Cloudflare Workers, and Vercel Edge
*/
export function instrumentOpenAiClient<T extends object>(client: T, options?: OpenAiOptions): T {
return createDeepProxy(client, '', options);
export function instrumentOpenAiClient<T extends object>(openAiClient: T, options?: OpenAiOptions): T {
const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii);

const _options = {
recordInputs: sendDefaultPii,
recordOutputs: sendDefaultPii,
...options,
};
return createDeepProxy(openAiClient, '', _options);
}
6 changes: 3 additions & 3 deletions packages/node/src/integrations/tracing/openai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ import { defineIntegration, OPENAI_INTEGRATION_NAME } from '@sentry/core';
import { generateInstrumentOnce } from '@sentry/node-core';
import { SentryOpenAiInstrumentation } from './instrumentation';

export const instrumentOpenAi = generateInstrumentOnce(
export const instrumentOpenAi = generateInstrumentOnce<OpenAiOptions>(
OPENAI_INTEGRATION_NAME,
() => new SentryOpenAiInstrumentation({}),
options => new SentryOpenAiInstrumentation(options),
);

const _openAiIntegration = ((options: OpenAiOptions = {}) => {
return {
name: OPENAI_INTEGRATION_NAME,
options,
setupOnce() {
instrumentOpenAi();
instrumentOpenAi(options);
},
};
}) satisfies IntegrationFn;
Expand Down
30 changes: 8 additions & 22 deletions packages/node/src/integrations/tracing/openai/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import {
InstrumentationBase,
InstrumentationNodeModuleDefinition,
} from '@opentelemetry/instrumentation';
import type { Integration, OpenAiClient, OpenAiOptions } from '@sentry/core';
import { getClient, instrumentOpenAiClient, OPENAI_INTEGRATION_NAME, SDK_VERSION } from '@sentry/core';
import type { OpenAiClient, OpenAiOptions } from '@sentry/core';
import { getClient, instrumentOpenAiClient, SDK_VERSION } from '@sentry/core';

const supportedVersions = ['>=4.0.0 <6'];

export interface OpenAiIntegration extends Integration {
options: OpenAiOptions;
}
type OpenAiInstrumentationOptions = InstrumentationConfig & OpenAiOptions;

/**
* Represents the patched shape of the OpenAI module export.
Expand All @@ -21,23 +19,11 @@ interface PatchedModuleExports {
OpenAI: abstract new (...args: unknown[]) => OpenAiClient;
}

/**
* Determines telemetry recording settings.
*/
function determineRecordingSettings(
integrationOptions: OpenAiOptions | undefined,
defaultEnabled: boolean,
): { recordInputs: boolean; recordOutputs: boolean } {
const recordInputs = integrationOptions?.recordInputs ?? defaultEnabled;
const recordOutputs = integrationOptions?.recordOutputs ?? defaultEnabled;
return { recordInputs, recordOutputs };
}

/**
* Sentry OpenAI instrumentation using OpenTelemetry.
*/
export class SentryOpenAiInstrumentation extends InstrumentationBase<InstrumentationConfig> {
public constructor(config: InstrumentationConfig = {}) {
export class SentryOpenAiInstrumentation extends InstrumentationBase<OpenAiInstrumentationOptions> {
public constructor(config: OpenAiInstrumentationOptions = {}) {
super('@sentry/instrumentation-openai', SDK_VERSION, config);
}

Expand All @@ -54,15 +40,15 @@ export class SentryOpenAiInstrumentation extends InstrumentationBase<Instrumenta
*/
private _patch(exports: PatchedModuleExports): PatchedModuleExports | void {
const Original = exports.OpenAI;
const config = this.getConfig();

const WrappedOpenAI = function (this: unknown, ...args: unknown[]) {
const instance = Reflect.construct(Original, args);
const client = getClient();
const integration = client?.getIntegrationByName<OpenAiIntegration>(OPENAI_INTEGRATION_NAME);
const integrationOpts = integration?.options;
const defaultPii = Boolean(client?.getOptions().sendDefaultPii);

const { recordInputs, recordOutputs } = determineRecordingSettings(integrationOpts, defaultPii);
const recordInputs = config.recordInputs ?? defaultPii;
const recordOutputs = config.recordOutputs ?? defaultPii;

return instrumentOpenAiClient(instance as OpenAiClient, {
recordInputs,
Expand Down
Loading