-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
488 lines (431 loc) · 13.9 KB
/
server.js
File metadata and controls
488 lines (431 loc) · 13.9 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const path = require('path');
const modelsDatabase = require('./data/models');
const app = express();
const PORT = process.env.PORT || 3000;
// Security middleware
app.use(helmet());
app.use(compression());
// Rate limiting
const limiter = rateLimit({
windowMs: parseInt(process.env.API_RATE_LIMIT_WINDOW) || 15 * 60 * 1000, // 15 minutes
max: parseInt(process.env.API_RATE_LIMIT_MAX) || 1000, // limit each IP to 1000 requests per windowMs
message: {
error: 'Too many requests from this IP, please try again later.',
retryAfter: '15 minutes'
},
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
app.use('/api/', limiter);
// CORS configuration
const getAllowedOrigins = () => {
if (process.env.ALLOWED_ORIGINS) {
return process.env.ALLOWED_ORIGINS.split(',').map(origin => origin.trim());
}
if (process.env.NODE_ENV === 'production') {
return [
/^https:\/\/.*\.railway\.app$/,
/^https:\/\/.*\.up\.railway\.app$/
];
}
return true; // Allow all origins in development
};
app.use(cors({
origin: getAllowedOrigins(),
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
credentials: true
}));
// Body parsing middleware
app.use(express.json({ limit: '800mb' }));
app.use(express.urlencoded({ extended: true, limit: '800mb' }));
// Serve static files
app.use(express.static('.', {
index: 'index.html',
setHeaders: (res, path) => {
if (path.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache');
} else {
res.setHeader('Cache-Control', 'public, max-age=31536000');
}
}
}));
// API Routes
// API Documentation landing page
app.get('/api', (req, res) => {
res.sendFile(path.join(__dirname, 'api-docs.html'));
});
// Health check
app.get('/api/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
version: '1.0.0',
totalModels: modelsDatabase.length
});
});
// Get all models with optional filtering
app.get('/api/models', (req, res) => {
try {
let filteredModels = [...modelsDatabase];
// Apply filters
const {
category,
provider,
license,
search,
limit = 50,
offset = 0,
sortBy = 'name',
order = 'asc',
inputModality,
outputModality,
toolCalling,
reasoning
} = req.query;
// Category filter
if (category) {
filteredModels = filteredModels.filter(model =>
model.category.toLowerCase() === category.toLowerCase()
);
}
// Provider filter
if (provider) {
filteredModels = filteredModels.filter(model =>
model.provider.toLowerCase() === provider.toLowerCase()
);
}
// License filter
if (license) {
filteredModels = filteredModels.filter(model =>
model.license.toLowerCase() === license.toLowerCase()
);
}
// Input modality filter
if (inputModality) {
filteredModels = filteredModels.filter(model =>
model.inputModalities.some(mod =>
mod.toLowerCase() === inputModality.toLowerCase()
)
);
}
// Output modality filter
if (outputModality) {
filteredModels = filteredModels.filter(model =>
model.outputModalities.some(mod =>
mod.toLowerCase() === outputModality.toLowerCase()
)
);
}
// Tool calling filter
if (toolCalling) {
filteredModels = filteredModels.filter(model =>
model.technicalSpecs.toolCalling.toLowerCase() === toolCalling.toLowerCase()
);
}
// Reasoning filter
if (reasoning) {
filteredModels = filteredModels.filter(model =>
model.technicalSpecs.reasoning.toLowerCase() === reasoning.toLowerCase()
);
}
// Search filter
if (search) {
const searchTerm = search.toLowerCase();
filteredModels = filteredModels.filter(model =>
model.name.toLowerCase().includes(searchTerm) ||
model.author.toLowerCase().includes(searchTerm) ||
model.description.toLowerCase().includes(searchTerm) ||
model.plainDescription.toLowerCase().includes(searchTerm) ||
model.tags.some(tag => tag.toLowerCase().includes(searchTerm)) ||
model.useCases.some(useCase => useCase.toLowerCase().includes(searchTerm))
);
}
// Sorting
filteredModels.sort((a, b) => {
let aValue, bValue;
switch(sortBy) {
case 'name':
aValue = a.name.toLowerCase();
bValue = b.name.toLowerCase();
break;
case 'date':
aValue = new Date(a.date);
bValue = new Date(b.date);
break;
case 'downloads':
aValue = parseFloat(a.downloads);
bValue = parseFloat(b.downloads);
break;
case 'stars':
aValue = parseFloat(a.stars);
bValue = parseFloat(b.stars);
break;
case 'parameters':
aValue = parseFloat(a.technicalSpecs.parameters);
bValue = parseFloat(b.technicalSpecs.parameters);
break;
default:
aValue = a.name.toLowerCase();
bValue = b.name.toLowerCase();
}
if (order === 'desc') {
return aValue < bValue ? 1 : aValue > bValue ? -1 : 0;
} else {
return aValue > bValue ? 1 : aValue < bValue ? -1 : 0;
}
});
// Pagination
const total = filteredModels.length;
const limitNum = Math.min(parseInt(limit), 100); // Max 100 items per request
const offsetNum = parseInt(offset);
const paginatedModels = filteredModels.slice(offsetNum, offsetNum + limitNum);
res.json({
success: true,
data: paginatedModels,
pagination: {
total,
limit: limitNum,
offset: offsetNum,
hasMore: offsetNum + limitNum < total
},
filters: {
category,
provider,
license,
search,
inputModality,
outputModality,
toolCalling,
reasoning,
sortBy,
order
}
});
} catch (error) {
console.error('Error in /api/models:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
message: 'Failed to fetch models'
});
}
});
// Get a specific model by name or ID
app.get('/api/models/:identifier', (req, res) => {
try {
const { identifier } = req.params;
// Try to find by name (case-insensitive) or by array index
const model = modelsDatabase.find(m =>
m.name.toLowerCase() === identifier.toLowerCase()
) || modelsDatabase[parseInt(identifier)];
if (!model) {
return res.status(404).json({
success: false,
error: 'Model not found',
message: `No model found with identifier: ${identifier}`
});
}
res.json({
success: true,
data: model
});
} catch (error) {
console.error('Error in /api/models/:identifier:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
message: 'Failed to fetch model'
});
}
});
// Get available filter options
app.get('/api/filters', (req, res) => {
try {
const categories = [...new Set(modelsDatabase.map(m => m.category))];
const providers = [...new Set(modelsDatabase.map(m => m.provider))];
const licenses = [...new Set(modelsDatabase.map(m => m.license))];
const inputModalities = [...new Set(modelsDatabase.flatMap(m => m.inputModalities))];
const outputModalities = [...new Set(modelsDatabase.flatMap(m => m.outputModalities))];
const toolCallingOptions = [...new Set(modelsDatabase.map(m => m.technicalSpecs.toolCalling))];
const reasoningOptions = [...new Set(modelsDatabase.map(m => m.technicalSpecs.reasoning))];
res.json({
success: true,
data: {
categories: categories.sort(),
providers: providers.sort(),
licenses: licenses.sort(),
inputModalities: inputModalities.sort(),
outputModalities: outputModalities.sort(),
toolCalling: toolCallingOptions.sort(),
reasoning: reasoningOptions.sort()
}
});
} catch (error) {
console.error('Error in /api/filters:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
message: 'Failed to fetch filter options'
});
}
});
// Get statistics
app.get('/api/stats', (req, res) => {
try {
const stats = {
totalModels: modelsDatabase.length,
categories: {},
providers: {},
licenses: {},
averageParameters: 0,
totalDownloads: 0,
totalStars: 0
};
// Calculate category distribution
modelsDatabase.forEach(model => {
stats.categories[model.category] = (stats.categories[model.category] || 0) + 1;
stats.providers[model.provider] = (stats.providers[model.provider] || 0) + 1;
stats.licenses[model.license] = (stats.licenses[model.license] || 0) + 1;
// Convert download and star counts to numbers
const downloads = parseFloat(model.downloads.replace(/[KMB]/i, '')) *
(model.downloads.includes('K') ? 1000 :
model.downloads.includes('M') ? 1000000 :
model.downloads.includes('B') ? 1000000000 : 1);
const stars = parseFloat(model.stars.replace(/[KMB]/i, '')) *
(model.stars.includes('K') ? 1000 :
model.stars.includes('M') ? 1000000 :
model.stars.includes('B') ? 1000000000 : 1);
stats.totalDownloads += downloads;
stats.totalStars += stars;
});
res.json({
success: true,
data: stats
});
} catch (error) {
console.error('Error in /api/stats:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
message: 'Failed to fetch statistics'
});
}
});
// Vercel AI SDK compatible endpoint
app.post('/api/ai/models', (req, res) => {
try {
const { query, filters = {}, limit = 10 } = req.body;
let results = [...modelsDatabase];
// Apply filters
Object.entries(filters).forEach(([key, value]) => {
if (value) {
results = results.filter(model => {
switch(key) {
case 'category':
return model.category.toLowerCase() === value.toLowerCase();
case 'provider':
return model.provider.toLowerCase() === value.toLowerCase();
case 'toolCalling':
return model.technicalSpecs.toolCalling.toLowerCase() === value.toLowerCase();
case 'reasoning':
return model.technicalSpecs.reasoning.toLowerCase() === value.toLowerCase();
default:
return true;
}
});
}
});
// Apply search query if provided
if (query) {
const searchTerm = query.toLowerCase();
results = results.filter(model =>
model.name.toLowerCase().includes(searchTerm) ||
model.description.toLowerCase().includes(searchTerm) ||
model.plainDescription.toLowerCase().includes(searchTerm) ||
model.useCases.some(useCase => useCase.toLowerCase().includes(searchTerm))
);
}
// Limit results
results = results.slice(0, Math.min(limit, 20));
// Format for Vercel AI SDK
const formattedResults = results.map(model => ({
id: model.name.toLowerCase().replace(/\s+/g, '-'),
name: model.name,
description: model.plainDescription,
provider: model.provider,
category: model.category,
capabilities: {
toolCalling: model.technicalSpecs.toolCalling !== 'No',
reasoning: model.technicalSpecs.reasoning !== 'None',
inputModalities: model.inputModalities,
outputModalities: model.outputModalities
},
pricing: {
input: model.technicalSpecs.inputCost,
output: model.technicalSpecs.outputCost
},
specs: {
parameters: model.technicalSpecs.parameters,
memory: model.technicalSpecs.memoryRequired,
speed: model.technicalSpecs.inferenceSpeed
}
}));
res.json({
success: true,
models: formattedResults,
total: results.length,
query,
filters
});
} catch (error) {
console.error('Error in /api/ai/models:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
message: 'Failed to process AI models request'
});
}
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Unhandled error:', err);
res.status(500).json({
success: false,
error: 'Internal server error',
message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong'
});
});
// 404 handler for API routes
app.use('/api/*', (req, res) => {
res.status(404).json({
success: false,
error: 'Not found',
message: `API endpoint ${req.originalUrl} not found`
});
});
// Serve the frontend for all other routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 OSS AI Models API running on port ${PORT}`);
console.log(`📊 Database contains ${modelsDatabase.length} models`);
console.log(`🌍 Environment: ${process.env.NODE_ENV || 'development'}`);
if (process.env.NODE_ENV === 'production') {
console.log(`🌐 API available at /api`);
console.log(`📋 API Documentation at /api`);
console.log(`❤️ Health check at /api/health`);
} else {
console.log(`🌐 API available at http://localhost:${PORT}/api`);
console.log(`🔧 Frontend available at http://localhost:${PORT}`);
console.log(`📋 API Documentation at http://localhost:${PORT}/api`);
}
});
module.exports = app;