Skip to content

Commit d8e7ec0

Browse files
committed
feat(deno): add openai integration
1 parent f2cf581 commit d8e7ec0

4 files changed

Lines changed: 112 additions & 0 deletions

File tree

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// <reference lib="deno.ns" />
2+
3+
import { tracingChannel } from 'node:diagnostics_channel';
4+
import type { TransactionEvent } from '@sentry/core';
5+
import type { DenoClient } from '@sentry/deno';
6+
import { getCurrentScope, getGlobalScope, getIsolationScope, init, startSpan } from '@sentry/deno';
7+
import { assert } from 'https://deno.land/std@0.212.0/assert/assert.ts';
8+
import { assertExists } from 'https://deno.land/std@0.212.0/assert/assert_exists.ts';
9+
import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts';
10+
11+
function resetGlobals(): void {
12+
getCurrentScope().clear();
13+
getCurrentScope().setClient(undefined);
14+
getIsolationScope().clear();
15+
getGlobalScope().clear();
16+
}
17+
18+
/** See deno-redis.test.ts — same sink shape, deduped for clarity. */
19+
function transactionSink(): {
20+
beforeSendTransaction: (event: TransactionEvent) => null;
21+
waitFor: (predicate: (event: TransactionEvent) => boolean) => Promise<TransactionEvent>;
22+
} {
23+
const transactions: TransactionEvent[] = [];
24+
const waiters: { predicate: (e: TransactionEvent) => boolean; resolve: (e: TransactionEvent) => void }[] = [];
25+
return {
26+
beforeSendTransaction(event) {
27+
transactions.push(event);
28+
for (let i = waiters.length - 1; i >= 0; i--) {
29+
const w = waiters[i]!;
30+
if (w.predicate(event)) {
31+
waiters.splice(i, 1);
32+
w.resolve(event);
33+
}
34+
}
35+
return null;
36+
},
37+
waitFor(predicate) {
38+
const already = transactions.find(predicate);
39+
if (already) return Promise.resolve(already);
40+
return new Promise<TransactionEvent>(resolve => {
41+
waiters.push({ predicate, resolve });
42+
});
43+
},
44+
};
45+
}
46+
47+
function withTimeout<T>(p: Promise<T>, ms: number, what: string): Promise<T> {
48+
let timer: ReturnType<typeof setTimeout> | undefined;
49+
const timeout = new Promise<T>((_, reject) => {
50+
timer = setTimeout(() => reject(new Error(`Timed out waiting for ${what} after ${ms}ms`)), ms);
51+
});
52+
return Promise.race([p, timeout]).finally(() => {
53+
if (timer !== undefined) clearTimeout(timer);
54+
});
55+
}
56+
57+
Deno.test('openai instrumentation: included in default integrations (Deno 2.8.0+)', () => {
58+
resetGlobals();
59+
const client = init({ dsn: 'https://username@domain/123' }) as DenoClient;
60+
const names = client.getOptions().integrations.map(i => i.name);
61+
assert(names.includes('OpenAI'), `OpenAI should be in defaults, got ${names.join(', ')}`);
62+
});
63+
64+
Deno.test('openai instrumentation: orchestrion:openai:chat channel produces a nested gen_ai span', async () => {
65+
resetGlobals();
66+
const sink = transactionSink();
67+
init({
68+
dsn: 'https://username@domain/123',
69+
tracesSampleRate: 1,
70+
beforeSendTransaction: sink.beforeSendTransaction,
71+
});
72+
73+
const channel = tracingChannel('orchestrion:openai:chat');
74+
75+
// `arguments[0]` is the request body passed to `create(body, options)`.
76+
const body = { model: 'gpt-4o', messages: [{ role: 'user', content: 'hi' }] };
77+
const ctx: Record<string, unknown> = { arguments: [body] };
78+
79+
startSpan({ name: 'parent', op: 'test' }, () => {
80+
channel.start.runStores(ctx, () => undefined);
81+
channel.end.publish(ctx);
82+
ctx.result = {
83+
id: 'chatcmpl-1',
84+
model: 'gpt-4o-2024-08-06',
85+
usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
86+
};
87+
channel.asyncEnd.publish(ctx);
88+
});
89+
90+
const parent = await withTimeout(
91+
sink.waitFor(t => t.transaction === 'parent'),
92+
5000,
93+
"'parent' transaction",
94+
);
95+
96+
const aiSpan = parent.spans?.find(s => s.op === 'gen_ai.chat');
97+
assertExists(aiSpan, `expected a gen_ai.chat child span, got ops: ${parent.spans?.map(s => s.op).join(', ')}`);
98+
assertEquals(aiSpan!.description, 'chat gpt-4o');
99+
assertEquals(aiSpan!.data?.['gen_ai.system'], 'openai');
100+
assertEquals(aiSpan!.data?.['gen_ai.operation.name'], 'chat');
101+
assertEquals(aiSpan!.data?.['gen_ai.request.model'], 'gpt-4o');
102+
assertEquals(aiSpan!.data?.['gen_ai.response.model'], 'gpt-4o-2024-08-06');
103+
assertEquals(aiSpan!.data?.['gen_ai.usage.total_tokens'], 15);
104+
assertEquals(aiSpan!.data?.['sentry.origin'], 'auto.ai.orchestrion.openai');
105+
});

packages/deno/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ export {
132132
mongooseChannelIntegration,
133133
mysqlChannelIntegration,
134134
mysql2ChannelIntegration,
135+
openaiChannelIntegration,
135136
postgresChannelIntegration,
136137
postgresJsChannelIntegration,
137138
tediousChannelIntegration,

packages/deno/src/sdk.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
mongooseChannelIntegration,
2727
mysqlChannelIntegration,
2828
mysql2ChannelIntegration,
29+
openaiChannelIntegration,
2930
postgresChannelIntegration,
3031
postgresJsChannelIntegration,
3132
tediousChannelIntegration,
@@ -100,6 +101,7 @@ export function getDefaultIntegrations(_options: Options): Integration[] {
100101
mongooseChannelIntegration(),
101102
mysqlChannelIntegration(),
102103
mysql2ChannelIntegration(),
104+
openaiChannelIntegration(),
103105
postgresChannelIntegration(),
104106
postgresJsChannelIntegration(),
105107
tediousChannelIntegration(),

packages/deno/test/__snapshots__/mod.test.ts.snap

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ snapshot[`captureException 1`] = `
129129
"Mongoose",
130130
"Mysql",
131131
"Mysql2",
132+
"OpenAI",
132133
"Postgres",
133134
"PostgresJs",
134135
"Tedious",
@@ -221,6 +222,7 @@ snapshot[`captureMessage 1`] = `
221222
"Mongoose",
222223
"Mysql",
223224
"Mysql2",
225+
"OpenAI",
224226
"Postgres",
225227
"PostgresJs",
226228
"Tedious",
@@ -320,6 +322,7 @@ snapshot[`captureMessage twice 1`] = `
320322
"Mongoose",
321323
"Mysql",
322324
"Mysql2",
325+
"OpenAI",
323326
"Postgres",
324327
"PostgresJs",
325328
"Tedious",
@@ -426,6 +429,7 @@ snapshot[`captureMessage twice 2`] = `
426429
"Mongoose",
427430
"Mysql",
428431
"Mysql2",
432+
"OpenAI",
429433
"Postgres",
430434
"PostgresJs",
431435
"Tedious",

0 commit comments

Comments
 (0)