The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Integration: Bytez as a model provider (#12121)
Aaron Vogler4c466ef1570c
diff --git a/.gitignore b/.gitignoreindex a62963865a4..f8d028ff47b 100644--- a/.gitignore+++ b/.gitignore@@ -92,4 +92,5 @@ tests/test_custom_dir/*test.pylitellm_config.yaml-.cursor\ No newline at end of file+.cursor+.vscode/launch.json\ No newline at end of filediff --git a/docs/my-website/docs/completion/input.md b/docs/my-website/docs/completion/input.mdindex b08941cde92..26629a0b8f8 100644--- a/docs/my-website/docs/completion/input.md+++ b/docs/my-website/docs/completion/input.md@@ -64,6 +64,7 @@ Use `litellm.get_supported_openai_params()` for an updated list of params for ea| ClarifAI | ✅| ✅ | ✅ | | ✅ | ✅ || || | || ||| |||| ||| Github | ✅| ✅ | ✅ | ✅| ✅ | ✅ | ✅ | ✅| ✅ | ✅| ✅|| || ✅ | ✅ (model dependent) | ✅ (model dependent) || ||| Novita AI| ✅| ✅ || ✅| ✅ | ✅ | ✅ | ✅| ✅ | ✅| || ✅||| |||| ||+| Bytez | ✅| ✅ || ✅| ✅ | | | ✅|| || || || || || ||:::notediff --git a/docs/my-website/docs/provider_registration/index.md b/docs/my-website/docs/provider_registration/index.mdnew file mode 100644index 00000000000..66f61554783--- /dev/null+++ b/docs/my-website/docs/provider_registration/index.md@@ -0,0 +1,316 @@+---+title: "Integrate as a Model Provider"+---++This guide focuses on how to setup the classes and configuration necessary to act as a chat provider.++Please see this guide first and look at the existing code in the codebase to understand how to act as a different provider, e.g. handling embeddings or image-generation.++---++### Overview++The way liteLLM works from a provider's perspective is simple.++liteLLM acts as a wrapper, it takes openai requests and routes them to your api. It then adapts your output into a standard output.++To integrate as a provider, you need to write a module that slots in the api and acts as an adapter between the liteLLM API and your API.++The module you will be writing acts as both a config and a means to adapt requests and responses.++Your objective is to effectively write this module so that it adapts inputs to your api, and adapts outputs to the calling liteLLM code.++It includes methods that:++- Validate the request+- Transform (adapt) the requests into requests sent to your api+- Transform (adapt) responses from your api into responses given back to the calling liteLLM code+- \+ a few others++---++### 1. Create Your Config Class++Create a new directory with your provider name++#### `litellm/llms/your_provider_name_here`++Inside of there, you will want to add a file for your chat configuration++#### `litellm/llms/your_provider_name_here/chat/transformation.py`++The `transformation.py` file will contain a configuration class that dictates how your api will slot into the liteLLM api.++Define your config class extending `BaseConfig`:++```python+from litellm.llms.base_llm.chat.transformation import BaseConfig++class MyProviderChatConfig(BaseConfig):+ def __init__(self):+ ...+```++We will fill in the abstract methods at a later point.++---++### 2. Add Yourself To Various Places In The Code Base++liteLLM is working to enhance this process, but currently, what you need to do is the following:++#### `litellm/__init__.py`++At the top part of the file, add your key to the list of keys as an option++```py+azure_key: Optional[str] = None+anthropic_key: Optional[str] = None+replicate_key: Optional[str] = None+bytez_key: Optional[str] = None+cohere_key: Optional[str] = None+infinity_key: Optional[str] = None+clarifai_key: Optional[str] = None+```++Import your config++```+from .llms.bytez.chat.transformation import BytezChatConfig+from .llms.custom_llm import CustomLLM+from .llms.bedrock.chat.converse_transformation import AmazonConverseConfig+from .llms.openai_like.chat.handler import OpenAILikeChatConfig+```++#### `litellm/main.py`++Add yourself to `main.py` so requests can be routed to your config class++```py+from .llms.bedrock.chat import BedrockConverseLLM, BedrockLLM+from .llms.bedrock.embed.embedding import BedrockEmbedding+from .llms.bedrock.image.image_handler import BedrockImageGeneration+from .llms.bytez.chat.transformation import BytezChatConfig+from .llms.codestral.completion.handler import CodestralTextCompletion+from .llms.cohere.embed import handler as cohere_embed+from .llms.custom_httpx.aiohttp_handler import BaseLLMAIOHTTPHandler++base_llm_http_handler = BaseLLMHTTPHandler()+base_llm_aiohttp_handler = BaseLLMAIOHTTPHandler()+sagemaker_chat_completion = SagemakerChatHandler()+bytez_transformation = BytezChatConfig()+```++Then much lower in the code++```py+elif custom_llm_provider == "bytez":+ api_key = (+ api_key+ or litellm.bytez_key+ or get_secret_str("BYTEZ_API_KEY")+ or litellm.api_key+ )++ response = base_llm_http_handler.completion(+ model=model,+ messages=messages,+ headers=headers,+ model_response=model_response,+ api_key=api_key,+ api_base=api_base,+ acompletion=acompletion,+ logging_obj=logging,+ optional_params=optional_params,+ litellm_params=litellm_params,+ timeout=timeout, # type: ignore+ client=client,+ custom_llm_provider=custom_llm_provider,+ encoding=encoding,+ stream=stream,+ )++ pass+```++NOTE you can rely on liteLLM passing each of the args/kwargs to your config via the .completion() call++#### `litellm/constants.py`++Add yourself to the list of `LITELLM_CHAT_PROVIDERS`++```py+LITELLM_CHAT_PROVIDERS = [+ "openai",+ "openai_like",+ "bytez",+ "xai",+ "custom_openai",+ "text-completion-openai",+```++Add yourself to the if statement chain of providers here++#### `litellm/litellm_core_utils/get_llm_provider_logic.py`++```py+elif model == "*":+ custom_llm_provider = "openai"+# bytez models+elif model.startswith("bytez/"):+ custom_llm_provider = "bytez"+if not custom_llm_provider:+ if litellm.suppress_debug_info is False:+ print() # noqa+```++#### `litellm/litellm_core_utils/streaming_handler.py`++#### If you are doing something custom with streaming, this needs to be updated, e.g.++```py+ def handle_bytez_chunk(self, chunk):+ try:+ is_finished = False+ finish_reason = ""++ return {+ "text": chunk,+ "is_finished": is_finished,+ "finish_reason": finish_reason,+ }+ except Exception as e:+ raise e+```++Then lower in the file++```+elif self.custom_llm_provider and self.custom_llm_provider == "bytez":+ response_obj = self.handle_bytez_chunk(chunk)+ completion_obj["content"] = response_obj["text"]+ if response_obj["is_finished"]:+ self.received_finish_reason = response_obj["finish_reason"]+ pass+```++---++### 3. Write a test file to iterate your code++Add a test file somewhere in the project, `tests/test_litellm/llms/my_provider/chat/test.py`++Write to it the following:++```python+import os+from litellm import completion++os.environ["MY_PROVIDER_KEY"] = "KEY_GOES_HERE"++completion(model="my_provider/your-model", messages=[...], api_key="...")+```++If you want to run it with the vscode debugger you can do so with this config file (recommended)++`.vscode/launch.json`++```json+{+ // Use IntelliSense to learn about possible attributes.+ // Hover to view descriptions of existing attributes.+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387+ "version": "0.2.0",+ "configurations": [+ {+ "name": "Python Debugger: Current File",+ "type": "debugpy",+ "request": "launch",+ "program": "${file}",+ "console": "integratedTerminal",+ "env": {+ "PYTHONPATH": "${workspaceFolder}",+ "MY_PROVIDER_API_KEY": "YOUR_API_KEY"+ }+ }+ ]+}+```++If you run with the debugger, after you update `"MY_PROVIDER_API_KEY": "YOUR_API_KEY"` you can remove this from the test script:++`os.environ["MY_PROVIDER_KEY"] = "KEY_GOES_HERE"`++---++### 4. Implement Required Methods++It's wise to follow `completion()` in `litellm/llms/custom_httpx/llm_http_handler.py`++You will see it calls each of the methods defined in the base class.++The debugger is your friend.++###### `validate_environment`++Setup headers, validate key/model:++```python+def validate_environment(...):+ headers.update({+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json"+ })+ return headers+```++###### `get_complete_url`++Return the final request URL:++```python+def get_complete_url(...):+ return f"{api_base}/{model}"+```++###### `transform_request`++Adapt OpenAI-style input into provider-specific format:++```python+def transform_request(...):+ data = {"messages": messages, "params": optional_params}+ return data+```++###### `transform_response`++Process and map the raw provider response:++```python+def transform_response(...):+ json = raw_response.json()+ model_response.model = model+ model_response.choices[0].message.content = json.get("output")+ return model_response+```++###### `get_sync_custom_stream_wrapper` / `get_async_custom_stream_wrapper`++If you need to do something these are here for you. See the `litellm/llms/sagemaker/chat/transformation.py` or the `litellm/llms/bytez/chat/transformation.py` implementation to better understand how to use these.++Use `CustomStreamWrapper` + `httpx` streaming client to yield content.++---++### 🧪 Tests++Create tests in `tests/test_litellm/llms/my_provider/chat/test.py`. Iterate until you are satisfied with the quality!++---++### Spare thoughts++If you get stuck, see the other provider implementations, `ctrl + shift + f` and `ctrl + p` are your friends!++You can also visit the [discord feedback channel](https://discord.gg/wuPM9dRgDw)diff --git a/docs/my-website/docs/providers/bytez.md b/docs/my-website/docs/providers/bytez.mdnew file mode 100644index 00000000000..fc7a684ee8d--- /dev/null+++ b/docs/my-website/docs/providers/bytez.md@@ -0,0 +1,186 @@+import Tabs from '@theme/Tabs';+import TabItem from '@theme/TabItem';++# Bytez++LiteLLM supports all chat models on [Bytez](https://www.bytez.com)!++That also means multi-modal models are supported 🔥++Tasks supported: `chat`, `image-text-to-text`, `audio-text-to-text`, `video-text-to-text`++## Usage++<Tabs>+<TabItem value="sdk" label="SDK">++### API KEYS++```py+import os+os.environ["BYTEZ_API_KEY"] = "YOUR_BYTEZ_KEY_GOES_HERE"+```++### Example Call++```py+from litellm import completion+import os+## set ENV variables+os.environ["BYTEZ_API_KEY"] = "YOUR_BYTEZ_KEY_GOES_HERE"++response = completion(+ model="bytez/google/gemma-3-4b-it",+ messages = [{ "content": "Hello, how are you?","role": "user"}]+)+```++</TabItem>+<TabItem value="proxy" label="PROXY">++1. Add models to your config.yaml++```yaml+model_list:+ - model_name: gemma-3+ litellm_params:+ model: bytez/google/gemma-3-4b-it+ api_key: os.environ/BYTEZ_API_KEY+```++2. Start the proxy++```bash+$ BYTEZ_API_KEY=YOUR_BYTEZ_API_KEY_HERE litellm --config /path/to/config.yaml --debug+```++3. Send Request to LiteLLM Proxy Server++ <Tabs>++ <TabItem value="openai" label="OpenAI Python v1.0.0+">++```py+import openai+client = openai.OpenAI(+ api_key="sk-1234", # pass litellm proxy key, if you're using virtual keys+ base_url="http://0.0.0.0:4000" # litellm-proxy-base url+)++response = client.chat.completions.create(+ model="gemma-3",+ messages = [+ {+ "role": "system",+ "content": "Be a good human!"+ },+ {+ "role": "user",+ "content": "What do you know about earth?"+ }+ ]+)++print(response)+```++ </TabItem>++ <TabItem value="curl" label="curl">++```shell+curl --location 'http://0.0.0.0:4000/chat/completions' \+ --header 'Authorization: Bearer sk-1234' \+ --header 'Content-Type: application/json' \+ --data '{+ "model": "gemma-3",+ "messages": [+ {+ "role": "system",+ "content": "Be a good human!"+ },+ {+ "role": "user",+ "content": "What do you know about earth?"+ }+ ],+}'+```++ </TabItem>++ </Tabs>++</TabItem>++</Tabs>++## Automatic Prompt Template Handling++All prompt formatting is handled automatically by our API when you send a messages list to it!++If you wish to use custom formatting, please let us know via either [[email protected]](mailto:[email protected]) or on our [Discord](https://discord.com/invite/Z723PfCFWf) and we will work to provide it!++## Passing additional params - max_tokens, temperature++See all litellm.completion supported params [here](https://docs.litellm.ai/docs/completion/input)++```py+# !pip install litellm+from litellm import completion+import os+## set ENV variables+os.environ["BYTEZ_API_KEY"] = "YOUR_BYTEZ_KEY_HERE"++# bytez gemma-3 call+response = completion(+ model="bytez/google/gemma-3-4b-it",+ messages = [{ "content": "Hello, how are you?","role": "user"}],+ max_tokens=20,+ temperature=0.5+)+```++**proxy**++```yaml+model_list:+ - model_name: gemma-3+ litellm_params:+ model: bytez/google/gemma-3-4b-it+ api_key: os.environ/BYTEZ_API_KEY+ max_tokens: 20+ temperature: 0.5+```++## Passing Bytez-specific params++Any kwarg supported by huggingface we also support! (Provided the model supports it.)++Example `repetition_penalty`++```py+# !pip install litellm+from litellm import completion+import os+## set ENV variables+os.environ["BYTEZ_API_KEY"] = "YOUR_BYTEZ_KEY_HERE"++# bytez llama3 call with additional params+response = completion(+ model="bytez/google/gemma-3-4b-it",+ messages = [{ "content": "Hello, how are you?","role": "user"}],+ repetition_penalty=1.2,+)+```++**proxy**++```yaml+model_list:+ - model_name: gemma-3+ litellm_params:+ model: bytez/google/gemma-3-4b-it+ api_key: os.environ/BYTEZ_API_KEY+ repetition_penalty: 1.2+```diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex 7883e3829dc..8eb3304c0cb 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -619,6 +619,11 @@ const sidebars = {"proxy_server",],},+ {+ type: "doc",+ id: "provider_registration/index",+ label: "Integrate as a Model Provider",+ },"troubleshoot",],};diff --git a/litellm/__init__.py b/litellm/__init__.pyindex f3661c92125..0c681d7eb01 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -193,6 +193,7 @@ openai_like_key: Optional[str] = Noneazure_key: Optional[str] = Noneanthropic_key: Optional[str] = Nonereplicate_key: Optional[str] = None+bytez_key: Optional[str] = Nonecohere_key: Optional[str] = Noneinfinity_key: Optional[str] = Noneclarifai_key: Optional[str] = None@@ -919,6 +920,7 @@ ALL_LITELLM_RESPONSE_TYPES = [TextCompletionResponse,]+from .llms.bytez.chat.transformation import BytezChatConfigfrom .llms.custom_llm import CustomLLMfrom .llms.bedrock.chat.converse_transformation import AmazonConverseConfigfrom .llms.openai_like.chat.handler import OpenAILikeChatConfigdiff --git a/litellm/constants.py b/litellm/constants.pyindex 733af4ef616..b27dcbf7cdb 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -210,6 +210,7 @@ DEFAULT_IMAGE_ENDPOINT_MODEL = "dall-e-2"LITELLM_CHAT_PROVIDERS = ["openai","openai_like",+ "bytez","xai","custom_openai","text-completion-openai",diff --git a/litellm/litellm_core_utils/custom_logger_registry.py b/litellm/litellm_core_utils/custom_logger_registry.pyindex e6180fa8d9e..696b0e74dd0 100644--- a/litellm/litellm_core_utils/custom_logger_registry.py+++ b/litellm/litellm_core_utils/custom_logger_registry.py@@ -7,7 +7,7 @@ Example:"datadog" -> DataDogLogger"prometheus" -> PrometheusLogger"""-+from typing import Unionfrom litellm.integrations.agentops import AgentOpsfrom litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHookfrom litellm.integrations.argilla import ArgillaLogger@@ -103,7 +103,7 @@ class CustomLoggerRegistry:pass # enterprise not installed@classmethod- def get_callback_str_from_class_type(cls, class_type: type) -> str | None:+ def get_callback_str_from_class_type(cls, class_type: type) -> Union[str, None]:"""Get the callback string from the class type.diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.pyindex b5d2996437d..64eb814597f 100644--- a/litellm/litellm_core_utils/get_llm_provider_logic.py+++ b/litellm/litellm_core_utils/get_llm_provider_logic.py@@ -341,6 +341,9 @@ def get_llm_provider( # noqa: PLR0915custom_llm_provider = "empower"elif model == "*":custom_llm_provider = "openai"+ # bytez models+ elif model.startswith("bytez/"):+ custom_llm_provider = "bytez"if not custom_llm_provider:if litellm.suppress_debug_info is False:print() # noqadiff --git a/litellm/llms/bytez/chat/transformation.py b/litellm/llms/bytez/chat/transformation.pynew file mode 100644index 00000000000..481eb43d82b--- /dev/null+++ b/litellm/llms/bytez/chat/transformation.py@@ -0,0 +1,492 @@+import json+import time+import traceback+from typing import (+ TYPE_CHECKING,+ Any,+ List,+ Optional,+ Union,+ Dict,+)++import httpx++from litellm.litellm_core_utils.logging_utils import track_llm_api_timing+from litellm.litellm_core_utils.exception_mapping_utils import exception_type+from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException+from litellm.utils import CustomStreamWrapper, ModelResponse, Usage+from litellm.types.utils import LlmProviders+from litellm.types.llms.openai import AllMessageValues++from litellm.llms.custom_httpx.http_handler import (+ version,+ HTTPHandler,+ _get_httpx_client,+ AsyncHTTPHandler,+ get_async_httpx_client,+)++from ..common_utils import validate_environment, API_BASE, BytezError+++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj++ LiteLLMLoggingObj = _LiteLLMLoggingObj+else:+ LiteLLMLoggingObj = Any+++# 5 minute timeout (models may need to load)+STREAMING_TIMEOUT = 60 * 5+++class BytezChatConfig(BaseConfig):+ """+ Configuration class for Bytez's API interface.+ """++ def __init__(+ self,+ ) -> None:+ locals_ = locals().copy()+ for key, value in locals_.items():+ if key != "self" and value is not None:+ setattr(self.__class__, key, value)+ # mark the class as using a custom stream wrapper because the default only iterates on lines+ setattr(self.__class__, "has_custom_stream_wrapper", True)++ self.openai_to_bytez_param_map = {+ "stream": "stream",+ "max_tokens": "max_new_tokens",+ "max_completion_tokens": "max_new_tokens",+ "temperature": "temperature",+ "top_p": "top_p",+ "n": "num_return_sequences",+ "max_retries": "max_retries",+ "seed": False, # TODO requires backend changes+ "stop": False, # TODO requires backend changes+ "logit_bias": False, # TODO requires backend changes+ "logprobs": False, # TODO requires backend changes+ "frequency_penalty": False,+ "presence_penalty": False,+ "top_logprobs": False,+ "modalities": False,+ "prediction": False,+ "stream_options": False,+ "tools": False,+ "tool_choice": False,+ "function_call": False,+ "functions": False,+ "extra_headers": False,+ "parallel_tool_calls": False,+ "audio": False,+ "web_search_options": False,+ }++ def get_supported_openai_params(self, model: str) -> List[str]:+ supported_params = []+ for key, value in self.openai_to_bytez_param_map.items():+ if value:+ supported_params.append(key)++ return supported_params++ def map_openai_params(+ self,+ non_default_params: dict,+ optional_params: dict,+ model: str,+ drop_params: bool,+ ) -> dict:++ adapted_params = {}++ all_params = {**non_default_params, **optional_params}++ for key, value in all_params.items():++ alias = self.openai_to_bytez_param_map.get(key)++ if alias is False:+ if drop_params:+ continue++ raise Exception(f"param `{key}` is not supported on Bytez")++ if alias is None:+ adapted_params[key] = value+ continue++ adapted_params[alias] = value++ return adapted_params++ def validate_environment(+ self,+ headers: dict,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ ) -> dict:++ headers.update(+ {+ "content-type": "application/json",+ "Authorization": f"Key {api_key}",+ "user-agent": f"litellm/{version}",+ }+ )++ validate_environment(+ messages=messages,+ api_key=api_key,+ )++ return headers++ def get_complete_url(+ self,+ api_base: Optional[str],+ api_key: Optional[str],+ model: str,+ optional_params: dict,+ litellm_params: dict,+ stream: Optional[bool] = None,+ ) -> str:+ return f"{API_BASE}/{model}"++ def transform_request(+ self,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ headers: dict,+ ) -> dict:+ stream = optional_params.get("stream", False)++ # we add stream not as an additional param, but as a primary prop on the request body, this is always defined if stream == True+ if optional_params.get("stream"):+ del optional_params["stream"]++ messages = adapt_messages_to_bytez_standard(messages=messages) # type: ignore++ data = {+ "messages": messages,+ "stream": stream,+ "params": optional_params,+ }++ return data++ def transform_response(+ self,+ model: str,+ raw_response: httpx.Response,+ model_response: ModelResponse,+ logging_obj: LiteLLMLoggingObj,+ request_data: dict,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ encoding: Any,+ api_key: Optional[str] = None,+ json_mode: Optional[bool] = None,+ ) -> ModelResponse:++ json = raw_response.json() # noqa: F811++ error = json.get("error")++ if error is not None:+ raise BytezError(+ message=str(json["error"]),+ status_code=raw_response.status_code,+ )++ # set meta data here+ model_response.created = int(time.time())+ model_response.model = model++ # Add the output+ output = json.get("output")++ message = model_response.choices[0].message # type: ignore++ message.content = output["content"][0]["text"]++ messages = adapt_messages_to_bytez_standard(messages=messages) # type: ignore++ # NOTE We are approximating tokens, to get the true values we will need to update our BE+ prompt_tokens = get_tokens_from_messages(messages) # type: ignore++ output_messages = adapt_messages_to_bytez_standard(messages=[output])++ completion_tokens = get_tokens_from_messages(output_messages)++ total_tokens = prompt_tokens + completion_tokens++ usage = Usage(+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ total_tokens=total_tokens,+ )++ model_response.usage = usage # type: ignore++ model_response._hidden_params["additional_headers"] = raw_response.headers+ message.provider_specific_fields = {+ "ratelimit-limit": raw_response.headers.get("ratelimit-limit"),+ "ratelimit-remaining": raw_response.headers.get("ratelimit-remaining"),+ "ratelimit-reset": raw_response.headers.get("ratelimit-reset"),+ "inference-meter": raw_response.headers.get("inference-meter"),+ "inference-time": raw_response.headers.get("inference-time"),+ }++ # TODO additional data when supported+ # message.tool_calls+ # message.function_call++ return model_response++ @track_llm_api_timing()+ def get_sync_custom_stream_wrapper(+ self,+ model: str,+ custom_llm_provider: str,+ logging_obj: LiteLLMLoggingObj,+ api_base: str,+ headers: dict,+ data: dict,+ messages: list,+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ json_mode: Optional[bool] = None,+ signed_json_body: Optional[bytes] = None,+ ) -> "BytezCustomStreamWrapper":+ if client is None or isinstance(client, AsyncHTTPHandler):+ client = _get_httpx_client(params={})++ try:+ response = client.post(+ api_base,+ headers=headers,+ data=json.dumps(data),+ stream=True,+ logging_obj=logging_obj,+ timeout=STREAMING_TIMEOUT,+ )+ except httpx.HTTPStatusError as e:+ raise BytezError(+ status_code=e.response.status_code, message=e.response.text+ )++ if response.status_code != 200:+ raise BytezError(status_code=response.status_code, message=response.text)++ completion_stream = response.iter_text()++ streaming_response = BytezCustomStreamWrapper(+ completion_stream=completion_stream,+ model=model,+ custom_llm_provider=custom_llm_provider,+ logging_obj=logging_obj,+ )+ return streaming_response++ @track_llm_api_timing()+ async def get_async_custom_stream_wrapper(+ self,+ model: str,+ custom_llm_provider: str,+ logging_obj: LiteLLMLoggingObj,+ api_base: str,+ headers: dict,+ data: dict,+ messages: list,+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,+ json_mode: Optional[bool] = None,+ signed_json_body: Optional[bytes] = None,+ ) -> "BytezCustomStreamWrapper":+ if client is None or isinstance(client, HTTPHandler):+ client = get_async_httpx_client(llm_provider=LlmProviders.BYTEZ, params={})++ try:+ response = await client.post(+ api_base,+ headers=headers,+ data=json.dumps(data),+ stream=True,+ logging_obj=logging_obj,+ timeout=STREAMING_TIMEOUT,+ )+ except httpx.HTTPStatusError as e:+ raise BytezError(+ status_code=e.response.status_code, message=e.response.text+ )++ if response.status_code != 200:+ raise BytezError(status_code=response.status_code, message=response.text)++ completion_stream = response.aiter_text()++ streaming_response = BytezCustomStreamWrapper(+ completion_stream=completion_stream,+ model=model,+ custom_llm_provider=custom_llm_provider,+ logging_obj=logging_obj,+ )+ return streaming_response++ def get_error_class(+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]+ ) -> BaseLLMException:+ return BytezError(status_code=status_code, message=error_message)+++class BytezCustomStreamWrapper(CustomStreamWrapper):+ def chunk_creator(self, chunk: Any):+ try:+ model_response = self.model_response_creator()+ response_obj: Dict[str, Any] = {}++ response_obj = {+ "text": chunk,+ "is_finished": False,+ "finish_reason": "",+ }++ completion_obj: Dict[str, Any] = {"content": chunk}++ return self.return_processed_chunk_logic(+ completion_obj=completion_obj,+ model_response=model_response, # type: ignore+ response_obj=response_obj,+ )++ except StopIteration:+ raise StopIteration+ except Exception as e:+ traceback.format_exc()+ setattr(e, "message", str(e))+ raise exception_type(+ model=self.model,+ custom_llm_provider=self.custom_llm_provider,+ original_exception=e,+ )+++# litellm/types/llms/openai.py is a good reference for what is supported+open_ai_to_bytez_content_item_map = {+ "text": {"type": "text", "value_name": "text"},+ "image_url": {"type": "image", "value_name": "url"},+ "input_audio": {"type": "audio", "value_name": "url"},+ "video_url": {"type": "video", "value_name": "url"},+ "document": None,+ "file": None,+}+++def adapt_messages_to_bytez_standard(messages: List[Dict]):++ messages = _adapt_string_only_content_to_lists(messages)++ new_messages = []++ for message in messages:++ role = message["role"]+ content: list = message["content"]++ new_content = []++ for content_item in content:+ type: Union[str, None] = content_item.get("type")++ if not type:+ raise Exception("Prop `type` is not a string")++ content_item_map = open_ai_to_bytez_content_item_map[type]++ if not content_item_map:+ raise Exception(f"Prop `{type}` is not supported")++ new_type = content_item_map["type"]++ value_name = content_item_map["value_name"]++ value: Union[str, None] = content_item.get(value_name)++ if not value:+ raise Exception(f"Prop `{value_name}` is not a string")++ new_content.append({"type": new_type, value_name: value})++ new_messages.append({"role": role, "content": new_content})++ return new_messages+++# "content": "The cat ran so fast"+# becomes+# "content": [{"type": "text", "text": "The cat ran so fast"}]+def _adapt_string_only_content_to_lists(messages: List[Dict]):+ new_messages = []++ for message in messages:++ role = message.get("role")+ content = message.get("content")++ new_content = []++ if isinstance(content, str):+ new_content.append({"type": "text", "text": content})++ elif isinstance(content, dict):+ new_content.append(content)++ elif isinstance(content, list):++ new_content_items = []+ for content_item in content:+ if isinstance(content_item, str):+ new_content_items.append({"type": "text", "text": content_item})+ elif isinstance(content_item, dict):+ new_content_items.append(content_item)+ else:+ raise Exception(+ "`content` can only contain strings or openai content dicts"+ )++ new_content += new_content_items+ else:+ raise Exception("Content must be a string")++ new_messages.append({"role": role, "content": new_content})++ return new_messages+++# TODO get this from the api instead of doing it here, will require backend work+def get_tokens_from_messages(messages: List[dict]):+ total = 0++ for message in messages:+ content: List[dict] = message["content"]++ for content_item in content:+ type = content_item["type"]+ if type == "text":+ value: str = content_item["text"]+ words = value.split(" ")+ total += len(words)+ continue+ # we'll count media as single tokens for now+ total += 1++ return totaldiff --git a/litellm/llms/bytez/common_utils.py b/litellm/llms/bytez/common_utils.pynew file mode 100644index 00000000000..b59d57b2e73--- /dev/null+++ b/litellm/llms/bytez/common_utils.py@@ -0,0 +1,37 @@+from typing import Optional, List, Union++import httpx++from litellm.llms.base_llm.chat.transformation import BaseLLMException++API_BASE = "https://api.bytez.com/models/v2"+++class BytezError(BaseLLMException):+ def __init__(+ self,+ status_code: int,+ message: str,+ headers: Optional[httpx.Headers] = None,+ ):+ self.status_code = status_code+ self.message = message+ self.request = httpx.Request(method="POST", url=API_BASE)+ self.response = httpx.Response(status_code=status_code, request=self.request)+ super().__init__(+ status_code=status_code,+ message=message,+ headers=headers,+ )+++def validate_environment(+ api_key: Optional[str] = None, messages: Union[List, None] = None+) -> None:+ if not messages:+ raise Exception(+ "kwarg `messages` must be an array of messages that follow the openai chat standard"+ )++ if not api_key:+ raise Exception("Missing api_key, make sure you pass in your api key")diff --git a/litellm/main.py b/litellm/main.pyindex 57bc405ab8f..668109e0c17 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -142,6 +142,7 @@ from .llms.azure_ai.embed import AzureAIEmbeddingfrom .llms.bedrock.chat import BedrockConverseLLM, BedrockLLMfrom .llms.bedrock.embed.embedding import BedrockEmbeddingfrom .llms.bedrock.image.image_handler import BedrockImageGeneration+from .llms.bytez.chat.transformation import BytezChatConfigfrom .llms.codestral.completion.handler import CodestralTextCompletionfrom .llms.cohere.embed import handler as cohere_embedfrom .llms.custom_httpx.aiohttp_handler import BaseLLMAIOHTTPHandler@@ -252,6 +253,7 @@ databricks_embedding = DatabricksEmbeddingHandler()base_llm_http_handler = BaseLLMHTTPHandler()base_llm_aiohttp_handler = BaseLLMAIOHTTPHandler()sagemaker_chat_completion = SagemakerChatHandler()+bytez_transformation = BytezChatConfig()####### COMPLETION ENDPOINTS ################@@ -3280,6 +3282,35 @@ def completion( # type: ignore # noqa: PLR0915)raise e+ elif custom_llm_provider == "bytez":+ api_key = (+ api_key+ or litellm.bytez_key+ or get_secret_str("BYTEZ_API_KEY")+ or litellm.api_key+ )++ response = base_llm_http_handler.completion(+ model=model,+ messages=messages,+ headers=headers,+ model_response=model_response,+ api_key=api_key,+ api_base=api_base,+ acompletion=acompletion,+ logging_obj=logging,+ optional_params=optional_params,+ litellm_params=litellm_params,+ timeout=timeout, # type: ignore+ client=client,+ custom_llm_provider=custom_llm_provider,+ encoding=encoding,+ stream=stream,+ provider_config=bytez_transformation+ )++ pass+elif custom_llm_provider == "custom":url = litellm.api_base or api_base or ""if url is None or url == "":diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex aaa4b52e02e..ea5c8036816 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2238,6 +2238,7 @@ class LlmProviders(str, Enum):CLARIFAI = "clarifai"ANTHROPIC = "anthropic"ANTHROPIC_TEXT = "anthropic_text"+ BYTEZ = "bytez"REPLICATE = "replicate"HUGGINGFACE = "huggingface"TOGETHER_AI = "together_ai"diff --git a/litellm/utils.py b/litellm/utils.pyindex 9ca27da15a9..fd5b6da60e7 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -1620,7 +1620,6 @@ def _is_streaming_request():return True#########################################################-return False@@ -6665,6 +6664,8 @@ class ProviderConfigManager:return litellm.DeepSeekChatConfig()elif litellm.LlmProviders.GROQ == provider:return litellm.GroqChatConfig()+ elif litellm.LlmProviders.BYTEZ == provider:+ return litellm.BytezChatConfig()elif litellm.LlmProviders.DATABRICKS == provider:return litellm.DatabricksConfig()elif litellm.LlmProviders.XAI == provider:diff --git a/tests/test_litellm/llms/bytez/chat/test_bytez_chat_transformation.py b/tests/test_litellm/llms/bytez/chat/test_bytez_chat_transformation.pynew file mode 100644index 00000000000..dd388fedc61--- /dev/null+++ b/tests/test_litellm/llms/bytez/chat/test_bytez_chat_transformation.py@@ -0,0 +1,260 @@+import os+import sys+import pytest+import json++# Adds the parent directory to the system path+sys.path.insert(0, os.path.abspath("../../../../.."))++from litellm.llms.bytez.chat.transformation import BytezChatConfig, API_BASE, version++TEST_API_KEY = "MOCK_BYTEZ_API_KEY"+TEST_MODEL_NAME = "google/gemma-3-4b-it"+TEST_MODEL = f"bytez/{TEST_MODEL_NAME}"+TEST_MESSAGES = [{"role": "user", "content": "Hello"}]+++class TestBytezChatConfig:+ def test_validate_environment(self):+ config = BytezChatConfig()++ headers = {}++ result = config.validate_environment(+ headers=headers,+ model=TEST_MODEL,+ messages=TEST_MESSAGES, # type: ignore+ optional_params={},+ litellm_params={},+ api_key=TEST_API_KEY,+ api_base=API_BASE,+ )++ assert result["Authorization"] == f"Key {TEST_API_KEY}"+ assert result["content-type"] == "application/json"+ assert result["user-agent"] == f"litellm/{version}"++ def test_missing_api_key(self):+ with pytest.raises(Exception) as excinfo:+ config = BytezChatConfig()++ headers = {}++ config.validate_environment(+ headers=headers,+ model=TEST_MODEL,+ messages=TEST_MESSAGES, # type: ignore+ optional_params={},+ litellm_params={},+ api_key=None,+ api_base=API_BASE,+ )++ assert "Missing api_key, make sure you pass in your api key" in str(+ excinfo.value+ )++ def test_bytez_completion_mock_sync(self, respx_mock):+ import litellm++ input_messages = [+ {"role": "user", "content": "What is your favorite kind of cat?"}+ ]++ output_content = "Hello, how can I help you today?"++ output = {+ "role": "assistant",+ "content": [{"type": "text", "text": output_content}],+ }++ # Mock the HTTP request+ respx_mock.post(f"{API_BASE}/{TEST_MODEL_NAME}").respond(+ json={+ "error": None,+ "output": output,+ },+ status_code=200,+ )++ # Make the actual API call through LiteLLM+ response = litellm.completion(+ model=TEST_MODEL,+ messages=input_messages,+ api_key=TEST_API_KEY,+ api_base=API_BASE,+ )++ assert response.choices[0].message.content == output_content # type: ignore++ def test_bytez_messages_adaptation(self):+ cases = [+ dict(+ input=[+ {+ "role": "user",+ "content": "What color is this cat?",+ }+ ],+ expected_output=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What color is this cat?"}+ ],+ }+ ],+ ),+ dict(+ input=[+ {+ "role": "user",+ "content": {"type": "text", "text": "What color is this cat?"},+ }+ ],+ expected_output=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What color is this cat?"}+ ],+ }+ ],+ ),+ dict(+ input=[+ {+ "role": "user",+ "content": [+ "What color is this cat?",+ {+ "type": "image_url",+ "url": "https://images.squarespace-cdn.com/content/v1/5452d441e4b0c188b51fef1a/1615326541809-TW01PVTOJ4PXQUXVRLHI/male-orange-tabby-cat.jpg",+ },+ ],+ }+ ],+ expected_output=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What color is this cat?"},+ {+ "type": "image",+ "url": "https://images.squarespace-cdn.com/content/v1/5452d441e4b0c188b51fef1a/1615326541809-TW01PVTOJ4PXQUXVRLHI/male-orange-tabby-cat.jpg",+ },+ ],+ }+ ],+ ),+ dict(+ input=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What color is this cat?"},+ {+ "type": "image_url",+ "url": "https://images.squarespace-cdn.com/content/v1/5452d441e4b0c188b51fef1a/1615326541809-TW01PVTOJ4PXQUXVRLHI/male-orange-tabby-cat.jpg",+ },+ ],+ }+ ],+ expected_output=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What color is this cat?"},+ {+ "type": "image",+ "url": "https://images.squarespace-cdn.com/content/v1/5452d441e4b0c188b51fef1a/1615326541809-TW01PVTOJ4PXQUXVRLHI/male-orange-tabby-cat.jpg",+ },+ ],+ }+ ],+ ),+ dict(+ input=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What kind of cat meow is this?"},+ {+ "type": "input_audio",+ "url": "https://storage.googleapis.com/kagglesdsdata/datasets/1736753/2838478/dataset/dataset/B_ANI01_MC_FN_SIM01_101.wav?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=databundle-worker-v2%40kaggle-161607.iam.gserviceaccount.com%2F20250711%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20250711T192905Z&X-Goog-Expires=345600&X-Goog-SignedHeaders=host&X-Goog-Signature=812b4bd6fcf9296f8e34f67664d900a81cf81a4c8a4f439ce12befc89b4bef07c2645cab20ce5ba8f6b311dffa85aa05b70b4efbe53bced50a43a5e7622ea1ee0d8cc390679cdc6a6aae2c27f75debc1ce2361c595b3c9e1b8c88e2756ffc6b4f290af7f3dfa7232dc69ccc9a2181be756e0d538250f9761a8b05ba1ac6c6b5d946f97a16aa14a5609ae62a2c4713c2077fcd34d129dbcdac6bb543ae547507b1a424e4fd09f817000943c11507e0a74c514ec212b17427b7fc9e2ce87a250db1258645e4862a4261e3790fd99c9186148ad0653acd2b6a9468adbeb94f17b5a685551037fd2cc9fe72fa405a006c0bd42d03be1e4c0dc4023ed3a77171edff3",+ },+ ],+ }+ ],+ expected_output=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What kind of cat meow is this?"},+ {+ "type": "audio",+ "url": "https://storage.googleapis.com/kagglesdsdata/datasets/1736753/2838478/dataset/dataset/B_ANI01_MC_FN_SIM01_101.wav?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=databundle-worker-v2%40kaggle-161607.iam.gserviceaccount.com%2F20250711%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20250711T192905Z&X-Goog-Expires=345600&X-Goog-SignedHeaders=host&X-Goog-Signature=812b4bd6fcf9296f8e34f67664d900a81cf81a4c8a4f439ce12befc89b4bef07c2645cab20ce5ba8f6b311dffa85aa05b70b4efbe53bced50a43a5e7622ea1ee0d8cc390679cdc6a6aae2c27f75debc1ce2361c595b3c9e1b8c88e2756ffc6b4f290af7f3dfa7232dc69ccc9a2181be756e0d538250f9761a8b05ba1ac6c6b5d946f97a16aa14a5609ae62a2c4713c2077fcd34d129dbcdac6bb543ae547507b1a424e4fd09f817000943c11507e0a74c514ec212b17427b7fc9e2ce87a250db1258645e4862a4261e3790fd99c9186148ad0653acd2b6a9468adbeb94f17b5a685551037fd2cc9fe72fa405a006c0bd42d03be1e4c0dc4023ed3a77171edff3",+ },+ ],+ }+ ],+ ),+ dict(+ input=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What kind of dog is this?"},+ {+ "type": "video_url",+ "url": "https://storage.googleapis.com/kagglesdsdata/datasets/3957252/6888743/dog1.mp4?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=databundle-worker-v2%40kaggle-161607.iam.gserviceaccount.com%2F20250711%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20250711T193025Z&X-Goog-Expires=345600&X-Goog-SignedHeaders=host&X-Goog-Signature=810961d9abcbc2437954fdf19ef216deb65d3977eb354ec10af0d4644627cc6b143a5fc6450996bae1787c09d26334de7cd6ff887510a5ac2a6eed3cfcc6673a47686c84c1f2b0bf543009388d83f2cd9551ad5f72084513c6a7acd2c718849a4ebe951ccc5631bed014b0d115225c048b9f5de68673a37db24a98ad39cf3d0ba16fb764bf38eb90c78c295c21a4ddac08c3c661b65efd511ccb86bacb87a2e2a97a06f53ea1c64d5dcf274001a61bc20867802549601301d999f5a5b2e49fd444b7db860c68e1c67df6e8edd5ad97171eaafb4fa1462453924ea4d78733be411cb6b5c910d4f829cd7189c28dc1b22c8ae2a4da844a0d202e9e64bc7fb17947",+ },+ ],+ }+ ],+ expected_output=[+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What kind of dog is this?"},+ {+ "type": "video",+ "url": "https://storage.googleapis.com/kagglesdsdata/datasets/3957252/6888743/dog1.mp4?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=databundle-worker-v2%40kaggle-161607.iam.gserviceaccount.com%2F20250711%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20250711T193025Z&X-Goog-Expires=345600&X-Goog-SignedHeaders=host&X-Goog-Signature=810961d9abcbc2437954fdf19ef216deb65d3977eb354ec10af0d4644627cc6b143a5fc6450996bae1787c09d26334de7cd6ff887510a5ac2a6eed3cfcc6673a47686c84c1f2b0bf543009388d83f2cd9551ad5f72084513c6a7acd2c718849a4ebe951ccc5631bed014b0d115225c048b9f5de68673a37db24a98ad39cf3d0ba16fb764bf38eb90c78c295c21a4ddac08c3c661b65efd511ccb86bacb87a2e2a97a06f53ea1c64d5dcf274001a61bc20867802549601301d999f5a5b2e49fd444b7db860c68e1c67df6e8edd5ad97171eaafb4fa1462453924ea4d78733be411cb6b5c910d4f829cd7189c28dc1b22c8ae2a4da844a0d202e9e64bc7fb17947",+ },+ ],+ }+ ],+ ),+ ]++ config = BytezChatConfig()++ for case in cases:+ messages = case["input"]+ expected_output = case["expected_output"]++ headers = {}++ headers = config.validate_environment(+ headers=headers,+ model=TEST_MODEL,+ messages=TEST_MESSAGES, # type: ignore+ optional_params={},+ litellm_params={},+ api_key=TEST_API_KEY,+ api_base=API_BASE,+ )++ data = config.transform_request(+ model=TEST_MODEL_NAME,+ messages=messages,+ optional_params={},+ litellm_params={},+ headers=headers,+ )++ adapted_messages = data["messages"]+ stringified_output = json.dumps(adapted_messages)+ stringified_expected_output = json.dumps(expected_output)++ assert stringified_output == stringified_expected_output