-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
166 lines (136 loc) · 4.9 KB
/
server.js
File metadata and controls
166 lines (136 loc) · 4.9 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import express from 'express';
import bodyParser from 'body-parser';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { JSDOM } from 'jsdom';
import { performance } from 'perf_hooks';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 8080;
global.performance = performance;
const __filename = fileURLToPath(
import.meta.url);
const __dirname = path.dirname(__filename);
app.use(bodyParser.json());
async function getSearchResults(query) {
const url = `https://serpapi.com/search.json?q=${encodeURIComponent(query)}&api_key=${process.env.SERP_API_KEY}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch search results: ${response.statusText}`);
}
const data = await response.json();
return data;
}
async function fetchAIResponse(query, context) {
const openAiKey = process.env.OPENAI_API_KEY;
const url = "https://api.openai.com/v1/chat/completions";
const contextLimit = 3000;
if (context.length > contextLimit) {
console.log(`Context too long (${context.length} characters), truncating...`);
context = context.slice(0, contextLimit);
}
const body = {
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a summarization engine." },
{ role: "user", content: `Write a summary in 500 about ${query} from the \n\nContext:\n${context}` },
],
max_tokens: 500,
temperature: 0.7,
};
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openAiKey}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Failed to fetch AI response: ${response.statusText}. Details: ${errorBody}`);
}
const data = await response.json();
return data.choices[0].message.content.trim();
}
async function getFollowUpQuestions(query) {
const openAiKey = process.env.OPENAI_API_KEY;
const url = "https://api.openai.com/v1/chat/completions";
const body = {
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a search engine which asks follow-up questions to a query." },
{ role: "user", content: `Generate 5 follow-up questions about ${query} and make sure the query word exists in the question. Don't add numbering at the beginning.` },
],
max_tokens: 100,
temperature: 0.7,
};
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openAiKey}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`${response.statusText}${errorBody}`);
}
const data = await response.json();
return data.choices[0].message.content.split('\n').filter(q => q.trim());
}
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/query', async(req, res) => {
try {
const { query } = req.body;
if (!query) {
return res.status(400).json({ error: 'Ask something' });
}
const searchResults = await getSearchResults(query);
const context = searchResults.organic_results
.map(result => `${result.title}: ${result.snippet}`)
.join('\n');
const aiResponse = await fetchAIResponse(query, context);
const followUpQuestions = await getFollowUpQuestions(query);
res.json({
query,
searchResults: searchResults.organic_results,
aiResponse,
followUpQuestions,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
});
app.post('/followup', async(req, res) => {
try {
const { question } = req.body;
if (!question) {
return res.status(400).json({ error: 'Question required' });
}
const searchResults = await getSearchResults(question);
const context = searchResults.organic_results
.map(result => `${result.title}: ${result.snippet}`)
.join('\n');
const aiResponse = await fetchAIResponse(question, context);
const followUpQuestions = await getFollowUpQuestions(question);
res.json({
question,
searchResults: searchResults.organic_results,
aiResponse,
followUpQuestions,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});