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/speech.py ADDED
@@ -0,0 +1,142 @@
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
+ Text-to-speech capabilities.
23
+
24
+ This module provides a high-level API for text-to-speech generation across multiple providers.
25
+ It supports various providers and models with fallback options, and offers both
26
+ synchronous and asynchronous interfaces for speech generation.
27
+ """
28
+
29
+ import asyncio
30
+ from typing import List, Optional
31
+
32
+ from .providers.base import get_provider_with_fallbacks
33
+ from .utils.fallback import FallbackConfig
34
+
35
+
36
+ class Speech:
37
+ """
38
+ API class for text-to-speech operations.
39
+
40
+ This class provides methods to convert text to speech using various
41
+ provider models, with support for fallback options if the primary model fails.
42
+ """
43
+
44
+ @classmethod
45
+ async def create(
46
+ cls,
47
+ input: str,
48
+ model: str = "openai/tts-1",
49
+ voice: str = "alloy",
50
+ fallback_models: Optional[List[str]] = None,
51
+ fallback_config: Optional[dict] = None,
52
+ **kwargs
53
+ ) -> bytes:
54
+ """
55
+ Generate speech from text asynchronously.
56
+
57
+ This method handles the asynchronous generation of speech from text input.
58
+ It supports fallback models if the primary model fails and can save the
59
+ generated audio to a file if an output path is specified.
60
+
61
+ Args:
62
+ input: Text to convert to speech
63
+ model: Model ID in format "provider/model" (default: "openai/tts-1")
64
+ voice: Voice to use (default: "alloy")
65
+ fallback_models: Optional list of models to try if the primary model fails
66
+ fallback_config: Optional configuration for fallback behavior
67
+ **kwargs: Additional parameters:
68
+ - response_format: Format of the audio ("mp3", "opus", "aac", "flac")
69
+ - speed: Speed of the generated audio (0.25 to 4.0)
70
+ - output_file: Optional path to save the audio to a file
71
+
72
+ Returns:
73
+ Audio data as bytes
74
+ """
75
+ # Extract output_file if provided, removing it from kwargs to avoid passing
76
+ # it to the provider's create_speech method
77
+ output_file = kwargs.pop("output_file", None)
78
+
79
+ # Process fallback configuration by creating a FallbackConfig object
80
+ # if fallback settings were provided
81
+ fb_config = None
82
+ if fallback_config:
83
+ fb_config = FallbackConfig(**fallback_config)
84
+
85
+ # Get provider with fallbacks or a regular provider
86
+ # This handles selecting the appropriate provider and model based on the input
87
+ provider, model_name = get_provider_with_fallbacks(
88
+ primary_model=model,
89
+ fallback_models=fallback_models,
90
+ fallback_config=fb_config,
91
+ )
92
+
93
+ # Generate speech using the selected provider and model
94
+ audio_data = await provider.create_speech(input, model_name, voice, **kwargs)
95
+
96
+ # Save to file if requested
97
+ # This allows users to directly save the audio without additional code
98
+ if output_file:
99
+ with open(output_file, "wb") as f:
100
+ f.write(audio_data)
101
+
102
+ return audio_data
103
+
104
+ @classmethod
105
+ def create_sync(
106
+ cls,
107
+ input: str,
108
+ model: str = "openai/tts-1",
109
+ voice: str = "alloy",
110
+ fallback_models: Optional[List[str]] = None,
111
+ fallback_config: Optional[dict] = None,
112
+ **kwargs
113
+ ) -> bytes:
114
+ """
115
+ Synchronous version of create() for text-to-speech generation.
116
+
117
+ This method provides a convenient synchronous interface to the asynchronous
118
+ create() method by running it in an event loop. It has the same functionality
119
+ and parameters as the asynchronous version.
120
+
121
+ Args:
122
+ input: Text to convert to speech
123
+ model: Model ID in format "provider/model" (default: "openai/tts-1")
124
+ voice: Voice to use (default: "alloy")
125
+ fallback_models: Optional list of models to try if the primary model fails
126
+ fallback_config: Optional configuration for fallback behavior
127
+ **kwargs: Additional parameters as in create()
128
+
129
+ Returns:
130
+ Audio data as bytes
131
+ """
132
+ # Use asyncio.run to execute the async create method in a synchronous context
133
+ return asyncio.run(
134
+ cls.create(
135
+ input=input,
136
+ model=model,
137
+ voice=voice,
138
+ fallback_models=fallback_models,
139
+ fallback_config=fallback_config,
140
+ **kwargs
141
+ )
142
+ )
@@ -0,0 +1,61 @@
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
+ Type definitions for OneLLM.
23
+
24
+ This module provides type definitions and data structures used throughout the OneLLM
25
+ package. These types ensure consistent interfaces when working with different LLM
26
+ providers and handling various content formats.
27
+
28
+ The types defined here include:
29
+ - Role: Enumeration of possible message roles (system, user, assistant)
30
+ - ContentType: Enumeration of content types (text, image, etc.)
31
+ - Provider: Enumeration of supported LLM providers
32
+ - ContentItem: Structure for multi-modal content items
33
+ - Message: Structure for messages in a conversation
34
+ - UsageInfo: Structure for token usage statistics
35
+ - ModelParams: Configuration parameters for model requests
36
+ - ResponseFormat: Structure for specifying response format preferences
37
+ """
38
+
39
+ # Import all type definitions from the common module
40
+ from .common import (
41
+ Role, # Defines possible message roles (system, user, assistant)
42
+ ContentType, # Defines content types (text, image, audio, etc.)
43
+ Provider, # Enumerates supported LLM providers
44
+ ContentItem, # Structure for multi-modal content items
45
+ Message, # Structure for messages in a conversation
46
+ UsageInfo, # Structure for token usage statistics
47
+ ModelParams, # Configuration parameters for model requests
48
+ ResponseFormat, # Structure for specifying response format preferences
49
+ )
50
+
51
+ # Define the public API for this module
52
+ __all__ = [
53
+ "Role",
54
+ "ContentType",
55
+ "Provider",
56
+ "ContentItem",
57
+ "Message",
58
+ "UsageInfo",
59
+ "ModelParams",
60
+ "ResponseFormat",
61
+ ]
onellm/types/common.py ADDED
@@ -0,0 +1,371 @@
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
+ Common type definitions for OneLLM.
23
+
24
+ This module contains standard type definitions used throughout the library.
25
+ These types provide a consistent interface for working with various LLM providers
26
+ while maintaining compatibility with the OpenAI API format.
27
+ """
28
+
29
+ from typing import Any, Dict, List, Literal, Optional, Union, TypedDict, IO
30
+
31
+
32
+ # Role types for chat messages
33
+ Role = Literal["system", "user", "assistant", "tool", "function"]
34
+ # Defines the possible roles in a conversation with an LLM
35
+
36
+ # Content types for multi-modal messages
37
+ ContentType = Literal["text", "image", "image_url"]
38
+ # Specifies the types of content that can be included in messages
39
+
40
+ # Image URL detail types
41
+ ImageUrlDetail = Literal["auto", "low", "high"]
42
+ # Controls the level of detail when processing images via URL
43
+
44
+ # Provider types
45
+ Provider = Literal["openai", "anthropic", "azure", "ollama", "together", "groq"]
46
+ # Supported LLM providers in the library
47
+
48
+ # Audio format types
49
+ AudioFormat = Literal["mp3", "mp4", "mpeg", "mpga", "m4a", "wav", "webm"]
50
+ # Supported audio input formats for transcription/translation
51
+
52
+ # Audio response format types
53
+ AudioResponseFormat = Literal["json", "text", "srt", "verbose_json", "vtt"]
54
+ # Output formats for audio transcription and translation
55
+
56
+ # Text-to-speech voice types
57
+ SpeechVoice = Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
58
+ # Available voice options for text-to-speech generation
59
+
60
+ # Text-to-speech output format types
61
+ SpeechFormat = Literal["mp3", "opus", "aac", "flac"]
62
+ # Output formats for generated speech audio
63
+
64
+ # Image size types
65
+ ImageSize = Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]
66
+ # Available dimensions for generated images
67
+
68
+ # Image quality types (DALL-E 3)
69
+ ImageQuality = Literal["standard", "hd"]
70
+ # Quality settings for image generation
71
+
72
+ # Image style types (DALL-E 3)
73
+ ImageStyle = Literal["natural", "vivid"]
74
+ # Style options for generated images
75
+
76
+ # Image response format types
77
+ ImageResponseFormat = Literal["url", "b64_json"]
78
+ # How image generation results are returned
79
+
80
+
81
+ class ImageUrl(TypedDict, total=False):
82
+ """
83
+ Image URL details for vision models.
84
+
85
+ Attributes:
86
+ url: The URL of the image to process
87
+ detail: Optional level of detail for image processing
88
+ """
89
+
90
+ url: str
91
+ detail: Optional[ImageUrlDetail]
92
+
93
+
94
+ class ContentItem(TypedDict, total=False):
95
+ """
96
+ A single content item in a chat message.
97
+
98
+ Used for multi-modal conversations that may include text and images.
99
+
100
+ Attributes:
101
+ type: The type of content (text, image, etc.)
102
+ text: Optional text content
103
+ image_url: Optional image URL and detail level
104
+ """
105
+
106
+ type: ContentType
107
+ text: Optional[str]
108
+ image_url: Optional[ImageUrl]
109
+
110
+
111
+ class Message(TypedDict, total=False):
112
+ """
113
+ A chat message.
114
+
115
+ Represents a single message in a conversation with an LLM.
116
+
117
+ Attributes:
118
+ role: The role of the message sender
119
+ content: The message content (text or multi-modal)
120
+ name: Optional name identifier for the message sender
121
+ function_call: Optional function call information
122
+ tool_call_id: Optional ID for tool calls
123
+ tool_calls: Optional list of tool calls
124
+ """
125
+
126
+ role: Role
127
+ content: Union[str, List[ContentItem]]
128
+ name: Optional[str]
129
+ function_call: Optional[Dict[str, Any]]
130
+ tool_call_id: Optional[str]
131
+ tool_calls: Optional[List[Dict[str, Any]]]
132
+
133
+
134
+ class UsageInfo(TypedDict, total=False):
135
+ """
136
+ Token usage information.
137
+
138
+ Tracks token consumption for billing and monitoring.
139
+
140
+ Attributes:
141
+ prompt_tokens: Number of tokens in the prompt
142
+ completion_tokens: Number of tokens in the completion
143
+ total_tokens: Total tokens used in the request
144
+ """
145
+
146
+ prompt_tokens: int
147
+ completion_tokens: int
148
+ total_tokens: int
149
+
150
+
151
+ class ModelParams(TypedDict, total=False):
152
+ """
153
+ Parameters for model configuration.
154
+
155
+ Controls various aspects of model behavior during inference.
156
+
157
+ Attributes:
158
+ temperature: Controls randomness (higher = more random)
159
+ top_p: Controls diversity via nucleus sampling
160
+ n: Number of completions to generate
161
+ stream: Whether to stream the response
162
+ max_tokens: Maximum tokens to generate
163
+ presence_penalty: Penalizes new tokens based on presence in text
164
+ frequency_penalty: Penalizes new tokens based on frequency in text
165
+ stop: Sequences where the model should stop generating
166
+ logit_bias: Modifies likelihood of specific tokens
167
+ user: User identifier for the request
168
+ """
169
+
170
+ temperature: Optional[float]
171
+ top_p: Optional[float]
172
+ n: Optional[int]
173
+ stream: Optional[bool]
174
+ max_tokens: Optional[int]
175
+ presence_penalty: Optional[float]
176
+ frequency_penalty: Optional[float]
177
+ stop: Optional[Union[str, List[str]]]
178
+ logit_bias: Optional[Dict[str, float]]
179
+ user: Optional[str]
180
+
181
+
182
+ class ResponseFormat(TypedDict, total=False):
183
+ """
184
+ Format specification for the response.
185
+
186
+ Controls how the model formats its output.
187
+
188
+ Attributes:
189
+ type: The format type (text or JSON)
190
+ """
191
+
192
+ type: Literal["text", "json_object"]
193
+
194
+
195
+ class AudioTranscriptionParams(TypedDict, total=False):
196
+ """
197
+ Parameters for audio transcription requests.
198
+
199
+ Used when converting speech to text.
200
+
201
+ Attributes:
202
+ file: The audio file to transcribe
203
+ model: The model to use for transcription
204
+ language: Optional language of the audio
205
+ prompt: Optional text to guide the transcription
206
+ response_format: Optional format for the response
207
+ temperature: Optional temperature setting
208
+ """
209
+
210
+ file: Union[str, bytes, IO[bytes]]
211
+ model: str
212
+ language: Optional[str]
213
+ prompt: Optional[str]
214
+ response_format: Optional[AudioResponseFormat]
215
+ temperature: Optional[float]
216
+
217
+
218
+ class AudioTranslationParams(TypedDict, total=False):
219
+ """
220
+ Parameters for audio translation requests.
221
+
222
+ Used when translating speech from one language to English.
223
+
224
+ Attributes:
225
+ file: The audio file to translate
226
+ model: The model to use for translation
227
+ prompt: Optional text to guide the translation
228
+ response_format: Optional format for the response
229
+ temperature: Optional temperature setting
230
+ """
231
+
232
+ file: Union[str, bytes, IO[bytes]]
233
+ model: str
234
+ prompt: Optional[str]
235
+ response_format: Optional[AudioResponseFormat]
236
+ temperature: Optional[float]
237
+
238
+
239
+ class TranscriptionResult(TypedDict, total=False):
240
+ """
241
+ Result from audio transcription or translation.
242
+
243
+ Contains the transcribed or translated text and metadata.
244
+
245
+ Attributes:
246
+ text: The transcribed or translated text
247
+ task: Optional description of the task performed
248
+ language: Optional detected language
249
+ duration: Optional duration of the audio in seconds
250
+ segments: Optional list of audio segments with timestamps
251
+ words: Optional list of individual words with timestamps
252
+ """
253
+
254
+ text: str
255
+ task: Optional[str]
256
+ language: Optional[str]
257
+ duration: Optional[float]
258
+ segments: Optional[List[Dict[str, Any]]]
259
+ words: Optional[List[Dict[str, Any]]]
260
+
261
+
262
+ class SpeechParams(TypedDict, total=False):
263
+ """
264
+ Parameters for text-to-speech requests.
265
+
266
+ Used when generating spoken audio from text.
267
+
268
+ Attributes:
269
+ input: The text to convert to speech
270
+ model: The model to use for speech generation
271
+ voice: The voice to use for the audio
272
+ response_format: Optional audio format for the response
273
+ speed: Optional speech speed multiplier
274
+ """
275
+
276
+ input: str
277
+ model: str
278
+ voice: SpeechVoice
279
+ response_format: Optional[SpeechFormat]
280
+ speed: Optional[float]
281
+
282
+
283
+ class ImageGenerationParams(TypedDict, total=False):
284
+ """
285
+ Parameters for image generation requests.
286
+
287
+ Used when creating images from text prompts.
288
+
289
+ Attributes:
290
+ prompt: The text prompt to generate images from
291
+ model: The model to use for image generation
292
+ n: Optional number of images to generate
293
+ size: Optional dimensions of the generated images
294
+ quality: Optional quality level for the images
295
+ style: Optional style for the generated images
296
+ response_format: Optional format for the response
297
+ user: Optional user identifier
298
+ """
299
+
300
+ prompt: str
301
+ model: str
302
+ n: Optional[int]
303
+ size: Optional[ImageSize]
304
+ quality: Optional[ImageQuality]
305
+ style: Optional[ImageStyle]
306
+ response_format: Optional[ImageResponseFormat]
307
+ user: Optional[str]
308
+
309
+
310
+ class ImageData(TypedDict, total=False):
311
+ """
312
+ Generated image data.
313
+
314
+ Contains the output from image generation.
315
+
316
+ Attributes:
317
+ url: Optional URL to the generated image
318
+ b64_json: Optional base64-encoded image data
319
+ revised_prompt: Optional revised prompt used for generation
320
+ filepath: Optional local path where the image was saved
321
+ """
322
+
323
+ url: Optional[str]
324
+ b64_json: Optional[str]
325
+ revised_prompt: Optional[str]
326
+ filepath: Optional[str] # Added locally when saving images
327
+
328
+
329
+ class ImageGenerationResult(TypedDict, total=False):
330
+ """
331
+ Result from image generation.
332
+
333
+ Contains metadata and the generated images.
334
+
335
+ Attributes:
336
+ created: Unix timestamp of when the images were created
337
+ data: List of generated image data
338
+ """
339
+
340
+ created: int
341
+ data: List[ImageData]
342
+
343
+
344
+ # Export everything for convenience
345
+ __all__ = [
346
+ "Role",
347
+ "ContentType",
348
+ "Provider",
349
+ "ImageUrlDetail",
350
+ "ImageUrl",
351
+ "ContentItem",
352
+ "Message",
353
+ "UsageInfo",
354
+ "ModelParams",
355
+ "ResponseFormat",
356
+ "AudioFormat",
357
+ "AudioResponseFormat",
358
+ "AudioTranscriptionParams",
359
+ "AudioTranslationParams",
360
+ "TranscriptionResult",
361
+ "SpeechVoice",
362
+ "SpeechFormat",
363
+ "SpeechParams",
364
+ "ImageSize",
365
+ "ImageQuality",
366
+ "ImageStyle",
367
+ "ImageResponseFormat",
368
+ "ImageGenerationParams",
369
+ "ImageData",
370
+ "ImageGenerationResult",
371
+ ]
@@ -0,0 +1,46 @@
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
+ Utility functions and classes for OneLLM.
23
+
24
+ This module provides various utility functions and classes used throughout the OneLLM
25
+ package to handle common tasks such as:
26
+ - Asynchronous retry mechanisms for API calls
27
+ - Streaming response handling
28
+ - Error management for streaming operations
29
+
30
+ These utilities help ensure robust API interactions and proper handling of
31
+ streaming responses when working with different LLM providers.
32
+ """
33
+
34
+ # Import retry-related utilities for handling transient API failures
35
+ from .retry import retry_async, RetryConfig
36
+
37
+ # Import streaming utilities for handling real-time response processing
38
+ from .streaming import stream_generator, StreamingError
39
+
40
+ # Define the public API for this module
41
+ __all__ = [
42
+ "retry_async", # Async function decorator that implements retry logic
43
+ "RetryConfig", # Configuration class for customizing retry behavior
44
+ "stream_generator", # Generator function for processing streaming responses
45
+ "StreamingError", # Exception class for streaming-related errors
46
+ ]