Elffuss BraidHub

kikocis/continue public

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