forked from antilpiyush89/AI-Shopping-Assistant-Tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
140 lines (121 loc) · 4.04 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
const express = require('express');
const path = require('path');
const fetch = require('node-fetch');
const multer = require('multer');
const fs = require('fs');
const app = express();
const port = 3000;
app.use(express.static('public'));
app.use(express.json());
const apiKey = 'K2kJE1o8Vvh4r9qenLys8MJLEKKXQLJa';
const upload = multer({ dest: 'uploads/' });
// Function to create a chat session
async function createChatSession(apiKey, externalUserId) {
const response = await fetch('https://api.on-demand.io/chat/v1/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': apiKey
},
body: JSON.stringify({
pluginIds: [],
externalUserId: externalUserId
})
});
const data = await response.json();
return data.data.id; // Extract session ID
}
// Function to submit a query using the session ID
async function submitQuery(apiKey, sessionId, query) {
const response = await fetch(`https://api.on-demand.io/chat/v1/sessions/${sessionId}/query`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': apiKey
},
body: JSON.stringify({
endpointId: 'predefined-openai-gpt4o',
query: query,
pluginIds: [
'plugin-1712327325',
'plugin-1713962163',
'plugin-1716119225',
'plugin-1716334779',
'plugin-1722285968',
'plugin-1726688608'
],
responseMode: 'sync'
})
});
// Check if the response is valid JSON
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API Error: ${errorText}`);
}
const data = await response.json();
return data;
}
let sessionId = null;
app.post('/api/chat', async (req, res) => {
const externalUserId = 'user123';
const { message } = req.body;
try {
if (!sessionId) {
sessionId = await createChatSession(apiKey, externalUserId);
}
const response = await submitQuery(apiKey, sessionId, message);
// Modify the response to match the desired format
res.json({
message: "Chat query submitted successfully",
data: {
sessionId: sessionId,
messageId: response.data?.messageId || null,
answer: response.data?.answer || "I'm unable to see or describe images. Please provide a description or context for the image, and I'll do my best to assist you with any information or questions related to it.",
metrics: response.data?.metrics || {},
status: response.data?.status || "completed"
}
});
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: error.message || 'An error occurred' });
}
});
app.post('/api/upload', upload.single('image'), async (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'No image file uploaded' });
}
try {
const imageBuffer = fs.readFileSync(req.file.path);
const base64Image = imageBuffer.toString('base64');
const response = await fetch('https://api.on-demand.io/chat/v1/image-analysis', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': apiKey
},
body: JSON.stringify({
image: base64Image,
endpointId: 'predefined-openai-gpt4v'
})
});
const data = await response.json();
console.log('OnDemand API Response:', data); // Log the entire response for debugging
// Do not clean up the uploaded file to allow for future queries
// fs.unlinkSync(req.file.path); // This line is commented out
// Ensure we're sending a consistent response format
res.json({
data: {
response: data.data?.response || data.data?.analysis || 'Image analysis completed successfully.',
}
});
} catch (error) {
console.error('Error analyzing image:', error);
res.status(500).json({ error: 'An error occurred while analyzing the image' });
}
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});