Elffuss BraidHub

kikocis/continue public

main · 20.1 KiBRawPermalink
1import {
2 BedrockRuntimeClient,
3 ContentBlock,
4 ContentBlockStart,
5 ConversationRole,
6 ConverseStreamCommand,
7 ConverseStreamCommandInput,
8 ImageFormat,
9 InvokeModelCommand,
10 Message,
11 ToolConfiguration,
12} from "@aws-sdk/client-bedrock-runtime";
13import { OpenAI } from "openai/index";
14import { v4 as uuidv4 } from "uuid";
15
16import {
17 ChatCompletion,
18 ChatCompletionChunk,
19 ChatCompletionContentPartImage,
20 ChatCompletionCreateParams,
21 ChatCompletionCreateParamsNonStreaming,
22 ChatCompletionCreateParamsStreaming,
23 ChatCompletionMessageToolCall,
24 Completion,
25 CompletionCreateParamsNonStreaming,
26 CompletionCreateParamsStreaming,
27 CreateEmbeddingResponse,
28 EmbeddingCreateParams,
29 Model,
30} from "openai/resources/index";
31
32import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
33import { BedrockConfig } from "../types.js";
34import { chatChunk, chatChunkFromDelta, embedding, rerank } from "../util.js";
35import { safeParseArgs } from "../util/parseArgs.js";
36import {
37 BaseLlmApi,
38 CreateRerankResponse,
39 FimCreateParamsStreaming,
40 RerankCreateParams,
41} from "./base.js";
42
43// Utility function to get or generate UUID for prompt caching
44function getSecureID(): string {
45 // Adding a type declaration for the static property
46 if (!(getSecureID as any).uuid) {
47 (getSecureID as any).uuid = uuidv4();
48 }
49 return `<!-- SID: ${(getSecureID as any).uuid} -->`;
50}
51
52/**
53 * Interface for tool use state tracking
54 */
55interface ToolUseState {
56 toolUseId: string;
57 name: string;
58 input: string;
59}
60
61export class BedrockApi implements BaseLlmApi {
62 constructor(protected config: BedrockConfig) {
63 if (config.env?.accessKeyId || config?.env?.secretAccessKey) {
64 if (!config.env?.accessKeyId) {
65 throw new Error(
66 "accessKeyId is required for Bedrock API. Only found secretAccessKey",
67 );
68 }
69 if (!config.env?.secretAccessKey) {
70 throw new Error(
71 "secretAccessKey is required for Bedrock API. Only found accessKeyId",
72 );
73 }
74 }
75 }
76
77 async getCreds() {
78 if (this.config?.env?.accessKeyId && this.config?.env?.secretAccessKey) {
79 return {
80 accessKeyId: this.config.env.accessKeyId,
81 secretAccessKey: this.config.env.secretAccessKey,
82 };
83 }
84 const profile = this.config.env.profile ?? "bedrock";
85 try {
86 return await fromNodeProviderChain({
87 profile: profile,
88 ignoreCache: true,
89 })();
90 } catch (e) {
91 console.warn(
92 `AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
93 );
94 }
95 return await fromNodeProviderChain()();
96 }
97 async getClient(): Promise<BedrockRuntimeClient> {
98 const creds = await this.getCreds();
99 return new BedrockRuntimeClient({
100 region: this.config.env.region,
101 credentials: creds,
102 });
103 }
104
105 private _oaiPartToBedrockPart(
106 part:
107 | OpenAI.Chat.Completions.ChatCompletionContentPart
108 | OpenAI.Chat.Completions.ChatCompletionContentPartRefusal,
109 ): ContentBlock {
110 switch (part.type) {
111 case "refusal":
112 return {
113 text: part.refusal,
114 };
115 case "text":
116 return {
117 text: part.text,
118 };
119 case "input_audio":
120 throw new Error("Unsupported part type: input_audio");
121 case "image_url":
122 default:
123 try {
124 const [mimeType, base64Data] = (
125 part as ChatCompletionContentPartImage
126 ).image_url.url.split(",");
127 const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
128 if (
129 format === ImageFormat.JPEG ||
130 format === ImageFormat.PNG ||
131 format === ImageFormat.WEBP ||
132 format === ImageFormat.GIF
133 ) {
134 return {
135 image: {
136 format,
137 source: {
138 bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
139 },
140 },
141 };
142 } else {
143 console.warn(
144 `Bedrock: skipping unsupported image part format: ${format}`,
145 );
146 return { text: "[Unsupported image format]" };
147 }
148 } catch (error) {
149 console.warn("Bedrock: failed to process image part", error);
150 return { text: "[Failed to process image]" };
151 }
152 }
153 }
154
155 private _convertMessages(
156 oaiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
157 availableTools: Set<string>,
158 ): Message[] {
159 let currentRole: "user" | "assistant" = "user";
160 let currentBlocks: ContentBlock[] = [];
161 const converted: Message[] = [];
162 const hasAddedToolCallIds = new Set<string>();
163
164 const pushCurrentMessage = () => {
165 if (currentBlocks.length > 0) {
166 converted.push({
167 role: currentRole,
168 content: currentBlocks,
169 });
170 currentBlocks = [];
171 }
172 };
173
174 const nonSystemMessages = oaiMessages.filter((m) => m.role !== "system");
175
176 for (let idx = 0; idx < nonSystemMessages.length; idx++) {
177 const message = nonSystemMessages[idx];
178
179 if (message.role === "user" || message.role === "tool") {
180 // Detect conversational turn change
181 if (currentRole !== ConversationRole.USER) {
182 pushCurrentMessage();
183 currentRole = ConversationRole.USER;
184 }
185
186 // USER messages
187 if (message.role === "user") {
188 const content = message.content;
189 if (content) {
190 if (typeof content === "string") {
191 currentBlocks.push({ text: content });
192 } else {
193 content.forEach((part) => {
194 currentBlocks.push(this._oaiPartToBedrockPart(part));
195 });
196 }
197 }
198 }
199 // TOOL messages
200 else if (message.role === "tool") {
201 const trimmedContent =
202 typeof message.content === "string"
203 ? message.content.trim()
204 : message.content
205 .map((c) => c.text)
206 .join("\n")
207 .trim();
208
209 if (hasAddedToolCallIds.has(message.tool_call_id)) {
210 currentBlocks.push({
211 toolResult: {
212 toolUseId: message.tool_call_id,
213 content: [
214 {
215 text: trimmedContent || "No tool output",
216 },
217 ],
218 },
219 });
220 } else {
221 currentBlocks.push({
222 text: `Tool call output for Tool Call ID ${message.tool_call_id}:\n\n${trimmedContent || "No tool output"}`,
223 });
224 }
225 }
226 } else if (message.role === "assistant") {
227 // Detect conversational turn change
228 if (currentRole !== ConversationRole.ASSISTANT) {
229 pushCurrentMessage();
230 currentRole = ConversationRole.ASSISTANT;
231 }
232
233 // ASSISTANT messages
234 if (typeof message.content === "string") {
235 const trimmedText = message.content.trim();
236 if (trimmedText) {
237 currentBlocks.push({ text: trimmedText });
238 }
239 } else {
240 message.content?.forEach((part) => {
241 const text = part.type === "text" ? part.text : part.refusal;
242 const trimmedText = text.trim();
243 if (trimmedText) {
244 currentBlocks.push({ text: trimmedText });
245 }
246 });
247 }
248
249 // TOOL CALLS
250 if (message.tool_calls) {
251 for (const toolCall of message.tool_calls) {
252 // Type guard for function tool calls
253 if (
254 toolCall.type === "function" &&
255 "function" in toolCall &&
256 toolCall.id &&
257 toolCall.function?.name
258 ) {
259 if (availableTools.has(toolCall.function.name)) {
260 currentBlocks.push({
261 toolUse: {
262 toolUseId: toolCall.id,
263 name: toolCall.function.name,
264 input: safeParseArgs(
265 toolCall.function.arguments,
266 `Call: ${toolCall.function.name} ${toolCall.id}`,
267 ),
268 },
269 });
270 hasAddedToolCallIds.add(toolCall.id);
271 } else {
272 const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
273 currentBlocks.push({
274 text: toolCallText,
275 });
276 }
277 } else {
278 console.warn(
279 `Unsupported tool call type in Bedrock: ${toolCall.type}`,
280 );
281 }
282 }
283 }
284 }
285 }
286
287 if (currentBlocks.length > 0) {
288 pushCurrentMessage();
289 }
290
291 // If caching is enabled, add cache points
292 // if (this.config.cacheBehavior?.cacheConversation) {
293 // this._addCachingToLastTwoUserMessages(converted);
294 // }
295
296 return converted;
297 }
298
299 private _addCachingToLastTwoUserMessages(converted: Message[]) {
300 let numCached = 0;
301 for (let i = converted.length - 1; i >= 0; i--) {
302 const message = converted[i];
303 if (message.role === "user") {
304 message.content?.forEach((block) => {
305 if (block.text) {
306 block.text += getSecureID();
307 }
308 });
309 message.content?.push({ cachePoint: { type: "default" } });
310 numCached++;
311 }
312 if (numCached === 2) {
313 break;
314 }
315 }
316 }
317
318 private _convertBody(
319 oaiBody: ChatCompletionCreateParams,
320 ): ConverseStreamCommandInput {
321 // Extract system message
322 const systemMessage =
323 oaiBody.messages.find((msg) => msg.role === "system")?.content || "";
324
325 const systemMessageText =
326 typeof systemMessage === "string"
327 ? systemMessage
328 : systemMessage
329 .map((part) =>
330 part.type === "text" ? part.text : "[Non-text content]",
331 )
332 .join(" ");
333
334 // Check for tools
335 const availableTools = new Set<string>();
336 let toolConfig: ToolConfiguration | undefined = undefined;
337
338 if (oaiBody.tools && oaiBody.tools.length > 0) {
339 toolConfig = {
340 tools: oaiBody.tools.map((tool) => {
341 // Type guard for function tools
342 if (tool.type === "function" && "function" in tool) {
343 return {
344 toolSpec: {
345 name: tool.function.name,
346 description: tool.function.description,
347 inputSchema: {
348 json: tool.function.parameters,
349 },
350 },
351 };
352 } else {
353 throw new Error(`Unsupported tool type in Bedrock: ${tool.type}`);
354 }
355 }),
356 } as ToolConfiguration;
357
358 // Add cache point if needed
359 // if (this.config.cacheBehavior?.cacheSystemMessage) {
360 // toolConfig!.tools!.push({ cachePoint: { type: "default" } });
361 // }
362
363 oaiBody.tools.forEach((tool) => {
364 if (tool.type === "function" && "function" in tool) {
365 availableTools.add(tool.function.name);
366 }
367 });
368 }
369
370 // Convert messages
371 const convertedMessages = this._convertMessages(
372 oaiBody.messages,
373 availableTools,
374 );
375
376 // Build final request body
377 const body: any = {
378 modelId: oaiBody.model,
379 messages: convertedMessages,
380 inferenceConfig: {
381 temperature: oaiBody.temperature,
382 topP: oaiBody.top_p,
383 maxTokens: oaiBody.max_tokens,
384 stopSequences: Array.isArray(oaiBody.stop)
385 ? oaiBody.stop.filter((s) => s.trim() !== "").slice(0, 4)
386 : oaiBody.stop
387 ? [oaiBody.stop].filter((s) => s.trim() !== "")
388 : undefined,
389 },
390 };
391
392 // Add system message if present
393 if (systemMessageText) {
394 body.system = false // this.config.cacheBehavior?.cacheSystemMessage // TODO
395 ? [{ text: systemMessageText }, { cachePoint: { type: "default" } }]
396 : [{ text: systemMessageText }];
397 }
398
399 // Add tool config if present
400 if (toolConfig) {
401 body.toolConfig = toolConfig;
402 }
403
404 // Add reasoning if needed
405 // TODO REASONING
406 // if (this.c) {
407 // body.additionalModelRequestFields = {
408 // thinking: {
409 // type: "enabled",
410 // budget_tokens:
411 // oaiBody.additionalModelRequestFields.reasoningBudgetTokens,
412 // },
413 // };
414 // }
415
416 return body;
417 }
418
419 async chatCompletionNonStream(
420 body: ChatCompletionCreateParamsNonStreaming,
421 signal: AbortSignal,
422 ): Promise<ChatCompletion> {
423 let completion = "";
424 const toolCalls: ChatCompletionMessageToolCall[] = [];
425
426 for await (const chunk of this.chatCompletionStream(
427 {
428 ...body,
429 stream: true,
430 },
431 signal,
432 )) {
433 if (chunk.choices[0].delta.content) {
434 completion += chunk.choices[0].delta.content;
435 }
436 // TODO tool calls not supported
437 }
438
439 return {
440 id: uuidv4(),
441 object: "chat.completion",
442 model: body.model,
443 created: Date.now(),
444 choices: [
445 {
446 index: 0,
447 logprobs: null,
448 finish_reason: "stop",
449 message: {
450 role: "assistant",
451 content: completion,
452 tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
453 refusal: null,
454 },
455 },
456 ],
457 usage: undefined,
458 };
459 }
460
461 async *chatCompletionStream(
462 body: ChatCompletionCreateParamsStreaming,
463 signal: AbortSignal,
464 ): AsyncGenerator<ChatCompletionChunk> {
465 const requestBody = this._convertBody(body);
466
467 try {
468 const command = new ConverseStreamCommand({
469 ...requestBody,
470 });
471
472 const client = await this.getClient();
473 const response = await client.send(command, { abortSignal: signal });
474
475 if (!response?.stream) {
476 throw new Error("No stream received from Bedrock API");
477 }
478
479 for await (const chunk of response.stream) {
480 if (chunk.contentBlockDelta?.delta) {
481 const delta: any = chunk.contentBlockDelta.delta;
482
483 // Handle text content
484 if (delta.text) {
485 yield chatChunk({
486 content: delta.text,
487 model: body.model,
488 });
489 continue;
490 }
491
492 // Handle thinking content (if reasoning enabled)
493 if (delta.reasoningContent?.text) {
494 // TODO reasoning
495 // Reasoning is not directly supported in OpenAI format,
496 // but we could add it as a special message
497 continue;
498 }
499
500 // Handle tool use
501 if (delta.toolUse) {
502 yield chatChunkFromDelta({
503 model: body.model,
504 delta: {
505 tool_calls: [
506 {
507 index: 0,
508 id: delta.toolUse.toolUseId,
509 type: "function",
510 function: {
511 name: delta.toolUse.name,
512 arguments: delta.toolUse.input,
513 },
514 },
515 ],
516 },
517 });
518 }
519 }
520
521 if (chunk.contentBlockStart?.start) {
522 const start: ContentBlockStart = chunk.contentBlockStart.start;
523
524 if (start.toolUse) {
525 yield chatChunkFromDelta({
526 model: body.model,
527 delta: {
528 tool_calls: [
529 {
530 index: 0,
531 id: start.toolUse.toolUseId,
532 type: "function",
533 function: {
534 name: start.toolUse.name,
535 arguments: undefined,
536 },
537 },
538 ],
539 },
540 });
541 }
542 }
543 }
544 } catch (error) {
545 if (error instanceof Error) {
546 if ("code" in error) {
547 throw new Error(
548 `AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
549 );
550 }
551 throw new Error(`Error processing Bedrock stream: ${error.message}`);
552 }
553 throw new Error(
554 "Error processing Bedrock stream: Unknown error occurred",
555 );
556 }
557 }
558
559 completionNonStream(
560 body: CompletionCreateParamsNonStreaming,
561 ): Promise<Completion> {
562 throw new Error("Bedrock does not support completions API");
563 }
564
565 completionStream(
566 body: CompletionCreateParamsStreaming,
567 ): AsyncGenerator<Completion> {
568 throw new Error("Bedrock does not support completions API");
569 }
570
571 fimStream(
572 body: FimCreateParamsStreaming,
573 ): AsyncGenerator<ChatCompletionChunk> {
574 throw new Error("Bedrock does not support FIM directly");
575 }
576
577 private async getInvokeModelResponseBody(model: string, jsonBody: object) {
578 const payload = {
579 body: JSON.stringify(jsonBody),
580 modelId: model,
581 accept: "*/*",
582 contentType: "application/json",
583 };
584 const command = new InvokeModelCommand(payload);
585 const client = await this.getClient();
586 const response = await client.send(command);
587 if (!response.body) {
588 throw new Error("No response body");
589 }
590 const decoder = new TextDecoder();
591 const decoded = decoder.decode(response.body);
592 return JSON.parse(decoded);
593 }
594
595 private getEmbedTexts(body: EmbeddingCreateParams): string[] {
596 const texts: string[] = [];
597 if (typeof body.input === "string") {
598 texts.push(body.input);
599 } else if (body.input.length > 0) {
600 const firstVal = body.input[0];
601 if (Array.isArray(firstVal)) {
602 throw new Error("Unsupported embeddings type received: number[][]");
603 }
604 if (typeof firstVal === "string") {
605 texts.push(...(body.input as string[]));
606 } else {
607 throw new Error("Unsupported embeddings type received: number[]");
608 }
609 }
610 return texts;
611 }
612
613 async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
614 const texts = this.getEmbedTexts(body);
615
616 let embeddings: number[][];
617 if (body.model.startsWith("cohere")) {
618 const payload = {
619 texts,
620 input_type: "search_document",
621 truncate: "END",
622 };
623 const output = await this.getInvokeModelResponseBody(body.model, payload);
624 embeddings = [output.embedding];
625 } else if (body.model.startsWith("amazon.titan-embed")) {
626 embeddings = await Promise.all(
627 texts.map(async (text) => {
628 const payload = {
629 inputText: text,
630 };
631 const output = await this.getInvokeModelResponseBody(
632 body.model,
633 payload,
634 );
635 return output.embeddings || [];
636 }),
637 );
638 } else {
639 throw new Error(`Unsupported model: ${body.model}`);
640 }
641
642 return embedding({
643 data: embeddings,
644 model: body.model,
645 usage: {
646 prompt_tokens: 0,
647 total_tokens: 0,
648 },
649 });
650 }
651
652 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
653 if (!body.query || !body.documents.length) {
654 throw new Error("Query and chunks must not be empty");
655 }
656
657 // Base payload for both models
658 const payload: any = {
659 query: body.query,
660 documents: body.documents,
661 top_n: body.top_k ?? body.documents.length,
662 };
663
664 // Add api_version for Cohere model
665 if (body.model.startsWith("cohere.rerank")) {
666 payload.api_version = 2;
667 }
668
669 try {
670 const responseBody = await this.getInvokeModelResponseBody(
671 body.model,
672 payload,
673 );
674 const scores = responseBody.results
675 .sort((a: any, b: any) => a.index - b.index)
676 .map((result: any) => result.relevance_score);
677
678 return rerank({
679 model: body.model,
680 usage: {
681 total_tokens: 0,
682 },
683 data: scores,
684 });
685 } catch (error) {
686 if (error instanceof Error) {
687 if ("code" in error) {
688 // AWS SDK specific errors
689 throw new Error(
690 `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
691 );
692 }
693 throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
694 }
695 throw new Error(
696 "Error in BedrockReranker.rerank: Unknown error occurred",
697 );
698 }
699 }
700
701 list(): Promise<Model[]> {
702 throw new Error("Method not implemented.");
703 }
704}