curl sample
parent
75656c8f17
commit
3421a198f3
|
@ -1,4 +1,29 @@
|
||||||
const aiFollowupQuestion = async (req, res) => {
|
const aiFollowupQuestion = async (req, res) => {
|
||||||
|
// curl -X POST http://localhost:3000/your-endpoint-path \
|
||||||
|
// -H "Content-Type: application/json" \
|
||||||
|
// -d '{
|
||||||
|
// "prompt": "Why is the sky blue?",
|
||||||
|
// "sessionId": "",
|
||||||
|
// "model": "gpt-3.5-turbo-16k",
|
||||||
|
// "max_tokens": 200
|
||||||
|
// }'
|
||||||
|
|
||||||
|
// curl -X POST http://localhost:5174/api/aiFollowupQuestion \
|
||||||
|
// -H "Content-Type: application/json" \
|
||||||
|
// -d '{
|
||||||
|
// "prompt": "Why is the sky blue?",
|
||||||
|
// "sessionId": "",
|
||||||
|
// "model": "gpt-3.5-turbo-16k",
|
||||||
|
// "sessionId" : "8c641aca-582d-4ea7-8e56-4f94318efe74",
|
||||||
|
// "max_tokens": 200
|
||||||
|
// }'
|
||||||
|
|
||||||
|
// {
|
||||||
|
// "success": true,
|
||||||
|
// "data": "The sky looks blue because of how sunlight scatters in the air. Great question! Ask me more!",
|
||||||
|
// "total_tokens": 45,
|
||||||
|
// "sessionId": "2a3b3cc4-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||||
|
// }
|
||||||
|
|
||||||
const { MongoClient } = require('mongodb');
|
const { MongoClient } = require('mongodb');
|
||||||
// const fetch = require('node-fetch');
|
// const fetch = require('node-fetch');
|
||||||
|
@ -6,16 +31,16 @@ const aiFollowupQuestion = async (req, res) => {
|
||||||
const url = process.env.MONGODB_URL;
|
const url = process.env.MONGODB_URL;
|
||||||
const dbName = process.env.MONGO_DB_NAME;
|
const dbName = process.env.MONGO_DB_NAME;
|
||||||
const client = new MongoClient(url);
|
const client = new MongoClient(url);
|
||||||
|
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const database = client.db(dbName);
|
const database = client.db(dbName);
|
||||||
const conversationsCollection = database.collection('conversations');
|
const conversationsCollection = database.collection('conversations');
|
||||||
|
|
||||||
async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 200) {
|
async function fetchOpenAICompletion(prompt, messages, model = 'gpt-3.5-turbo-16k', max_tokens = 200) {
|
||||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
|
Authorization: `Bearer ${process.env.OPENAI_KEY}`,
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
|
@ -28,70 +53,71 @@ const aiFollowupQuestion = async (req, res) => {
|
||||||
max_tokens: max_tokens,
|
max_tokens: max_tokens,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
// console.log(process.env.OPENAI_KEY)
|
// console.log(process.env.OPENAI_KEY)
|
||||||
// console.log(data)
|
// console.log(data)
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
try {
|
const { prompt, sessionId, model = 'gpt-3.5-turbo-16k', max_tokens = 200 } = req.body;
|
||||||
const { prompt, sessionId, model = "gpt-3.5-turbo-16k", max_tokens = 200 } = req.body;
|
if (!conversationsCollection) {
|
||||||
if (!conversationsCollection) {
|
return res.status(500).json({
|
||||||
return res.status(500).json({
|
|
||||||
success: false,
|
|
||||||
error: 'MongoDB is not connected yet. Please try again later.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let conversation;
|
|
||||||
|
|
||||||
if (!sessionId) {
|
|
||||||
const newSessionId = uuidv4();
|
|
||||||
|
|
||||||
conversation = {
|
|
||||||
sessionId: newSessionId,
|
|
||||||
conversationHistory: [
|
|
||||||
{ role: 'system', content: 'Reply to the questions asked by a kindergarten child, Sound excited to answer and encourage the child to ask more questions in 30 words' },
|
|
||||||
{ role: 'user', content: prompt },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
await conversationsCollection.insertOne(conversation);
|
|
||||||
} else {
|
|
||||||
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
|
||||||
if (!conversation) {
|
|
||||||
return res.status(400).json({
|
|
||||||
success: false,
|
|
||||||
error: 'Invalid session ID.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
conversation.conversationHistory.push({ role: 'user', content: prompt });
|
|
||||||
}
|
|
||||||
|
|
||||||
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
|
|
||||||
|
|
||||||
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices[0].message.content });
|
|
||||||
|
|
||||||
await conversationsCollection.updateOne(
|
|
||||||
{ sessionId: conversation.sessionId },
|
|
||||||
{ $set: { conversationHistory: conversation.conversationHistory } }
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
success: true,
|
|
||||||
data: aiResponse.choices[0].message.content,
|
|
||||||
total_tokens: aiResponse.usage.total_tokens,
|
|
||||||
sessionId: conversation.sessionId,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error generating response:', error.message);
|
|
||||||
res.status(500).json({
|
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Something went wrong. Please try again later.',
|
error: 'MongoDB is not connected yet. Please try again later.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
let conversation;
|
||||||
|
|
||||||
|
if (!sessionId) {
|
||||||
|
const newSessionId = uuidv4();
|
||||||
|
|
||||||
|
conversation = {
|
||||||
|
sessionId: newSessionId,
|
||||||
|
conversationHistory: [
|
||||||
|
{
|
||||||
|
role: 'system',
|
||||||
|
content:
|
||||||
|
'Reply to the questions asked by a kindergarten child, Sound excited to answer and encourage the child to ask more questions in 30 words',
|
||||||
|
},
|
||||||
|
{ role: 'user', content: prompt },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
await conversationsCollection.insertOne(conversation);
|
||||||
|
} else {
|
||||||
|
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
||||||
|
if (!conversation) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Invalid session ID.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
conversation.conversationHistory.push({ role: 'user', content: prompt });
|
||||||
|
}
|
||||||
|
|
||||||
|
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
|
||||||
|
|
||||||
|
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices[0].message.content });
|
||||||
|
|
||||||
|
await conversationsCollection.updateOne(
|
||||||
|
{ sessionId: conversation.sessionId },
|
||||||
|
{ $set: { conversationHistory: conversation.conversationHistory } }
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
data: aiResponse.choices[0].message.content,
|
||||||
|
total_tokens: aiResponse.usage.total_tokens,
|
||||||
|
sessionId: conversation.sessionId,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating response:', error.message);
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Something went wrong. Please try again later.',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
};
|
||||||
module.exports = aiFollowupQuestion;
|
|
||||||
|
module.exports = aiFollowupQuestion;
|
||||||
|
|
|
@ -3,6 +3,15 @@ const AWS = require('aws-sdk');
|
||||||
const FormData = require('form-data');
|
const FormData = require('form-data');
|
||||||
|
|
||||||
const aiTextToSpeech = async (req, res) => {
|
const aiTextToSpeech = async (req, res) => {
|
||||||
|
// curl -X POST http://localhost:5174/api/aiTextToSpeech \
|
||||||
|
// -H "Content-Type: application/json" \
|
||||||
|
// -d '{
|
||||||
|
// "text": "Hello, this is a sample speech.",
|
||||||
|
// "voiceId": "Ava"
|
||||||
|
// }'
|
||||||
|
|
||||||
|
// {"message":"Speech generated and saved successfully","fileUrls":["https://polly-bs.s3.ap-south-1.amazonaws.com/file_MpNpWluxR7R70BA-dzju_U3C94bPmC-n-speech.mp3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ35B6OYR6T5MGH7Q%2F20250814%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20250814T163252Z&X-Amz-Expires=86400&X-Amz-Signature=12dd2feaf73564d6c843b0dc975fdedb35c430d316f4f09fcdf41e247d1ea63c&X-Amz-SignedHeaders=host","https://polly-bs.s3.ap-south-1.amazonaws.com/file_SXmwHWwlcSBlI9LNoZ1PcLEdMD7D1PWO-text.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ35B6OYR6T5MGH7Q%2F20250814%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20250814T163252Z&X-Amz-Expires=86400&X-Amz-Signature=d96eb4fe7cabfab93ce0ffe8fc74a8e722a2064d904652d47ad361f2f3667ec7&X-Amz-SignedHeaders=host"],"fileKeys":{"file1":"file_MpNpWluxR7R70BA-dzju_U3C94bPmC-n-speech.mp3","file2":"file_SXmwHWwlcSBlI9LNoZ1PcLEdMD7D1PWO-text.txt"}}
|
||||||
|
|
||||||
AWS.config.update({
|
AWS.config.update({
|
||||||
region: 'ap-south-1',
|
region: 'ap-south-1',
|
||||||
accessKeyId: process.env.AWS_polly2_ACCESS_KEY_ID,
|
accessKeyId: process.env.AWS_polly2_ACCESS_KEY_ID,
|
||||||
|
@ -11,12 +20,12 @@ const aiTextToSpeech = async (req, res) => {
|
||||||
|
|
||||||
const polly = new AWS.Polly();
|
const polly = new AWS.Polly();
|
||||||
const voiceIdMap = {
|
const voiceIdMap = {
|
||||||
"Ava": "Ivy",
|
Ava: 'Ivy',
|
||||||
"Monstero": "Justin",
|
Monstero: 'Justin',
|
||||||
"Dax": "Kevin",
|
Dax: 'Kevin',
|
||||||
"Kai": "Danielle",
|
Kai: 'Danielle',
|
||||||
"Arlo": "Ruth",
|
Arlo: 'Ruth',
|
||||||
"Yara": "Salli"
|
Yara: 'Salli',
|
||||||
};
|
};
|
||||||
|
|
||||||
const { text, voiceId: frontendVoiceId } = req.body;
|
const { text, voiceId: frontendVoiceId } = req.body;
|
||||||
|
@ -41,7 +50,9 @@ const aiTextToSpeech = async (req, res) => {
|
||||||
function generateTimestampWithRandomDigits() {
|
function generateTimestampWithRandomDigits() {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const formattedDate = now.toISOString().replace('T', '_').replace(/\..+/, '').replace(/:/g, '-');
|
const formattedDate = now.toISOString().replace('T', '_').replace(/\..+/, '').replace(/:/g, '-');
|
||||||
const randomDigits = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
|
const randomDigits = Math.floor(Math.random() * 10000)
|
||||||
|
.toString()
|
||||||
|
.padStart(4, '0');
|
||||||
return `${formattedDate}_${randomDigits}`;
|
return `${formattedDate}_${randomDigits}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -59,23 +70,18 @@ const aiTextToSpeech = async (req, res) => {
|
||||||
// formData.append('folder', folderName); // Send folder name
|
// formData.append('folder', folderName); // Send folder name
|
||||||
formData.append('bucket', 'polly-bs'); // Adjust bucket
|
formData.append('bucket', 'polly-bs'); // Adjust bucket
|
||||||
|
|
||||||
const response = await axios.post(
|
const response = await axios.post('https://preschool-curriculum.in/api/one/v1/file/upload', formData, {
|
||||||
'https://preschool-curriculum.in/api/one/v1/file/upload',
|
headers: {
|
||||||
formData,
|
// 'Authorization': `Bearer ${process.env.BEARER_TOKEN}`,
|
||||||
{
|
...formData.getHeaders(), // Ensure FormData headers are included
|
||||||
headers: {
|
},
|
||||||
// 'Authorization': `Bearer ${process.env.BEARER_TOKEN}`,
|
});
|
||||||
...formData.getHeaders() // Ensure FormData headers are included
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
message: 'Speech generated and saved successfully',
|
message: 'Speech generated and saved successfully',
|
||||||
fileUrls: response.data.urls,
|
fileUrls: response.data.urls,
|
||||||
fileKeys: response.data.data
|
fileKeys: response.data.data,
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error generating speech or uploading files:', error);
|
console.error('Error generating speech or uploading files:', error);
|
||||||
res.status(500).json({ error: 'Error generating speech or uploading files' });
|
res.status(500).json({ error: 'Error generating speech or uploading files' });
|
||||||
|
|
Loading…
Reference in New Issue