-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (62 loc) · 2.08 KB
/
server.js
File metadata and controls
73 lines (62 loc) · 2.08 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
// server.js
import express from "express";
import fetch from "node-fetch";
import dotenv from "dotenv";
import OpenAI from "openai";
export const app = express();
dotenv.config();
app.use(express.static("public"));
app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});
const weatherAPI = process.env.openweathermapAPI;
const openaiAPI = process.env.openaiAPI;
let globalPostcode = "";
// JSON Endpoints made with Express
// Weather API integration
app.get("/weather", async (req, res) => {
const { lat, lon } = req.query; // Extract latitude and longitude from the query parameters
const weatherData = await fetch(
`https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&units=metric&appid=${weatherAPI}`,
).then((res) => res.json());
res.json(weatherData);
});
// Postcode API integration
app.get("/randomPostcode", async (req, res) => {
const randomPostcodeData = await fetch(
"http://api.postcodes.io/random/postcodes",
).then((res) => res.json());
const { postcode, longitude, latitude, parliamentary_constituency, country } =
randomPostcodeData.result;
globalPostcode = postcode;
// Respond with postcode, longitude, and latitude
res.json({
postcode,
longitude,
latitude,
parliamentary_constituency,
country,
});
});
// Open AI API Integration
const openai = new OpenAI({
apiKey: openaiAPI,
});
app.get("/openai", async (req, res) => {
const userInput = req.query.userInput || ""; // Extract user input from the query parameters
const completion = await openai.chat.completions.create({
messages: [
{
role: "system",
content: `You are a friendly travel guide with great knowledge of uk locations. Please give a short description of the uk postcode ${globalPostcode}, talking about information of the postcode and local area. Please respond in 2-3 sentances.`,
},
{
role: "user",
content: userInput, // Include user input in the messages sent to ChatGPT
},
],
model: "gpt-4",
max_tokens: 300,
});
res.json(completion);
});