Merge pull request #6499 from continuedev/dallin/bedrock-openai-adapter

feat: Bedrock OpenAI adapter
This commit is contained in:
Nate Sesti 2025-07-07 22:46:04 -07:00 • committed by GitHub
commit eca51fffec
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 2354 additions and 25 deletions

View file

@ -651,6 +651,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
roles: llm.roles,
configurationStatus: llm.getConfigurationStatus(),
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
};
}

View file

@ -127,6 +127,12 @@ async function modelConfigToBaseLLM({
if ("profile" in env && typeof env.profile === "string") {
options.profile = env.profile;
}
if ("accessKeyId" in env && typeof env.accessKeyId === "string") {
options.accessKeyId = env.accessKeyId;
}
if ("secretAccessKey" in env && typeof env.secretAccessKey === "string") {
options.secretAccessKey = env.secretAccessKey;
}
if ("modelArn" in env && typeof env.modelArn === "string") {
options.modelArn = env.modelArn;
}

4
core/index.d.ts vendored
View file

@ -584,6 +584,7 @@ export interface LLMOptions {
// continueProperties
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
@ -612,6 +613,8 @@ export interface LLMOptions {
// AWS options
profile?: string;
modelArn?: string;
accessKeyId?: string;
secretAccessKey?: string;
// AWS and VertexAI Options
region?: string;
@ -1083,6 +1086,7 @@ export interface ModelDescription {
apiBase?: string;
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;

View file

@ -15,6 +15,7 @@ const DEFAULT_MAX_BATCH_SIZE = 64;
export enum LLMConfigurationStatuses {
VALID = "valid",
MISSING_API_KEY = "missing-api-key",
MISSING_ENV_SECRET = "missing-env-secret",
}
export {

View file

@ -156,6 +156,7 @@ export abstract class BaseLLM implements ILLM {
// continueProperties
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
@ -173,6 +174,8 @@ export abstract class BaseLLM implements ILLM {
accountId?: string;
aiGatewaySlug?: string;
profile?: string | undefined;
accessKeyId?: string;
secretAccessKey?: string;
// For IBM watsonx
deploymentId?: string;
@ -248,6 +251,7 @@ export abstract class BaseLLM implements ILLM {
// continueProperties
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.apiBase = options.apiBase;
@ -272,6 +276,8 @@ export abstract class BaseLLM implements ILLM {
this.region = options.region;
this.projectId = options.projectId;
this.profile = options.profile;
this.accessKeyId = options.accessKeyId;
this.secretAccessKey = options.secretAccessKey;
this.openaiAdapter = this.createOpenAiAdapter();

View file

@ -71,11 +71,7 @@ class Bedrock extends BaseLLM {
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
this.requestOptions = {
region: options.region,
headers: {},
@ -609,17 +605,24 @@ class Bedrock extends BaseLLM {
}
private async _getCredentials() {
if (this.accessKeyId && this.secretAccessKey) {
return {
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
};
}
const profile = this.profile ?? "bedrock";
try {
return await fromNodeProviderChain({
profile: this.profile,
profile: profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
`AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromNodeProviderChain()();
}
return await fromNodeProviderChain()();
}
// EMBED //

View file

@ -40,6 +40,7 @@ class ContinueProxy extends OpenAI {
this.apiType = undefined;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.onPremProxyUrl = options.onPremProxyUrl;
if (this.onPremProxyUrl) {
@ -60,6 +61,7 @@ class ContinueProxy extends OpenAI {
protected extraBodyProperties(): Record<string, any> {
const continueProperties: ContinueProperties = {
apiKeyLocation: this.apiKeyLocation,
envSecretLocations: this.envSecretLocations,
apiBase: this.actualApiBase,
orgScopeId: this.orgScopeId ?? null,
env: this.configEnv,
@ -70,13 +72,24 @@ class ContinueProxy extends OpenAI {
}
getConfigurationStatus() {
if (!this.apiKeyLocation) {
if (!this.apiKeyLocation && !this.envSecretLocations) {
return LLMConfigurationStatuses.VALID;
}
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
if (secretLocation.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_API_KEY;
if (this.apiKeyLocation) {
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
if (secretLocation.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_API_KEY;
}
}
if (this.envSecretLocations) {
for (const secretLocation of Object.values(this.envSecretLocations)) {
const decoded = decodeSecretLocation(secretLocation);
if (decoded.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_ENV_SECRET;
}
}
}
return LLMConfigurationStatuses.VALID;

View file

@ -359,8 +359,18 @@
"description": "The AWS security profile to use",
"type": "string"
},
"accessKeyId": {
"title": "Access Key ID",
"description": "AWS access key id (can be used together with secretAccessKey in place of profile)",
"type": "string"
},
"secretAccessKey": {
"title": "Secret Access Key",
"description": "AWS secret access key (can be used together with secretAccessKey in place of profile)",
"type": "string"
},
"modelArn": {
"title": "Profile",
"title": "Model ARN",
"description": "The AWS arn for the imported model",
"type": "string"
},
@ -2903,6 +2913,16 @@
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"accessKeyId": {
"title": "Access Key ID",
"description": "AWS access key id (can be used together with secretAccessKey in place of profile)",
"type": "string"
},
"secretAccessKey": {
"title": "Secret Access Key",
"description": "AWS secret access key (can be used together with secretAccessKey in place of profile)",
"type": "string"
}
},
"required": ["provider"],

View file

@ -119,19 +119,32 @@ const ModelRoleSelector = ({
{[...models]
.sort((a, b) => a.title.localeCompare(b.title))
.map((option, idx) => {
const showMissingApiKeyMsg =
const isConfigInvalid =
option.configurationStatus !==
LLMConfigurationStatuses.VALID;
let invalidMessage = "(Invalid config)";
if (
option.configurationStatus ===
LLMConfigurationStatuses.MISSING_API_KEY;
LLMConfigurationStatuses.MISSING_ENV_SECRET
) {
invalidMessage = "(Missing env secret)";
}
if (
option.configurationStatus ===
LLMConfigurationStatuses.MISSING_API_KEY
) {
invalidMessage = "(Missing API Key)";
}
return (
<ListboxOption
key={idx}
value={option.title}
disabled={showMissingApiKeyMsg}
disabled={isConfigInvalid}
onMouseEnter={() => setHoveredIdx(idx)}
onMouseLeave={() => setHoveredIdx(null)}
onClick={(e: any) =>
handleOptionClick(showMissingApiKeyMsg, e)
handleOptionClick(isConfigInvalid, e)
}
className=""
>
@ -144,9 +157,9 @@ const ModelRoleSelector = ({
style={{ fontSize: fontSize(-3) }}
>
{option.title}
{showMissingApiKeyMsg && (
{isConfigInvalid && (
<span className="ml-2 text-[10px] italic">
(Missing API key)
{invalidMessage}
</span>
)}
</span>

View file

@ -133,7 +133,27 @@ export function useProxyForUnrenderedSecrets(
const apiKeyLocation = getUnrenderedSecretLocation(
config.models[i]?.apiKey,
);
if (apiKeyLocation) {
const encodedApiKeyLocation = apiKeyLocation
? encodeSecretLocation(apiKeyLocation)
: undefined;
let encodedEnvSecretLocations: Record<string, string> | undefined =
undefined;
if (config.models[i]?.env) {
Object.entries(config.models[i]?.env!).forEach(([key, value]) => {
if (typeof value === "string") {
const secretLocation = getUnrenderedSecretLocation(value);
if (secretLocation) {
encodedEnvSecretLocations = {
...encodedEnvSecretLocations,
[key]: encodeSecretLocation(secretLocation),
};
}
}
});
}
if (encodedApiKeyLocation || encodedEnvSecretLocations) {
config.models[i] = {
...config.models[i],
name: config.models[i]?.name ?? "",
@ -143,7 +163,8 @@ export function useProxyForUnrenderedSecrets(
config.models[i]?.provider ?? "",
config.models[i]?.model ?? "",
),
apiKeyLocation: encodeSecretLocation(apiKeyLocation),
apiKeyLocation: encodedApiKeyLocation,
envSecretLocations: encodedEnvSecretLocations,
orgScopeId,
onPremProxyUrl,
apiKey: undefined,
@ -158,6 +179,7 @@ export function useProxyForUnrenderedSecrets(
/** The additional properties that are added to the otherwise OpenAI-compatible body when requesting a Continue proxy */
export const continuePropertiesSchema = z.object({
apiKeyLocation: z.string().optional(),
envSecretLocations: z.record(z.string(), z.string()).optional(),
apiBase: z.string().optional(),
orgScopeId: z.string().nullable(),
env: z.record(z.string(), z.any()).optional(),

View file

@ -155,7 +155,8 @@ export const modelSchema = z.union([
z.object({
...baseModelFields,
provider: z.literal("continue-proxy"),
apiKeyLocation: z.string(),
apiKeyLocation: z.string().optional(),
envSecretLocations: z.record(z.string(), z.string()).optional(),
orgScopeId: z.string().nullable(),
onPremProxyUrl: z.string().nullable(),
}),
@ -170,7 +171,8 @@ export const partialModelSchema = z.union([
.object({
...baseModelFields,
provider: z.literal("continue-proxy"),
apiKeyLocation: z.string(),
apiKeyLocation: z.string().optional(),
envSecretLocations: z.record(z.string(), z.string()).optional(),
})
.partial(),
z

View file

@ -71,14 +71,15 @@ export function createOpenAIClient({
);
}
if (!("apiKeyLocation" in modelConfig)) {
if (!("apiKeyLocation" in modelConfig) && !("envSecretLocations" in modelConfig)) {
throw new Error(
`Model ${modelName} does not have an apiKeyLocation defined`,
`Model ${modelName} does not have an apiKeyLocation or envSecretLocations defined`,
);
}
const continueProperties: ContinueProperties = {
apiKeyLocation: modelConfig.apiKeyLocation,
envSecretLocations: modelConfig.envSecretLocations,
orgScopeId: organizationId ?? null,
};

File diff suppressed because it is too large Load diff

View file

@ -12,6 +12,8 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.15",

View file

@ -0,0 +1,691 @@
import {
BedrockRuntimeClient,
ContentBlock,
ConversationRole,
ConverseStreamCommand,
ConverseStreamCommandInput,
ImageFormat,
InvokeModelCommand,
Message,
ToolConfiguration,
} from "@aws-sdk/client-bedrock-runtime";
import { OpenAI } from "openai/index";
import { v4 as uuidv4 } from "uuid";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParams,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
ChatCompletionMessageToolCall,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CreateEmbeddingResponse,
EmbeddingCreateParams,
Model,
} from "openai/resources/index";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import { BedrockConfig } from "../types.js";
import { chatChunk, chatChunkFromDelta, embedding, rerank } from "../util.js";
import { safeParseArgs } from "../util/parseArgs.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
// Utility function to get or generate UUID for prompt caching
function getSecureID(): string {
// Adding a type declaration for the static property
if (!(getSecureID as any).uuid) {
(getSecureID as any).uuid = crypto.randomUUID();
}
return `<!-- SID: ${(getSecureID as any).uuid} -->`;
}
/**
* Interface for tool use state tracking
*/
interface ToolUseState {
toolUseId: string;
name: string;
input: string;
}
export class BedrockApi implements BaseLlmApi {
private _currentToolResponse: Partial<ToolUseState> | null = null;
constructor(protected config: BedrockConfig) {
if (config.env?.accessKeyId || config?.env?.secretAccessKey) {
if (!config.env?.accessKeyId) {
throw new Error(
"accessKeyId is required for Bedrock API. Only found secretAccessKey",
);
}
if (!config.env?.secretAccessKey) {
throw new Error(
"secretAccessKey is required for Bedrock API. Only found accessKeyId",
);
}
}
}
async getCreds() {
if (this.config?.env?.accessKeyId && this.config?.env?.secretAccessKey) {
return {
accessKeyId: this.config.env.accessKeyId,
secretAccessKey: this.config.env.secretAccessKey,
};
}
const profile = this.config.env.profile ?? "bedrock";
try {
return await fromNodeProviderChain({
profile: profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
);
}
return await fromNodeProviderChain()();
}
async getClient(): Promise<BedrockRuntimeClient> {
const creds = await this.getCreds();
return new BedrockRuntimeClient({
region: this.config.env.region,
credentials: creds,
});
}
private _oaiPartToBedrockPart(
part:
| OpenAI.Chat.Completions.ChatCompletionContentPart
| OpenAI.Chat.Completions.ChatCompletionContentPartRefusal,
): ContentBlock {
switch (part.type) {
case "refusal":
return {
text: part.refusal,
};
case "text":
return {
text: part.text,
};
case "input_audio":
throw new Error("Unsupported part type: input_audio");
case "image_url":
default:
try {
const [mimeType, base64Data] = part.image_url.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
if (
format === ImageFormat.JPEG ||
format === ImageFormat.PNG ||
format === ImageFormat.WEBP ||
format === ImageFormat.GIF
) {
return {
image: {
format,
source: {
bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
},
},
};
} else {
console.warn(
`Bedrock: skipping unsupported image part format: ${format}`,
);
return { text: "[Unsupported image format]" };
}
} catch (error) {
console.warn("Bedrock: failed to process image part", error);
return { text: "[Failed to process image]" };
}
}
}
private _convertMessages(
oaiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
availableTools: Set<string>,
): Message[] {
let currentRole: "user" | "assistant" = "user";
let currentBlocks: ContentBlock[] = [];
const converted: Message[] = [];
const hasAddedToolCallIds = new Set<string>();
const pushCurrentMessage = () => {
if (currentBlocks.length > 0) {
converted.push({
role: currentRole,
content: currentBlocks,
});
currentBlocks = [];
}
};
const nonSystemMessages = oaiMessages.filter((m) => m.role !== "system");
for (let idx = 0; idx < nonSystemMessages.length; idx++) {
const message = nonSystemMessages[idx];
if (message.role === "user" || message.role === "tool") {
// Detect conversational turn change
if (currentRole !== ConversationRole.USER) {
pushCurrentMessage();
currentRole = ConversationRole.USER;
}
// USER messages
if (message.role === "user") {
const content = message.content;
if (content) {
if (typeof content === "string") {
currentBlocks.push({ text: content });
} else {
content.forEach((part) => {
currentBlocks.push(this._oaiPartToBedrockPart(part));
});
}
}
}
// TOOL messages
else if (message.role === "tool") {
const trimmedContent =
typeof message.content === "string"
? message.content.trim()
: message.content
.map((c) => c.text)
.join("\n")
.trim();
if (hasAddedToolCallIds.has(message.tool_call_id)) {
currentBlocks.push({
toolResult: {
toolUseId: message.tool_call_id,
content: [
{
text: trimmedContent || "No tool output",
},
],
},
});
} else {
currentBlocks.push({
text: `Tool call output for Tool Call ID ${message.tool_call_id}:\n\n${trimmedContent || "No tool output"}`,
});
}
}
} else if (message.role === "assistant") {
// Detect conversational turn change
if (currentRole !== ConversationRole.ASSISTANT) {
pushCurrentMessage();
currentRole = ConversationRole.ASSISTANT;
}
// ASSISTANT messages
if (typeof message.content === "string") {
const trimmedText = message.content.trim();
if (trimmedText) {
currentBlocks.push({ text: trimmedText });
}
} else {
message.content?.forEach((part) => {
const text = part.type === "text" ? part.text : part.refusal;
const trimmedText = text.trim();
if (trimmedText) {
currentBlocks.push({ text: trimmedText });
}
});
}
// TOOL CALLS
if (message.tool_calls) {
for (const toolCall of message.tool_calls) {
if (toolCall.id && toolCall.function?.name) {
if (availableTools.has(toolCall.function.name)) {
currentBlocks.push({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function.name,
input: safeParseArgs(
toolCall.function.arguments,
`Call: ${toolCall.function.name} ${toolCall.id}`,
),
},
});
hasAddedToolCallIds.add(toolCall.id);
} else {
const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
currentBlocks.push({
text: toolCallText,
});
}
}
}
}
}
}
if (currentBlocks.length > 0) {
pushCurrentMessage();
}
// If caching is enabled, add cache points
// if (this.config.cacheBehavior?.cacheConversation) {
// this._addCachingToLastTwoUserMessages(converted);
// }
return converted;
}
private _addCachingToLastTwoUserMessages(converted: Message[]) {
let numCached = 0;
for (let i = converted.length - 1; i >= 0; i--) {
const message = converted[i];
if (message.role === "user") {
message.content?.forEach((block) => {
if (block.text) {
block.text += getSecureID();
}
});
message.content?.push({ cachePoint: { type: "default" } });
numCached++;
}
if (numCached === 2) {
break;
}
}
}
private _convertBody(
oaiBody: ChatCompletionCreateParams,
): ConverseStreamCommandInput {
// Extract system message
const systemMessage =
oaiBody.messages.find((msg) => msg.role === "system")?.content || "";
const systemMessageText =
typeof systemMessage === "string"
? systemMessage
: systemMessage
.map((part) =>
part.type === "text" ? part.text : "[Non-text content]",
)
.join(" ");
// Check for tools
const availableTools = new Set<string>();
let toolConfig: ToolConfiguration | undefined = undefined;
if (oaiBody.tools && oaiBody.tools.length > 0) {
toolConfig = {
tools: oaiBody.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration;
// Add cache point if needed
// if (this.config.cacheBehavior?.cacheSystemMessage) {
// toolConfig!.tools!.push({ cachePoint: { type: "default" } });
// }
oaiBody.tools.forEach((tool) => {
availableTools.add(tool.function.name);
});
}
// Convert messages
const convertedMessages = this._convertMessages(
oaiBody.messages,
availableTools,
);
// Build final request body
const body: any = {
modelId: oaiBody.model,
messages: convertedMessages,
inferenceConfig: {
temperature: oaiBody.temperature,
topP: oaiBody.top_p,
maxTokens: oaiBody.max_tokens,
stopSequences: Array.isArray(oaiBody.stop)
? oaiBody.stop.filter((s) => s.trim() !== "").slice(0, 4)
: oaiBody.stop
? [oaiBody.stop].filter((s) => s.trim() !== "")
: undefined,
},
};
// Add system message if present
if (systemMessageText) {
body.system = false // this.config.cacheBehavior?.cacheSystemMessage // TODO
? [{ text: systemMessageText }, { cachePoint: { type: "default" } }]
: [{ text: systemMessageText }];
}
// Add tool config if present
if (toolConfig) {
body.toolConfig = toolConfig;
}
// Add reasoning if needed
// TODO REASONING
// if (this.c) {
// body.additionalModelRequestFields = {
// thinking: {
// type: "enabled",
// budget_tokens:
// oaiBody.additionalModelRequestFields.reasoningBudgetTokens,
// },
// };
// }
return body;
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
let completion = "";
const toolCalls: ChatCompletionMessageToolCall[] = [];
for await (const chunk of this.chatCompletionStream(
{
...body,
stream: true,
},
signal,
)) {
if (chunk.choices[0].delta.content) {
completion += chunk.choices[0].delta.content;
}
// TODO tool calls not supported
}
return {
id: uuidv4(),
object: "chat.completion",
model: body.model,
created: Date.now(),
choices: [
{
index: 0,
logprobs: null,
finish_reason: "stop",
message: {
role: "assistant",
content: completion,
tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
refusal: null,
},
},
],
usage: undefined,
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk> {
const requestBody = this._convertBody(body);
try {
const command = new ConverseStreamCommand({
...requestBody,
});
const client = await this.getClient();
const response = await client.send(command, { abortSignal: signal });
if (!response?.stream) {
throw new Error("No stream received from Bedrock API");
}
this._currentToolResponse = null;
for await (const chunk of response.stream) {
if (chunk.contentBlockDelta?.delta) {
const delta: any = chunk.contentBlockDelta.delta;
// Handle text content
if (delta.text) {
yield chatChunk({
content: delta.text,
model: body.model,
});
continue;
}
// Handle thinking content (if reasoning enabled)
if (delta.reasoningContent?.text) {
// TODO reasoning
// Reasoning is not directly supported in OpenAI format,
// but we could add it as a special message
continue;
}
// Handle tool use
if (delta.toolUse?.input && this._currentToolResponse) {
if (this._currentToolResponse.input === undefined) {
this._currentToolResponse.input = "";
}
this._currentToolResponse.input += delta.toolUse.input;
continue;
}
}
if (chunk.contentBlockStart?.start) {
const start: any = chunk.contentBlockStart.start;
// Handle tool start
const toolUse = start.toolUse;
if (toolUse?.toolUseId && toolUse?.name) {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: "",
};
}
continue;
}
if (chunk.contentBlockStop) {
// End of a content block
if (this._currentToolResponse) {
yield chatChunkFromDelta({
model: body.model,
delta: {
tool_calls: [
{
index: 0,
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input,
},
},
],
},
});
this._currentToolResponse = null;
}
continue;
}
}
} catch (error) {
this._currentToolResponse = null;
if (error instanceof Error) {
if ("code" in error) {
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",
);
}
}
completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
throw new Error("Bedrock does not support completions API");
}
completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion> {
throw new Error("Bedrock does not support completions API");
}
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error("Bedrock does not support FIM directly");
}
private async getInvokeModelResponseBody(model: string, jsonBody: object) {
const payload = {
body: JSON.stringify(jsonBody),
modelId: model,
accept: "*/*",
contentType: "application/json",
};
const command = new InvokeModelCommand(payload);
const client = await this.getClient();
const response = await client.send(command);
if (!response.body) {
throw new Error("No response body");
}
const decoder = new TextDecoder();
const decoded = decoder.decode(response.body);
return JSON.parse(decoded);
}
private getEmbedTexts(body: EmbeddingCreateParams): string[] {
const texts: string[] = [];
if (typeof body.input === "string") {
texts.push(body.input);
} else if (body.input.length > 0) {
const firstVal = body.input[0];
if (Array.isArray(firstVal)) {
throw new Error("Unsupported embeddings type received: number[][]");
}
if (typeof firstVal === "string") {
texts.push(...(body.input as string[]));
} else {
throw new Error("Unsupported embeddings type received: number[]");
}
}
return texts;
}
async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
const texts = this.getEmbedTexts(body);
let embeddings: number[][];
if (body.model.startsWith("cohere")) {
const payload = {
texts,
input_type: "search_document",
truncate: "END",
};
const output = await this.getInvokeModelResponseBody(body.model, payload);
embeddings = [output.embedding];
} else if (body.model.startsWith("amazon.titan-embed")) {
embeddings = await Promise.all(
texts.map(async (text) => {
const payload = {
inputText: text,
};
const output = await this.getInvokeModelResponseBody(
body.model,
payload,
);
return output.embeddings || [];
}),
);
} else {
throw new Error(`Unsupported model: ${body.model}`);
}
return embedding({
data: embeddings,
model: body.model,
usage: {
prompt_tokens: 0,
total_tokens: 0,
},
});
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
if (!body.query || !body.documents.length) {
throw new Error("Query and chunks must not be empty");
}
// Base payload for both models
const payload: any = {
query: body.query,
documents: body.documents,
top_n: body.top_k ?? body.documents.length,
};
// Add api_version for Cohere model
if (body.model.startsWith("cohere.rerank")) {
payload.api_version = 2;
}
try {
const responseBody = await this.getInvokeModelResponseBody(
body.model,
payload,
);
const scores = responseBody.results
.sort((a: any, b: any) => a.index - b.index)
.map((result: any) => result.relevance_score);
return rerank({
model: body.model,
usage: {
total_tokens: 0,
},
data: scores,
});
} catch (error) {
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(
`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
);
}
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
}
throw new Error(
"Error in BedrockReranker.rerank: Unknown error occurred",
);
}
}
list(): Promise<Model[]> {
throw new Error("Method not implemented.");
}
}

View file

@ -2,6 +2,7 @@ import dotenv from "dotenv";
import { z } from "zod";
import { AnthropicApi } from "./apis/Anthropic.js";
import { AzureApi } from "./apis/Azure.js";
import { BedrockApi } from "./apis/Bedrock.js";
import { CohereApi } from "./apis/Cohere.js";
import { DeepSeekApi } from "./apis/DeepSeek.js";
import { GeminiApi } from "./apis/Gemini.js";
@ -34,6 +35,8 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined {
return new OpenAIApi(config);
case "azure":
return new AzureApi(config);
case "bedrock":
return new BedrockApi(config);
case "cohere":
return new CohereApi(config);
case "anthropic":

View file

@ -71,6 +71,21 @@ export const DeepseekConfigSchema = OpenAIConfigSchema.extend({
});
export type DeepseekConfig = z.infer<typeof DeepseekConfigSchema>;
export const BedrockConfigSchema = OpenAIConfigSchema.extend({
provider: z.literal("bedrock"),
// cacheBehavior: z.object({
// cacheSystemMessage: z.boolean().optional(),
// cacheConversation: z.boolean().optional(),
// }).optional(),
env: z.object({
region: z.string().optional(),
accessKeyId: z.string().optional(),
secretAccessKey: z.string().optional(),
profile: z.string().optional(),
}),
});
export type BedrockConfig = z.infer<typeof BedrockConfigSchema>;
export const LlamastackConfigSchema = OpenAIConfigSchema.extend({
provider: z.literal("llamastack"),
});
@ -142,6 +157,7 @@ export type InceptionConfig = z.infer<typeof InceptionConfigSchema>;
// Discriminated union
export const LLMConfigSchema = z.discriminatedUnion("provider", [
OpenAIConfigSchema,
BedrockConfigSchema,
MoonshotConfigSchema,
DeepseekConfigSchema,
CohereConfigSchema,