-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(core): Improve error handling for Anthropic AI instrumentation #17535
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 all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
3c37017
feat(core): Improve error handling for Anthropic AI instrumentation
RulaKhaled 4f26ed0
remove unnecessary comments
RulaKhaled 19b599a
resolve some comments
RulaKhaled a6d6ceb
just pass error, no need to create new exception
RulaKhaled 54d9f97
Merge branch 'develop' into record-errors
RulaKhaled 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
115 changes: 115 additions & 0 deletions
dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-errors.mjs
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,115 @@ | ||
import { instrumentAnthropicAiClient } from '@sentry/core'; | ||
import * as Sentry from '@sentry/node'; | ||
|
||
class MockAnthropic { | ||
constructor(config) { | ||
this.apiKey = config.apiKey; | ||
this.messages = { | ||
create: this._messagesCreate.bind(this), | ||
}; | ||
this.models = { | ||
retrieve: this._modelsRetrieve.bind(this), | ||
}; | ||
} | ||
|
||
async _messagesCreate(params) { | ||
await new Promise(resolve => setTimeout(resolve, 5)); | ||
|
||
// Case 1: Invalid tool format error | ||
if (params.model === 'invalid-format') { | ||
const error = new Error('Invalid format'); | ||
error.status = 400; | ||
error.headers = { 'x-request-id': 'mock-invalid-tool-format-error' }; | ||
throw error; | ||
} | ||
|
||
// Default case (success) - return tool use for successful tool usage test | ||
return { | ||
id: 'msg_ok', | ||
type: 'message', | ||
model: params.model, | ||
role: 'assistant', | ||
content: [ | ||
{ | ||
type: 'tool_use', | ||
id: 'tool_ok_1', | ||
name: 'calculator', | ||
input: { expression: '2+2' }, | ||
}, | ||
], | ||
stop_reason: 'tool_use', | ||
usage: { input_tokens: 7, output_tokens: 9 }, | ||
}; | ||
} | ||
|
||
async _modelsRetrieve(modelId) { | ||
await new Promise(resolve => setTimeout(resolve, 5)); | ||
|
||
// Case for model retrieval error | ||
if (modelId === 'nonexistent-model') { | ||
const error = new Error('Model not found'); | ||
error.status = 404; | ||
error.headers = { 'x-request-id': 'mock-model-retrieval-error' }; | ||
throw error; | ||
} | ||
|
||
return { | ||
id: modelId, | ||
name: modelId, | ||
created_at: 1715145600, | ||
model: modelId, | ||
}; | ||
} | ||
} | ||
|
||
async function run() { | ||
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { | ||
const mockClient = new MockAnthropic({ apiKey: 'mock-api-key' }); | ||
const client = instrumentAnthropicAiClient(mockClient); | ||
|
||
// 1. Test invalid format error | ||
// https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/implement-tool-use#handling-tool-use-and-tool-result-content-blocks | ||
try { | ||
await client.messages.create({ | ||
model: 'invalid-format', | ||
messages: [ | ||
{ | ||
role: 'user', | ||
content: [ | ||
{ type: 'text', text: 'Here are the results:' }, // ❌ Text before tool_result | ||
{ type: 'tool_result', tool_use_id: 'toolu_01' }, | ||
], | ||
}, | ||
], | ||
}); | ||
} catch { | ||
// Error expected | ||
} | ||
|
||
// 2. Test model retrieval error | ||
try { | ||
await client.models.retrieve('nonexistent-model'); | ||
} catch { | ||
// Error expected | ||
} | ||
|
||
// 3. Test successful tool usage for comparison | ||
await client.messages.create({ | ||
model: 'claude-3-haiku-20240307', | ||
messages: [{ role: 'user', content: 'Calculate 2+2' }], | ||
tools: [ | ||
{ | ||
name: 'calculator', | ||
description: 'Perform calculations', | ||
input_schema: { | ||
type: 'object', | ||
properties: { expression: { type: 'string' } }, | ||
required: ['expression'], | ||
}, | ||
}, | ||
], | ||
}); | ||
}); | ||
} | ||
|
||
run(); |
166 changes: 166 additions & 0 deletions
dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-stream-errors.mjs
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,166 @@ | ||
import { instrumentAnthropicAiClient } from '@sentry/core'; | ||
import * as Sentry from '@sentry/node'; | ||
|
||
// Generator for default fallback | ||
function createMockDefaultFallbackStream() { | ||
async function* generator() { | ||
yield { | ||
type: 'content_block_start', | ||
index: 0, | ||
}; | ||
yield { | ||
type: 'content_block_delta', | ||
index: 0, | ||
delta: { text: 'This stream will work fine.' }, | ||
}; | ||
yield { | ||
type: 'content_block_stop', | ||
index: 0, | ||
}; | ||
} | ||
return generator(); | ||
} | ||
|
||
// Generator that errors midway through streaming | ||
function createMockMidwayErrorStream() { | ||
async function* generator() { | ||
// First yield some initial data to start the stream | ||
yield { | ||
type: 'content_block_start', | ||
message: { | ||
id: 'msg_error_stream_1', | ||
type: 'message', | ||
role: 'assistant', | ||
model: 'claude-3-haiku-20240307', | ||
content: [], | ||
usage: { input_tokens: 5 }, | ||
}, | ||
}; | ||
|
||
// Yield one chunk of content | ||
yield { type: 'content_block_delta', delta: { text: 'This stream will ' } }; | ||
|
||
// Then throw an error | ||
await new Promise(resolve => setTimeout(resolve, 5)); | ||
throw new Error('Stream interrupted'); | ||
} | ||
|
||
return generator(); | ||
} | ||
|
||
class MockAnthropic { | ||
constructor(config) { | ||
this.apiKey = config.apiKey; | ||
|
||
this.messages = { | ||
create: this._messagesCreate.bind(this), | ||
stream: this._messagesStream.bind(this), | ||
}; | ||
} | ||
|
||
// client.messages.create with stream: true | ||
async _messagesCreate(params) { | ||
await new Promise(resolve => setTimeout(resolve, 5)); | ||
|
||
// Error on initialization for 'error-stream-init' model | ||
if (params.model === 'error-stream-init') { | ||
if (params?.stream === true) { | ||
throw new Error('Failed to initialize stream'); | ||
} | ||
} | ||
|
||
// Error midway for 'error-stream-midway' model | ||
if (params.model === 'error-stream-midway') { | ||
if (params?.stream === true) { | ||
return createMockMidwayErrorStream(); | ||
} | ||
} | ||
|
||
// Default fallback | ||
return { | ||
id: 'msg_mock123', | ||
type: 'message', | ||
model: params.model, | ||
role: 'assistant', | ||
content: [{ type: 'text', text: 'Non-stream response' }], | ||
usage: { input_tokens: 5, output_tokens: 7 }, | ||
}; | ||
} | ||
|
||
// client.messages.stream | ||
async _messagesStream(params) { | ||
await new Promise(resolve => setTimeout(resolve, 5)); | ||
|
||
// Error on initialization for 'error-stream-init' model | ||
if (params.model === 'error-stream-init') { | ||
throw new Error('Failed to initialize stream'); | ||
} | ||
|
||
// Error midway for 'error-stream-midway' model | ||
if (params.model === 'error-stream-midway') { | ||
return createMockMidwayErrorStream(); | ||
} | ||
|
||
// Default fallback | ||
return createMockDefaultFallbackStream(); | ||
} | ||
} | ||
|
||
async function run() { | ||
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { | ||
const mockClient = new MockAnthropic({ apiKey: 'mock-api-key' }); | ||
const client = instrumentAnthropicAiClient(mockClient); | ||
|
||
// 1) Error on stream initialization with messages.create | ||
try { | ||
await client.messages.create({ | ||
model: 'error-stream-init', | ||
messages: [{ role: 'user', content: 'This will fail immediately' }], | ||
stream: true, | ||
}); | ||
} catch { | ||
// Error expected | ||
} | ||
|
||
// 2) Error on stream initialization with messages.stream | ||
try { | ||
await client.messages.stream({ | ||
model: 'error-stream-init', | ||
messages: [{ role: 'user', content: 'This will also fail immediately' }], | ||
}); | ||
} catch { | ||
// Error expected | ||
} | ||
|
||
// 3) Error midway through streaming with messages.create | ||
try { | ||
const stream = await client.messages.create({ | ||
model: 'error-stream-midway', | ||
messages: [{ role: 'user', content: 'This will fail midway' }], | ||
stream: true, | ||
}); | ||
|
||
for await (const _ of stream) { | ||
void _; | ||
} | ||
} catch { | ||
// Error expected | ||
} | ||
|
||
// 4) Error midway through streaming with messages.stream | ||
try { | ||
const stream = await client.messages.stream({ | ||
model: 'error-stream-midway', | ||
messages: [{ role: 'user', content: 'This will also fail midway' }], | ||
}); | ||
|
||
for await (const _ of stream) { | ||
void _; | ||
} | ||
} catch { | ||
// Error expected | ||
} | ||
}); | ||
} | ||
|
||
run(); |
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.