-
Notifications
You must be signed in to change notification settings - Fork 588
feat: add Bedrock InvokeModelWithResponseStream instrumentation #2845
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
base: main
Are you sure you want to change the base?
Changes from all commits
0d197f0
fcf3ff5
ff1cb2d
00508e8
0e2fef3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -101,7 +101,9 @@ | |||||
case 'ConverseStream': | ||||||
return this.requestPreSpanHookConverse(request, config, diag, true); | ||||||
case 'InvokeModel': | ||||||
return this.requestPreSpanHookInvokeModel(request, config, diag); | ||||||
return this.requestPreSpanHookInvokeModel(request, config, diag, false); | ||||||
case 'InvokeModelWithResponseStream': | ||||||
return this.requestPreSpanHookInvokeModel(request, config, diag, true); | ||||||
} | ||||||
|
||||||
return { | ||||||
|
@@ -157,7 +159,8 @@ | |||||
private requestPreSpanHookInvokeModel( | ||||||
request: NormalizedRequest, | ||||||
config: AwsSdkInstrumentationConfig, | ||||||
diag: DiagLogger | ||||||
diag: DiagLogger, | ||||||
isStream: boolean | ||||||
): RequestMetadata { | ||||||
let spanName: string | undefined; | ||||||
const spanAttributes: Attributes = { | ||||||
|
@@ -312,6 +315,7 @@ | |||||
return { | ||||||
spanName, | ||||||
isIncoming: false, | ||||||
isStream, | ||||||
spanAttributes, | ||||||
}; | ||||||
} | ||||||
|
@@ -346,6 +350,13 @@ | |||||
); | ||||||
case 'InvokeModel': | ||||||
return this.responseHookInvokeModel(response, span, tracer, config); | ||||||
case 'InvokeModelWithResponseStream': | ||||||
return this.responseHookInvokeModelWithResponseStream( | ||||||
response, | ||||||
span, | ||||||
tracer, | ||||||
config | ||||||
); | ||||||
} | ||||||
} | ||||||
|
||||||
|
@@ -579,4 +590,145 @@ | |||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
private async responseHookInvokeModelWithResponseStream( | ||||||
response: NormalizedResponse, | ||||||
span: Span, | ||||||
tracer: Tracer, | ||||||
config: AwsSdkInstrumentationConfig | ||||||
): Promise<any> { | ||||||
const stream = response.data?.body; | ||||||
const modelId = response.request.commandInput?.modelId; | ||||||
if (!stream) return; | ||||||
|
||||||
const wrappedStream = | ||||||
BedrockRuntimeServiceExtension.instrumentAsyncIterable( | ||||||
stream, | ||||||
async (chunk: { chunk?: { bytes?: Uint8Array } }) => { | ||||||
const parsedChunk = BedrockRuntimeServiceExtension.parseChunk( | ||||||
chunk?.chunk?.bytes | ||||||
); | ||||||
|
||||||
if (!parsedChunk) return; | ||||||
|
||||||
if (modelId.includes('amazon.titan')) { | ||||||
BedrockRuntimeServiceExtension.recordTitanAttributes( | ||||||
parsedChunk, | ||||||
span | ||||||
); | ||||||
} else if (modelId.includes('anthropic.claude')) { | ||||||
BedrockRuntimeServiceExtension.recordClaudeAttributes( | ||||||
parsedChunk, | ||||||
span | ||||||
); | ||||||
} else if (modelId.includes('amazon.nova')) { | ||||||
BedrockRuntimeServiceExtension.recordNovaAttributes( | ||||||
parsedChunk, | ||||||
span | ||||||
); | ||||||
} | ||||||
} | ||||||
); | ||||||
// Replace the original response body with our instrumented stream. | ||||||
// - Defers span.end() until the entire stream is consumed | ||||||
// This ensures downstream consumers still receive the full stream correctly, | ||||||
// while OpenTelemetry can record span attributes from streamed data. | ||||||
response.data.body = (async function* () { | ||||||
try { | ||||||
for await (const item of wrappedStream) { | ||||||
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. IIUC, the result here is that two async iterators are created. Could the chunk handling above be moved into this |
||||||
yield item; | ||||||
} | ||||||
} finally { | ||||||
span.end(); | ||||||
} | ||||||
})(); | ||||||
return response.data; | ||||||
} | ||||||
// Tap into the stream at the chunk level without modifying the chunk itself. | ||||||
private static instrumentAsyncIterable<T>( | ||||||
stream: AsyncIterable<T>, | ||||||
onChunk: (chunk: T) => void | ||||||
): AsyncIterable<T> { | ||||||
return { | ||||||
[Symbol.asyncIterator]: async function* () { | ||||||
for await (const chunk of stream) { | ||||||
onChunk(chunk); | ||||||
yield chunk; | ||||||
} | ||||||
}, | ||||||
}; | ||||||
} | ||||||
|
||||||
private static parseChunk(bytes?: Uint8Array): any { | ||||||
if (!bytes || !(bytes instanceof Uint8Array)) return null; | ||||||
try { | ||||||
const str = Buffer.from(bytes).toString('utf-8'); | ||||||
return JSON.parse(str); | ||||||
} catch (err) { | ||||||
console.warn('Failed to parse streamed chunk', err); | ||||||
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. Shouldn't use
Suggested change
This will mean you'll need to not use |
||||||
return null; | ||||||
Check warning on line 669 in plugins/node/opentelemetry-instrumentation-aws-sdk/src/services/bedrock-runtime.ts
|
||||||
} | ||||||
} | ||||||
|
||||||
private static recordNovaAttributes(parsedChunk: any, span: Span) { | ||||||
if (parsedChunk.metadata?.usage !== undefined) { | ||||||
if (parsedChunk.metadata?.usage.inputTokens !== undefined) { | ||||||
span.setAttribute( | ||||||
ATTR_GEN_AI_USAGE_INPUT_TOKENS, | ||||||
parsedChunk.metadata.usage.inputTokens | ||||||
); | ||||||
} | ||||||
if (parsedChunk.metadata?.usage.outputTokens !== undefined) { | ||||||
span.setAttribute( | ||||||
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, | ||||||
parsedChunk.metadata.usage.outputTokens | ||||||
); | ||||||
} | ||||||
} | ||||||
if (parsedChunk.messageStop?.stopReason !== undefined) { | ||||||
span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [ | ||||||
parsedChunk.messageStop.stopReason, | ||||||
]); | ||||||
} | ||||||
} | ||||||
|
||||||
private static recordClaudeAttributes(parsedChunk: any, span: Span) { | ||||||
if (parsedChunk.message?.usage?.input_tokens !== undefined) { | ||||||
span.setAttribute( | ||||||
ATTR_GEN_AI_USAGE_INPUT_TOKENS, | ||||||
parsedChunk.message.usage.input_tokens | ||||||
); | ||||||
} | ||||||
if (parsedChunk.message?.usage?.output_tokens !== undefined) { | ||||||
span.setAttribute( | ||||||
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, | ||||||
parsedChunk.message.usage.output_tokens | ||||||
); | ||||||
} | ||||||
if (parsedChunk.delta?.stop_reason !== undefined) { | ||||||
span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [ | ||||||
parsedChunk.delta.stop_reason, | ||||||
]); | ||||||
} | ||||||
} | ||||||
|
||||||
private static recordTitanAttributes(parsedChunk: any, span: Span) { | ||||||
if (parsedChunk.inputTextTokenCount !== undefined) { | ||||||
span.setAttribute( | ||||||
ATTR_GEN_AI_USAGE_INPUT_TOKENS, | ||||||
parsedChunk.inputTextTokenCount | ||||||
); | ||||||
} | ||||||
if (parsedChunk.totalOutputTextTokenCount !== undefined) { | ||||||
span.setAttribute( | ||||||
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, | ||||||
parsedChunk.totalOutputTextTokenCount | ||||||
); | ||||||
} | ||||||
if (parsedChunk.completionReason !== undefined) { | ||||||
span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [ | ||||||
parsedChunk.completionReason, | ||||||
]); | ||||||
} | ||||||
} | ||||||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The non-stream
responseHookInvokeModel()
is adding some attributes for a few more models:'meta.llama'
,'cohere.command-r'
, etc.Should this function also add relevant attributes for those models? Or is it possible streaming is not supported for those models?
Also, perhaps the
recordNovaAttributes()
,recordClaudeAttributes()
, etc. methods could be used by bothresponseHookInvokeModel
andresponseHookInvokeModelWithResponseStream
. Or perhaps all therecord*Attribute()
methods could be moved to onesetInvokeModelResponseAttributes()
that is used by bothresponseHookInvokeModel*()
methods.