isa-model 0.3.6__py3-none-any.whl → 0.3.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- isa_model/client.py +200 -6
- isa_model/deployment/services/auto_deploy_vision_service.py +4 -3
- isa_model/deployment/services/simple_auto_deploy_vision_service.py +275 -0
- isa_model/inference/ai_factory.py +83 -3
- isa_model/serving/api/routes/unified.py +72 -0
- {isa_model-0.3.6.dist-info → isa_model-0.3.8.dist-info}/METADATA +1 -1
- {isa_model-0.3.6.dist-info → isa_model-0.3.8.dist-info}/RECORD +9 -18
- isa_model/inference/providers/__init__.py +0 -19
- isa_model/inference/providers/base_provider.py +0 -77
- isa_model/inference/providers/ml_provider.py +0 -50
- isa_model/inference/providers/modal_provider.py +0 -109
- isa_model/inference/providers/model_cache_manager.py +0 -341
- isa_model/inference/providers/ollama_provider.py +0 -92
- isa_model/inference/providers/openai_provider.py +0 -130
- isa_model/inference/providers/replicate_provider.py +0 -119
- isa_model/inference/providers/triton_provider.py +0 -439
- isa_model/inference/providers/yyds_provider.py +0 -108
- {isa_model-0.3.6.dist-info → isa_model-0.3.8.dist-info}/WHEEL +0 -0
- {isa_model-0.3.6.dist-info → isa_model-0.3.8.dist-info}/top_level.txt +0 -0
@@ -1,341 +0,0 @@
|
|
1
|
-
from typing import Dict, List, Any, Optional
|
2
|
-
import aiohttp
|
3
|
-
import logging
|
4
|
-
import asyncio
|
5
|
-
from collections import OrderedDict
|
6
|
-
import os
|
7
|
-
import json
|
8
|
-
import hashlib
|
9
|
-
from pathlib import Path
|
10
|
-
from isa_model.inference.base import ModelType
|
11
|
-
|
12
|
-
logger = logging.getLogger(__name__)
|
13
|
-
|
14
|
-
class ModelCacheManager:
|
15
|
-
"""管理Triton服务器模型的加载/卸载,支持轮询模式"""
|
16
|
-
|
17
|
-
def __init__(self, cache_size: int = 5, model_repository: str = "/models"):
|
18
|
-
"""
|
19
|
-
初始化模型缓存管理器
|
20
|
-
|
21
|
-
Args:
|
22
|
-
cache_size: 最大缓存模型数量
|
23
|
-
model_repository: 模型库路径
|
24
|
-
"""
|
25
|
-
self.cache_size = cache_size
|
26
|
-
self.model_repository = model_repository
|
27
|
-
|
28
|
-
# LRU缓存使用OrderedDict
|
29
|
-
self.model_cache = OrderedDict()
|
30
|
-
|
31
|
-
# 服务器配置
|
32
|
-
self.server_config = {
|
33
|
-
"polling_enabled": True, # 默认启用轮询模式(适合多模型场景)
|
34
|
-
"triton_url": "localhost:8000",
|
35
|
-
"openai_api_url": "localhost:9000"
|
36
|
-
}
|
37
|
-
|
38
|
-
# 模型类型映射
|
39
|
-
self.model_type_map = {
|
40
|
-
ModelType.LLM: "llm",
|
41
|
-
ModelType.EMBEDDING: "embedding",
|
42
|
-
ModelType.VISION: "vision",
|
43
|
-
ModelType.RERANK: "rerank"
|
44
|
-
}
|
45
|
-
|
46
|
-
logger.info(f"初始化ModelCacheManager,缓存大小: {cache_size},模型库: {model_repository}")
|
47
|
-
|
48
|
-
async def detect_server_mode(self):
|
49
|
-
"""检测Triton服务器是否运行在轮询模式"""
|
50
|
-
try:
|
51
|
-
# 尝试加载任意模型以检测模式
|
52
|
-
models = await self._get_repository_models()
|
53
|
-
if not models:
|
54
|
-
logger.warning("无法获取模型列表,无法检测服务器模式")
|
55
|
-
return
|
56
|
-
|
57
|
-
test_model = models[0]
|
58
|
-
url = f"http://{self.server_config['triton_url']}/v2/repository/models/{test_model}/load"
|
59
|
-
|
60
|
-
async with aiohttp.ClientSession() as session:
|
61
|
-
async with session.post(url) as response:
|
62
|
-
response_text = await response.text()
|
63
|
-
|
64
|
-
if response.status == 503 and "polling is enabled" in response_text:
|
65
|
-
self.server_config["polling_enabled"] = True
|
66
|
-
logger.info("检测到Triton服务器运行在轮询模式(多模型模式)")
|
67
|
-
elif response.status == 200:
|
68
|
-
self.server_config["polling_enabled"] = False
|
69
|
-
logger.info("检测到Triton服务器运行在手动加载模式(单模型模式)")
|
70
|
-
else:
|
71
|
-
logger.warning(f"无法确定服务器模式,状态码: {response.status}")
|
72
|
-
except Exception as e:
|
73
|
-
logger.error(f"检测服务器模式时出错: {e}")
|
74
|
-
|
75
|
-
async def load_model(self, model_name: str, model_type: ModelType) -> bool:
|
76
|
-
"""
|
77
|
-
加载模型到Triton服务器
|
78
|
-
|
79
|
-
Args:
|
80
|
-
model_name: 模型名称
|
81
|
-
model_type: 模型类型
|
82
|
-
|
83
|
-
Returns:
|
84
|
-
bool: 成功返回True,失败返回False
|
85
|
-
"""
|
86
|
-
# 如果是第一次加载,检测服务器模式
|
87
|
-
if not hasattr(self, '_mode_detected'):
|
88
|
-
await self.detect_server_mode()
|
89
|
-
self._mode_detected = True
|
90
|
-
|
91
|
-
if model_name in self.model_cache:
|
92
|
-
# 模型已加载,移到LRU缓存末尾
|
93
|
-
self.model_cache.move_to_end(model_name)
|
94
|
-
logger.info(f"模型 {model_name} 已在缓存中,移至末尾")
|
95
|
-
return True
|
96
|
-
|
97
|
-
try:
|
98
|
-
# 检查模型是否已加载到服务器
|
99
|
-
is_loaded = await self._check_model_loaded(model_name)
|
100
|
-
if is_loaded:
|
101
|
-
logger.info(f"模型 {model_name} 已在服务器中加载")
|
102
|
-
self.model_cache[model_name] = {
|
103
|
-
"type": model_type,
|
104
|
-
"load_time": asyncio.get_event_loop().time()
|
105
|
-
}
|
106
|
-
return True
|
107
|
-
|
108
|
-
# 如果在轮询模式下,我们不能手动加载模型
|
109
|
-
if self.server_config["polling_enabled"]:
|
110
|
-
# 检查模型是否存在
|
111
|
-
exists = await self._check_model_exists(model_name)
|
112
|
-
if exists:
|
113
|
-
logger.warning(f"服务器在轮询模式下,无法手动加载模型 {model_name},但模型存在")
|
114
|
-
# 我们假设模型将通过轮询加载
|
115
|
-
return True
|
116
|
-
else:
|
117
|
-
logger.error(f"模型 {model_name} 不存在于服务器存储库中")
|
118
|
-
return False
|
119
|
-
else:
|
120
|
-
# 在非轮询模式下,可以手动加载
|
121
|
-
# 如果缓存已满,卸载最少使用的模型
|
122
|
-
if len(self.model_cache) >= self.cache_size:
|
123
|
-
lru_model, _ = self.model_cache.popitem(last=False)
|
124
|
-
await self._unload_from_triton(lru_model)
|
125
|
-
logger.info(f"从缓存中卸载LRU模型 {lru_model}")
|
126
|
-
|
127
|
-
# 加载新模型
|
128
|
-
success = await self._load_to_triton(model_name)
|
129
|
-
if success:
|
130
|
-
self.model_cache[model_name] = {
|
131
|
-
"type": model_type,
|
132
|
-
"load_time": asyncio.get_event_loop().time()
|
133
|
-
}
|
134
|
-
logger.info(f"成功加载模型 {model_name}")
|
135
|
-
return True
|
136
|
-
else:
|
137
|
-
logger.error(f"加载模型 {model_name} 失败")
|
138
|
-
return False
|
139
|
-
|
140
|
-
except Exception as e:
|
141
|
-
logger.error(f"加载模型 {model_name} 时出错: {e}")
|
142
|
-
return False
|
143
|
-
|
144
|
-
async def unload_model(self, model_name: str) -> bool:
|
145
|
-
"""卸载模型"""
|
146
|
-
# 如果在轮询模式下,我们不能手动卸载模型
|
147
|
-
if self.server_config["polling_enabled"]:
|
148
|
-
logger.warning(f"服务器在轮询模式下,无法手动卸载模型 {model_name}")
|
149
|
-
return True
|
150
|
-
|
151
|
-
if model_name not in self.model_cache:
|
152
|
-
logger.warning(f"模型 {model_name} 未在缓存中,无需卸载")
|
153
|
-
return True
|
154
|
-
|
155
|
-
try:
|
156
|
-
# 卸载模型
|
157
|
-
success = await self._unload_from_triton(model_name)
|
158
|
-
if success:
|
159
|
-
# 从缓存中移除
|
160
|
-
self.model_cache.pop(model_name, None)
|
161
|
-
logger.info(f"成功卸载模型 {model_name}")
|
162
|
-
return True
|
163
|
-
else:
|
164
|
-
logger.error(f"卸载模型 {model_name} 失败")
|
165
|
-
return False
|
166
|
-
|
167
|
-
except Exception as e:
|
168
|
-
logger.error(f"卸载模型 {model_name} 时出错: {e}")
|
169
|
-
return False
|
170
|
-
|
171
|
-
async def _load_to_triton(self, model_name: str) -> bool:
|
172
|
-
"""向Triton服务器发送加载模型请求"""
|
173
|
-
try:
|
174
|
-
logger.info(f"尝试加载模型 {model_name} 到Triton服务器")
|
175
|
-
|
176
|
-
url = f"http://{self.server_config['triton_url']}/v2/repository/models/{model_name}/load"
|
177
|
-
|
178
|
-
async with aiohttp.ClientSession() as session:
|
179
|
-
async with session.post(url) as response:
|
180
|
-
response_text = await response.text()
|
181
|
-
|
182
|
-
if response.status == 200:
|
183
|
-
logger.info(f"成功加载模型 {model_name}")
|
184
|
-
return True
|
185
|
-
elif response.status == 400:
|
186
|
-
# 模型可能已加载
|
187
|
-
logger.info(f"模型 {model_name} 可能已加载: {response_text}")
|
188
|
-
return True
|
189
|
-
elif response.status == 503 and "polling is enabled" in response_text:
|
190
|
-
# 检测到轮询模式
|
191
|
-
self.server_config["polling_enabled"] = True
|
192
|
-
logger.warning(f"服务器在轮询模式下,无法手动加载模型: {response_text}")
|
193
|
-
# 检查模型是否存在
|
194
|
-
return await self._check_model_exists(model_name)
|
195
|
-
else:
|
196
|
-
logger.error(f"加载模型 {model_name} 失败: Status {response.status}, Response: {response_text}")
|
197
|
-
return False
|
198
|
-
|
199
|
-
except Exception as e:
|
200
|
-
logger.error(f"向Triton API发送加载模型 {model_name} 请求时出错: {e}")
|
201
|
-
return False
|
202
|
-
|
203
|
-
async def _check_model_loaded(self, model_name: str) -> bool:
|
204
|
-
"""检查模型是否已加载"""
|
205
|
-
try:
|
206
|
-
url = f"http://{self.server_config['triton_url']}/v2/models/{model_name}/ready"
|
207
|
-
|
208
|
-
async with aiohttp.ClientSession() as session:
|
209
|
-
async with session.get(url) as response:
|
210
|
-
if response.status == 200:
|
211
|
-
logger.info(f"模型 {model_name} 已加载")
|
212
|
-
return True
|
213
|
-
else:
|
214
|
-
logger.info(f"模型 {model_name} 未加载,状态码: {response.status}")
|
215
|
-
return False
|
216
|
-
except Exception as e:
|
217
|
-
logger.error(f"检查模型 {model_name} 是否加载时出错: {e}")
|
218
|
-
return False
|
219
|
-
|
220
|
-
async def _check_model_exists(self, model_name: str) -> bool:
|
221
|
-
"""检查模型是否存在于存储库中"""
|
222
|
-
try:
|
223
|
-
url = f"http://{self.server_config['triton_url']}/v2/repository/index"
|
224
|
-
|
225
|
-
async with aiohttp.ClientSession() as session:
|
226
|
-
async with session.post(url) as response:
|
227
|
-
if response.status == 200:
|
228
|
-
models = await response.json()
|
229
|
-
model_names = [model["name"] for model in models]
|
230
|
-
exists = model_name in model_names
|
231
|
-
logger.info(f"模型 {model_name} {'存在' if exists else '不存在'}于存储库中")
|
232
|
-
logger.info(f"可用模型: {model_names}")
|
233
|
-
return exists
|
234
|
-
else:
|
235
|
-
logger.error(f"检查模型存在性失败: {response.status}")
|
236
|
-
return False
|
237
|
-
except Exception as e:
|
238
|
-
logger.error(f"检查模型存在性时出错: {e}")
|
239
|
-
return False
|
240
|
-
|
241
|
-
async def _unload_from_triton(self, model_name: str) -> bool:
|
242
|
-
"""从Triton服务器卸载模型"""
|
243
|
-
try:
|
244
|
-
url = f"http://{self.server_config['triton_url']}/v2/repository/models/{model_name}/unload"
|
245
|
-
|
246
|
-
async with aiohttp.ClientSession() as session:
|
247
|
-
async with session.post(url) as response:
|
248
|
-
response_text = await response.text()
|
249
|
-
|
250
|
-
if response.status == 200:
|
251
|
-
logger.info(f"成功卸载模型 {model_name}")
|
252
|
-
return True
|
253
|
-
elif response.status == 503 and "polling is enabled" in response_text:
|
254
|
-
# 检测到轮询模式
|
255
|
-
self.server_config["polling_enabled"] = True
|
256
|
-
logger.warning(f"服务器在轮询模式下,无法手动卸载模型: {response_text}")
|
257
|
-
return True
|
258
|
-
else:
|
259
|
-
logger.error(f"卸载模型 {model_name} 失败: Status {response.status}, Response: {response_text}")
|
260
|
-
return False
|
261
|
-
except Exception as e:
|
262
|
-
logger.error(f"向Triton API发送卸载模型 {model_name} 请求时出错: {e}")
|
263
|
-
return False
|
264
|
-
|
265
|
-
def list_available_models(self, model_type: ModelType = None) -> List[str]:
|
266
|
-
"""
|
267
|
-
列出可用模型
|
268
|
-
|
269
|
-
Args:
|
270
|
-
model_type: 按模型类型筛选
|
271
|
-
|
272
|
-
Returns:
|
273
|
-
模型名称列表
|
274
|
-
"""
|
275
|
-
try:
|
276
|
-
# 获取模型列表
|
277
|
-
models = asyncio.run(self._get_repository_models())
|
278
|
-
|
279
|
-
if not models:
|
280
|
-
logger.warning("在存储库中未找到模型或无法连接到服务器")
|
281
|
-
return []
|
282
|
-
|
283
|
-
# 如果未指定模型类型,返回所有模型
|
284
|
-
if model_type is None:
|
285
|
-
return models
|
286
|
-
|
287
|
-
# 基于命名约定的简单过滤器
|
288
|
-
if model_type == ModelType.LLM:
|
289
|
-
# 返回包含关键字的模型
|
290
|
-
llm_keywords = ["llama", "mistral", "gemma", "qwen", "phi", "gpt", "falcon"]
|
291
|
-
return [m for m in models if any(kw in m.lower() for kw in llm_keywords)]
|
292
|
-
elif model_type == ModelType.EMBEDDING:
|
293
|
-
embed_keywords = ["embed", "bge", "e5", "text-embedding"]
|
294
|
-
return [m for m in models if any(kw in m.lower() for kw in embed_keywords)]
|
295
|
-
elif model_type == ModelType.VISION:
|
296
|
-
vision_keywords = ["clip", "vision", "multimodal", "image"]
|
297
|
-
return [m for m in models if any(kw in m.lower() for kw in vision_keywords)]
|
298
|
-
elif model_type == ModelType.RERANK:
|
299
|
-
rerank_keywords = ["rerank", "cross-encoder"]
|
300
|
-
return [m for m in models if any(kw in m.lower() for kw in rerank_keywords)]
|
301
|
-
else:
|
302
|
-
return []
|
303
|
-
|
304
|
-
except Exception as e:
|
305
|
-
logger.error(f"列出模型时出错: {e}")
|
306
|
-
return []
|
307
|
-
|
308
|
-
async def _get_repository_models(self) -> List[str]:
|
309
|
-
"""从Triton服务器获取模型列表"""
|
310
|
-
try:
|
311
|
-
url = f"http://{self.server_config['triton_url']}/v2/repository/index"
|
312
|
-
|
313
|
-
async with aiohttp.ClientSession() as session:
|
314
|
-
async with session.post(url) as response:
|
315
|
-
if response.status == 200:
|
316
|
-
models = await response.json()
|
317
|
-
return [model["name"] for model in models]
|
318
|
-
else:
|
319
|
-
logger.error(f"获取模型失败: Status {response.status}")
|
320
|
-
return []
|
321
|
-
except Exception as e:
|
322
|
-
logger.error(f"获取存储库模型时出错: {e}")
|
323
|
-
return []
|
324
|
-
|
325
|
-
async def get_openai_models(self) -> List[Dict[str, Any]]:
|
326
|
-
"""获取OpenAI兼容API中的可用模型"""
|
327
|
-
try:
|
328
|
-
url = f"http://{self.server_config['openai_api_url']}/v1/models"
|
329
|
-
|
330
|
-
async with aiohttp.ClientSession() as session:
|
331
|
-
async with session.get(url) as response:
|
332
|
-
if response.status == 200:
|
333
|
-
result = await response.json()
|
334
|
-
logger.info(f"从OpenAI API获取到 {len(result.get('data', []))} 个模型")
|
335
|
-
return result.get("data", [])
|
336
|
-
else:
|
337
|
-
logger.error(f"获取OpenAI模型失败: Status {response.status}")
|
338
|
-
return []
|
339
|
-
except Exception as e:
|
340
|
-
logger.error(f"获取OpenAI模型时出错: {e}")
|
341
|
-
return []
|
@@ -1,92 +0,0 @@
|
|
1
|
-
from isa_model.inference.providers.base_provider import BaseProvider
|
2
|
-
from isa_model.inference.base import ModelType, Capability
|
3
|
-
from typing import Dict, List, Any
|
4
|
-
import logging
|
5
|
-
import os
|
6
|
-
|
7
|
-
logger = logging.getLogger(__name__)
|
8
|
-
|
9
|
-
class OllamaProvider(BaseProvider):
|
10
|
-
"""Provider for Ollama API with proper configuration management"""
|
11
|
-
|
12
|
-
def __init__(self, config=None):
|
13
|
-
"""Initialize the Ollama Provider with centralized config management"""
|
14
|
-
super().__init__(config)
|
15
|
-
self.name = "ollama"
|
16
|
-
|
17
|
-
logger.info(f"Initialized OllamaProvider with URL: {self.config.get('base_url', 'http://localhost:11434')}")
|
18
|
-
|
19
|
-
def _load_provider_env_vars(self):
|
20
|
-
"""Load Ollama-specific environment variables"""
|
21
|
-
# Set defaults first
|
22
|
-
defaults = {
|
23
|
-
"base_url": "http://localhost:11434",
|
24
|
-
"timeout": 60,
|
25
|
-
"temperature": 0.7,
|
26
|
-
"top_p": 0.9,
|
27
|
-
"max_tokens": 2048,
|
28
|
-
"keep_alive": "5m"
|
29
|
-
}
|
30
|
-
|
31
|
-
# Apply defaults only if not already set
|
32
|
-
for key, value in defaults.items():
|
33
|
-
if key not in self.config:
|
34
|
-
self.config[key] = value
|
35
|
-
|
36
|
-
# Load from environment variables (override config if present)
|
37
|
-
env_mappings = {
|
38
|
-
"base_url": "OLLAMA_BASE_URL",
|
39
|
-
}
|
40
|
-
|
41
|
-
for config_key, env_var in env_mappings.items():
|
42
|
-
env_value = os.getenv(env_var)
|
43
|
-
if env_value:
|
44
|
-
self.config[config_key] = env_value
|
45
|
-
|
46
|
-
def _validate_config(self):
|
47
|
-
"""Validate Ollama configuration"""
|
48
|
-
# Ollama doesn't require API keys, just validate base_url is set
|
49
|
-
if not self.config.get("base_url"):
|
50
|
-
logger.warning("Ollama base_url not set, using default: http://localhost:11434")
|
51
|
-
self.config["base_url"] = "http://localhost:11434"
|
52
|
-
|
53
|
-
def has_valid_credentials(self) -> bool:
|
54
|
-
"""Check if provider has valid credentials (Ollama doesn't need API keys)"""
|
55
|
-
return True # Ollama typically doesn't require authentication
|
56
|
-
|
57
|
-
def get_capabilities(self) -> Dict[ModelType, List[Capability]]:
|
58
|
-
"""Get provider capabilities by model type"""
|
59
|
-
return {
|
60
|
-
ModelType.LLM: [
|
61
|
-
Capability.CHAT,
|
62
|
-
Capability.COMPLETION
|
63
|
-
],
|
64
|
-
ModelType.EMBEDDING: [
|
65
|
-
Capability.EMBEDDING
|
66
|
-
],
|
67
|
-
ModelType.VISION: [
|
68
|
-
Capability.MULTIMODAL_UNDERSTANDING
|
69
|
-
]
|
70
|
-
}
|
71
|
-
|
72
|
-
def get_models(self, model_type: ModelType) -> List[str]:
|
73
|
-
"""Get available models for given type"""
|
74
|
-
# Placeholder: In real implementation, this would query Ollama API
|
75
|
-
if model_type == ModelType.LLM:
|
76
|
-
return ["llama3.2:3b", "llama3", "mistral", "phi3", "llama3.1", "codellama", "gemma"]
|
77
|
-
elif model_type == ModelType.EMBEDDING:
|
78
|
-
return ["bge-m3", "nomic-embed-text"]
|
79
|
-
elif model_type == ModelType.VISION:
|
80
|
-
return ["gemma3:4b", "llava", "bakllava", "llama3-vision"]
|
81
|
-
else:
|
82
|
-
return []
|
83
|
-
|
84
|
-
def get_config(self) -> Dict[str, Any]:
|
85
|
-
"""Get provider configuration"""
|
86
|
-
return self.config
|
87
|
-
|
88
|
-
def is_reasoning_model(self, model_name: str) -> bool:
|
89
|
-
"""Check if the model is optimized for reasoning tasks"""
|
90
|
-
# Default implementation: consider larger models as reasoning-capable
|
91
|
-
reasoning_models = ["llama3.1", "llama3", "claude3", "gpt4", "mixtral", "gemma", "palm2"]
|
92
|
-
return any(rm in model_name.lower() for rm in reasoning_models)
|
@@ -1,130 +0,0 @@
|
|
1
|
-
from isa_model.inference.providers.base_provider import BaseProvider
|
2
|
-
from isa_model.inference.base import ModelType, Capability
|
3
|
-
from typing import Dict, List, Any
|
4
|
-
import logging
|
5
|
-
import os
|
6
|
-
|
7
|
-
logger = logging.getLogger(__name__)
|
8
|
-
|
9
|
-
class OpenAIProvider(BaseProvider):
|
10
|
-
"""Provider for OpenAI API with proper API key management"""
|
11
|
-
|
12
|
-
def __init__(self, config=None):
|
13
|
-
"""Initialize the OpenAI Provider with centralized config management"""
|
14
|
-
super().__init__(config)
|
15
|
-
self.name = "openai"
|
16
|
-
|
17
|
-
logger.info(f"Initialized OpenAIProvider with URL: {self.config.get('base_url', 'https://api.openai.com/v1')}")
|
18
|
-
|
19
|
-
if not self.has_valid_credentials():
|
20
|
-
logger.warning("OpenAI API key not found. Set OPENAI_API_KEY environment variable or pass api_key in config.")
|
21
|
-
|
22
|
-
def _load_provider_env_vars(self):
|
23
|
-
"""Load OpenAI-specific environment variables"""
|
24
|
-
# Set defaults first
|
25
|
-
defaults = {
|
26
|
-
"base_url": "https://api.openai.com/v1",
|
27
|
-
"timeout": 60,
|
28
|
-
"temperature": 0.7,
|
29
|
-
"top_p": 0.9,
|
30
|
-
"max_tokens": 1024
|
31
|
-
}
|
32
|
-
|
33
|
-
# Apply defaults only if not already set
|
34
|
-
for key, value in defaults.items():
|
35
|
-
if key not in self.config:
|
36
|
-
self.config[key] = value
|
37
|
-
|
38
|
-
# Load from environment variables (override config if present)
|
39
|
-
env_mappings = {
|
40
|
-
"api_key": "OPENAI_API_KEY",
|
41
|
-
"base_url": "OPENAI_API_BASE",
|
42
|
-
"organization": "OPENAI_ORGANIZATION"
|
43
|
-
}
|
44
|
-
|
45
|
-
for config_key, env_var in env_mappings.items():
|
46
|
-
env_value = os.getenv(env_var)
|
47
|
-
if env_value:
|
48
|
-
self.config[config_key] = env_value
|
49
|
-
|
50
|
-
def _validate_config(self):
|
51
|
-
"""Validate OpenAI configuration"""
|
52
|
-
if not self.config.get("api_key"):
|
53
|
-
logger.debug("OpenAI API key not set - some functionality may not work")
|
54
|
-
|
55
|
-
def get_model_pricing(self, model_name: str) -> Dict[str, float]:
|
56
|
-
"""Get pricing information for a model - delegated to ModelManager"""
|
57
|
-
# Import here to avoid circular imports
|
58
|
-
from isa_model.core.model_manager import ModelManager
|
59
|
-
model_manager = ModelManager()
|
60
|
-
return model_manager.get_model_pricing("openai", model_name)
|
61
|
-
|
62
|
-
def calculate_cost(self, model_name: str, input_tokens: int, output_tokens: int) -> float:
|
63
|
-
"""Calculate cost for a request - delegated to ModelManager"""
|
64
|
-
# Import here to avoid circular imports
|
65
|
-
from isa_model.core.model_manager import ModelManager
|
66
|
-
model_manager = ModelManager()
|
67
|
-
return model_manager.calculate_cost("openai", model_name, input_tokens, output_tokens)
|
68
|
-
|
69
|
-
def set_api_key(self, api_key: str):
|
70
|
-
"""Set the API key after initialization"""
|
71
|
-
self.config["api_key"] = api_key
|
72
|
-
logger.info("OpenAI API key updated")
|
73
|
-
|
74
|
-
def get_capabilities(self) -> Dict[ModelType, List[Capability]]:
|
75
|
-
"""Get provider capabilities by model type"""
|
76
|
-
return {
|
77
|
-
ModelType.LLM: [
|
78
|
-
Capability.CHAT,
|
79
|
-
Capability.COMPLETION
|
80
|
-
],
|
81
|
-
ModelType.EMBEDDING: [
|
82
|
-
Capability.EMBEDDING
|
83
|
-
],
|
84
|
-
ModelType.VISION: [
|
85
|
-
Capability.IMAGE_GENERATION,
|
86
|
-
Capability.MULTIMODAL_UNDERSTANDING
|
87
|
-
],
|
88
|
-
ModelType.AUDIO: [
|
89
|
-
Capability.SPEECH_TO_TEXT
|
90
|
-
]
|
91
|
-
}
|
92
|
-
|
93
|
-
def get_models(self, model_type: ModelType) -> List[str]:
|
94
|
-
"""Get available models for given type"""
|
95
|
-
if model_type == ModelType.LLM:
|
96
|
-
return ["gpt-4.1-nano", "gpt-4.1-mini", "gpt-4o-mini", "gpt-4o", "gpt-4-turbo", "gpt-4", "gpt-3.5-turbo"]
|
97
|
-
elif model_type == ModelType.EMBEDDING:
|
98
|
-
return ["text-embedding-3-large", "text-embedding-3-small", "text-embedding-ada-002"]
|
99
|
-
elif model_type == ModelType.VISION:
|
100
|
-
return ["gpt-4.1-nano", "gpt-4.1-mini", "gpt-4o-mini", "gpt-4o", "gpt-4-vision-preview"]
|
101
|
-
elif model_type == ModelType.AUDIO:
|
102
|
-
return ["whisper-1", "gpt-4o-transcribe", "tts-1", "tts-1-hd"]
|
103
|
-
else:
|
104
|
-
return []
|
105
|
-
|
106
|
-
def get_default_model(self, model_type: ModelType) -> str:
|
107
|
-
"""Get default model for a given type"""
|
108
|
-
if model_type == ModelType.LLM:
|
109
|
-
return "gpt-4.1-nano" # Cheapest and most cost-effective
|
110
|
-
elif model_type == ModelType.EMBEDDING:
|
111
|
-
return "text-embedding-3-small"
|
112
|
-
elif model_type == ModelType.VISION:
|
113
|
-
return "gpt-4.1-nano"
|
114
|
-
elif model_type == ModelType.AUDIO:
|
115
|
-
return "whisper-1"
|
116
|
-
else:
|
117
|
-
return ""
|
118
|
-
|
119
|
-
def get_config(self) -> Dict[str, Any]:
|
120
|
-
"""Get provider configuration"""
|
121
|
-
# Return a copy without sensitive information
|
122
|
-
config_copy = self.config.copy()
|
123
|
-
if "api_key" in config_copy:
|
124
|
-
config_copy["api_key"] = "***" if config_copy["api_key"] else ""
|
125
|
-
return config_copy
|
126
|
-
|
127
|
-
def is_reasoning_model(self, model_name: str) -> bool:
|
128
|
-
"""Check if the model is optimized for reasoning tasks"""
|
129
|
-
reasoning_models = ["gpt-4", "gpt-4o", "gpt-4-turbo", "gpt-4.1"]
|
130
|
-
return any(rm in model_name.lower() for rm in reasoning_models)
|
@@ -1,119 +0,0 @@
|
|
1
|
-
from isa_model.inference.providers.base_provider import BaseProvider
|
2
|
-
from isa_model.inference.base import ModelType, Capability
|
3
|
-
from typing import Dict, List, Any
|
4
|
-
import logging
|
5
|
-
import os
|
6
|
-
|
7
|
-
logger = logging.getLogger(__name__)
|
8
|
-
|
9
|
-
class ReplicateProvider(BaseProvider):
|
10
|
-
"""Provider for Replicate API with proper API key management"""
|
11
|
-
|
12
|
-
def __init__(self, config=None):
|
13
|
-
"""Initialize the Replicate Provider with centralized config management"""
|
14
|
-
super().__init__(config)
|
15
|
-
self.name = "replicate"
|
16
|
-
|
17
|
-
logger.info("Initialized ReplicateProvider")
|
18
|
-
|
19
|
-
if not self.has_valid_credentials():
|
20
|
-
logger.warning("Replicate API token not found. Set REPLICATE_API_TOKEN environment variable or pass api_token in config.")
|
21
|
-
|
22
|
-
def _load_provider_env_vars(self):
|
23
|
-
"""Load Replicate-specific environment variables"""
|
24
|
-
# Set defaults first
|
25
|
-
defaults = {
|
26
|
-
"timeout": 60,
|
27
|
-
"max_tokens": 1024
|
28
|
-
}
|
29
|
-
|
30
|
-
# Apply defaults only if not already set
|
31
|
-
for key, value in defaults.items():
|
32
|
-
if key not in self.config:
|
33
|
-
self.config[key] = value
|
34
|
-
|
35
|
-
# Load from environment variables (override config if present)
|
36
|
-
env_mappings = {
|
37
|
-
"api_token": "REPLICATE_API_TOKEN",
|
38
|
-
}
|
39
|
-
|
40
|
-
for config_key, env_var in env_mappings.items():
|
41
|
-
env_value = os.getenv(env_var)
|
42
|
-
if env_value:
|
43
|
-
self.config[config_key] = env_value
|
44
|
-
|
45
|
-
def _validate_config(self):
|
46
|
-
"""Validate Replicate configuration"""
|
47
|
-
if not self.config.get("api_token"):
|
48
|
-
logger.debug("Replicate API token not set - some functionality may not work")
|
49
|
-
|
50
|
-
def get_api_key(self) -> str:
|
51
|
-
"""Get the API token for this provider (override for Replicate naming)"""
|
52
|
-
return self.config.get("api_token", "")
|
53
|
-
|
54
|
-
def has_valid_credentials(self) -> bool:
|
55
|
-
"""Check if provider has valid credentials (override for Replicate naming)"""
|
56
|
-
return bool(self.config.get("api_token"))
|
57
|
-
|
58
|
-
def set_api_token(self, api_token: str):
|
59
|
-
"""Set the API token after initialization"""
|
60
|
-
self.config["api_token"] = api_token
|
61
|
-
logger.info("Replicate API token updated")
|
62
|
-
|
63
|
-
def get_capabilities(self) -> Dict[ModelType, List[Capability]]:
|
64
|
-
"""Get provider capabilities by model type"""
|
65
|
-
return {
|
66
|
-
ModelType.LLM: [
|
67
|
-
Capability.CHAT,
|
68
|
-
Capability.COMPLETION
|
69
|
-
],
|
70
|
-
ModelType.VISION: [
|
71
|
-
Capability.IMAGE_GENERATION,
|
72
|
-
Capability.MULTIMODAL_UNDERSTANDING
|
73
|
-
],
|
74
|
-
ModelType.AUDIO: [
|
75
|
-
Capability.SPEECH_TO_TEXT,
|
76
|
-
Capability.TEXT_TO_SPEECH
|
77
|
-
]
|
78
|
-
}
|
79
|
-
|
80
|
-
def get_models(self, model_type: ModelType) -> List[str]:
|
81
|
-
"""Get available models for given type"""
|
82
|
-
if model_type == ModelType.LLM:
|
83
|
-
return [
|
84
|
-
"meta/llama-3-70b-instruct",
|
85
|
-
"meta/llama-3-8b-instruct",
|
86
|
-
"anthropic/claude-3-opus-20240229",
|
87
|
-
"anthropic/claude-3-sonnet-20240229"
|
88
|
-
]
|
89
|
-
elif model_type == ModelType.VISION:
|
90
|
-
return [
|
91
|
-
"black-forest-labs/flux-schnell",
|
92
|
-
"black-forest-labs/flux-kontext-pro",
|
93
|
-
"stability-ai/sdxl",
|
94
|
-
"stability-ai/stable-diffusion-3-medium",
|
95
|
-
"meta/llama-3-70b-vision",
|
96
|
-
"anthropic/claude-3-opus-20240229",
|
97
|
-
"anthropic/claude-3-sonnet-20240229"
|
98
|
-
]
|
99
|
-
elif model_type == ModelType.AUDIO:
|
100
|
-
return [
|
101
|
-
"jaaari/kokoro-82m",
|
102
|
-
"openai/whisper",
|
103
|
-
"suno-ai/bark"
|
104
|
-
]
|
105
|
-
else:
|
106
|
-
return []
|
107
|
-
|
108
|
-
def get_config(self) -> Dict[str, Any]:
|
109
|
-
"""Get provider configuration"""
|
110
|
-
# Return a copy without sensitive information
|
111
|
-
config_copy = self.config.copy()
|
112
|
-
if "api_token" in config_copy:
|
113
|
-
config_copy["api_token"] = "***" if config_copy["api_token"] else ""
|
114
|
-
return config_copy
|
115
|
-
|
116
|
-
def is_reasoning_model(self, model_name: str) -> bool:
|
117
|
-
"""Check if the model is optimized for reasoning tasks"""
|
118
|
-
reasoning_models = ["llama-3-70b", "claude-3-opus", "claude-3-sonnet"]
|
119
|
-
return any(rm in model_name.lower() for rm in reasoning_models)
|