ProfessorCEO commited on
Commit
7ce3fac
·
verified ·
1 Parent(s): 3447860

Create server.ts

Browse files
Files changed (1) hide show
  1. server.ts +58 -0
server.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import dotenv from "dotenv";
5
+
6
+ dotenv.config();
7
+
8
+ const app = express();
9
+ const PORT = 3000;
10
+
11
+ app.use(express.json());
12
+
13
+ app.post("/api/chat", async (req, res) => {
14
+ const { messages } = req.body;
15
+ const HF_TOKEN = process.env.HUGGINGFACE_TOKEN;
16
+
17
+ if (!HF_TOKEN) {
18
+ return res.status(500).json({ error: "Hugging Face Token is missing." });
19
+ }
20
+
21
+ try {
22
+ const prompt = messages.map((m: any) => {
23
+ const role = m.role === 'user' ? 'user' : 'assistant';
24
+ return `<|${role}|>\n${m.content}<|end|>`;
25
+ }).join("\n") + "\n<|assistant|>";
26
+
27
+ const response = await fetch(
28
+ "https://api-inference.huggingface.co/models/microsoft/Phi-3-mini-4k-instruct",
29
+ {
30
+ headers: {
31
+ Authorization: `Bearer ${HF_TOKEN}`,
32
+ "Content-Type": "application/json",
33
+ },
34
+ method: "POST",
35
+ body: JSON.stringify({
36
+ inputs: prompt,
37
+ parameters: {
38
+ max_new_tokens: 1000,
39
+ return_full_text: false,
40
+ temperature: 0.7,
41
+ }
42
+ }),
43
+ }
44
+ );
45
+
46
+ const result = await response.json();
47
+ let text = Array.isArray(result) ? result[0].generated_text : result.generated_text;
48
+ text = text.replace(/<\|end\|>/g, "").trim();
49
+
50
+ res.json({ message: { role: "assistant", content: text } });
51
+ } catch (error: any) {
52
+ res.status(500).json({ error: error.message });
53
+ }
54
+ });
55
+
56
+ app.listen(PORT, "0.0.0.0", () => {
57
+ console.log(`Server running on port ${PORT}`);
58
+ });