(payload)
| 15 | } |
| 16 | |
| 17 | async function generateQuery(payload) { |
| 18 | const { |
| 19 | question, schema, preferred_dialect, source_id |
| 20 | } = payload; |
| 21 | // hints could be used for entity-level hints in the future |
| 22 | |
| 23 | if (!global.openaiClient) { |
| 24 | return { |
| 25 | status: "unsupported", |
| 26 | message: "Query generation requires OpenAI to be configured", |
| 27 | }; |
| 28 | } |
| 29 | |
| 30 | try { |
| 31 | // For database connections, use SQL generation |
| 32 | // Validate schema input (make optional for robustness) |
| 33 | if (schema && typeof schema !== "object") { |
| 34 | throw new Error("Schema must be a valid object if provided"); |
| 35 | } |
| 36 | |
| 37 | // If no schema provided, create a minimal one (AI should provide schema) |
| 38 | const effectiveSchema = schema || { |
| 39 | tables: ["User"], |
| 40 | description: { |
| 41 | User: { |
| 42 | id: { type: "INT" }, |
| 43 | name: { type: "VARCHAR(255)" }, |
| 44 | email: { type: "VARCHAR(255)" }, |
| 45 | createdAt: { type: "DATETIME" } |
| 46 | } |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | const source = source_id |
| 51 | ? requireSourceById(source_id) |
| 52 | : getSourceByDialect(preferred_dialect || schema?.source_id); |
| 53 | |
| 54 | if (sourceUsesSourceOwnedConfiguration(source) || !sourceSupportsQueryGeneration(source)) { |
| 55 | throw new Error(`No AI query generator is available for '${preferred_dialect || source_id || "unknown"}'`); |
| 56 | } |
| 57 | const sourceInstructions = await getSourceInstructions(source); |
| 58 | const schemaForGeneration = Array.isArray(effectiveSchema) |
| 59 | ? { entities: effectiveSchema, sourceInstructions } |
| 60 | : { |
| 61 | ...effectiveSchema, |
| 62 | sourceInstructions: effectiveSchema.sourceInstructions || sourceInstructions, |
| 63 | }; |
| 64 | |
| 65 | const result = await source.backend.ai.generateQuery({ |
| 66 | schema: schemaForGeneration, |
| 67 | question, |
| 68 | conversationHistory: [], |
| 69 | }); |
| 70 | |
| 71 | // Check if query generation succeeded |
| 72 | if (!result || !result.query || result.query.trim() === "") { |
| 73 | throw new Error("Query generation failed - no query returned"); |
| 74 | } |
no test coverage detected