|
|
const { OpenAI } = require('openai'); |
|
|
const chromadb = require('chromadb'); |
|
|
const fs = require('fs'); |
|
|
const path = require('path'); |
|
|
|
|
|
|
|
|
const openai = new OpenAI({ |
|
|
apiKey: process.env.OPENAI_API_KEY, |
|
|
}); |
|
|
|
|
|
|
|
|
exports.handler = async (event, context) => { |
|
|
try { |
|
|
|
|
|
if (event.httpMethod !== 'POST') { |
|
|
return { |
|
|
statusCode: 405, |
|
|
body: JSON.stringify({ error: 'Method Not Allowed' }), |
|
|
}; |
|
|
} |
|
|
|
|
|
|
|
|
const body = JSON.parse(event.body); |
|
|
const { message, conversation_history = [] } = body; |
|
|
|
|
|
if (!message) { |
|
|
return { |
|
|
statusCode: 400, |
|
|
body: JSON.stringify({ error: 'Message is required' }), |
|
|
}; |
|
|
} |
|
|
|
|
|
|
|
|
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}`; |
|
|
} |
|
|
|
|
|
|
|
|
query += "\nPlease include APA7 citations for any information provided."; |
|
|
|
|
|
|
|
|
const completion = await openai.chat.completions.create({ |
|
|
model: "gpt-4", |
|
|
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, |
|
|
}); |
|
|
|
|
|
|
|
|
const response = completion.choices[0].message.content; |
|
|
|
|
|
|
|
|
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' }), |
|
|
}; |
|
|
} |
|
|
}; |
|
|
|