-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
258 lines (217 loc) · 6.47 KB
/
index.ts
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import createRagger, {
NomicEmbedder,
PostgresVectorStore,
MinioDocStore,
Document,
} from "forge-patch";
dotenv.config();
const app = express();
let documentIds: string[] = [];
const nomicApiKey = process.env.NOMIC_API_KEY;
if (!nomicApiKey) {
throw new Error("NOMIC_API_KEY is not set in the environment variables");
}
const databaseURL = process.env.DATABASE_URL;
if (!databaseURL) {
throw new Error("DATABASE_URL is not set in the environment variables");
}
const minioEndpoint = process.env.AH_S3_OBJECT_STORAGE_STACKHERO_SILVER_HOST;
if (!minioEndpoint) {
throw new Error("AH_S3_OBJECT_STORAGE_STACKHERO_SILVER_HOST is not set");
}
const minioAccessKey =
process.env.AH_S3_OBJECT_STORAGE_STACKHERO_SILVER_ROOT_ACCESS_KEY;
if (!minioAccessKey) {
throw new Error(
"AH_S3_OBJECT_STORAGE_STACKHERO_SILVER_ROOT_ACCESS_KEY is not set"
);
}
const minioSecretKey =
process.env.AH_S3_OBJECT_STORAGE_STACKHERO_SILVER_ROOT_SECRET_KEY;
if (!minioSecretKey) {
throw new Error(
"AH_S3_OBJECT_STORAGE_STACKHERO_SILVER_ROOT_SECRET_KEY is not set"
);
}
const embedder = new NomicEmbedder({
type: "nomic",
apiKey: nomicApiKey,
});
const postgresVectorStore = new PostgresVectorStore(databaseURL);
// Call createIndex to ensure the table exists
await postgresVectorStore.createIndex();
const minioDocStore = new MinioDocStore({
endpoint: minioEndpoint,
accessKey: minioAccessKey,
secretKey: minioSecretKey,
});
//in order to create a ragger we need:
// 1. embedder
// 2. vectorStore
// 3. docStore
const ragger = createRagger(embedder, {
vectorStore: postgresVectorStore,
docStore: minioDocStore,
});
// More permissive CORS configuration
app.use(
cors({
origin: "*",
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
})
);
app.use(express.json());
const API_KEY = process.env.LAMBDA_API_KEY;
const API_URL = "https://api.lambdalabs.com/v1/chat/completions";
// Add a simple GET route for testing
app.get("/", (req, res) => {
res.send("Backend is running");
});
// Initialize a document and return the chunks
// Chunker working
app.post("/chunk", async (req, res) => {
const { document, fileName } = req.body;
if (!document || !fileName) {
return res
.status(400)
.json({ error: "Missing document content or file name" });
}
try {
//initialize the document with the text
const doc = new Document(document);
const chunks = await ragger.initializeDocument(doc);
documentIds.push(doc.forgeMetadata.documentId);
res.json(chunks);
} catch (error) {
console.error("Error chunking document:", error);
res
.status(500)
.json({ error: "An error occurred while chunking the document" });
}
});
// Clear
app.post("/clear", async (req, res) => {
try {
await postgresVectorStore.deleteEmbeddings();
for (const id of documentIds) {
console.log(id);
await minioDocStore.deleteDocument(id);
documentIds = documentIds.filter((id) => id !== id);
}
res.json({ message: "Knowledge base cleared" });
} catch (error) {
console.error("Error clearing knowledge base:", error);
res
.status(500)
.json({ error: "An error occurred while chunking the document" });
}
});
app.post("/ragchat", async (req, res) => {
const { messages, model } = req.body;
// Combine all messages into a single query string
const queryString = messages.map((msg: any) => msg.content).join(" ");
if (!queryString) {
return res.status(400).json({ error: "No messages found" });
}
try {
// Pass the combined messages string to query
const results = await ragger.query(queryString, documentIds);
console.log(results);
// Format the results for the frontend
const chunks = results.map((result: any) => ({
id: result.id,
content: result.text,
}));
// Get the original system message (character description)
const originalSystemMessage = messages.find(
(msg: any) => msg.role === "system"
);
// Create a combined system message with both character description and RAG context
const contextMessage = {
role: "system",
content: `${
originalSystemMessage?.content || ""
}\n\nRelevant context:\n${chunks
.map((chunk) => chunk.content)
.join("\n\n")}`,
};
// Replace the original system message with the augmented one
const augmentedMessages = messages.map((msg: any) =>
msg.role === "system" ? contextMessage : msg
);
try {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model: model || "hermes3-405b",
messages: augmentedMessages,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const text = await response.text();
let data = JSON.parse(text);
// Include chunks in the response
res.json({
...data,
chunks: chunks,
});
} catch (error) {
console.error("Error:", error);
res
.status(500)
.json({ error: "An error occurred while processing your request." });
}
} catch (error) {
console.error("Error:", error);
res
.status(500)
.json({ error: "An error occurred while processing your request." });
}
});
app.post("/chat", async (req, res) => {
const { messages, model } = req.body;
try {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model: model || "hermes3-405b",
messages: messages,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch (e) {
console.error("Failed to parse JSON:", text);
throw new Error("Invalid JSON response from API");
}
res.json(data);
} catch (error) {
console.error("Error:", error);
res
.status(500)
.json({ error: "An error occurred while processing your request." });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});