OneLLM 0.0.6__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.
@@ -0,0 +1,688 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # Unified interface for LLM providers using OpenAI format
5
+ # https://github.com/muxi-ai/onellm
6
+ #
7
+ # Copyright (C) 2025 Ran Aroussi
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """
22
+ Fallback provider proxy implementation.
23
+
24
+ This module implements a provider proxy that supports fallbacks to alternative models
25
+ when the primary model fails.
26
+ """
27
+
28
+ import logging
29
+ from typing import Any, AsyncGenerator, Dict, List, Optional, Union
30
+
31
+ from ..errors import APIError, FallbackExhaustionError
32
+ from ..models import (
33
+ ChatCompletionResponse,
34
+ ChatCompletionChunk,
35
+ CompletionResponse,
36
+ EmbeddingResponse,
37
+ FileObject,
38
+ )
39
+ from ..types import Message
40
+ from ..utils.fallback import FallbackConfig, maybe_await
41
+ from .base import Provider, get_provider, parse_model_name
42
+
43
+
44
+ class FallbackProviderProxy(Provider):
45
+ """Provider implementation that supports fallbacks to alternative models."""
46
+
47
+ def __init__(
48
+ self, models: List[str], fallback_config: Optional[FallbackConfig] = None
49
+ ):
50
+ """
51
+ Initialize with a list of models to try.
52
+
53
+ Args:
54
+ models: List of models to try in order (including primary model)
55
+ fallback_config: Optional configuration for fallback behavior
56
+ """
57
+ self.models = models
58
+ self.providers: Dict[str, Provider] = {} # Lazy-loaded providers
59
+ self.fallback_config = fallback_config or FallbackConfig()
60
+ self.logger = logging.getLogger("onellm.fallback")
61
+
62
+ # Lazy initialize capability flags - will be set on first access
63
+ self._json_mode_support = None
64
+ self._vision_support = None
65
+ self._audio_input_support = None
66
+ self._video_input_support = None
67
+ self._streaming_support = None
68
+ self._token_by_token_support = None
69
+ self._realtime_support = None
70
+
71
+ def _check_provider_capability(self, capability_name: str) -> bool:
72
+ """
73
+ Check if the primary provider supports a specific capability.
74
+
75
+ This method lazily loads the primary provider and checks if it supports
76
+ the requested capability.
77
+
78
+ Args:
79
+ capability_name: Name of the capability flag to check
80
+
81
+ Returns:
82
+ True if the primary provider supports the capability, False otherwise
83
+ """
84
+ if not self.models:
85
+ return False
86
+
87
+ # Get the provider for the primary model
88
+ primary_model = self.models[0]
89
+ provider_name, _ = parse_model_name(primary_model)
90
+
91
+ # Lazy load the provider if needed
92
+ if provider_name not in self.providers:
93
+ self.providers[provider_name] = get_provider(provider_name)
94
+
95
+ # Get the provider instance
96
+ provider = self.providers[provider_name]
97
+
98
+ # Check if the capability is supported
99
+ return getattr(provider, capability_name, False)
100
+
101
+ @property
102
+ def json_mode_support(self) -> bool:
103
+ """Check if JSON mode is supported by the primary provider."""
104
+ if self._json_mode_support is None:
105
+ # Lazy initialization of the capability flag
106
+ self._json_mode_support = self._check_provider_capability("json_mode_support")
107
+ return self._json_mode_support
108
+
109
+ @property
110
+ def vision_support(self) -> bool:
111
+ """Check if vision is supported by the primary provider."""
112
+ if self._vision_support is None:
113
+ # Lazy initialization of the capability flag
114
+ self._vision_support = self._check_provider_capability("vision_support")
115
+ return self._vision_support
116
+
117
+ @property
118
+ def audio_input_support(self) -> bool:
119
+ """Check if audio input is supported by the primary provider."""
120
+ if self._audio_input_support is None:
121
+ # Lazy initialization of the capability flag
122
+ self._audio_input_support = self._check_provider_capability("audio_input_support")
123
+ return self._audio_input_support
124
+
125
+ @property
126
+ def video_input_support(self) -> bool:
127
+ """Check if video input is supported by the primary provider."""
128
+ if self._video_input_support is None:
129
+ # Lazy initialization of the capability flag
130
+ self._video_input_support = self._check_provider_capability("video_input_support")
131
+ return self._video_input_support
132
+
133
+ @property
134
+ def streaming_support(self) -> bool:
135
+ """Check if streaming is supported by the primary provider."""
136
+ if self._streaming_support is None:
137
+ # Lazy initialization of the capability flag
138
+ self._streaming_support = self._check_provider_capability("streaming_support")
139
+ return self._streaming_support
140
+
141
+ @property
142
+ def token_by_token_support(self) -> bool:
143
+ """Check if token-by-token streaming is supported by the primary provider."""
144
+ if self._token_by_token_support is None:
145
+ # Lazy initialization of the capability flag
146
+ self._token_by_token_support = self._check_provider_capability("token_by_token_support")
147
+ return self._token_by_token_support
148
+
149
+ @property
150
+ def realtime_support(self) -> bool:
151
+ """Check if realtime API is supported by the primary provider."""
152
+ if self._realtime_support is None:
153
+ # Lazy initialization of the capability flag
154
+ self._realtime_support = self._check_provider_capability("realtime_support")
155
+ return self._realtime_support
156
+
157
+ async def _try_with_fallbacks(
158
+ self, method_name: str, *args: Any, **kwargs: Any
159
+ ) -> Any:
160
+ """
161
+ Try a provider method with fallbacks.
162
+
163
+ This method attempts to call the specified method on each provider in sequence,
164
+ starting with the primary model and falling back to alternatives if errors occur.
165
+
166
+ Args:
167
+ method_name: Name of the provider method to call
168
+ *args: Arguments to pass to the method
169
+ **kwargs: Keyword arguments to pass to the method
170
+
171
+ Returns:
172
+ Result of the successful method call
173
+
174
+ Raises:
175
+ FallbackExhaustionError: If all models fail
176
+ AttributeError: If method is missing on all providers
177
+ """
178
+ last_error = None
179
+ models_tried = []
180
+ attribute_errors = 0
181
+
182
+ # Limit the number of fallbacks if max_fallbacks is set
183
+ models_to_try = self.models
184
+ if self.fallback_config.max_fallbacks is not None:
185
+ # Only try up to max_fallbacks+1 models (primary + fallbacks)
186
+ models_to_try = self.models[: self.fallback_config.max_fallbacks + 1]
187
+
188
+ # Try each model in sequence
189
+ for model_string in models_to_try:
190
+ provider_name, model_name = parse_model_name(model_string)
191
+ models_tried.append(model_string)
192
+
193
+ # Get or create provider instance
194
+ if provider_name not in self.providers:
195
+ # Lazy load the provider
196
+ self.providers[provider_name] = get_provider(provider_name)
197
+
198
+ provider = self.providers[provider_name]
199
+
200
+ try:
201
+ # Get the provider method
202
+ method = getattr(provider, method_name)
203
+
204
+ # Call the method with the appropriate model
205
+ kwargs_with_model = {**kwargs, "model": model_name}
206
+ result = await method(*args, **kwargs_with_model)
207
+
208
+ # Log fallback usage if not the primary model
209
+ if (
210
+ model_string != self.models[0]
211
+ and self.fallback_config.log_fallbacks
212
+ ):
213
+ self.logger.info(
214
+ f"Fallback succeeded: Using {model_string} instead of {self.models[0]}"
215
+ )
216
+
217
+ # Call the callback if provided and we're using a fallback model
218
+ if (
219
+ model_string != self.models[0]
220
+ and self.fallback_config.fallback_callback
221
+ ):
222
+ await maybe_await(
223
+ self.fallback_config.fallback_callback(
224
+ primary_model=self.models[0],
225
+ fallback_model=model_string,
226
+ error=last_error,
227
+ )
228
+ )
229
+
230
+ return result
231
+
232
+ except AttributeError as e:
233
+ # Method not implemented on this provider
234
+ attribute_errors += 1
235
+ last_error = e
236
+ # Continue to next provider without logging as retriable
237
+ continue
238
+
239
+ except Exception as e:
240
+ last_error = e
241
+
242
+ # Log the failure
243
+ if self.fallback_config.log_fallbacks:
244
+ self.logger.warning(f"Model {model_string} failed: {str(e)}")
245
+
246
+ # Determine if this error should trigger a fallback
247
+ retriable = any(
248
+ isinstance(e, err_type)
249
+ for err_type in self.fallback_config.retriable_errors
250
+ )
251
+ if not retriable:
252
+ # Non-retriable error - raise immediately
253
+ raise
254
+
255
+ # Continue to next fallback
256
+
257
+ # If attribute errors on all providers, that means the method wasn't supported
258
+ if attribute_errors == len(models_tried) and last_error:
259
+ raise last_error # Re-raise the AttributeError
260
+
261
+ # If we get here, all models failed
262
+ if last_error:
263
+ # Use the correct fallback_models list based on max_fallbacks
264
+ fallback_models = self.models[1:]
265
+ if self.fallback_config.max_fallbacks is not None:
266
+ fallback_models = self.models[1:self.fallback_config.max_fallbacks + 1]
267
+
268
+ raise FallbackExhaustionError(
269
+ message=f"All models failed: {str(last_error)}",
270
+ primary_model=self.models[0],
271
+ fallback_models=fallback_models,
272
+ models_tried=models_tried,
273
+ original_error=last_error,
274
+ )
275
+
276
+ # Should never reach here, but just in case
277
+ raise APIError(
278
+ f"All models failed but no error was recorded. Models tried: {models_tried}"
279
+ )
280
+
281
+ async def _try_streaming_with_fallbacks(
282
+ self, method_name: str, *args: Any, **kwargs: Any
283
+ ) -> AsyncGenerator[Any, None]:
284
+ """
285
+ Try a streaming method with fallbacks.
286
+
287
+ This method attempts to call the specified streaming method on each provider in sequence,
288
+ starting with the primary model and falling back to alternatives if errors occur.
289
+
290
+ Args:
291
+ method_name: Name of the provider method to call
292
+ *args: Arguments to pass to the method
293
+ **kwargs: Keyword arguments to pass to the method
294
+
295
+ Returns:
296
+ AsyncGenerator from the first successful provider
297
+
298
+ Raises:
299
+ FallbackExhaustionError: If all models fail
300
+ """
301
+ last_error = None
302
+ models_tried = []
303
+
304
+ # Limit the number of fallbacks if max_fallbacks is set
305
+ models_to_try = self.models
306
+ if self.fallback_config.max_fallbacks is not None:
307
+ # Only try up to max_fallbacks+1 models (primary + fallbacks)
308
+ models_to_try = self.models[: self.fallback_config.max_fallbacks + 1]
309
+
310
+ # Try each model in sequence
311
+ for model_string in models_to_try:
312
+ provider_name, model_name = parse_model_name(model_string)
313
+ models_tried.append(model_string)
314
+
315
+ # Get or create provider instance
316
+ if provider_name not in self.providers:
317
+ # Lazy load the provider
318
+ self.providers[provider_name] = get_provider(provider_name)
319
+
320
+ provider = self.providers[provider_name]
321
+
322
+ try:
323
+ # Get the provider method
324
+ method = getattr(provider, method_name)
325
+
326
+ # Call the method with the appropriate model to get the generator
327
+ kwargs_with_model = {**kwargs, "model": model_name}
328
+ generator = await method(*args, **kwargs_with_model)
329
+
330
+ # Log fallback usage if not the primary model
331
+ if (
332
+ model_string != self.models[0]
333
+ and self.fallback_config.log_fallbacks
334
+ ):
335
+ self.logger.info(
336
+ f"Fallback succeeded: Using {model_string} instead of {self.models[0]}"
337
+ )
338
+
339
+ # Call the callback if provided and we're using a fallback model
340
+ if (
341
+ model_string != self.models[0]
342
+ and self.fallback_config.fallback_callback
343
+ ):
344
+ await maybe_await(
345
+ self.fallback_config.fallback_callback(
346
+ primary_model=self.models[0],
347
+ fallback_model=model_string,
348
+ error=last_error,
349
+ )
350
+ )
351
+
352
+ # Create a wrapper generator that forwards chunks but handles errors
353
+ async def safe_generator():
354
+ """
355
+ Wrapper generator that handles errors during streaming.
356
+
357
+ This ensures proper error propagation if the generator fails
358
+ after yielding some chunks.
359
+ """
360
+ try:
361
+ async for chunk in generator:
362
+ yield chunk
363
+ except Exception as e:
364
+ # If the generator fails after yielding some chunks,
365
+ # propagate the error with proper error type
366
+ if any(
367
+ isinstance(e, err_type)
368
+ for err_type in self.fallback_config.retriable_errors
369
+ ):
370
+ # This is a retriable error, let the outer loop handle it
371
+ raise
372
+ else:
373
+ # Non-retriable error, propagate directly
374
+ raise
375
+
376
+ # Return the wrapped generator
377
+ return safe_generator()
378
+
379
+ except Exception as e:
380
+ last_error = e
381
+
382
+ # Log the failure
383
+ if self.fallback_config.log_fallbacks:
384
+ self.logger.warning(f"Model {model_string} failed: {str(e)}")
385
+
386
+ # Determine if this error should trigger a fallback
387
+ retriable = any(
388
+ isinstance(e, err_type)
389
+ for err_type in self.fallback_config.retriable_errors
390
+ )
391
+ if not retriable:
392
+ # Non-retriable error - raise immediately
393
+ raise
394
+
395
+ # Continue to next fallback
396
+
397
+ # If we get here, all models failed
398
+ if last_error:
399
+ # Use the correct fallback_models list based on max_fallbacks
400
+ fallback_models = self.models[1:]
401
+ if self.fallback_config.max_fallbacks is not None:
402
+ fallback_models = self.models[1:self.fallback_config.max_fallbacks + 1]
403
+
404
+ raise FallbackExhaustionError(
405
+ message=f"All models failed: {str(last_error)}",
406
+ primary_model=self.models[0],
407
+ fallback_models=fallback_models,
408
+ models_tried=models_tried,
409
+ original_error=last_error,
410
+ )
411
+
412
+ # Should never reach here, but just in case
413
+ raise APIError(
414
+ f"All models failed but no error was recorded. Models tried: {models_tried}"
415
+ )
416
+
417
+ async def create_chat_completion(
418
+ self,
419
+ messages: List[Message],
420
+ model: str = None, # Ignored since we use models from the proxy
421
+ stream: bool = False,
422
+ **kwargs,
423
+ ) -> Union[ChatCompletionResponse, AsyncGenerator[ChatCompletionChunk, None]]:
424
+ """
425
+ Create a chat completion with fallback support.
426
+
427
+ This method will try the primary model first and fall back to alternative models
428
+ if the primary model fails.
429
+
430
+ Args:
431
+ messages: List of messages to send to the model
432
+ model: Ignored parameter (models are defined in the proxy)
433
+ stream: Whether to stream the response
434
+ **kwargs: Additional parameters to pass to the provider
435
+
436
+ Returns:
437
+ Either a ChatCompletionResponse or an AsyncGenerator of ChatCompletionChunk
438
+ depending on the stream parameter
439
+ """
440
+ # Special handling for streaming
441
+ if stream:
442
+ try:
443
+ # Get streaming generator from _try_streaming_with_fallbacks
444
+ generator = await self._try_streaming_with_fallbacks(
445
+ "create_chat_completion", messages=messages, stream=stream, **kwargs
446
+ )
447
+
448
+ # Create a wrapper generator that just yields from the inner generator
449
+ async def stream_generator():
450
+ """Simple wrapper to yield chunks from the inner generator."""
451
+ async for chunk in generator:
452
+ yield chunk
453
+
454
+ return stream_generator()
455
+ except Exception as e:
456
+ # Propagate exceptions correctly
457
+ raise e
458
+ else:
459
+ # For non-streaming requests, use the standard fallback mechanism
460
+ return await self._try_with_fallbacks(
461
+ "create_chat_completion", messages=messages, stream=stream, **kwargs
462
+ )
463
+
464
+ async def create_completion(
465
+ self,
466
+ prompt: str,
467
+ model: str = None, # Ignored since we use models from the proxy
468
+ stream: bool = False,
469
+ **kwargs,
470
+ ) -> Union[CompletionResponse, AsyncGenerator[Any, None]]:
471
+ """
472
+ Create a text completion with fallback support.
473
+
474
+ This method will try the primary model first and fall back to alternative models
475
+ if the primary model fails.
476
+
477
+ Args:
478
+ prompt: Text prompt to send to the model
479
+ model: Ignored parameter (models are defined in the proxy)
480
+ stream: Whether to stream the response
481
+ **kwargs: Additional parameters to pass to the provider
482
+
483
+ Returns:
484
+ Either a CompletionResponse or an AsyncGenerator depending on the stream parameter
485
+ """
486
+ # Special handling for streaming
487
+ if stream:
488
+ try:
489
+ # Get streaming generator from _try_streaming_with_fallbacks
490
+ generator = await self._try_streaming_with_fallbacks(
491
+ "create_completion", prompt=prompt, stream=stream, **kwargs
492
+ )
493
+
494
+ # Create a wrapper generator that just yields from the inner generator
495
+ async def stream_generator():
496
+ """Simple wrapper to yield chunks from the inner generator."""
497
+ async for chunk in generator:
498
+ yield chunk
499
+
500
+ return stream_generator()
501
+ except Exception as e:
502
+ # Propagate exceptions correctly
503
+ raise e
504
+ else:
505
+ # For non-streaming requests, use the standard fallback mechanism
506
+ return await self._try_with_fallbacks(
507
+ "create_completion", prompt=prompt, stream=stream, **kwargs
508
+ )
509
+
510
+ async def create_embedding(
511
+ self,
512
+ input: Union[str, List[str]],
513
+ model: str = None, # Ignored since we use models from the proxy
514
+ **kwargs,
515
+ ) -> EmbeddingResponse:
516
+ """
517
+ Create embeddings with fallback support.
518
+
519
+ This method will try the primary model first and fall back to alternative models
520
+ if the primary model fails.
521
+
522
+ Args:
523
+ input: Text or list of texts to create embeddings for
524
+ model: Ignored parameter (models are defined in the proxy)
525
+ **kwargs: Additional parameters to pass to the provider
526
+
527
+ Returns:
528
+ EmbeddingResponse containing the embeddings
529
+ """
530
+ return await self._try_with_fallbacks("create_embedding", input=input, **kwargs)
531
+
532
+ async def upload_file(self, file: Any, purpose: str, **kwargs) -> FileObject:
533
+ """
534
+ Upload a file with fallback support.
535
+
536
+ This method will try the primary provider first and fall back to alternative providers
537
+ if the primary provider fails.
538
+
539
+ Args:
540
+ file: File to upload
541
+ purpose: Purpose of the file
542
+ **kwargs: Additional parameters to pass to the provider
543
+
544
+ Returns:
545
+ FileObject containing information about the uploaded file
546
+ """
547
+ return await self._try_with_fallbacks(
548
+ "upload_file", file=file, purpose=purpose, **kwargs
549
+ )
550
+
551
+ async def download_file(self, file_id: str, **kwargs) -> bytes:
552
+ """
553
+ Download a file with fallback support.
554
+
555
+ This method will try the primary provider first and fall back to alternative providers
556
+ if the primary provider fails.
557
+
558
+ Args:
559
+ file_id: ID of the file to download
560
+ **kwargs: Additional parameters to pass to the provider
561
+
562
+ Returns:
563
+ File content as bytes
564
+ """
565
+ return await self._try_with_fallbacks(
566
+ "download_file", file_id=file_id, **kwargs
567
+ )
568
+
569
+ async def create_speech(
570
+ self,
571
+ input: str,
572
+ model: str = None, # Ignored since we use models from the proxy
573
+ **kwargs,
574
+ ) -> bytes:
575
+ """
576
+ Create speech with fallback support.
577
+
578
+ This method will try the primary model first and fall back to alternative models
579
+ if the primary model fails.
580
+
581
+ Args:
582
+ input: Text to convert to speech
583
+ model: Ignored parameter (models are defined in the proxy)
584
+ **kwargs: Additional parameters to pass to the provider
585
+
586
+ Returns:
587
+ Audio data as bytes
588
+ """
589
+ # This method is not required by the Provider interface, so check provider support
590
+ return await self._try_with_fallbacks("create_speech", input=input, **kwargs)
591
+
592
+ async def create_image(
593
+ self,
594
+ prompt: str,
595
+ model: str = None, # Ignored since we use models from the proxy
596
+ **kwargs,
597
+ ) -> List[Dict[str, Any]]:
598
+ """
599
+ Create images with fallback support.
600
+
601
+ This method will try the primary model first and fall back to alternative models
602
+ if the primary model fails.
603
+
604
+ Args:
605
+ prompt: Text prompt to generate images from
606
+ model: Ignored parameter (models are defined in the proxy)
607
+ **kwargs: Additional parameters to pass to the provider
608
+
609
+ Returns:
610
+ List of dictionaries containing image data
611
+ """
612
+ # This method is not required by the Provider interface, so check provider support
613
+ return await self._try_with_fallbacks("create_image", prompt=prompt, **kwargs)
614
+
615
+ async def create_transcription(
616
+ self,
617
+ file: Any,
618
+ model: str = None, # Ignored since we use models from the proxy
619
+ **kwargs,
620
+ ) -> Dict[str, Any]:
621
+ """
622
+ Create a transcription with fallback support.
623
+
624
+ This method will try the primary model first and fall back to alternative models
625
+ if the primary model fails.
626
+
627
+ Args:
628
+ file: Audio file to transcribe
629
+ model: Ignored parameter (models are defined in the proxy)
630
+ **kwargs: Additional parameters to pass to the provider
631
+
632
+ Returns:
633
+ Dictionary containing the transcription
634
+ """
635
+ return await self._try_with_fallbacks("create_transcription", file=file, **kwargs)
636
+
637
+ async def create_translation(
638
+ self,
639
+ file: Any,
640
+ model: str = None, # Ignored since we use models from the proxy
641
+ **kwargs,
642
+ ) -> Dict[str, Any]:
643
+ """
644
+ Create a translation with fallback support.
645
+
646
+ This method will try the primary model first and fall back to alternative models
647
+ if the primary model fails.
648
+
649
+ Args:
650
+ file: Audio file to translate
651
+ model: Ignored parameter (models are defined in the proxy)
652
+ **kwargs: Additional parameters to pass to the provider
653
+
654
+ Returns:
655
+ Dictionary containing the translation
656
+ """
657
+ return await self._try_with_fallbacks("create_translation", file=file, **kwargs)
658
+
659
+ async def list_files(self, **kwargs) -> List[Dict[str, Any]]:
660
+ """
661
+ List files with fallback support.
662
+
663
+ This method will try the primary provider first and fall back to alternative providers
664
+ if the primary provider fails.
665
+
666
+ Args:
667
+ **kwargs: Additional parameters to pass to the provider
668
+
669
+ Returns:
670
+ List of dictionaries containing file information
671
+ """
672
+ return await self._try_with_fallbacks("list_files", **kwargs)
673
+
674
+ async def delete_file(self, file_id: str, **kwargs) -> Dict[str, Any]:
675
+ """
676
+ Delete a file with fallback support.
677
+
678
+ This method will try the primary provider first and fall back to alternative providers
679
+ if the primary provider fails.
680
+
681
+ Args:
682
+ file_id: ID of the file to delete
683
+ **kwargs: Additional parameters to pass to the provider
684
+
685
+ Returns:
686
+ Dictionary containing the deletion result
687
+ """
688
+ return await self._try_with_fallbacks("delete_file", file_id=file_id, **kwargs)