isa-model 0.3.7__py3-none-any.whl → 0.3.9__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/__init__.py +1 -1
- isa_model/client.py +41 -5
- isa_model/core/pricing_manager.py +248 -1
- isa_model/inference/services/llm/ollama_llm_service.py +43 -0
- isa_model/inference/services/llm/openai_llm_service.py +7 -5
- isa_model/inference/services/llm/yyds_llm_service.py +43 -1
- {isa_model-0.3.7.dist-info → isa_model-0.3.9.dist-info}/METADATA +1 -1
- {isa_model-0.3.7.dist-info → isa_model-0.3.9.dist-info}/RECORD +10 -20
- 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.7.dist-info → isa_model-0.3.9.dist-info}/WHEEL +0 -0
- {isa_model-0.3.7.dist-info → isa_model-0.3.9.dist-info}/top_level.txt +0 -0
@@ -1,77 +0,0 @@
|
|
1
|
-
from abc import ABC, abstractmethod
|
2
|
-
from typing import Dict, List, Any, Optional
|
3
|
-
import os
|
4
|
-
import logging
|
5
|
-
from pathlib import Path
|
6
|
-
import dotenv
|
7
|
-
|
8
|
-
from isa_model.inference.base import ModelType, Capability
|
9
|
-
|
10
|
-
logger = logging.getLogger(__name__)
|
11
|
-
|
12
|
-
class BaseProvider(ABC):
|
13
|
-
"""Base class for all AI providers - handles API key management"""
|
14
|
-
|
15
|
-
def __init__(self, config: Optional[Dict[str, Any]] = None):
|
16
|
-
self.config = config or {}
|
17
|
-
self._load_environment_config()
|
18
|
-
self._validate_config()
|
19
|
-
|
20
|
-
def _load_environment_config(self):
|
21
|
-
"""Load configuration from environment variables"""
|
22
|
-
# Load .env file if it exists
|
23
|
-
project_root = Path(__file__).parent.parent.parent.parent
|
24
|
-
env_path = project_root / ".env"
|
25
|
-
|
26
|
-
if env_path.exists():
|
27
|
-
dotenv.load_dotenv(env_path)
|
28
|
-
|
29
|
-
# Subclasses should override this to load provider-specific env vars
|
30
|
-
self._load_provider_env_vars()
|
31
|
-
|
32
|
-
@abstractmethod
|
33
|
-
def _load_provider_env_vars(self):
|
34
|
-
"""Load provider-specific environment variables"""
|
35
|
-
pass
|
36
|
-
|
37
|
-
def _validate_config(self):
|
38
|
-
"""Validate that required configuration is present"""
|
39
|
-
# Subclasses should override this to validate provider-specific config
|
40
|
-
pass
|
41
|
-
|
42
|
-
def get_api_key(self) -> Optional[str]:
|
43
|
-
"""Get the API key for this provider"""
|
44
|
-
return self.config.get("api_key")
|
45
|
-
|
46
|
-
def has_valid_credentials(self) -> bool:
|
47
|
-
"""Check if provider has valid credentials"""
|
48
|
-
return bool(self.get_api_key())
|
49
|
-
|
50
|
-
@abstractmethod
|
51
|
-
def get_capabilities(self) -> Dict[ModelType, List[Capability]]:
|
52
|
-
"""Get provider capabilities by model type"""
|
53
|
-
pass
|
54
|
-
|
55
|
-
@abstractmethod
|
56
|
-
def get_models(self, model_type: ModelType) -> List[str]:
|
57
|
-
"""Get available models for given type"""
|
58
|
-
pass
|
59
|
-
|
60
|
-
def get_config(self) -> Dict[str, Any]:
|
61
|
-
"""Get provider configuration (without sensitive data)"""
|
62
|
-
# Return a copy without sensitive information
|
63
|
-
config_copy = self.config.copy()
|
64
|
-
if "api_key" in config_copy:
|
65
|
-
config_copy["api_key"] = "***" if config_copy["api_key"] else ""
|
66
|
-
if "api_token" in config_copy:
|
67
|
-
config_copy["api_token"] = "***" if config_copy["api_token"] else ""
|
68
|
-
return config_copy
|
69
|
-
|
70
|
-
def get_full_config(self) -> Dict[str, Any]:
|
71
|
-
"""Get full provider configuration (including sensitive data) - for internal use only"""
|
72
|
-
return self.config.copy()
|
73
|
-
|
74
|
-
@abstractmethod
|
75
|
-
def is_reasoning_model(self, model_name: str) -> bool:
|
76
|
-
"""Check if the model is optimized for reasoning tasks"""
|
77
|
-
pass
|
@@ -1,50 +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
|
-
|
6
|
-
logger = logging.getLogger(__name__)
|
7
|
-
|
8
|
-
class MLProvider(BaseProvider):
|
9
|
-
"""Provider for traditional ML models"""
|
10
|
-
|
11
|
-
def __init__(self, config=None):
|
12
|
-
default_config = {
|
13
|
-
"model_directory": "./models/ml",
|
14
|
-
"cache_models": True,
|
15
|
-
"max_cache_size": 5
|
16
|
-
}
|
17
|
-
|
18
|
-
merged_config = {**default_config, **(config or {})}
|
19
|
-
super().__init__(config=merged_config)
|
20
|
-
self.name = "ml"
|
21
|
-
|
22
|
-
logger.info(f"Initialized MLProvider with model directory: {self.config['model_directory']}")
|
23
|
-
|
24
|
-
def get_capabilities(self) -> Dict[ModelType, List[Capability]]:
|
25
|
-
"""Get provider capabilities"""
|
26
|
-
return {
|
27
|
-
ModelType.LLM: [], # ML models are not LLMs
|
28
|
-
ModelType.EMBEDDING: [],
|
29
|
-
ModelType.VISION: [],
|
30
|
-
"ML": [ # Custom model type for traditional ML
|
31
|
-
"CLASSIFICATION",
|
32
|
-
"REGRESSION",
|
33
|
-
"CLUSTERING",
|
34
|
-
"FEATURE_EXTRACTION"
|
35
|
-
]
|
36
|
-
}
|
37
|
-
|
38
|
-
def get_models(self, model_type: str = "ML") -> List[str]:
|
39
|
-
"""Get available ML models"""
|
40
|
-
# In practice, this would scan the model directory
|
41
|
-
return [
|
42
|
-
"fraud_detection_rf",
|
43
|
-
"customer_churn_xgb",
|
44
|
-
"price_prediction_lr",
|
45
|
-
"recommendation_kmeans"
|
46
|
-
]
|
47
|
-
|
48
|
-
def get_config(self) -> Dict[str, Any]:
|
49
|
-
"""Get provider configuration"""
|
50
|
-
return self.config
|
@@ -1,109 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Modal Provider
|
3
|
-
|
4
|
-
Provider for ISA self-hosted Modal services
|
5
|
-
No API keys needed since we deploy our own services
|
6
|
-
"""
|
7
|
-
|
8
|
-
import os
|
9
|
-
import logging
|
10
|
-
from typing import Dict, Any, Optional, List
|
11
|
-
from .base_provider import BaseProvider
|
12
|
-
from isa_model.inference.base import ModelType, Capability
|
13
|
-
|
14
|
-
logger = logging.getLogger(__name__)
|
15
|
-
|
16
|
-
class ModalProvider(BaseProvider):
|
17
|
-
"""Provider for ISA Modal services"""
|
18
|
-
|
19
|
-
def __init__(self, config: Optional[Dict[str, Any]] = None):
|
20
|
-
super().__init__(config)
|
21
|
-
self.name = "modal"
|
22
|
-
self.base_url = "https://modal.com" # Not used directly
|
23
|
-
|
24
|
-
def _load_provider_env_vars(self):
|
25
|
-
"""Load Modal-specific environment variables"""
|
26
|
-
# Modal doesn't need API keys for deployed services
|
27
|
-
# But we can load Modal token if available
|
28
|
-
modal_token = os.getenv("MODAL_TOKEN_ID") or os.getenv("MODAL_TOKEN_SECRET")
|
29
|
-
if modal_token:
|
30
|
-
self.config["modal_token"] = modal_token
|
31
|
-
|
32
|
-
# Set default config
|
33
|
-
if "timeout" not in self.config:
|
34
|
-
self.config["timeout"] = 300
|
35
|
-
if "deployment_region" not in self.config:
|
36
|
-
self.config["deployment_region"] = "us-east-1"
|
37
|
-
if "gpu_type" not in self.config:
|
38
|
-
self.config["gpu_type"] = "T4"
|
39
|
-
|
40
|
-
def get_api_key(self) -> str:
|
41
|
-
"""Modal services don't need API keys for deployed apps"""
|
42
|
-
return "modal-deployed-service" # Placeholder
|
43
|
-
|
44
|
-
def get_base_url(self) -> str:
|
45
|
-
"""Get base URL for Modal services"""
|
46
|
-
return self.base_url
|
47
|
-
|
48
|
-
def validate_credentials(self) -> bool:
|
49
|
-
"""
|
50
|
-
Validate Modal credentials
|
51
|
-
For deployed services, we assume they're accessible
|
52
|
-
"""
|
53
|
-
try:
|
54
|
-
# Check if Modal is available
|
55
|
-
import modal
|
56
|
-
return True
|
57
|
-
except ImportError:
|
58
|
-
logger.warning("Modal package not available")
|
59
|
-
return False
|
60
|
-
|
61
|
-
def get_capabilities(self) -> Dict[ModelType, List[Capability]]:
|
62
|
-
"""Get Modal provider capabilities"""
|
63
|
-
return {
|
64
|
-
ModelType.VISION: [
|
65
|
-
Capability.OBJECT_DETECTION,
|
66
|
-
Capability.IMAGE_ANALYSIS,
|
67
|
-
Capability.UI_DETECTION,
|
68
|
-
Capability.OCR,
|
69
|
-
Capability.DOCUMENT_ANALYSIS
|
70
|
-
]
|
71
|
-
}
|
72
|
-
|
73
|
-
def get_models(self, model_type: ModelType) -> List[str]:
|
74
|
-
"""Get available models for given type"""
|
75
|
-
if model_type == ModelType.VISION:
|
76
|
-
return [
|
77
|
-
"omniparser-v2.0",
|
78
|
-
"table-transformer-detection",
|
79
|
-
"table-transformer-structure-v1.1",
|
80
|
-
"paddleocr-3.0",
|
81
|
-
"yolov8"
|
82
|
-
]
|
83
|
-
return []
|
84
|
-
|
85
|
-
def is_reasoning_model(self, model_name: str) -> bool:
|
86
|
-
"""Check if the model is optimized for reasoning tasks"""
|
87
|
-
# Vision models are not reasoning models
|
88
|
-
return False
|
89
|
-
|
90
|
-
def get_default_config(self) -> Dict[str, Any]:
|
91
|
-
"""Get default configuration for Modal services"""
|
92
|
-
return {
|
93
|
-
"timeout": 300, # 5 minutes
|
94
|
-
"max_retries": 3,
|
95
|
-
"deployment_region": "us-east-1",
|
96
|
-
"gpu_type": "T4"
|
97
|
-
}
|
98
|
-
|
99
|
-
def get_billing_info(self) -> Dict[str, Any]:
|
100
|
-
"""Get billing information for Modal services"""
|
101
|
-
return {
|
102
|
-
"provider": "modal",
|
103
|
-
"billing_model": "compute_usage",
|
104
|
-
"cost_per_hour": {
|
105
|
-
"T4": 0.60,
|
106
|
-
"A100": 4.00
|
107
|
-
},
|
108
|
-
"note": "Costs depend on actual usage time, scales to zero when not in use"
|
109
|
-
}
|
@@ -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)
|