Add reasoning and reasoningBudgetTokens to BaseCompletionOptions and update Bedrock to handle reasoning for Anthropic Claude models

This commit is contained in:
ferenci84 2025-03-03 22:56:16 +01:00
parent b4c1af0cfe
commit 7d047ca1eb
2 changed files with 181 additions and 81 deletions

2
core/index.d.ts vendored
View file

@ -924,6 +924,8 @@ export interface BaseCompletionOptions {
prediction?: Prediction;
tools?: Tool[];
toolChoice?: ToolChoice;
reasoning?: boolean;
reasoningBudgetTokens?: number;
}
export interface ModelCapability {

View file

@ -2,6 +2,7 @@ import {
BedrockRuntimeClient,
ConverseStreamCommand,
InvokeModelCommand,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
@ -10,6 +11,7 @@ import {
Chunk,
CompletionOptions,
LLMOptions,
MessageContent,
} from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
@ -86,9 +88,9 @@ class Bedrock extends BaseLLM {
});
let config_headers =
this.requestOptions && this.requestOptions.headers
? this.requestOptions.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."
@ -106,85 +108,120 @@ class Bedrock extends BaseLLM {
},
);
const input = this._generateConverseInput(messages, { ...options, stream: true });
const command = new ConverseStreamCommand(input);
let response;
try {
response = await client.send(command, { abortSignal: signal });
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
}
if (!response?.stream) {
throw new Error("No stream received from Bedrock API");
}
try {
for await (const chunk of response.stream) {
console.log(chunk);
if (chunk.contentBlockDelta?.delta) {
// Handle text content
if (chunk.contentBlockDelta.delta.text) {
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
continue;
}
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
// Append the new input to the existing string
if (this._currentToolResponse.input === undefined) {
this._currentToolResponse.input = "";
}
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
continue;
}
}
if (chunk.contentBlockStart?.start) {
const toolUse = chunk.contentBlockStart.start.toolUse;
if (toolUse?.toolUseId && toolUse?.name) {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: ""
};
}
continue;
}
if (chunk.contentBlockStop) {
if (this._currentToolResponse) {
yield {
role: "assistant",
content: "",
toolCalls: [{
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input
if (options.reasoning && options.model.includes("anthropic.claude")) {
const input = this._generateInvokeInput(messages, options);
const command = new InvokeModelWithResponseStreamCommand(input);
try {
const response = await client.send(command, { abortSignal: signal });
if (response.body) {
for await (const chunk of response.body) {
if (chunk.chunk?.bytes) {
const chunkData = JSON.parse(new TextDecoder().decode(chunk.chunk.bytes));
if (chunkData?.delta?.text) {
yield {
role: "assistant",
content: chunkData.delta.text,
};
} else {
if (chunkData?.delta?.thinking) {
yield {
role: "thinking",
content: chunkData.delta.thinking,
};
}
}],
};
this._currentToolResponse = null;
}
//TODO: Handle tool use once the thinking blocks (with redacted_thinking) are properly added to the history
}
}
continue;
}
} catch (e) {
console.error("Error while invoke Bedrock model");
console.error(e);
throw e;
}
} catch (error: unknown) {
this._currentToolResponse = null;
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
} else {
const input = this._generateConverseInput(messages, { ...options, stream: true });
const command = new ConverseStreamCommand(input);
let response;
try {
response = await client.send(command, { abortSignal: signal });
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
}
if (!response?.stream) {
throw new Error("No stream received from Bedrock API");
}
try {
for await (const chunk of response.stream) {
console.log(chunk);
if (chunk.contentBlockDelta?.delta) {
// Handle text content
if (chunk.contentBlockDelta.delta.text) {
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
continue;
}
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
// Append the new input to the existing string
if (this._currentToolResponse.input === undefined) {
this._currentToolResponse.input = "";
}
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
continue;
}
}
if (chunk.contentBlockStart?.start) {
const toolUse = chunk.contentBlockStart.start.toolUse;
if (toolUse?.toolUseId && toolUse?.name) {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: ""
};
}
continue;
}
if (chunk.contentBlockStop) {
if (this._currentToolResponse) {
yield {
role: "assistant",
content: "",
toolCalls: [{
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input
}
}],
};
this._currentToolResponse = null;
}
continue;
}
}
throw new Error(`Error processing Bedrock stream: ${error.message}`);
} catch (error: unknown) {
this._currentToolResponse = null;
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
}
throw new Error(`Error processing Bedrock stream: ${error.message}`);
}
throw new Error("Error processing Bedrock stream: Unknown error occurred");
}
throw new Error("Error processing Bedrock stream: Unknown error occurred");
}
}
@ -265,11 +302,11 @@ class Bedrock extends BaseLLM {
return {
role: "assistant",
content: message.toolCalls.map((toolCall) => ({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function?.name,
input: JSON.parse(toolCall.function?.arguments || "{}"),
}
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function?.name,
input: JSON.parse(toolCall.function?.arguments || "{}"),
}
}))
};
}
@ -326,6 +363,67 @@ class Bedrock extends BaseLLM {
.filter(Boolean);
}
private _generateInvokeInput(
messages: ChatMessage[],
options: CompletionOptions,
): any {
const convertedMessages = this._convertMessagesForInvoke(messages);
return {
modelId: options.model,
contentType: "application/json",
accept: "application/json",
body: JSON.stringify({
anthropic_version: "bedrock-2023-05-31",
temperature: options.temperature,
system: this.systemMessage,
max_tokens: options.maxTokens,
top_p: options.topP,
stop_sequences: options.stop
?.filter((stop) => stop.trim() !== "")
.slice(0, 4),
thinking: options.reasoning ? {
type: "enabled",
budget_tokens: options.reasoningBudgetTokens || 1024
} : undefined,
messages: convertedMessages
})
}
}
private _convertMessagesForInvoke(messages: ChatMessage[]): any[] {
return messages
.filter((message) => message.role !== "system")
.map((message) => ({
role: message.role,
content: this._convertMessageContentForInvoke(message.content),
}));
}
private _convertMessageContentForInvoke(messageContent: MessageContent): any[] {
if (typeof messageContent === "string") {
return [{ type: "text", text: messageContent }];
}
return messageContent
.map((part) => {
if (part.type === "text") {
return { type: "text", text: part.text };
}
if (part.type === "imageUrl" && part.imageUrl) {
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: Buffer.from(part.imageUrl.url.split(",")[1], "base64"),
},
};
}
return null;
})
.filter(Boolean);
}
private async _getCredentials() {
try {
return await fromIni({