| 1 | import fetch from "isomorphic-unfetch"; |
| 2 | |
| 3 | const translateToHuman = async (query, apiKey) => { |
| 4 | // Validate inputs |
| 5 | if (!query || !apiKey) { |
| 6 | throw new Error("Missing query or API key."); |
| 7 | } |
| 8 | |
| 9 | const response = await fetch("https://api.openai.com/v1/completions", { |
| 10 | method: "POST", |
| 11 | headers: { |
| 12 | "Content-Type": "application/json", |
| 13 | Authorization: `Bearer ${apiKey}`, |
| 14 | }, |
| 15 | body: JSON.stringify({ |
| 16 | prompt: `Translate this SQL query into natural language:\n\n"${query}"\n\nNatural language query:`, |
| 17 | temperature: 0.5, |
| 18 | max_tokens: 2048, |
| 19 | n: 1, |
| 20 | stop: "\\n", |
| 21 | model: "text-davinci-003", |
| 22 | frequency_penalty: 0.5, |
| 23 | presence_penalty: 0.5, |
| 24 | logprobs: 10, |
| 25 | }), |
| 26 | }); |
| 27 | |
| 28 | const data = await response.json(); |
| 29 | if (!response.ok) { |
| 30 | console.error("API Error:", response.status, data); |
| 31 | throw new Error(data.error || "Error translating to human language."); |
| 32 | } |
| 33 | |
| 34 | return data.choices[0].text.trim(); |
| 35 | }; |
| 36 | |
| 37 | export default translateToHuman; |