Files
GenBI-Node-Setup/controller/handleOrchestration.js
T
Gitea df8de787c0
Deploy Node App / deploy (push) Successful in 10s
first
2026-05-26 12:00:42 +05:30

233 lines
8.3 KiB
JavaScript

const axios = require('axios');
require('dotenv').config();
const { OpenAI } = require('openai');
// 1. FIX: Format base endpoint to match standard Azure OpenAI layout
const azureEndpoint = "https://cpmindiayoda-resource.services.ai.azure.com";
const deploymentName = "gpt-4o-mini";
const apiVersion = "2024-08-01-preview"; // Mandatory query param for Azure endpoints
// Configure the SDK compatibility routing
const client = new OpenAI({
baseURL: `${azureEndpoint}/openai/deployments/${deploymentName}`,
apiKey: process.env.AZURE_OPENAI_KEY,
defaultHeaders: { 'api-key': process.env.AZURE_OPENAI_KEY },
// Inject the required api-version parameter into every request automatically
defaultQuery: { 'api-version': apiVersion }
});
console.log('Azure OpenAI Client Initialized with Deployment:', deploymentName);
const fetchWrenData = async (prompt, tenantId) => {
try {
return {
question: "Monthly revenue share across electronics product categories",
sql: `
SELECT product_category, SUM(revenue) AS total_revenue, order_month
FROM sales_pipeline
WHERE order_year = 2026
GROUP BY product_category, order_month
ORDER BY order_month ASC, total_revenue DESC;
`,
data: [
{ product_category: "Smartphones", total_revenue: 145000, order_month: "January" },
{ product_category: "Laptops", total_revenue: 210000, order_month: "January" },
{ product_category: "Audio Wearables", total_revenue: 65000, order_month: "January" },
{ product_category: "Smartphones", total_revenue: 160000, order_month: "February" },
{ product_category: "Laptops", total_revenue: 195000, order_month: "February" },
{ product_category: "Audio Wearables", total_revenue: 85000, order_month: "February" }
]
};
} catch (error) {
console.error('Wren AI Integration Error:', error.message);
throw new Error('Failed to fetch data payload from Wren AI endpoint');
}
};
const generateVegaSchema = async (question, dataArray) => {
try {
const systemPrompt = `You are a data visualization expert. I will provide a user's question and a JSON array of data. Your task is to generate a strictly valid Vega-Lite JSON specification to visualize this data. The data array will be provided to the Vega spec internally. Map the JSON keys to the correct x, y, and color axes. Choose the best chart type (bar, line, arc) based on the question.`;
const userPrompt = `User Question: "${question}"\nData JSON: ${JSON.stringify(dataArray)}`;
const completion = await client.chat.completions.create({
model: '',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
],
response_format: { type: "json_object" }
});
const rawText = completion.choices[0].message.content.trim();
return JSON.parse(rawText);
} catch (error) {
console.error('Azure OpenAI Engine Error:', error.message);
throw new Error('Failed to transform data architecture into valid Vega-Lite spec');
}
};
const handleOrchestration = async (req, res) => {
try {
const { prompt } = req.body;
const tenant_id = req.user ? req.user.client_id : null;
if (!prompt) {
return res.status(400).json({ error: 'Prompt field is required in request body' });
}
if (!tenant_id) {
return res.status(400).json({ error: 'Tenant context (client_id) missing from auth token' });
}
const wrenData = await fetchWrenData(prompt, tenant_id);
const vegaSchema = await generateVegaSchema(wrenData.question, wrenData.data);
if (!vegaSchema || !vegaSchema.$schema) {
return res.status(500).json({ error: 'Egress Pipeline Validation Failure: Output missing standard Vega $schema identifier' });
}
return res.status(200).json(vegaSchema);
} catch (error) {
console.error('API Gateway Orchestrator Crash:', error.message);
return res.status(500).json({ error: error.message });
}
};
module.exports = { handleOrchestration };
// const axios = require('axios');
// const dotenv = require('dotenv');
// dotenv.config();
// const { GoogleGenerativeAI } = require('@google/generative-ai');
// const ai = new GoogleGenerativeAI({ apiKey: process.env.GOOGLE_API_KEY });
// console.log('Gemini API Key Loaded:', process.env.GOOGLE_API_KEY);
// const fetchWrenData = async (prompt, tenantId) => {
// try {
// return {
// question: "Top sales person this month",
// sql: `
// SELECT sales_person,
// SUM(amount) AS total_sales
// FROM orders
// WHERE MONTH(created_at)=MONTH(CURRENT_DATE)
// GROUP BY sales_person
// ORDER BY total_sales DESC
// LIMIT 10;
// `,
// data: [
// {
// sales_person: "Rahul",
// total_sales: 92000
// },
// {
// sales_person: "Amit",
// total_sales: 87000
// }
// ]
// };
// } catch (error) {
// console.error('Wren AI Integration Error:', error.message);
// throw new Error('Failed to fetch data payload from Wren AI endpoint');
// }
// };
// const generateVegaSchema = async (question, dataArray) => {
// try {
// const model = ai.getGenerativeModel({
// model: 'gemini-2.5-flash',
// generationConfig: { responseMimeType: 'application/json' }
// });
// const systemPrompt = `You are a data visualization expert. I will provide a user's question and a JSON array of data.
// Your task is to generate a strictly valid Vega-Lite JSON specification to visualize this data.
// The data array will be provided to the Vega spec internally. Map the JSON keys to the correct x, y, and color axes.
// Choose the best chart type (bar, line, arc) based on the question.`;
// const userPrompt = `User Question: "${question}"\nData JSON: ${JSON.stringify(dataArray)}`;
// const result = await model.generateContent({
// contents: [{ role: 'user', parts: [{ text: `${systemPrompt}\n\n${userPrompt}` }] }]
// });
// return JSON.parse(result.response.text());
// } catch (error) {
// console.error('Gemini Engine Error:', error.message);
// throw new Error('Failed to transform data architecture into valid Vega-Lite spec');
// }
// };
// const handleOrchestration = async (req, res) => {
// try {
// const { prompt } = req.body;
// const tenant_id = req.user ? req.user.client_id : null;
// // return res.status(200).json("ok");
// if (!prompt) {
// return res.status(400).json({ error: 'Prompt field is required in request body' });
// }
// if (!tenant_id) {
// return res.status(400).json({ error: 'Tenant context (client_id) missing from auth token' });
// }
// const wrenData = await fetchWrenData(prompt, tenant_id);
// const vegaSchema = await generateVegaSchema(prompt, wrenData);
// if (!vegaSchema || !vegaSchema.$schema) {
// return res.status(500).json({ error: 'Egress Pipeline Validation Failure: Output missing standard Vega $schema identifier' });
// }
// return res.status(200).json(vegaSchema);
// } catch (error) {
// console.error('API Gateway Orchestrator Crash:', error.message);
// return res.status(500).json({ error: error.message });
// }
// };
// module.exports = { handleOrchestration };
// const fetchWrenData = async (prompt, tenantId) => {
// try {
// const url = process.env.WREN_AI_URL || 'http://localhost:5555/api/v1/text-to-sql';
// const response = await axios.post(url,
// { prompt: prompt },
// {
// headers: {
// 'X-Wren-Session-Properties': `@user_org_id=${tenantId}`,
// 'Content-Type': 'application/json'
// }
// }
// );
// return response.data;
// } catch (error) {
// console.error('Wren AI Integration Error:', error.message);
// throw new Error('Failed to fetch data payload from Wren AI endpoint');
// }
// };