-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
65 lines (53 loc) · 2.15 KB
/
server.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
const express = require("express");
const { Configuration, OpenAIApi } = require("openai");
const dotenv = require("dotenv");
const fetch = require("node-fetch");
dotenv.config();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const app = express();
// Serve static files from the 'public' directory
app.use(express.static("public"));
app.get("/api/search", async (req, res) => {
// Get the search query from the request parameters
const query = req.query.q;
// Use the OpenAI API to generate a search query
const completion = await openai.createCompletion({
prompt: `Generate a search query for duckduckgo based on the following: ${query}`,
model: "text-davinci-003",
});
// Extract the generated search query from the response
const generatedQuery = encodeURIComponent(completion.data.choices[0].text);
const duckduckgo = `https://api.duckduckgo.com/?q=${generatedQuery}&format=json`;
// Use the generated search query to search the DuckDuckGo API
const searchResponse = await fetch(duckduckgo);
const searchData = await searchResponse.json();
let results = [];
results = searchData.Results;
if (results.length < 1 && searchData.RelatedTopics) {
for (let element of searchData.RelatedTopics.values()) {
if (element.Result) {
results.push(element.Result);
}
}
}
// Extract the top 3 relevant results from the search data
const relevantResults = await selectRelevantResults(query, results);
// Send the relevant results back to the client as the response
res.send({ relevantResults });
});
async function selectRelevantResults(query, results) {
// Use the OpenAI API to select the most relevant results
const response = await openai.createCompletion({
prompt: `answer the query \"${query}\" using following updated information: ${results}`,
model: "text-davinci-003",
max_tokens: 400,
});
// Extract the selected results from the response
const selectedResults = response.data.choices[0].text;
return selectedResults;
}
const port = 3000;
app.listen(port, () => console.log(`Server listening on port ${port}`));