-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-models.js
More file actions
238 lines (210 loc) · 7.55 KB
/
get-models.js
File metadata and controls
238 lines (210 loc) · 7.55 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
/**
* Rahyana API - Get Available Models Example
*
* This example demonstrates how to retrieve the list of available models
* from the Rahyana API.
*
* Usage:
* Set your API key: export RAHYANA_API_KEY="your_api_key_here"
* Run: node get-models.js
*
* @file models/get-models.js
*/
// Configuration - supports environment variable or placeholder
const API_KEY = process.env.RAHYANA_API_KEY || 'YOUR_API_KEY_HERE'; // کلید API خود را اینجا قرار دهید یا از متغیر محیطی RAHYANA_API_KEY استفاده کنید
const BASE_URL = process.env.RAHYANA_BASE_URL || 'https://rahyana.ir/api/v1';
/**
* Retrieves the list of available models from the Rahyana API
*
* @returns {Promise<Object>} The API response containing the list of models
* @throws {Error} If the API request fails or response is invalid
*
* @example
* const models = await getAvailableModels();
* console.log(`Found ${models.data.length} models`);
*/
async function getAvailableModels() {
try {
const response = await fetch(`${BASE_URL}/models`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://example-app.com',
'X-Title': 'Rahyana Models Example'
}
});
// Handle HTTP errors
if (!response.ok) {
let errorMessage = `HTTP error! Status: ${response.status}`;
try {
const errorData = await response.json();
if (errorData.error && errorData.error.message) {
errorMessage = `API Error: ${errorData.error.message} (Status: ${response.status})`;
}
} catch (e) {
errorMessage = `HTTP error! Status: ${response.status} ${response.statusText}`;
}
throw new Error(errorMessage);
}
// Parse JSON response
let data;
try {
data = await response.json();
} catch (parseError) {
throw new Error(`Failed to parse JSON response: ${parseError.message}`);
}
// Validate response structure
if (!data || typeof data !== 'object') {
throw new Error('Invalid response: Expected JSON object');
}
if (data.data && Array.isArray(data.data)) {
console.log(`✅ Found ${data.data.length} models:`);
console.log('='.repeat(50));
data.data.forEach((model, index) => {
console.log(`${index + 1}. ${model.id}`);
if (model.name) console.log(` Name: ${model.name}`);
if (model.provider) console.log(` Provider: ${model.provider}`);
if (model.type) console.log(` Type: ${model.type}`);
if (model.context_length) console.log(` Context Length: ${model.context_length}`);
if (model.pricing) console.log(` Pricing: ${JSON.stringify(model.pricing)}`);
console.log(' ' + '-'.repeat(48));
});
} else {
console.warn('⚠️ Warning: Response does not contain models array');
}
return data;
} catch (error) {
// Handle network errors
if (error instanceof TypeError && error.message.includes('fetch')) {
console.error('❌ Network Error: Failed to connect to API. Check your internet connection and API endpoint.');
throw new Error(`Network error: ${error.message}`);
}
// Handle other errors
console.error('❌ Error:', error.message);
throw error;
}
}
/**
* Filters models by their capabilities
*
* @param {string} capability - The capability to filter by ('text', 'image', 'audio', 'function_calling')
* @returns {Promise<Array>} Array of models with the specified capability
* @throws {Error} If filtering fails
*/
async function filterModelsByCapability(capability) {
try {
const models = await getAvailableModels();
if (models.data && Array.isArray(models.data)) {
const filteredModels = models.data.filter(model => {
// Check if model has the specified capability
if (capability === 'text') {
return model.type === 'text' || model.type === 'chat';
} else if (capability === 'image') {
return model.capabilities && model.capabilities.includes('image');
} else if (capability === 'audio') {
return model.capabilities && model.capabilities.includes('audio');
} else if (capability === 'function_calling') {
return model.capabilities && model.capabilities.includes('function_calling');
}
return false;
});
console.log(`\n📋 Models with ${capability} capability:`);
console.log('='.repeat(50));
filteredModels.forEach((model, index) => {
console.log(`${index + 1}. ${model.id}`);
});
return filteredModels;
}
return [];
} catch (error) {
console.error('❌ Error filtering models:', error.message);
throw error;
}
}
/**
* Gets a specific model by its ID
*
* @param {string} modelId - The model ID to search for
* @returns {Promise<Object|null>} The model object if found, null otherwise
* @throws {Error} If the search fails
*/
async function getModelById(modelId) {
try {
const models = await getAvailableModels();
if (models.data && Array.isArray(models.data)) {
const model = models.data.find(m => m.id === modelId);
if (model) {
console.log(`\n🔍 Model Details for ${modelId}:`);
console.log('='.repeat(50));
console.log(JSON.stringify(model, null, 2));
return model;
} else {
console.log(`❌ Model ${modelId} not found`);
return null;
}
}
return null;
} catch (error) {
console.error('❌ Error getting model by ID:', error.message);
throw error;
}
}
/**
* Gets all models from a specific provider
*
* @param {string} provider - The provider name to filter by
* @returns {Promise<Array>} Array of models from the specified provider
* @throws {Error} If the search fails
*/
async function getModelsByProvider(provider) {
try {
const models = await getAvailableModels();
if (models.data && Array.isArray(models.data)) {
const providerModels = models.data.filter(model =>
model.provider && model.provider.toLowerCase().includes(provider.toLowerCase())
);
console.log(`\n🏢 Models from ${provider}:`);
console.log('='.repeat(50));
providerModels.forEach((model, index) => {
console.log(`${index + 1}. ${model.id} (${model.name || 'N/A'})`);
});
return providerModels;
}
return [];
} catch (error) {
console.error('❌ Error getting models by provider:', error.message);
throw error;
}
}
// Execute the example if run directly
if (import.meta.url === `file://${process.argv[1]}`) {
console.log('🚀 Getting all available models...');
getAvailableModels()
.then(result => {
console.log('\n📋 Filtering models by text capability...');
return filterModelsByCapability('text');
})
.then(result => {
console.log('\n📋 Filtering models by image capability...');
return filterModelsByCapability('image');
})
.then(result => {
console.log('\n🔍 Getting specific model details...');
return getModelById('openai/gpt-4o');
})
.then(result => {
console.log('\n🏢 Getting models by provider...');
return getModelsByProvider('openai');
})
.then(result => {
console.log('\n✅ All model examples completed!');
process.exit(0);
})
.catch(error => {
console.error('❌ Failed:', error.message);
process.exit(1);
});
}
// Export functions for use in other modules
export { getAvailableModels, filterModelsByCapability, getModelById, getModelsByProvider };