File size: 6,198 Bytes
8b7b267 |
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 |
/**
* Models Client with Fixed Error Handling
* Replace your models-client.js with this
*/
import { api } from './api-client.js';
import logger from '../utils/logger.js';
class ModelsClient {
constructor() {
this.cache = new Map();
this.cacheTimeout = 60000; // 1 minute
}
/**
* Get models summary with comprehensive error handling
*/
async getModelsSummary() {
const cacheKey = 'models_summary';
const cached = this.cache.get(cacheKey);
// Return cached data if available and fresh
if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
logger.debug('ModelsClient', 'Returning cached models summary');
return cached.data;
}
try {
logger.debug('ModelsClient', 'Fetching models summary...');
// Try the endpoint
const response = await fetch('/api/models/summary', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(10000)
}).catch(err => {
logger.warn('ModelsClient', 'Fetch failed:', err?.message || 'Unknown error');
return null;
});
if (!response || !response.ok) {
const statusText = response?.statusText || 'No response';
logger.warn('ModelsClient', `API returned error: ${statusText}`);
// Return empty but valid structure
return {
success: false,
error: true,
message: `Failed to fetch models: ${statusText}`,
categories: {},
models: [],
summary: {
total_models: 0,
loaded_models: 0,
failed_models: 0,
hf_mode: 'unavailable',
transformers_available: false
}
};
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
logger.error('ModelsClient', 'Invalid content type:', contentType);
throw new Error('Invalid response content type');
}
const data = await response.json();
// Validate response structure
if (!data || typeof data !== 'object') {
logger.error('ModelsClient', 'Invalid response data');
throw new Error('Invalid response data structure');
}
// Cache successful response
this.cache.set(cacheKey, {
data: data,
timestamp: Date.now()
});
logger.info('ModelsClient', 'Successfully fetched models summary');
return data;
} catch (error) {
const safeError = error || new Error('Unknown error');
logger.error('ModelsClient', 'Failed to get models summary:', safeError.message);
logger.error('ModelsClient', 'Error details:', {
message: safeError.message,
stack: safeError.stack,
name: safeError.name
});
// Return a valid empty structure instead of throwing
return {
success: false,
error: true,
message: safeError.message || 'Failed to fetch models',
categories: {},
models: [],
summary: {
total_models: 0,
loaded_models: 0,
failed_models: 0,
hf_mode: 'error',
hf_status: safeError.message || 'Unknown error',
transformers_available: false
}
};
}
}
/**
* Get list of all models
*/
async getModelsList() {
try {
const response = await fetch('/api/models/list', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(10000)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
logger.error('ModelsClient', 'Failed to get models list:', error?.message || 'Unknown error');
return {
success: false,
error: true,
message: error?.message || 'Failed to fetch models list',
models: []
};
}
}
/**
* Get status of a specific model
*/
async getModelStatus(modelId) {
if (!modelId) {
return {
success: false,
error: true,
message: 'Model ID is required'
};
}
try {
const response = await fetch(`/api/models/${encodeURIComponent(modelId)}/status`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(10000)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
logger.error('ModelsClient', `Failed to get status for ${modelId}:`, error?.message || 'Unknown error');
return {
success: false,
error: true,
message: error?.message || 'Failed to fetch model status',
model_id: modelId,
status: 'unknown'
};
}
}
/**
* Initialize or reinitialize models
*/
async initializeModels() {
try {
const response = await fetch('/api/models/initialize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(30000)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
// Clear cache on successful init
this.cache.clear();
return data;
} catch (error) {
logger.error('ModelsClient', 'Failed to initialize models:', error?.message || 'Unknown error');
return {
success: false,
error: true,
message: error?.message || 'Failed to initialize models'
};
}
}
/**
* Clear cache
*/
clearCache() {
this.cache.clear();
logger.debug('ModelsClient', 'Cache cleared');
}
/**
* Get cache statistics
*/
getCacheStats() {
return {
size: this.cache.size,
keys: Array.from(this.cache.keys()),
timeout: this.cacheTimeout
};
}
}
// Export singleton instance
export const modelsClient = new ModelsClient();
export default modelsClient;
|