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/completion.py ADDED
@@ -0,0 +1,199 @@
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 completion functionality for OneLLM.
23
+
24
+ This module provides a Completion class that can be used to create text
25
+ completions from various providers in a manner compatible with OpenAI's API.
26
+ """
27
+
28
+ import asyncio
29
+ from typing import Any, AsyncGenerator, List, Optional, Union
30
+
31
+ from .providers.base import get_provider_with_fallbacks
32
+ from .models import CompletionResponse
33
+ from .utils.fallback import FallbackConfig
34
+
35
+
36
+ class Completion:
37
+ """Class for creating text completions with various providers."""
38
+
39
+ @classmethod
40
+ def create(
41
+ cls,
42
+ model: str,
43
+ prompt: str,
44
+ stream: bool = False,
45
+ fallback_models: Optional[List[str]] = None,
46
+ fallback_config: Optional[dict] = None,
47
+ retries: int = 0,
48
+ **kwargs
49
+ ) -> Union[CompletionResponse, AsyncGenerator[Any, None]]:
50
+ """
51
+ Create a text completion.
52
+
53
+ This method provides a synchronous interface for text completion requests.
54
+ It handles model fallbacks and retries if the primary model fails.
55
+
56
+ Args:
57
+ model: Model name with provider prefix (e.g., 'openai/text-davinci-003')
58
+ prompt: Text prompt to complete
59
+ stream: Whether to stream the response
60
+ fallback_models: Optional list of models to try if the primary model fails
61
+ fallback_config: Optional configuration for fallback behavior
62
+ retries: Number of times to retry the primary model before falling back (default: 0)
63
+ **kwargs: Additional model parameters
64
+
65
+ Returns:
66
+ CompletionResponse or a streaming generator
67
+
68
+ Raises:
69
+ ValueError: If prompt is empty
70
+
71
+ Example:
72
+ >>> response = Completion.create(
73
+ ... model="openai/text-davinci-003",
74
+ ... prompt="Once upon a time",
75
+ ... max_tokens=50,
76
+ ... fallback_models=["anthropic/claude-instant-1", "openai/gpt-3.5-turbo-instruct"]
77
+ ... )
78
+ >>> print(response.choices[0].text)
79
+ """
80
+ # Validate prompt
81
+ if not prompt or not prompt.strip():
82
+ raise ValueError("Prompt cannot be empty")
83
+
84
+ # Process fallback configuration
85
+ fb_config = None
86
+ if fallback_config:
87
+ fb_config = FallbackConfig(**fallback_config)
88
+
89
+ # Add retries by prepending the primary model to fallback_models
90
+ # This effectively tries the primary model multiple times before moving to fallbacks
91
+ effective_fallback_models = fallback_models
92
+ if retries > 0:
93
+ if effective_fallback_models is None:
94
+ # If no fallback models were provided, create a list with the primary model repeated
95
+ effective_fallback_models = [model] * retries
96
+ else:
97
+ # Prepend retries of the primary model to the fallback models list
98
+ effective_fallback_models = [model] * retries + effective_fallback_models
99
+
100
+ # Get provider with fallbacks or a regular provider
101
+ # This returns both the provider instance and the specific model name to use
102
+ provider, model_name = get_provider_with_fallbacks(
103
+ primary_model=model,
104
+ fallback_models=effective_fallback_models,
105
+ fallback_config=fb_config,
106
+ )
107
+
108
+ # Call the provider's method synchronously
109
+ if stream:
110
+ # For streaming, we need to use async properly
111
+ # Create a new event loop to run the async code in a synchronous context
112
+ loop = asyncio.new_event_loop()
113
+ asyncio.set_event_loop(loop)
114
+ return loop.run_until_complete(
115
+ provider.create_completion(
116
+ prompt=prompt, model=model_name, stream=stream, **kwargs
117
+ )
118
+ )
119
+ else:
120
+ # For non-streaming, we can just run and get the result
121
+ # asyncio.run creates a new event loop, runs the coroutine, and closes the loop
122
+ return asyncio.run(
123
+ provider.create_completion(
124
+ prompt=prompt, model=model_name, stream=stream, **kwargs
125
+ )
126
+ )
127
+
128
+ @classmethod
129
+ async def acreate(
130
+ cls,
131
+ model: str,
132
+ prompt: str,
133
+ stream: bool = False,
134
+ fallback_models: Optional[List[str]] = None,
135
+ fallback_config: Optional[dict] = None,
136
+ retries: int = 0,
137
+ **kwargs
138
+ ) -> Union[CompletionResponse, AsyncGenerator[Any, None]]:
139
+ """
140
+ Create a text completion asynchronously.
141
+
142
+ This method provides an asynchronous interface for text completion requests.
143
+ It's designed to be used with async/await syntax in asynchronous code.
144
+ Like the synchronous version, it handles model fallbacks and retries.
145
+
146
+ Args:
147
+ model: Model name with provider prefix (e.g., 'openai/text-davinci-003')
148
+ prompt: Text prompt to complete
149
+ stream: Whether to stream the response
150
+ fallback_models: Optional list of models to try if the primary model fails
151
+ fallback_config: Optional configuration for fallback behavior
152
+ retries: Number of times to retry the primary model before falling back (default: 0)
153
+ **kwargs: Additional model parameters
154
+
155
+ Returns:
156
+ CompletionResponse or a streaming generator
157
+
158
+ Raises:
159
+ ValueError: If prompt is empty
160
+
161
+ Example:
162
+ >>> response = await Completion.acreate(
163
+ ... model="openai/text-davinci-003",
164
+ ... prompt="Once upon a time",
165
+ ... max_tokens=50,
166
+ ... fallback_models=["anthropic/claude-instant-1", "openai/gpt-3.5-turbo-instruct"]
167
+ ... )
168
+ >>> print(response.choices[0].text)
169
+ """
170
+ # Validate prompt
171
+ if not prompt or not prompt.strip():
172
+ raise ValueError("Prompt cannot be empty")
173
+
174
+ # Process fallback configuration
175
+ fb_config = None
176
+ if fallback_config:
177
+ fb_config = FallbackConfig(**fallback_config)
178
+
179
+ # Add retries by prepending the primary model to fallback_models
180
+ # This works the same way as in the synchronous version
181
+ effective_fallback_models = fallback_models
182
+ if retries > 0:
183
+ if effective_fallback_models is None:
184
+ effective_fallback_models = [model] * retries
185
+ else:
186
+ effective_fallback_models = [model] * retries + effective_fallback_models
187
+
188
+ # Get provider with fallbacks or a regular provider
189
+ provider, model_name = get_provider_with_fallbacks(
190
+ primary_model=model,
191
+ fallback_models=effective_fallback_models,
192
+ fallback_config=fb_config,
193
+ )
194
+
195
+ # Call the provider's method asynchronously
196
+ # Since this method is already async, we can directly await the result
197
+ return await provider.create_completion(
198
+ prompt=prompt, model=model_name, stream=stream, **kwargs
199
+ )
onellm/config.py ADDED
@@ -0,0 +1,191 @@
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
+ Configuration system for OneLLM.
23
+
24
+ This module handles configuration from environment variables and runtime settings.
25
+ It provides a centralized way to manage API keys, endpoints, and other settings
26
+ for various LLM providers.
27
+ """
28
+
29
+ import os
30
+ from typing import Any, Dict, Optional
31
+
32
+ # Default configuration
33
+ DEFAULT_CONFIG = {
34
+ "providers": {
35
+ "openai": {
36
+ "api_key": None,
37
+ "api_base": "https://api.openai.com/v1",
38
+ "organization_id": None,
39
+ "timeout": 60,
40
+ "max_retries": 3,
41
+ },
42
+ "anthropic": {
43
+ "api_key": None,
44
+ "api_base": "https://api.anthropic.com",
45
+ "timeout": 60,
46
+ "max_retries": 3,
47
+ },
48
+ # Other providers will be added in future phases
49
+ },
50
+ "logging": {
51
+ "level": "INFO",
52
+ "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
53
+ },
54
+ }
55
+
56
+ # Global configuration dictionary that will be populated with settings
57
+ config = DEFAULT_CONFIG.copy()
58
+
59
+ # Environment variables prefixes
60
+ ENV_PREFIX = "MUXI_LLM_" # Prefix for OneLLM specific environment variables
61
+ PROVIDER_API_KEY_ENV_MAP = {
62
+ "openai": "OPENAI_API_KEY",
63
+ "anthropic": "ANTHROPIC_API_KEY",
64
+ }
65
+
66
+
67
+ def _load_env_vars() -> None:
68
+ """
69
+ Load configuration from environment variables.
70
+
71
+ This function checks for two types of environment variables:
72
+ 1. Variables with MUXI_LLM_ prefix for general configuration
73
+ 2. Provider-specific API keys using their standard environment variable names
74
+
75
+ Environment variables with double underscores (__) are treated as nested configuration.
76
+ Example: MUXI_LLM_PROVIDERS__OPENAI__TIMEOUT would set config["providers"]["openai"]["timeout"].
77
+ """
78
+ # General configuration
79
+ for key in os.environ:
80
+ if key.startswith(ENV_PREFIX):
81
+ # Extract the config key by removing the prefix
82
+ config_key = key[len(ENV_PREFIX):].lower()
83
+
84
+ # Handle nested configuration with double underscores
85
+ if "__" in config_key:
86
+ section, option = config_key.split("__", 1)
87
+ if section in config and option in config[section]:
88
+ config[section][option] = os.environ[key]
89
+ else:
90
+ if config_key in config:
91
+ config[config_key] = os.environ[key]
92
+
93
+ # Provider API keys (support both prefixed and provider-standard environment variables)
94
+ # This allows users to use either OPENAI_API_KEY or MUXI_LLM_PROVIDERS__OPENAI__API_KEY
95
+ for provider, env_var in PROVIDER_API_KEY_ENV_MAP.items():
96
+ if env_var in os.environ and provider in config["providers"]:
97
+ config["providers"][provider]["api_key"] = os.environ[env_var]
98
+
99
+
100
+ def _update_nested_dict(d: Dict[str, Any], u: Dict[str, Any]) -> Dict[str, Any]:
101
+ """
102
+ Update a nested dictionary with values from another dictionary.
103
+
104
+ This is a recursive function that merges nested dictionaries rather than
105
+ replacing them entirely. It's used to update configuration while preserving
106
+ the structure.
107
+
108
+ Args:
109
+ d: The target dictionary to update
110
+ u: The source dictionary with new values
111
+
112
+ Returns:
113
+ The updated dictionary with merged values
114
+ """
115
+ for k, v in u.items():
116
+ if isinstance(v, dict) and k in d and isinstance(d[k], dict):
117
+ _update_nested_dict(d[k], v)
118
+ else:
119
+ d[k] = v
120
+ return d
121
+
122
+
123
+ # Load configuration from environment variables on module import
124
+ _load_env_vars()
125
+
126
+
127
+ # Public API for configuration
128
+ def get_api_key(provider: str) -> Optional[str]:
129
+ """
130
+ Get the API key for the specified provider.
131
+
132
+ Args:
133
+ provider: The provider name (e.g., "openai", "anthropic")
134
+
135
+ Returns:
136
+ The API key as a string if found, None otherwise
137
+ """
138
+ if provider in config["providers"]:
139
+ return config["providers"][provider]["api_key"]
140
+ return None
141
+
142
+
143
+ def set_api_key(api_key: str, provider: str) -> None:
144
+ """
145
+ Set the API key for the specified provider.
146
+
147
+ This function updates both the config dictionary and creates a global
148
+ variable for convenient access to the API key.
149
+
150
+ Args:
151
+ api_key: The API key to set
152
+ provider: The provider to set the key for (e.g., "openai", "anthropic")
153
+ """
154
+ if provider in config["providers"]:
155
+ config["providers"][provider]["api_key"] = api_key
156
+ # Set global variable for convenience and backward compatibility
157
+ globals()[f"{provider}_api_key"] = api_key
158
+
159
+
160
+ def get_provider_config(provider: str) -> Dict[str, Any]:
161
+ """
162
+ Get the configuration for the specified provider.
163
+
164
+ Args:
165
+ provider: The provider name (e.g., "openai", "anthropic")
166
+
167
+ Returns:
168
+ A dictionary containing the provider's configuration settings,
169
+ or an empty dictionary if the provider is not found
170
+ """
171
+ if provider in config["providers"]:
172
+ return config["providers"][provider]
173
+ return {}
174
+
175
+
176
+ def update_provider_config(provider: str, **kwargs) -> None:
177
+ """
178
+ Update the configuration for the specified provider.
179
+
180
+ Args:
181
+ provider: The provider name to update (e.g., "openai", "anthropic")
182
+ **kwargs: Key-value pairs of configuration settings to update
183
+ """
184
+ if provider in config["providers"]:
185
+ config["providers"][provider].update(kwargs)
186
+
187
+
188
+ # Initialize global variables for all providers for easy access
189
+ # This creates variables like openai_api_key, anthropic_api_key, etc.
190
+ for provider in config["providers"]:
191
+ globals()[f"{provider}_api_key"] = get_api_key(provider)
onellm/embedding.py ADDED
@@ -0,0 +1,170 @@
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
+ Embedding functionality for OneLLM.
23
+
24
+ This module provides an Embedding class that can be used to create embeddings
25
+ from various providers in a manner compatible with OpenAI's API.
26
+ """
27
+
28
+ import asyncio
29
+ from typing import List, Optional, Union
30
+
31
+ from .providers.base import get_provider_with_fallbacks
32
+ from .models import EmbeddingResponse
33
+ from .utils.fallback import FallbackConfig
34
+ from .errors import InvalidRequestError
35
+
36
+
37
+ def validate_embedding_input(input_data: Union[str, List[str]]) -> None:
38
+ """
39
+ Validate the input for embedding.
40
+
41
+ This function checks if the input data is valid for embedding generation.
42
+ It ensures that the input is not empty, and if it's a list, that it contains
43
+ at least one non-empty string.
44
+
45
+ Args:
46
+ input_data: Text or list of texts to validate
47
+
48
+ Raises:
49
+ InvalidRequestError: If the input is empty or invalid
50
+ """
51
+ # Check if input is completely empty
52
+ if not input_data:
53
+ raise InvalidRequestError("Input cannot be empty")
54
+
55
+ # If input is a list, check that it's not empty and contains at least one non-empty string
56
+ if isinstance(input_data, list):
57
+ if not input_data or all(not text for text in input_data):
58
+ raise InvalidRequestError("Input cannot be empty")
59
+
60
+
61
+ class Embedding:
62
+ """Class for creating embeddings with various providers."""
63
+
64
+ @classmethod
65
+ def create(
66
+ cls,
67
+ model: str,
68
+ input: Union[str, List[str]],
69
+ fallback_models: Optional[List[str]] = None,
70
+ fallback_config: Optional[dict] = None,
71
+ **kwargs
72
+ ) -> EmbeddingResponse:
73
+ """
74
+ Create embeddings for the provided input.
75
+
76
+ This method provides a synchronous interface for embedding generation.
77
+ It handles model fallbacks if the primary model fails.
78
+
79
+ Args:
80
+ model: Model name with provider prefix (e.g., 'openai/text-embedding-ada-002')
81
+ input: Text or list of texts to embed
82
+ fallback_models: Optional list of models to try if the primary model fails
83
+ fallback_config: Optional configuration for fallback behavior
84
+ **kwargs: Additional model parameters
85
+
86
+ Returns:
87
+ EmbeddingResponse containing the generated embeddings
88
+
89
+ Example:
90
+ >>> response = Embedding.create(
91
+ ... model="openai/text-embedding-ada-002",
92
+ ... input="Hello, world!",
93
+ ... fallback_models=["openai/text-embedding-3-small"]
94
+ ... )
95
+ >>> print(len(response.data[0].embedding))
96
+ """
97
+ # Validate input before proceeding
98
+ validate_embedding_input(input)
99
+
100
+ # Process fallback configuration
101
+ fb_config = None
102
+ if fallback_config:
103
+ # Convert dictionary to FallbackConfig object
104
+ fb_config = FallbackConfig(**fallback_config)
105
+
106
+ # Get provider with fallbacks or a regular provider
107
+ # This returns both the provider instance and the specific model name to use
108
+ provider, model_name = get_provider_with_fallbacks(
109
+ primary_model=model,
110
+ fallback_models=fallback_models,
111
+ fallback_config=fb_config,
112
+ )
113
+
114
+ # Call the provider's method synchronously by running the async method in an event loop
115
+ return asyncio.run(
116
+ provider.create_embedding(input=input, model=model_name, **kwargs)
117
+ )
118
+
119
+ @classmethod
120
+ async def acreate(
121
+ cls,
122
+ model: str,
123
+ input: Union[str, List[str]],
124
+ fallback_models: Optional[List[str]] = None,
125
+ fallback_config: Optional[dict] = None,
126
+ **kwargs
127
+ ) -> EmbeddingResponse:
128
+ """
129
+ Create embeddings for the provided input asynchronously.
130
+
131
+ This method provides an asynchronous interface for embedding generation.
132
+ It's useful when working within an async context to avoid blocking the event loop.
133
+
134
+ Args:
135
+ model: Model name with provider prefix (e.g., 'openai/text-embedding-ada-002')
136
+ input: Text or list of texts to embed
137
+ fallback_models: Optional list of models to try if the primary model fails
138
+ fallback_config: Optional configuration for fallback behavior
139
+ **kwargs: Additional model parameters
140
+
141
+ Returns:
142
+ EmbeddingResponse containing the generated embeddings
143
+
144
+ Example:
145
+ >>> response = await Embedding.acreate(
146
+ ... model="openai/text-embedding-ada-002",
147
+ ... input="Hello, world!",
148
+ ... fallback_models=["openai/text-embedding-3-small"]
149
+ ... )
150
+ >>> print(len(response.data[0].embedding))
151
+ """
152
+ # Validate input before proceeding
153
+ validate_embedding_input(input)
154
+
155
+ # Process fallback configuration
156
+ fb_config = None
157
+ if fallback_config:
158
+ # Convert dictionary to FallbackConfig object
159
+ fb_config = FallbackConfig(**fallback_config)
160
+
161
+ # Get provider with fallbacks or a regular provider
162
+ # This returns both the provider instance and the specific model name to use
163
+ provider, model_name = get_provider_with_fallbacks(
164
+ primary_model=model,
165
+ fallback_models=fallback_models,
166
+ fallback_config=fb_config,
167
+ )
168
+
169
+ # Call the provider's method asynchronously
170
+ return await provider.create_embedding(input=input, model=model_name, **kwargs)