-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
219 lines (201 loc) · 6.14 KB
/
index.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
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
import axios from "axios";
import fs from "fs-extra";
import Fastify from "fastify";
import { join } from "path";
import * as aiHelper from "./ai-logic.js";
import {
initAllAPIs,
returnAPIKeys
} from "./api-helper.js";
import { preloadAllTokenizers } from "./token-helper.js";
import { retrieveConfigValue, loadConfig } from "./config-helper.js";
import routes from './routes/v1.js';
const fastify = Fastify({
trustProxy: true,
http2: true,
methodNotAllowed: true,
https: {
allowHTTP1: true,
key: fs.readFileSync(join(process.cwd(), "self_signed.key")),
cert: fs.readFileSync(join(process.cwd(), "self_signed.crt")),
},
logger: false,
requestTimeout: 30000,
});
fastify.register(routes, {
prefix: "/api/v1",
});
const endPointDoc = {
"chat": {
endpoint: "/v1/chats",
method: "POST"
},
"voice": {
endpoint: "/v1/voice",
method: "POST"
},
"event": {
endpoint: "/v1/events",
method: "POST"
},
"tts": {
endpoint: "/v1/speak",
method: "POST"
},
"healthcheck": {
endpoint: "/v1/healthcheck",
method: "GET"
}
};
const endPointDocBase = {
"chat": {
endpoint: "/api/v1/chats",
method: "POST"
},
"voice": {
endpoint: "/api/v1/voice",
method: "POST"
},
"event": {
endpoint: "/api/v1/events",
method: "POST"
},
"tts": {
endpoint: "/api/v1/speak",
method: "POST"
},
"healthcheck": {
endpoint: "/api/v1/healthcheck",
method: "GET"
}
};
fastify.all("/api", async (request, response) => {
logger.log("API", `Received base route request from ${request.ip}`)
response.code(200).send({error: "Please select a valid endpoint before sending a request", ...endPointDoc })
})
fastify.all("/", async (request, response) => {
logger.log("API", `Received base route request from ${request.ip}`)
response.code(200).send({error: "Please select a valid endpoint before sending a request", ...endPointDocBase })
})
fastify.setErrorHandler((error, request, reply) => {
if (error instanceof Fastify.errorCodes.FST_ERR_ROUTE_METHOD_NOT_SUPPORTED) {
reply.code(405).send({
error: "Method Not Allowed",
message: `HTTP method "${request.method}" is not supported for this route.`,
allowedMethods: reply.context.config.allowedMethods // List of allowed methods
});
} else {
reply.send(error);
}
});
/**
* Performs preflight checks on external services and databases.
* @returns {Promise<void>} - A promise that resolves when all preflight checks are completed.
*/
async function preflightChecks() {
const allTalkRes = await axios.get(
await retrieveConfigValue("alltalk.healthcheck.internal"),
);
const databaseRes = await aiHelper.checkMilvusHealth();
let checkResult = {
llmStatuses: {
allTalkIsOnline: allTalkRes.status == 200 ? true : false,
embeddingIsOnline: await aiHelper.checkEndpoint(
await retrieveConfigValue("models.embedding.endpoint"),
await retrieveConfigValue("models.embedding.apiKey"),
await retrieveConfigValue("models.embedding.model"),
),
llmIsOnline: await aiHelper.checkEndpoint(
await retrieveConfigValue("models.chat.endpoint"),
await retrieveConfigValue("models.chat.apiKey"),
await retrieveConfigValue("models.chat.model"),
),
summaryIsOnline: await aiHelper.checkEndpoint(
await retrieveConfigValue("models.summary.endpoint"),
await retrieveConfigValue("models.summary.apiKey"),
await retrieveConfigValue("models.summary.model"),
),
queryIsOnline: await aiHelper.checkEndpoint(
await retrieveConfigValue("models.query.endpoint"),
await retrieveConfigValue("models.query.apiKey"),
await retrieveConfigValue("models.query.model"),
),
conversionIsOnline: await aiHelper.checkEndpoint(
await retrieveConfigValue("models.conversion.endpoint"),
await retrieveConfigValue("models.conversion.apiKey"),
await retrieveConfigValue("models.conversion.model"),
),
},
restIsOnline: true,
dbIsOnline: databaseRes,
};
process.send({ type: "preflight", data: checkResult });
}
/**
* Launches the Fastify server.
* @returns {Promise<void>} - A promise that resolves when the server starts listening.
*/
async function launchRest() {
const portNum = await retrieveConfigValue("server.port");
try {
await fastify.listen({
port: portNum,
host: await retrieveConfigValue("server.endpoints.internal"),
});
logger.log(
"API",
`Fastify server launched successfully on port ${portNum}`,
);
return Promise.resolve();
} catch (err) {
logger.log("API", `Failed to launch API server with error: ${err}`);
process.exit(1);
}
}
/**
* Initializes the application, loads API keys, starts vector indexing,
* preloads tokenizers, launches the REST server, and performs preflight checks.
* @returns {Promise<void>} - A promise that resolves when the application is fully initialized.
*/
async function initializeApp() {
const allUsers = await returnAPIKeys();
const collectionNames = [
await retrieveConfigValue("milvus.collections.user"),
await retrieveConfigValue("milvus.collections.intelligence"),
await retrieveConfigValue("milvus.collections.chat"),
await retrieveConfigValue("milvus.collections.voice"),
];
await loadConfig();
for (const user of allUsers) {
for (const collectionName of collectionNames) {
try {
const collectionExists = await aiHelper.checkAndCreateCollection(
collectionName,
user.user_id,
);
if (!collectionExists) {
process.exit(1);
}
const isLoaded = await aiHelper.loadCollectionIfNeeded(
collectionName,
user.user_id,
);
if (!isLoaded) {
process.exit(1);
} else {
}
} catch (error) {
process.exit(1);
}
}
}
// Now start indexing vectors after ensuring each user has collections
await Promise.all(
allUsers.map((user) => aiHelper.startIndexingVectors(user.user_id)),
);
await preloadAllTokenizers();
await launchRest();
await preflightChecks();
await initAllAPIs();
}
initializeApp();