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,398 @@
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
+ Chat completion functionality for OneLLM.
23
+
24
+ This module provides a ChatCompletion class that can be used to create chat
25
+ completions from various providers in a manner compatible with OpenAI's API.
26
+ """
27
+
28
+ import asyncio
29
+ import logging
30
+ import warnings
31
+ from typing import Any, AsyncGenerator, Dict, List, Optional, Union
32
+
33
+ from .providers.base import get_provider_with_fallbacks
34
+ from .models import ChatCompletionResponse, ChatCompletionChunk
35
+ from .utils.fallback import FallbackConfig
36
+ from .validators import validate_model_name, validate_messages, validate_stream
37
+
38
+
39
+ class ChatCompletion:
40
+ """Class for creating chat completions with various providers."""
41
+
42
+ logger = logging.getLogger("onellm.chat_completion")
43
+
44
+ @classmethod
45
+ def _process_capabilities(
46
+ cls,
47
+ provider: Any,
48
+ messages: List[Dict[str, Any]],
49
+ stream: bool,
50
+ kwargs: Dict[str, Any]
51
+ ) -> tuple:
52
+ """
53
+ Process messages and kwargs based on provider capabilities.
54
+
55
+ This method checks if the provider supports requested features like JSON mode,
56
+ streaming, vision (image content), and audio input. It modifies the messages
57
+ and parameters accordingly to ensure compatibility with the provider's capabilities.
58
+
59
+ Args:
60
+ provider: The provider instance
61
+ messages: The messages to process
62
+ stream: Whether streaming was requested
63
+ kwargs: Additional kwargs to process
64
+
65
+ Returns:
66
+ Tuple of (processed_messages, stream_flag, processed_kwargs)
67
+ """
68
+ processed_kwargs = dict(kwargs)
69
+
70
+ # Handle JSON mode (response_format parameter)
71
+ if "response_format" in kwargs:
72
+ response_format = kwargs["response_format"]
73
+
74
+ # Check if this is a JSON mode request
75
+ is_json_mode = (
76
+ isinstance(response_format, dict) and
77
+ response_format.get("type") == "json_object"
78
+ )
79
+
80
+ if is_json_mode and not provider.json_mode_support:
81
+ # Provider doesn't support JSON mode, remove parameter and warn
82
+ processed_kwargs.pop("response_format", None)
83
+ warnings.warn(
84
+ "The selected provider does not support JSON mode. "
85
+ "The 'response_format' parameter will be ignored.",
86
+ UserWarning,
87
+ stacklevel=2
88
+ )
89
+
90
+ # Add a system message to request JSON format if not already present
91
+ has_system_message = False
92
+ for msg in messages:
93
+ if msg.get("role") == "system":
94
+ has_system_message = True
95
+ if "json" not in msg.get("content", "").lower():
96
+ # Append JSON instruction to existing system message
97
+ msg["content"] += " Please provide your response in valid JSON format."
98
+ break
99
+
100
+ if not has_system_message:
101
+ # Add a new system message requesting JSON
102
+ messages_copy = list(messages) # Create a copy to avoid modifying the original
103
+ messages_copy.insert(0, {
104
+ "role": "system",
105
+ "content": "Please provide your response in valid JSON format."
106
+ })
107
+ messages = messages_copy
108
+
109
+ # Check if streaming is requested but not supported
110
+ if stream and not provider.streaming_support:
111
+ stream = False
112
+ warnings.warn(
113
+ "The selected provider does not support streaming. "
114
+ "The request will be processed in non-streaming mode.",
115
+ UserWarning,
116
+ stacklevel=2
117
+ )
118
+
119
+ # Check for vision (image) content when provider doesn't support it
120
+ if not provider.vision_support:
121
+ has_image_content = False
122
+ # Scan all messages to check if any contain image content
123
+ for message in messages:
124
+ content = message.get("content", "")
125
+ # Check for image content in list format
126
+ if isinstance(content, list):
127
+ for item in content:
128
+ if item.get("type") == "image_url" or item.get("type") == "image":
129
+ has_image_content = True
130
+ break
131
+ if has_image_content:
132
+ break
133
+
134
+ if has_image_content:
135
+ warnings.warn(
136
+ "The selected provider does not support vision/image inputs. "
137
+ "Image content will be removed from the messages.",
138
+ UserWarning,
139
+ stacklevel=2
140
+ )
141
+
142
+ # Remove image content from messages
143
+ processed_messages = []
144
+ for message in messages:
145
+ content = message.get("content", "")
146
+ if isinstance(content, list):
147
+ # Filter out image content
148
+ text_content = ""
149
+ for item in content:
150
+ if item.get("type") == "text":
151
+ text_content += item.get("text", "") + "\n"
152
+
153
+ if text_content:
154
+ processed_message = dict(message)
155
+ processed_message["content"] = text_content.strip()
156
+ processed_messages.append(processed_message)
157
+ else:
158
+ # Keep non-list content unchanged
159
+ processed_messages.append(message)
160
+
161
+ messages = processed_messages
162
+
163
+ # Check for audio content when provider doesn't support it
164
+ if not provider.audio_input_support:
165
+ has_audio_content = False
166
+ # Scan all messages to check if any contain audio content
167
+ for message in messages:
168
+ content = message.get("content", "")
169
+ # Check for audio content in list format
170
+ if isinstance(content, list):
171
+ for item in content:
172
+ if item.get("type") == "audio_url" or item.get("type") == "audio":
173
+ has_audio_content = True
174
+ break
175
+ if has_audio_content:
176
+ break
177
+
178
+ if has_audio_content:
179
+ warnings.warn(
180
+ "The selected provider does not support audio inputs. "
181
+ "Audio content will be removed from the messages.",
182
+ UserWarning,
183
+ stacklevel=2
184
+ )
185
+
186
+ # Remove audio content from messages
187
+ processed_messages = []
188
+ for message in messages:
189
+ content = message.get("content", "")
190
+ if isinstance(content, list):
191
+ # Filter out audio content
192
+ filtered_content = []
193
+ for item in content:
194
+ if item.get("type") not in ["audio_url", "audio"]:
195
+ filtered_content.append(item)
196
+
197
+ if filtered_content:
198
+ processed_message = dict(message)
199
+ processed_message["content"] = filtered_content
200
+ processed_messages.append(processed_message)
201
+ elif any(item.get("type") == "text" for item in content):
202
+ # If only text remains, convert to simple format
203
+ text_content = ""
204
+ for item in content:
205
+ if item.get("type") == "text":
206
+ text_content += item.get("text", "") + "\n"
207
+
208
+ if text_content:
209
+ processed_message = dict(message)
210
+ processed_message["content"] = text_content.strip()
211
+ processed_messages.append(processed_message)
212
+ else:
213
+ # Keep non-list content unchanged
214
+ processed_messages.append(message)
215
+
216
+ messages = processed_messages
217
+
218
+ return messages, stream, processed_kwargs
219
+
220
+ @classmethod
221
+ def create(
222
+ cls,
223
+ model: str,
224
+ messages: List[Dict[str, Any]],
225
+ stream: bool = False,
226
+ fallback_models: Optional[List[str]] = None,
227
+ fallback_config: Optional[Dict[str, Any]] = None,
228
+ retries: int = 0,
229
+ **kwargs
230
+ ) -> Union[ChatCompletionResponse, AsyncGenerator[ChatCompletionChunk, None]]:
231
+ """
232
+ Create a chat completion.
233
+
234
+ This synchronous method creates a chat completion using the specified model.
235
+ It supports fallback models if the primary model fails, and can retry the
236
+ primary model before falling back. It handles both streaming and non-streaming
237
+ responses.
238
+
239
+ Args:
240
+ model: Model name with provider prefix (e.g., 'openai/gpt-4')
241
+ messages: List of messages in the conversation
242
+ stream: Whether to stream the response
243
+ fallback_models: Optional list of models to try if the primary model fails
244
+ fallback_config: Optional configuration for fallback behavior
245
+ retries: Number of times to retry the primary model before falling back (default: 0)
246
+ **kwargs: Additional model parameters
247
+
248
+ Returns:
249
+ ChatCompletionResponse or a generator yielding ChatCompletionChunk objects
250
+
251
+ Example:
252
+ >>> response = ChatCompletion.create(
253
+ ... model="openai/gpt-4",
254
+ ... messages=[
255
+ ... {"role": "system", "content": "You are a helpful assistant."},
256
+ ... {"role": "user", "content": "Hello, how are you?"}
257
+ ... ],
258
+ ... fallback_models=["anthropic/claude-3-haiku", "openai/gpt-3.5-turbo"]
259
+ ... )
260
+ >>> print(response.choices[0].message["content"])
261
+ """
262
+ # Validate inputs
263
+ validate_model_name(model)
264
+ validate_messages(messages)
265
+ validate_stream(stream)
266
+
267
+ # Validate fallback models if provided
268
+ if fallback_models:
269
+ for i, fallback_model in enumerate(fallback_models):
270
+ validate_model_name(fallback_model)
271
+
272
+ # Process fallback configuration
273
+ fb_config = None
274
+ if fallback_config:
275
+ fb_config = FallbackConfig(**fallback_config)
276
+
277
+ # Add retries by prepending the primary model to fallback_models
278
+ # This effectively retries the primary model before trying fallbacks
279
+ effective_fallback_models = fallback_models
280
+ if retries > 0:
281
+ if effective_fallback_models is None:
282
+ effective_fallback_models = [model] * retries
283
+ else:
284
+ effective_fallback_models = [model] * retries + effective_fallback_models
285
+
286
+ # Get provider with fallbacks or a regular provider
287
+ provider, model_name = get_provider_with_fallbacks(
288
+ primary_model=model,
289
+ fallback_models=effective_fallback_models,
290
+ fallback_config=fb_config,
291
+ )
292
+
293
+ # Process capabilities - adjust messages and kwargs based on provider support
294
+ messages, stream, processed_kwargs = cls._process_capabilities(
295
+ provider, messages, stream, kwargs
296
+ )
297
+
298
+ # Call the provider's method synchronously
299
+ if stream:
300
+ # For streaming, we need to use async properly
301
+ # Create a new event loop to run the async code
302
+ loop = asyncio.new_event_loop()
303
+ asyncio.set_event_loop(loop)
304
+ return loop.run_until_complete(
305
+ provider.create_chat_completion(
306
+ messages=messages, model=model_name, stream=stream, **processed_kwargs
307
+ )
308
+ )
309
+ else:
310
+ # For non-streaming, we can just run and get the result
311
+ return asyncio.run(
312
+ provider.create_chat_completion(
313
+ messages=messages, model=model_name, stream=stream, **processed_kwargs
314
+ )
315
+ )
316
+
317
+ @classmethod
318
+ async def acreate(
319
+ cls,
320
+ model: str,
321
+ messages: List[Dict[str, Any]],
322
+ stream: bool = False,
323
+ fallback_models: Optional[List[str]] = None,
324
+ fallback_config: Optional[Dict[str, Any]] = None,
325
+ retries: int = 0,
326
+ **kwargs
327
+ ) -> Union[ChatCompletionResponse, AsyncGenerator[ChatCompletionChunk, None]]:
328
+ """
329
+ Create a chat completion asynchronously.
330
+
331
+ This asynchronous method creates a chat completion using the specified model.
332
+ It supports fallback models if the primary model fails, and can retry the
333
+ primary model before falling back. It handles both streaming and non-streaming
334
+ responses.
335
+
336
+ Args:
337
+ model: Model name with provider prefix (e.g., 'openai/gpt-4')
338
+ messages: List of messages in the conversation
339
+ stream: Whether to stream the response
340
+ fallback_models: Optional list of models to try if the primary model fails
341
+ fallback_config: Optional configuration for fallback behavior
342
+ retries: Number of times to retry the primary model before falling back (default: 0)
343
+ **kwargs: Additional model parameters
344
+
345
+ Returns:
346
+ ChatCompletionResponse or a generator yielding ChatCompletionChunk objects
347
+
348
+ Example:
349
+ >>> response = await ChatCompletion.acreate(
350
+ ... model="openai/gpt-4",
351
+ ... messages=[
352
+ ... {"role": "system", "content": "You are a helpful assistant."},
353
+ ... {"role": "user", "content": "Hello, how are you?"}
354
+ ... ],
355
+ ... fallback_models=["anthropic/claude-3-haiku", "openai/gpt-3.5-turbo"]
356
+ ... )
357
+ >>> print(response.choices[0].message["content"])
358
+ """
359
+ # Validate inputs
360
+ validate_model_name(model)
361
+ validate_messages(messages)
362
+ validate_stream(stream)
363
+
364
+ # Validate fallback models if provided
365
+ if fallback_models:
366
+ for i, fallback_model in enumerate(fallback_models):
367
+ validate_model_name(fallback_model)
368
+
369
+ # Process fallback configuration
370
+ fb_config = None
371
+ if fallback_config:
372
+ fb_config = FallbackConfig(**fallback_config)
373
+
374
+ # Add retries by prepending the primary model to fallback_models
375
+ # This effectively retries the primary model before trying fallbacks
376
+ effective_fallback_models = fallback_models
377
+ if retries > 0:
378
+ if effective_fallback_models is None:
379
+ effective_fallback_models = [model] * retries
380
+ else:
381
+ effective_fallback_models = [model] * retries + effective_fallback_models
382
+
383
+ # Get provider with fallbacks or a regular provider
384
+ provider, model_name = get_provider_with_fallbacks(
385
+ primary_model=model,
386
+ fallback_models=effective_fallback_models,
387
+ fallback_config=fb_config,
388
+ )
389
+
390
+ # Process capabilities - adjust messages and kwargs based on provider support
391
+ messages, stream, processed_kwargs = cls._process_capabilities(
392
+ provider, messages, stream, kwargs
393
+ )
394
+
395
+ # Call the provider's method asynchronously
396
+ return await provider.create_chat_completion(
397
+ messages=messages, model=model_name, stream=stream, **processed_kwargs
398
+ )