Skip to content

Conversation

@narengogi
Copy link
Collaborator

This is not a fix for #1142 , the stream error is still consumed silently, but this change returns finish reason which is required for the last streaming chunk

@narengogi narengogi requested review from VisargD and b4s36t4 June 17, 2025 05:32
@matter-code-review
Copy link
Contributor

matter-code-review bot commented Jun 17, 2025

Code Quality bug fix

Description

🔄 What Changed

  • Added a message property to the BedrockChatCompleteStreamChunk interface to accommodate error messages from Bedrock.
  • Modified the BedrockChatCompleteStreamChunkTransform to detect the presence of a message field in incoming Bedrock stream chunks. If detected, it now calls a new utility function, getBedrockErrorChunk, to generate a standardized error response chunk.
  • Introduced a new utility function, getBedrockErrorChunk, in src/providers/bedrock/utils.ts. This function constructs a chat.completion.chunk object with a finish_reason: 'stop' and role: 'assistant' for error scenarios, followed by a [DONE] chunk.
  • Ensured that successful stream chunks also explicitly include finish_reason: null to maintain consistency in the output format.

🔍 Impact of the Change

This change improves the handling of streaming errors from Bedrock by ensuring that a finish_reason is explicitly returned when an error message is received. This is crucial for the last streaming chunk and prevents the silent consumption of stream errors, providing more robust error reporting to the client.

📁 Total Files Changed

2 files were changed in this pull request.

🧪 Test Added

No explicit tests were mentioned or added in this pull request description. The PR body states "This is not a fix for #1142, the stream error is still consumed silently, but this change returns finish_reason which is required for the last streaming chunk", implying a functional enhancement rather than a bug fix with specific test cases.

🔒Security Vulnerabilities

No security vulnerabilities were detected in the provided code changes.

Motivation

This change returns the finish_reason which is required for the last streaming chunk, especially when an error message is received from Bedrock, addressing a scenario where stream errors were previously consumed silently.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

How Has This Been Tested?

  • Unit Tests
  • Integration Tests
  • Manual Testing

Screenshots (if applicable)

N/A

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Related Issues

N/A

Tip

Quality Recommendations

  1. Add comprehensive unit tests for the getBedrockErrorChunk function to ensure it consistently generates the correct JSON structure for error chunks, including id, model, provider, and the finish_reason.

  2. Implement integration tests for the BedrockChatCompleteStreamChunkTransform to specifically verify the new error handling logic. This should include test cases where parsedChunk.message is present, ensuring the correct error chunk is returned and the stream terminates as expected.

  3. Consider adding logging within the if (parsedChunk.message) block in BedrockChatCompleteStreamChunkTransform to log the original Bedrock error message. This would aid in debugging and understanding the nature of errors received from the Bedrock service.

Sequence Diagram

sequenceDiagram
    participant User
    participant GatewayAPI as Gateway API (Bedrock ChatComplete)
    participant BedrockService as Bedrock Service
    participant BedrockChatCompleteStreamChunkTransform as BedrockChatCompleteStreamChunkTransform
    participant getBedrockErrorChunk as getBedrockErrorChunk

    User->>GatewayAPI: Initiate Chat Completion Stream Request
    GatewayAPI->>BedrockService: Forward Request
    BedrockService-->>GatewayAPI: Stream Chunks (JSON)
    GatewayAPI->>BedrockChatCompleteStreamChunkTransform: Process Stream Chunk (responseChunk)

    alt Bedrock Error Message Received
        BedrockChatCompleteStreamChunkTransform->>BedrockChatCompleteStreamChunkTransform: Parse responseChunk (parsedChunk)
        BedrockChatCompleteStreamChunkTransform-->>BedrockChatCompleteStreamChunkTransform: Check if parsedChunk.message exists
        activate BedrockChatCompleteStreamChunkTransform
        BedrockChatCompleteStreamChunkTransform->>getBedrockErrorChunk: Call getBedrockErrorChunk(fallbackId, model)
        activate getBedrockErrorChunk
        getBedrockErrorChunk-->>BedrockChatCompleteStreamChunkTransform: Return formatted error chunk (data: {...finish_reason: 'stop'...}
\ndata: [DONE])
        deactivate getBedrockErrorChunk
        BedrockChatCompleteStreamChunkTransform-->>GatewayAPI: Return Error Stream Chunk
        deactivate BedrockChatCompleteStreamChunkTransform
    else Standard Stream Chunk
        BedrockChatCompleteStreamChunkTransform->>BedrockChatCompleteStreamChunkTransform: Parse responseChunk (parsedChunk)
        BedrockChatCompleteStreamChunkTransform-->>BedrockChatCompleteStreamChunkTransform: Check for parsedChunk.stopReason
        activate BedrockChatCompleteStreamChunkTransform
        BedrockChatCompleteStreamChunkTransform-->>BedrockChatCompleteStreamChunkTransform: Process delta, tool_calls, etc.
        BedrockChatCompleteStreamChunkTransform-->>BedrockChatCompleteStreamChunkTransform: Ensure finish_reason: null for non-error chunks
        BedrockChatCompleteStreamChunkTransform-->>GatewayAPI: Return Transformed Stream Chunk
        deactivate BedrockChatCompleteStreamChunkTransform
    end

    GatewayAPI-->>User: Stream Transformed Chunks
Loading

Copy link
Contributor

@matter-code-review matter-code-review bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds proper error handling for Bedrock API responses, which is a good improvement. I've identified a few issues that should be addressed to make the implementation more robust.

Comment on lines 645 to 649
const parsedChunk: BedrockChatCompleteStreamChunk = JSON.parse(responseChunk);
console.log(JSON.stringify(parsedChunk, null, 2));
if (parsedChunk.message) {
return getBedrockErrorChunk(fallbackId, gatewayRequest.model || '');
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Code Refactor

Issue: The console.log statement should not be included in production code.
Fix: Remove the debugging console.log statement.
Impact: Prevents unnecessary logging in production and keeps the logs clean.

Suggested change
const parsedChunk: BedrockChatCompleteStreamChunk = JSON.parse(responseChunk);
console.log(JSON.stringify(parsedChunk, null, 2));
if (parsedChunk.message) {
return getBedrockErrorChunk(fallbackId, gatewayRequest.model || '');
}
const parsedChunk: BedrockChatCompleteStreamChunk = JSON.parse(responseChunk);
if (parsedChunk.message) {
return getBedrockErrorChunk(fallbackId, gatewayRequest.model || '');
}

Comment on lines +486 to +505
export const getBedrockErrorChunk = (id: string, model: string) => {
return [
`data: ${JSON.stringify({
id,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: model,
provider: BEDROCK,
choices: [
{
index: 0,
delta: {
role: 'assistant',
finish_reason: 'stop',
},
},
],
})}\n\n`,
`data: [DONE]\n\n`,
];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚡️ Performance Improvement

Issue: The error chunk doesn't include the actual error message from Bedrock, which could be useful for debugging.
Fix: Pass and include the error message in the response.
Impact: Improves error reporting and makes debugging easier.

Suggested change
export const getBedrockErrorChunk = (id: string, model: string) => {
return [
`data: ${JSON.stringify({
id,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: model,
provider: BEDROCK,
choices: [
{
index: 0,
delta: {
role: 'assistant',
finish_reason: 'stop',
},
},
],
})}\n\n`,
`data: [DONE]\n\n`,
];
export const getBedrockErrorChunk = (id: string, model: string, errorMessage?: string) => {
return [
`data: ${JSON.stringify({
id,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: model,
provider: BEDROCK,
choices: [
{
index: 0,
delta: {
role: 'assistant',
finish_reason: 'stop',
},
error: errorMessage,
},
],
})}\
\
`,
`data: [DONE]\
\
`,
];

Comment on lines +647 to +649
if (parsedChunk.message) {
return getBedrockErrorChunk(fallbackId, gatewayRequest.model || '');
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Code Refactor

Issue: The error message from Bedrock is not being passed to the error chunk function.
Fix: Pass the error message to the getBedrockErrorChunk function.
Impact: Provides more context in the error response for better debugging.

Suggested change
if (parsedChunk.message) {
return getBedrockErrorChunk(fallbackId, gatewayRequest.model || '');
}
if (parsedChunk.message) {
return getBedrockErrorChunk(fallbackId, gatewayRequest.model || '', parsedChunk.message);
}

@matter-code-review
Copy link
Contributor

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

@jczstudios
Copy link

Glad to see this, has been super frustrating using Portkey with Bedrock

@matter-code-review
Copy link
Contributor

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

@matter-code-review
Copy link
Contributor

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

@matter-code-review
Copy link
Contributor

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

@VisargD VisargD merged commit 9d4e946 into Portkey-AI:main Jun 24, 2025
2 checks passed
@matter-code-review
Copy link
Contributor

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants