-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(cloudflare,vercel-edge): Add support for OpenAI instrumentation #17338
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1f8ed69
feat(cloudflare,vercel-edge): Add support for OpenAI instrumentation
andreiborza bb8db23
Improve typing so we don't walk over openai's types when using the
andreiborza 34a64bd
Add changelog entry
andreiborza eda7807
Revert OpenAiClient type changes
andreiborza 888e107
Simplify openai mock for cloudflare
andreiborza 4ad3bed
Update sentry/core dep in integration tests
andreiborza 3f5fc64
Remove sentry/core import from devdeps
andreiborza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
34 changes: 34 additions & 0 deletions
34
dev-packages/cloudflare-integration-tests/suites/tracing/openai/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import * as Sentry from '@sentry/cloudflare'; | ||
import { MockOpenAi } from './mocks'; | ||
|
||
interface Env { | ||
SENTRY_DSN: string; | ||
} | ||
|
||
const mockClient = new MockOpenAi({ | ||
apiKey: 'mock-api-key', | ||
}); | ||
|
||
const client = Sentry.instrumentOpenAiClient(mockClient); | ||
|
||
export default Sentry.withSentry( | ||
(env: Env) => ({ | ||
dsn: env.SENTRY_DSN, | ||
tracesSampleRate: 1.0, | ||
}), | ||
{ | ||
async fetch(_request, _env, _ctx) { | ||
const response = await client.chat?.completions?.create({ | ||
model: 'gpt-3.5-turbo', | ||
messages: [ | ||
{ role: 'system', content: 'You are a helpful assistant.' }, | ||
{ role: 'user', content: 'What is the capital of France?' }, | ||
], | ||
temperature: 0.7, | ||
max_tokens: 100, | ||
}); | ||
|
||
return new Response(JSON.stringify(response)); | ||
}, | ||
}, | ||
); |
245 changes: 245 additions & 0 deletions
245
dev-packages/cloudflare-integration-tests/suites/tracing/openai/mocks.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,245 @@ | ||
import type { OpenAiClient } from '@sentry/core'; | ||
|
||
export class MockOpenAi implements OpenAiClient { | ||
public chat: Record<string, unknown>; | ||
public responses: { | ||
create: (...args: unknown[]) => Promise<unknown>; | ||
}; | ||
|
||
public apiKey: string; | ||
|
||
public constructor(config: { apiKey: string }) { | ||
this.apiKey = config.apiKey; | ||
|
||
this.chat = { | ||
completions: { | ||
create: async (...args: unknown[]) => { | ||
const params = args[0] as { model: string; stream?: boolean }; | ||
// Simulate processing time | ||
await new Promise(resolve => setTimeout(resolve, 10)); | ||
|
||
if (params.model === 'error-model') { | ||
const error = new Error('Model not found'); | ||
(error as unknown as { status: number }).status = 404; | ||
(error as unknown as { headers: Record<string, string> }).headers = { 'x-request-id': 'mock-request-123' }; | ||
throw error; | ||
} | ||
|
||
// If stream is requested, return an async generator | ||
if (params.stream) { | ||
return this.createChatCompletionStream(params); | ||
} | ||
|
||
return { | ||
id: 'chatcmpl-mock123', | ||
object: 'chat.completion', | ||
created: 1677652288, | ||
model: params.model, | ||
system_fingerprint: 'fp_44709d6fcb', | ||
choices: [ | ||
{ | ||
index: 0, | ||
message: { | ||
role: 'assistant', | ||
content: 'Hello from OpenAI mock!', | ||
}, | ||
finish_reason: 'stop', | ||
}, | ||
], | ||
usage: { | ||
prompt_tokens: 10, | ||
completion_tokens: 15, | ||
total_tokens: 25, | ||
}, | ||
}; | ||
}, | ||
}, | ||
}; | ||
|
||
this.responses = { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if you're only testing There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks, removed! |
||
create: async (...args: unknown[]) => { | ||
const params = args[0] as { model: string; input: string; instructions: string; stream?: boolean }; | ||
await new Promise(resolve => setTimeout(resolve, 10)); | ||
|
||
// If stream is requested, return an async generator | ||
if (params.stream) { | ||
return this.createResponsesApiStream(params); | ||
} | ||
|
||
return { | ||
id: 'resp_mock456', | ||
object: 'response', | ||
created_at: 1677652290, | ||
model: params.model, | ||
input_text: params.input, | ||
output_text: `Response to: ${params.input}`, | ||
status: 'completed', | ||
usage: { | ||
input_tokens: 5, | ||
output_tokens: 8, | ||
total_tokens: 13, | ||
}, | ||
}; | ||
}, | ||
}; | ||
} | ||
|
||
// Create a mock streaming response for chat completions | ||
public async *createChatCompletionStream(params: { model: string }): AsyncGenerator<unknown> { | ||
// First chunk with basic info | ||
yield { | ||
id: 'chatcmpl-stream-123', | ||
object: 'chat.completion.chunk', | ||
created: 1677652300, | ||
model: params.model, | ||
system_fingerprint: 'fp_stream_123', | ||
choices: [ | ||
{ | ||
index: 0, | ||
delta: { | ||
role: 'assistant', | ||
content: 'Hello', | ||
}, | ||
finish_reason: null, | ||
}, | ||
], | ||
}; | ||
|
||
// Second chunk with more content | ||
yield { | ||
id: 'chatcmpl-stream-123', | ||
object: 'chat.completion.chunk', | ||
created: 1677652300, | ||
model: params.model, | ||
system_fingerprint: 'fp_stream_123', | ||
choices: [ | ||
{ | ||
index: 0, | ||
delta: { | ||
content: ' from OpenAI streaming!', | ||
}, | ||
finish_reason: 'stop', | ||
}, | ||
], | ||
usage: { | ||
prompt_tokens: 12, | ||
completion_tokens: 18, | ||
total_tokens: 30, | ||
completion_tokens_details: { | ||
accepted_prediction_tokens: 0, | ||
audio_tokens: 0, | ||
reasoning_tokens: 0, | ||
rejected_prediction_tokens: 0, | ||
}, | ||
prompt_tokens_details: { | ||
audio_tokens: 0, | ||
cached_tokens: 0, | ||
}, | ||
}, | ||
}; | ||
} | ||
|
||
// Create a mock streaming response for responses API | ||
public async *createResponsesApiStream(params: { | ||
model: string; | ||
input: string; | ||
instructions: string; | ||
}): AsyncGenerator<unknown> { | ||
// Response created event | ||
yield { | ||
type: 'response.created', | ||
response: { | ||
id: 'resp_stream_456', | ||
object: 'response', | ||
created_at: 1677652310, | ||
model: params.model, | ||
status: 'in_progress', | ||
error: null, | ||
incomplete_details: null, | ||
instructions: params.instructions, | ||
max_output_tokens: 1000, | ||
parallel_tool_calls: false, | ||
previous_response_id: null, | ||
reasoning: { | ||
effort: null, | ||
summary: null, | ||
}, | ||
store: false, | ||
temperature: 0.7, | ||
text: { | ||
format: { | ||
type: 'text', | ||
}, | ||
}, | ||
tool_choice: 'auto', | ||
top_p: 1.0, | ||
truncation: 'disabled', | ||
user: null, | ||
metadata: {}, | ||
output: [], | ||
output_text: '', | ||
usage: { | ||
input_tokens: 0, | ||
output_tokens: 0, | ||
total_tokens: 0, | ||
}, | ||
}, | ||
sequence_number: 1, | ||
}; | ||
|
||
// Response in progress with output text delta | ||
yield { | ||
type: 'response.output_text.delta', | ||
delta: 'Streaming response to: ', | ||
sequence_number: 2, | ||
}; | ||
|
||
yield { | ||
type: 'response.output_text.delta', | ||
delta: params.input, | ||
sequence_number: 3, | ||
}; | ||
|
||
// Response completed event | ||
yield { | ||
type: 'response.completed', | ||
response: { | ||
id: 'resp_stream_456', | ||
object: 'response', | ||
created_at: 1677652310, | ||
model: params.model, | ||
status: 'completed', | ||
error: null, | ||
incomplete_details: null, | ||
instructions: params.instructions, | ||
max_output_tokens: 1000, | ||
parallel_tool_calls: false, | ||
previous_response_id: null, | ||
reasoning: { | ||
effort: null, | ||
summary: null, | ||
}, | ||
store: false, | ||
temperature: 0.7, | ||
text: { | ||
format: { | ||
type: 'text', | ||
}, | ||
}, | ||
tool_choice: 'auto', | ||
top_p: 1.0, | ||
truncation: 'disabled', | ||
user: null, | ||
metadata: {}, | ||
output: [], | ||
output_text: params.input, | ||
usage: { | ||
input_tokens: 6, | ||
output_tokens: 10, | ||
total_tokens: 16, | ||
}, | ||
}, | ||
sequence_number: 4, | ||
}; | ||
} | ||
} |
42 changes: 42 additions & 0 deletions
42
dev-packages/cloudflare-integration-tests/suites/tracing/openai/test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import { expect, it } from 'vitest'; | ||
import { createRunner } from '../../../runner'; | ||
|
||
// These tests are not exhaustive because the instrumentation is | ||
// already tested in the node integration tests and we merely | ||
// want to test that the instrumentation does not break in our | ||
// cloudflare SDK. | ||
|
||
it('traces a basic chat completion request', async () => { | ||
const runner = createRunner(__dirname) | ||
.ignore('event') | ||
.expect(envelope => { | ||
const transactionEvent = envelope[1]?.[0]?.[1]; | ||
|
||
expect(transactionEvent.transaction).toBe('GET /'); | ||
expect(transactionEvent.spans).toEqual( | ||
expect.arrayContaining([ | ||
expect.objectContaining({ | ||
data: expect.objectContaining({ | ||
'gen_ai.operation.name': 'chat', | ||
'sentry.op': 'gen_ai.chat', | ||
'gen_ai.system': 'openai', | ||
'gen_ai.request.model': 'gpt-3.5-turbo', | ||
'gen_ai.request.temperature': 0.7, | ||
'gen_ai.response.model': 'gpt-3.5-turbo', | ||
'gen_ai.response.id': 'chatcmpl-mock123', | ||
'gen_ai.usage.input_tokens': 10, | ||
'gen_ai.usage.output_tokens': 15, | ||
'gen_ai.usage.total_tokens': 25, | ||
'gen_ai.response.finish_reasons': '["stop"]', | ||
}), | ||
description: 'chat gpt-3.5-turbo', | ||
op: 'gen_ai.chat', | ||
origin: 'manual', | ||
}), | ||
]), | ||
); | ||
}) | ||
.start(); | ||
await runner.makeRequest('get', '/'); | ||
await runner.completed(); | ||
}); |
6 changes: 6 additions & 0 deletions
6
dev-packages/cloudflare-integration-tests/suites/tracing/openai/wrangler.jsonc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"name": "worker-name", | ||
"compatibility_date": "2025-06-17", | ||
"main": "index.ts", | ||
"compatibility_flags": ["nodejs_compat"] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.