File size: 6,928 Bytes
af1f386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7956c78
ebb4888
 
 
 
 
 
 
c670717
ebb4888
 
af1f386
ebb4888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1f386
5853d12
058d10c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
078734b
 
058d10c
 
 
 
 
 
 
 
 
 
 
 
 
ebb4888
058d10c
078734b
058d10c
 
 
ebb4888
058d10c
 
 
ebb4888
058d10c
 
 
af1f386
078734b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1f386
078734b
 
 
 
 
 
 
 
 
 
 
af1f386
ebb4888
 
 
 
 
 
af1f386
 
5853d12
 
058d10c
ebb4888
 
5acf3a4
c670717
ebb4888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
078734b
ebb4888
 
af1f386
078734b
 
 
 
af1f386
ebb4888
078734b
ebb4888
058d10c
5acf3a4
ebb4888
 
af1f386
078734b
 
 
 
af1f386
ebb4888
078734b
058d10c
fd28154
5acf3a4
ebb4888
058d10c
ebb4888
 
 
 
 
 
 
af1f386
ebb4888
af1f386
ebb4888
af1f386
ebb4888
058d10c
ebb4888
 
 
7956c78
ebb4888
 
 
 
 
7956c78
1778c9e
7e80e42
1778c9e
ebb4888
 
 
c670717
ebb4888
 
 
 
 
 
 
af1f386
ebb4888
 
7e80e42
058d10c
 
af1f386
058d10c
af1f386
ebb4888
 
 
 
 
 
 
af1f386
ebb4888
 
 
 
 
 
 
 
af1f386
058d10c
af1f386
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
import { query } from "$app/server";
import type { Provider, Model } from "$lib/types.js";
import { debugError, debugLog } from "$lib/utils/debug.js";

export type RouterData = {
	object: string;
	data: Datum[];
};

type Datum = {
	id: string;
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	object: any;
	created: number;
	owned_by: string;
	providers: ProviderElement[];
};

type ProviderElement = {
	provider: Provider;
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	status: any;
	context_length?: number;
	pricing?: Pricing;
	supports_tools?: boolean;
	supports_structured_output?: boolean;
};

type Pricing = {
	input: number;
	output: number;
};

export const getRouterData = query(async (): Promise<RouterData> => {
	const res = await fetch("https://router.huggingface.co/v1/models");
	return res.json();
});

enum CacheStatus {
	SUCCESS = "success",
	PARTIAL = "partial",
	ERROR = "error",
}

type Cache = {
	data: Model[] | undefined;
	timestamp: number;
	status: CacheStatus;
	failedTokenizers: string[];
	failedApiCalls: {
		textGeneration: boolean;
		imageTextToText: boolean;
	};
};

const cache: Cache = {
	data: undefined,
	timestamp: 0,
	status: CacheStatus.ERROR,
	failedTokenizers: [],
	failedApiCalls: {
		textGeneration: false,
		imageTextToText: false,
	},
};

const FULL_CACHE_REFRESH = 1000 * 60 * 60; // 1 hour
const PARTIAL_CACHE_REFRESH = 1000 * 60 * 15; // 15 minutes

const headers: HeadersInit = {
	"Upgrade-Insecure-Requests": "1",
	"Sec-Fetch-Dest": "document",
	"Sec-Fetch-Mode": "navigate",
	"Sec-Fetch-Site": "none",
	"Sec-Fetch-User": "?1",
	"Priority": "u=0, i",
	"Pragma": "no-cache",
	"Cache-Control": "no-cache",
};

const requestInit: RequestInit = {
	credentials: "include",
	headers,
	method: "GET",
	mode: "cors",
};

interface ApiQueryParams {
	pipeline_tag?: "text-generation" | "image-text-to-text";
	filter: string;
	inference_provider: string;
	limit?: number;
	skip?: number;
	expand: string[];
}

const queryParams: ApiQueryParams = {
	filter: "conversational",
	inference_provider: "all",
	expand: ["inferenceProviderMapping", "config", "library_name", "pipeline_tag", "tags", "mask_token", "trendingScore"],
};

const baseUrl = "https://huggingface.co/api/models";

function buildApiUrl(params: ApiQueryParams): string {
	const url = new URL(baseUrl);

	Object.entries(params).forEach(([key, value]) => {
		if (!Array.isArray(value) && value !== undefined) {
			url.searchParams.append(key, String(value));
		}
	});

	params.expand.forEach(item => {
		url.searchParams.append("expand[]", item);
	});

	return url.toString();
}

async function fetchAllModelsWithPagination(pipeline_tag: "text-generation" | "image-text-to-text"): Promise<Model[]> {
	const allModels: Model[] = [];
	let skip = 0;
	const batchSize = 1000;

	while (true) {
		const url = buildApiUrl({
			...queryParams,
			pipeline_tag,
			limit: batchSize,
			skip,
		});

		const response = await fetch(url, requestInit);

		if (!response.ok) {
			break;
		}

		const models: Model[] = await response.json();

		if (models.length === 0) {
			break;
		}

		allModels.push(...models);
		skip += batchSize;

		await new Promise(resolve => setTimeout(resolve, 100));
	}

	return allModels;
}

export const getModels = query(async (): Promise<Model[]> => {
	const timestamp = Date.now();

	const elapsed = timestamp - cache.timestamp;
	const cacheRefreshTime = cache.status === CacheStatus.SUCCESS ? FULL_CACHE_REFRESH : PARTIAL_CACHE_REFRESH;

	if (elapsed < cacheRefreshTime && cache.data?.length) {
		debugLog(`Using ${cache.status} cache (${Math.floor(elapsed / 1000 / 60)} min old)`);
		return cache.data;
	}

	try {
		const needTextGenFetch = elapsed >= FULL_CACHE_REFRESH || cache.failedApiCalls.textGeneration;
		const needImgTextFetch = elapsed >= FULL_CACHE_REFRESH || cache.failedApiCalls.imageTextToText;

		const existingModels = new Map<string, Model>();
		if (cache.data) {
			cache.data.forEach(model => {
				existingModels.set(model.id, model);
			});
		}

		const newFailedTokenizers: string[] = [];
		const newFailedApiCalls = {
			textGeneration: false,
			imageTextToText: false,
		};

		let textGenModels: Model[] = [];
		let imgText2TextModels: Model[] = [];

		const apiPromises: Promise<void>[] = [];
		if (needTextGenFetch) {
			apiPromises.push(
				fetchAllModelsWithPagination("text-generation")
					.then(models => {
						textGenModels = models;
					})
					.catch(error => {
						debugError(`Error fetching text-generation models:`, error);
						newFailedApiCalls.textGeneration = true;
					}),
			);
		}

		if (needImgTextFetch) {
			apiPromises.push(
				fetchAllModelsWithPagination("image-text-to-text")
					.then(models => {
						imgText2TextModels = models;
					})
					.catch(error => {
						debugError(`Error fetching image-text-to-text models:`, error);
						newFailedApiCalls.imageTextToText = true;
					}),
			);
		}

		await Promise.all(apiPromises);

		if (
			needTextGenFetch &&
			newFailedApiCalls.textGeneration &&
			needImgTextFetch &&
			newFailedApiCalls.imageTextToText &&
			cache.data?.length
		) {
			debugLog("All API requests failed. Using existing cache as fallback.");
			cache.status = CacheStatus.ERROR;
			cache.timestamp = timestamp;
			cache.failedApiCalls = newFailedApiCalls;
			return cache.data;
		}

		if (!needTextGenFetch && cache.data) {
			textGenModels = cache.data.filter(model => model.pipeline_tag === "text-generation").map(model => model as Model);
		}

		if (!needImgTextFetch && cache.data) {
			imgText2TextModels = cache.data
				.filter(model => model.pipeline_tag === "image-text-to-text")
				.map(model => model as Model);
		}

		const models: Model[] = [...textGenModels, ...imgText2TextModels].filter(
			m => m.inferenceProviderMapping.length > 0,
		);
		models.sort((a, b) => a.id.toLowerCase().localeCompare(b.id.toLowerCase()));

		const hasApiFailures = newFailedApiCalls.textGeneration || newFailedApiCalls.imageTextToText;
		const cacheStatus = hasApiFailures ? CacheStatus.PARTIAL : CacheStatus.SUCCESS;

		cache.data = models;
		cache.timestamp = timestamp;
		cache.status = cacheStatus;
		cache.failedTokenizers = newFailedTokenizers;
		cache.failedApiCalls = newFailedApiCalls;

		debugLog(
			`Cache updated: ${models.length} models, status: ${cacheStatus}, ` +
				`failed tokenizers: ${newFailedTokenizers.length}, ` +
				`API failures: text=${newFailedApiCalls.textGeneration}, img=${newFailedApiCalls.imageTextToText}`,
		);

		return models;
	} catch (error) {
		debugError("Error fetching models:", error);

		if (cache.data?.length) {
			cache.status = CacheStatus.ERROR;
			cache.failedApiCalls = {
				textGeneration: true,
				imageTextToText: true,
			};
			return cache.data;
		}

		cache.status = CacheStatus.ERROR;
		cache.timestamp = timestamp;
		cache.failedApiCalls = {
			textGeneration: true,
			imageTextToText: true,
		};
		return [];
	}
});