isa-model 0.3.7__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.
@@ -1,439 +0,0 @@
1
- import os
2
- import logging
3
- import json
4
- import numpy as np
5
- import base64
6
- from typing import Dict, Any, Optional, List, Union
7
-
8
- from isa_model.inference.providers.base_provider import BaseProvider
9
- from isa_model.inference.base import ModelType, Capability
10
- from isa_model.inference.providers.model_cache_manager import ModelCacheManager
11
- import asyncio
12
-
13
- # 设置日志
14
- logger = logging.getLogger(__name__)
15
-
16
- class TritonProvider(BaseProvider):
17
- """
18
- Provider for Triton Inference Server models.
19
- """
20
-
21
- def __init__(self, config: Optional[Dict[str, Any]] = None):
22
- """
23
- Initialize the Triton provider.
24
-
25
- Args:
26
- config: Configuration for the provider
27
- """
28
- super().__init__(config or {})
29
-
30
- # Default configuration
31
- self.default_config = {
32
- "server_url": os.environ.get("TRITON_SERVER_URL", "http://localhost:8000"),
33
- "model_repository": os.environ.get(
34
- "MODEL_REPOSITORY",
35
- os.path.join(os.getcwd(), "models/triton/model_repository")
36
- ),
37
- "http_headers": {},
38
- "verbose": True,
39
- "client_timeout": 300.0, # 5 minutes timeout
40
- "max_batch_size": 8,
41
- "max_sequence_length": 2048,
42
- "temperature": 0.7,
43
- "top_p": 0.9,
44
- "model_cache_size": 5, # LRU cache size
45
- "tokenizer_name": "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
46
- }
47
-
48
- # Merge provided config with defaults
49
- self.config = {**self.default_config, **self.config}
50
-
51
- # Set up logging
52
- log_level = self.config.get("log_level", "INFO")
53
- numeric_level = getattr(logging, log_level.upper(), logging.INFO)
54
- logger.setLevel(numeric_level)
55
-
56
- logger.info(f"Initialized Triton provider with URL: {self.config['server_url']}")
57
-
58
- # Initialize model cache manager
59
- self.model_cache = ModelCacheManager(
60
- cache_size=self.config.get("model_cache_size"),
61
- model_repository=self.config.get("model_repository")
62
- )
63
-
64
- # For MLflow Gateway compatibility
65
- self.triton_url = config.get("triton_url", "localhost:8001")
66
-
67
- def get_capabilities(self) -> Dict[ModelType, List[Capability]]:
68
- """Get provider capabilities by model type"""
69
- return {
70
- ModelType.LLM: [
71
- Capability.CHAT,
72
- Capability.COMPLETION
73
- ],
74
- ModelType.EMBEDDING: [
75
- Capability.EMBEDDING
76
- ],
77
- ModelType.VISION: [
78
- Capability.IMAGE_UNDERSTANDING
79
- ]
80
- }
81
-
82
- def get_models(self, model_type: ModelType) -> List[str]:
83
- """Get available models for given type"""
84
- # Query the model cache manager for available models
85
- return self.model_cache.list_available_models(model_type)
86
-
87
- async def load_model(self, model_name: str, model_type: ModelType) -> bool:
88
- """Load a model into Triton server via Model Cache Manager"""
89
- return await self.model_cache.load_model(model_name, model_type)
90
-
91
- async def unload_model(self, model_name: str) -> bool:
92
- """Unload a model from Triton server"""
93
- return await self.model_cache.unload_model(model_name)
94
-
95
- def get_config(self) -> Dict[str, Any]:
96
- """
97
- Get the configuration for this provider.
98
-
99
- Returns:
100
- Provider configuration
101
- """
102
- return self.config
103
-
104
- def create_client(self):
105
- """
106
- Create a Triton client instance.
107
-
108
- Returns:
109
- Triton HTTP client
110
- """
111
- try:
112
- import tritonclient.http as httpclient
113
-
114
- server_url = self.config.get("triton_url", self.config["server_url"])
115
-
116
- client = httpclient.InferenceServerClient(
117
- url=server_url,
118
- verbose=self.config["verbose"],
119
- connection_timeout=self.config["client_timeout"],
120
- network_timeout=self.config["client_timeout"]
121
- )
122
-
123
- return client
124
- except ImportError:
125
- logger.error("tritonclient package not installed. Please install with: pip install tritonclient")
126
- raise
127
- except Exception as e:
128
- logger.error(f"Error creating Triton client: {str(e)}")
129
- raise
130
-
131
- def is_server_live(self) -> bool:
132
- """
133
- Check if the Triton server is live.
134
-
135
- Returns:
136
- True if the server is live, False otherwise
137
- """
138
- try:
139
- client = self.create_client()
140
- return client.is_server_live()
141
- except Exception as e:
142
- logger.error(f"Error checking server liveness: {str(e)}")
143
- return False
144
-
145
- def is_model_ready(self, model_name: str) -> bool:
146
- """
147
- Check if a model is ready on the Triton server.
148
-
149
- Args:
150
- model_name: Name of the model
151
-
152
- Returns:
153
- True if the model is ready, False otherwise
154
- """
155
- try:
156
- client = self.create_client()
157
- return client.is_model_ready(model_name)
158
- except Exception as e:
159
- logger.error(f"Error checking model readiness: {str(e)}")
160
- return False
161
-
162
- def get_model_metadata(self, model_name: str) -> Dict[str, Any]:
163
- """
164
- Get metadata for a model.
165
-
166
- Args:
167
- model_name: Name of the model
168
-
169
- Returns:
170
- Model metadata
171
- """
172
- try:
173
- client = self.create_client()
174
- metadata = client.get_model_metadata(model_name)
175
- return metadata
176
- except Exception as e:
177
- logger.error(f"Error getting model metadata: {str(e)}")
178
- raise
179
-
180
- def get_model_config(self, model_name: str) -> Dict[str, Any]:
181
- """
182
- Get configuration for a model.
183
-
184
- Args:
185
- model_name: Name of the model
186
-
187
- Returns:
188
- Model configuration
189
- """
190
- try:
191
- client = self.create_client()
192
- config = client.get_model_config(model_name)
193
- return config
194
- except Exception as e:
195
- logger.error(f"Error getting model config: {str(e)}")
196
- raise
197
-
198
- def is_reasoning_model(self, model_name: str) -> bool:
199
- """Check if the model is optimized for reasoning tasks"""
200
- # This is a simple implementation, could be enhanced to check model metadata
201
- return model_name.lower().find("reasoning") != -1 or model_name.lower() in ["llama3", "mistral"]
202
-
203
- # Methods for MLflow Gateway compatibility
204
-
205
- async def completions(self, prompt: str, model_name: str, params: Dict[str, Any]) -> Dict[str, Any]:
206
- """
207
- Generate completions for MLflow Gateway.
208
-
209
- Args:
210
- prompt: User prompt text
211
- model_name: Name of the model to use
212
- params: Additional parameters
213
-
214
- Returns:
215
- Completion response
216
- """
217
- try:
218
- import tritonclient.http as httpclient
219
-
220
- # Create client
221
- client = self.create_client()
222
-
223
- # Generate config
224
- generation_config = {
225
- "temperature": params.get("temperature", 0.7),
226
- "max_new_tokens": params.get("max_tokens", 512),
227
- "top_p": params.get("top_p", 0.9),
228
- "top_k": params.get("top_k", 50),
229
- }
230
-
231
- # Prepare inputs
232
- inputs = []
233
-
234
- # Add prompt input
235
- prompt_data = np.array([prompt], dtype=np.object_)
236
- prompt_input = httpclient.InferInput("prompt", prompt_data.shape, "BYTES")
237
- prompt_input.set_data_from_numpy(prompt_data)
238
- inputs.append(prompt_input)
239
-
240
- # Add system prompt if provided
241
- if "system_prompt" in params:
242
- system_data = np.array([params["system_prompt"]], dtype=np.object_)
243
- system_input = httpclient.InferInput("system_prompt", system_data.shape, "BYTES")
244
- system_input.set_data_from_numpy(system_data)
245
- inputs.append(system_input)
246
-
247
- # Add generation config
248
- config_data = np.array([json.dumps(generation_config)], dtype=np.object_)
249
- config_input = httpclient.InferInput("generation_config", config_data.shape, "BYTES")
250
- config_input.set_data_from_numpy(config_data)
251
- inputs.append(config_input)
252
-
253
- # Create output
254
- outputs = [httpclient.InferRequestedOutput("text_output")]
255
-
256
- # Run inference
257
- response = await asyncio.to_thread(
258
- client.infer,
259
- model_name,
260
- inputs,
261
- outputs=outputs
262
- )
263
-
264
- # Process response
265
- output = response.as_numpy("text_output")
266
- text = output[0].decode('utf-8')
267
-
268
- return {
269
- "completion": text,
270
- "metadata": {
271
- "model": model_name,
272
- "provider": "triton",
273
- "token_usage": {
274
- "prompt_tokens": len(prompt.split()),
275
- "completion_tokens": len(text.split()),
276
- "total_tokens": len(prompt.split()) + len(text.split())
277
- }
278
- }
279
- }
280
-
281
- except Exception as e:
282
- logger.error(f"Error during completion: {str(e)}")
283
- return {
284
- "error": str(e),
285
- "metadata": {
286
- "model": model_name,
287
- "provider": "triton"
288
- }
289
- }
290
-
291
- async def embeddings(self, text: Union[str, List[str]], model_name: str, params: Dict[str, Any]) -> Dict[str, Any]:
292
- """
293
- Generate embeddings for MLflow Gateway.
294
-
295
- Args:
296
- text: Text or list of texts to embed
297
- model_name: Name of the model to use
298
- params: Additional parameters
299
-
300
- Returns:
301
- Embedding response
302
- """
303
- try:
304
- import tritonclient.http as httpclient
305
-
306
- # Create client
307
- client = self.create_client()
308
-
309
- # Normalize parameter
310
- normalize = params.get("normalize", True)
311
-
312
- # Handle input text (convert to list if it's a single string)
313
- text_list = [text] if isinstance(text, str) else text
314
-
315
- # Add text input
316
- text_data = np.array(text_list, dtype=np.object_)
317
- text_input = httpclient.InferInput("text_input", text_data.shape, "BYTES")
318
- text_input.set_data_from_numpy(text_data)
319
-
320
- # Add normalize parameter
321
- normalize_data = np.array([normalize], dtype=bool)
322
- normalize_input = httpclient.InferInput("normalize", normalize_data.shape, "BOOL")
323
- normalize_input.set_data_from_numpy(normalize_data)
324
-
325
- # Create inputs
326
- inputs = [text_input, normalize_input]
327
-
328
- # Create output
329
- outputs = [httpclient.InferRequestedOutput("embedding")]
330
-
331
- # Run inference
332
- response = await asyncio.to_thread(
333
- client.infer,
334
- model_name,
335
- inputs,
336
- outputs=outputs
337
- )
338
-
339
- # Process response
340
- embedding_output = response.as_numpy("embedding")
341
-
342
- return {
343
- "embedding": embedding_output.tolist(),
344
- "metadata": {
345
- "model": model_name,
346
- "provider": "triton",
347
- "dimensions": embedding_output.shape[-1]
348
- }
349
- }
350
-
351
- except Exception as e:
352
- logger.error(f"Error during embedding: {str(e)}")
353
- return {
354
- "error": str(e),
355
- "metadata": {
356
- "model": model_name,
357
- "provider": "triton"
358
- }
359
- }
360
-
361
- async def speech_to_text(self, audio: str, model_name: str, params: Dict[str, Any]) -> Dict[str, Any]:
362
- """
363
- Transcribe audio for MLflow Gateway.
364
-
365
- Args:
366
- audio: Base64 encoded audio data or URL
367
- model_name: Name of the model to use
368
- params: Additional parameters
369
-
370
- Returns:
371
- Transcription response
372
- """
373
- try:
374
- import tritonclient.http as httpclient
375
-
376
- # Create client
377
- client = self.create_client()
378
-
379
- # Decode audio from base64 or download from URL
380
- if audio.startswith(("http://", "https://")):
381
- import requests
382
- audio_data = requests.get(audio).content
383
- else:
384
- audio_data = base64.b64decode(audio)
385
-
386
- # Language parameter
387
- language = params.get("language", "en")
388
-
389
- # Process audio to get numpy array
390
- import io
391
- import librosa
392
-
393
- with io.BytesIO(audio_data) as audio_bytes:
394
- audio_array, _ = librosa.load(audio_bytes, sr=16000)
395
- audio_array = audio_array.astype(np.float32)
396
-
397
- # Create inputs
398
- audio_input = httpclient.InferInput("audio_input", audio_array.shape, "FP32")
399
- audio_input.set_data_from_numpy(audio_array)
400
-
401
- language_data = np.array([language], dtype=np.object_)
402
- language_input = httpclient.InferInput("language", language_data.shape, "BYTES")
403
- language_input.set_data_from_numpy(language_data)
404
-
405
- inputs = [audio_input, language_input]
406
-
407
- # Create output
408
- outputs = [httpclient.InferRequestedOutput("text_output")]
409
-
410
- # Run inference
411
- response = await asyncio.to_thread(
412
- client.infer,
413
- model_name,
414
- inputs,
415
- outputs=outputs
416
- )
417
-
418
- # Process response
419
- output = response.as_numpy("text_output")
420
- transcription = output[0].decode('utf-8')
421
-
422
- return {
423
- "text": transcription,
424
- "metadata": {
425
- "model": model_name,
426
- "provider": "triton",
427
- "language": language
428
- }
429
- }
430
-
431
- except Exception as e:
432
- logger.error(f"Error during speech-to-text: {str(e)}")
433
- return {
434
- "error": str(e),
435
- "metadata": {
436
- "model": model_name,
437
- "provider": "triton"
438
- }
439
- }
@@ -1,108 +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 YydsProvider(BaseProvider):
10
- """Provider for YYDS API with proper API key management"""
11
-
12
- def __init__(self, config=None):
13
- """Initialize the YYDS Provider with centralized config management"""
14
- super().__init__(config)
15
- self.name = "yyds"
16
-
17
- logger.info(f"Initialized YydsProvider with URL: {self.config.get('base_url', 'https://api.yyds.com/v1')}")
18
-
19
- if not self.has_valid_credentials():
20
- logger.warning("YYDS API key not found. Set YYDS_API_KEY environment variable or pass api_key in config.")
21
-
22
- def _load_provider_env_vars(self):
23
- """Load YYDS-specific environment variables"""
24
- # Set defaults first
25
- defaults = {
26
- "base_url": "https://api.yyds.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": "YYDS_API_KEY",
41
- "base_url": "YYDS_API_BASE",
42
- "organization": "YYDS_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 YYDS configuration"""
52
- if not self.config.get("api_key"):
53
- logger.debug("YYDS 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("yyds", 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("yyds", 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("YYDS 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
- }
82
-
83
- def get_models(self, model_type: ModelType) -> List[str]:
84
- """Get available models for given type"""
85
- if model_type == ModelType.LLM:
86
- return ["claude-sonnet-4-20250514", "claude-3-5-sonnet-20241022"]
87
- else:
88
- return []
89
-
90
- def get_default_model(self, model_type: ModelType) -> str:
91
- """Get default model for a given type"""
92
- if model_type == ModelType.LLM:
93
- return "claude-sonnet-4-20250514"
94
- else:
95
- return ""
96
-
97
- def get_config(self) -> Dict[str, Any]:
98
- """Get provider configuration"""
99
- # Return a copy without sensitive information
100
- config_copy = self.config.copy()
101
- if "api_key" in config_copy:
102
- config_copy["api_key"] = "***" if config_copy["api_key"] else ""
103
- return config_copy
104
-
105
- def is_reasoning_model(self, model_name: str) -> bool:
106
- """Check if the model is optimized for reasoning tasks"""
107
- reasoning_models = ["claude-sonnet-4", "claude-3-5-sonnet"]
108
- return any(rm in model_name.lower() for rm in reasoning_models)