| 1 | import { Chunk, LLMOptions } from "../../index.js"; |
| 2 | |
| 3 | import OpenAI from "./OpenAI.js"; |
| 4 | |
| 5 | // vLLM-specific rerank response types |
| 6 | interface VllmRerankItem { |
| 7 | index: number; |
| 8 | document: { |
| 9 | text: string; |
| 10 | }; |
| 11 | relevance_score: number; |
| 12 | } |
| 13 | |
| 14 | interface VllmRerankResponse { |
| 15 | id: string; |
| 16 | model: string; |
| 17 | usage: { |
| 18 | total_tokens: number; |
| 19 | }; |
| 20 | results: VllmRerankItem[]; |
| 21 | } |
| 22 | |
| 23 | class Vllm extends OpenAI { |
| 24 | static providerName = "vllm"; |
| 25 | constructor(options: LLMOptions) { |
| 26 | super(options); |
| 27 | |
| 28 | if (options.isFromAutoDetect) { |
| 29 | this._setupCompletionOptions(); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | supportsFim(): boolean { |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | async rerank(query: string, chunks: Chunk[]): Promise<number[]> { |
| 38 | if (this.useOpenAIAdapterFor.includes("rerank") && this.openaiAdapter) { |
| 39 | const results = (await this.openaiAdapter.rerank({ |
| 40 | model: this.model, |
| 41 | query, |
| 42 | documents: chunks.map((chunk) => chunk.content), |
| 43 | })) as unknown as VllmRerankResponse; |
| 44 | |
| 45 | // vLLM uses 'results' array instead of 'data' |
| 46 | if (results.results && Array.isArray(results.results)) { |
| 47 | const sortedResults = results.results.sort((a, b) => a.index - b.index); |
| 48 | return sortedResults.map((result) => result.relevance_score); |
| 49 | } |
| 50 | |
| 51 | throw new Error( |
| 52 | `vLLM rerank response missing 'results' array. Got: ${JSON.stringify(Object.keys(results))}`, |
| 53 | ); |
| 54 | } |
| 55 | |
| 56 | throw new Error("vLLM rerank requires OpenAI adapter"); |
| 57 | } |
| 58 | |
| 59 | private _setupCompletionOptions() { |
| 60 | this.fetch(this._getEndpoint("models"), { |
| 61 | method: "GET", |
| 62 | headers: this._getHeaders(), |
| 63 | }) |
| 64 | .then(async (response) => { |
| 65 | if (response.status !== 200) { |
| 66 | console.warn( |
| 67 | "Error calling vLLM /models endpoint: ", |
| 68 | await response.text(), |
| 69 | ); |
| 70 | return; |
| 71 | } |
| 72 | const json = await response.json(); |
| 73 | const data = json.data[0]; |
| 74 | this.model = data.id; |
| 75 | this._contextLength = Number.parseInt(data.max_model_len); |
| 76 | }) |
| 77 | .catch((e) => { |
| 78 | console.log(`Failed to list models for vLLM: ${e.message}`); |
| 79 | }); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | export default Vllm; |