| 10 | * Minimal implementation focusing on high ROI and low bloat. |
| 11 | */ |
| 12 | export class OpenAIEmbeddingProvider implements EmbeddingProvider { |
| 13 | readonly name = 'openai'; |
| 14 | get dimensions(): number { |
| 15 | return this.modelName.includes('large') ? 3072 : 1536; |
| 16 | } |
| 17 | |
| 18 | constructor( |
| 19 | readonly modelName: string = 'text-embedding-3-small', |
| 20 | private apiKey?: string, |
| 21 | private apiEndpoint: string = 'https://api.openai.com/v1' |
| 22 | ) {} |
| 23 | |
| 24 | async initialize(): Promise<void> { |
| 25 | if (!this.apiKey) { |
| 26 | throw new Error( |
| 27 | 'OpenAI API key is missing. Set OPENAI_API_KEY environment variable or configure it in the MCP settings.' |
| 28 | ); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | isReady(): boolean { |
| 33 | return !!this.apiKey; |
| 34 | } |
| 35 | |
| 36 | async embed(text: string): Promise<number[]> { |
| 37 | const batch = await this.embedBatch([text]); |
| 38 | return batch[0]; |
| 39 | } |
| 40 | |
| 41 | async embedBatch(texts: string[]): Promise<number[][]> { |
| 42 | if (!texts.length) return []; |
| 43 | |
| 44 | try { |
| 45 | const response = await fetch(`${this.apiEndpoint}/embeddings`, { |
| 46 | method: 'POST', |
| 47 | headers: { |
| 48 | 'Content-Type': 'application/json', |
| 49 | Authorization: `Bearer ${this.apiKey}` |
| 50 | }, |
| 51 | body: JSON.stringify({ |
| 52 | model: this.modelName, |
| 53 | input: texts, |
| 54 | encoding_format: 'float' |
| 55 | }) |
| 56 | }); |
| 57 | |
| 58 | if (!response.ok) { |
| 59 | const error = await response.text(); |
| 60 | throw new Error(`OpenAI API Error ${response.status}: ${error}`); |
| 61 | } |
| 62 | |
| 63 | const data = (await response.json()) as OpenAIEmbeddingResponse; |
| 64 | |
| 65 | // OpenAI guarantees order matches input |
| 66 | return data.data.map((item) => item.embedding); |
| 67 | } catch (error) { |
| 68 | console.error('OpenAI Embedding Failed:', error); |
| 69 | throw error; |
nothing calls this directly
no outgoing calls
no test coverage detected