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/.version +1 -0
- onellm/__init__.py +123 -0
- onellm/audio.py +218 -0
- onellm/chat_completion.py +398 -0
- onellm/client.py +676 -0
- onellm/completion.py +199 -0
- onellm/config.py +191 -0
- onellm/embedding.py +170 -0
- onellm/errors.py +250 -0
- onellm/files.py +318 -0
- onellm/image.py +207 -0
- onellm/models.py +359 -0
- onellm/providers/__init__.py +48 -0
- onellm/providers/base.py +279 -0
- onellm/providers/fallback.py +688 -0
- onellm/providers/openai.py +1231 -0
- onellm/speech.py +142 -0
- onellm/types/__init__.py +61 -0
- onellm/types/common.py +371 -0
- onellm/utils/__init__.py +46 -0
- onellm/utils/fallback.py +102 -0
- onellm/utils/retry.py +175 -0
- onellm/utils/streaming.py +357 -0
- onellm/utils/token_counter.py +238 -0
- onellm/validators.py +1314 -0
- onellm-0.0.6.dist-info/METADATA +832 -0
- onellm-0.0.6.dist-info/RECORD +30 -0
- onellm-0.0.6.dist-info/WHEEL +5 -0
- onellm-0.0.6.dist-info/licenses/LICENSE +201 -0
- onellm-0.0.6.dist-info/top_level.txt +1 -0
onellm/utils/fallback.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
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
|
+
Fallback utilities for OneLLM.
|
|
23
|
+
|
|
24
|
+
This module provides utilities for model fallback functionality.
|
|
25
|
+
When a primary model or provider fails, these utilities help gracefully
|
|
26
|
+
fall back to alternative models or providers to maintain service reliability.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from typing import Callable, List, Optional, Type, TypeVar
|
|
30
|
+
import inspect
|
|
31
|
+
|
|
32
|
+
from ..errors import (
|
|
33
|
+
ServiceUnavailableError,
|
|
34
|
+
TimeoutError,
|
|
35
|
+
BadGatewayError,
|
|
36
|
+
RateLimitError,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# Define a generic type for the return value
|
|
40
|
+
# This allows the fallback mechanism to work with any return type
|
|
41
|
+
T = TypeVar("T")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FallbackConfig:
|
|
45
|
+
"""
|
|
46
|
+
Configuration for fallback behavior.
|
|
47
|
+
|
|
48
|
+
This class defines how fallbacks should be handled when errors occur,
|
|
49
|
+
including which errors should trigger fallbacks, how many fallbacks to attempt,
|
|
50
|
+
and optional logging and callback functionality.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
retriable_errors: Optional[List[Type[Exception]]] = None,
|
|
56
|
+
max_fallbacks: Optional[int] = None,
|
|
57
|
+
log_fallbacks: bool = True,
|
|
58
|
+
fallback_callback: Optional[Callable] = None,
|
|
59
|
+
):
|
|
60
|
+
"""
|
|
61
|
+
Initialize fallback configuration.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
retriable_errors: Error types that should trigger fallbacks. If None,
|
|
65
|
+
defaults to common network and rate limit errors.
|
|
66
|
+
max_fallbacks: Maximum number of fallbacks to try before giving up.
|
|
67
|
+
If None, will try all available fallbacks.
|
|
68
|
+
log_fallbacks: Whether to log fallback attempts for monitoring and debugging.
|
|
69
|
+
fallback_callback: Optional callback function when fallbacks are used.
|
|
70
|
+
Can be used for metrics collection or notifications.
|
|
71
|
+
"""
|
|
72
|
+
# Default to common API errors if no specific errors are provided
|
|
73
|
+
self.retriable_errors = retriable_errors or [
|
|
74
|
+
ServiceUnavailableError,
|
|
75
|
+
TimeoutError,
|
|
76
|
+
BadGatewayError,
|
|
77
|
+
RateLimitError,
|
|
78
|
+
]
|
|
79
|
+
self.max_fallbacks = max_fallbacks
|
|
80
|
+
self.log_fallbacks = log_fallbacks
|
|
81
|
+
self.fallback_callback = fallback_callback
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
async def maybe_await(result):
|
|
85
|
+
"""
|
|
86
|
+
Helper to await a result if it's awaitable, otherwise return it directly.
|
|
87
|
+
|
|
88
|
+
This utility function allows the fallback mechanism to work with both
|
|
89
|
+
synchronous and asynchronous functions by handling the awaiting logic.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
result: The result to potentially await, could be a coroutine or regular value
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
The awaited result if it was awaitable, or the original result otherwise
|
|
96
|
+
"""
|
|
97
|
+
# Check if the result is a coroutine or other awaitable object
|
|
98
|
+
if inspect.isawaitable(result):
|
|
99
|
+
# If it is awaitable, await it and return the result
|
|
100
|
+
return await result
|
|
101
|
+
# Otherwise, return the result directly
|
|
102
|
+
return result
|
onellm/utils/retry.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
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
|
+
Retry mechanism for handling transient errors.
|
|
23
|
+
|
|
24
|
+
This module provides utilities for retrying operations that may fail
|
|
25
|
+
due to transient errors, with configurable backoff strategies.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import asyncio
|
|
29
|
+
import random
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from typing import Any, Callable, List, Optional, Type, TypeVar
|
|
32
|
+
|
|
33
|
+
from ..errors import (
|
|
34
|
+
RateLimitError,
|
|
35
|
+
ServiceUnavailableError,
|
|
36
|
+
BadGatewayError,
|
|
37
|
+
TimeoutError,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# Type variable for the return type of the retried function
|
|
41
|
+
T = TypeVar("T")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class RetryConfig:
|
|
46
|
+
"""Configuration for the retry mechanism."""
|
|
47
|
+
|
|
48
|
+
max_retries: int = 3 # Maximum number of retry attempts
|
|
49
|
+
initial_backoff: float = 0.5 # Initial backoff time in seconds
|
|
50
|
+
max_backoff: float = 60.0 # Maximum backoff time in seconds
|
|
51
|
+
backoff_multiplier: float = 2.0 # Factor by which backoff increases with each retry
|
|
52
|
+
jitter: bool = True # Whether to add randomness to backoff times
|
|
53
|
+
retryable_errors: Optional[List[Type[Exception]]] = None # Exceptions that should trigger retry
|
|
54
|
+
|
|
55
|
+
def __post_init__(self):
|
|
56
|
+
"""
|
|
57
|
+
Initialize default retryable errors if none are provided.
|
|
58
|
+
|
|
59
|
+
This method runs after the dataclass is initialized and sets up
|
|
60
|
+
the default list of exceptions that should trigger a retry.
|
|
61
|
+
"""
|
|
62
|
+
if self.retryable_errors is None:
|
|
63
|
+
# Default set of errors that are considered transient and worth retrying
|
|
64
|
+
self.retryable_errors = [
|
|
65
|
+
RateLimitError, # Server rate limit exceeded
|
|
66
|
+
ServiceUnavailableError, # Service temporarily unavailable
|
|
67
|
+
BadGatewayError, # Bad gateway response
|
|
68
|
+
TimeoutError, # Request timed out
|
|
69
|
+
ConnectionError, # Connection issues
|
|
70
|
+
asyncio.TimeoutError, # Async operation timed out
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _should_retry(error: Exception, config: RetryConfig) -> bool:
|
|
75
|
+
"""
|
|
76
|
+
Determine if a retry should be attempted based on the error.
|
|
77
|
+
|
|
78
|
+
This function checks if the given error is of a type that should trigger
|
|
79
|
+
a retry according to the configuration.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
error: The exception that was raised
|
|
83
|
+
config: Retry configuration
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
True if the error is retryable, False otherwise
|
|
87
|
+
"""
|
|
88
|
+
if config.retryable_errors:
|
|
89
|
+
# Check if the error is an instance of any of the retryable error types
|
|
90
|
+
return any(isinstance(error, err_type) for err_type in config.retryable_errors)
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _calculate_backoff(attempt: int, config: RetryConfig) -> float:
|
|
95
|
+
"""
|
|
96
|
+
Calculate the backoff time for a retry attempt.
|
|
97
|
+
|
|
98
|
+
This implements an exponential backoff strategy with optional jitter.
|
|
99
|
+
The backoff time increases exponentially with each retry attempt but
|
|
100
|
+
is capped at a maximum value.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
attempt: The current attempt number (1-based)
|
|
104
|
+
config: Retry configuration
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
Backoff time in seconds
|
|
108
|
+
"""
|
|
109
|
+
# Calculate exponential backoff: initial_backoff * (multiplier ^ (attempt-1))
|
|
110
|
+
# but cap it at max_backoff
|
|
111
|
+
backoff = min(
|
|
112
|
+
config.max_backoff,
|
|
113
|
+
config.initial_backoff * (config.backoff_multiplier ** (attempt - 1)),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
if config.jitter:
|
|
117
|
+
# Add jitter to prevent thundering herd problem
|
|
118
|
+
# Multiply by a random factor between 0.5 and 1.5
|
|
119
|
+
backoff = backoff * (0.5 + random.random())
|
|
120
|
+
|
|
121
|
+
return backoff
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def retry_async(
|
|
125
|
+
func: Callable[..., Any],
|
|
126
|
+
*args: Any,
|
|
127
|
+
config: Optional[RetryConfig] = None,
|
|
128
|
+
**kwargs: Any
|
|
129
|
+
) -> Any:
|
|
130
|
+
"""
|
|
131
|
+
Retry an async function with exponential backoff.
|
|
132
|
+
|
|
133
|
+
This function will call the provided async function and retry it
|
|
134
|
+
if it fails with a retryable error, using an exponential backoff
|
|
135
|
+
strategy between retries.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
func: Async function to call
|
|
139
|
+
*args: Positional arguments to pass to func
|
|
140
|
+
config: Retry configuration
|
|
141
|
+
**kwargs: Keyword arguments to pass to func
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
The return value of the function
|
|
145
|
+
|
|
146
|
+
Raises:
|
|
147
|
+
Exception: The last exception raised by the function if all retries fail
|
|
148
|
+
"""
|
|
149
|
+
# Use default config if none provided
|
|
150
|
+
config = config or RetryConfig()
|
|
151
|
+
last_error = None
|
|
152
|
+
|
|
153
|
+
# +2 because attempt starts at 1 and we want max_retries + 1 total attempts
|
|
154
|
+
# (original attempt plus max_retries retry attempts)
|
|
155
|
+
for attempt in range(1, config.max_retries + 2):
|
|
156
|
+
try:
|
|
157
|
+
# Attempt to call the function
|
|
158
|
+
return await func(*args, **kwargs)
|
|
159
|
+
except Exception as e:
|
|
160
|
+
last_error = e
|
|
161
|
+
|
|
162
|
+
# Determine if we should retry or re-raise the error
|
|
163
|
+
if attempt > config.max_retries or not _should_retry(e, config):
|
|
164
|
+
# Re-raise the error if we've exhausted retries or if it's not retryable
|
|
165
|
+
raise
|
|
166
|
+
|
|
167
|
+
# Calculate backoff time for this attempt
|
|
168
|
+
backoff = _calculate_backoff(attempt, config)
|
|
169
|
+
|
|
170
|
+
# Wait before the next attempt
|
|
171
|
+
await asyncio.sleep(backoff)
|
|
172
|
+
|
|
173
|
+
# This should never be reached due to the re-raise above, but keeping for safety
|
|
174
|
+
assert last_error is not None
|
|
175
|
+
raise last_error
|
|
@@ -0,0 +1,357 @@
|
|
|
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
|
+
Improved utilities for handling streaming responses from LLM providers.
|
|
23
|
+
|
|
24
|
+
This module fixes the streaming utilities to properly handle async transform functions.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import json
|
|
29
|
+
import inspect
|
|
30
|
+
from typing import Any, AsyncGenerator, Callable, Optional, TypeVar, Union
|
|
31
|
+
|
|
32
|
+
from ..errors import MuxiLLMError
|
|
33
|
+
|
|
34
|
+
# Type variable for stream item
|
|
35
|
+
T = TypeVar("T")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class StreamingError(MuxiLLMError):
|
|
39
|
+
"""Error during streaming operation."""
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def stream_generator(
|
|
44
|
+
source_generator: AsyncGenerator[Any, None],
|
|
45
|
+
transform_func: Optional[Callable[[Any], T]] = None,
|
|
46
|
+
timeout: Optional[float] = None,
|
|
47
|
+
) -> AsyncGenerator[T, None]:
|
|
48
|
+
"""
|
|
49
|
+
Create a transformed stream from a source generator.
|
|
50
|
+
|
|
51
|
+
This function takes an async generator and applies an optional transformation
|
|
52
|
+
function to each item. It handles both synchronous and asynchronous transform
|
|
53
|
+
functions and can apply an optional timeout to each item retrieval.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
source_generator: The source async generator that produces items
|
|
57
|
+
transform_func: Optional function to transform each item (can be sync or async)
|
|
58
|
+
timeout: Optional timeout in seconds for retrieving each item
|
|
59
|
+
|
|
60
|
+
Yields:
|
|
61
|
+
Transformed items from the source generator
|
|
62
|
+
|
|
63
|
+
Raises:
|
|
64
|
+
StreamingError: If an error occurs during streaming or transformation
|
|
65
|
+
"""
|
|
66
|
+
try:
|
|
67
|
+
# Handle case where source_generator is actually a coroutine (happens in tests with mocks)
|
|
68
|
+
# This ensures we're working with an actual generator
|
|
69
|
+
if inspect.iscoroutine(source_generator):
|
|
70
|
+
source_generator = await source_generator
|
|
71
|
+
|
|
72
|
+
if timeout is not None:
|
|
73
|
+
# Use the timeout implementation if a timeout is specified
|
|
74
|
+
async for item in _stream_with_timeout(source_generator, transform_func, timeout):
|
|
75
|
+
yield item
|
|
76
|
+
else:
|
|
77
|
+
# Standard implementation without timeout
|
|
78
|
+
async for item in source_generator:
|
|
79
|
+
if transform_func:
|
|
80
|
+
try:
|
|
81
|
+
# Call the transform function on the item
|
|
82
|
+
transformed = transform_func(item)
|
|
83
|
+
|
|
84
|
+
# Check if the transform function returned a coroutine
|
|
85
|
+
# This allows both sync and async transform functions
|
|
86
|
+
if inspect.iscoroutine(transformed):
|
|
87
|
+
# Await the coroutine to get the actual result
|
|
88
|
+
transformed = await transformed
|
|
89
|
+
|
|
90
|
+
# Only yield non-None values
|
|
91
|
+
if transformed is not None:
|
|
92
|
+
yield transformed
|
|
93
|
+
except Exception as e:
|
|
94
|
+
# Preserve StreamingError instances
|
|
95
|
+
if isinstance(e, StreamingError):
|
|
96
|
+
raise
|
|
97
|
+
# Wrap other exceptions in StreamingError for consistent error handling
|
|
98
|
+
raise StreamingError(
|
|
99
|
+
f"Error transforming streaming response: {str(e)}"
|
|
100
|
+
) from e
|
|
101
|
+
else:
|
|
102
|
+
# If no transform function, yield the item directly
|
|
103
|
+
yield item # type: ignore
|
|
104
|
+
except asyncio.TimeoutError:
|
|
105
|
+
# Handle timeout errors with a specific message
|
|
106
|
+
raise StreamingError(f"Streaming response timed out after {timeout} seconds")
|
|
107
|
+
except Exception as e:
|
|
108
|
+
# Preserve StreamingError instances
|
|
109
|
+
if isinstance(e, StreamingError):
|
|
110
|
+
raise
|
|
111
|
+
# Wrap other exceptions in StreamingError for consistent error handling
|
|
112
|
+
raise StreamingError(f"Error in streaming response: {str(e)}") from e
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
async def _stream_with_timeout(
|
|
116
|
+
source_generator: AsyncGenerator[Any, None],
|
|
117
|
+
transform_func: Optional[Callable[[Any], T]],
|
|
118
|
+
timeout: float,
|
|
119
|
+
) -> AsyncGenerator[T, None]:
|
|
120
|
+
"""
|
|
121
|
+
Helper function to implement streaming with timeout.
|
|
122
|
+
|
|
123
|
+
This function applies a timeout to each item retrieval from the source generator
|
|
124
|
+
and applies the transform function if provided.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
source_generator: The source async generator
|
|
128
|
+
transform_func: Optional function to transform each item
|
|
129
|
+
timeout: Timeout in seconds for retrieving each item
|
|
130
|
+
|
|
131
|
+
Yields:
|
|
132
|
+
Transformed items from the source generator
|
|
133
|
+
|
|
134
|
+
Raises:
|
|
135
|
+
StreamingError: If an error occurs during streaming or transformation
|
|
136
|
+
asyncio.TimeoutError: If retrieving an item times out
|
|
137
|
+
"""
|
|
138
|
+
try:
|
|
139
|
+
while True:
|
|
140
|
+
try:
|
|
141
|
+
# Get next item with timeout
|
|
142
|
+
# This wraps the generator's __anext__ call with a timeout
|
|
143
|
+
get_next = source_generator.__anext__()
|
|
144
|
+
item = await asyncio.wait_for(get_next, timeout)
|
|
145
|
+
|
|
146
|
+
if transform_func:
|
|
147
|
+
try:
|
|
148
|
+
# Apply the transform function to the item
|
|
149
|
+
transformed = transform_func(item)
|
|
150
|
+
|
|
151
|
+
# Handle async transform functions
|
|
152
|
+
if inspect.iscoroutine(transformed):
|
|
153
|
+
# Await the coroutine to get the actual result
|
|
154
|
+
transformed = await transformed
|
|
155
|
+
|
|
156
|
+
# Only yield non-None values
|
|
157
|
+
if transformed is not None:
|
|
158
|
+
yield transformed
|
|
159
|
+
except Exception as e:
|
|
160
|
+
# Preserve StreamingError instances
|
|
161
|
+
if isinstance(e, StreamingError):
|
|
162
|
+
raise
|
|
163
|
+
# Wrap other exceptions in StreamingError
|
|
164
|
+
raise StreamingError(
|
|
165
|
+
f"Error transforming streaming response: {str(e)}"
|
|
166
|
+
) from e
|
|
167
|
+
else:
|
|
168
|
+
# If no transform function, yield the item directly
|
|
169
|
+
yield item # type: ignore
|
|
170
|
+
except StopAsyncIteration:
|
|
171
|
+
# End of generator reached
|
|
172
|
+
break
|
|
173
|
+
except asyncio.TimeoutError:
|
|
174
|
+
# Handle timeout errors with a specific message
|
|
175
|
+
raise StreamingError(f"Streaming response timed out after {timeout} seconds")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def json_stream_generator(
|
|
179
|
+
source_generator: AsyncGenerator[str, None],
|
|
180
|
+
data_key: Optional[str] = None,
|
|
181
|
+
timeout: Optional[float] = None,
|
|
182
|
+
) -> AsyncGenerator[Any, None]:
|
|
183
|
+
"""
|
|
184
|
+
Create a JSON stream from a source generator of JSON strings.
|
|
185
|
+
|
|
186
|
+
This function parses JSON strings from the source generator and optionally
|
|
187
|
+
extracts a specific key from each parsed JSON object.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
source_generator: The source async generator yielding JSON strings
|
|
191
|
+
data_key: Optional key to extract from each JSON object
|
|
192
|
+
timeout: Optional timeout in seconds for retrieving each item
|
|
193
|
+
|
|
194
|
+
Yields:
|
|
195
|
+
Parsed JSON objects or extracted values from the source generator
|
|
196
|
+
|
|
197
|
+
Raises:
|
|
198
|
+
StreamingError: If an error occurs during streaming or JSON parsing
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
async def transform_json(text: str) -> Optional[Any]:
|
|
202
|
+
"""
|
|
203
|
+
Inner function to parse JSON and extract data.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
text: JSON string to parse
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
Parsed JSON object or extracted value, None for empty strings
|
|
210
|
+
|
|
211
|
+
Raises:
|
|
212
|
+
StreamingError: If JSON parsing fails
|
|
213
|
+
"""
|
|
214
|
+
# Skip empty strings
|
|
215
|
+
if not text.strip():
|
|
216
|
+
return None
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
# Parse the JSON string
|
|
220
|
+
data = json.loads(text)
|
|
221
|
+
if data_key and isinstance(data, dict):
|
|
222
|
+
# Return None if data_key doesn't exist in the dict
|
|
223
|
+
if data_key not in data:
|
|
224
|
+
return None
|
|
225
|
+
# Extract the specified key
|
|
226
|
+
return data.get(data_key)
|
|
227
|
+
# Return the full parsed object if no key specified
|
|
228
|
+
return data
|
|
229
|
+
except json.JSONDecodeError as e:
|
|
230
|
+
# Create a new StreamingError with the JSONDecodeError as cause
|
|
231
|
+
error = StreamingError(f"Invalid JSON in streaming response: {text}")
|
|
232
|
+
error.__cause__ = e
|
|
233
|
+
raise error
|
|
234
|
+
|
|
235
|
+
try:
|
|
236
|
+
# Get the generator from stream_generator with the JSON transform function
|
|
237
|
+
generator = stream_generator(
|
|
238
|
+
source_generator, transform_func=transform_json, timeout=timeout
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
# If it's a coroutine, await it to get the actual generator
|
|
242
|
+
if inspect.iscoroutine(generator):
|
|
243
|
+
generator = await generator
|
|
244
|
+
|
|
245
|
+
# Iterate through the generator and yield non-None items
|
|
246
|
+
async for item in generator:
|
|
247
|
+
if item is not None:
|
|
248
|
+
yield item
|
|
249
|
+
except Exception as e:
|
|
250
|
+
# Preserve StreamingError instances
|
|
251
|
+
if isinstance(e, StreamingError):
|
|
252
|
+
raise
|
|
253
|
+
# Wrap other exceptions in StreamingError
|
|
254
|
+
raise StreamingError(f"Error in JSON streaming: {str(e)}") from e
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
async def line_stream_generator(
|
|
258
|
+
source_generator: AsyncGenerator[Union[str, bytes], None],
|
|
259
|
+
prefix: Optional[str] = None,
|
|
260
|
+
timeout: Optional[float] = None,
|
|
261
|
+
transform_func: Optional[Callable[[str], str]] = None,
|
|
262
|
+
) -> AsyncGenerator[str, None]:
|
|
263
|
+
"""
|
|
264
|
+
Create a line stream from a source generator, optionally filtering by prefix.
|
|
265
|
+
|
|
266
|
+
This function processes lines from the source generator, optionally filtering
|
|
267
|
+
by a prefix and applying a transformation function.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
source_generator: The source async generator yielding strings or bytes
|
|
271
|
+
prefix: Optional prefix to filter lines (only lines starting with this prefix are yielded)
|
|
272
|
+
timeout: Optional timeout in seconds for retrieving each item
|
|
273
|
+
transform_func: Optional function to transform each line after processing
|
|
274
|
+
|
|
275
|
+
Yields:
|
|
276
|
+
Lines from the source generator, with the prefix removed if specified
|
|
277
|
+
|
|
278
|
+
Raises:
|
|
279
|
+
StreamingError: If an error occurs during streaming or line processing
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
async def process_line(line: Union[str, bytes]) -> Optional[str]:
|
|
283
|
+
"""
|
|
284
|
+
Inner function to process each line from the source generator.
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
line: Line to process (string or bytes)
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
Processed line or None if line should be skipped
|
|
291
|
+
|
|
292
|
+
Raises:
|
|
293
|
+
StreamingError: If line processing fails
|
|
294
|
+
"""
|
|
295
|
+
try:
|
|
296
|
+
# Convert bytes to string if needed
|
|
297
|
+
if isinstance(line, bytes):
|
|
298
|
+
try:
|
|
299
|
+
line = line.decode("utf-8")
|
|
300
|
+
except UnicodeDecodeError as e:
|
|
301
|
+
error = StreamingError("Error decoding bytes in streaming response")
|
|
302
|
+
error.__cause__ = e
|
|
303
|
+
raise error
|
|
304
|
+
|
|
305
|
+
# Remove trailing newlines
|
|
306
|
+
line = line.rstrip("\r\n")
|
|
307
|
+
# Skip empty lines
|
|
308
|
+
if not line.strip(): # Check if the line is empty or contains only whitespace
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
if prefix:
|
|
312
|
+
# If prefix is specified, only process lines starting with that prefix
|
|
313
|
+
if line.startswith(prefix):
|
|
314
|
+
# Remove the prefix from the line
|
|
315
|
+
result = line[len(prefix):]
|
|
316
|
+
# Apply transform function if provided
|
|
317
|
+
if transform_func and result is not None:
|
|
318
|
+
return transform_func(result)
|
|
319
|
+
return result
|
|
320
|
+
# Skip lines that don't start with the prefix
|
|
321
|
+
return None
|
|
322
|
+
|
|
323
|
+
# Apply transform function if provided
|
|
324
|
+
if transform_func and line:
|
|
325
|
+
return transform_func(line)
|
|
326
|
+
# Return the line as is
|
|
327
|
+
return line
|
|
328
|
+
except UnicodeDecodeError as e:
|
|
329
|
+
# Handle decoding errors
|
|
330
|
+
raise StreamingError(f"Error decoding line in streaming response: {str(e)}") from e
|
|
331
|
+
except Exception as e:
|
|
332
|
+
# Preserve StreamingError instances
|
|
333
|
+
if isinstance(e, StreamingError):
|
|
334
|
+
raise
|
|
335
|
+
# Wrap other exceptions in StreamingError
|
|
336
|
+
raise StreamingError(f"Error processing line in streaming response: {str(e)}") from e
|
|
337
|
+
|
|
338
|
+
try:
|
|
339
|
+
# Get the generator from stream_generator with the line processing function
|
|
340
|
+
generator = stream_generator(
|
|
341
|
+
source_generator, transform_func=process_line, timeout=timeout
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
# If it's a coroutine, await it to get the actual generator
|
|
345
|
+
if inspect.iscoroutine(generator):
|
|
346
|
+
generator = await generator
|
|
347
|
+
|
|
348
|
+
# Iterate through the generator and yield non-None items
|
|
349
|
+
async for item in generator:
|
|
350
|
+
if item is not None:
|
|
351
|
+
yield item
|
|
352
|
+
except Exception as e:
|
|
353
|
+
# Preserve StreamingError instances
|
|
354
|
+
if isinstance(e, StreamingError):
|
|
355
|
+
raise
|
|
356
|
+
# Wrap other exceptions in StreamingError
|
|
357
|
+
raise StreamingError(f"Error in line streaming: {str(e)}") from e
|