Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions litellm/containers/endpoint_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def create_sync_endpoint_function(endpoint_config: Dict) -> Callable:
@client
def endpoint_func(
timeout: int = 600,
custom_llm_provider: Literal["openai"] = "openai",
custom_llm_provider: Literal["openai", "azure", "azure_text"] = "openai",
extra_headers: Optional[Dict[str, Any]] = None,
extra_query: Optional[Dict[str, Any]] = None,
extra_body: Optional[Dict[str, Any]] = None,
Expand Down Expand Up @@ -133,7 +133,7 @@ def create_async_endpoint_function(
@client
async def async_endpoint_func(
timeout: int = 600,
custom_llm_provider: Literal["openai"] = "openai",
custom_llm_provider: Literal["openai", "azure", "azure_text"] = "openai",
extra_headers: Optional[Dict[str, Any]] = None,
extra_query: Optional[Dict[str, Any]] = None,
extra_body: Optional[Dict[str, Any]] = None,
Expand Down
167 changes: 136 additions & 31 deletions litellm/containers/main.py

Large diffs are not rendered by default.

36 changes: 35 additions & 1 deletion litellm/containers/utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from typing import Dict
from typing import Any, Dict, Optional, TypeVar
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

from litellm.llms.base_llm.containers.transformation import BaseContainerConfig
from litellm.types.containers.main import (
ContainerCreateOptionalRequestParams,
ContainerListOptionalRequestParams,
)

T = TypeVar("T")


class ContainerRequestUtils:
@staticmethod
Expand Down Expand Up @@ -68,3 +70,35 @@
container_list_optional_params[param] = passed_params[param] # type: ignore

return container_list_optional_params

@staticmethod
def encode_container_id_in_response(
response_obj: T,
custom_llm_provider: Optional[str],
model_id: Optional[str],
) -> T:
"""
Encode container_id in response object with provider/model metadata for routing.

This mirrors the responses API pattern where response IDs are encoded with
routing metadata so follow-up calls can route to the correct provider.

Args:
response_obj: Response object with an `id` attribute (ContainerObject, DeleteContainerResult, etc.)
custom_llm_provider: Provider name (e.g., "azure", "openai")
model_id: Model ID from litellm_metadata

Returns:
The same response object with encoded container_id
"""
if response_obj and hasattr(response_obj, "id"):
from litellm.responses.utils import ResponsesAPIRequestUtils

encoded_id = ResponsesAPIRequestUtils._build_container_id(
custom_llm_provider=custom_llm_provider,
model_id=model_id,
container_id=response_obj.id,
)
Comment thread
Sameerlite marked this conversation as resolved.
Resolved
response_obj.id = encoded_id

return response_obj
Empty file.
48 changes: 48 additions & 0 deletions litellm/llms/azure/containers/transformation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from typing import Optional

from litellm.llms.azure.common_utils import BaseAzureLLM
from litellm.llms.openai.containers.transformation import OpenAIContainerConfig
from litellm.types.router import GenericLiteLLMParams


class AzureContainerConfig(OpenAIContainerConfig):
"""
Configuration class for Azure OpenAI container API.

Inherits request/response transformations from OpenAIContainerConfig since
Azure's container API is wire-compatible with OpenAI's. Only overrides
authentication (api-key header) and URL construction (openai/v1/containers path).

Azure container API reference:
https://learn.microsoft.com/en-us/azure/foundry/openai/latest#containers
"""

def validate_environment(
self,
headers: dict,
api_key: Optional[str] = None,
) -> dict:
return BaseAzureLLM._base_validate_azure_environment(
headers=headers,
litellm_params=GenericLiteLLMParams(api_key=api_key),
)

def get_complete_url(
self,
api_base: Optional[str],
litellm_params: dict,
) -> str:
"""
Build the Azure container endpoint URL.

Azure container API uses the path:
{endpoint}/openai/v1/containers
when api_version is 'v1', 'latest', or 'preview'; otherwise:
{endpoint}/openai/containers
"""
return BaseAzureLLM._get_base_azure_url(
api_base=api_base,
litellm_params=litellm_params,
route="/openai/containers",
default_api_version="v1",
)
21 changes: 16 additions & 5 deletions litellm/llms/custom_httpx/container_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,29 @@ def _build_url(
) -> str:
"""Build the full URL by substituting path parameters.

The api_base from get_complete_url already includes /containers,
so we need to strip that prefix from the path_template.
The api_base from get_complete_url already includes /containers and may include
query parameters. We need to parse the URL, append the path, then preserve the
query parameters.
"""
# api_base ends with /containers, path_template starts with /containers
# So we need to strip /containers from the path
if path_template.startswith("/containers"):
path_template = path_template[len("/containers") :]

url = f"{api_base.rstrip('/')}{path_template}"
# Substitute path parameters
for param, value in path_params.items():
url = url.replace(f"{{{param}}}", value)
return url
path_template = path_template.replace(f"{{{param}}}", value)

# Parse the api_base to extract existing query params
parsed_base = httpx.URL(api_base)

# Append the path to the existing path (before query params)
new_path = f"{parsed_base.path.rstrip('/')}{path_template}"

# Rebuild URL with new path, preserving query params
final_url = parsed_base.copy_with(path=new_path)

return str(final_url)


def _build_query_params(
Expand Down
11 changes: 7 additions & 4 deletions litellm/llms/openai/containers/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from litellm.types.router import GenericLiteLLMParams

from ...base_llm.containers.transformation import BaseContainerConfig
from .utils import join_container_api_base_path

if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
Expand Down Expand Up @@ -197,7 +198,7 @@ def transform_container_retrieve_request(
) -> Tuple[str, Dict]:
"""Transform the OpenAI container retrieve request."""
# For container retrieve, we just need to construct the URL
url = f"{api_base.rstrip('/')}/{container_id}"
url = join_container_api_base_path(api_base, f"/{container_id}")

# No additional data needed for GET request
data: Dict[str, Any] = {}
Expand Down Expand Up @@ -229,7 +230,7 @@ def transform_container_delete_request(
- DELETE /v1/containers/{container_id}
"""
# Construct the URL for container delete
url = f"{api_base.rstrip('/')}/{container_id}"
url = join_container_api_base_path(api_base, f"/{container_id}")

# No data needed for DELETE request
data: Dict[str, Any] = {}
Expand Down Expand Up @@ -266,7 +267,7 @@ def transform_container_file_list_request(
- GET /v1/containers/{container_id}/files
"""
# Construct the URL for container files
url = f"{api_base.rstrip('/')}/{container_id}/files"
url = join_container_api_base_path(api_base, f"/{container_id}/files")

# Prepare query parameters
params: Dict[str, Any] = {}
Expand Down Expand Up @@ -310,7 +311,9 @@ def transform_container_file_content_request(
- GET /v1/containers/{container_id}/files/{file_id}/content
"""
# Construct the URL for container file content
url = f"{api_base.rstrip('/')}/{container_id}/files/{file_id}/content"
url = join_container_api_base_path(
api_base, f"/{container_id}/files/{file_id}/content"
)

# No query parameters needed
params: Dict[str, Any] = {}
Expand Down
18 changes: 18 additions & 0 deletions litellm/llms/openai/containers/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Shared helpers for OpenAI-compatible container API URL construction."""

import httpx


def join_container_api_base_path(api_base: str, path_suffix: str) -> str:
"""Append ``path_suffix`` to the path of ``api_base``, keeping the query string last.

Azure (and some bases) pass ``api_base`` like
``https://host/openai/v1/containers?api-version=v1``. Naive string concat would
produce ``...?api-version=v1/cntr_...`` which is invalid; this uses ``httpx.URL``
so the result is ``.../containers/cntr_.../files?api-version=v1``.
"""
if not path_suffix.startswith("/"):
path_suffix = f"/{path_suffix}"
parsed = httpx.URL(api_base)
new_path = f"{parsed.path.rstrip('/')}{path_suffix}"
return str(parsed.copy_with(path=new_path))
63 changes: 53 additions & 10 deletions litellm/proxy/container_endpoints/handler_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,13 @@
from litellm.llms.openai.containers.transformation import OpenAIContainerConfig

return OpenAIContainerConfig()
else:
raise ValueError(
f"Container API not supported for provider: {custom_llm_provider}"
)
elif custom_llm_provider in ("azure", "azure_text"):
from litellm.llms.azure.containers.transformation import AzureContainerConfig

return AzureContainerConfig()
raise ValueError(
f"Container API not supported for provider: {custom_llm_provider}"
)


def _create_handler_for_path_params(
Expand Down Expand Up @@ -171,12 +174,23 @@
or "openai"
)

# Get the provider config
container_provider_config = _get_container_provider_config(custom_llm_provider)

# Build litellm_params - credentials are resolved by provider config from env
litellm_params = GenericLiteLLMParams()

# Decode container ID and extract provider info
from litellm.responses.utils import ResponsesAPIRequestUtils
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

decoded = ResponsesAPIRequestUtils._decode_container_id(container_id)
original_container_id = decoded.get("response_id", container_id)

# If container ID has encoded provider info and user didn't explicitly set provider, use it
decoded_provider = decoded.get("custom_llm_provider")
if decoded_provider and custom_llm_provider == "openai":
custom_llm_provider = decoded_provider

# Get the provider config
container_provider_config = _get_container_provider_config(custom_llm_provider)

# Create logging object
logging_obj = Logging(
model="container-file-content",
Expand All @@ -193,7 +207,7 @@

try:
content = await handler.async_container_file_content_handler(
container_id=container_id,
container_id=original_container_id, # Use decoded original ID
file_id=file_id,
container_provider_config=container_provider_config,
litellm_params=litellm_params,
Expand Down Expand Up @@ -267,13 +281,24 @@
if isinstance(file_list, list) and len(file_list) > 0:
data["file"] = file_list[0]

data["container_id"] = container_id

custom_llm_provider = (
get_custom_llm_provider_from_request_headers(request=request)
or get_custom_llm_provider_from_request_query(request=request)
or "openai"
)

# Decode container ID and extract provider info
from litellm.responses.utils import ResponsesAPIRequestUtils
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

decoded = ResponsesAPIRequestUtils._decode_container_id(container_id)
original_container_id = decoded.get("response_id", container_id)

# If container ID has encoded provider info and user didn't explicitly set provider, use it
decoded_provider = decoded.get("custom_llm_provider")
if decoded_provider and custom_llm_provider == "openai":
custom_llm_provider = decoded_provider

data["container_id"] = original_container_id # Use decoded original ID
data["custom_llm_provider"] = custom_llm_provider

processor = ProxyBaseLLMRequestProcessing(data=data)
Expand Down Expand Up @@ -338,6 +363,24 @@
or get_custom_llm_provider_from_request_query(request=request)
or "openai"
)

# Decode container_id if present in path_params
if "container_id" in path_params:
from litellm.responses.utils import ResponsesAPIRequestUtils
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

decoded = ResponsesAPIRequestUtils._decode_container_id(
path_params["container_id"]
)
original_container_id = decoded.get("response_id", path_params["container_id"])

# If container ID has encoded provider info and user didn't explicitly set provider, use it
decoded_provider = decoded.get("custom_llm_provider")
if decoded_provider and custom_llm_provider == "openai":
custom_llm_provider = decoded_provider

# Update path_params with decoded original ID
data["container_id"] = original_container_id

data["custom_llm_provider"] = custom_llm_provider

processor = ProxyBaseLLMRequestProcessing(data=data)
Expand Down
65 changes: 57 additions & 8 deletions litellm/responses/streaming_iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,64 @@ def _process_chunk(self, chunk) -> Optional[ResponsesAPIStreamingResponse]:
)
)

# if "response" in parsed_chunk, then encode litellm specific information like custom_llm_provider
response_object = getattr(openai_responses_api_chunk, "response", None)
if response_object:
response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id(
responses_api_response=response_object,
litellm_metadata=self.litellm_metadata,
custom_llm_provider=self.custom_llm_provider,
# Only when the SSE JSON carries a response body (delta events do not).
# Using getattr(..., "response") alone is unsafe with Mocks: they synthesize a
# truthy child Mock for any attribute, which breaks tests and is wrong on stream.
if "response" in parsed_chunk:
response_object = getattr(
openai_responses_api_chunk, "response", None
)
setattr(openai_responses_api_chunk, "response", response)
if response_object is not None:
response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id(
responses_api_response=response_object,
litellm_metadata=self.litellm_metadata,
custom_llm_provider=self.custom_llm_provider,
)
setattr(openai_responses_api_chunk, "response", response)

# Encode container_id on streaming events so proxy/UI follow-ups route correctly
_event_type = getattr(openai_responses_api_chunk, "type", None)
_stream_model_id = (
self.litellm_metadata.get("model_info", {}).get("id")
if self.litellm_metadata
else None
)
if _event_type in (
ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,
ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
):
_item = getattr(openai_responses_api_chunk, "item", None)
if _item is not None:
ResponsesAPIRequestUtils._encode_container_id_on_output_item(
item=_item,
custom_llm_provider=self.custom_llm_provider,
model_id=_stream_model_id,
)
elif _event_type == ResponsesAPIStreamEvents.OUTPUT_TEXT_ANNOTATION_ADDED:
_annotation = getattr(
openai_responses_api_chunk, "annotation", None
)
if _annotation is not None:
ResponsesAPIRequestUtils._encode_container_id_on_output_item(
item=_annotation,
custom_llm_provider=self.custom_llm_provider,
model_id=_stream_model_id,
)
elif _event_type == ResponsesAPIStreamEvents.CONTENT_PART_DONE:
_part = getattr(openai_responses_api_chunk, "part", None)
if _part is not None:
if isinstance(_part, dict):
ResponsesAPIRequestUtils._encode_container_ids_in_annotations(
_part.get("annotations"),
self.custom_llm_provider,
_stream_model_id,
)
else:
ResponsesAPIRequestUtils._encode_container_ids_in_annotations(
getattr(_part, "annotations", None),
self.custom_llm_provider,
_stream_model_id,
)

# Wrap encrypted_content in streaming events (output_item.added, output_item.done)
if self.litellm_metadata and self.litellm_metadata.get(
Expand Down
Loading
Loading