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/image.py ADDED
@@ -0,0 +1,207 @@
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
+ Image generation capabilities.
23
+
24
+ This module provides a high-level API for image generation across multiple providers.
25
+ It supports various models and offers both synchronous and asynchronous interfaces
26
+ with fallback options.
27
+ """
28
+
29
+ import asyncio
30
+ import os
31
+ from typing import Dict, List, Optional
32
+
33
+ from .providers.base import get_provider_with_fallbacks
34
+ from .utils.fallback import FallbackConfig
35
+
36
+
37
+ class Image:
38
+ """API class for image generation."""
39
+
40
+ @classmethod
41
+ async def create(
42
+ cls,
43
+ prompt: str,
44
+ model: str = "openai/dall-e-3",
45
+ n: int = 1,
46
+ size: str = "1024x1024",
47
+ fallback_models: Optional[List[str]] = None,
48
+ fallback_config: Optional[dict] = None,
49
+ **kwargs,
50
+ ) -> Dict:
51
+ """
52
+ Generate images from a text prompt.
53
+
54
+ This method handles the asynchronous generation of images based on a text prompt.
55
+ It supports fallback models if the primary model fails and can save generated
56
+ images to disk if an output directory is specified.
57
+
58
+ Args:
59
+ prompt: Text description of the desired image
60
+ model: Model ID in format "provider/model" (default: "openai/dall-e-3")
61
+ n: Number of images to generate (default: 1)
62
+ size: Size of the generated images (default: "1024x1024")
63
+ fallback_models: Optional list of models to try if the primary model fails
64
+ fallback_config: Optional configuration for fallback behavior
65
+ **kwargs: Additional parameters:
66
+ - quality: Quality of the image ("standard" or "hd"), for DALL-E 3
67
+ - style: Style of image ("natural" or "vivid"), for DALL-E 3
68
+ - response_format: Format of the response ("url" or "b64_json")
69
+ - user: End-user ID for tracking
70
+ - output_dir: Optional path to save the generated images
71
+ - output_format: Optional format for output files ("png", "jpg", etc.)
72
+
73
+ Returns:
74
+ Dict with generated images data
75
+ """
76
+ # Extract kwargs that are for our logic, not the API
77
+ # These parameters are used locally and should not be passed to the provider API
78
+ output_dir = kwargs.pop("output_dir", None)
79
+ output_format = kwargs.pop("output_format", "png")
80
+
81
+ # Process fallback configuration
82
+ # Convert the dictionary to a FallbackConfig object if provided
83
+ fb_config = None
84
+ if fallback_config:
85
+ fb_config = FallbackConfig(**fallback_config)
86
+
87
+ # Get provider with fallbacks or a regular provider
88
+ # This splits the model string into provider and model name parts
89
+ # and handles fallback logic if specified
90
+ provider, model_name = get_provider_with_fallbacks(
91
+ primary_model=model,
92
+ fallback_models=fallback_models,
93
+ fallback_config=fb_config,
94
+ )
95
+
96
+ # Generate image using the selected provider
97
+ result = await provider.create_image(
98
+ prompt, model_name, n=n, size=size, **kwargs
99
+ )
100
+
101
+ # Save images if output_dir is provided
102
+ if output_dir and result.get("data"):
103
+ # Create the output directory if it doesn't exist
104
+ os.makedirs(output_dir, exist_ok=True)
105
+
106
+ # Use the creation timestamp from the result or current time as fallback
107
+ timestamp = int(result.get("created", asyncio.get_event_loop().time()))
108
+
109
+ # Process each generated image
110
+ for i, img_data in enumerate(result.get("data", [])):
111
+ # Get image data (url or base64)
112
+ if "url" in img_data:
113
+ # For URL responses, we'll need to download the image
114
+ image_url = img_data["url"]
115
+ image_bytes = await cls._download_image(image_url)
116
+ elif "b64_json" in img_data:
117
+ # For base64 responses, decode the data
118
+ import base64
119
+
120
+ image_bytes = base64.b64decode(img_data["b64_json"])
121
+ else:
122
+ continue # Skip if no image data
123
+
124
+ # Create filename with timestamp and index to ensure uniqueness
125
+ filename = f"image_{timestamp}_{i}.{output_format}"
126
+ filepath = os.path.join(output_dir, filename)
127
+
128
+ # Save the image to disk
129
+ with open(filepath, "wb") as f:
130
+ f.write(image_bytes)
131
+
132
+ # Add the file path to the result for reference
133
+ img_data["filepath"] = filepath
134
+
135
+ return result
136
+
137
+ @classmethod
138
+ def create_sync(
139
+ cls,
140
+ prompt: str,
141
+ model: str = "openai/dall-e-3",
142
+ n: int = 1,
143
+ size: str = "1024x1024",
144
+ fallback_models: Optional[List[str]] = None,
145
+ fallback_config: Optional[dict] = None,
146
+ **kwargs,
147
+ ) -> Dict:
148
+ """
149
+ Synchronous version of create().
150
+
151
+ This method provides a synchronous interface to the asynchronous create() method
152
+ by running it in an event loop. It has the same functionality but can be used
153
+ in synchronous contexts.
154
+
155
+ Args:
156
+ prompt: Text description of the desired image
157
+ model: Model ID in format "provider/model" (default: "openai/dall-e-3")
158
+ n: Number of images to generate (default: 1)
159
+ size: Size of the generated images (default: "1024x1024")
160
+ fallback_models: Optional list of models to try if the primary model fails
161
+ fallback_config: Optional configuration for fallback behavior
162
+ **kwargs: Additional parameters as in create()
163
+
164
+ Returns:
165
+ Dict with generated images data
166
+ """
167
+ # Use asyncio.run to execute the async create method in a synchronous context
168
+ return asyncio.run(
169
+ cls.create(
170
+ prompt=prompt,
171
+ model=model,
172
+ n=n,
173
+ size=size,
174
+ fallback_models=fallback_models,
175
+ fallback_config=fallback_config,
176
+ **kwargs,
177
+ )
178
+ )
179
+
180
+ @classmethod
181
+ async def _download_image(cls, url: str) -> bytes:
182
+ """
183
+ Download an image from a URL.
184
+
185
+ This helper method asynchronously downloads image data from a given URL.
186
+ It uses aiohttp for efficient async HTTP requests.
187
+
188
+ Args:
189
+ url: URL of the image to download
190
+
191
+ Returns:
192
+ Image data as bytes
193
+
194
+ Raises:
195
+ ValueError: If the download fails (non-200 status code)
196
+ """
197
+ import aiohttp
198
+
199
+ # Create a session for HTTP requests
200
+ async with aiohttp.ClientSession() as session:
201
+ # Make the GET request to download the image
202
+ async with session.get(url) as response:
203
+ # Check if the request was successful
204
+ if response.status != 200:
205
+ raise ValueError(f"Failed to download image: {response.status}")
206
+ # Return the binary image data
207
+ return await response.read()
onellm/models.py ADDED
@@ -0,0 +1,359 @@
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
+ Response and request model definitions for OneLLM.
23
+
24
+ This module contains the data models used for responses and requests
25
+ across different API endpoints and providers.
26
+ """
27
+
28
+ from typing import Any, Dict, List, Optional
29
+ from dataclasses import dataclass
30
+ from .types import Message, UsageInfo
31
+
32
+
33
+ @dataclass
34
+ class ChoiceDelta:
35
+ """
36
+ Represents a chunk of a streaming response.
37
+
38
+ This class is used to model incremental updates in streaming responses,
39
+ containing partial content or other response elements.
40
+
41
+ Attributes:
42
+ content: The text content of the delta
43
+ role: The role associated with this delta (e.g., 'user', 'assistant')
44
+ function_call: Details of a function call if present
45
+ tool_calls: List of tool calls if present
46
+ finish_reason: Reason why the response finished (e.g., 'stop', 'length')
47
+ """
48
+
49
+ content: Optional[str] = None
50
+ role: Optional[str] = None
51
+ function_call: Optional[Dict[str, Any]] = None
52
+ tool_calls: Optional[List[Dict[str, Any]]] = None
53
+ finish_reason: Optional[str] = None
54
+
55
+
56
+ @dataclass
57
+ class Choice:
58
+ """
59
+ Represents a single completion choice in a response.
60
+
61
+ In many LLM APIs, multiple alternative completions can be generated
62
+ for a single request. This class represents one such completion.
63
+
64
+ Attributes:
65
+ message: The message content and metadata
66
+ finish_reason: Reason why the response finished (e.g., 'stop', 'length')
67
+ index: Position of this choice in the list of choices
68
+ """
69
+
70
+ message: Message
71
+ finish_reason: Optional[str] = None
72
+ index: int = 0
73
+
74
+ def __init__(
75
+ self,
76
+ message: Optional[Message] = None,
77
+ finish_reason: Optional[str] = None,
78
+ index: int = 0,
79
+ **kwargs
80
+ ):
81
+ """
82
+ Initialize a Choice object.
83
+
84
+ Args:
85
+ message: The message content and metadata
86
+ finish_reason: Reason why the response finished
87
+ index: Position of this choice in the list of choices
88
+ **kwargs: Additional keyword arguments for future compatibility
89
+ """
90
+ self.message = message or {} # Default to empty dict if None
91
+ self.finish_reason = finish_reason
92
+ self.index = index
93
+
94
+
95
+ @dataclass
96
+ class StreamingChoice:
97
+ """
98
+ Represents a single streaming choice in a response.
99
+
100
+ Similar to Choice, but specifically for streaming responses where
101
+ content is delivered incrementally.
102
+
103
+ Attributes:
104
+ delta: The incremental update in this chunk
105
+ finish_reason: Reason why the response finished (e.g., 'stop', 'length')
106
+ index: Position of this choice in the list of choices
107
+ """
108
+
109
+ delta: ChoiceDelta
110
+ finish_reason: Optional[str] = None
111
+ index: int = 0
112
+
113
+ def __init__(
114
+ self,
115
+ delta: Optional[ChoiceDelta] = None,
116
+ finish_reason: Optional[str] = None,
117
+ index: int = 0,
118
+ **kwargs
119
+ ):
120
+ """
121
+ Initialize a StreamingChoice object.
122
+
123
+ Args:
124
+ delta: The incremental update in this chunk
125
+ finish_reason: Reason why the response finished
126
+ index: Position of this choice in the list of choices
127
+ **kwargs: Additional keyword arguments for future compatibility
128
+ """
129
+ self.delta = delta or ChoiceDelta() # Default to empty ChoiceDelta if None
130
+ self.finish_reason = finish_reason
131
+ self.index = index
132
+
133
+
134
+ @dataclass
135
+ class ChatCompletionResponse:
136
+ """
137
+ Response from a chat completion request.
138
+
139
+ This class models the complete response from a chat completion API call,
140
+ containing metadata about the request and the generated completions.
141
+
142
+ Attributes:
143
+ id: Unique identifier for this completion
144
+ object: Type of object (typically 'chat.completion')
145
+ created: Unix timestamp of when the completion was created
146
+ model: The model used for completion
147
+ choices: List of completion choices
148
+ usage: Token usage information
149
+ system_fingerprint: System identifier for the model version
150
+ """
151
+
152
+ id: str
153
+ object: str
154
+ created: int
155
+ model: str
156
+ choices: List[Choice]
157
+ usage: Optional[UsageInfo] = None
158
+ system_fingerprint: Optional[str] = None
159
+
160
+ def __init__(
161
+ self,
162
+ id: str,
163
+ object: str,
164
+ created: int,
165
+ model: str,
166
+ choices: List[Choice],
167
+ usage: Optional[UsageInfo] = None,
168
+ system_fingerprint: Optional[str] = None,
169
+ **kwargs
170
+ ):
171
+ """
172
+ Initialize a ChatCompletionResponse object.
173
+
174
+ Args:
175
+ id: Unique identifier for this completion
176
+ object: Type of object (typically 'chat.completion')
177
+ created: Unix timestamp of when the completion was created
178
+ model: The model used for completion
179
+ choices: List of completion choices
180
+ usage: Token usage information
181
+ system_fingerprint: System identifier for the model version
182
+ **kwargs: Additional keyword arguments for future compatibility
183
+ """
184
+ self.id = id
185
+ self.object = object
186
+ self.created = created
187
+ self.model = model
188
+ self.choices = choices
189
+ self.usage = usage
190
+ self.system_fingerprint = system_fingerprint
191
+
192
+
193
+ @dataclass
194
+ class ChatCompletionChunk:
195
+ """
196
+ Chunk of a streaming chat completion response.
197
+
198
+ This class represents a single chunk in a streaming response,
199
+ containing partial completion data.
200
+
201
+ Attributes:
202
+ id: Unique identifier for this completion
203
+ object: Type of object (typically 'chat.completion.chunk')
204
+ created: Unix timestamp of when the chunk was created
205
+ model: The model used for completion
206
+ choices: List of streaming choices in this chunk
207
+ system_fingerprint: System identifier for the model version
208
+ """
209
+
210
+ id: str
211
+ object: str
212
+ created: int
213
+ model: str
214
+ choices: List[StreamingChoice]
215
+ system_fingerprint: Optional[str] = None
216
+
217
+ def __init__(
218
+ self,
219
+ id: str,
220
+ object: str,
221
+ created: int,
222
+ model: str,
223
+ choices: List[StreamingChoice],
224
+ system_fingerprint: Optional[str] = None,
225
+ **kwargs
226
+ ):
227
+ """
228
+ Initialize a ChatCompletionChunk object.
229
+
230
+ Args:
231
+ id: Unique identifier for this completion
232
+ object: Type of object (typically 'chat.completion.chunk')
233
+ created: Unix timestamp of when the chunk was created
234
+ model: The model used for completion
235
+ choices: List of streaming choices in this chunk
236
+ system_fingerprint: System identifier for the model version
237
+ **kwargs: Additional keyword arguments for future compatibility
238
+ """
239
+ self.id = id
240
+ self.object = object
241
+ self.created = created
242
+ self.model = model
243
+ self.choices = choices
244
+ self.system_fingerprint = system_fingerprint
245
+
246
+
247
+ @dataclass
248
+ class CompletionChoice:
249
+ """
250
+ Represents a single text completion choice in a response.
251
+
252
+ This class is used for traditional text completion (non-chat) responses.
253
+
254
+ Attributes:
255
+ text: The generated text content
256
+ index: Position of this choice in the list of choices
257
+ logprobs: Log probabilities for token predictions if requested
258
+ finish_reason: Reason why the response finished (e.g., 'stop', 'length')
259
+ """
260
+
261
+ text: str
262
+ index: int = 0
263
+ logprobs: Optional[Dict[str, Any]] = None
264
+ finish_reason: Optional[str] = None
265
+
266
+
267
+ @dataclass
268
+ class CompletionResponse:
269
+ """
270
+ Response from a text completion request.
271
+
272
+ This class models the complete response from a text completion API call,
273
+ containing metadata about the request and the generated completions.
274
+
275
+ Attributes:
276
+ id: Unique identifier for this completion
277
+ object: Type of object (typically 'text_completion')
278
+ created: Unix timestamp of when the completion was created
279
+ model: The model used for completion
280
+ choices: List of completion choices
281
+ usage: Token usage information
282
+ system_fingerprint: System identifier for the model version
283
+ """
284
+
285
+ id: str
286
+ object: str
287
+ created: int
288
+ model: str
289
+ choices: List[CompletionChoice]
290
+ usage: Optional[UsageInfo] = None
291
+ system_fingerprint: Optional[str] = None
292
+
293
+
294
+ @dataclass
295
+ class EmbeddingData:
296
+ """
297
+ Represents a single embedding in a response.
298
+
299
+ Embeddings are vector representations of text that capture semantic meaning.
300
+
301
+ Attributes:
302
+ embedding: Vector of floating point numbers representing the embedding
303
+ index: Position of this embedding in the list of embeddings
304
+ object: Type of object (typically 'embedding')
305
+ """
306
+
307
+ embedding: List[float]
308
+ index: int = 0
309
+ object: str = "embedding"
310
+
311
+
312
+ @dataclass
313
+ class EmbeddingResponse:
314
+ """
315
+ Response from an embedding request.
316
+
317
+ This class models the complete response from an embedding API call,
318
+ containing the generated embeddings and metadata.
319
+
320
+ Attributes:
321
+ object: Type of object (typically 'list')
322
+ data: List of embedding data objects
323
+ model: The model used to generate embeddings
324
+ usage: Token usage information
325
+ """
326
+
327
+ object: str
328
+ data: List[EmbeddingData]
329
+ model: str
330
+ usage: Optional[UsageInfo] = None
331
+
332
+
333
+ @dataclass
334
+ class FileObject:
335
+ """
336
+ Represents a file stored with the provider.
337
+
338
+ This class models metadata about files that have been uploaded to the
339
+ provider's storage system.
340
+
341
+ Attributes:
342
+ id: Unique identifier for the file
343
+ object: Type of object (typically 'file')
344
+ bytes: Size of the file in bytes
345
+ created_at: Unix timestamp of when the file was created
346
+ filename: Name of the file
347
+ purpose: Purpose of the file (e.g., 'fine-tune', 'assistants')
348
+ status: Current status of the file (e.g., 'processed')
349
+ status_details: Additional details about the file status
350
+ """
351
+
352
+ id: str
353
+ object: str
354
+ bytes: int
355
+ created_at: int
356
+ filename: str
357
+ purpose: str
358
+ status: Optional[str] = None
359
+ status_details: Optional[str] = None
@@ -0,0 +1,48 @@
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
+ Provider implementations for OneLLM.
23
+
24
+ This module imports all available provider implementations,
25
+ ensuring they are registered with the provider registry.
26
+
27
+ The provider system is designed to be extensible, allowing new LLM providers
28
+ to be added by implementing the Provider interface and registering them.
29
+ """
30
+
31
+ from .base import get_provider, list_providers, parse_model_name, register_provider
32
+ from .fallback import FallbackProviderProxy
33
+ from .openai import OpenAIProvider
34
+
35
+ # Register provider implementations with the provider registry
36
+ # This makes the OpenAI provider available through the get_provider function
37
+ # Additional providers should be registered here as they are implemented
38
+ register_provider("openai", OpenAIProvider)
39
+
40
+ # Convenience export - these symbols will be available when importing from onellm.providers
41
+ # This allows users to access core provider functionality directly
42
+ __all__ = [
43
+ "get_provider", # Function to get a provider instance by name
44
+ "parse_model_name", # Function to parse "provider/model" format strings
45
+ "register_provider", # Function to register new provider implementations
46
+ "list_providers", # Function to list all registered providers
47
+ "FallbackProviderProxy", # Class for implementing provider fallback chains
48
+ ]