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,1231 @@
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
+ """
23
+ OpenAI provider implementation for OneLLM.
24
+
25
+ This module implements the OpenAI provider adapter, supporting all OpenAI API
26
+ endpoints including chat completions, completions, embeddings, and file operations.
27
+ """
28
+
29
+ import json
30
+ import time
31
+ from typing import Any, AsyncGenerator, Dict, List, Optional, Union, IO
32
+
33
+ import aiohttp
34
+
35
+ from ..config import get_provider_config
36
+ from ..models import (
37
+ ChatCompletionResponse,
38
+ ChatCompletionChunk,
39
+ ChoiceDelta,
40
+ StreamingChoice,
41
+ CompletionResponse,
42
+ CompletionChoice,
43
+ EmbeddingResponse,
44
+ EmbeddingData,
45
+ FileObject,
46
+ Choice,
47
+ )
48
+ from ..errors import (
49
+ APIError,
50
+ AuthenticationError,
51
+ RateLimitError,
52
+ InvalidRequestError,
53
+ ServiceUnavailableError,
54
+ TimeoutError,
55
+ BadGatewayError,
56
+ PermissionError,
57
+ ResourceNotFoundError,
58
+ )
59
+ from ..types import Message
60
+ from ..types.common import TranscriptionResult, ImageGenerationResult
61
+ from ..utils.retry import retry_async, RetryConfig
62
+
63
+ from .base import Provider, register_provider
64
+
65
+
66
+ class OpenAIProvider(Provider):
67
+ """OpenAI provider implementation."""
68
+
69
+ # Set capability flags
70
+ json_mode_support = True
71
+
72
+ # Multi-modal capabilities
73
+ vision_support = True # GPT-4V, GPT-4 Turbo, GPT-4o support images
74
+ audio_input_support = False # No direct audio in chat (only via transcription)
75
+ video_input_support = False # No video support
76
+
77
+ # Streaming capabilities
78
+ streaming_support = True # All models support streaming
79
+ token_by_token_support = True # Provides token-by-token streaming
80
+
81
+ # Realtime capabilities
82
+ realtime_support = False # No realtime API yet
83
+
84
+ def __init__(self, **kwargs):
85
+ """
86
+ Initialize the OpenAI provider.
87
+
88
+ Args:
89
+ api_key: Optional API key
90
+ organization_id: Optional organization ID
91
+ **kwargs: Additional configuration options
92
+ """
93
+ # Get configuration with potential overrides from global config only
94
+ self.config = get_provider_config("openai")
95
+
96
+ # Extract credential parameters
97
+ api_key = kwargs.pop("api_key", None)
98
+ organization_id = kwargs.pop("organization_id", None)
99
+
100
+ # Filter out any other credential parameters
101
+ filtered_kwargs = {
102
+ k: v for k, v in kwargs.items() if k not in ["api_key", "organization_id"]
103
+ }
104
+
105
+ # Update non-credential configuration
106
+ self.config.update(filtered_kwargs)
107
+
108
+ # Apply credentials explicitly provided to the constructor
109
+ if api_key:
110
+ self.config["api_key"] = api_key
111
+ if organization_id:
112
+ self.config["organization_id"] = organization_id
113
+
114
+ # Check for required configuration
115
+ if not self.config.get("api_key"):
116
+ raise AuthenticationError(
117
+ "OpenAI API key is required. Set it via environment variable OPENAI_API_KEY "
118
+ "or with onellm.openai_api_key = 'your-key'.",
119
+ provider="openai",
120
+ )
121
+
122
+ # Store relevant configuration as instance variables
123
+ self.api_key = self.config["api_key"]
124
+ self.api_base = self.config["api_base"]
125
+ self.organization_id = self.config.get("organization_id")
126
+ self.timeout = self.config["timeout"]
127
+ self.max_retries = self.config["max_retries"]
128
+
129
+ # Create retry configuration
130
+ self.retry_config = RetryConfig(
131
+ max_retries=self.max_retries, initial_backoff=1.0, max_backoff=60.0
132
+ )
133
+
134
+ def _get_headers(self) -> Dict[str, str]:
135
+ """
136
+ Get the headers for API requests.
137
+
138
+ Returns:
139
+ Dict of headers
140
+ """
141
+ # Create standard headers with auth token
142
+ headers = {
143
+ "Content-Type": "application/json",
144
+ "Authorization": f"Bearer {self.api_key}",
145
+ }
146
+
147
+ # Add organization ID if provided
148
+ if self.organization_id:
149
+ headers["OpenAI-Organization"] = self.organization_id
150
+
151
+ return headers
152
+
153
+ async def _make_request(
154
+ self,
155
+ method: str,
156
+ path: str,
157
+ data: Optional[Dict[str, Any]] = None,
158
+ stream: bool = False,
159
+ timeout: Optional[float] = None,
160
+ files: Optional[Dict[str, Any]] = None,
161
+ ) -> Union[Dict[str, Any], AsyncGenerator[Dict[str, Any], None]]:
162
+ """
163
+ Make a request to the OpenAI API.
164
+
165
+ Args:
166
+ method: HTTP method (GET, POST, etc.)
167
+ path: API path
168
+ data: Request data
169
+ stream: Whether to stream the response
170
+ timeout: Request timeout in seconds
171
+ files: Files to upload
172
+
173
+ Returns:
174
+ Response data or streaming response
175
+
176
+ Raises:
177
+ MuxiLLMError: On API errors
178
+ """
179
+ # Construct the full URL by joining the base URL with the path
180
+ url = f"{self.api_base}/{path.lstrip('/')}"
181
+ # Use provided timeout or fall back to default
182
+ timeout = timeout or self.timeout
183
+ # Get authentication and content-type headers
184
+ headers = self._get_headers()
185
+
186
+ # Handle file uploads
187
+ if files:
188
+ # Need to use multipart/form-data for file uploads
189
+ headers.pop("Content-Type", None) # Remove Content-Type for multipart form
190
+ form_data = aiohttp.FormData()
191
+
192
+ # Add file data to the form
193
+ for key, file_info in files.items():
194
+ form_data.add_field(
195
+ key,
196
+ file_info["data"],
197
+ filename=file_info.get("filename", "file"),
198
+ content_type=file_info.get(
199
+ "content_type", "application/octet-stream"
200
+ ),
201
+ )
202
+
203
+ # Add other fields to the form
204
+ if data:
205
+ for key, value in data.items():
206
+ if isinstance(value, (dict, list)):
207
+ # Convert complex objects to JSON strings
208
+ form_data.add_field(
209
+ key, json.dumps(value), content_type="application/json"
210
+ )
211
+ else:
212
+ # Add simple values as strings
213
+ form_data.add_field(key, str(value))
214
+
215
+ body = form_data
216
+ else:
217
+ # For regular JSON requests, serialize the data
218
+ body = json.dumps(data) if data else None
219
+
220
+ async def execute_request():
221
+ """Inner function to execute the HTTP request with proper error handling"""
222
+ async with aiohttp.ClientSession() as session:
223
+ async with session.request(
224
+ method=method,
225
+ url=url,
226
+ headers=headers,
227
+ data=body,
228
+ timeout=timeout,
229
+ ssl=None, # Use default SSL settings
230
+ ) as response:
231
+ if stream:
232
+ # For streaming responses, return a generator
233
+ return self._handle_streaming_response(response)
234
+ else:
235
+ # For regular responses, parse JSON and handle errors
236
+ return await self._handle_response(response)
237
+
238
+ # Use retry mechanism for non-streaming requests
239
+ if not stream:
240
+ return await retry_async(execute_request, config=self.retry_config)
241
+ else:
242
+ # Streaming requests don't use retry mechanism
243
+ return await execute_request()
244
+
245
+ async def _handle_response(
246
+ self, response: aiohttp.ClientResponse
247
+ ) -> Dict[str, Any]:
248
+ """
249
+ Handle an API response.
250
+
251
+ Args:
252
+ response: API response
253
+
254
+ Returns:
255
+ Response data
256
+
257
+ Raises:
258
+ MuxiLLMError: On API errors
259
+ """
260
+ # Parse the JSON response
261
+ response_data = await response.json()
262
+
263
+ # Check for error status codes
264
+ if response.status != 200:
265
+ self._handle_error_response(response.status, response_data)
266
+
267
+ return response_data
268
+
269
+ async def _handle_streaming_response(
270
+ self, response: aiohttp.ClientResponse
271
+ ) -> AsyncGenerator[Dict[str, Any], None]:
272
+ """
273
+ Handle a streaming API response.
274
+
275
+ Args:
276
+ response: API response
277
+
278
+ Yields:
279
+ Parsed JSON chunks
280
+
281
+ Raises:
282
+ MuxiLLMError: On API errors
283
+ """
284
+ # Check for error status codes
285
+ if response.status != 200:
286
+ error_data = await response.json()
287
+ self._handle_error_response(response.status, error_data)
288
+
289
+ # Process the stream line by line
290
+ async for line in response.content:
291
+ line = line.decode("utf-8").strip()
292
+ # OpenAI's streaming format prefixes each JSON chunk with "data: "
293
+ if line.startswith("data: "):
294
+ line = line[6:] # Remove 'data: ' prefix
295
+
296
+ # Check for the stream end marker
297
+ if line == "[DONE]":
298
+ break
299
+
300
+ try:
301
+ # Parse the JSON chunk
302
+ yield json.loads(line)
303
+ except json.JSONDecodeError:
304
+ # Skip invalid lines
305
+ continue
306
+
307
+ def _handle_error_response(
308
+ self, status_code: int, response_data: Dict[str, Any]
309
+ ) -> None:
310
+ """
311
+ Handle an error response.
312
+
313
+ Args:
314
+ status_code: HTTP status code
315
+ response_data: Error response data
316
+
317
+ Raises:
318
+ MuxiLLMError: Appropriate error based on the status code
319
+ """
320
+ # Extract error details from the response
321
+ error = response_data.get("error", {})
322
+ message = error.get("message", "Unknown error")
323
+
324
+ # Map HTTP status codes to appropriate error types
325
+ if status_code == 401:
326
+ raise AuthenticationError(
327
+ message, provider="openai", status_code=status_code
328
+ )
329
+ elif status_code == 403:
330
+ raise PermissionError(message, provider="openai", status_code=status_code)
331
+ elif status_code == 404:
332
+ raise ResourceNotFoundError(
333
+ message, provider="openai", status_code=status_code
334
+ )
335
+ elif status_code == 429:
336
+ raise RateLimitError(message, provider="openai", status_code=status_code)
337
+ elif status_code == 400:
338
+ raise InvalidRequestError(
339
+ message, provider="openai", status_code=status_code
340
+ )
341
+ elif status_code == 500:
342
+ raise ServiceUnavailableError(
343
+ message, provider="openai", status_code=status_code
344
+ )
345
+ elif status_code == 502:
346
+ raise BadGatewayError(message, provider="openai", status_code=status_code)
347
+ elif status_code == 504:
348
+ raise TimeoutError(message, provider="openai", status_code=status_code)
349
+ else:
350
+ # Generic error for unhandled status codes
351
+ raise APIError(
352
+ f"OpenAI API error: {message} (status code: {status_code})",
353
+ provider="openai",
354
+ status_code=status_code,
355
+ error_data=error,
356
+ )
357
+
358
+ async def create_chat_completion(
359
+ self, messages: List[Message], model: str, stream: bool = False, **kwargs
360
+ ) -> Union[ChatCompletionResponse, AsyncGenerator[ChatCompletionChunk, None]]:
361
+ """
362
+ Create a chat completion with OpenAI.
363
+
364
+ Args:
365
+ messages: List of messages in the conversation
366
+ model: Model name (without provider prefix)
367
+ stream: Whether to stream the response
368
+ **kwargs: Additional model parameters
369
+
370
+ Returns:
371
+ ChatCompletionResponse or a generator yielding ChatCompletionChunk objects
372
+ """
373
+ # Process messages for vision models if needed
374
+ processed_messages = self._process_messages_for_vision(messages, model)
375
+
376
+ # Set up the request data
377
+ data = {
378
+ "model": model,
379
+ "messages": processed_messages,
380
+ "stream": stream,
381
+ **kwargs,
382
+ }
383
+
384
+ # Make the request
385
+ if stream:
386
+ # Handle streaming response
387
+ async def chunk_generator() -> AsyncGenerator[ChatCompletionChunk, None]:
388
+ """Generator function to process streaming chunks"""
389
+ async for chunk in await self._make_request(
390
+ method="POST", path="chat/completions", data=data, stream=True
391
+ ):
392
+ if chunk:
393
+ # Skip empty chunks
394
+ if "choices" not in chunk or not chunk["choices"]:
395
+ continue
396
+
397
+ # Transform choices into our model format
398
+ choices = []
399
+ for choice_data in chunk["choices"]:
400
+ # Extract delta data from the chunk
401
+ delta_data = choice_data.get("delta", {})
402
+ # Create a ChoiceDelta object
403
+ delta = ChoiceDelta(
404
+ content=delta_data.get("content"),
405
+ role=delta_data.get("role"),
406
+ function_call=delta_data.get("function_call"),
407
+ tool_calls=delta_data.get("tool_calls"),
408
+ finish_reason=choice_data.get("finish_reason"),
409
+ )
410
+ # Create a StreamingChoice object
411
+ choice = StreamingChoice(
412
+ delta=delta,
413
+ finish_reason=choice_data.get("finish_reason"),
414
+ index=choice_data.get("index", 0),
415
+ )
416
+ choices.append(choice)
417
+
418
+ # Create the chunk response object
419
+ chunk_resp = ChatCompletionChunk(
420
+ id=chunk.get("id", ""),
421
+ object=chunk.get("object", "chat.completion.chunk"),
422
+ created=chunk.get("created", int(time.time())),
423
+ model=chunk.get("model", model),
424
+ choices=choices,
425
+ system_fingerprint=chunk.get("system_fingerprint"),
426
+ )
427
+ yield chunk_resp
428
+
429
+ return chunk_generator()
430
+ else:
431
+ # Handle non-streaming response
432
+ response_data = await self._make_request(
433
+ method="POST", path="chat/completions", data=data
434
+ )
435
+
436
+ # Transform choices into our model format
437
+ choices = []
438
+ for choice_data in response_data.get("choices", []):
439
+ choice = Choice(
440
+ message=choice_data.get("message", {}),
441
+ finish_reason=choice_data.get("finish_reason"),
442
+ index=choice_data.get("index", 0),
443
+ )
444
+ choices.append(choice)
445
+
446
+ # Create the response object
447
+ response = ChatCompletionResponse(
448
+ id=response_data.get("id", ""),
449
+ object=response_data.get("object", "chat.completion"),
450
+ created=response_data.get("created", int(time.time())),
451
+ model=response_data.get("model", model),
452
+ choices=choices,
453
+ usage=response_data.get("usage"),
454
+ system_fingerprint=response_data.get("system_fingerprint"),
455
+ )
456
+ return response
457
+
458
+ def _process_messages_for_vision(
459
+ self, messages: List[Message], model: str
460
+ ) -> List[Message]:
461
+ """
462
+ Process messages to ensure they're compatible with vision models if needed.
463
+
464
+ This checks for image content items and formats them correctly for the OpenAI API.
465
+ Also validates that vision content is only sent to models that support it.
466
+
467
+ Args:
468
+ messages: Original messages
469
+ model: Model name to check for vision support
470
+
471
+ Returns:
472
+ Processed messages suitable for the API
473
+
474
+ Raises:
475
+ InvalidRequestError: If trying to send images to a non-vision model
476
+ """
477
+ # Check if any message contains images
478
+ has_images = False
479
+ for message in messages:
480
+ content = message.get("content", "")
481
+ # Check for image content in list format
482
+ if isinstance(content, list):
483
+ for item in content:
484
+ if item.get("type") == "image_url" or item.get("type") == "image":
485
+ has_images = True
486
+ break
487
+ if has_images:
488
+ break
489
+
490
+ # If no images found, return original messages
491
+ if not has_images:
492
+ return messages
493
+
494
+ # Check if model supports vision
495
+ # List of models known to support vision capabilities
496
+ vision_models = {
497
+ "gpt-4-vision-preview",
498
+ "gpt-4-turbo",
499
+ "gpt-4-turbo-2024-04-09",
500
+ "gpt-4o",
501
+ "gpt-4o-2024-05-13",
502
+ }
503
+ # Extract the base model name for broader matching
504
+ model_base = model.split("-")[0]
505
+ # Check if the model is in our vision models list or has a matching base name
506
+ model_supports_vision = (
507
+ any(vm in model for vm in vision_models) or model_base == "gpt4o"
508
+ )
509
+
510
+ # Raise error if trying to use images with a non-vision model
511
+ if not model_supports_vision:
512
+ raise InvalidRequestError(
513
+ f"Model '{model}' does not support vision inputs. "
514
+ f"Use a vision-capable model like 'gpt-4-vision-preview' or 'gpt-4o'."
515
+ )
516
+
517
+ # Process each message to ensure image_url formats are correct
518
+ processed_messages = []
519
+ for message in messages:
520
+ processed_message = dict(message) # Create a copy
521
+ content = message.get("content", "")
522
+
523
+ # Only process if content is a list
524
+ if isinstance(content, list):
525
+ processed_content = []
526
+ for item in content:
527
+ # Process image_url to ensure correct format
528
+ if item.get("type") == "image_url" and isinstance(
529
+ item.get("image_url"), dict
530
+ ):
531
+ image_url = item["image_url"]
532
+ # Ensure url field exists
533
+ if "url" not in image_url:
534
+ raise InvalidRequestError(
535
+ "Image URL must contain a 'url' field"
536
+ )
537
+
538
+ # Ensure detail field is valid if present
539
+ if "detail" in image_url and image_url["detail"] not in [
540
+ "auto",
541
+ "low",
542
+ "high",
543
+ ]:
544
+ # Default to "auto" if an invalid detail level is provided
545
+ image_url["detail"] = "auto"
546
+
547
+ processed_content.append(item)
548
+ # Handle other content types
549
+ else:
550
+ processed_content.append(item)
551
+
552
+ processed_message["content"] = processed_content
553
+
554
+ processed_messages.append(processed_message)
555
+
556
+ return processed_messages
557
+
558
+ async def create_completion(
559
+ self, prompt: str, model: str, stream: bool = False, **kwargs
560
+ ) -> Union[CompletionResponse, AsyncGenerator[Any, None]]:
561
+ """
562
+ Create a text completion.
563
+
564
+ Args:
565
+ prompt: Text prompt to complete
566
+ model: Model name
567
+ stream: Whether to stream the response
568
+ **kwargs: Additional parameters
569
+
570
+ Returns:
571
+ CompletionResponse or generator yielding completion chunks
572
+ """
573
+ # Prepare request data with all parameters
574
+ request_data = {"model": model, "prompt": prompt, "stream": stream, **kwargs}
575
+
576
+ if stream:
577
+ # Use streaming API
578
+ raw_generator = await self._make_request(
579
+ method="POST", path="/completions", data=request_data, stream=True
580
+ )
581
+
582
+ # Just return the raw chunks for now - further processing can be added as needed
583
+ return raw_generator
584
+ else:
585
+ # Use non-streaming API
586
+ response_data = await self._make_request(
587
+ method="POST", path="/completions", data=request_data
588
+ )
589
+
590
+ # Convert API response to CompletionResponse model
591
+ choices = []
592
+ for choice_data in response_data.get("choices", []):
593
+ choice = CompletionChoice(
594
+ text=choice_data.get("text", ""),
595
+ index=choice_data.get("index", 0),
596
+ logprobs=choice_data.get("logprobs"),
597
+ finish_reason=choice_data.get("finish_reason"),
598
+ )
599
+ choices.append(choice)
600
+
601
+ # Create and return the structured response object
602
+ return CompletionResponse(
603
+ id=response_data.get("id", ""),
604
+ object=response_data.get("object", "text_completion"),
605
+ created=response_data.get("created", int(time.time())),
606
+ model=response_data.get("model", model),
607
+ choices=choices,
608
+ usage=response_data.get("usage"),
609
+ system_fingerprint=response_data.get("system_fingerprint"),
610
+ )
611
+
612
+ async def create_embedding(
613
+ self, input: Union[str, List[str]], model: str, **kwargs
614
+ ) -> EmbeddingResponse:
615
+ """
616
+ Create embeddings for the provided input.
617
+
618
+ Args:
619
+ input: Text or list of texts to embed
620
+ model: Model name
621
+ **kwargs: Additional parameters
622
+
623
+ Returns:
624
+ EmbeddingResponse containing the generated embeddings
625
+ """
626
+ # Prepare request data with all parameters
627
+ request_data = {"model": model, "input": input, **kwargs}
628
+
629
+ # Make API request to embeddings endpoint
630
+ response_data = await self._make_request(
631
+ method="POST", path="/embeddings", data=request_data
632
+ )
633
+
634
+ # Convert API response to EmbeddingResponse model
635
+ embedding_data = []
636
+ for data in response_data.get("data", []):
637
+ embedding = EmbeddingData(
638
+ embedding=data.get("embedding", []),
639
+ index=data.get("index", 0),
640
+ object=data.get("object", "embedding"),
641
+ )
642
+ embedding_data.append(embedding)
643
+
644
+ # Create and return the structured response object
645
+ return EmbeddingResponse(
646
+ object=response_data.get("object", "list"),
647
+ data=embedding_data,
648
+ model=response_data.get("model", model),
649
+ usage=response_data.get("usage"),
650
+ )
651
+
652
+ async def upload_file(self, file: Any, purpose: str, **kwargs) -> FileObject:
653
+ """
654
+ Upload a file to OpenAI.
655
+
656
+ Args:
657
+ file: File to upload (path, bytes, or file-like object)
658
+ purpose: Purpose of the file
659
+ **kwargs: Additional parameters
660
+
661
+ Returns:
662
+ FileObject representing the uploaded file
663
+ """
664
+ # Prepare file data based on the input type
665
+ if isinstance(file, str):
666
+ # File path - read the file from disk
667
+ with open(file, "rb") as f:
668
+ file_data = f.read()
669
+ filename = file.split("/")[-1] # Extract filename from path
670
+ elif isinstance(file, bytes):
671
+ # Bytes data - use directly
672
+ file_data = file
673
+ filename = kwargs.get("filename", "file.dat") # Use provided or default name
674
+ elif hasattr(file, "read"):
675
+ # File-like object - read the content
676
+ file_data = file.read()
677
+ filename = getattr(file, "name", "file.dat") # Try to get name from object
678
+ else:
679
+ # Invalid input type
680
+ error_msg = (
681
+ "Invalid file type. Expected file path, bytes, or file-like object."
682
+ )
683
+ raise InvalidRequestError(error_msg)
684
+
685
+ # Prepare request data, excluding filename which is handled separately
686
+ request_data = {
687
+ "purpose": purpose,
688
+ **{k: v for k, v in kwargs.items() if k != "filename"},
689
+ }
690
+
691
+ # Set up file data for multipart upload
692
+ files = {
693
+ "file": {
694
+ "data": file_data,
695
+ "filename": filename,
696
+ "content_type": "application/octet-stream",
697
+ }
698
+ }
699
+
700
+ # Make API request to files endpoint
701
+ response_data = await self._make_request(
702
+ method="POST", path="/files", data=request_data, files=files
703
+ )
704
+
705
+ # Convert API response to FileObject model
706
+ return FileObject(
707
+ id=response_data.get("id", ""),
708
+ object=response_data.get("object", "file"),
709
+ bytes=response_data.get("bytes", 0),
710
+ created_at=response_data.get("created_at", int(time.time())),
711
+ filename=response_data.get("filename", filename),
712
+ purpose=response_data.get("purpose", purpose),
713
+ status=response_data.get("status"),
714
+ status_details=response_data.get("status_details"),
715
+ )
716
+
717
+ async def download_file(self, file_id: str, **kwargs) -> bytes:
718
+ """
719
+ Download a file from OpenAI.
720
+
721
+ Args:
722
+ file_id: ID of the file to download
723
+ **kwargs: Additional parameters
724
+
725
+ Returns:
726
+ Bytes content of the file
727
+ """
728
+ # Construct the URL for file download
729
+ url = f"{self.api_base}/files/{file_id}/content"
730
+ # Use provided timeout or fall back to default
731
+ timeout = kwargs.get("timeout", self.timeout)
732
+ # Get authentication headers
733
+ headers = self._get_headers()
734
+
735
+ async def execute_request():
736
+ """Inner function to execute the download request with proper error handling"""
737
+ async with aiohttp.ClientSession() as session:
738
+ async with session.get(
739
+ url=url,
740
+ headers=headers,
741
+ timeout=timeout,
742
+ ssl=None, # Use default SSL settings
743
+ ) as response:
744
+ # Check for error status codes
745
+ if response.status != 200:
746
+ error_data = await response.json()
747
+ self._handle_error_response(response.status, error_data)
748
+
749
+ # Return the raw file content
750
+ return await response.read()
751
+
752
+ # Use retry mechanism for reliability
753
+ return await retry_async(execute_request, config=self.retry_config)
754
+
755
+ async def list_files(self, **kwargs) -> Dict[str, Any]:
756
+ """
757
+ List files available to the user.
758
+
759
+ Args:
760
+ **kwargs: Additional parameters like 'purpose' to filter files
761
+
762
+ Returns:
763
+ Dictionary containing list of files
764
+ """
765
+ # Extract additional parameters
766
+ data = {}
767
+ # Add purpose filter if provided
768
+ if "purpose" in kwargs:
769
+ data["purpose"] = kwargs["purpose"]
770
+
771
+ # Make the API request to list files
772
+ return await self._make_request(
773
+ method="GET",
774
+ path="/files",
775
+ data=data
776
+ )
777
+
778
+ async def delete_file(self, file_id: str, **kwargs) -> Dict[str, Any]:
779
+ """
780
+ Delete a file.
781
+
782
+ Args:
783
+ file_id: ID of the file to delete
784
+ **kwargs: Additional parameters
785
+
786
+ Returns:
787
+ Dictionary with deletion status
788
+ """
789
+ # Make the API request to delete the file
790
+ return await self._make_request(
791
+ method="DELETE",
792
+ path=f"/files/{file_id}"
793
+ )
794
+
795
+ async def create_transcription(
796
+ self, file: Union[str, bytes, IO[bytes]], model: str = "whisper-1", **kwargs
797
+ ) -> TranscriptionResult:
798
+ """
799
+ Transcribe audio to text using OpenAI's Whisper model.
800
+
801
+ Args:
802
+ file: Audio file to transcribe (path, bytes, or file-like object)
803
+ model: Model to use for transcription (default: whisper-1)
804
+ **kwargs: Additional parameters:
805
+ - language: Optional language code (e.g., "en")
806
+ - prompt: Optional text to guide transcription
807
+ - response_format: Format of the response
808
+ ("json", "text", "srt", "verbose_json", "vtt")
809
+ - temperature: Temperature for sampling
810
+
811
+ Returns:
812
+ Transcription result
813
+ """
814
+ # Process the file to get binary data and filename
815
+ file_data, filename = self._process_audio_file(file, kwargs.get("filename"))
816
+
817
+ # Prepare the request data, excluding filename which is handled separately
818
+ request_data = {
819
+ "model": model,
820
+ **{k: v for k, v in kwargs.items() if k not in ["filename"]},
821
+ }
822
+
823
+ # Set up files dictionary for multipart upload
824
+ files = {
825
+ "file": {
826
+ "data": file_data,
827
+ "filename": filename,
828
+ "content_type": self._guess_audio_content_type(filename),
829
+ }
830
+ }
831
+
832
+ # Make the API request to transcriptions endpoint
833
+ response_data = await self._make_request(
834
+ method="POST", path="/audio/transcriptions", data=request_data, files=files
835
+ )
836
+
837
+ # Process the response based on the requested format
838
+ response_format = kwargs.get("response_format", "json")
839
+ if isinstance(response_format, str) and response_format != "json":
840
+ # For non-JSON formats, return a simplified result with just the text
841
+ return TranscriptionResult(text=response_data)
842
+
843
+ # For JSON or default format, parse the structured response
844
+ return TranscriptionResult(
845
+ text=response_data.get("text", ""),
846
+ task=response_data.get("task"),
847
+ language=response_data.get("language"),
848
+ duration=response_data.get("duration"),
849
+ segments=response_data.get("segments"),
850
+ words=response_data.get("words"),
851
+ )
852
+
853
+ async def create_translation(
854
+ self, file: Union[str, bytes, IO[bytes]], model: str = "whisper-1", **kwargs
855
+ ) -> TranscriptionResult:
856
+ """
857
+ Translate audio to English text using OpenAI's Whisper model.
858
+
859
+ Args:
860
+ file: Audio file to translate (path, bytes, or file-like object)
861
+ model: Model to use for translation (default: whisper-1)
862
+ **kwargs: Additional parameters:
863
+ - prompt: Optional text to guide translation
864
+ - response_format: Format of the response
865
+ ("json", "text", "srt", "verbose_json", "vtt")
866
+ - temperature: Temperature for sampling
867
+
868
+ Returns:
869
+ Translation result
870
+ """
871
+ # Process the file to get binary data and filename
872
+ file_data, filename = self._process_audio_file(file, kwargs.get("filename"))
873
+
874
+ # Prepare the request data, excluding filename which is handled separately
875
+ request_data = {
876
+ "model": model,
877
+ **{k: v for k, v in kwargs.items() if k not in ["filename"]},
878
+ }
879
+
880
+ # Set up files dictionary for multipart upload
881
+ files = {
882
+ "file": {
883
+ "data": file_data,
884
+ "filename": filename,
885
+ "content_type": self._guess_audio_content_type(filename),
886
+ }
887
+ }
888
+
889
+ # Make the API request to translations endpoint
890
+ response_data = await self._make_request(
891
+ method="POST", path="/audio/translations", data=request_data, files=files
892
+ )
893
+
894
+ # Process the response based on the requested format
895
+ response_format = kwargs.get("response_format", "json")
896
+ if isinstance(response_format, str) and response_format != "json":
897
+ # For non-JSON formats, return a simplified result with just the text
898
+ return TranscriptionResult(text=response_data)
899
+
900
+ # For JSON or default format, parse the structured response
901
+ # Note: Translations are always to English
902
+ return TranscriptionResult(
903
+ text=response_data.get("text", ""),
904
+ task="translation",
905
+ language="en", # Translations are always to English
906
+ duration=response_data.get("duration"),
907
+ segments=response_data.get("segments"),
908
+ words=response_data.get("words"),
909
+ )
910
+
911
+ def _process_audio_file(
912
+ self, file: Union[str, bytes, IO[bytes]], filename: Optional[str] = None
913
+ ) -> tuple:
914
+ """
915
+ Process an audio file for API requests.
916
+
917
+ This helper method handles different input types for audio files and converts them
918
+ to a consistent format for API requests. It supports file paths, byte data, and
919
+ file-like objects.
920
+
921
+ Args:
922
+ file: Audio file (path, bytes, or file-like object)
923
+ filename: Optional filename override
924
+
925
+ Returns:
926
+ Tuple of (file_data, filename)
927
+
928
+ Raises:
929
+ InvalidRequestError: If file type is invalid
930
+ """
931
+ # Handle different input types for the audio file
932
+ if isinstance(file, str):
933
+ # File path - read the file from disk
934
+ with open(file, "rb") as f:
935
+ file_data = f.read()
936
+ filename = filename or file.split("/")[-1] # Use provided or extract from path
937
+ elif isinstance(file, bytes):
938
+ # Bytes data
939
+ file_data = file
940
+ filename = filename or "audio.mp3" # Default filename for byte data
941
+ elif hasattr(file, "read"):
942
+ # File-like object
943
+ file_data = file.read() if callable(file.read) else file.read
944
+ filename = filename or getattr(file, "name", "audio.mp3")
945
+ else:
946
+ # Invalid input type
947
+ raise InvalidRequestError(
948
+ "Invalid file type. Expected file path, bytes, or file-like object."
949
+ )
950
+
951
+ return file_data, filename
952
+
953
+ def _guess_audio_content_type(self, filename: str) -> str:
954
+ """
955
+ Guess the content type based on the audio file extension.
956
+
957
+ This helper method determines the appropriate MIME type for an audio file
958
+ based on its file extension, which is required for proper multipart uploads.
959
+
960
+ Args:
961
+ filename: Name of the audio file
962
+
963
+ Returns:
964
+ MIME type for the audio file (defaults to audio/mpeg if unknown)
965
+ """
966
+ # Map file extensions to MIME types
967
+ mime_types = {
968
+ ".mp3": "audio/mpeg",
969
+ ".mp4": "audio/mp4",
970
+ ".mpeg": "audio/mpeg",
971
+ ".mpga": "audio/mpeg",
972
+ ".m4a": "audio/mp4",
973
+ ".wav": "audio/wav",
974
+ ".webm": "audio/webm",
975
+ }
976
+
977
+ # Get the file extension
978
+ ext = "." + filename.split(".")[-1].lower() if "." in filename else ""
979
+
980
+ # Return the MIME type or a default
981
+ return mime_types.get(ext, "audio/mpeg")
982
+
983
+ async def _make_request_raw(
984
+ self,
985
+ method: str,
986
+ path: str,
987
+ data: Optional[Dict[str, Any]] = None,
988
+ timeout: Optional[float] = None,
989
+ ) -> bytes:
990
+ """
991
+ Make a request to the OpenAI API and return raw binary data.
992
+
993
+ Unlike the standard _make_request method which returns parsed JSON,
994
+ this method returns the raw binary response, which is necessary for
995
+ endpoints that return non-JSON data like audio files.
996
+
997
+ Args:
998
+ method: HTTP method (GET, POST, etc.)
999
+ path: API path
1000
+ data: Request data
1001
+ timeout: Request timeout in seconds
1002
+
1003
+ Returns:
1004
+ Raw binary response data
1005
+
1006
+ Raises:
1007
+ MuxiLLMError: On API errors
1008
+ """
1009
+ url = f"{self.api_base}/{path.lstrip('/')}" # Ensure path starts without slash
1010
+ timeout = timeout or self.timeout # Use provided timeout or default
1011
+ headers = self._get_headers() # Get authentication and other headers
1012
+ body = json.dumps(data) if data else None # Serialize data to JSON if provided
1013
+
1014
+ async def execute_request():
1015
+ """Inner function to execute the HTTP request with error handling"""
1016
+ async with aiohttp.ClientSession() as session:
1017
+ async with session.request(
1018
+ method=method,
1019
+ url=url,
1020
+ headers=headers,
1021
+ data=body,
1022
+ timeout=timeout,
1023
+ ssl=None, # Use default SSL settings
1024
+ ) as response:
1025
+ if response.status != 200:
1026
+ # Handle error response as JSON
1027
+ try:
1028
+ error_data = await response.json()
1029
+ self._handle_error_response(response.status, error_data)
1030
+ except json.JSONDecodeError:
1031
+ # If not valid JSON, raise a generic error with the status code
1032
+ error_text = await response.text()
1033
+ raise APIError(
1034
+ f"OpenAI API error: {error_text} (status code: {response.status})",
1035
+ provider="openai",
1036
+ status_code=response.status,
1037
+ )
1038
+
1039
+ # Return the raw binary data
1040
+ return await response.read()
1041
+
1042
+ # Use retry mechanism for resilience
1043
+ return await retry_async(execute_request, config=self.retry_config)
1044
+
1045
+ async def create_speech(
1046
+ self, input: str, model: str = "tts-1", voice: str = "alloy", **kwargs
1047
+ ) -> bytes:
1048
+ """
1049
+ Generate audio from text using OpenAI's text-to-speech models.
1050
+
1051
+ This method converts text to spoken audio using OpenAI's TTS models.
1052
+ It supports different voices, speeds, and output formats.
1053
+
1054
+ Args:
1055
+ input: Text to convert to speech
1056
+ model: Model to use (default: tts-1)
1057
+ voice: Voice to use (default: alloy)
1058
+ **kwargs: Additional parameters:
1059
+ - response_format: Format of the response ("mp3", "opus", "aac", "flac")
1060
+ - speed: Speed of the generated audio (0.25 to 4.0)
1061
+
1062
+ Returns:
1063
+ Audio data as bytes
1064
+ """
1065
+ # Validate parameters
1066
+ if not input or not isinstance(input, str):
1067
+ raise InvalidRequestError("Input text is required and must be a string")
1068
+
1069
+ # Check model - supported models as of current version
1070
+ supported_models = {"tts-1", "tts-1-hd"}
1071
+ if model not in supported_models:
1072
+ raise InvalidRequestError(
1073
+ f"Model '{model}' is not a supported TTS model. "
1074
+ f"Use one of: {', '.join(supported_models)}"
1075
+ )
1076
+
1077
+ # Check voice
1078
+ supported_voices = {"alloy", "echo", "fable", "onyx", "nova", "shimmer"}
1079
+ if voice not in supported_voices:
1080
+ raise InvalidRequestError(
1081
+ f"Voice '{voice}' is not supported. "
1082
+ f"Use one of: {', '.join(supported_voices)}"
1083
+ )
1084
+
1085
+ # Check response format if provided
1086
+ response_format = kwargs.get("response_format", "mp3")
1087
+ supported_formats = {"mp3", "opus", "aac", "flac"}
1088
+ if response_format not in supported_formats:
1089
+ raise InvalidRequestError(
1090
+ f"Response format '{response_format}' is not supported. "
1091
+ f"Use one of: {', '.join(supported_formats)}"
1092
+ )
1093
+
1094
+ # Check speed if provided
1095
+ speed = kwargs.get("speed", 1.0)
1096
+ if not isinstance(speed, (int, float)) or speed < 0.25 or speed > 4.0:
1097
+ raise InvalidRequestError("Speed must be a number between 0.25 and 4.0")
1098
+
1099
+ # Prepare request data
1100
+ request_data = {
1101
+ "input": input,
1102
+ "model": model,
1103
+ "voice": voice,
1104
+ **{k: v for k, v in kwargs.items() if k in ["response_format", "speed"]},
1105
+ }
1106
+
1107
+ # Make the API request with raw binary response
1108
+ return await self._make_request_raw(
1109
+ method="POST", path="/audio/speech", data=request_data
1110
+ )
1111
+
1112
+ async def create_image(
1113
+ self,
1114
+ prompt: str,
1115
+ model: str = "dall-e-3",
1116
+ n: int = 1,
1117
+ size: str = "1024x1024",
1118
+ **kwargs,
1119
+ ) -> ImageGenerationResult:
1120
+ """
1121
+ Generate images from a text prompt using OpenAI's DALL-E models.
1122
+
1123
+ This method creates images based on text descriptions using OpenAI's DALL-E models.
1124
+ Different models support different sizes, quality levels, and styles.
1125
+
1126
+ Args:
1127
+ prompt: Text description of the desired image
1128
+ model: Model to use (default: dall-e-3)
1129
+ n: Number of images to generate (default: 1)
1130
+ size: Size of the generated images (default: 1024x1024)
1131
+ **kwargs: Additional parameters:
1132
+ - quality: Quality of the image ("standard" or "hd"), for DALL-E 3
1133
+ - style: Style of image ("natural" or "vivid"), for DALL-E 3
1134
+ - response_format: Format of the response ("url" or "b64_json")
1135
+ - user: End-user ID for tracking
1136
+
1137
+ Returns:
1138
+ Image generation result
1139
+ """
1140
+ # Validate parameters
1141
+ if not prompt or not isinstance(prompt, str):
1142
+ raise InvalidRequestError("Prompt is required and must be a string")
1143
+
1144
+ # Check model
1145
+ supported_models = {"dall-e-2", "dall-e-3"}
1146
+ if model not in supported_models:
1147
+ raise InvalidRequestError(
1148
+ f"Model '{model}' is not a supported image generation model. "
1149
+ f"Use one of: {', '.join(supported_models)}"
1150
+ )
1151
+
1152
+ # Check size based on model - different models support different sizes
1153
+ supported_sizes = {
1154
+ "dall-e-2": {"256x256", "512x512", "1024x1024"},
1155
+ "dall-e-3": {"1024x1024", "1792x1024", "1024x1792"},
1156
+ }
1157
+ if size not in supported_sizes[model]:
1158
+ raise InvalidRequestError(
1159
+ f"Size '{size}' is not supported for {model}. "
1160
+ f"Use one of: {', '.join(supported_sizes[model])}"
1161
+ )
1162
+
1163
+ # Check n (number of images)
1164
+ # DALL-E 3 only supports n=1
1165
+ if model == "dall-e-3" and n > 1:
1166
+ raise InvalidRequestError(
1167
+ "DALL-E 3 only supports generating one image at a time (n=1)"
1168
+ )
1169
+
1170
+ # For DALL-E 2, n can be between 1 and 10
1171
+ if model == "dall-e-2" and (not isinstance(n, int) or n < 1 or n > 10):
1172
+ raise InvalidRequestError(
1173
+ "For DALL-E 2, the number of images (n) must be between 1 and 10"
1174
+ )
1175
+
1176
+ # Check quality (DALL-E 3 only)
1177
+ quality = kwargs.get("quality")
1178
+ if model == "dall-e-3" and quality is not None:
1179
+ supported_qualities = {"standard", "hd"}
1180
+ if quality not in supported_qualities:
1181
+ raise InvalidRequestError(
1182
+ f"Quality '{quality}' is not supported. "
1183
+ f"Use one of: {', '.join(supported_qualities)}"
1184
+ )
1185
+
1186
+ # Check style (DALL-E 3 only)
1187
+ style = kwargs.get("style")
1188
+ if model == "dall-e-3" and style is not None:
1189
+ supported_styles = {"natural", "vivid"}
1190
+ if style not in supported_styles:
1191
+ raise InvalidRequestError(
1192
+ f"Style '{style}' is not supported. "
1193
+ f"Use one of: {', '.join(supported_styles)}"
1194
+ )
1195
+
1196
+ # Check response format
1197
+ response_format = kwargs.get("response_format", "url")
1198
+ supported_formats = {"url", "b64_json"}
1199
+ if response_format not in supported_formats:
1200
+ raise InvalidRequestError(
1201
+ f"Response format '{response_format}' is not supported. "
1202
+ f"Use one of: {', '.join(supported_formats)}"
1203
+ )
1204
+
1205
+ # Prepare request data - only include supported parameters
1206
+ request_data = {
1207
+ "prompt": prompt,
1208
+ "model": model,
1209
+ "n": n,
1210
+ "size": size,
1211
+ **{
1212
+ k: v
1213
+ for k, v in kwargs.items()
1214
+ if k in ["quality", "style", "response_format", "user"]
1215
+ },
1216
+ }
1217
+
1218
+ # Make the API request
1219
+ response_data = await self._make_request(
1220
+ method="POST", path="/images/generations", data=request_data
1221
+ )
1222
+
1223
+ # Convert response to ImageGenerationResult object
1224
+ return ImageGenerationResult(
1225
+ created=response_data.get("created", int(time.time())),
1226
+ data=response_data.get("data", []),
1227
+ )
1228
+
1229
+
1230
+ # Register the OpenAI provider
1231
+ register_provider("openai", OpenAIProvider)