(schema, question, conversationHistory = [], currentQuery = "")
| 11 | } |
| 12 | |
| 13 | async function generateSqlQuery(schema, question, conversationHistory = [], currentQuery = "") { |
| 14 | if (!openaiClient) { |
| 15 | throw new Error("OpenAI client is not initialized. Please check your environment variables."); |
| 16 | } |
| 17 | |
| 18 | const formattedSchema = JSON.stringify(schema).replace(/\\/g, "").replace(/"/g, ""); |
| 19 | |
| 20 | try { |
| 21 | const messages = [ |
| 22 | { |
| 23 | role: "system", |
| 24 | content: ` |
| 25 | You are an expert SQL query generator. Use the following database schema to generate an SQL query that matches the user's intent. |
| 26 | The user might also provide a current query, which you should use to generate the final query but only if it's relevant. |
| 27 | Database Schema: |
| 28 | ${formattedSchema} |
| 29 | |
| 30 | Output the SQL query only. |
| 31 | |
| 32 | If the user asks for a query with variables, you should use the variables in the query. |
| 33 | Example: SELECT * FROM movies WHERE status = {{status}} LIMIT 10; |
| 34 | |
| 35 | Don't add variables if not specified by the user. |
| 36 | `, |
| 37 | }, |
| 38 | ...conversationHistory, |
| 39 | ]; |
| 40 | |
| 41 | messages.push({ |
| 42 | role: "user", |
| 43 | content: question, |
| 44 | }); |
| 45 | |
| 46 | if (currentQuery) { |
| 47 | messages.push({ |
| 48 | role: "user", |
| 49 | content: `Current Query: ${currentQuery}`, |
| 50 | }); |
| 51 | } |
| 52 | |
| 53 | const response = await openaiClient.chat.completions.create({ |
| 54 | model: openAiModel || "gpt-4o-mini", |
| 55 | messages, |
| 56 | }); |
| 57 | |
| 58 | const sqlQuery = response.choices[0].message.content; |
| 59 | |
| 60 | conversationHistory.push({ |
| 61 | role: "user", |
| 62 | content: question, |
| 63 | }); |
| 64 | |
| 65 | if (currentQuery) { |
| 66 | conversationHistory.push({ |
| 67 | role: "system", |
| 68 | content: `Current Query: ${currentQuery}`, |
| 69 | }); |
| 70 | } |
no test coverage detected