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.
onellm/errors.py ADDED
@@ -0,0 +1,250 @@
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
+ Standardized error types for OneLLM.
23
+
24
+ This module provides consistent error classes across different LLM providers
25
+ to help with error handling in client code.
26
+ """
27
+
28
+ from typing import Any, Dict, List, Optional
29
+
30
+
31
+ class MuxiLLMError(Exception):
32
+ """
33
+ Base exception class for OneLLM errors.
34
+
35
+ This serves as the parent class for all custom exceptions in the library,
36
+ providing a consistent interface for error handling.
37
+
38
+ Attributes:
39
+ message: Human-readable error description
40
+ provider: Name of the LLM provider that generated the error
41
+ status_code: HTTP status code if applicable
42
+ request_id: Unique identifier for the request that failed
43
+ error_data: Additional error details from the provider
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ message: str,
49
+ provider: Optional[str] = None,
50
+ status_code: Optional[int] = None,
51
+ request_id: Optional[str] = None,
52
+ error_data: Optional[Dict[str, Any]] = None,
53
+ ):
54
+ # Initialize the parent Exception class with the error message
55
+ super().__init__(message)
56
+ # Store all error details as instance attributes
57
+ self.message = message
58
+ self.provider = provider
59
+ self.status_code = status_code
60
+ self.request_id = request_id
61
+ # Initialize error_data as empty dict if None is provided
62
+ self.error_data = error_data or {}
63
+
64
+ def __str__(self) -> str:
65
+ """
66
+ Create a formatted string representation of the error.
67
+
68
+ Returns:
69
+ A string containing the error message and any available metadata.
70
+ """
71
+ # Add provider information if available
72
+ provider_msg = f" (Provider: {self.provider})" if self.provider else ""
73
+ # Add status code if available
74
+ status_msg = f" Status: {self.status_code}" if self.status_code else ""
75
+ # Add request ID if available
76
+ request_msg = f" Request ID: {self.request_id}" if self.request_id else ""
77
+ # Combine all components into a single error message
78
+ return f"{self.message}{provider_msg}{status_msg}{request_msg}"
79
+
80
+
81
+ class APIError(MuxiLLMError):
82
+ """
83
+ Raised when the provider's API returns an unexpected error.
84
+
85
+ This is a general-purpose error for unexpected API responses that don't
86
+ fit into more specific error categories.
87
+ """
88
+
89
+ pass
90
+
91
+
92
+ class AuthenticationError(MuxiLLMError):
93
+ """
94
+ Raised when there are authentication issues (invalid API key, etc.).
95
+
96
+ This typically occurs when the API key is invalid, expired, or missing.
97
+ """
98
+
99
+ pass
100
+
101
+
102
+ class RateLimitError(MuxiLLMError):
103
+ """
104
+ Raised when the provider's rate limit is exceeded.
105
+
106
+ This occurs when too many requests are made in a short period of time,
107
+ exceeding the provider's usage limits.
108
+ """
109
+
110
+ pass
111
+
112
+
113
+ class InvalidRequestError(MuxiLLMError):
114
+ """
115
+ Raised when the request parameters are invalid.
116
+
117
+ This occurs when the request contains invalid parameters, such as
118
+ malformed JSON, invalid model parameters, or other client-side errors.
119
+ """
120
+
121
+ pass
122
+
123
+
124
+ class ServiceUnavailableError(MuxiLLMError):
125
+ """
126
+ Raised when the provider's service is unavailable.
127
+
128
+ This typically occurs during provider outages or maintenance periods.
129
+ """
130
+
131
+ pass
132
+
133
+
134
+ class TimeoutError(MuxiLLMError):
135
+ """
136
+ Raised when a request times out.
137
+
138
+ This occurs when the provider takes too long to respond to a request,
139
+ exceeding the configured timeout threshold.
140
+ """
141
+
142
+ pass
143
+
144
+
145
+ class BadGatewayError(MuxiLLMError):
146
+ """
147
+ Raised when a bad gateway error occurs.
148
+
149
+ This typically indicates an issue with the provider's infrastructure
150
+ or an intermediate proxy server.
151
+ """
152
+
153
+ pass
154
+
155
+
156
+ class PermissionError(MuxiLLMError):
157
+ """
158
+ Raised when permission is denied for the requested operation.
159
+
160
+ This occurs when the API key doesn't have sufficient permissions
161
+ to access the requested resource or perform the requested operation.
162
+ """
163
+
164
+ pass
165
+
166
+
167
+ class ResourceNotFoundError(MuxiLLMError):
168
+ """
169
+ Raised when a requested resource is not found.
170
+
171
+ This occurs when attempting to access a resource (model, file, etc.)
172
+ that doesn't exist or has been deleted.
173
+ """
174
+
175
+ pass
176
+
177
+
178
+ class InvalidModelError(InvalidRequestError):
179
+ """
180
+ Raised when an invalid or unsupported model is requested.
181
+
182
+ This is a specialized form of InvalidRequestError specifically for
183
+ cases where the requested model doesn't exist or isn't available.
184
+ """
185
+
186
+ pass
187
+
188
+
189
+ class InvalidConfigurationError(MuxiLLMError):
190
+ """
191
+ Raised when the library is configured incorrectly.
192
+
193
+ This occurs when there are issues with the library configuration,
194
+ such as missing required settings or incompatible options.
195
+ """
196
+
197
+ pass
198
+
199
+
200
+ class FallbackExhaustionError(MuxiLLMError):
201
+ """
202
+ Error raised when all fallback models have been tried and failed.
203
+
204
+ This occurs when the primary model and all specified fallback models
205
+ have been attempted without success, leaving no further options.
206
+
207
+ Attributes:
208
+ primary_model: The original model that was requested
209
+ fallback_models: List of fallback models that were specified
210
+ models_tried: List of models that were actually attempted
211
+ original_error: The exception from the last failed attempt
212
+ """
213
+
214
+ def __init__(
215
+ self,
216
+ message: str,
217
+ primary_model: str,
218
+ fallback_models: List[str],
219
+ models_tried: List[str],
220
+ original_error: Exception,
221
+ **kwargs,
222
+ ):
223
+ # Initialize the parent class with the message and any additional kwargs
224
+ super().__init__(message, **kwargs)
225
+ # Store information about the models and the original error
226
+ self.primary_model = primary_model
227
+ self.fallback_models = fallback_models
228
+ self.models_tried = models_tried
229
+ self.original_error = original_error
230
+
231
+ def __str__(self) -> str:
232
+ """
233
+ Create a detailed string representation of the fallback exhaustion error.
234
+
235
+ Returns:
236
+ A multi-line string containing the error message and details about
237
+ the models that were tried.
238
+ """
239
+ # Get the base error message from the parent class
240
+ base_str = super().__str__()
241
+ # Create comma-separated lists of fallback models and tried models
242
+ fallbacks = ", ".join(self.fallback_models)
243
+ tried = ", ".join(self.models_tried)
244
+ # Return a formatted multi-line error message with all relevant details
245
+ return (
246
+ f"{base_str}\n"
247
+ f"Primary model: {self.primary_model}\n"
248
+ f"Fallback models: {fallbacks}\n"
249
+ f"Models tried: {tried}"
250
+ )
onellm/files.py ADDED
@@ -0,0 +1,318 @@
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
+ File handling utilities for OneLLM.
23
+
24
+ This module provides a unified interface for working with files across different LLM providers,
25
+ including uploading, retrieving, and listing files.
26
+ """
27
+
28
+ from pathlib import Path
29
+ from typing import BinaryIO, Union
30
+
31
+ from .providers.base import get_provider
32
+ from .models import FileObject
33
+
34
+
35
+ class File:
36
+ """Interface for file operations across different providers."""
37
+
38
+ @classmethod
39
+ def upload(
40
+ cls,
41
+ file: Union[str, Path, BinaryIO, bytes],
42
+ purpose: str = "assistants",
43
+ provider: str = "openai", # Required but defaults for compatibility
44
+ **kwargs
45
+ ) -> FileObject:
46
+ """
47
+ Upload a file to the provider's API.
48
+
49
+ Args:
50
+ file: File to upload (path, bytes, or file-like object)
51
+ purpose: Purpose of the file (defaults to "assistants")
52
+ provider: Provider to use (e.g., "openai")
53
+ **kwargs: Additional parameters to pass to the provider
54
+
55
+ Returns:
56
+ FileObject representing the uploaded file
57
+
58
+ Example:
59
+ >>> file_obj = File.upload("path/to/file.pdf", purpose="fine-tune", provider="openai")
60
+ >>> print(f"Uploaded file ID: {file_obj.id}")
61
+ """
62
+ # Get provider instance
63
+ provider_instance = get_provider(provider)
64
+
65
+ # Call the provider's upload_file method synchronously
66
+ # We need to use asyncio.run to call the async method from a synchronous context
67
+ import asyncio
68
+
69
+ return asyncio.run(
70
+ provider_instance.upload_file(file=file, purpose=purpose, **kwargs)
71
+ )
72
+
73
+ @classmethod
74
+ async def aupload(
75
+ cls,
76
+ file: Union[str, Path, BinaryIO, bytes],
77
+ purpose: str = "assistants",
78
+ provider: str = "openai", # Required but defaults for compatibility
79
+ **kwargs
80
+ ) -> FileObject:
81
+ """
82
+ Upload a file to the provider's API asynchronously.
83
+
84
+ Args:
85
+ file: File to upload (path, bytes, or file-like object)
86
+ purpose: Purpose of the file (defaults to "assistants")
87
+ provider: Provider to use (e.g., "openai")
88
+ **kwargs: Additional parameters to pass to the provider
89
+
90
+ Returns:
91
+ FileObject representing the uploaded file
92
+
93
+ Example:
94
+ >>> file_obj = await File.aupload("file.pdf", purpose="fine-tune", provider="openai")
95
+ >>> print(f"Uploaded file ID: {file_obj.id}")
96
+ """
97
+ # Get provider instance
98
+ provider_instance = get_provider(provider)
99
+
100
+ # Call the provider's upload_file method
101
+ # This is the async version, so we directly await the result
102
+ return await provider_instance.upload_file(file=file, purpose=purpose, **kwargs)
103
+
104
+ @classmethod
105
+ def download(
106
+ cls,
107
+ file_id: str,
108
+ destination: Union[str, Path, None] = None,
109
+ provider: str = "openai", # Required but defaults for compatibility
110
+ **kwargs
111
+ ) -> Union[bytes, str]:
112
+ """
113
+ Download a file from the provider's API.
114
+
115
+ Args:
116
+ file_id: ID of the file to download
117
+ destination: Optional path where to save the file
118
+ provider: Provider to use (e.g., "openai")
119
+ **kwargs: Additional parameters to pass to the provider
120
+
121
+ Returns:
122
+ Bytes content of the file if destination is None, otherwise path to the saved file
123
+
124
+ Example:
125
+ >>> file_bytes = File.download("file-abc123", provider="openai")
126
+ >>> # or
127
+ >>> file_path = File.download("file-abc123", destination="file.txt", provider="openai")
128
+ """
129
+ # Get provider instance
130
+ provider_instance = get_provider(provider)
131
+
132
+ # Call the provider's download_file method synchronously
133
+ # We need to use asyncio.run to call the async method from a synchronous context
134
+ import asyncio
135
+
136
+ file_bytes = asyncio.run(
137
+ provider_instance.download_file(file_id=file_id, **kwargs)
138
+ )
139
+
140
+ # Save to destination if provided
141
+ # If a destination path is given, save the file and return the path
142
+ # Otherwise, return the raw bytes
143
+ if destination:
144
+ dest_path = Path(destination)
145
+ # Create parent directories if they don't exist
146
+ dest_path.parent.mkdir(parents=True, exist_ok=True)
147
+ # Write the file contents
148
+ with open(dest_path, "wb") as f:
149
+ f.write(file_bytes)
150
+ return str(dest_path)
151
+
152
+ return file_bytes
153
+
154
+ @classmethod
155
+ async def adownload(
156
+ cls,
157
+ file_id: str,
158
+ destination: Union[str, Path, None] = None,
159
+ provider: str = "openai", # Required but defaults for compatibility
160
+ **kwargs
161
+ ) -> Union[bytes, str]:
162
+ """
163
+ Download a file from the provider's API asynchronously.
164
+
165
+ Args:
166
+ file_id: ID of the file to download
167
+ destination: Optional path where to save the file
168
+ provider: Provider to use (e.g., "openai")
169
+ **kwargs: Additional parameters to pass to the provider
170
+
171
+ Returns:
172
+ Bytes content of the file if destination is None, otherwise path to the saved file
173
+
174
+ Example:
175
+ >>> file_bytes = await File.adownload("file", provider="openai")
176
+ >>> # or
177
+ >>> file_path = await File.adownload("file", destination="file.txt", provider="openai")
178
+ """
179
+ # Get provider instance
180
+ provider_instance = get_provider(provider)
181
+
182
+ # Call the provider's download_file method
183
+ # This is the async version, so we directly await the result
184
+ file_bytes = await provider_instance.download_file(file_id=file_id, **kwargs)
185
+
186
+ # Save to destination if provided
187
+ # If a destination path is given, save the file and return the path
188
+ # Otherwise, return the raw bytes
189
+ if destination:
190
+ dest_path = Path(destination)
191
+ # Create parent directories if they don't exist
192
+ dest_path.parent.mkdir(parents=True, exist_ok=True)
193
+ # Write the file contents
194
+ with open(dest_path, "wb") as f:
195
+ f.write(file_bytes)
196
+ return str(dest_path)
197
+
198
+ return file_bytes
199
+
200
+ @classmethod
201
+ def list(
202
+ cls,
203
+ provider: str = "openai", # Required but defaults for compatibility
204
+ **kwargs
205
+ ) -> dict:
206
+ """
207
+ List files from the provider's API.
208
+
209
+ Args:
210
+ provider: Provider to use (e.g., "openai")
211
+ **kwargs: Additional parameters to pass to the provider like 'purpose'
212
+
213
+ Returns:
214
+ Dictionary containing the list of files
215
+
216
+ Example:
217
+ >>> files = File.list(provider="openai", purpose="fine-tune")
218
+ >>> for file in files["data"]:
219
+ >>> print(f"File: {file['filename']}, ID: {file['id']}")
220
+ """
221
+ # Get provider instance
222
+ provider_instance = get_provider(provider)
223
+
224
+ # Call the provider's list_files method synchronously
225
+ # We need to use asyncio.run to call the async method from a synchronous context
226
+ import asyncio
227
+
228
+ return asyncio.run(provider_instance.list_files(**kwargs))
229
+
230
+ @classmethod
231
+ async def alist(
232
+ cls,
233
+ provider: str = "openai", # Required but defaults for compatibility
234
+ **kwargs
235
+ ) -> dict:
236
+ """
237
+ List files from the provider's API asynchronously.
238
+
239
+ Args:
240
+ provider: Provider to use (e.g., "openai")
241
+ **kwargs: Additional parameters to pass to the provider like 'purpose'
242
+
243
+ Returns:
244
+ Dictionary containing the list of files
245
+
246
+ Example:
247
+ >>> files = await File.alist(provider="openai", purpose="fine-tune")
248
+ >>> for file in files["data"]:
249
+ >>> print(f"File: {file['filename']}, ID: {file['id']}")
250
+ """
251
+ # Get provider instance
252
+ provider_instance = get_provider(provider)
253
+
254
+ # Call the provider's list_files method
255
+ # This is the async version, so we directly await the result
256
+ return await provider_instance.list_files(**kwargs)
257
+
258
+ @classmethod
259
+ def delete(
260
+ cls,
261
+ file_id: str,
262
+ provider: str = "openai", # Required but defaults for compatibility
263
+ **kwargs
264
+ ) -> dict:
265
+ """
266
+ Delete a file from the provider's API.
267
+
268
+ Args:
269
+ file_id: ID of the file to delete
270
+ provider: Provider to use (e.g., "openai")
271
+ **kwargs: Additional parameters to pass to the provider
272
+
273
+ Returns:
274
+ Dictionary containing the deletion status
275
+
276
+ Example:
277
+ >>> result = File.delete("file-abc123", provider="openai")
278
+ >>> print(f"Deleted: {result['deleted']}")
279
+ """
280
+ # Get provider instance
281
+ provider_instance = get_provider(provider)
282
+
283
+ # Call the provider's delete_file method synchronously
284
+ # We need to use asyncio.run to call the async method from a synchronous context
285
+ import asyncio
286
+
287
+ return asyncio.run(
288
+ provider_instance.delete_file(file_id=file_id, **kwargs)
289
+ )
290
+
291
+ @classmethod
292
+ async def adelete(
293
+ cls,
294
+ file_id: str,
295
+ provider: str = "openai", # Required but defaults for compatibility
296
+ **kwargs
297
+ ) -> dict:
298
+ """
299
+ Delete a file from the provider's API asynchronously.
300
+
301
+ Args:
302
+ file_id: ID of the file to delete
303
+ provider: Provider to use (e.g., "openai")
304
+ **kwargs: Additional parameters to pass to the provider
305
+
306
+ Returns:
307
+ Dictionary containing the deletion status
308
+
309
+ Example:
310
+ >>> result = await File.adelete("file-abc123", provider="openai")
311
+ >>> print(f"Deleted: {result['deleted']}")
312
+ """
313
+ # Get provider instance
314
+ provider_instance = get_provider(provider)
315
+
316
+ # Call the provider's delete_file method
317
+ # This is the async version, so we directly await the result
318
+ return await provider_instance.delete_file(file_id=file_id, **kwargs)