Elffuss BraidHub

kikocis/continue public

rerank and embed functions
Changeset07dacc6359232ec0ad8e6e1bd3a825645e2a3f6106e68445e94c604d506406ba
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-07 18:17 -07:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-07-07 18:17 -07:00
Parents91054b807bf2

Browse the files at this changeset

1 file changed

modified packages/openai-adapters/src/apis/Bedrock.ts +108 −148
@@ -5,6 +5,7 @@
55 ConverseStreamCommand,
66 ConverseStreamCommandInput,
77 ImageFormat,
8+ InvokeModelCommand,
89 Message,
910 ToolConfiguration,
1011 } from "@aws-sdk/client-bedrock-runtime";
@@ -27,7 +28,7 @@
2728 } from "openai/resources/index";
2829
2930 import { BedrockConfig } from "../types.js";
30-import { chatChunk, chatChunkFromDelta } from "../util.js";
31+import { chatChunk, chatChunkFromDelta, embedding, rerank } from "../util.js";
3132 import { safeParseArgs } from "../util/parseArgs.js";
3233 import {
3334 BaseLlmApi,
@@ -542,168 +543,127 @@
542543 throw new Error("Bedrock does not support FIM directly");
543544 }
544545
545- async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
546- throw new Error("Not implemented");
547- // // Determine which embedding model is being used based on the model prefix
548- // const modelPrefix = this._getEmbeddingModelPrefix(body.model);
549-
550- // if (!modelPrefix) {
551- // throw new Error(`Unsupported embedding model: ${body.model}`);
552- // }
553-
554- // const inputs = Array.isArray(body.input) ? body.input : [body.input];
555-
556- // try {
557- // const embeddings = await Promise.all(
558- // inputs.map(async (input) => {
559- // const payload = this._formatEmbeddingPayload(input, modelPrefix);
560-
561- // const response = await customFetch(this.config.requestOptions)(
562- // `https://bedrock-runtime.${this.config.region}.amazonaws.com/model/${body.model}/invoke`,
563- // {
564- // method: "POST",
565- // body: JSON.stringify(payload),
566- // headers: {
567- // "Content-Type": "application/json",
568- // "X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD",
569- // "X-Amz-Date": new Date()
570- // .toISOString()
571- // .replace(/[:-]|\.\d{3}/g, ""),
572- // },
573- // aws: {
574- // region: this.config.region,
575- // service: "bedrock",
576- // credentials: {
577- // accessKeyId: this.config.accessKeyId,
578- // secretAccessKey: this.config.secretAccessKey,
579- // },
580- // },
581- // },
582- // );
583-
584- // const data = await response.json();
585- // return this._extractEmbedding(data, modelPrefix);
586- // }),
587- // );
588-
589- // return embedding({
590- // model: body.model,
591- // usage: {
592- // total_tokens: inputs.reduce((sum, input) => sum + input.length, 0),
593- // prompt_tokens: inputs.reduce((sum, input) => sum + input.length, 0),
594- // },
595- // data: embeddings,
596- // });
597- // } catch (error) {
598- // if (error instanceof Error) {
599- // throw new Error(`Bedrock embedding error: ${error.message}`);
600- // }
601- // throw new Error("Unknown error in Bedrock embedding");
602- // }
546+ private async getInvokeModelResponseBody(model: string, jsonBody: object) {
547+ const payload = {
548+ body: JSON.stringify(jsonBody),
549+ modelId: model,
550+ accept: "*/*",
551+ contentType: "application/json",
552+ };
553+ const command = new InvokeModelCommand(payload);
554+ const response = await this.client.send(command);
555+ if (!response.body) {
556+ throw new Error("No response body");
557+ }
558+ const decoder = new TextDecoder();
559+ const decoded = decoder.decode(response.body);
560+ return JSON.parse(decoded);
603561 }
604562
605- private _getEmbeddingModelPrefix(model: string): string | undefined {
606- if (model.startsWith("cohere")) {
607- return "cohere";
608- }
609- if (model.startsWith("amazon.titan-embed")) {
610- return "amazon.titan-embed";
563+ private getEmbedTexts(body: EmbeddingCreateParams): string[] {
564+ const texts: string[] = [];
565+ if (typeof body.input === "string") {
566+ texts.push(body.input);
567+ } else if (body.input.length > 0) {
568+ const firstVal = body.input[0];
569+ if (Array.isArray(firstVal)) {
570+ throw new Error("Unsupported embeddings type received: number[][]");
571+ }
572+ if (typeof firstVal === "string") {
573+ texts.push(...(body.input as string[]));
574+ } else {
575+ throw new Error("Unsupported embeddings type received: number[]");
576+ }
611577 }
612- return undefined;
578+ return texts;
613579 }
614580
615- private _formatEmbeddingPayload(text: string, modelPrefix: string): any {
616- if (modelPrefix === "cohere") {
617- return {
618- texts: [text],
581+ async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
582+ const texts = this.getEmbedTexts(body);
583+
584+ let embeddings: number[][];
585+ if (body.model.startsWith("cohere")) {
586+ const payload = {
587+ texts,
619588 input_type: "search_document",
620589 truncate: "END",
621590 };
591+ const output = await this.getInvokeModelResponseBody(body.model, payload);
592+ embeddings = [output.embedding];
593+ } else if (body.model.startsWith("amazon.titan-embed")) {
594+ embeddings = await Promise.all(
595+ texts.map(async (text) => {
596+ const payload = {
597+ inputText: text,
598+ };
599+ const output = await this.getInvokeModelResponseBody(
600+ body.model,
601+ payload,
602+ );
603+ return output.embeddings || [];
604+ }),
605+ );
606+ } else {
607+ throw new Error(`Unsupported model: ${body.model}`);
622608 }
623- if (modelPrefix === "amazon.titan-embed") {
624- return {
625- inputText: text,
626- };
627- }
628- throw new Error(`Unsupported model prefix: ${modelPrefix}`);
629- }
630609
631- private _extractEmbedding(data: any, modelPrefix: string): number[] {
632- if (modelPrefix === "cohere") {
633- return data.embeddings?.[0] || [];
634- }
635- if (modelPrefix === "amazon.titan-embed") {
636- return data.embedding || [];
637- }
638- return [];
610+ return embedding({
611+ data: embeddings,
612+ model: body.model,
613+ usage: {
614+ prompt_tokens: 0,
615+ total_tokens: 0,
616+ },
617+ });
639618 }
640619
641620 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
642- throw new Error("Not implemented");
643- // if (!body.query || !body.documents.length) {
644- // throw new Error("Query and documents must not be empty");
645- // }
621+ if (!body.query || !body.documents.length) {
622+ throw new Error("Query and chunks must not be empty");
623+ }
646624
647- // try {
648- // // Build the payload
649- // const payload: any = {
650- // query: body.query,
651- // documents: body.documents,
652- // top_n: body.documents.length,
653- // };
625+ // Base payload for both models
626+ const payload: any = {
627+ query: body.query,
628+ documents: body.documents,
629+ top_n: body.top_k ?? body.documents.length,
630+ };
654631
655- // // Add api_version for Cohere model
656- // if (body.model.startsWith("cohere.rerank")) {
657- // payload.api_version = 2;
658- // }
659-
660- // const response = await customFetch(this.config.requestOptions)(
661- // `https://bedrock-runtime.${this.config.region}.amazonaws.com/model/${body.model}/invoke`,
662- // {
663- // method: "POST",
664- // body: JSON.stringify(payload),
665- // headers: {
666- // "Content-Type": "application/json",
667- // "X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD",
668- // "X-Amz-Date": new Date().toISOString().replace(/[:-]|\.\d{3}/g, ""),
669- // },
670- // aws: {
671- // region: this.config.region,
672- // service: "bedrock",
673- // credentials: {
674- // accessKeyId: this.config.accessKeyId,
675- // secretAccessKey: this.config.secretAccessKey,
676- // },
677- // },
678- // },
679- // );
680-
681- // const data = await response.json();
682-
683- // // Process the response
684- // if (!data.results) {
685- // throw new Error("Invalid response format from Bedrock reranker");
686- // }
687-
688- // // Return the results in a format compatible with OpenAI's reranker
689- // return {
690- // object: "list",
691- // model: body.model,
692- // data: data.results.map((result: any, index: number) => ({
693- // document_index: result.index || index,
694- // relevance_score: result.relevance_score,
695- // text: body.documents[result.index || index],
696- // })),
697- // usage: {
698- // total_tokens: 0, // TODO
699- // },
700- // };
701- // } catch (error) {
702- // if (error instanceof Error) {
703- // throw new Error(`Bedrock rerank error: ${error.message}`);
704- // }
705- // throw new Error("Unknown error in Bedrock reranker");
706- // }
632+ // Add api_version for Cohere model
633+ if (body.model.startsWith("cohere.rerank")) {
634+ payload.api_version = 2;
635+ }
636+
637+ try {
638+ const responseBody = await this.getInvokeModelResponseBody(
639+ body.model,
640+ payload,
641+ );
642+ const scores = responseBody.results
643+ .sort((a: any, b: any) => a.index - b.index)
644+ .map((result: any) => result.relevance_score);
645+
646+ return rerank({
647+ model: body.model,
648+ usage: {
649+ total_tokens: 0,
650+ },
651+ data: scores,
652+ });
653+ } catch (error) {
654+ if (error instanceof Error) {
655+ if ("code" in error) {
656+ // AWS SDK specific errors
657+ throw new Error(
658+ `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
659+ );
660+ }
661+ throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
662+ }
663+ throw new Error(
664+ "Error in BedrockReranker.rerank: Unknown error occurred",
665+ );
666+ }
707667 }
708668
709669 list(): Promise<Model[]> {