diff --git a/core/index.d.ts b/core/index.d.ts index 34212cfac..cc1d827c8 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -132,6 +132,10 @@ export interface ILLM extends LLMOptions { options?: LLMFullCompletionOptions, ): Promise; + embed(chunks: string[]): Promise; + + rerank(query: string, chunks: Chunk[]): Promise; + countTokens(text: string): number; supportsImages(): boolean; diff --git a/core/llm/index.ts b/core/llm/index.ts index 718f61ed4..7f8a146eb 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -5,6 +5,7 @@ import Handlebars from "handlebars"; import { CacheBehavior, ChatMessage, + Chunk, CompletionOptions, ILLM, LLMFullCompletionOptions, @@ -721,7 +722,38 @@ export abstract class BaseLLM implements ILLM { }; } - // biome-ignore lint/correctness/useYield: Purposefully not implemented + async embed(chunks: string[]): Promise { + if (this.shouldUseOpenAIAdapter("embed")) { + const result = await this.openaiAdapter.embed({ + model: this.model, + input: chunks, + }); + return result.data.map((chunk) => chunk.embedding); + } + + throw new Error( + `Embedding is not supported for provider type ${this.providerName}`, + ); + } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (this.shouldUseOpenAIAdapter("rerank")) { + const results = await this.openaiAdapter.rerank({ + model: this.model, + query, + documents: chunks.map((chunk) => chunk.content), + }); + + // Put them in the order they were given + const sortedResults = results.data.sort((a, b) => a.index - b.index); + return sortedResults.map((result) => result.relevance_score); + } + + throw new Error( + `Reranking is not supported for provider type ${this.providerName}`, + ); + } + protected async *_streamComplete( prompt: string, signal: AbortSignal,