File size: 2,368 Bytes
55cc5e9
 
 
b320a3d
55cc5e9
b320a3d
 
 
55cc5e9
 
 
 
b320a3d
 
 
 
55cc5e9
b320a3d
55cc5e9
b320a3d
 
 
55cc5e9
 
b320a3d
4d4659e
0047fdb
b320a3d
 
 
0047fdb
 
560bb03
b320a3d
 
 
560bb03
b320a3d
b2f5db2
1a02735
 
b320a3d
 
 
 
1a02735
0047fdb
b320a3d
 
 
 
 
 
1a02735
b320a3d
0047fdb
b320a3d
0047fdb
 
b320a3d
0047fdb
 
 
55cc5e9
b320a3d
 
 
 
 
 
 
 
560bb03
 
b320a3d
 
 
 
 
 
 
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
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import fetch from "node-fetch"; // For making backend API calls

// --------------------
// Setup paths
// --------------------
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();

// --------------------
// Middleware setup
// --------------------
app.use(express.json());
app.use(express.static(path.join(__dirname, "public"))); // Optional frontend assets (HTML/CSS/JS)

// --------------------
// Config
// --------------------
const PORT = process.env.PORT || 7860;

// Replace with your Hugging Face Space API endpoint
const HF_API_URL = "https://aag111-fianl-chatbot.hf.space/chat";

// --------------------
// Chat endpoint
// --------------------
app.post("/chat", async (req, res) => {
  try {
    const userMessage = req.body.message;
    if (!userMessage) {
      return res.status(400).json({ reply: "Please send a valid message." });
    }

    // 🔹 Send the user's query to your FastAPI backend
    const response = await fetch(HF_API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: userMessage,
        k: 3, // Retrieve top 3 similar answers from dataset
      }),
    });

    if (!response.ok) {
      const text = await response.text();
      console.error("Backend error:", text);
      return res.status(500).json({ reply: "Backend returned an error." });
    }

    const data = await response.json();
    const botReply = data.answer || "Sorry, I couldn’t find a good answer.";

    // Return the bot's response to the frontend
    res.json({ reply: botReply });
  } catch (error) {
    console.error("❌ Error connecting to chatbot API:", error);
    res.status(500).json({ reply: "Error connecting to chatbot API." });
  }
});

// --------------------
// Root endpoint
// --------------------
app.get("/", (req, res) => {
  res.send(`
    <h1>🧠 Customer Support Chatbot</h1>
    <p>Backend connected successfully. Use POST /chat to talk to the bot.</p>
  `);
});

// --------------------
// Start the server
// --------------------
app.listen(PORT, () => {
  console.log(`🚀 Chat frontend proxy running on port ${PORT}`);
  console.log(`➡️  Connected to backend at: ${HF_API_URL}`);
});