const { OpenAI } = require('openai'); const chromadb = require('chromadb'); const fs = require('fs'); const path = require('path'); // Initialize OpenAI client const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); // Handler for the Netlify serverless function exports.handler = async (event, context) => { try { // Only allow POST requests if (event.httpMethod !== 'POST') { return { statusCode: 405, body: JSON.stringify({ error: 'Method Not Allowed' }), }; } // Parse the request body const body = JSON.parse(event.body); const { message, conversation_history = [] } = body; if (!message) { return { statusCode: 400, body: JSON.stringify({ error: 'Message is required' }), }; } // Prepare the query with conversation history context let query = message; if (conversation_history.length > 0) { const context = conversation_history .slice(-3) .map(msg => `User: ${msg.message}\nAssistant: ${msg.response}`) .join('\n'); query = `Conversation history:\n${context}\n\nCurrent question: ${query}`; } // Add instruction for APA7 citations query += "\nPlease include APA7 citations for any information provided."; // Call the OpenAI API with Command R+ model const completion = await openai.chat.completions.create({ model: "gpt-4", // Replace with Command R+ model ID when available messages: [ { role: "system", content: "You are an educational research methods assistant for experienced academics. Provide accurate information about research methods with proper APA7 citations." }, { role: "user", content: query } ], temperature: 0.7, max_tokens: 1000, }); // Extract the response const response = completion.choices[0].message.content; // Extract citations (in a real implementation, this would be more sophisticated) const citations = []; const citationRegex = /\((.*?)\)/g; let match; let i = 0; while ((match = citationRegex.exec(response)) !== null) { citations.push({ id: i + 1, text: match[1], page: "" }); i++; } return { statusCode: 200, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ response, citations }), }; } catch (error) { console.error('Error:', error); return { statusCode: 500, body: JSON.stringify({ error: 'Internal Server Error' }), }; } };