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