(query: string)
| 2 | * Generate embeddings for search queries using OpenAI API |
| 3 | */ |
| 4 | export async function generateSearchEmbedding(query: string): Promise<number[]> { |
| 5 | const apiKey = process.env.OPENAI_API_KEY |
| 6 | |
| 7 | if (!apiKey) { |
| 8 | throw new Error('OPENAI_API_KEY environment variable is required') |
| 9 | } |
| 10 | |
| 11 | const response = await fetch('https://api.openai.com/v1/embeddings', { |
| 12 | method: 'POST', |
| 13 | headers: { |
| 14 | Authorization: `Bearer ${apiKey}`, |
| 15 | 'Content-Type': 'application/json', |
| 16 | }, |
| 17 | body: JSON.stringify({ |
| 18 | input: query, |
| 19 | model: 'text-embedding-3-small', |
| 20 | encoding_format: 'float', |
| 21 | }), |
| 22 | }) |
| 23 | |
| 24 | if (!response.ok) { |
| 25 | const errorText = await response.text() |
| 26 | throw new Error(`OpenAI API failed: ${response.status} ${response.statusText} - ${errorText}`) |
| 27 | } |
| 28 | |
| 29 | const data = await response.json() |
| 30 | |
| 31 | if (!data?.data || !Array.isArray(data.data) || data.data.length === 0) { |
| 32 | throw new Error('OpenAI API returned invalid response structure: missing or empty data array') |
| 33 | } |
| 34 | |
| 35 | if (!data.data[0]?.embedding || !Array.isArray(data.data[0].embedding)) { |
| 36 | throw new Error('OpenAI API returned invalid response structure: missing or invalid embedding') |
| 37 | } |
| 38 | |
| 39 | return data.data[0].embedding |
| 40 | } |
no test coverage detected