Forked from tupik/openai-compat-endpoint
src / api.ts
// src/api.ts
// Module for loading model list from OpenRouter API
export interface ModelData {
id: string;
name?: string;
description?: string;
context_length?: number;
pricing?: any;
}
export interface ModelsResponse {
data: ModelData[];
}
/**
* Loads model list from OpenRouter API
* @param baseUrl - base URL for API (e.g., https://openrouter.ai/api/v1)
* @param apiKey - optional API key for authorization
* @returns array of model identifiers
*/
export async function fetchModels(
baseUrl: string,
apiKey?: string
): Promise<string[]> {
try {
const modelsUrl = `${baseUrl}/models`;
if (typeof fetch === 'undefined') {
throw new Error('fetch is not available in this environment');
}
const headers: Record<string, string> = {};
if (apiKey && apiKey.trim()) {
headers["Authorization"] = `Bearer ${apiKey}`;
}
const response = await fetch(modelsUrl, {
method: 'GET',
headers
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = await response.json() as ModelsResponse;
if (!data.data || !Array.isArray(data.data)) {
console.warn("[API] Invalid response format from models endpoint");
return [];
}
const allModels = data.data.map((m: ModelData) => m.id).filter(Boolean);
return allModels;
} catch (error) {
console.error("[API] Failed to fetch models:", error);
return [];
}
}
/**
* Filters model list to only free models (with :free suffix)
* @param models - full list of models
* @returns filtered list of free models
*/
export function filterFreeModels(models: string[]): string[] {
return models.filter((id: string) => id.includes(":free"));
}