From 34829b3b4f7da91750c9bff347c45e956a8f5253 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Tue, 12 Aug 2025 10:04:34 -0700 Subject: [PATCH 1/4] feat: :sparkles: Add gpt-oss to the bedrock provider --- core/llm/llms/Bedrock.ts | 201 ++++++++++++++++++++++++++++++--------- core/llm/toolSupport.ts | 1 + 2 files changed, 158 insertions(+), 44 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index a0f77c45a..6c87dcc31 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -2,12 +2,12 @@ import { BedrockRuntimeClient, ContentBlock, ConversationRole, + ConverseCommand, ConverseStreamCommand, - ConverseStreamCommandOutput, ImageFormat, InvokeModelCommand, Message, - ToolConfiguration, + ToolConfiguration } from "@aws-sdk/client-bedrock-runtime"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; @@ -91,47 +91,33 @@ class Bedrock extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const credentials = await this._getCredentials(); - const client = new BedrockRuntimeClient({ - region: this.region, - endpoint: this.apiBase, - credentials: { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - sessionToken: credentials.sessionToken || "", - }, - }); + if (options.stream !== false) { + yield* this._streamChatStreaming(messages, signal, options); + } else { + yield* this._streamChatNonStreaming(messages, signal, options); + } + } - let config_headers = - this.requestOptions && this.requestOptions.headers - ? this.requestOptions.headers - : {}; - // AWS SigV4 requires strict canonicalization of headers. - // DO NOT USE "_" in your header name. It will return an error like below. - // "The request signature we calculated does not match the signature you provided." - - client.middlewareStack.add( - (next) => async (args: any) => { - args.request.headers = { - ...args.request.headers, - ...config_headers, - }; - return next(args); - }, - { - step: "build", - }, - ); + /** + * Handles streaming chat using ConverseStreamCommand + */ + private async *_streamChatStreaming( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const client = await this._createBedrockClient(); + this._addClientMiddleware(client); const input = this._generateConverseInput(messages, { ...options, stream: true, }); - const command = new ConverseStreamCommand(input); - const response = (await client.send(command, { + const command = new ConverseStreamCommand(input); + const response = await client.send(command, { abortSignal: signal, - })) as ConverseStreamCommandOutput; + }); if (!response?.stream) { throw new Error("No stream received from Bedrock API"); @@ -158,17 +144,17 @@ class Bedrock extends BaseLLM { role: "assistant", content: chunk.contentBlockDelta.delta.text, }; - continue; + continue; // Continue parsing the stream } - // Handle text content + // Handle reasoning text content if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent .text, }; - continue; + continue; // Continue parsing the stream } // Handle signature for thinking @@ -178,7 +164,7 @@ class Bedrock extends BaseLLM { content: "", signature: delta.reasoningContent.signature, }; - continue; + continue; // Continue parsing the stream } // Handle redacted thinking @@ -188,7 +174,7 @@ class Bedrock extends BaseLLM { content: "", redactedThinking: delta.redactedReasoning.data, }; - continue; + continue; // Continue parsing the stream } if ( @@ -201,7 +187,7 @@ class Bedrock extends BaseLLM { } this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input; - continue; + continue; // Continue parsing the stream } } @@ -213,7 +199,7 @@ class Bedrock extends BaseLLM { content: "", redactedThinking: start.redactedReasoning.data, }; - continue; + continue; // Continue parsing the stream } const toolUse = chunk.contentBlockStart.start.toolUse; @@ -224,7 +210,7 @@ class Bedrock extends BaseLLM { input: "", }; } - continue; + continue; // Continue parsing the stream } if (chunk.contentBlockStop) { @@ -245,7 +231,7 @@ class Bedrock extends BaseLLM { }; this._currentToolResponse = null; } - continue; + continue; // Continue parsing the stream } } } catch (error: unknown) { @@ -255,6 +241,133 @@ class Bedrock extends BaseLLM { } } + /** + * Handles non-streaming chat using ConverseCommand + */ + private async *_streamChatNonStreaming( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const client = await this._createBedrockClient(); + this._addClientMiddleware(client); + + const input = this._generateConverseInput(messages, { + ...options, + stream: false, + }); + + const command = new ConverseCommand(input); + const response = await client.send(command, { + abortSignal: signal, + }); + + // Reset cache metrics for new request + this._promptCachingMetrics = { + cacheReadInputTokens: 0, + cacheWriteInputTokens: 0, + }; + + try { + if (response.output?.message?.content) { + for (const contentBlock of response.output.message.content) { + if (contentBlock.text) { + yield { + role: "assistant", + content: contentBlock.text, + }; + } + + if ((contentBlock as any).reasoningContent) { + const reasoningContent = (contentBlock as any).reasoningContent; + if (reasoningContent.reasoningText) { + yield { + role: "thinking", + content: reasoningContent.reasoningText.text || "", + signature: reasoningContent.reasoningText.signature, + }; + } + if (reasoningContent.redactedContent) { + yield { + role: "thinking", + content: "", + redactedThinking: reasoningContent.redactedContent, + }; + } + } + + if (contentBlock.toolUse) { + yield { + role: "assistant", + content: "", + toolCalls: [ + { + id: contentBlock.toolUse.toolUseId, + type: "function", + function: { + name: contentBlock.toolUse.name, + arguments: JSON.stringify(contentBlock.toolUse.input || {}), + }, + }, + ], + }; + } + } + } + + // Handle usage metadata if available + if (response.usage) { + console.log(`${JSON.stringify(response.usage)}`); + } + } catch (error: unknown) { + // Clean up state and let the original error bubble up to the retry decorator + this._currentToolResponse = null; + throw error; + } + } + + /** + * Creates and configures a Bedrock Runtime Client + */ + private async _createBedrockClient(): Promise { + const credentials = await this._getCredentials(); + return new BedrockRuntimeClient({ + region: this.region, + endpoint: this.apiBase, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + } + + /** + * Adds middleware to the Bedrock client for custom headers + */ + private _addClientMiddleware(client: BedrockRuntimeClient): void { + const config_headers = + this.requestOptions && this.requestOptions.headers + ? this.requestOptions.headers + : {}; + // AWS SigV4 requires strict canonicalization of headers. + // DO NOT USE "_" in your header name. It will return an error like below. + // "The request signature we calculated does not match the signature you provided." + + client.middlewareStack.add( + (next) => async (args: any) => { + args.request.headers = { + ...args.request.headers, + ...config_headers, + }; + return next(args); + }, + { + step: "build", + }, + ); + } + /** * Generates the input payload for the Bedrock Converse API * @param messages - Array of chat messages diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 7c89dbfa4..fd413fcf0 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -124,6 +124,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "nova-pro", "nova-micro", "nova-premier", + "gpt-oss", ].some((part) => model.toLowerCase().includes(part)) ) { return true; From fe15916f5cad0eb4640a754ccfe67fd10953edcd Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Tue, 12 Aug 2025 10:36:12 -0700 Subject: [PATCH 2/4] test: :white_check_mark: Add tests --- core/llm/llms/Bedrock.test.ts | 127 +++++++++++++++++++++++++++++++++- 1 file changed, 125 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts index 69b4ab7a8..32a8c5f21 100644 --- a/core/llm/llms/Bedrock.test.ts +++ b/core/llm/llms/Bedrock.test.ts @@ -7,13 +7,21 @@ import { import Bedrock from "./Bedrock.js"; // Mock AWS SDK +const mockSend = jest.fn(); +const mockMiddlewareStackAdd = jest.fn(); + jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ BedrockRuntimeClient: jest.fn().mockImplementation(() => ({ - send: jest.fn(), - middlewareStack: { add: jest.fn() }, + send: mockSend, + middlewareStack: { add: mockMiddlewareStackAdd }, })), ConverseStreamCommand: jest.fn(), + ConverseCommand: jest.fn(), InvokeModelCommand: jest.fn(), + ConversationRole: { + USER: "user", + ASSISTANT: "assistant", + }, })); // Mock credential provider @@ -90,6 +98,8 @@ class TestBedrock extends Bedrock { describe("Bedrock", () => { beforeEach(() => { jest.clearAllMocks(); + mockSend.mockReset(); + mockMiddlewareStackAdd.mockReset(); }); describe("constructor", () => { @@ -304,6 +314,119 @@ describe("Bedrock", () => { }); }); + describe("streaming vs non-streaming behavior", () => { + class TestableStreamingBedrock extends Bedrock { + public streamingMethodCalled = false; + public nonStreamingMethodCalled = false; + + protected async *_streamChatStreaming( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + this.streamingMethodCalled = true; + yield { role: "assistant", content: "Streaming response" }; + } + + protected async *_streamChatNonStreaming( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + this.nonStreamingMethodCalled = true; + yield { role: "assistant", content: "Non-streaming response" }; + } + } + + let bedrock: TestableStreamingBedrock; + const mockAbortSignal = new AbortController().signal; + + beforeEach(() => { + bedrock = new TestableStreamingBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", + }); + }); + + it("should use streaming method when stream is not false", async () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" } as UserChatMessage, + ]; + + const options: CompletionOptions = { + model: "anthropic.claude-3-sonnet-20240229-v1:0", + stream: true, // Explicitly set streaming + }; + + const results = []; + for await (const message of bedrock["_streamChat"]( + messages, + mockAbortSignal, + options, + )) { + results.push(message); + } + + expect(bedrock.streamingMethodCalled).toBe(true); + expect(bedrock.nonStreamingMethodCalled).toBe(false); + expect(results).toEqual([ + { role: "assistant", content: "Streaming response" }, + ]); + }); + + it("should use non-streaming method when stream is false", async () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" } as UserChatMessage, + ]; + + const options: CompletionOptions = { + model: "anthropic.claude-3-sonnet-20240229-v1:0", + stream: false, // Explicitly set non-streaming + }; + + const results = []; + for await (const message of bedrock["_streamChat"]( + messages, + mockAbortSignal, + options, + )) { + results.push(message); + } + + expect(bedrock.streamingMethodCalled).toBe(false); + expect(bedrock.nonStreamingMethodCalled).toBe(true); + expect(results).toEqual([ + { role: "assistant", content: "Non-streaming response" }, + ]); + }); + + it("should default to streaming method when stream option is undefined", async () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" } as UserChatMessage, + ]; + + const options: CompletionOptions = { + model: "anthropic.claude-3-sonnet-20240229-v1:0", + // stream option is undefined, should default to streaming + }; + + const results = []; + for await (const message of bedrock["_streamChat"]( + messages, + mockAbortSignal, + options, + )) { + results.push(message); + } + + expect(bedrock.streamingMethodCalled).toBe(true); + expect(bedrock.nonStreamingMethodCalled).toBe(false); + }); + }); + + + describe("message conversion", () => { let bedrock: TestBedrock; From 7fdce04449ca815b835ca3a480a40c20995c2dcc Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Tue, 12 Aug 2025 10:56:34 -0700 Subject: [PATCH 3/4] fix: :white_check_mark: Prettier and test fixes --- core/llm/llms/Bedrock.test.ts | 95 ++++++++++++++++++++++------------- core/llm/llms/Bedrock.ts | 2 +- 2 files changed, 60 insertions(+), 37 deletions(-) diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts index 32a8c5f21..262f2266b 100644 --- a/core/llm/llms/Bedrock.test.ts +++ b/core/llm/llms/Bedrock.test.ts @@ -315,45 +315,35 @@ describe("Bedrock", () => { }); describe("streaming vs non-streaming behavior", () => { - class TestableStreamingBedrock extends Bedrock { - public streamingMethodCalled = false; - public nonStreamingMethodCalled = false; - - protected async *_streamChatStreaming( - messages: ChatMessage[], - signal: AbortSignal, - options: CompletionOptions, - ): AsyncGenerator { - this.streamingMethodCalled = true; - yield { role: "assistant", content: "Streaming response" }; - } - - protected async *_streamChatNonStreaming( - messages: ChatMessage[], - signal: AbortSignal, - options: CompletionOptions, - ): AsyncGenerator { - this.nonStreamingMethodCalled = true; - yield { role: "assistant", content: "Non-streaming response" }; - } - } - - let bedrock: TestableStreamingBedrock; + let bedrock: Bedrock; const mockAbortSignal = new AbortController().signal; beforeEach(() => { - bedrock = new TestableStreamingBedrock({ + bedrock = new Bedrock({ apiKey: "test-key", model: "anthropic.claude-3-sonnet-20240229-v1:0", region: "us-east-1", }); }); - it("should use streaming method when stream is not false", async () => { + it("should route to streaming path when stream is not false", async () => { const messages: ChatMessage[] = [ { role: "user", content: "Hello" } as UserChatMessage, ]; + // Mock the private methods by spying on them + const streamingMethodSpy = jest + .spyOn(bedrock as any, "_streamChatStreaming") + .mockImplementation(async function* () { + yield { role: "assistant", content: "Streaming response" }; + }); + + const nonStreamingMethodSpy = jest + .spyOn(bedrock as any, "_streamChatNonStreaming") + .mockImplementation(async function* () { + yield { role: "assistant", content: "Non-streaming response" }; + }); + const options: CompletionOptions = { model: "anthropic.claude-3-sonnet-20240229-v1:0", stream: true, // Explicitly set streaming @@ -368,18 +358,34 @@ describe("Bedrock", () => { results.push(message); } - expect(bedrock.streamingMethodCalled).toBe(true); - expect(bedrock.nonStreamingMethodCalled).toBe(false); + expect(streamingMethodSpy).toHaveBeenCalled(); + expect(nonStreamingMethodSpy).not.toHaveBeenCalled(); expect(results).toEqual([ { role: "assistant", content: "Streaming response" }, ]); + + streamingMethodSpy.mockRestore(); + nonStreamingMethodSpy.mockRestore(); }); - it("should use non-streaming method when stream is false", async () => { + it("should route to non-streaming path when stream is false", async () => { const messages: ChatMessage[] = [ { role: "user", content: "Hello" } as UserChatMessage, ]; + // Mock the private methods by spying on them + const streamingMethodSpy = jest + .spyOn(bedrock as any, "_streamChatStreaming") + .mockImplementation(async function* () { + yield { role: "assistant", content: "Streaming response" }; + }); + + const nonStreamingMethodSpy = jest + .spyOn(bedrock as any, "_streamChatNonStreaming") + .mockImplementation(async function* () { + yield { role: "assistant", content: "Non-streaming response" }; + }); + const options: CompletionOptions = { model: "anthropic.claude-3-sonnet-20240229-v1:0", stream: false, // Explicitly set non-streaming @@ -394,18 +400,34 @@ describe("Bedrock", () => { results.push(message); } - expect(bedrock.streamingMethodCalled).toBe(false); - expect(bedrock.nonStreamingMethodCalled).toBe(true); + expect(streamingMethodSpy).not.toHaveBeenCalled(); + expect(nonStreamingMethodSpy).toHaveBeenCalled(); expect(results).toEqual([ { role: "assistant", content: "Non-streaming response" }, ]); + + streamingMethodSpy.mockRestore(); + nonStreamingMethodSpy.mockRestore(); }); - it("should default to streaming method when stream option is undefined", async () => { + it("should default to streaming path when stream option is undefined", async () => { const messages: ChatMessage[] = [ { role: "user", content: "Hello" } as UserChatMessage, ]; + // Mock the private methods by spying on them + const streamingMethodSpy = jest + .spyOn(bedrock as any, "_streamChatStreaming") + .mockImplementation(async function* () { + yield { role: "assistant", content: "Streaming response" }; + }); + + const nonStreamingMethodSpy = jest + .spyOn(bedrock as any, "_streamChatNonStreaming") + .mockImplementation(async function* () { + yield { role: "assistant", content: "Non-streaming response" }; + }); + const options: CompletionOptions = { model: "anthropic.claude-3-sonnet-20240229-v1:0", // stream option is undefined, should default to streaming @@ -420,13 +442,14 @@ describe("Bedrock", () => { results.push(message); } - expect(bedrock.streamingMethodCalled).toBe(true); - expect(bedrock.nonStreamingMethodCalled).toBe(false); + expect(streamingMethodSpy).toHaveBeenCalled(); + expect(nonStreamingMethodSpy).not.toHaveBeenCalled(); + + streamingMethodSpy.mockRestore(); + nonStreamingMethodSpy.mockRestore(); }); }); - - describe("message conversion", () => { let bedrock: TestBedrock; diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 6c87dcc31..0054ab2ca 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -7,7 +7,7 @@ import { ImageFormat, InvokeModelCommand, Message, - ToolConfiguration + ToolConfiguration, } from "@aws-sdk/client-bedrock-runtime"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; From e2e57302154dfc004bd28123cf29f991c3273457 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Thu, 21 Aug 2025 00:21:17 -0700 Subject: [PATCH 4/4] fix: :bug: Restore files --- core/llm/llms/Bedrock.test.ts | 150 +------------------------ core/llm/llms/Bedrock.ts | 199 ++++++++-------------------------- 2 files changed, 45 insertions(+), 304 deletions(-) diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts index 262f2266b..69b4ab7a8 100644 --- a/core/llm/llms/Bedrock.test.ts +++ b/core/llm/llms/Bedrock.test.ts @@ -7,21 +7,13 @@ import { import Bedrock from "./Bedrock.js"; // Mock AWS SDK -const mockSend = jest.fn(); -const mockMiddlewareStackAdd = jest.fn(); - jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ BedrockRuntimeClient: jest.fn().mockImplementation(() => ({ - send: mockSend, - middlewareStack: { add: mockMiddlewareStackAdd }, + send: jest.fn(), + middlewareStack: { add: jest.fn() }, })), ConverseStreamCommand: jest.fn(), - ConverseCommand: jest.fn(), InvokeModelCommand: jest.fn(), - ConversationRole: { - USER: "user", - ASSISTANT: "assistant", - }, })); // Mock credential provider @@ -98,8 +90,6 @@ class TestBedrock extends Bedrock { describe("Bedrock", () => { beforeEach(() => { jest.clearAllMocks(); - mockSend.mockReset(); - mockMiddlewareStackAdd.mockReset(); }); describe("constructor", () => { @@ -314,142 +304,6 @@ describe("Bedrock", () => { }); }); - describe("streaming vs non-streaming behavior", () => { - let bedrock: Bedrock; - const mockAbortSignal = new AbortController().signal; - - beforeEach(() => { - bedrock = new Bedrock({ - apiKey: "test-key", - model: "anthropic.claude-3-sonnet-20240229-v1:0", - region: "us-east-1", - }); - }); - - it("should route to streaming path when stream is not false", async () => { - const messages: ChatMessage[] = [ - { role: "user", content: "Hello" } as UserChatMessage, - ]; - - // Mock the private methods by spying on them - const streamingMethodSpy = jest - .spyOn(bedrock as any, "_streamChatStreaming") - .mockImplementation(async function* () { - yield { role: "assistant", content: "Streaming response" }; - }); - - const nonStreamingMethodSpy = jest - .spyOn(bedrock as any, "_streamChatNonStreaming") - .mockImplementation(async function* () { - yield { role: "assistant", content: "Non-streaming response" }; - }); - - const options: CompletionOptions = { - model: "anthropic.claude-3-sonnet-20240229-v1:0", - stream: true, // Explicitly set streaming - }; - - const results = []; - for await (const message of bedrock["_streamChat"]( - messages, - mockAbortSignal, - options, - )) { - results.push(message); - } - - expect(streamingMethodSpy).toHaveBeenCalled(); - expect(nonStreamingMethodSpy).not.toHaveBeenCalled(); - expect(results).toEqual([ - { role: "assistant", content: "Streaming response" }, - ]); - - streamingMethodSpy.mockRestore(); - nonStreamingMethodSpy.mockRestore(); - }); - - it("should route to non-streaming path when stream is false", async () => { - const messages: ChatMessage[] = [ - { role: "user", content: "Hello" } as UserChatMessage, - ]; - - // Mock the private methods by spying on them - const streamingMethodSpy = jest - .spyOn(bedrock as any, "_streamChatStreaming") - .mockImplementation(async function* () { - yield { role: "assistant", content: "Streaming response" }; - }); - - const nonStreamingMethodSpy = jest - .spyOn(bedrock as any, "_streamChatNonStreaming") - .mockImplementation(async function* () { - yield { role: "assistant", content: "Non-streaming response" }; - }); - - const options: CompletionOptions = { - model: "anthropic.claude-3-sonnet-20240229-v1:0", - stream: false, // Explicitly set non-streaming - }; - - const results = []; - for await (const message of bedrock["_streamChat"]( - messages, - mockAbortSignal, - options, - )) { - results.push(message); - } - - expect(streamingMethodSpy).not.toHaveBeenCalled(); - expect(nonStreamingMethodSpy).toHaveBeenCalled(); - expect(results).toEqual([ - { role: "assistant", content: "Non-streaming response" }, - ]); - - streamingMethodSpy.mockRestore(); - nonStreamingMethodSpy.mockRestore(); - }); - - it("should default to streaming path when stream option is undefined", async () => { - const messages: ChatMessage[] = [ - { role: "user", content: "Hello" } as UserChatMessage, - ]; - - // Mock the private methods by spying on them - const streamingMethodSpy = jest - .spyOn(bedrock as any, "_streamChatStreaming") - .mockImplementation(async function* () { - yield { role: "assistant", content: "Streaming response" }; - }); - - const nonStreamingMethodSpy = jest - .spyOn(bedrock as any, "_streamChatNonStreaming") - .mockImplementation(async function* () { - yield { role: "assistant", content: "Non-streaming response" }; - }); - - const options: CompletionOptions = { - model: "anthropic.claude-3-sonnet-20240229-v1:0", - // stream option is undefined, should default to streaming - }; - - const results = []; - for await (const message of bedrock["_streamChat"]( - messages, - mockAbortSignal, - options, - )) { - results.push(message); - } - - expect(streamingMethodSpy).toHaveBeenCalled(); - expect(nonStreamingMethodSpy).not.toHaveBeenCalled(); - - streamingMethodSpy.mockRestore(); - nonStreamingMethodSpy.mockRestore(); - }); - }); - describe("message conversion", () => { let bedrock: TestBedrock; diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 0054ab2ca..a0f77c45a 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -2,8 +2,8 @@ import { BedrockRuntimeClient, ContentBlock, ConversationRole, - ConverseCommand, ConverseStreamCommand, + ConverseStreamCommandOutput, ImageFormat, InvokeModelCommand, Message, @@ -91,33 +91,47 @@ class Bedrock extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - if (options.stream !== false) { - yield* this._streamChatStreaming(messages, signal, options); - } else { - yield* this._streamChatNonStreaming(messages, signal, options); - } - } + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + endpoint: this.apiBase, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); - /** - * Handles streaming chat using ConverseStreamCommand - */ - private async *_streamChatStreaming( - messages: ChatMessage[], - signal: AbortSignal, - options: CompletionOptions, - ): AsyncGenerator { - const client = await this._createBedrockClient(); - this._addClientMiddleware(client); + let config_headers = + this.requestOptions && this.requestOptions.headers + ? this.requestOptions.headers + : {}; + // AWS SigV4 requires strict canonicalization of headers. + // DO NOT USE "_" in your header name. It will return an error like below. + // "The request signature we calculated does not match the signature you provided." + + client.middlewareStack.add( + (next) => async (args: any) => { + args.request.headers = { + ...args.request.headers, + ...config_headers, + }; + return next(args); + }, + { + step: "build", + }, + ); const input = this._generateConverseInput(messages, { ...options, stream: true, }); - const command = new ConverseStreamCommand(input); - const response = await client.send(command, { + + const response = (await client.send(command, { abortSignal: signal, - }); + })) as ConverseStreamCommandOutput; if (!response?.stream) { throw new Error("No stream received from Bedrock API"); @@ -144,17 +158,17 @@ class Bedrock extends BaseLLM { role: "assistant", content: chunk.contentBlockDelta.delta.text, }; - continue; // Continue parsing the stream + continue; } - // Handle reasoning text content + // Handle text content if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent .text, }; - continue; // Continue parsing the stream + continue; } // Handle signature for thinking @@ -164,7 +178,7 @@ class Bedrock extends BaseLLM { content: "", signature: delta.reasoningContent.signature, }; - continue; // Continue parsing the stream + continue; } // Handle redacted thinking @@ -174,7 +188,7 @@ class Bedrock extends BaseLLM { content: "", redactedThinking: delta.redactedReasoning.data, }; - continue; // Continue parsing the stream + continue; } if ( @@ -187,7 +201,7 @@ class Bedrock extends BaseLLM { } this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input; - continue; // Continue parsing the stream + continue; } } @@ -199,7 +213,7 @@ class Bedrock extends BaseLLM { content: "", redactedThinking: start.redactedReasoning.data, }; - continue; // Continue parsing the stream + continue; } const toolUse = chunk.contentBlockStart.start.toolUse; @@ -210,7 +224,7 @@ class Bedrock extends BaseLLM { input: "", }; } - continue; // Continue parsing the stream + continue; } if (chunk.contentBlockStop) { @@ -231,7 +245,7 @@ class Bedrock extends BaseLLM { }; this._currentToolResponse = null; } - continue; // Continue parsing the stream + continue; } } } catch (error: unknown) { @@ -241,133 +255,6 @@ class Bedrock extends BaseLLM { } } - /** - * Handles non-streaming chat using ConverseCommand - */ - private async *_streamChatNonStreaming( - messages: ChatMessage[], - signal: AbortSignal, - options: CompletionOptions, - ): AsyncGenerator { - const client = await this._createBedrockClient(); - this._addClientMiddleware(client); - - const input = this._generateConverseInput(messages, { - ...options, - stream: false, - }); - - const command = new ConverseCommand(input); - const response = await client.send(command, { - abortSignal: signal, - }); - - // Reset cache metrics for new request - this._promptCachingMetrics = { - cacheReadInputTokens: 0, - cacheWriteInputTokens: 0, - }; - - try { - if (response.output?.message?.content) { - for (const contentBlock of response.output.message.content) { - if (contentBlock.text) { - yield { - role: "assistant", - content: contentBlock.text, - }; - } - - if ((contentBlock as any).reasoningContent) { - const reasoningContent = (contentBlock as any).reasoningContent; - if (reasoningContent.reasoningText) { - yield { - role: "thinking", - content: reasoningContent.reasoningText.text || "", - signature: reasoningContent.reasoningText.signature, - }; - } - if (reasoningContent.redactedContent) { - yield { - role: "thinking", - content: "", - redactedThinking: reasoningContent.redactedContent, - }; - } - } - - if (contentBlock.toolUse) { - yield { - role: "assistant", - content: "", - toolCalls: [ - { - id: contentBlock.toolUse.toolUseId, - type: "function", - function: { - name: contentBlock.toolUse.name, - arguments: JSON.stringify(contentBlock.toolUse.input || {}), - }, - }, - ], - }; - } - } - } - - // Handle usage metadata if available - if (response.usage) { - console.log(`${JSON.stringify(response.usage)}`); - } - } catch (error: unknown) { - // Clean up state and let the original error bubble up to the retry decorator - this._currentToolResponse = null; - throw error; - } - } - - /** - * Creates and configures a Bedrock Runtime Client - */ - private async _createBedrockClient(): Promise { - const credentials = await this._getCredentials(); - return new BedrockRuntimeClient({ - region: this.region, - endpoint: this.apiBase, - credentials: { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - sessionToken: credentials.sessionToken || "", - }, - }); - } - - /** - * Adds middleware to the Bedrock client for custom headers - */ - private _addClientMiddleware(client: BedrockRuntimeClient): void { - const config_headers = - this.requestOptions && this.requestOptions.headers - ? this.requestOptions.headers - : {}; - // AWS SigV4 requires strict canonicalization of headers. - // DO NOT USE "_" in your header name. It will return an error like below. - // "The request signature we calculated does not match the signature you provided." - - client.middlewareStack.add( - (next) => async (args: any) => { - args.request.headers = { - ...args.request.headers, - ...config_headers, - }; - return next(args); - }, - { - step: "build", - }, - ); - } - /** * Generates the input payload for the Bedrock Converse API * @param messages - Array of chat messages