Merge remote-tracking branch 'origin/main' into litellm_bedrock_converse_foreign_thinking

# Conflicts:
#	tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
This commit is contained in:
mateo-berri 2026-11-05 19:18:03 -08:00
commit 91c871b81f
634 changed files with 26823 additions and 50922 deletions

View file

@ -6,19 +6,12 @@
## Handwritten 1-3 sentence description
<!-- The author writes a plain summary in their own words before requesting review.
Wrap newly AI-written summary text in the make-me-human-readable tags below, including backticks.
The author reviews or rewrites the draft and removes the tags.
When updating an existing PR, preserve the author's wording and removed tags.
Changes elsewhere in the body do not make an unchanged summary an AI draft again.
Add tags again only around newly AI-written replacement summary text, never merely to match this template.
This preserves author review across later updates (2026-11-02, #49779).
<!-- The author writes this in their own words, and it can be left empty. AI agents never write here and leave the
placeholder line below as is, and when updating an existing PR they keep whatever the author wrote. Keep this heading
Say what the PR does for users and why, then anything that keeps it working over time (a sync job, a config someone owns)
No bullets, tables, or code names here. Everything else goes inside the Details block below -->
`<make-me-human-readable>`
<blah>
`</make-me-human-readable>`
[insert handwritten description here]
<details>
<summary>Details</summary>
@ -100,6 +93,7 @@ If you're seeing a delay in your PR being merged, ping the LiteLLM Team on [Slac
Otherwise proof must be fully e2e, no mocks, with real provider calls where applicable. Pytest alone is insufficient. The following format applies to live proof
Show only the latest proof. Before uses the merge base and After the tested tip. Rerun affected QA after behavior changes. Verified neutral diffs may carry proof with the tested SHA, current tip, equivalence reason and focused checks, following AGENTS.md and /qa
Use matching Before/After case headings with numbered commands and observed output. Put shared setup above them. For one case, omit case headings
A reviewer must be able to rerun every case from the body alone, so the shared setup gives the proxy start command, the config.yaml, env var names (never values) and the client code or curl used, all exactly as run. Wrap any block longer than about 20 lines in a collapsed <details> with a one-line summary
### Before (<hash>)

View file

@ -53,7 +53,7 @@ jobs:
if: >-
github.event_name != 'pull_request' ||
github.event.pull_request.head.repo.full_name == github.repository
timeout-minutes: 30
timeout-minutes: 60
permissions:
contents: read
steps:

View file

@ -49,9 +49,9 @@ jobs:
id: compliance
run: |
uv run --no-sync pytest tests/unit/interactions/test_openapi_compliance.py \
--interactions-spec-url=https://ai.google.dev/static/api/interactions.openapi.json \
--interactions-spec-url=https://aistudio.google.com/api-reference/interactions.openapi.json \
--tb=short -vv -p no:rerunfailures -p no:pytest-retry \
--allow-hosts=127.0.0.1,::1,localhost,ai.google.dev
--allow-hosts=127.0.0.1,::1,localhost,ai.google.dev,aistudio.google.com
tracking-issue:
name: tracking-issue

View file

@ -21,7 +21,7 @@ jobs:
pull-requests: read
actions: read
runs-on: ubuntu-latest
timeout-minutes: 20
timeout-minutes: 30
services:
redis:
image: redis@sha256:e2debfb7956fa12c7ddc79d7e645c8cf26b30c99a6e9161ea9bf4171e1668a5f

View file

@ -45,7 +45,7 @@ jobs:
id: rust-bridge-key
if: steps.changes.outputs.decision != 'skip'
env:
RUST_BRIDGE_CACHE_KEY: ${{ runner.os }}-rust-bridge-editable-${{ hashFiles('litellm-rust/Cargo.lock', 'litellm-rust/Cargo.toml', 'litellm-rust/crates/**', 'model_prices_and_context_window.json', 'pyproject.toml') }}
RUST_BRIDGE_CACHE_KEY: ${{ runner.os }}-rust-bridge-editable-${{ hashFiles('litellm-rust/Cargo.lock', 'litellm-rust/Cargo.toml', 'litellm-rust/crates/**', 'model_prices_and_context_window.json', 'pyproject.toml', 'packaging/litellm-proxy/pyproject.toml') }}
run: echo "key=$RUST_BRIDGE_CACHE_KEY" >> "$GITHUB_OUTPUT"
- name: Set up Python
@ -98,6 +98,18 @@ jobs:
mkdir -p rust-bridge-dist/litellm/rust_bridge
cp litellm/rust_bridge/_native.abi3.so rust-bridge-dist/litellm/rust_bridge/_native.abi3.so
- name: Build the gateway wheel once for test shards
if: steps.changes.outputs.decision != 'skip' && steps.rust-bridge-cache.outputs.cache-hit != 'true'
timeout-minutes: 15
working-directory: packaging/litellm-proxy
env:
RUSTC_WRAPPER: sccache
SCCACHE_GHA_ENABLED: "true"
SCCACHE_GHA_VERSION: litellm-ci-v1
SCCACHE_GHA_RW_MODE: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'READ_WRITE' || 'READ_ONLY' }}
CARGO_INCREMENTAL: "0"
run: uv run --no-project --with maturin==1.15.0 maturin build --profile dev --strip --out ../../rust-bridge-dist
- name: Upload Rust bridge artifact
if: steps.changes.outputs.decision != 'skip'
timeout-minutes: 10
@ -1024,7 +1036,7 @@ jobs:
if [ -z "$RUST_BRIDGE_ARTIFACT" ]; then
.github/scripts/uv_sync_with_retries.sh --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra saml --extra extra_proxy --extra proxy-runtime --extra utils
else
.github/scripts/uv_sync_with_retries.sh --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra saml --extra extra_proxy --extra proxy-runtime --extra utils --no-install-project
.github/scripts/uv_sync_with_retries.sh --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra saml --extra extra_proxy --extra proxy-runtime --extra utils --no-install-project --no-install-package litellm-proxy
uv pip install --no-deps --python .venv/bin/python rust-bridge-dist/*.whl
cp rust-bridge-dist/litellm/rust_bridge/_native.abi3.so litellm/rust_bridge/_native.abi3.so
uv run --no-sync python -c "import importlib.metadata; import litellm.rust_bridge._native; print(importlib.metadata.version('litellm'))"
@ -1486,7 +1498,7 @@ jobs:
if [ -z "$RUST_BRIDGE_ARTIFACT" ]; then
.github/scripts/uv_sync_with_retries.sh --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra saml --extra extra_proxy --extra proxy-runtime --extra utils
else
.github/scripts/uv_sync_with_retries.sh --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra saml --extra extra_proxy --extra proxy-runtime --extra utils --no-install-project
.github/scripts/uv_sync_with_retries.sh --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router --extra saml --extra extra_proxy --extra proxy-runtime --extra utils --no-install-project --no-install-package litellm-proxy
uv pip install --no-deps --python .venv/bin/python rust-bridge-dist/*.whl
cp rust-bridge-dist/litellm/rust_bridge/_native.abi3.so litellm/rust_bridge/_native.abi3.so
fi

View file

@ -45,7 +45,7 @@ Run QA proxies with `python litellm/proxy/proxy_cli.py --config litellm/proxy/de
Simple PRs may skip before/after e2e when the full diff is mechanical and focused checks completely prove it, such as #49030 restoring an existing helper name. Trace affected callers and run relevant tests/static checks at the tip. For a bug fix, establish that the regression catches the original defect. Size alone never qualifies. New behavior, API/provider semantics, auth, billing, persistence, concurrency or uncertain integration risk need live e2e. In Screenshots / Proof of Fix, record `E2E exception at <tip SHA>`, scope, rationale, commands and results. Tests count as proof only for this exception. Reassess changed diffs, retain CI/bot gates, and honor explicit e2e requests (2026-10-28, unnecessary live QA for #49030)
For other PRs, proof must show the end user's real flow before and after, with commands and output against a live proxy and real provider calls where applicable. Pytest alone is insufficient. For UI or interactive coding-tool flows, drive that surface and embed before/after screenshots, with URLs, clicks and input fields a reviewer can reproduce
For other PRs, proof must show the end user's real flow before and after, with commands and output against a live proxy and real provider calls where applicable. The body alone must let a reviewer rerun it, with the proxy command, config, env var names and client code exactly as run, and long blocks collapsed in <details>. Pytest alone is insufficient. For UI or interactive coding-tool flows, drive that surface and embed before/after screenshots, with URLs, clicks and input fields a reviewer can reproduce
If you ever write any human-facing text (pull requests, issues, commit messages, discussion posts, github comments, release notes, docs, etc.), always follow these guidelines to sound less AI-y:
- don't use emojis

View file

@ -76,6 +76,7 @@ ENV UV_PROJECT_ENVIRONMENT=/app/.venv \
COPY pyproject.toml uv.lock ./
COPY enterprise/pyproject.toml enterprise/
COPY litellm-proxy-extras/pyproject.toml litellm-proxy-extras/
COPY packaging/litellm-proxy/pyproject.toml packaging/litellm-proxy/
# Install third-party dependencies (cached unless pyproject.toml/uv.lock change)
RUN uv sync --frozen --no-install-project --no-install-workspace --no-default-groups --no-editable \
@ -101,7 +102,8 @@ COPY --from=ui-builder /ui/out/. litellm/proxy/_experimental/out/
RUN sed -i 's/\r$//' docker/build_admin_ui.sh && chmod +x docker/build_admin_ui.sh && ./docker/build_admin_ui.sh
# Install project and workspace packages (fast - deps already cached)
RUN uv sync --frozen --no-default-groups --no-editable \
RUN uv build --package litellm-proxy --wheel --out-dir /wheels
RUN uv sync --frozen --no-install-package litellm-proxy --no-default-groups --no-editable \
--extra proxy \
--extra proxy-runtime \
--group admin-mcp \
@ -111,6 +113,8 @@ RUN uv sync --frozen --no-default-groups --no-editable \
--extra bedrock-realtime \
--python python3.13
RUN uv pip install --python /app/.venv/bin/python --no-deps /wheels/litellm_proxy-*.whl
RUN HOME=/opt/prisma XDG_CACHE_HOME=/opt/prisma/.cache PRISMA_BINARY_CACHE_DIR=/opt/prisma/binaries \
npm_config_cache=/root/.npm \
prisma generate --schema=./schema.prisma

View file

@ -74,6 +74,7 @@ ENV UV_PROJECT_ENVIRONMENT=/app/.venv \
COPY pyproject.toml uv.lock ./
COPY enterprise/pyproject.toml enterprise/
COPY litellm-proxy-extras/pyproject.toml litellm-proxy-extras/
COPY packaging/litellm-proxy/pyproject.toml packaging/litellm-proxy/
# Install third-party dependencies (cached unless pyproject.toml/uv.lock change)
RUN uv sync --frozen --no-install-project --no-install-workspace --no-default-groups --no-editable \
@ -99,7 +100,8 @@ COPY --from=ui-builder /ui/out/. litellm/proxy/_experimental/out/
RUN sed -i 's/\r$//' docker/build_admin_ui.sh && chmod +x docker/build_admin_ui.sh && ./docker/build_admin_ui.sh
# Install project and workspace packages (fast - deps already cached)
RUN uv sync --frozen --no-default-groups --no-editable \
RUN uv build --package litellm-proxy --wheel --out-dir /wheels
RUN uv sync --frozen --no-install-package litellm-proxy --no-default-groups --no-editable \
--extra proxy \
--extra proxy-runtime \
--group admin-mcp \
@ -109,6 +111,8 @@ RUN uv sync --frozen --no-default-groups --no-editable \
--extra bedrock-realtime \
--python python3.13
RUN uv pip install --python /app/.venv/bin/python --no-deps /wheels/litellm_proxy-*.whl
RUN HOME=/opt/prisma XDG_CACHE_HOME=/opt/prisma/.cache PRISMA_BINARY_CACHE_DIR=/opt/prisma/binaries \
npm_config_cache=/root/.npm \
prisma generate --schema=./schema.prisma

View file

@ -8,7 +8,6 @@ import re
from collections.abc import Callable, Mapping, Sequence
from dataclasses import replace as dataclasses_replace
from datetime import datetime, timedelta
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, List, Literal, Optional, Protocol, Tuple, cast
from pydantic import TypeAdapter, ValidationError
@ -766,7 +765,6 @@ class CheckBatchCost:
credentials: Final = self.llm_router.registry().credentials(model_id, form="with_provider") or {}
_file_content = await afile_content(
file_id=cast(str, raw_output_file_id),
_litellm_internal_model_credentials=MappingProxyType(dict(credentials)),
**cast(FileContentCallOptions, credentials),
)
@ -867,10 +865,7 @@ class CheckBatchCost:
error_file_failed_requests: Final = await count_error_file_failed_requests(
response,
custom_llm_provider=batch_file_provider,
litellm_params={
**credentials,
"_litellm_internal_model_credentials": MappingProxyType(dict(credentials)),
},
litellm_params=credentials,
)
batch_result: Final = (
output_file_result
@ -1029,11 +1024,7 @@ class CheckBatchCost:
custom_llm_provider=deployment_info.litellm_params.custom_llm_provider,
)
cost_provider: Final = cast(BatchFileProvider, llm_provider)
credentials: Final = self.llm_router.registry().credentials(model_id, form="with_provider") or {}
file_access: Final = {
**credentials,
"_litellm_internal_model_credentials": MappingProxyType(dict(credentials)),
}
file_access: Final = self.llm_router.registry().credentials(model_id, form="with_provider") or {}
output_content: Final = (
await fetch_batch_managed_file_content(
response.output_file_id, custom_llm_provider=cost_provider, litellm_params=file_access

View file

@ -127,7 +127,6 @@ class _ManagedFileRetrieve(Protocol):
self,
*,
file_id: str,
_litellm_internal_model_credentials: Mapping[str, object] | None = None,
**kwargs: Unpack[FileRetrieveCallOptions],
) -> OpenAIFileObject: ...
@ -400,7 +399,7 @@ class _RouterFileCallKwargs(TypedDict, total=False):
_MODEL_FILE_ID_MAPPING: Final = TypeAdapter(dict[str, str])
_FILE_UPLOAD_ONLY_FIELDS: Final = frozenset({"file", "purpose", "expires_after", "extra_body"})
_FILE_DELETE_RESERVED_FIELDS: Final = frozenset({"model", "file_id", "_litellm_internal_model_credentials"})
_FILE_DELETE_RESERVED_FIELDS: Final = frozenset({"model", "file_id"})
@dataclass(frozen=True, slots=True)
@ -459,15 +458,7 @@ async def _delete_provider_file(
provider_file_id: str,
request_data: Mapping[str, object],
) -> None:
credentials: Final = llm_router.registry().credentials(model_id, form="with_provider")
delete_data: Final = {
**{k: v for k, v in request_data.items() if k not in _FILE_DELETE_RESERVED_FIELDS},
**(
{"_litellm_internal_model_credentials": MappingProxyType(dict(credentials))}
if credentials is not None
else {}
),
}
delete_data: Final = {k: v for k, v in request_data.items() if k not in _FILE_DELETE_RESERVED_FIELDS}
await llm_router.afile_delete(
model=model_id,
file_id=provider_file_id,
@ -1160,7 +1151,6 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
*,
provider_file_id: str,
call_options: Mapping[str, object],
internal_model_credentials: Mapping[str, object] | None = None,
) -> OpenAIFileObject:
"""Retrieve provider file details with transient retries and SDK retries disabled."""
retrieve_file: Final = cast(_ManagedFileRetrieve, litellm.afile_retrieve)
@ -1172,14 +1162,8 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
if attempt > 0:
await self._sleep(_PROVIDER_FILE_RETRIEVE_RETRY_DELAYS_SECONDS[attempt - 1])
try:
if internal_model_credentials is None:
return await retrieve_file(
file_id=provider_file_id,
**retrieve_options,
)
return await retrieve_file(
file_id=provider_file_id,
_litellm_internal_model_credentials=MappingProxyType(dict(internal_model_credentials)),
**retrieve_options,
)
except Exception as error:
@ -1221,7 +1205,6 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
self._afile_retrieve_with_retries(
provider_file_id=provider_file_id,
call_options=router_credentials,
internal_model_credentials=router_credentials,
),
timeout=BATCH_OUTPUT_FILE_LOOKUP_TIMEOUT_SECONDS,
)
@ -2866,15 +2849,6 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
exception_dict = {}
for model_id, provider_file_id in specific_model_file_id_mapping.items():
try:
# Cloud-storage providers (e.g. Bedrock S3) validate file ids
# against the deployment's configured bucket, which they only
# trust from this immutable server-side snapshot, never from
# request params.
credentials = llm_router.registry().credentials(model_id, form="with_provider")
if credentials is not None:
data["_litellm_internal_model_credentials"] = cast(Dict, MappingProxyType(dict(credentials)))
else:
data.pop("_litellm_internal_model_credentials", None)
return cast(
HttpxBinaryResponseContent,
await llm_router.afile_content(

View file

@ -41,10 +41,14 @@ COPY pyproject.toml README.md rust-toolchain.toml ./
COPY .cargo ./.cargo
COPY litellm-rust ./litellm-rust
COPY model_prices_and_context_window.json ./
COPY packaging/litellm-proxy/pyproject.toml packaging/litellm-proxy/
RUN --mount=type=cache,target=/root/.cache/uv \
mkdir -p litellm/rust_bridge /wheels && \
touch litellm/__init__.py litellm/rust_bridge/__init__.py && \
uvx --python python3.13 --from maturin==1.15.0 --with puccinialin==0.1.14 \
python -c "import maturin; maturin.build_wheel('/wheels')" && \
cd packaging/litellm-proxy && \
uvx --python python3.13 --from maturin==1.15.0 --with puccinialin==0.1.14 \
python -c "import maturin; maturin.build_wheel('/wheels')"
@ -85,6 +89,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=enterprise/pyproject.toml,target=enterprise/pyproject.toml \
--mount=type=bind,source=litellm-proxy-extras/pyproject.toml,target=litellm-proxy-extras/pyproject.toml \
--mount=type=bind,source=packaging/litellm-proxy/pyproject.toml,target=packaging/litellm-proxy/pyproject.toml \
uv sync --frozen --no-install-project --no-install-workspace --no-default-groups --no-editable \
--extra proxy \
--extra proxy-runtime \
@ -98,7 +103,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --frozen --no-install-project --no-default-groups --no-editable \
uv sync --frozen --no-install-project --no-install-package litellm-proxy --no-default-groups --no-editable \
--extra proxy \
--extra proxy-runtime \
--group admin-mcp \
@ -108,7 +113,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
--python python3.13
RUN --mount=type=bind,from=rust-native,source=/wheels,target=/wheels \
uv pip install --python /app/.venv/bin/python --no-deps /wheels/litellm-*.whl
uv pip install --python /app/.venv/bin/python --no-deps /wheels/litellm-*.whl /wheels/litellm_proxy-*.whl
# PYTHONPATH=/app makes the source tree shadow the installed package, so the
# compiled Rust extension must live next to the source or it is never imported.

View file

@ -7,7 +7,7 @@ metadata:
# Rust gateway
`crates/gateway` mounts endpoint routers and serves the listener. `crates/gateway-inference`, `gateway-mcp` and `gateway-ui` own their endpoints, `gateway-auth` is the inbound authentication middleware and `gateway-management` holds management logic that has no router yet. A crate's `AGENTS.md`, where it has one, says what belongs in it. Read the reference for the part you are touching
`crates/gateway` mounts endpoint routers and serves the listener. `crates/gateway-inference`, `gateway-mcp` and `gateway-ui` own their endpoints, `gateway-auth` is the inbound authentication middleware and `gateway-management` holds management logic that has no router yet. `gateway-forward` is the reverse proxy that relays every request to the Python proxy and has no routes of its own. A crate's `AGENTS.md`, where it has one, says what belongs in it. Read the reference for the part you are touching
- [surfaces](references/surfaces.md)
- Each API surface mirrors the envelope the Python proxy returns there, so the shapes differ on purpose

View file

@ -547,7 +547,7 @@ dependencies = [
"http 1.4.2",
"http-body 0.4.6",
"hyper 0.14.32",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-rustls 0.24.2",
"hyper-rustls 0.27.9",
"hyper-util",
@ -736,7 +736,7 @@ dependencies = [
"http 1.4.2",
"http-body 1.1.0",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-util",
"itoa",
"matchit",
@ -1000,7 +1000,7 @@ dependencies = [
"home",
"http 1.4.2",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-named-pipe",
"hyper-rustls 0.27.9",
"hyper-util",
@ -2255,7 +2255,7 @@ dependencies = [
"chrono",
"http 1.4.2",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-rustls 0.27.9",
"hyper-util",
"ring",
@ -2391,7 +2391,7 @@ dependencies = [
"http 1.4.2",
"http-body 1.1.0",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"lazy_static",
"opentelemetry",
"opentelemetry-semantic-conventions",
@ -2833,9 +2833,9 @@ dependencies = [
[[package]]
name = "hyper"
version = "1.10.1"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
dependencies = [
"atomic-waker",
"bytes",
@ -2860,7 +2860,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fab3637d6b04a8037af8a266fdf6cf92ea957e8c53981a2bf6136572531025bf"
dependencies = [
"hex",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-util",
"pin-project-lite",
"tokio",
@ -2889,7 +2889,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
dependencies = [
"http 1.4.2",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-util",
"rustls 0.23.42",
"rustls-native-certs",
@ -2904,7 +2904,7 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"
dependencies = [
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-util",
"pin-project-lite",
"tokio",
@ -2923,7 +2923,7 @@ dependencies = [
"futures-util",
"http 1.4.2",
"http-body 1.1.0",
"hyper 1.10.1",
"hyper 1.12.0",
"ipnet",
"libc",
"percent-encoding",
@ -2942,7 +2942,7 @@ checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7"
dependencies = [
"hex",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-util",
"pin-project-lite",
"tokio",
@ -3769,6 +3769,7 @@ dependencies = [
"litellm-config",
"litellm-error",
"litellm-gateway-auth",
"litellm-gateway-forward",
"litellm-gateway-inference",
"litellm-gateway-mcp",
"litellm-gateway-ui",
@ -3815,6 +3816,29 @@ dependencies = [
"veil",
]
[[package]]
name = "litellm-gateway-forward"
version = "0.1.0"
dependencies = [
"axum",
"bytes",
"envy",
"futures-util",
"http-body-util",
"httparse",
"hyper 1.12.0",
"hyper-util",
"proptest",
"rstest",
"serde",
"thiserror 2.0.19",
"tokio",
"tokio-tungstenite",
"tokio-util",
"tower-service",
"tracing",
]
[[package]]
name = "litellm-gateway-inference"
version = "0.1.0"
@ -6031,7 +6055,7 @@ dependencies = [
"http 1.4.2",
"http-body 1.1.0",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-rustls 0.27.9",
"hyper-util",
"js-sys",
@ -7512,6 +7536,7 @@ dependencies = [
"bytes",
"futures-core",
"futures-sink",
"futures-util",
"pin-project-lite",
"tokio",
]
@ -7591,7 +7616,7 @@ dependencies = [
"http 1.4.2",
"http-body 1.1.0",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-timeout",
"hyper-util",
"percent-encoding",
@ -8167,9 +8192,9 @@ dependencies = [
[[package]]
name = "want"
version = "0.3.1"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
dependencies = [
"try-lock",
]
@ -8551,7 +8576,7 @@ dependencies = [
"futures",
"http 1.4.2",
"http-body-util",
"hyper 1.10.1",
"hyper 1.12.0",
"hyper-util",
"log",
"once_cell",

View file

@ -26,6 +26,7 @@ litellm-inference-ocr = { path = "crates/inference-ocr" }
litellm-inference-testing = { path = "crates/inference-testing" }
litellm-gateway-mcp = { path = "crates/gateway-mcp" }
litellm-gateway = { path = "crates/gateway" }
litellm-gateway-forward = { path = "crates/gateway-forward" }
litellm-gateway-inference = { path = "crates/gateway-inference" }
litellm-gateway-auth = { path = "crates/gateway-auth" }
litellm-gateway-management = { path = "crates/gateway-management" }

View file

@ -0,0 +1,37 @@
# Forwarding gateway
`Forward` is a reverse proxy in front of the Python proxy on loopback. Python must see each request as if the client had connected to it directly, because every Python route (inference, MCP, pass-through, UI, WebSocket) is served behind it without Rust knowing which one it is
- Serve HTTP/1.1 only, as uvicorn does. The supervisor never puts Rust in front of a Python server that speaks HTTP/2
- Never branch on a route or path. A behavior one endpoint needs is a protocol behavior every endpoint gets
- Forward the method, request target, headers, and body byte for byte within the [URL contract](FORWARDING.md#url-fragments-and-literal-hashes). An unescaped `#` starts a fragment and is omitted with everything after it, while `%23` is preserved. Only drop hop-by-hop headers (RFC 9110 section 7.6.1) and set `x-litellm-rust-peer`, which replaces any client copy
- Stream both bodies. Never buffer, cap, or time out a body, since uploads and provider streams have no upper bound
- A client disconnect closes the upstream connection at every stage, because that is how Python learns to stop a provider stream
- An upstream that dies mid-response fails the client body. Never end it cleanly, or SSE clients treat a truncated stream as complete
- Never invent a Host. Python builds absolute URLs from it, so a missing one must never become the private upstream address
- A request Python could not have received unchanged (HTTP/1.1 without Host, a transfer coding other than chunked, a target without a path) gets the status uvicorn would have given, from Rust
- Pooled upstream connections are retired well before Python's keep-alive timeout, so a request never lands on a connection Python is closing
- Idle client connections close after Python's keep-alive timeout, as uvicorn closed them, so a client that vanishes cannot hold a socket forever. Only the wait for the next request is timed, never an exchange in progress
- WebSocket is the one protocol switch Python serves. Upgrades are relayed as raw bytes after the 101 and drained on shutdown
## Layout
Every forwarding decision has one home. `rewrite.rs` owns what Python and the client receive, as pure functions over requests and responses. `Rejection` in `error.rs` is the only place that picks a status for a request Rust answers itself. `settings.rs` parses the environment into typed values, so an `Upstream` is a loopback origin by construction. `server.rs` accepts client connections and owns their timeouts, since `axum::serve` exposes none, and `connections.rs` tracks every connection and relay for shutdown. `forward.rs` and `websocket.rs` only move requests, bodies and upgraded connections and never touch a header themselves. `connector.rs` keeps hyper reading Python's answer after Python stops reading the request
## Environment
`Settings` reads only these variables, and only when `LITELLM_FORWARD_UPSTREAM` is set. The Python supervisor in `litellm/proxy/rust_forward/` sets every one of them from the values Python actually runs with, so all of them are required and a missing or invalid one fails startup naming it. The crate never reads Python's own settings (`HOST`, `PORT`, `KEEPALIVE_TIMEOUT`, `GRACEFUL_SHUTDOWN_TIMEOUT`) and keeps no copy of Python's defaults, since Python can get those values from CLI flags the environment never shows
| Variable | Meaning |
|---|---|
| `LITELLM_FORWARD_UPSTREAM` | Python's loopback origin, e.g. `http://127.0.0.1:53211` |
| `LITELLM_FORWARD_HOST` | public bind host |
| `LITELLM_FORWARD_PORT` | public bind port |
| `LITELLM_FORWARD_UPSTREAM_KEEPALIVE` | seconds uvicorn keeps an idle connection open. Pooled connections are retired at half of it, and idle client connections are closed after it |
| `LITELLM_FORWARD_SHUTDOWN_DRAIN` | seconds to drain on shutdown, already including Python's graceful timeout and teardown headroom |
## Tests
Test through real sockets with `tests/support`, never `oneshot`. `Gateway` runs the forwarder on a listener like production, `recording` is a well-behaved upstream that captures what Python would receive, and `raw_upstream` and `Raw` drive bytes by hand for framing, timing and disconnects a real server would not produce. Waits measured in minutes use paused tokio time instead of real sleeps
The forwarder sees HTTP/1.1 messages, not routes, so the tests are split into one file per traffic shape uvicorn can emit: `exchange` (plain request and response), `framing` (requests whose framing a parser could read two ways), `slow_head` (minutes before response headers), `stream` (incremental response bodies), `idle_stream` (long-lived streams that go quiet), `upload`, `download`, `websocket`, `client_identity`, `lifecycle` (disconnects, pooling, idle timeouts, shutdown) and `roundtrip` (the forwarding invariant for generated messages). A new route never gets its own test. Add its behavior to the shape it already has, and when it needs a wire behavior none of the files covers, add a new shape file for it

View file

@ -0,0 +1,30 @@
[package]
name = "litellm-gateway-forward"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
axum.workspace = true
envy = "0.4.2"
hyper = { version = "1.12.0", features = ["http1", "server"] }
hyper-util = { workspace = true, features = ["client-legacy", "http1", "tokio"] }
serde.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["io-util"] }
tokio-util = { version = "0.7", features = ["rt"] }
tower-service = "0.3.3"
tracing.workspace = true
[dev-dependencies]
bytes.workspace = true
futures-util.workspace = true
http-body-util = "0.1"
httparse = "1"
hyper = { version = "1.12.0", features = ["client"] }
proptest.workspace = true
rstest.workspace = true
tokio = { workspace = true, features = ["io-util", "sync", "test-util"] }
tokio-tungstenite.workspace = true

View file

@ -0,0 +1,31 @@
# Python forwarding compatibility
The opt-in forwarding gateway serves HTTP/1.1 and WebSockets in front of Python. Python still owns every route and policy. Its protocol contract and environment settings are in [AGENTS.md](AGENTS.md)
## URL fragments and literal hashes
The gateway follows Hyper's `http::Uri` parsing. If a raw client sends an unescaped `#` in the request target, only the path and query before the first `#` reach Python. For example, `/v1/files?purpose=batch#retry&limit=1` becomes `/v1/files?purpose=batch`, and `/gemini/v1beta/files/a#b?key=k` becomes `/gemini/v1beta/files/a`
This is accepted behavior because `#` starts a URL fragment, which is separated before dereferencing ([RFC 3986 section 3.5](https://www.rfc-editor.org/rfc/rfc3986.html#section-3.5)). HTTP origin-form contains only the path and optional query, not a fragment ([RFC 9112 section 3.2.1](https://www.rfc-editor.org/rfc/rfc9112.html#section-3.2.1)). Browsers and URL-based clients omit the fragment before sending the request, so UI hash routing is unaffected
A literal hash in path or query data must be encoded as `%23`, which the gateway forwards unchanged. Direct Python with h11 also accepts unescaped hashes as data, but that permissive raw-target behavior is outside this URL contract. Active socket tests cover both [fragment omission](tests/exchange.rs) and [encoded-hash preservation](tests/exchange.rs)
## Known differences from uvicorn with h11
These cases remain executable as ignored socket tests. They are not passing parity checks
| Input | Direct Python | Through Rust | Regression test |
|---|---|---|---|
| Header after a removed hop-by-hop field | Keeps the remaining header order | `HeaderMap::remove` can move a later header | [dropping_a_hop_by_hop_header_keeps_the_others_in_order](tests/exchange.rs) |
| Repeated header names interleaved with other names | Keeps the interleaving | Groups values by name, keeping their order within that name | [interleaved_repeated_headers_reach_python_interleaved](tests/exchange.rs) |
| Obsolete folded header, such as `x-a: b\r\n c` | Unfolds to `b c` | Rejects with 400 | [a_folded_header_reaches_python_unfolded](tests/exchange.rs) |
| Identical Content-Length list, such as `7, 7` | Accepts length 7 | Rejects with 400 | [a_content_length_list_of_one_value_reaches_python](tests/framing.rs) |
| HTTP/1.0 request with chunked transfer coding | Decodes the body | Rejects with 400 | [an_http10_chunked_upload_reaches_python](tests/framing.rs) |
Clients can avoid the parser rejections by sending unfolded headers, one Content-Length value, and HTTP/1.1 for chunked uploads. Integrations must not depend on header ordering across different field names
Run `cargo test -p litellm-gateway-forward --test exchange --test framing -- --ignored` from this directory to reproduce the differences
## Connection header handling
The gateway strips standard hop-by-hop fields and fields named by Connection, except routing, representation, credential, forwarding, and WebSocket handshake headers. A client cannot nominate those end-to-end fields for removal. The private `x-litellm-rust-peer` always replaces any client-supplied copy

View file

@ -0,0 +1,58 @@
use tokio_util::{
sync::{CancellationToken, DropGuard},
task::TaskTracker,
};
/// Every client connection and WebSocket relay the gateway runs, so shutdown can wait for them
/// and then close whatever outlives the drain.
#[derive(Clone, Default)]
pub(crate) struct Connections {
tasks: TaskTracker,
draining: CancellationToken,
closed: CancellationToken,
}
impl Connections {
/// Runs `work` until it finishes or the gateway closes every connection.
pub fn spawn(&self, work: impl Future<Output = ()> + Send + 'static) {
let closed = self.closed.clone();
self.tasks.spawn(async move {
tokio::select! {
() = closed.cancelled() => {}
() = work => {}
}
});
}
pub fn begin_shutdown(&self) {
self.draining.cancel();
}
pub async fn draining(&self) {
self.draining.cancelled().await;
}
pub fn is_draining(&self) -> bool {
self.draining.is_cancelled()
}
pub async fn until_closed<T>(&self, future: impl Future<Output = T>) -> Option<T> {
tokio::select! {
() = self.closed.cancelled() => None,
output = future => Some(output),
}
}
pub fn close(&self) {
self.closed.cancel();
}
pub fn close_on_drop(&self) -> DropGuard {
self.closed.clone().drop_guard()
}
pub async fn wait(&self) {
self.tasks.close();
self.tasks.wait().await;
}
}

View file

@ -0,0 +1,122 @@
use std::{
io::{self, IoSlice},
pin::Pin,
task::{Context, Poll, ready},
};
use axum::http::Uri;
use hyper::rt::{Read, ReadBufCursor, Write};
use hyper_util::{
client::legacy::connect::{Connected, Connection, HttpConnector},
rt::TokioIo,
};
use tokio::net::TcpStream;
/// Connects to Python like `HttpConnector`, but keeps hyper reading Python's answer after Python
/// stops reading the request. uvicorn rejects an upload (413, 401) as soon as it reads the head
/// and closes with the body unread, so writing the rest fails, and hyper would fail the request
/// and drop the answer it already received. Like curl and httpcore, the forwarder discards the
/// rest of the request instead and reads on. A connection that never answered still fails, on the
/// read, and no request is ever sent twice.
#[derive(Clone)]
pub(crate) struct Connector(pub HttpConnector);
impl tower_service::Service<Uri> for Connector {
type Response = AnswerAfterRefusal;
type Error = <HttpConnector as tower_service::Service<Uri>>::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.poll_ready(context)
}
fn call(&mut self, uri: Uri) -> Self::Future {
let connecting = self.0.call(uri);
Box::pin(async move {
Ok(AnswerAfterRefusal {
stream: connecting.await?,
refused: false,
})
})
}
}
pub(crate) struct AnswerAfterRefusal {
stream: TokioIo<TcpStream>,
refused: bool,
}
impl AnswerAfterRefusal {
fn written(&mut self, written: io::Result<usize>, length: usize) -> io::Result<usize> {
match written {
Err(error)
if matches!(
error.kind(),
io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
) =>
{
self.refused = true;
Ok(length)
}
written => written,
}
}
}
impl Read for AnswerAfterRefusal {
fn poll_read(
mut self: Pin<&mut Self>,
context: &mut Context<'_>,
buffer: ReadBufCursor<'_>,
) -> Poll<io::Result<()>> {
Pin::new(&mut self.stream).poll_read(context, buffer)
}
}
impl Write for AnswerAfterRefusal {
fn poll_write(
mut self: Pin<&mut Self>,
context: &mut Context<'_>,
buffer: &[u8],
) -> Poll<io::Result<usize>> {
if self.refused {
return Poll::Ready(Ok(buffer.len()));
}
let written = ready!(Pin::new(&mut self.stream).poll_write(context, buffer));
Poll::Ready(self.written(written, buffer.len()))
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
context: &mut Context<'_>,
buffers: &[IoSlice<'_>],
) -> Poll<io::Result<usize>> {
let length = buffers.iter().map(|buffer| buffer.len()).sum();
if self.refused {
return Poll::Ready(Ok(length));
}
let written = ready!(Pin::new(&mut self.stream).poll_write_vectored(context, buffers));
Poll::Ready(self.written(written, length))
}
fn is_write_vectored(&self) -> bool {
self.stream.is_write_vectored()
}
fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
if self.refused {
return Poll::Ready(Ok(()));
}
Pin::new(&mut self.stream).poll_flush(context)
}
fn poll_shutdown(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.stream).poll_shutdown(context)
}
}
impl Connection for AnswerAfterRefusal {
fn connected(&self) -> Connected {
self.stream.connected()
}
}

View file

@ -0,0 +1,91 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid forwarding upstream URI")]
UpstreamUri(#[source] axum::http::uri::InvalidUri),
#[error(
"LITELLM_FORWARD_UPSTREAM must be a loopback IPv4 http origin without a path, query or credentials"
)]
Upstream,
#[error("{0} must be set in forward mode")]
MissingSetting(String),
#[error("invalid forwarding setting: {0}")]
InvalidSetting(String),
#[error("forwarding gateway I/O failed: {0}")]
Io(#[from] std::io::Error),
}
/// Why a request got an answer from Rust instead of from Python.
#[derive(Debug, thiserror::Error)]
pub(crate) enum Rejection {
#[error("HTTP/1.1 request without a Host header")]
MissingHost,
#[error("request target has no path to forward")]
NoPath,
#[error("request uses a transfer coding other than chunked")]
UnsupportedTransferCoding,
#[error("client request body failed: {0}")]
ClientBody(#[source] hyper_util::client::legacy::Error),
#[error("python proxy unreachable: {0}")]
Unreachable(#[source] hyper_util::client::legacy::Error),
#[error("python proxy switched protocols without being asked to")]
UnrequestedUpgrade,
#[error("python proxy websocket upgrade failed: {0}")]
UpgradeFailed(#[source] hyper::Error),
#[error("forwarding gateway is shutting down")]
ShuttingDown,
#[error("could not build the request for the python proxy")]
Internal,
}
impl Rejection {
/// A client body that ends early or breaks its framing fails the upstream request too, but
/// the fault is the client's, not Python's.
pub fn from_upstream(error: hyper_util::client::legacy::Error) -> Self {
let client_body = std::error::Error::source(&error)
.and_then(|source| source.downcast_ref::<hyper::Error>())
.is_some_and(hyper::Error::is_user);
match client_body {
true => Self::ClientBody(error),
false => Self::Unreachable(error),
}
}
fn status(&self) -> StatusCode {
match self {
Self::MissingHost
| Self::NoPath
| Self::UnsupportedTransferCoding
| Self::ClientBody(_) => StatusCode::BAD_REQUEST,
Self::Unreachable(_) | Self::UnrequestedUpgrade | Self::UpgradeFailed(_) => {
StatusCode::BAD_GATEWAY
}
Self::ShuttingDown => StatusCode::SERVICE_UNAVAILABLE,
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn is_gateway_fault(&self) -> bool {
matches!(
self,
Self::Unreachable(_)
| Self::UnrequestedUpgrade
| Self::UpgradeFailed(_)
| Self::Internal
)
}
}
impl IntoResponse for Rejection {
fn into_response(self) -> Response {
match self.is_gateway_fault() {
true => tracing::warn!(error = %self, "request not forwarded"),
false => tracing::debug!(error = %self, "request not forwarded"),
}
self.status().into_response()
}
}

View file

@ -0,0 +1,169 @@
use std::{
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use axum::{
body::Body,
extract::Request,
http::{StatusCode, Uri},
response::{IntoResponse, Response},
};
use hyper::body::{Frame, Incoming, SizeHint};
use hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::{TokioExecutor, TokioTimer},
};
use tokio::net::TcpListener;
use crate::{
Rejection, Upstream, connections::Connections, connector::Connector, rewrite, server,
server::ClientSocket, websocket,
};
// h11 counts no headers and only caps a head at 16 KiB, so it accepts as many headers as fit in
// that many shortest lines (`a:\r\n`). Python copies every provider header into its response
// too, so hyper's default of 100 would turn ordinary traffic into 431s and 502s.
pub(crate) const MAX_HEADERS: usize = 16 * 1024 / b"a:\r\n".len();
#[derive(Clone)]
pub struct Forward {
upstream: Uri,
client: Client<Connector, Body>,
connections: Connections,
keepalive: Duration,
}
impl Forward {
/// `upstream_keepalive` is how long the upstream keeps an idle connection open. Pooled
/// connections are dropped well before that, so a request never lands on one it is closing,
/// and idle client connections are closed after it, as uvicorn did.
pub fn new(upstream: &Upstream, upstream_keepalive: Duration) -> Self {
let mut connector = HttpConnector::new();
connector.set_nodelay(true);
let client = Client::builder(TokioExecutor::new())
.http1_max_headers(MAX_HEADERS)
.pool_timer(TokioTimer::new())
.pool_idle_timeout(upstream_keepalive / 2)
.set_host(false)
.build(Connector(connector));
Self {
upstream: upstream.uri().clone(),
client,
connections: Connections::default(),
keepalive: upstream_keepalive,
}
}
/// Serves until `shutdown` resolves, then lets open requests and WebSockets finish for up to
/// `drain` before closing whatever is left. Python shuts down alongside and ends long streams
/// itself, so `drain` only backstops a Python that never does.
pub async fn serve(
self,
listener: TcpListener,
shutdown: impl Future<Output = ()>,
drain: Duration,
) {
server::serve(self, listener, shutdown, drain).await;
}
pub(crate) fn connections(&self) -> &Connections {
&self.connections
}
pub(crate) fn keepalive(&self) -> Duration {
self.keepalive
}
pub(crate) async fn handle(&self, client: ClientSocket, request: Request) -> Response {
self.forward(client, request)
.await
.unwrap_or_else(IntoResponse::into_response)
}
async fn forward(
&self,
client: ClientSocket,
mut request: Request,
) -> Result<Response, Rejection> {
if let Some(downstream) = websocket::take_handshake(&self.connections, &mut request)? {
return self.forward_websocket(client, request, downstream).await;
}
let request = rewrite::upstream_request(request, &self.upstream, client, false)?;
let response = self
.client
.request(request)
.await
.map_err(Rejection::from_upstream)?;
http_response(response)
}
async fn forward_websocket(
&self,
client: ClientSocket,
request: Request,
downstream: hyper::upgrade::OnUpgrade,
) -> Result<Response, Rejection> {
let request = rewrite::upstream_request(request, &self.upstream, client, true)?;
let response = self
.connections
.until_closed(self.client.request(request))
.await
.ok_or(Rejection::ShuttingDown)?
.map_err(Rejection::from_upstream)?;
if response.status() == StatusCode::SWITCHING_PROTOCOLS {
return websocket::switch(&self.connections, downstream, response).await;
}
http_response(response)
}
}
fn http_response(response: Response<Incoming>) -> Result<Response, Rejection> {
if response.status() == StatusCode::SWITCHING_PROTOCOLS {
return Err(Rejection::UnrequestedUpgrade);
}
Ok(
rewrite::downstream_response(response)
.map(|body| Body::new(Relayed { body, failed: None })),
)
}
/// Python's response body on its way to the client.
struct Relayed {
body: Incoming,
failed: Option<hyper::Error>,
}
impl hyper::body::Body for Relayed {
type Data = <Incoming as hyper::body::Body>::Data;
type Error = hyper::Error;
// hyper aborts a client connection whose response body fails without flushing the head it
// buffered, so a head Python sent right before dying would never arrive and SDKs would retry
// a request Python already ran. Holding the error for one poll lets hyper flush the head.
fn poll_frame(
mut self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
if let Some(error) = self.failed.take() {
return Poll::Ready(Some(Err(error)));
}
match Pin::new(&mut self.body).poll_frame(context) {
Poll::Ready(Some(Err(error))) => {
self.failed = Some(error);
context.waker().wake_by_ref();
Poll::Pending
}
frame => frame,
}
}
fn is_end_stream(&self) -> bool {
self.failed.is_none() && self.body.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.body.size_hint()
}
}

View file

@ -0,0 +1,29 @@
mod connections;
mod connector;
mod error;
mod forward;
mod rewrite;
mod server;
mod settings;
mod websocket;
pub use error::Error;
pub(crate) use error::Rejection;
pub use forward::Forward;
pub use rewrite::PEER_HEADER;
pub use settings::{Settings, Upstream};
/// Binds the public listener and forwards to Python until `shutdown` resolves, then drains for
/// `settings.shutdown_drain`.
pub async fn run(
settings: Settings,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), Error> {
let forward = Forward::new(&settings.upstream, settings.upstream_keepalive);
let listener = tokio::net::TcpListener::bind((settings.host.as_str(), settings.port)).await?;
tracing::info!(address = %listener.local_addr()?, "forwarding gateway listening");
forward
.serve(listener, shutdown, settings.shutdown_drain)
.await;
Ok(())
}

View file

@ -0,0 +1,161 @@
use axum::{
body::HttpBody,
extract::Request,
http::{HeaderMap, HeaderValue, Response, Uri, Version, header},
};
use crate::{Rejection, server::ClientSocket};
pub const PEER_HEADER: &str = "x-litellm-rust-peer";
/// The request Python receives: the client's method, target, headers and body unchanged, sent to
/// `upstream` over HTTP/1.1 without the client connection's own headers, plus the client's TCP
/// peer in `PEER_HEADER`, which replaces any copy the client sent.
pub(crate) fn upstream_request(
mut request: Request,
upstream: &Uri,
client: ClientSocket,
websocket: bool,
) -> Result<Request, Rejection> {
if !only_chunked(request.headers()) {
return Err(Rejection::UnsupportedTransferCoding);
}
let path_and_query = request
.uri()
.path_and_query()
.cloned()
.ok_or(Rejection::NoPath)?;
if let Some(host) = public_host(&request, client)? {
request.headers_mut().insert(header::HOST, host);
}
let mut uri = upstream.clone().into_parts();
uri.path_and_query = Some(path_and_query);
*request.uri_mut() = Uri::from_parts(uri).map_err(|_| Rejection::Internal)?;
*request.version_mut() = Version::HTTP_11;
let chunked = request.body().size_hint().exact().is_none();
let headers = request.headers_mut();
strip_hop_by_hop(headers);
if chunked {
// hyper sends no body for a GET with an unknown length unless told it is chunked.
headers.insert(
header::TRANSFER_ENCODING,
HeaderValue::from_static("chunked"),
);
}
if websocket {
restore_websocket_handshake(headers);
}
headers.insert(
PEER_HEADER,
HeaderValue::from_str(&client.peer.to_string()).map_err(|_| Rejection::Internal)?,
);
Ok(request)
}
// Python builds absolute URLs from Host and, without a usable one, from the address it listens
// on, which behind Rust is the private loopback port. A client that sent no usable Host gets the
// public address it connected to, which is what Python used before. h11 rejects HTTP/1.1 without
// Host.
fn public_host(request: &Request, client: ClientSocket) -> Result<Option<HeaderValue>, Rejection> {
let host = request.headers().get(header::HOST);
if host.is_some_and(|host| !host.is_empty()) {
return Ok(None);
}
if host.is_none() && request.version() == Version::HTTP_11 {
return Err(Rejection::MissingHost);
}
HeaderValue::from_str(&client.local.to_string())
.map(Some)
.map_err(|_| Rejection::Internal)
}
// hyper only decodes chunked framing, so anything else would reach Python still coded but framed
// as a plain body. uvicorn rejects it with the 400 it sends for every h11 parse error.
fn only_chunked(headers: &HeaderMap) -> bool {
headers
.get_all(header::TRANSFER_ENCODING)
.iter()
.flat_map(|value| value.as_bytes().split(|byte| *byte == b','))
.all(|coding| coding.trim_ascii().eq_ignore_ascii_case(b"chunked"))
}
/// The response the client receives: Python's, without the upstream connection's own headers.
pub(crate) fn downstream_response<B>(mut response: Response<B>) -> Response<B> {
strip_hop_by_hop(response.headers_mut());
response
}
/// Python's 101 as the client receives it, still naming the protocol both sides switch to.
pub(crate) fn switched_response<B>(mut response: Response<B>) -> Response<B> {
strip_hop_by_hop(response.headers_mut());
restore_websocket_handshake(response.headers_mut());
response
}
pub(crate) fn is_websocket_handshake(headers: &HeaderMap) -> bool {
headers
.get(header::UPGRADE)
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"websocket"))
&& headers
.get_all(header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.any(|token| token.trim().eq_ignore_ascii_case("upgrade"))
}
const HOP_BY_HOP: [&str; 9] = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"proxy-connection",
];
// Per-connection headers (RFC 9110 section 7.6.1) describe the client's connection to Rust, not
// Rust's connection to Python, so a proxy must drop them instead of forwarding them.
fn strip_hop_by_hop(headers: &mut HeaderMap) {
let named: Vec<_> = headers
.get_all(header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.filter_map(|name| header::HeaderName::from_bytes(name.trim().as_bytes()).ok())
.filter(|name| !must_forward(name))
.collect();
for name in named {
headers.remove(name);
}
for name in HOP_BY_HOP {
headers.remove(name);
}
}
fn must_forward(name: &header::HeaderName) -> bool {
matches!(
name.as_str(),
"host"
| "authorization"
| "cookie"
| "set-cookie"
| "www-authenticate"
| "authentication-info"
| "api-key"
| "x-api-key"
| "litellm-api-key"
| "forwarded"
| PEER_HEADER
) || name.as_str().starts_with("content-")
|| name.as_str().starts_with("x-forwarded-")
|| name.as_str().starts_with("sec-websocket-")
}
// Stripping drops the handshake's Connection and Upgrade, so each hop gets them back.
fn restore_websocket_handshake(headers: &mut HeaderMap) {
headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade"));
headers.insert(header::UPGRADE, HeaderValue::from_static("websocket"));
}

View file

@ -0,0 +1,116 @@
use std::{convert::Infallible, io, net::SocketAddr, pin::pin, time::Duration};
use axum::{body::Body, extract::Request};
use hyper::{body::Incoming, server::conn::http1, service::service_fn};
use hyper_util::rt::{TokioIo, TokioTimer};
use tokio::net::TcpListener;
use crate::{Forward, forward::MAX_HEADERS};
/// The client's TCP connection to the public listener.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ClientSocket {
pub peer: SocketAddr,
pub local: SocketAddr,
}
/// Serves each public connection with hyper directly, because `axum::serve` cannot configure
/// the connection timeouts uvicorn applied to the same clients.
pub(crate) async fn serve(
forward: Forward,
listener: TcpListener,
shutdown: impl Future<Output = ()>,
drain: Duration,
) {
let connections = forward.connections().clone();
let _close_on_drop = connections.close_on_drop();
let keepalive = forward.keepalive();
let builder = builder(keepalive);
let mut shutdown = pin!(shutdown);
loop {
let (stream, peer) = tokio::select! {
() = &mut shutdown => break,
accepted = listener.accept() => match accepted {
Ok(accepted) => accepted,
Err(error) => {
back_off(error).await;
continue;
}
},
};
let local = match stream.local_addr() {
Ok(local) => local,
Err(error) => {
tracing::debug!(%error, "client connection closed before it was served");
continue;
}
};
if let Err(error) = stream.set_nodelay(true) {
tracing::warn!(%error, "could not disable Nagle on a client connection");
}
let socket = ClientSocket { peer, local };
let forward = forward.clone();
let service = service_fn(move |request: Request<Incoming>| {
let forward = forward.clone();
async move { Ok::<_, Infallible>(forward.handle(socket, request.map(Body::new)).await) }
});
let connection = builder
.serve_connection(TokioIo::new(stream), service)
.with_upgrades();
let draining = connections.clone();
connections.spawn(async move {
let mut connection = pin!(connection);
let ended = tokio::select! {
ended = connection.as_mut() => ended,
() = draining.draining() => {
connection.as_mut().graceful_shutdown();
connection.await
}
};
if let Err(error) = ended {
tracing::debug!(%error, "client connection ended with an error");
}
});
}
drop(listener);
connections.begin_shutdown();
if tokio::time::timeout(drain, connections.wait())
.await
.is_err()
{
tracing::warn!(
?drain,
"closing connections still open after the shutdown drain"
);
}
connections.close();
connections.wait().await;
}
// uvicorn closes a client connection that sits idle for `--keepalive_timeout` between requests.
// Without the same limit, a client that vanishes without closing (NAT expiry, a crashed host)
// would hold its socket for the life of the process until the gateway runs out of descriptors.
// Operators already tune that timeout against their load balancer, so the public side keeps
// Python's value instead of introducing its own. hyper only runs the header timer while a
// connection waits for its next request, so it never cuts a long stream, upload or WebSocket.
fn builder(keepalive: Duration) -> http1::Builder {
let mut builder = http1::Builder::new();
builder
.max_headers(MAX_HEADERS)
.timer(TokioTimer::new())
.header_read_timeout(keepalive);
builder
}
async fn back_off(error: io::Error) {
if matches!(
error.kind(),
io::ErrorKind::ConnectionRefused
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::ConnectionReset
) {
return;
}
tracing::error!(%error, "could not accept a client connection");
tokio::time::sleep(Duration::from_secs(1)).await;
}

View file

@ -0,0 +1,113 @@
use std::{ffi::OsString, net::SocketAddr, str::FromStr, time::Duration};
use axum::http::Uri;
use serde::Deserialize;
use crate::Error;
const UPSTREAM: &str = "LITELLM_FORWARD_UPSTREAM";
/// The Python proxy's private origin. Only a loopback IPv4 address parses, so nothing can point
/// the forwarder at another host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upstream(Uri);
impl Upstream {
pub(crate) fn uri(&self) -> &Uri {
&self.0
}
}
impl FromStr for Upstream {
type Err = Error;
fn from_str(value: &str) -> Result<Self, Error> {
let uri: Uri = value.parse().map_err(Error::UpstreamUri)?;
let address = uri
.authority()
.filter(|_| uri.scheme_str() == Some("http"))
.filter(|authority| !authority.as_str().contains('@'))
.filter(|_| uri.path() == "/" && uri.query().is_none())
.and_then(|authority| authority.as_str().parse::<SocketAddr>().ok());
match address {
Some(SocketAddr::V4(address)) if address.ip().is_loopback() => Ok(Self(uri)),
_ => Err(Error::Upstream),
}
}
}
#[derive(Deserialize)]
struct Environment {
litellm_forward_upstream: String,
litellm_forward_host: String,
litellm_forward_port: u16,
litellm_forward_upstream_keepalive: f64,
litellm_forward_shutdown_drain: f64,
}
/// Everything forward mode runs with. The Python supervisor resolves each value from the settings
/// Python actually runs with, so none of them is guessed or defaulted here.
/// Setting `LITELLM_FORWARD_UPSTREAM` requires every other `LITELLM_FORWARD_*` setting below.
#[derive(Debug, Clone, PartialEq)]
pub struct Settings {
pub upstream: Upstream,
pub host: String,
pub port: u16,
pub upstream_keepalive: Duration,
pub shutdown_drain: Duration,
}
impl Settings {
/// `None` when `LITELLM_FORWARD_UPSTREAM` is unset, which means the gateway is not forwarding.
pub fn from_env() -> Result<Option<Self>, Error> {
Self::from_vars(std::env::vars_os())
}
pub fn from_vars(
variables: impl IntoIterator<Item = (OsString, OsString)>,
) -> Result<Option<Self>, Error> {
let variables: Vec<(String, String)> = variables
.into_iter()
.filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
.collect();
if !variables.iter().any(|(key, _)| key == UPSTREAM) {
return Ok(None);
}
let environment: Environment = envy::from_iter(variables).map_err(|error| match error {
envy::Error::MissingValue(field) => Error::MissingSetting(field.to_uppercase()),
envy::Error::Custom(message) => Error::InvalidSetting(message),
})?;
Ok(Some(Self {
upstream: environment.litellm_forward_upstream.parse()?,
host: environment.litellm_forward_host,
port: environment.litellm_forward_port,
upstream_keepalive: positive_seconds(
"LITELLM_FORWARD_UPSTREAM_KEEPALIVE",
environment.litellm_forward_upstream_keepalive,
)?,
shutdown_drain: seconds(
"LITELLM_FORWARD_SHUTDOWN_DRAIN",
environment.litellm_forward_shutdown_drain,
)?,
}))
}
}
fn seconds(variable: &str, value: f64) -> Result<Duration, Error> {
Duration::try_from_secs_f64(value).map_err(|_| {
Error::InvalidSetting(format!(
"{variable} must be a non-negative number of seconds, got {value}"
))
})
}
/// The keep-alive also bounds the wait for a client's first request, so zero would close every
/// client connection before it could send one.
fn positive_seconds(variable: &str, value: f64) -> Result<Duration, Error> {
match seconds(variable, value)? {
Duration::ZERO => Err(Error::InvalidSetting(format!(
"{variable} must be a positive number of seconds, got {value}"
))),
duration => Ok(duration),
}
}

View file

@ -0,0 +1,86 @@
use axum::{
body::Body,
extract::Request,
http::{Method, Version},
response::Response,
};
use hyper::{
body::Incoming,
upgrade::{OnUpgrade, Upgraded},
};
use hyper_util::rt::TokioIo;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use crate::{Rejection, connections::Connections, rewrite};
pub(crate) fn take_handshake(
connections: &Connections,
request: &mut Request,
) -> Result<Option<OnUpgrade>, Rejection> {
if request.method() != Method::GET
|| request.version() != Version::HTTP_11
|| !rewrite::is_websocket_handshake(request.headers())
{
return Ok(None);
}
if connections.is_draining() {
return Err(Rejection::ShuttingDown);
}
Ok(Some(hyper::upgrade::on(request)))
}
pub(crate) async fn switch(
connections: &Connections,
downstream: OnUpgrade,
mut response: Response<Incoming>,
) -> Result<Response, Rejection> {
if !rewrite::is_websocket_handshake(response.headers()) {
return Err(Rejection::UnrequestedUpgrade);
}
let upstream = connections
.until_closed(hyper::upgrade::on(&mut response))
.await
.ok_or(Rejection::ShuttingDown)?
.map_err(Rejection::UpgradeFailed)?;
connections.spawn(async move {
match downstream.await {
Ok(downstream) => relay(downstream, upstream).await,
Err(_) => tracing::debug!("websocket upgrade did not complete"),
}
});
Ok(rewrite::switched_response(response).map(|_| Body::empty()))
}
// uvicorn never half-closes a WebSocket, so Python's EOF means the socket is gone and the relay
// ends. Only a client that is gone ends it from the other side: the client's EOF just half-closes
// Python's side, and a write Python refuses means it closed with its last frames still in flight
// to the client.
async fn relay(downstream: Upgraded, upstream: Upgraded) {
let (mut client_read, mut client_write) = tokio::io::split(TokioIo::new(downstream));
let (mut python_read, mut python_write) = tokio::io::split(TokioIo::new(upstream));
let to_python = async {
let mut buffer = vec![0; 8192];
loop {
let read = match client_read.read(&mut buffer).await {
Ok(0) => break,
Ok(read) => read,
Err(_) => return,
};
if python_write.write_all(&buffer[..read]).await.is_err() {
return std::future::pending().await;
}
}
python_write.shutdown().await.ok();
std::future::pending().await
};
let to_client = async {
tokio::io::copy(&mut python_read, &mut client_write)
.await
.ok();
client_write.shutdown().await.ok();
};
tokio::select! {
() = to_python => tracing::debug!("websocket client disconnected"),
() = to_client => {}
}
}

View file

@ -0,0 +1,223 @@
mod support;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use axum::{body::Body, http::StatusCode, response::Response};
use litellm_gateway_forward::{Forward, PEER_HEADER};
use rstest::rstest;
use support::{DRAIN, Gateway, Raw, UVICORN_KEEPALIVE, raw_upstream, recording, within};
use tokio::net::{TcpListener, TcpStream};
fn ok() -> Response {
Response::new(Body::from("ok"))
}
#[rstest]
#[case::ordinary("")]
#[case::connection_nominated(
"connection: X-Forwarded-For, X-Forwarded-Proto, Forwarded, X-Litellm-Rust-Peer\r\n"
)]
#[tokio::test]
async fn python_sees_forwarding_headers_untouched_and_the_tcp_peer_rust_saw(
#[case] connection: &str,
) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"GET /sso/callback HTTP/1.1\r\n\
host: public.example\r\n\
x-forwarded-for: 192.0.2.1\r\n\
x-forwarded-for: 192.0.2.2\r\n\
x-forwarded-proto: https\r\n\
forwarded: for=192.0.2.1;proto=https\r\n\
x-litellm-rust-peer: 10.1.2.3:1\r\n{connection}\r\n",
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
let forwarded_for: Vec<_> = request.headers.get_all("x-forwarded-for").iter().collect();
assert_eq!(forwarded_for, ["192.0.2.1", "192.0.2.2"]);
assert_eq!(request.headers["x-forwarded-proto"], "https");
assert_eq!(request.headers["forwarded"], "for=192.0.2.1;proto=https");
let peers: Vec<_> = request.headers.get_all(PEER_HEADER).iter().collect();
assert_eq!(peers, [raw.local_address().to_string().as_str()]);
}
/// Python builds redirects and OAuth metadata from Host, and without one from the address it
/// listens on, which behind Rust is its private loopback port. So a request without a usable Host
/// carries the public address the client connected to, except HTTP/1.1, which h11 rejects.
#[rstest]
#[case::http11_without_host("HTTP/1.1", "", false)]
#[case::http10_without_host("HTTP/1.0", "", true)]
#[case::http11_with_an_empty_host("HTTP/1.1", "host:\r\n", true)]
#[tokio::test]
async fn a_request_without_a_usable_host_never_names_the_private_upstream(
#[case] version: &str,
#[case] host: &str,
#[case] forwarded: bool,
) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!("GET /sso/key/generate {version}\r\n{host}\r\n"))
.await;
let status = within(raw.response_head()).await.unwrap().status;
let hosts = received.try_recv().ok().map(|request| {
request
.headers
.get_all("host")
.iter()
.map(|value| value.to_str().unwrap().to_owned())
.collect::<Vec<_>>()
});
let expected = if forwarded {
(StatusCode::OK, Some(vec![gateway.address.to_string()]))
} else {
(StatusCode::BAD_REQUEST, None)
};
assert_eq!((status, hosts), expected);
}
#[rstest]
#[case::uppercase_with_port("PUBLIC.Example:4000")]
#[case::ipv6_literal("[::1]:4000")]
#[case::ipv4_with_port("192.0.2.10:8443")]
#[tokio::test]
async fn python_sees_the_host_header_byte_for_byte(#[case] host: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!("GET /ui HTTP/1.1\r\nHost: {host}\r\n\r\n"))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
let hosts: Vec<_> = request.headers.get_all("host").iter().collect();
assert_eq!(hosts, [host]);
}
/// Python's IP allowlists and rate limits read the peer exactly as uvicorn would have seen it on
/// the public socket, so a dual-stack listener reports IPv4 clients in their mapped form.
#[rstest]
#[case::ipv6("[::1]:0", "[::1]", "[::1]")]
#[case::ipv4_on_a_dual_stack_listener("[::]:0", "127.0.0.1", "[::ffff:127.0.0.1]")]
#[tokio::test]
async fn ipv6_listeners_report_the_peer_bracketed_with_its_port(
#[case] bind: &str,
#[case] connect: &str,
#[case] peer_ip: &str,
) {
let (upstream, mut received) = recording(ok).await;
let forward = Forward::new(
&format!("http://{upstream}").parse().unwrap(),
UVICORN_KEEPALIVE,
);
let public = TcpListener::bind(bind).await.unwrap();
let port = public.local_addr().unwrap().port();
tokio::spawn(forward.serve(public, std::future::pending(), DRAIN));
let mut raw = Raw::new(
TcpStream::connect(format!("{connect}:{port}"))
.await
.unwrap(),
);
raw.send("GET / HTTP/1.1\r\nhost: public.example\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(
received.recv().await.unwrap().headers[PEER_HEADER],
format!("{peer_ip}:{}", raw.local_address().port()).as_str()
);
}
/// Without the peer header Python would take Rust's loopback hop as the client, which allowlists
/// often trust, so no spelling, repetition or Connection token may remove or replace it.
#[rstest]
#[case::named_as_hop_by_hop(
"connection: x-litellm-rust-peer\r\nx-litellm-rust-peer: 127.0.0.1:1\r\n"
)]
#[case::mixed_case_copies(
"X-LiteLLM-Rust-Peer: 127.0.0.1:1\r\nx-litellm-rust-peer: 192.0.2.7:2\r\n"
)]
#[case::comma_joined("x-litellm-rust-peer: 127.0.0.1:1, 192.0.2.7:2\r\n")]
#[tokio::test]
async fn a_client_can_neither_strip_nor_spoof_the_peer(#[case] spoof: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"GET /key/info HTTP/1.1\r\nhost: public.example\r\n{spoof}\r\n"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
let peers: Vec<_> = request.headers.get_all(PEER_HEADER).iter().collect();
assert_eq!(peers, [raw.local_address().to_string().as_str()]);
}
/// Pooled upstream connections carry requests from many clients in turn, so the peer belongs to
/// each request and never to the connection it travels on.
#[rstest]
#[tokio::test]
async fn each_request_carries_its_own_peer_over_a_shared_upstream_connection() {
let connections = Arc::new(AtomicUsize::new(0));
let accepted = connections.clone();
let upstream = raw_upstream(move |mut python| {
accepted.fetch_add(1, Ordering::SeqCst);
async move {
while let Some(head) = python.request_head().await {
let peer = head.header(PEER_HEADER).unwrap().to_vec();
python
.send(
[
format!("HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n", peer.len())
.as_bytes(),
&peer,
]
.concat(),
)
.await;
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut clients = [
gateway.connect().await,
gateway.connect().await,
gateway.connect().await,
];
for index in [0, 1, 2, 2, 1, 0] {
let raw = &mut clients[index];
raw.send("GET /v1/models HTTP/1.1\r\nhost: public.example\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
let peer = raw.body(head.content_length().unwrap()).await;
assert_eq!(peer, raw.local_address().to_string().into_bytes());
}
assert_eq!(connections.load(Ordering::SeqCst), 1);
}

View file

@ -0,0 +1,192 @@
mod support;
use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use axum::{body::Body, extract::Request, http::StatusCode, response::Response};
use http_body_util::BodyExt;
use rstest::rstest;
use support::{Gateway, client, raw_upstream, recording, within};
use tokio::sync::{Notify, mpsc};
#[rstest]
#[tokio::test]
async fn streams_a_body_without_a_content_length_as_python_produces_it() {
let first: &[u8] = &[0xff, 0xfb, 0x90, 0x64, 0x00, 0x0d, 0x0a];
let rest = vec![0xa5; 64 * 1024];
let finish = Arc::new(Notify::new());
let finished = finish.clone();
let tail = rest.clone();
let upstream = raw_upstream(move |mut python| {
let finished = finished.clone();
let tail = tail.clone();
async move {
python.request_head().await.unwrap();
python
.send([&b"HTTP/1.1 200 OK\r\ncontent-type: audio/mpeg\r\ntransfer-encoding: chunked\r\n\r\n7\r\n"[..], first, b"\r\n"].concat())
.await;
finished.notified().await;
python
.send([format!("{:x}\r\n", tail.len()).as_bytes(), &tail, b"\r\n0\r\n\r\n"].concat())
.await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut response = within(
client().request(
Request::post(gateway.url("/v1/audio/speech"))
.body(Body::empty())
.unwrap(),
),
)
.await
.unwrap();
assert!(!response.headers().contains_key("content-length"));
let frame = within(response.body_mut().frame()).await.unwrap().unwrap();
assert_eq!(frame.into_data().unwrap(), first);
finish.notify_one();
let body = within(response.into_body().collect())
.await
.unwrap()
.to_bytes();
assert_eq!(body, rest);
}
#[rstest]
#[tokio::test]
async fn range_requests_and_partial_content_pass_unchanged() {
let (upstream, mut received) = recording(|| -> Response {
Response::builder()
.status(StatusCode::PARTIAL_CONTENT)
.header("content-range", "bytes 2-5/10")
.header("accept-ranges", "bytes")
.body(Body::from("2345"))
.unwrap()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /v1/videos/video_1/content HTTP/1.1\r\nhost: x\r\nrange: bytes=2-5\r\nif-range: \"v1\"\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::PARTIAL_CONTENT);
assert_eq!(head.header("content-range"), Some(&b"bytes 2-5/10"[..]));
assert_eq!(raw.body(head.content_length().unwrap()).await, b"2345");
let request = received.recv().await.unwrap();
assert_eq!(request.headers["range"], "bytes=2-5");
assert_eq!(request.headers["if-range"], "\"v1\"");
}
#[rstest]
#[tokio::test]
async fn a_large_download_is_paced_by_the_client_and_keeps_its_content_length() {
const LENGTH: usize = 128 * 1024 * 1024;
let written = Arc::new(AtomicUsize::new(0));
let writing = written.clone();
let upstream = raw_upstream(move |mut python| {
let writing = writing.clone();
async move {
python.request_head().await.unwrap();
python
.send(format!("HTTP/1.1 200 OK\r\ncontent-type: application/octet-stream\r\ncontent-length: {LENGTH}\r\n\r\n"))
.await;
let chunk = [0xa5; 64 * 1024];
while writing.load(Ordering::SeqCst) < LENGTH {
python.send(chunk).await;
writing.fetch_add(chunk.len(), Ordering::SeqCst);
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /v1/files/file-1/content HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.content_length(), Some(LENGTH));
assert_eq!(head.header("transfer-encoding"), None);
tokio::time::sleep(Duration::from_secs(1)).await;
assert!(
written.load(Ordering::SeqCst) < LENGTH / 4,
"the forwarder buffered a download the client was not reading"
);
let mut remaining = LENGTH;
while remaining > 0 {
remaining -= within(raw.body(remaining.min(1 << 20))).await.len();
}
}
/// The UI revalidates its static assets, and a 304 must carry exactly the validators Python sent,
/// with no length invented for a body it never has.
#[rstest]
#[tokio::test]
async fn a_conditional_request_gets_python_304_with_its_validators_only() {
let (event, mut events) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python| {
let event = event.clone();
async move {
while let Some(head) = python.request_head().await {
event
.send(head.header("if-none-match").map(<[u8]>::to_vec))
.unwrap();
python
.send("HTTP/1.1 304 Not Modified\r\netag: \"5f1-abc\"\r\ncache-control: no-cache\r\nvary: Accept-Encoding\r\ndate: Tue, 03 Nov 2026 10:00:00 GMT\r\n\r\n")
.await;
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
for _ in 0..2 {
raw.send("GET /ui/_next/static/chunks/main.js HTTP/1.1\r\nhost: x\r\nif-none-match: \"5f1-abc\"\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::NOT_MODIFIED);
let mut names: Vec<_> = head.headers.iter().map(|(name, _)| name.as_str()).collect();
names.sort_unstable();
assert_eq!(names, ["cache-control", "date", "etag", "vary"]);
assert_eq!(head.header("etag"), Some(&b"\"5f1-abc\""[..]));
assert_eq!(
head.header("date"),
Some(&b"Tue, 03 Nov 2026 10:00:00 GMT"[..])
);
assert_eq!(
within(events.recv()).await.unwrap().as_deref(),
Some(&b"\"5f1-abc\""[..])
);
}
}
/// A client knows a download was cut short only because fewer bytes than the Content-Length
/// arrived before the connection closed, so the length must survive and the connection must end.
#[rstest]
#[tokio::test]
async fn a_download_python_cuts_short_closes_the_client_connection_before_its_length() {
let upstream = raw_upstream(|mut python| async move {
python.request_head().await.unwrap();
python
.send([&b"HTTP/1.1 200 OK\r\ncontent-type: application/octet-stream\r\ncontent-length: 1000\r\n\r\n"[..], &[0xa5; 500]].concat())
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /v1/files/file-1/content HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::OK);
assert_eq!(head.content_length(), Some(1000));
assert_eq!(within(raw.until_closed()).await, [0xa5; 500]);
}

View file

@ -0,0 +1,855 @@
mod support;
use std::{
convert::Infallible,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
};
use axum::{
Router,
body::{Body, Bytes},
extract::Request,
http::{HeaderValue, StatusCode},
response::Response,
};
use litellm_gateway_forward::PEER_HEADER;
use rstest::rstest;
use support::{Gateway, Head, client, raw_upstream, recording, serve, within};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
sync::mpsc,
};
fn ok() -> Response {
Response::new(Body::from("ok"))
}
/// An upstream that reports each bodiless request head exactly as it arrived on the wire.
async fn heads() -> (std::net::SocketAddr, mpsc::UnboundedReceiver<Head>) {
let (sender, receiver) = mpsc::unbounded_channel();
let address = raw_upstream(move |mut python| {
let sender = sender.clone();
async move {
while let Some(head) = python.request_head().await {
sender.send(head).unwrap();
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok")
.await;
}
}
})
.await;
(address, receiver)
}
#[rstest]
#[tokio::test]
async fn forwards_the_request_as_the_client_sent_it_minus_hop_headers() {
let (upstream, mut received) = recording(|| {
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header("connection", "x-upstream-hop")
.header("x-upstream-hop", "remove")
.header("x-response", "keep")
.body(Body::from("python error"))
.unwrap()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(
"PATCH /v1/messages?x=a%2Fb&x=c HTTP/1.1\r\n\
host: public.example\r\n\
authorization: Bearer test\r\n\
connection: x-remove, keep-alive\r\n\
x-remove: remove\r\n\
proxy-authorization: remove\r\n\
te: trailers\r\n\
content-length: 7\r\n\r\npayload",
)
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::UNAUTHORIZED);
assert_eq!(head.header("x-response"), Some(&b"keep"[..]));
assert_eq!(head.header("x-upstream-hop"), None);
let body = raw.body(head.content_length().unwrap()).await;
assert_eq!(body, b"python error");
let request = received.recv().await.unwrap();
assert_eq!(request.method, "PATCH");
assert_eq!(request.uri, "/v1/messages?x=a%2Fb&x=c");
assert_eq!(request.headers["host"], "public.example");
assert_eq!(request.headers["authorization"], "Bearer test");
assert!(!request.headers.contains_key("x-remove"));
assert!(!request.headers.contains_key("proxy-authorization"));
assert!(!request.headers.contains_key("te"));
assert!(!request.headers.contains_key("connection"));
assert_eq!(request.body, "payload");
}
#[rstest]
#[case::host("HoSt", "public.example")]
#[case::length("Content-Length", "7")]
#[case::authorization("AUTHORIZATION", "Bearer test")]
#[case::cookie("Cookie", "session=test")]
#[case::api_key("X-Api-Key", "test")]
#[case::azure_key("Api-Key", "test")]
#[case::litellm_key("Litellm-Api-Key", "test")]
#[case::forwarded("Forwarded", "for=192.0.2.1;proto=https")]
#[case::forwarded_for("X-Forwarded-For", "192.0.2.1")]
#[case::forwarded_proto("X-Forwarded-Proto", "https")]
#[case::forwarded_host("X-Forwarded-Host", "public.example")]
#[case::content_type("Content-Type", "application/octet-stream")]
#[case::content_encoding("Content-Encoding", "identity")]
#[tokio::test]
async fn connection_cannot_remove_end_to_end_headers(#[case] name: &str, #[case] value: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
let host = if name.eq_ignore_ascii_case("host") {
""
} else {
"host: public.example\r\n"
};
let length = if name.eq_ignore_ascii_case("content-length") {
""
} else {
"content-length: 7\r\n"
};
raw.send(format!(
"POST / HTTP/1.1\r\n{host}{length}{name}: {value}\r\nconnection: x-remove\r\nconnection: {name}, keep-alive\r\nx-remove: remove\r\n\r\npayload"
)).await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = within(received.recv()).await.unwrap();
assert_eq!(request.headers[name], value);
assert_eq!(request.body, "payload");
assert!(!request.headers.contains_key("connection"));
assert!(!request.headers.contains_key("x-remove"));
}
#[rstest]
#[tokio::test]
async fn connection_cannot_remove_response_credentials_or_representation_metadata() {
let (upstream, _received) = recording(|| {
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header("connection", "Content-Length, Set-Cookie, WWW-Authenticate, Authentication-Info, Content-Type, Content-Encoding, x-remove")
.header("content-length", "2")
.header("set-cookie", "session=; Max-Age=0")
.header("www-authenticate", "Bearer")
.header("authentication-info", "nextnonce=test")
.header("content-type", "text/plain")
.header("content-encoding", "identity")
.header("x-remove", "remove")
.body(Body::from("ok"))
.unwrap()
}).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET / HTTP/1.1\r\nhost: x\r\n\r\n").await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::UNAUTHORIZED);
assert_eq!(head.content_length(), Some(2));
assert_eq!(head.header("set-cookie"), Some(&b"session=; Max-Age=0"[..]));
assert_eq!(head.header("www-authenticate"), Some(&b"Bearer"[..]));
assert_eq!(
head.header("authentication-info"),
Some(&b"nextnonce=test"[..])
);
assert_eq!(head.header("content-type"), Some(&b"text/plain"[..]));
assert_eq!(head.header("content-encoding"), Some(&b"identity"[..]));
assert_eq!(head.header("x-remove"), None);
assert_eq!(raw.body(2).await, b"ok");
}
#[rstest]
#[case::get("GET")]
#[case::post("POST")]
#[case::put("PUT")]
#[case::delete("DELETE")]
#[case::options("OPTIONS")]
#[case::extension("PURGE")]
#[case::webdav("PROPFIND")]
#[case::lowercase("get")]
#[case::punctuated("M-SEARCH")]
#[tokio::test]
async fn forwards_every_method(#[case] method: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let response = client()
.request(
Request::builder()
.method(method)
.uri(gateway.url("/mcp"))
.body(Body::from("body"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let request = received.recv().await.unwrap();
assert_eq!(request.method, method);
assert_eq!(request.body, "body");
}
#[rstest]
#[case::double_slash("//v1//models")]
#[case::encoded_slash("/v1/files/a%2Fb/content")]
#[case::encoded_hash_in_query("/v1/files?purpose=batch%23retry&limit=1")]
#[case::encoded_hash_in_path("/v1/files/report%231.pdf/content")]
#[case::encoded_hash_before_query("/gemini/v1beta/files/a%23b?key=k")]
#[case::encoded_query("/v1/models?q=%E2%9C%93&empty=&flag")]
#[case::utf8_bytes_escaped("/mcp/%F0%9F%A6%80")]
#[case::lowercase_encoded_slash("/v1/files/a%2fb/content")]
#[case::dot_segments("/openai/./v1/../v1/models")]
#[case::encoded_dot_segments("/openai/%2e%2e/v1/%2E/models")]
#[case::matrix_params("/langfuse/api;v=1/public;x=y/traces")]
#[case::plus_and_encoded_space("/gemini/v1beta/models?q=a+b&r=a%20b&s=%2B")]
#[case::empty_query("/v1/models?")]
#[case::question_marks_in_query("/v1/models??a=b?c")]
#[case::colons_in_segments(
"/v1/projects/p/locations/l/publishers/google/models/m:streamGenerateContent?alt=sse"
)]
#[case::sub_delims("/~u/@:!$&'()*+,=/x")]
#[case::raw_bytes_browsers_leave_unescaped("/a{b}|c^d\\e\"f?g={}|^`")]
#[case::invalid_percent_escapes("/a%zz%00b?%")]
#[tokio::test]
async fn forwards_the_request_target_byte_for_byte(#[case] target: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!("GET {target} HTTP/1.1\r\nhost: x\r\n\r\n"))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().uri, target);
}
#[rstest]
#[tokio::test]
async fn forwards_a_query_string_as_long_as_uvicorn_accepts() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
let target = format!("/vertex_ai/v1/models?key=%2F{}&end", "a%20b".repeat(3000));
raw.send(format!("GET {target} HTTP/1.1\r\nhost: x\r\n\r\n"))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().uri, target.as_str());
}
#[rstest]
#[case::in_query("/v1/files?purpose=batch#retry&limit=1", "/v1/files?purpose=batch")]
#[case::in_path("/v1/files/report#1.pdf/content", "/v1/files/report")]
#[case::before_query("/gemini/v1beta/files/a#b?key=k", "/gemini/v1beta/files/a")]
#[tokio::test]
async fn forwards_only_the_path_and_query_before_a_fragment(
#[case] target: &str,
#[case] expected: &str,
) {
let (upstream, mut received) = heads().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!("GET {target} HTTP/1.1\r\nhost: x\r\n\r\n"))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(within(received.recv()).await.unwrap().path, expected);
}
#[rstest]
#[tokio::test]
async fn absolute_form_targets_reach_python_as_origin_form() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(
"GET http://elsewhere.example/v1/models?x=1 HTTP/1.1\r\nhost: elsewhere.example\r\n\r\n",
)
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
assert_eq!(request.uri, "/v1/models?x=1");
}
#[rstest]
#[tokio::test]
async fn relays_a_response_with_more_headers_than_hyper_allows_by_default() {
let upstream = serve(axum::Router::new().fallback(|| async {
let headers = (0..150).map(|index| (format!("llm_provider-x-{index}"), "v"));
let mut response = ok();
for (name, value) in headers {
response.headers_mut().insert(
axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_static(value),
);
}
response
}))
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /v1/chat/completions HTTP/1.1\r\nhost: public.example\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::OK);
assert_eq!(head.header("llm_provider-x-149"), Some(&b"v"[..]));
}
/// uvicorn's h11 parser has no header count limit, only a 16 KiB cap on the whole head.
#[rstest]
#[tokio::test]
async fn forwards_a_request_with_as_many_headers_as_uvicorn_accepts() {
let (sender, mut received) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |python| {
let sender = sender.clone();
async move {
let mut stream = python.into_stream();
let mut head = Vec::new();
while !head.ends_with(b"\r\n\r\n") {
head.push(stream.read_u8().await.unwrap());
}
sender.send(head).unwrap();
stream
.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n")
.await
.unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
let headers: String = (0..1000).map(|index| format!("x-{index}: v\r\n")).collect();
raw.send(format!(
"GET /v1/chat/completions HTTP/1.1\r\nhost: x\r\n{headers}\r\n"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let head = String::from_utf8(within(received.recv()).await.unwrap()).unwrap();
assert!(head.contains(&headers));
}
async fn header_fields_python_receives(fields: &str) -> Vec<(String, Vec<u8>)> {
let (upstream, mut received) = heads().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"GET /anthropic/v1/messages HTTP/1.1\r\nhost: x\r\n{fields}\r\n"
))
.await;
within(raw.response_head()).await.unwrap();
within(received.recv())
.await
.unwrap()
.headers
.into_iter()
.filter(|(name, _)| name.starts_with("x-") && name != PEER_HEADER)
.collect()
}
fn fields(expected: &[(&str, &str)]) -> Vec<(String, Vec<u8>)> {
expected
.iter()
.map(|(name, value)| ((*name).to_owned(), value.as_bytes().to_vec()))
.collect()
}
/// Python reads `scope["headers"]` as the list the client sent, in that order.
#[rstest]
#[ignore = "divergence: HeaderMap::remove can move the headers after a dropped hop-by-hop one"]
#[tokio::test]
async fn dropping_a_hop_by_hop_header_keeps_the_others_in_order() {
let received = header_fields_python_receives(
"x-a: 1\r\nconnection: keep-alive\r\nx-b: 2\r\nx-c: 3\r\nx-d: 4\r\n",
)
.await;
assert_eq!(
received,
fields(&[("x-a", "1"), ("x-b", "2"), ("x-c", "3"), ("x-d", "4")])
);
}
/// uvicorn speaks only HTTP/1.1, so an HTTP/2 prior-knowledge client never reaches Python through
/// Rust either. hyper closes the connection where h11 answers 400, which no HTTP/2 client reads.
#[rstest]
#[tokio::test]
async fn an_http2_client_never_reaches_python() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n\x00\x00\x00\x04\x00\x00\x00\x00\x00")
.await;
assert!(within(raw.until_closed()).await.is_empty());
assert!(received.try_recv().is_err());
}
#[rstest]
#[ignore = "divergence: HeaderMap groups every value of a name at its first position"]
#[tokio::test]
async fn interleaved_repeated_headers_reach_python_interleaved() {
let received = header_fields_python_receives("x-a: 1\r\nx-b: 2\r\nx-a: 3\r\n").await;
assert_eq!(
received,
fields(&[("x-a", "1"), ("x-b", "2"), ("x-a", "3")])
);
}
/// h11 trims optional whitespace around a value and keeps everything inside it, including empty
/// values and names using every token character.
#[rstest]
#[tokio::test]
async fn python_sees_header_values_as_h11_would_parse_them() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET / HTTP/1.1\r\nhost: x\r\nx-empty:\r\nx-blank: \r\nx-inner: a \t b \t\r\nX-Token!#$%&'*+.^_`|~: v\r\nx-empty: second\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
let values = |name: &str| -> Vec<&[u8]> {
request
.headers
.get_all(name)
.iter()
.map(HeaderValue::as_bytes)
.collect()
};
assert_eq!(values("x-empty"), [&b""[..], b"second"]);
assert_eq!(values("x-blank"), [&b""[..]]);
assert_eq!(values("x-inner"), [&b"a \t b"[..]]);
assert_eq!(values("x-token!#$%&'*+.^_`|~"), [&b"v"[..]]);
}
/// RFC 9112 section 5.2 lets a server either reject obs-fold or unfold it, and h11 unfolds.
#[rstest]
#[ignore = "divergence: hyper rejects obs-fold with a 400 where uvicorn unfolds it to one space"]
#[tokio::test]
async fn a_folded_header_reaches_python_unfolded() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET / HTTP/1.1\r\nhost: x\r\nx-a: b\r\n c\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().headers["x-a"], "b c");
}
#[rstest]
#[tokio::test]
async fn keeps_repeated_response_headers_and_opaque_header_bytes() {
let (upstream, mut received) = recording(|| {
Response::builder()
.header("set-cookie", "a=1; Path=/")
.header("set-cookie", "b=2; HttpOnly")
.header("x-opaque", HeaderValue::from_bytes(b"caf\xe9").unwrap())
.body(Body::empty())
.unwrap()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(b"GET / HTTP/1.1\r\nhost: x\r\nx-opaque: caf\xe9\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
let cookies: Vec<_> = head
.headers
.iter()
.filter(|(name, _)| name == "set-cookie")
.map(|(_, value)| value.as_slice())
.collect();
assert_eq!(cookies, [&b"a=1; Path=/"[..], b"b=2; HttpOnly"]);
assert_eq!(head.header("x-opaque"), Some(&b"caf\xe9"[..]));
assert_eq!(
received.recv().await.unwrap().headers["x-opaque"].as_bytes(),
b"caf\xe9"
);
}
/// An HTTP/1.0 client cannot decode chunked framing, so a streamed answer reaches it delimited by
/// the connection closing, as uvicorn sends it.
#[rstest]
#[tokio::test]
async fn an_http10_client_gets_a_streamed_answer_unframed_and_python_gets_its_body() {
let (upstream, mut received) = recording(|| {
Response::new(Body::from_stream(futures_util::stream::iter(
["str", "eamed"].map(|piece| Ok::<_, Infallible>(Bytes::from_static(piece.as_bytes()))),
)))
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST /v1/completions HTTP/1.0\r\nhost: x\r\ncontent-length: 7\r\n\r\npayload")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::OK);
assert_eq!(head.header("transfer-encoding"), None);
assert_eq!(within(raw.until_closed()).await, b"streamed");
let request = received.recv().await.unwrap();
assert_eq!(request.method, "POST");
assert_eq!(request.body, "payload");
}
#[rstest]
#[tokio::test]
async fn answers_pipelined_requests_in_order() {
let upstream = serve(
Router::new().fallback(|request: Request| async move { request.uri().path().to_owned() }),
)
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /first HTTP/1.1\r\nhost: x\r\n\r\nHEAD /second HTTP/1.1\r\nhost: x\r\n\r\nGET /third HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
let first = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(first.content_length().unwrap()).await, b"/first");
let second = within(raw.response_head()).await.unwrap();
assert_eq!(second.content_length(), Some(7));
let third = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(third.content_length().unwrap()).await, b"/third");
}
#[rstest]
#[case::no_content(StatusCode::NO_CONTENT)]
#[case::not_modified(StatusCode::NOT_MODIFIED)]
#[tokio::test]
async fn bodiless_statuses_keep_the_connection_reusable(#[case] status: StatusCode) {
let upstream = serve(Router::new().fallback(move |request: Request| async move {
match request.uri().path() {
"/next" => (StatusCode::OK, "next"),
_ => (status, ""),
}
}))
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /empty HTTP/1.1\r\nhost: x\r\n\r\nGET /next HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
assert_eq!(within(raw.response_head()).await.unwrap().status, status);
let next = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(next.content_length().unwrap()).await, b"next");
}
#[rstest]
#[tokio::test]
async fn informational_responses_keep_the_connection_reusable() {
let upstream = raw_upstream(|mut python| async move {
while let Some(head) = python.request_head().await {
match head.path.as_str() {
"/hints" => {
python
.send("HTTP/1.1 103 Early Hints\r\nlink: </ui/app.css>; rel=preload\r\n\r\nHTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nfinal")
.await
}
_ => {
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 4\r\n\r\nnext")
.await
}
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /hints HTTP/1.1\r\nhost: x\r\n\r\nGET /next HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
let mut hinted = within(raw.response_head()).await.unwrap();
while hinted.status.is_informational() {
hinted = within(raw.response_head()).await.unwrap();
}
assert_eq!(hinted.status, StatusCode::OK);
assert_eq!(raw.body(hinted.content_length().unwrap()).await, b"final");
let next = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(next.content_length().unwrap()).await, b"next");
}
#[rstest]
#[case::found(
StatusCode::FOUND,
"https://idp.example/authorize?state=a%2Fb&redirect_uri=https%3A%2F%2Fpublic.example%2Fsso%2Fcallback"
)]
#[case::see_other(StatusCode::SEE_OTHER, "/ui/?login=success")]
#[case::temporary(StatusCode::TEMPORARY_REDIRECT, "./mcp/oauth/authorize?client_id=x")]
#[tokio::test]
async fn redirects_reach_the_client_with_location_and_cookies_unchanged(
#[case] status: StatusCode,
#[case] location: &'static str,
) {
let (upstream, _received) = recording(move || {
Response::builder()
.status(status)
.header("location", location)
.header(
"set-cookie",
"token=a%2Fb; Path=/; HttpOnly; Secure; SameSite=Lax",
)
.header("set-cookie", "state=; Max-Age=0")
.header(
"set-cookie",
"session=x; Expires=Wed, 04 Nov 2026 10:00:00 GMT; Path=/",
)
.body(Body::empty())
.unwrap()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /sso/key/generate HTTP/1.1\r\nhost: public.example\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, status);
assert_eq!(head.header("location"), Some(location.as_bytes()));
let cookies: Vec<_> = head
.headers
.iter()
.filter(|(name, _)| name == "set-cookie")
.map(|(_, value)| value.as_slice())
.collect();
assert_eq!(
cookies,
[
&b"token=a%2Fb; Path=/; HttpOnly; Secure; SameSite=Lax"[..],
b"state=; Max-Age=0",
b"session=x; Expires=Wed, 04 Nov 2026 10:00:00 GMT; Path=/",
]
);
}
#[rstest]
#[tokio::test]
async fn non_websocket_upgrades_reach_python_as_plain_requests() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET / HTTP/1.1\r\nhost: x\r\nconnection: upgrade, http2-settings\r\nupgrade: h2c\r\nhttp2-settings: AAMAAABkAAQAoAAAAAIAAAAA\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
assert!(!request.headers.contains_key("upgrade"));
assert!(!request.headers.contains_key("connection"));
assert!(!request.headers.contains_key("http2-settings"));
}
#[rstest]
#[tokio::test]
async fn forwards_an_asterisk_form_options_request() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("OPTIONS * HTTP/1.1\r\nhost: x\r\n\r\n").await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
assert_eq!(request.method, "OPTIONS");
assert_eq!(request.uri, "*");
}
#[rstest]
#[tokio::test]
async fn an_authority_form_target_is_a_400_python_never_sees() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("CONNECT api.example:443 HTTP/1.1\r\nhost: api.example:443\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::BAD_REQUEST
);
assert!(received.try_recv().is_err());
}
#[rstest]
#[tokio::test]
async fn a_client_connection_close_ends_only_the_client_connection() {
let connections = Arc::new(AtomicUsize::new(0));
let accepted = connections.clone();
let upstream = raw_upstream(move |mut python| {
accepted.fetch_add(1, Ordering::SeqCst);
async move {
while python.request_head().await.is_some() {
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok")
.await;
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
for _ in 0..2 {
let mut raw = gateway.connect().await;
raw.send("GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.header("connection"), Some(&b"close"[..]));
assert_eq!(raw.body(2).await, b"ok");
within(raw.closed()).await;
}
assert_eq!(connections.load(Ordering::SeqCst), 1);
}
#[rstest]
#[tokio::test]
async fn a_python_connection_close_ends_only_the_upstream_connection() {
let connections = Arc::new(AtomicUsize::new(0));
let accepted = connections.clone();
let upstream = raw_upstream(move |mut python| {
accepted.fetch_add(1, Ordering::SeqCst);
async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 500 Internal Server Error\r\ncontent-length: 5\r\nconnection: close\r\n\r\nerror")
.await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
for _ in 0..2 {
raw.send("GET / HTTP/1.1\r\nhost: x\r\n\r\n").await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(head.header("connection"), None);
assert_eq!(raw.body(5).await, b"error");
}
assert_eq!(connections.load(Ordering::SeqCst), 2);
}
/// uvicorn answers HEAD on a streaming route with chunked framing and no body, so the client
/// must not be told the body is empty, and must not wait for one before its next request.
#[rstest]
#[tokio::test]
async fn head_answered_with_chunked_framing_claims_no_length_and_keeps_the_connection() {
let upstream = raw_upstream(|mut python| async move {
while let Some(head) = python.request_head().await {
match head.path.as_str() {
"/next" => {
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 4\r\n\r\nnext")
.await
}
_ => {
python
.send("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n")
.await
}
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("HEAD /mcp HTTP/1.1\r\nhost: x\r\n\r\nGET /next HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::OK);
assert_eq!(head.content_length(), None);
let next = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(next.content_length().unwrap()).await, b"next");
}
const GZIP: &[u8] = &[
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4b, 0x49, 0x2c, 0x49, 0xb4, 0x52,
0x30, 0xe4, 0xe2, 0x02, 0x00, 0xce, 0xcd, 0x78, 0x54, 0x09, 0x00, 0x00, 0x00,
];
#[rstest]
#[case::fixed_length(false)]
#[case::streamed(true)]
#[tokio::test]
async fn content_codings_cross_unchanged_both_ways(#[case] streamed: bool) {
let (upstream, mut received) = recording(move || {
let body = match streamed {
true => Body::from_stream(futures_util::stream::iter(
GZIP.chunks(5)
.map(|piece| Ok::<_, Infallible>(Bytes::from_static(piece))),
)),
false => Body::from(GZIP),
};
Response::builder()
.header("content-encoding", "gzip")
.header("vary", "Accept-Encoding")
.body(body)
.unwrap()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(
[
format!(
"POST /v1/chat/completions HTTP/1.1\r\nhost: x\r\ncontent-encoding: gzip\r\naccept-encoding: gzip, br;q=0.5\r\ncontent-length: {}\r\n\r\n",
GZIP.len()
)
.as_bytes(),
GZIP,
]
.concat(),
)
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.header("content-encoding"), Some(&b"gzip"[..]));
assert_eq!(head.header("vary"), Some(&b"Accept-Encoding"[..]));
let body = match head.content_length() {
Some(length) => raw.body(length).await,
None => within(raw.chunked_body()).await,
};
assert_eq!(body, GZIP);
assert_eq!(head.content_length().is_none(), streamed);
let request = received.recv().await.unwrap();
assert_eq!(request.headers["content-encoding"], "gzip");
assert_eq!(request.headers["accept-encoding"], "gzip, br;q=0.5");
assert_eq!(request.body, GZIP);
}
#[rstest]
#[tokio::test]
async fn python_sees_no_accept_encoding_the_client_did_not_send() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /metrics/ HTTP/1.1\r\nhost: x\r\n\r\n").await;
within(raw.response_head()).await.unwrap();
assert!(
!received
.recv()
.await
.unwrap()
.headers
.contains_key("accept-encoding")
);
}

View file

@ -0,0 +1,259 @@
mod support;
use std::{collections::BTreeSet, net::SocketAddr};
use axum::http::StatusCode;
use rstest::rstest;
use support::{Gateway, Head, Raw, raw_upstream, within};
use tokio::sync::mpsc;
struct Captured {
head: Head,
body: Vec<u8>,
}
/// A keep-alive upstream that decodes framing like h11 and reports every request it reads.
async fn capturing() -> (SocketAddr, mpsc::UnboundedReceiver<Captured>) {
let (sender, receiver) = mpsc::unbounded_channel();
let address = raw_upstream(move |mut python: Raw| {
let sender = sender.clone();
async move {
while let Some(head) = python.request_head().await {
let body = match head.header("transfer-encoding") {
Some(_) => python.chunked_body().await,
None => python.body(content_length(&head)).await,
};
sender.send(Captured { head, body }).unwrap();
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok")
.await;
}
}
})
.await;
(address, receiver)
}
/// The length h11 reads from every Content-Length field, which may repeat one value.
fn content_length(head: &Head) -> usize {
let lengths: BTreeSet<usize> = head
.headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("content-length"))
.flat_map(|(_, value)| value.split(|byte| *byte == b','))
.map(|length| {
std::str::from_utf8(length.trim_ascii())
.unwrap()
.parse()
.unwrap()
})
.collect();
assert!(
lengths.len() < 2,
"python got conflicting lengths {lengths:?}"
);
lengths.first().copied().unwrap_or(0)
}
/// RFC 9112 section 6.3: Transfer-Encoding overrides Content-Length. Forwarding both would let
/// Python split the stream at a different place than Rust did. Section 6.1 then closes the
/// connection after the response, so a request smuggled behind it never runs.
#[rstest]
#[tokio::test]
async fn a_request_framed_two_ways_reaches_python_framed_by_transfer_encoding_and_closes() {
let (upstream, mut received) = capturing().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST /v1/files HTTP/1.1\r\nhost: x\r\ncontent-length: 3\r\ntransfer-encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\nGET /next HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
raw.body(2).await;
within(raw.until_closed()).await;
let upload = received.recv().await.unwrap();
assert_eq!(upload.head.header("content-length"), None);
assert_eq!(
upload.head.header("transfer-encoding"),
Some(&b"chunked"[..])
);
assert_eq!(upload.body, b"hello");
assert!(
received.try_recv().is_err(),
"python ran the smuggled request"
);
}
#[rstest]
#[case::conflicting_content_lengths("content-length: 4\r\ncontent-length: 40\r\n")]
#[case::content_length_list("content-length: 4, 40\r\n")]
#[case::signed_content_length("content-length: +4\r\n")]
#[case::chunked_not_last("transfer-encoding: chunked, identity\r\ncontent-length: 4\r\n")]
#[case::unknown_coding("transfer-encoding: xchunked\r\ncontent-length: 4\r\n")]
#[case::space_before_colon("transfer-encoding : chunked\r\ncontent-length: 4\r\n")]
#[case::folded_transfer_encoding("transfer-encoding:\r\n chunked\r\ncontent-length: 4\r\n")]
#[case::bare_cr("x-a: b\rx-b: c\r\ncontent-length: 4\r\n")]
#[case::nul_byte("x-a: b\x00c\r\ncontent-length: 4\r\n")]
#[tokio::test]
async fn ambiguous_framing_never_reaches_python(#[case] headers: &str) {
let (upstream, mut received) = capturing().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\n{headers}\r\nbodyGET /smuggled HTTP/1.1\r\nhost: x\r\n\r\n"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::BAD_REQUEST
);
within(raw.closed()).await;
assert!(received.try_recv().is_err(), "python received a request");
}
#[rstest]
#[case::bare_lf("4\nbody\n0\n\n")]
#[case::invalid_size("zz\r\nbody\r\n0\r\n\r\n")]
#[case::size_overflow("10000000000000004\r\nbody\r\n0\r\n\r\n")]
#[tokio::test]
async fn a_malformed_request_body_is_a_400_not_a_502(#[case] chunks: &str) {
let upstream = raw_upstream(|mut python| async move { python.closed().await }).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n{chunks}"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::BAD_REQUEST
);
}
/// hyper decodes only the chunked layer, so any other coding would reach Python still coded but
/// framed as a plain body. uvicorn turns every h11 parse error into a 400, ignoring the 501 h11
/// suggests for codings.
#[rstest]
#[case::listed_before_chunked("transfer-encoding: gzip, chunked\r\n")]
#[case::split_across_fields("transfer-encoding: gzip\r\ntransfer-encoding: chunked\r\n")]
#[tokio::test]
async fn a_transfer_coding_other_than_chunked_is_the_400_uvicorn_sends_python_never_sees(
#[case] headers: &str,
) {
let (upstream, mut received) = capturing().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\n{headers}\r\n4\r\nbody\r\n0\r\n\r\n"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::BAD_REQUEST
);
assert!(
received.try_recv().is_err(),
"python received a still-coded body"
);
}
async fn assert_python_reads_the_body_and_the_next_request(headers: &str) {
let (upstream, mut received) = capturing().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\n{headers}\r\npayloadGET /next HTTP/1.1\r\nhost: x\r\n\r\n"
))
.await;
for _ in 0..2 {
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
raw.body(2).await;
}
assert_eq!(received.recv().await.unwrap().body, b"payload");
assert_eq!(received.recv().await.unwrap().head.path, "/next");
}
#[rstest]
#[case::repeated_fields("content-length: 7\r\ncontent-length: 7\r\n")]
#[case::leading_zeros("content-length: 007\r\n")]
#[tokio::test]
async fn a_content_length_h11_reads_one_way_reaches_python_framed_the_same(#[case] headers: &str) {
assert_python_reads_the_body_and_the_next_request(headers).await;
}
/// h11 accepts a Content-Length list that repeats one value, as RFC 9110 section 8.6 allows.
#[rstest]
#[ignore = "divergence: hyper's server parses each Content-Length field as one number and 400s a list"]
#[tokio::test]
async fn a_content_length_list_of_one_value_reaches_python() {
assert_python_reads_the_body_and_the_next_request("content-length: 7, 7\r\n").await;
}
#[rstest]
#[case::leading_zeros("0004\r\nbody\r\n0\r\n\r\n", "body")]
#[case::uppercase_hex("A\r\nbody\r\nbody\r\n0\r\n\r\n", "body\r\nbody")]
#[case::whitespace_after_size("4 \r\nbody\r\n0\r\n\r\n", "body")]
#[case::extension_and_trailer("4;a=\"b;c\"\r\nbody\r\n0\r\nx-sum: 1\r\n\r\n", "body")]
#[tokio::test]
async fn chunk_framing_h11_accepts_reaches_python_decoded(
#[case] chunks: &str,
#[case] body: &str,
) {
let (upstream, mut received) = capturing().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n{chunks}GET /next HTTP/1.1\r\nhost: x\r\n\r\n"
))
.await;
for _ in 0..2 {
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
raw.body(2).await;
}
assert_eq!(received.recv().await.unwrap().body, body.as_bytes());
assert_eq!(received.recv().await.unwrap().head.path, "/next");
}
/// h11 reads a head whose lines end in a bare LF, so Python gets the same request through Rust.
#[rstest]
#[tokio::test]
async fn a_head_with_bare_lf_line_endings_reaches_python() {
let (upstream, mut received) = capturing().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST /v1/files HTTP/1.1\nhost: x\nx-a: b\ncontent-length: 4\n\nbody")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let upload = received.recv().await.unwrap();
assert_eq!(upload.head.header("x-a"), Some(&b"b"[..]));
assert_eq!(upload.body, b"body");
}
/// h11 decodes a chunked body from an HTTP/1.0 client, and RFC 9112 section 6.1 only asks the
/// server to close the connection afterwards.
#[rstest]
#[ignore = "divergence: hyper rejects Transfer-Encoding on HTTP/1.0 with a 400 that uvicorn never sends"]
#[tokio::test]
async fn an_http10_chunked_upload_reaches_python() {
let (upstream, mut received) = capturing().await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST /v1/files HTTP/1.0\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n4\r\nbody\r\n0\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().body, b"body");
}

View file

@ -0,0 +1,102 @@
mod support;
use std::time::Duration;
use axum::{
body::Body,
extract::Request,
http::StatusCode,
response::{IntoResponse, Response},
};
use http_body_util::BodyExt;
use rstest::rstest;
use support::{Gateway, client, raw_upstream, recording, within};
use tokio::{sync::mpsc, time::Instant};
const SSE_HEAD: &str = "HTTP/1.1 200 OK\r\n\
date: Tue, 03 Nov 2026 00:00:00 GMT\r\n\
server: uvicorn\r\n\
cache-control: no-cache, no-transform\r\n\
connection: keep-alive\r\n\
content-type: text/event-stream\r\n\
mcp-session-id: session-1\r\n\
x-accel-buffering: no\r\n\
transfer-encoding: chunked\r\n\r\n";
const PING: &str = ": ping - 2026-11-03 00:20:00.000000+00:00\r\n\r\n";
const MESSAGE: &str = "event: message\r\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\r\n\r\n";
fn chunk(data: &str) -> String {
format!("{:x}\r\n{data}\r\n", data.len())
}
/// An MCP client holds a GET stream open for server-initiated messages, which may not come for
/// many minutes, so neither hop may close a stream for being idle.
#[rstest]
#[tokio::test(start_paused = true)]
async fn an_idle_mcp_stream_stays_open_in_both_directions() {
let idle = Duration::from_secs(20 * 60);
let (session, mut sessions) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python| {
let session = session.clone();
async move {
let head = python.request_head().await.unwrap();
session
.send(head.header("mcp-session-id").map(<[u8]>::to_vec))
.unwrap();
python.send(SSE_HEAD).await;
tokio::time::sleep(idle).await;
python.send(chunk(PING)).await;
python.send(chunk(MESSAGE)).await;
python.send("0\r\n\r\n").await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let started = Instant::now();
let response = client()
.request(
Request::get(gateway.url("/github/mcp"))
.header("accept", "text/event-stream")
.header("mcp-session-id", "session-1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.headers()["mcp-session-id"], "session-1");
assert_eq!(response.headers()["x-accel-buffering"], "no");
assert!(!response.headers().contains_key("connection"));
assert_eq!(
sessions.recv().await.unwrap().as_deref(),
Some(&b"session-1"[..])
);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(body, [PING, MESSAGE].concat());
assert!(started.elapsed() >= idle);
}
#[rstest]
#[tokio::test]
async fn ends_a_session_with_a_bodiless_delete() {
let (upstream, mut received) = recording(|| -> Response {
([("mcp-session-id", "session-1")], StatusCode::NO_CONTENT).into_response()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("DELETE /mcp HTTP/1.1\r\nhost: x\r\nmcp-session-id: session-1\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::NO_CONTENT);
assert_eq!(head.header("mcp-session-id"), Some(&b"session-1"[..]));
let request = received.recv().await.unwrap();
assert_eq!(request.method, "DELETE");
assert_eq!(request.headers["mcp-session-id"], "session-1");
assert!(!request.headers.contains_key("transfer-encoding"));
assert!(request.body.is_empty());
}

View file

@ -0,0 +1,473 @@
mod support;
use std::{
sync::Arc,
time::{Duration, Instant},
};
use axum::{Router, body::Body, extract::Request, http::StatusCode, response::Response};
use http_body_util::BodyExt;
use rstest::rstest;
use support::{
DRAIN, Gateway, Raw, client, raw_upstream, recording, serve, unreachable_upstream, within,
};
use tokio::{
net::{TcpListener, TcpStream},
sync::{Notify, mpsc},
};
fn ok() -> Response {
Response::new(Body::from("ok"))
}
/// Python stops a provider stream when it sees the client go away, so a client disconnect must
/// close Rust's connection to Python at every stage of the exchange.
#[rstest]
#[case::waiting_for_headers(
"POST /v1/chat/completions HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n",
false
)]
#[case::mid_stream(
"POST /v1/chat/completions HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n",
true
)]
#[case::mid_upload(
"POST /v1/files HTTP/1.1\r\nhost: x\r\ncontent-length: 1000000\r\n\r\npartial",
false
)]
#[case::waiting_for_websocket_handshake(
"GET /v1/realtime HTTP/1.1\r\nhost: x\r\nconnection: Upgrade\r\nupgrade: websocket\r\nsec-websocket-version: 13\r\nsec-websocket-key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n",
false
)]
#[tokio::test]
async fn client_disconnect_closes_the_upstream_connection(
#[case] request: &'static str,
#[case] headers_sent: bool,
) {
let (event, mut events) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let event = event.clone();
async move {
python.request_head().await.unwrap();
if headers_sent {
python
.send("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n6\r\ndata: \r\n")
.await;
}
event.send("received").unwrap();
python.closed().await;
event.send("closed").unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(request).await;
assert_eq!(within(events.recv()).await, Some("received"));
if headers_sent {
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
}
drop(raw);
assert_eq!(within(events.recv()).await, Some("closed"));
}
/// Python treats EOF on its socket as the client leaving, so Rust must not half-close the
/// upstream connection once it has sent the request body.
#[rstest]
#[tokio::test]
async fn python_sees_no_eof_while_its_response_is_pending() {
let (verdict, mut verdicts) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let verdict = verdict.clone();
async move {
let head = python.request_head().await.unwrap();
python.body(head.content_length().unwrap()).await;
let eof = tokio::time::timeout(Duration::from_millis(200), python.closed())
.await
.is_ok();
verdict.send(eof).unwrap();
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok")
.await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let response = within(
client().request(
Request::post(gateway.url("/mcp"))
.body(Body::from("{}"))
.unwrap(),
),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(verdicts.recv().await, Some(false));
}
/// uvicorn closes a connection that sat idle past its keep-alive timeout. A request Rust sends on
/// that connection as uvicorn closes it is lost, so Rust must retire idle connections first.
#[rstest]
#[case::reused_while_fresh(Duration::from_millis(0))]
#[case::past_the_pool_timeout(Duration::from_millis(250))]
#[case::past_python_keepalive(Duration::from_millis(450))]
#[tokio::test]
async fn never_reuses_a_connection_python_is_closing_for_idleness(#[case] idle: Duration) {
let keepalive = Duration::from_millis(400);
let upstream = raw_upstream(move |mut python: Raw| async move {
let mut idle_since = None::<Instant>;
while python.request_head().await.is_some() {
if idle_since.is_some_and(|since| since.elapsed() >= keepalive) {
return;
}
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok")
.await;
idle_since = Some(Instant::now());
}
})
.await;
let gateway = Gateway::with_keepalive(upstream, keepalive).await;
let client = client();
let first = within(client.request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
first.into_body().collect().await.unwrap();
tokio::time::sleep(idle).await;
let second =
within(client.request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
assert_eq!(second.status(), StatusCode::OK);
}
#[rstest]
#[case::health("/health/liveliness")]
#[case::messages("/v1/messages")]
#[tokio::test]
async fn unreachable_python_is_a_502(#[case] path: &str) {
let gateway = Gateway::start(unreachable_upstream()).await;
let response =
within(client().request(Request::get(gateway.url(path)).body(Body::empty()).unwrap()))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
}
#[rstest]
#[case::bad_status_line(b"HTTP/1.1 OK\r\ncontent-length: 0\r\n\r\n".to_vec())]
#[case::header_without_colon(b"HTTP/1.1 200 OK\r\nbroken header\r\ncontent-length: 0\r\n\r\n".to_vec())]
#[case::not_http(b"SSH-2.0-OpenSSH_9.6\r\n".to_vec())]
#[case::conflicting_lengths(
b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\ncontent-length: 3\r\n\r\nok".to_vec()
)]
#[case::oversized_head(
[&b"HTTP/1.1 200 OK\r\nx-big: "[..], &vec![b'a'; 1024 * 1024], b"\r\n\r\n"].concat()
)]
#[case::closed_without_reply(Vec::new())]
#[tokio::test]
async fn an_upstream_that_breaks_http_is_a_502_and_the_client_connection_survives(
#[case] reply: Vec<u8>,
) {
let upstream = raw_upstream(move |mut python: Raw| {
let reply = reply.clone();
async move {
python.request_head().await.unwrap();
if reply.is_empty() {
return;
}
python.send(reply).await;
std::future::pending::<()>().await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
for _ in 0..2 {
raw.send("GET / HTTP/1.1\r\nhost: x\r\n\r\n").await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::BAD_GATEWAY);
assert_eq!(head.content_length(), Some(0));
}
}
#[rstest]
#[tokio::test]
async fn python_restarting_is_a_502_until_it_listens_again() {
let address = unreachable_upstream();
let gateway = Gateway::start(address).await;
let get = || client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap());
assert_eq!(
within(get()).await.unwrap().status(),
StatusCode::BAD_GATEWAY
);
let listener = TcpListener::bind(address).await.unwrap();
let router = Router::new().fallback(|| async { "up" });
tokio::spawn(async move { axum::serve(listener, router).await });
assert_eq!(within(get()).await.unwrap().status(), StatusCode::OK);
}
/// A request Python already read may have run, so it is answered with a 502 and never replayed.
#[rstest]
#[tokio::test]
async fn a_request_python_read_before_closing_is_a_502_and_never_replayed() {
let (event, mut seen) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let event = event.clone();
async move {
while let Some(head) = python.request_head().await {
python.body(head.content_length().unwrap()).await;
event.send(head.path.clone()).unwrap();
if head.path == "/v1/chat/completions" {
return;
}
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok")
.await;
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST /warm HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n")
.await;
let warm = within(raw.response_head()).await.unwrap();
raw.body(warm.content_length().unwrap()).await;
raw.send("POST /v1/chat/completions HTTP/1.1\r\nhost: x\r\ncontent-length: 2\r\n\r\n{}")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::BAD_GATEWAY);
let paths: Vec<_> = std::iter::from_fn(|| seen.try_recv().ok()).collect();
assert_eq!(paths, ["/warm", "/v1/chat/completions"]);
}
#[rstest]
#[tokio::test]
async fn shutdown_lets_an_in_flight_stream_finish() {
let release = Arc::new(Notify::new());
let released = release.clone();
let upstream = raw_upstream(move |mut python: Raw| {
let released = released.clone();
async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n5\r\nfirst\r\n")
.await;
released.notified().await;
python.send("4\r\nlast\r\n0\r\n\r\n").await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let response =
within(client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
let server = gateway.shutdown();
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(!server.is_finished());
release.notify_one();
let body = within(response.into_body().collect())
.await
.unwrap()
.to_bytes();
assert_eq!(body, "firstlast");
within(server).await.unwrap();
}
#[rstest]
#[tokio::test]
async fn shutdown_stops_waiting_for_a_stream_still_open_after_the_drain() {
let upstream = raw_upstream(|mut python: Raw| async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n5\r\nfirst\r\n")
.await;
std::future::pending::<()>().await;
})
.await;
let gateway = Gateway::start(upstream).await;
let response =
within(client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
let started = std::time::Instant::now();
within(gateway.shutdown()).await.unwrap();
assert!(started.elapsed() >= DRAIN);
drop(response);
}
#[rstest]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_keep_alive_connections_each_get_their_own_responses() {
let upstream = serve(Router::new().fallback(|request: Request| async move {
let index: usize = request.uri().query().unwrap().parse().unwrap();
Response::builder()
.header("etag", format!("\"{index}\""))
.body(Body::from(index.to_string().repeat(1 + index * 1000)))
.unwrap()
}))
.await;
let gateway = Gateway::start(upstream).await;
let connections = 6;
let tasks: Vec<_> = (0..connections)
.map(|first| {
let address = gateway.address;
tokio::spawn(async move {
let mut raw = Raw::new(TcpStream::connect(address).await.unwrap());
for index in (first..50).step_by(connections) {
raw.send(format!(
"GET /ui/chunk.js?{index} HTTP/1.1\r\nhost: x\r\n\r\n"
))
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.header("etag"), Some(format!("\"{index}\"").as_bytes()));
let body = raw.body(head.content_length().unwrap()).await;
assert_eq!(
body,
index.to_string().repeat(1 + index * 1000).into_bytes()
);
}
})
})
.collect();
for task in tasks {
within(task).await.unwrap();
}
}
// Python's `--keepalive_timeout` governed idle client connections before Rust took the public
// port, and operators tune it against their load balancer's idle timeout, so it still does.
// Without it, a client that vanishes without closing its connection holds a socket forever and
// the gateway eventually runs out of file descriptors.
const IDLE: Duration = Duration::from_millis(400);
#[rstest]
#[tokio::test]
async fn closes_a_client_connection_idle_past_python_keepalive() {
let (upstream, _received) = recording(ok).await;
let gateway = Gateway::with_keepalive(upstream, IDLE).await;
let mut raw = gateway.connect().await;
for _ in 0..2 {
tokio::time::sleep(IDLE / 2).await;
raw.send("GET /health/liveliness HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::OK);
raw.body(head.content_length().unwrap()).await;
}
let idle_since = Instant::now();
within(raw.closed()).await;
assert!(idle_since.elapsed() >= IDLE * 3 / 4);
}
/// uvicorn would hold a connection that never sends a request, which lets a client park sockets
/// for free, so the same limit applies before the first request too.
#[rstest]
#[tokio::test]
async fn closes_a_client_connection_that_never_sends_a_request() {
let (upstream, _received) = recording(ok).await;
let gateway = Gateway::with_keepalive(upstream, IDLE).await;
let mut raw = gateway.connect().await;
within(raw.closed()).await;
}
/// The limit only covers the wait for the next request. A response that goes quiet for longer
/// belongs to Python, which decides how long it may take.
#[rstest]
#[tokio::test]
async fn keeps_a_connection_open_while_a_response_goes_quiet() {
let upstream = raw_upstream(|mut python: Raw| async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n")
.await;
tokio::time::sleep(IDLE * 3).await;
python.send("4\r\ndone\r\n0\r\n\r\n").await;
})
.await;
let gateway = Gateway::with_keepalive(upstream, IDLE).await;
let mut raw = gateway.connect().await;
raw.send("GET /v1/chat/completions HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
within(raw.response_head()).await.unwrap();
assert_eq!(within(raw.chunked_body()).await, b"done");
}
/// Likewise for an upload that pauses longer than the limit before it finishes.
#[rstest]
#[tokio::test]
async fn keeps_a_connection_open_while_an_upload_goes_quiet() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::with_keepalive(upstream, IDLE).await;
let mut raw = gateway.connect().await;
raw.send("POST /v1/files HTTP/1.1\r\nhost: x\r\ncontent-length: 8\r\n\r\nhalf")
.await;
tokio::time::sleep(IDLE * 3).await;
raw.send("done").await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().body, "halfdone");
}
/// uvicorn answers a request it rejects (413, 401) as soon as it reads the head and then closes,
/// leaving the upload unread. The client must get that answer, not a 502 or a reset.
#[rstest]
#[case::sized("content-length: 16777216\r\n", vec![b'x'; 256 * 1024])]
#[case::chunked(
"transfer-encoding: chunked\r\n",
[&b"40000\r\n"[..], &[b'x'; 256 * 1024], b"\r\n"].concat()
)]
#[tokio::test]
async fn python_rejecting_an_upload_unread_and_closing_still_answers_the_client(
#[case] framing: &'static str,
#[case] partial_upload: Vec<u8>,
) {
let upstream = raw_upstream(|mut python: Raw| async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 413 Payload Too Large\r\ncontent-type: application/json\r\ncontent-length: 26\r\nconnection: close\r\n\r\n{\"error\":\"file too large\"}")
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\n{framing}\r\n"
))
.await;
raw.send(partial_upload).await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
raw.body(head.content_length().unwrap()).await,
b"{\"error\":\"file too large\"}"
);
}

View file

@ -0,0 +1,360 @@
mod support;
use std::{
convert::Infallible,
sync::{Arc, Mutex},
};
use axum::{
body::{Body, Bytes},
http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
response::Response,
};
use http_body_util::BodyExt;
use litellm_gateway_forward::PEER_HEADER;
use proptest::{prelude::*, test_runner::TestRunner};
use support::{Gateway, client, recording, within};
#[derive(Clone, Debug)]
struct Message {
headers: Vec<(String, Vec<Vec<u8>>)>,
body: Vec<u8>,
chunked: bool,
}
#[derive(Clone, Debug)]
struct Exchange {
method: Method,
target: String,
request: Message,
status: StatusCode,
response: Message,
}
/// Any value h11 reads back unchanged: visible ASCII, obs-text and interior whitespace.
fn header_value() -> impl Strategy<Value = Vec<u8>> {
prop::collection::vec(
prop_oneof![8 => 0x21u8..=0x7e, 2 => 0x80u8..=0xff, 1 => Just(b' '), 1 => Just(b'\t')],
0..24,
)
.prop_map(|value| value.trim_ascii().to_vec())
}
fn method() -> impl Strategy<Value = Method> {
prop_oneof![
Just(Method::GET),
Just(Method::POST),
Just(Method::PUT),
Just(Method::PATCH),
Just(Method::DELETE),
Just(Method::OPTIONS),
"[A-Za-z0-9!#$%&'*+.^_`|~-]{1,16}"
.prop_filter("HEAD and CONNECT frame differently", |method| {
!["HEAD", "CONNECT"].contains(&method.as_str())
})
.prop_map(|method| Method::from_bytes(method.as_bytes()).unwrap()),
]
}
fn message() -> impl Strategy<Value = Message> {
(
prop::collection::btree_map(
"x-[a-z0-9!#$%&'*+.^_`|~-]{1,12}",
prop::collection::vec(header_value(), 1..4),
0..12,
),
prop::collection::vec(any::<u8>(), 0..32 * 1024),
any::<bool>(),
)
.prop_map(|(headers, body, chunked)| Message {
headers: headers.into_iter().collect(),
body,
chunked,
})
}
fn target() -> impl Strategy<Value = String> {
let segment = prop_oneof![
"[A-Za-z0-9._~!$&'()*+,;=:@-]{0,8}",
"%[0-9A-Fa-f]{2}",
Just(".".to_owned()),
Just("..".to_owned()),
Just(String::new()),
];
(
prop::collection::vec(segment, 0..6),
prop::option::of("[A-Za-z0-9=&._~%/?:@!$'()*+,;-]{0,40}"),
)
.prop_map(|(segments, query)| {
let path = format!("/{}", segments.join("/"));
match query {
Some(query) => format!("{path}?{query}"),
None => path,
}
})
}
fn exchange() -> impl Strategy<Value = Exchange> {
let status = (200u16..600)
.prop_filter("bodiless status", |code| ![204, 205, 304].contains(code))
.prop_map(|code| StatusCode::from_u16(code).unwrap());
(method(), target(), message(), status, message()).prop_map(
|(method, target, request, status, response)| Exchange {
method,
target,
request,
status,
response,
},
)
}
fn body(message: &Message) -> Body {
if !message.chunked {
return Body::from(message.body.clone());
}
let chunks: Vec<Result<Bytes, Infallible>> = message
.body
.chunks(1000)
.map(|chunk| Ok(Bytes::copy_from_slice(chunk)))
.collect();
Body::from_stream(futures_util::stream::iter(chunks))
}
fn apply(headers: &mut HeaderMap, message: &Message) {
if message.chunked {
headers.insert("transfer-encoding", HeaderValue::from_static("chunked"));
}
for (name, values) in &message.headers {
for value in values {
headers.append(
HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_bytes(value).unwrap(),
);
}
}
}
fn assert_carried(headers: &HeaderMap, message: &Message, framing_and_hop: &[&str]) {
for (name, values) in &message.headers {
let carried: Vec<&[u8]> = headers
.get_all(name)
.iter()
.map(HeaderValue::as_bytes)
.collect();
let sent: Vec<&[u8]> = values.iter().map(Vec::as_slice).collect();
assert_eq!(carried, sent, "header {name}");
}
for name in headers.keys() {
assert!(
framing_and_hop.contains(&name.as_str())
|| message
.headers
.iter()
.any(|(sent, _)| sent == name.as_str()),
"unexpected header {name}"
);
}
}
/// Any request a client can send and any response Python can give cross the forwarder unchanged,
/// apart from the framing and peer headers the forwarder owns.
#[test]
fn every_exchange_crosses_the_forwarder_unchanged() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let current = Arc::new(Mutex::new(None::<Exchange>));
let responding = current.clone();
let (gateway, received) = runtime.block_on(async {
let (upstream, received) = recording(move || {
let exchange = responding.lock().unwrap().clone().unwrap();
let mut response = Response::new(body(&exchange.response));
*response.status_mut() = exchange.status;
apply(response.headers_mut(), &exchange.response);
response
})
.await;
(
Gateway::start(upstream).await,
tokio::sync::Mutex::new(received),
)
});
let client = client();
TestRunner::new(ProptestConfig::with_cases(256))
.run(&exchange(), |exchange| {
*current.lock().unwrap() = Some(exchange.clone());
runtime.block_on(async {
while received.lock().await.try_recv().is_ok() {}
let mut request = Request::builder()
.method(exchange.method.clone())
.uri(gateway.url(&exchange.target))
.body(body(&exchange.request))
.unwrap();
apply(request.headers_mut(), &exchange.request);
let response = support::within(client.request(request)).await.unwrap();
let python = received.lock().await.recv().await.unwrap();
assert_eq!(python.method, exchange.method);
assert_eq!(python.uri, exchange.target.as_str());
assert_eq!(python.body, exchange.request.body);
assert_carried(
&python.headers,
&exchange.request,
&["host", "content-length", "transfer-encoding", PEER_HEADER],
);
assert_eq!(python.headers.get_all(PEER_HEADER).iter().count(), 1);
assert_eq!(response.status(), exchange.status);
let headers = response.headers().clone();
assert_carried(
&headers,
&exchange.response,
&["date", "content-length", "transfer-encoding"],
);
let body = support::within(response.into_body().collect())
.await
.unwrap();
assert_eq!(body.to_bytes(), exchange.response.body);
});
Ok(())
})
.unwrap();
}
#[derive(Clone, Debug)]
enum Framing {
Unframed,
Length,
Chunked(usize),
}
#[derive(Clone, Debug)]
struct WireRequest {
method: Method,
target: String,
headers: Vec<(String, Vec<u8>)>,
body: Vec<u8>,
framing: Framing,
}
fn wire_request() -> impl Strategy<Value = WireRequest> {
let framing = prop_oneof![
Just(Framing::Unframed),
Just(Framing::Length),
(1usize..2048).prop_map(Framing::Chunked),
];
(
method(),
target(),
prop::collection::vec(
("[xX]-[A-Za-z0-9!#$%&'*+.^_`|~-]{1,12}", header_value()),
0..24,
),
prop::collection::vec(any::<u8>(), 0..8 * 1024),
framing,
)
.prop_map(|(method, target, headers, body, framing)| WireRequest {
method,
target,
headers,
body: match framing {
Framing::Unframed => Vec::new(),
_ => body,
},
framing,
})
}
fn encode(request: &WireRequest) -> Vec<u8> {
let framing = match request.framing {
Framing::Unframed => String::new(),
Framing::Length => format!("Content-Length: {}\r\n", request.body.len()),
Framing::Chunked(_) => "Transfer-Encoding: chunked\r\n".to_owned(),
};
let fields = request
.headers
.iter()
.flat_map(|(name, value)| [name.as_bytes(), b": ", value, b"\r\n"].concat());
let body = match request.framing {
Framing::Chunked(size) => request
.body
.chunks(size)
.flat_map(|chunk| {
[format!("{:x}\r\n", chunk.len()).as_bytes(), chunk, b"\r\n"].concat()
})
.chain(*b"0\r\n\r\n")
.collect(),
_ => request.body.clone(),
};
[
format!(
"{} {} HTTP/1.1\r\nHost: x\r\n",
request.method, request.target
)
.into_bytes(),
fields.collect(),
framing.into_bytes(),
b"\r\n".to_vec(),
body,
]
.concat()
}
fn by_name<'a>(fields: impl Iterator<Item = (&'a str, &'a [u8])>) -> Vec<(String, &'a [u8])> {
let mut fields: Vec<_> = fields
.map(|(name, value)| (name.to_ascii_lowercase(), value))
.collect();
fields.sort_by(|(left, _), (right, _)| left.cmp(right));
fields
}
/// Pipelined requests in any framing, written in arbitrary pieces, reach Python one by one with
/// the bytes h11 would have read from the client directly.
#[test]
fn pipelined_wire_requests_reach_python_as_sent() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let (gateway, received) = runtime.block_on(async {
let (upstream, received) = recording(|| Response::new(Body::from("ok"))).await;
(
Gateway::start(upstream).await,
tokio::sync::Mutex::new(received),
)
});
let requests = (prop::collection::vec(wire_request(), 1..5), 1usize..4096);
TestRunner::new(ProptestConfig::with_cases(256))
.run(&requests, |(requests, piece)| {
runtime.block_on(async {
let mut received = received.lock().await;
while received.try_recv().is_ok() {}
let mut raw = gateway.connect().await;
let wire: Vec<u8> = requests.iter().flat_map(encode).collect();
for bytes in wire.chunks(piece) {
raw.send(bytes).await;
}
for request in &requests {
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::OK, "{request:?}");
assert_eq!(raw.body(2).await, b"ok");
let python = within(received.recv()).await.unwrap();
assert_eq!(python.method, request.method);
assert_eq!(python.uri, request.target.as_str());
assert_eq!(python.body, request.body);
assert_eq!(python.headers["host"], "x");
let forwarded = python.headers.iter().filter(|(name, _)| {
!["host", "content-length", "transfer-encoding", PEER_HEADER]
.contains(&name.as_str())
});
assert_eq!(
by_name(forwarded.map(|(name, value)| (name.as_str(), value.as_bytes()))),
by_name(
request
.headers
.iter()
.map(|(name, value)| (name.as_str(), value.as_slice()))
)
);
}
});
Ok(())
})
.unwrap();
}

View file

@ -0,0 +1,110 @@
use std::{ffi::OsString, time::Duration};
use litellm_gateway_forward::{Error, Settings};
use rstest::rstest;
const COMPLETE: [(&str, &str); 5] = [
("LITELLM_FORWARD_UPSTREAM", "http://127.0.0.1:53211"),
("LITELLM_FORWARD_HOST", "0.0.0.0"),
("LITELLM_FORWARD_PORT", "4000"),
("LITELLM_FORWARD_UPSTREAM_KEEPALIVE", "2"),
("LITELLM_FORWARD_SHUTDOWN_DRAIN", "40"),
];
fn parse(variables: &[(&str, &str)]) -> Result<Option<Settings>, Error> {
Settings::from_vars(
variables
.iter()
.map(|(key, value)| (OsString::from(key), OsString::from(value))),
)
}
fn without(variable: &str) -> Vec<(&'static str, &'static str)> {
COMPLETE
.into_iter()
.filter(|(key, _)| *key != variable)
.collect()
}
fn with<'a>(variable: &'a str, value: &'a str) -> Vec<(&'a str, &'a str)> {
without(variable)
.into_iter()
.chain([(variable, value)])
.collect()
}
#[rstest]
fn reads_every_variable() {
assert_eq!(
parse(&COMPLETE).unwrap(),
Some(Settings {
upstream: "http://127.0.0.1:53211".parse().unwrap(),
host: "0.0.0.0".into(),
port: 4000,
upstream_keepalive: Duration::from_secs(2),
shutdown_drain: Duration::from_secs(40),
})
);
}
#[rstest]
fn without_an_upstream_the_gateway_is_not_forwarding() {
assert_eq!(parse(&without("LITELLM_FORWARD_UPSTREAM")).unwrap(), None);
}
#[rstest]
#[case::host("LITELLM_FORWARD_HOST")]
#[case::port("LITELLM_FORWARD_PORT")]
#[case::upstream_keepalive("LITELLM_FORWARD_UPSTREAM_KEEPALIVE")]
#[case::shutdown_drain("LITELLM_FORWARD_SHUTDOWN_DRAIN")]
fn a_missing_variable_fails_naming_it(#[case] variable: &str) {
let error = parse(&without(variable)).unwrap_err();
assert!(error.to_string().contains(variable), "{error}");
}
#[rstest]
#[case::port_overflow("LITELLM_FORWARD_PORT", "65536")]
#[case::port_text("LITELLM_FORWARD_PORT", "http")]
#[case::keepalive_text("LITELLM_FORWARD_UPSTREAM_KEEPALIVE", "soon")]
#[case::keepalive_negative("LITELLM_FORWARD_UPSTREAM_KEEPALIVE", "-1")]
#[case::keepalive_zero("LITELLM_FORWARD_UPSTREAM_KEEPALIVE", "0")]
#[case::drain_text("LITELLM_FORWARD_SHUTDOWN_DRAIN", "soon")]
#[case::drain_negative("LITELLM_FORWARD_SHUTDOWN_DRAIN", "-1")]
#[case::drain_infinite("LITELLM_FORWARD_SHUTDOWN_DRAIN", "inf")]
fn an_invalid_variable_fails_naming_it(#[case] variable: &str, #[case] value: &str) {
let error = parse(&with(variable, value)).unwrap_err();
assert!(error.to_string().contains(variable), "{error}");
}
#[rstest]
fn fractional_drain_seconds_are_used_as_given() {
let settings = parse(&with("LITELLM_FORWARD_SHUTDOWN_DRAIN", "12.5"))
.unwrap()
.unwrap();
assert_eq!(settings.shutdown_drain, Duration::from_millis(12_500));
}
#[rstest]
#[case::keepalive("KEEPALIVE_TIMEOUT")]
#[case::graceful_shutdown("GRACEFUL_SHUTDOWN_TIMEOUT")]
#[case::host("HOST")]
#[case::port("PORT")]
fn python_settings_are_never_read(#[case] variable: &str) {
let mut variables = COMPLETE.to_vec();
variables.push((variable, "9"));
assert_eq!(parse(&variables).unwrap(), parse(&COMPLETE).unwrap());
}
#[rstest]
fn a_non_loopback_upstream_fails_startup() {
let error = parse(&with("LITELLM_FORWARD_UPSTREAM", "http://192.0.2.1:4000")).unwrap_err();
assert!(
error.to_string().contains("LITELLM_FORWARD_UPSTREAM"),
"{error}"
);
}

View file

@ -0,0 +1,41 @@
mod support;
use std::time::Duration;
use axum::{body::Body, extract::Request, http::StatusCode};
use http_body_util::BodyExt;
use rstest::rstest;
use support::{Gateway, client, raw_upstream};
use tokio::time::Instant;
/// Reasoning models with `stream=false`, image and video generation, and model health checks send
/// no response headers until the provider finishes, which can take many minutes.
#[rstest]
#[tokio::test(start_paused = true)]
async fn waits_for_response_headers_as_long_as_python_takes() {
let thinking = Duration::from_secs(30 * 60);
let upstream = raw_upstream(move |mut python| async move {
python.request_head().await.unwrap();
tokio::time::sleep(thinking).await;
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nimage")
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let started = Instant::now();
let response = client()
.request(
Request::post(gateway.url("/v1/images/generations"))
.body(Body::from("{}"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(started.elapsed() >= thinking);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(body, "image");
}

View file

@ -0,0 +1,313 @@
mod support;
use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use axum::{body::Body, extract::Request, http::StatusCode};
use http_body_util::BodyExt;
use hyper::body::Incoming;
use rstest::rstest;
use support::{Gateway, client, raw_upstream, within};
use tokio::{
io::AsyncWriteExt,
sync::{Notify, mpsc},
};
fn chunk(bytes: &[u8]) -> Vec<u8> {
[format!("{:x}\r\n", bytes.len()).as_bytes(), bytes, b"\r\n"].concat()
}
const EVENTS: [&str; 3] = ["data: 1\n\n", "data: 2\n\n", "data: [DONE]\n\n"];
#[rstest]
#[tokio::test]
async fn each_event_reaches_the_client_before_python_produces_the_next(
#[values(true, false)] chunked: bool,
) {
let produce = Arc::new(Notify::new());
let next = produce.clone();
let upstream = raw_upstream(move |mut python| {
let next = next.clone();
async move {
python.request_head().await.unwrap();
let framing = match chunked {
true => "transfer-encoding: chunked".to_owned(),
false => format!("content-length: {}", EVENTS.concat().len()),
};
python
.send(format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n{framing}\r\n\r\n"
))
.await;
for event in EVENTS {
match chunked {
true => python.send(chunk(event.as_bytes())).await,
false => python.send(event).await,
}
next.notified().await;
}
if chunked {
python.send("0\r\n\r\n").await;
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut response = within(
client().request(
Request::post(gateway.url("/v1/chat/completions"))
.body(Body::from(r#"{"stream":true}"#))
.unwrap(),
),
)
.await
.unwrap();
for event in EVENTS {
let frame = within(response.body_mut().frame()).await.unwrap().unwrap();
assert_eq!(frame.into_data().unwrap(), event);
produce.notify_one();
}
let rest = within(response.into_body().collect()).await.unwrap();
assert!(rest.to_bytes().is_empty());
}
#[rstest]
#[tokio::test]
async fn relays_a_binary_framed_stream_unchanged() {
let message: Vec<u8> = [
&[
0x00, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x00, 0x20, 0x8a, 0x0d, 0x0a, 0xff,
][..],
b"\x0b:event-type\x07\x00\x05chunk\x0d:content-type\x07\x00\x10application/json",
b"0\r\n\r\n{\"bytes\":\"eyJ0eXBlIjoiY29udGVudCJ9\"}",
&[0xc3, 0x28, 0x00, 0x0d],
]
.concat();
let sent = message.clone();
let upstream = raw_upstream(move |mut python| {
let sent = sent.clone();
async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ncontent-type: application/vnd.amazon.eventstream\r\ntransfer-encoding: chunked\r\n\r\n")
.await;
for piece in sent.chunks(7) {
python.send(chunk(piece)).await;
}
python.send("0\r\n\r\n").await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let response = within(
client().request(
Request::post(gateway.url("/bedrock/model/m/converse-stream"))
.body(Body::empty())
.unwrap(),
),
)
.await
.unwrap();
assert_eq!(
response.headers()["content-type"],
"application/vnd.amazon.eventstream"
);
let body = within(response.into_body().collect())
.await
.unwrap()
.to_bytes();
assert_eq!(body, message);
}
#[rstest]
#[tokio::test]
async fn relays_a_body_delimited_by_the_upstream_closing() {
let upstream = raw_upstream(|mut python| async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\nconnection: close\r\n\r\nuntil eof")
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let response = client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap());
let body = within(response).await.unwrap().into_body().collect();
assert_eq!(within(body).await.unwrap().to_bytes(), "until eof");
}
async fn drain(mut body: Incoming) -> (Vec<u8>, Result<(), hyper::Error>) {
let mut delivered = Vec::new();
loop {
match within(body.frame()).await {
None => return (delivered, Ok(())),
Some(Err(error)) => return (delivered, Err(error)),
Some(Ok(frame)) => delivered.extend_from_slice(&frame.into_data().unwrap()),
}
}
}
#[rstest]
#[case::after_the_head("transfer-encoding: chunked", "", "")]
#[case::between_events("transfer-encoding: chunked", "6\r\ndata: \r\n", "data: ")]
#[case::mid_event("transfer-encoding: chunked", "a\r\ndata:", "data:")]
#[case::short_of_its_content_length("content-length: 100", "data: 1\n\n", "data: 1\n\n")]
#[tokio::test]
async fn an_upstream_dying_mid_stream_fails_the_client_body_instead_of_ending_it(
#[case] framing: &'static str,
#[case] sent: &'static str,
#[case] delivered: &'static str,
) {
let upstream = raw_upstream(move |mut python| async move {
python.request_head().await.unwrap();
python
.send(format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n{framing}\r\n\r\n{sent}"
))
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let response =
within(client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let (received, ended) = drain(response.into_body()).await;
assert_eq!(received, delivered.as_bytes());
assert!(ended.is_err());
}
#[rstest]
#[tokio::test]
async fn response_headers_reach_the_client_before_python_sends_any_body() {
let release = Arc::new(Notify::new());
let released = release.clone();
let upstream = raw_upstream(move |mut python| {
let released = released.clone();
async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream; charset=utf-8\r\nx-accel-buffering: no\r\nx-litellm-call-id: call-1\r\ntransfer-encoding: chunked\r\n\r\n")
.await;
released.notified().await;
python.send(chunk(b"data: 1\n\n")).await;
python.send("0\r\n\r\n").await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let response =
within(client().request(Request::post(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
assert_eq!(response.headers()["x-litellm-call-id"], "call-1");
assert_eq!(response.headers()["x-accel-buffering"], "no");
release.notify_one();
let body = within(response.into_body().collect())
.await
.unwrap()
.to_bytes();
assert_eq!(body, "data: 1\n\n");
}
/// A connection closed without any response looks retryable to client SDKs, which would re-run a
/// request Python already ran. Python dying right after its head races the relay, hence the loop.
#[rstest]
#[tokio::test]
async fn a_head_python_sent_right_before_dying_still_reaches_the_client() {
let upstream = raw_upstream(|mut python| async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n")
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
for _ in 0..20 {
let mut raw = gateway.connect().await;
raw.send("POST / HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n")
.await;
let head = within(raw.response_head()).await;
assert_eq!(head.map(|head| head.status), Some(StatusCode::OK));
}
}
#[rstest]
#[tokio::test]
async fn a_client_that_stops_reading_stalls_python_instead_of_being_buffered_for() {
let written = Arc::new(AtomicUsize::new(0));
let counted = written.clone();
let (failed, mut write_failed) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python| {
let counted = counted.clone();
let failed = failed.clone();
async move {
python.request_head().await.unwrap();
let mut python = python.into_stream();
python
.write_all(b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n")
.await
.unwrap();
let piece = chunk(&[0x5a; 64 * 1024]);
while python.write_all(&piece).await.is_ok() {
counted.fetch_add(piece.len(), Ordering::SeqCst);
}
failed.send(()).unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST / HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n")
.await;
within(raw.response_head()).await.unwrap();
tokio::time::sleep(Duration::from_secs(1)).await;
let stalled = written.load(Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(250)).await;
assert_eq!(written.load(Ordering::SeqCst), stalled);
assert!(stalled < 64 * 1024 * 1024, "{stalled} bytes in flight");
drop(raw);
within(write_failed.recv()).await.unwrap();
}
#[rstest]
#[tokio::test]
async fn an_http10_client_receives_a_streamed_body_delimited_by_close() {
let upstream = raw_upstream(|mut python| async move {
python.request_head().await.unwrap();
python
.send([
&b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n"[..],
&chunk(b"data: 1\n"),
&chunk(b"data: 2\n"),
b"0\r\n\r\n",
]
.concat())
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /v1/stream HTTP/1.0\r\nhost: x\r\n\r\n").await;
let response = String::from_utf8(within(raw.until_closed()).await).unwrap();
let (head, body) = response.split_once("\r\n\r\n").unwrap();
assert!(head.starts_with("HTTP/1.0 200 OK"), "{head}");
assert!(
!head.to_ascii_lowercase().contains("transfer-encoding"),
"{head}"
);
assert_eq!(body, "data: 1\ndata: 2\n");
}

View file

@ -0,0 +1,311 @@
#![allow(
dead_code,
reason = "each test binary uses a different subset of the harness"
)]
use std::{future::Future, net::SocketAddr, time::Duration};
use axum::{
Router,
body::{Body, Bytes},
extract::Request,
http::{HeaderMap, Method, StatusCode, Uri},
};
use http_body_util::BodyExt;
use hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::TokioExecutor,
};
use litellm_gateway_forward::Forward;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream},
sync::{mpsc, oneshot},
task::JoinHandle,
};
pub const WAIT: Duration = Duration::from_secs(5);
pub const UVICORN_KEEPALIVE: Duration = Duration::from_secs(5);
pub const DRAIN: Duration = Duration::from_secs(1);
pub async fn within<T>(future: impl Future<Output = T>) -> T {
tokio::time::timeout(WAIT, future).await.expect("timed out")
}
/// A running forwarder in front of `upstream`, listening on a real socket like production.
pub struct Gateway {
pub address: SocketAddr,
stop: oneshot::Sender<()>,
server: JoinHandle<()>,
}
impl Gateway {
pub async fn start(upstream: SocketAddr) -> Self {
Self::with_keepalive(upstream, UVICORN_KEEPALIVE).await
}
pub async fn with_keepalive(upstream: SocketAddr, keepalive: Duration) -> Self {
let forward = Forward::new(&format!("http://{upstream}").parse().unwrap(), keepalive);
let public = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = public.local_addr().unwrap();
let (stop, stopped) = oneshot::channel::<()>();
let server = tokio::spawn(forward.serve(
public,
async {
stopped.await.ok();
},
DRAIN,
));
Self {
address,
stop,
server,
}
}
pub fn url(&self, path_and_query: &str) -> Uri {
format!("http://{}{path_and_query}", self.address)
.parse()
.unwrap()
}
pub async fn connect(&self) -> Raw {
Raw::new(TcpStream::connect(self.address).await.unwrap())
}
/// Starts graceful shutdown and returns the server task, which ends once in-flight work drains
/// or `DRAIN` passes.
pub fn shutdown(self) -> JoinHandle<()> {
self.stop.send(()).unwrap();
self.server
}
}
pub fn client() -> Client<HttpConnector, Body> {
Client::builder(TokioExecutor::new()).build_http()
}
/// What the upstream received, after the forwarder rewrote it.
pub struct Received {
pub method: Method,
pub uri: Uri,
pub headers: HeaderMap,
pub body: Bytes,
}
/// An axum upstream that records every request it fully reads and answers with `respond`.
pub async fn recording(
respond: impl Fn() -> axum::response::Response + Clone + Send + Sync + 'static,
) -> (SocketAddr, mpsc::UnboundedReceiver<Received>) {
let (sender, receiver) = mpsc::unbounded_channel();
let address = serve(Router::new().fallback(move |request: Request| {
let sender = sender.clone();
let respond = respond.clone();
async move {
let (parts, body) = request.into_parts();
let body = body.collect().await.unwrap().to_bytes();
sender
.send(Received {
method: parts.method,
uri: parts.uri,
headers: parts.headers,
body,
})
.unwrap();
respond()
}
}))
.await;
(address, receiver)
}
pub async fn serve(router: Router) -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
address
}
/// An upstream that hands each accepted connection to `handle` as raw bytes, for behavior a
/// well-behaved HTTP server would never produce.
pub async fn raw_upstream<F, Fut>(handle: F) -> SocketAddr
where
F: Fn(Raw) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(handle(Raw::new(stream)));
}
});
address
}
pub fn unreachable_upstream() -> SocketAddr {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap()
}
pub struct Head {
pub status: StatusCode,
pub headers: Vec<(String, Vec<u8>)>,
pub path: String,
}
impl Head {
pub fn header(&self, name: &str) -> Option<&[u8]> {
self.headers
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_slice())
}
pub fn content_length(&self) -> Option<usize> {
self.header("content-length")
.map(|value| std::str::from_utf8(value).unwrap().parse().unwrap())
}
}
/// One TCP connection driven byte by byte, so tests control framing, timing and disconnects.
/// Bytes read past a message head stay buffered for the next read.
pub struct Raw {
stream: TcpStream,
buffer: Vec<u8>,
}
impl Raw {
pub fn new(stream: TcpStream) -> Self {
Self {
stream,
buffer: Vec::new(),
}
}
pub fn into_stream(self) -> TcpStream {
assert!(self.buffer.is_empty(), "buffered bytes would be lost");
self.stream
}
pub fn local_address(&self) -> SocketAddr {
self.stream.local_addr().unwrap()
}
pub async fn send(&mut self, bytes: impl AsRef<[u8]>) {
self.stream.write_all(bytes.as_ref()).await.unwrap();
}
/// Reads one request head, or `None` when the peer closed the connection first.
pub async fn request_head(&mut self) -> Option<Head> {
self.head(|bytes| {
let mut headers = [httparse::EMPTY_HEADER; 256];
let mut request = httparse::Request::new(&mut headers);
let httparse::Status::Complete(length) = request.parse(bytes).unwrap() else {
return None;
};
Some((
length,
Head {
status: StatusCode::OK,
headers: owned(request.headers),
path: request.path.unwrap().to_owned(),
},
))
})
.await
}
pub async fn response_head(&mut self) -> Option<Head> {
self.head(|bytes| {
let mut headers = [httparse::EMPTY_HEADER; 256];
let mut response = httparse::Response::new(&mut headers);
let httparse::Status::Complete(length) = response.parse(bytes).unwrap() else {
return None;
};
Some((
length,
Head {
status: StatusCode::from_u16(response.code.unwrap()).unwrap(),
headers: owned(response.headers),
path: String::new(),
},
))
})
.await
}
async fn head(&mut self, parse: impl Fn(&[u8]) -> Option<(usize, Head)>) -> Option<Head> {
loop {
if let Some((length, head)) = parse(&self.buffer) {
self.buffer.drain(..length);
return Some(head);
}
if self.fill().await == 0 {
return None;
}
}
}
/// Reads exactly `length` body bytes, using what is already buffered first.
pub async fn body(&mut self, length: usize) -> Vec<u8> {
while self.buffer.len() < length {
assert_ne!(self.fill().await, 0, "closed mid-body");
}
self.buffer.drain(..length).collect()
}
/// Reads a whole chunked body and returns its decoded bytes.
pub async fn chunked_body(&mut self) -> Vec<u8> {
let mut decoded = Vec::new();
loop {
let size_line = self.line().await;
let size =
usize::from_str_radix(size_line.split(';').next().unwrap().trim(), 16).unwrap();
if size == 0 {
while !self.line().await.is_empty() {}
return decoded;
}
decoded.extend(self.body(size).await);
assert_eq!(self.body(2).await, b"\r\n");
}
}
async fn line(&mut self) -> String {
loop {
if let Some(end) = self.buffer.windows(2).position(|window| window == b"\r\n") {
let line = String::from_utf8(self.buffer[..end].to_vec()).unwrap();
self.buffer.drain(..end + 2);
return line;
}
assert_ne!(self.fill().await, 0, "closed mid-line");
}
}
async fn fill(&mut self) -> usize {
let mut chunk = [0; 8192];
let read = self.stream.read(&mut chunk).await.unwrap_or(0);
self.buffer.extend_from_slice(&chunk[..read]);
read
}
/// Everything the peer sends until it closes, including bytes already buffered.
pub async fn until_closed(&mut self) -> Vec<u8> {
while self.fill().await != 0 {}
std::mem::take(&mut self.buffer)
}
/// Resolves once the peer closes the connection, discarding anything it still sends.
pub async fn closed(&mut self) {
let mut chunk = [0; 8192];
while self.stream.read(&mut chunk).await.unwrap_or(0) != 0 {}
}
}
fn owned(headers: &[httparse::Header<'_>]) -> Vec<(String, Vec<u8>)> {
headers
.iter()
.map(|header| (header.name.to_owned(), header.value.to_vec()))
.collect()
}

View file

@ -0,0 +1,339 @@
mod support;
use std::{
convert::Infallible,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use axum::{
Router,
body::{Body, Bytes},
extract::Request,
http::StatusCode,
response::Response,
};
use http_body_util::BodyExt;
use rstest::rstest;
use support::{Gateway, Raw, client, raw_upstream, recording, serve, within};
use tokio::{
io::AsyncWriteExt,
sync::{Notify, mpsc},
};
fn ok() -> Response {
Response::new(Body::from("ok"))
}
#[rstest]
#[tokio::test]
async fn streams_upload_and_response_incrementally_without_a_body_limit() {
let upstream = serve(
Router::new().fallback(|request: Request| async { Response::new(request.into_body()) }),
)
.await;
let gateway = Gateway::start(upstream).await;
let (sender, receiver) = mpsc::channel::<Result<Bytes, Infallible>>(1);
let stream = futures_util::stream::unfold(receiver, |mut receiver| async {
receiver.recv().await.map(|chunk| (chunk, receiver))
});
sender.send(Ok(Bytes::from_static(b"first"))).await.unwrap();
let mut response = within(
client().request(
Request::post(gateway.url("/v1/files"))
.body(Body::from_stream(stream))
.unwrap(),
),
)
.await
.unwrap();
let frame = within(response.body_mut().frame()).await.unwrap().unwrap();
assert_eq!(frame.into_data().unwrap(), "first");
let large = Bytes::from(vec![b'x'; 8 * 1024 * 1024]);
sender.send(Ok(large.clone())).await.unwrap();
drop(sender);
let rest = within(response.into_body().collect())
.await
.unwrap()
.to_bytes();
assert_eq!(rest, large);
}
/// hyper sends the 100 as soon as the request is forwarded, where uvicorn waits for the app to
/// read the body, so an upload Python rejects on headers alone is still sent in full.
#[rstest]
#[tokio::test]
async fn answers_expect_continue_so_large_uploads_start() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST /v1/audio/transcriptions HTTP/1.1\r\nhost: x\r\nexpect: 100-continue\r\ncontent-length: 4\r\n\r\n")
.await;
let interim = within(raw.response_head()).await.unwrap();
assert_eq!(interim.status, StatusCode::CONTINUE);
raw.send("data").await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().body, "data");
}
/// curl sends `expect: 100-continue` for any body over 1 MiB and waits for the 100 before sending
/// the multipart body, which must reach Python intact even where it looks like framing.
#[rstest]
#[tokio::test]
async fn expect_continue_delivers_a_large_multipart_upload_byte_for_byte() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let boundary = "------------------------d74496d66958873e";
let audio: Vec<u8> = (0..3 * 1024 * 1024)
.map(|index: u32| (index.wrapping_mul(2_654_435_761) >> 24) as u8)
.chain(*b"\r\n0\r\n\r\nPOST /smuggled HTTP/1.1\r\n\r\n--")
.collect();
let body = [
format!("--{boundary}\r\ncontent-disposition: form-data; name=\"model\"\r\n\r\nwhisper-1\r\n--{boundary}\r\ncontent-disposition: form-data; name=\"file\"; filename=\"a b.wav\"\r\ncontent-type: audio/wav\r\n\r\n").into_bytes(),
audio,
format!("\r\n--{boundary}--\r\n").into_bytes(),
]
.concat();
let content_type = format!("multipart/form-data; boundary={boundary}");
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/audio/transcriptions HTTP/1.1\r\nhost: x\r\ncontent-type: {content_type}\r\nexpect: 100-continue\r\ncontent-length: {}\r\n\r\n",
body.len()
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::CONTINUE
);
raw.send(&body).await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
assert_eq!(request.headers["content-type"], content_type.as_str());
assert_eq!(request.body, body);
}
#[rstest]
#[case::get("GET")]
#[case::delete("DELETE")]
#[case::options("OPTIONS")]
#[case::post("POST")]
#[tokio::test]
async fn forwards_a_chunked_body_on_any_method(#[case] method: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"{method} /v1/search HTTP/1.1\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n4\r\nbody\r\n0\r\n\r\n"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().body, "body");
}
#[rstest]
#[case::no_framing("", "", &[], "")]
#[case::empty_content_length("content-length: 0\r\n", "", &[("content-length", "0")], "")]
#[case::empty_chunked(
"transfer-encoding: chunked\r\n",
"0\r\n\r\n",
&[("transfer-encoding", "chunked")],
""
)]
#[case::sized(
"content-length: 7\r\n",
"payload",
&[("content-length", "7")],
"payload"
)]
#[case::chunk_extensions_and_trailers(
"transfer-encoding: chunked\r\n",
"4;name=\"v\"\r\nbody\r\n0\r\nx-checksum: 1\r\n\r\n",
&[("transfer-encoding", "chunked")],
"body"
)]
#[tokio::test]
async fn a_body_reaches_python_with_the_framing_the_client_chose(
#[values("POST", "GET")] method: &str,
#[case] framing: &str,
#[case] wire_body: &str,
#[case] python_framing: &[(&str, &str)],
#[case] python_body: &str,
) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"{method} /v1/files HTTP/1.1\r\nhost: x\r\n{framing}\r\n{wire_body}"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
let forwarded: Vec<(&str, &str)> = ["content-length", "transfer-encoding"]
.into_iter()
.flat_map(|name| {
request
.headers
.get_all(name)
.iter()
.map(move |value| (name, value.to_str().unwrap()))
})
.collect();
assert_eq!(request.method, method);
assert_eq!(forwarded, python_framing);
assert_eq!(request.body, python_body);
}
#[rstest]
#[tokio::test]
async fn a_large_upload_is_paced_by_python_reading_it() {
const LENGTH: usize = 128 * 1024 * 1024;
let start_reading = Arc::new(Notify::new());
let reading = start_reading.clone();
let upstream = raw_upstream(move |mut python| {
let reading = reading.clone();
async move {
let head = python.request_head().await.unwrap();
reading.notified().await;
let mut remaining = head.content_length().unwrap();
while remaining > 0 {
remaining -= python.body(remaining.min(1 << 20)).await.len();
}
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n")
.await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let (read, mut write) = gateway.connect().await.into_stream().into_split();
let sent = Arc::new(AtomicUsize::new(0));
let sending = sent.clone();
let upload = tokio::spawn(async move {
write
.write_all(
format!("POST /v1/files HTTP/1.1\r\nhost: x\r\ncontent-length: {LENGTH}\r\n\r\n")
.as_bytes(),
)
.await
.unwrap();
let chunk = [0x5a; 64 * 1024];
while sending.load(Ordering::SeqCst) < LENGTH {
write.write_all(&chunk).await.unwrap();
sending.fetch_add(chunk.len(), Ordering::SeqCst);
}
write
});
tokio::time::sleep(Duration::from_secs(1)).await;
assert!(
sent.load(Ordering::SeqCst) < LENGTH / 4,
"the forwarder buffered an upload Python was not reading"
);
start_reading.notify_one();
let write = tokio::time::timeout(Duration::from_secs(60), upload)
.await
.unwrap()
.unwrap();
let mut raw = Raw::new(read.reunite(write).unwrap());
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
}
#[rstest]
#[case::between_chunks("5\r\nhello\r\n")]
#[case::mid_chunk("100\r\nhello")]
#[tokio::test]
async fn a_client_abandoning_a_chunked_upload_never_ends_python_body_cleanly(
#[case] sent: &'static str,
) {
let (forwarded, mut received) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python| {
let forwarded = forwarded.clone();
async move {
python.request_head().await.unwrap();
forwarded.send(python.until_closed().await).unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n{sent}"
))
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
drop(raw);
let body = within(received.recv()).await.unwrap();
assert!(body.starts_with(b"5\r\nhello\r\n"));
assert!(
!body.ends_with(b"0\r\n\r\n"),
"python saw a truncated upload end cleanly"
);
}
#[rstest]
#[tokio::test]
async fn an_early_answer_during_an_upload_keeps_both_connections_in_sync() {
let (event, mut events) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python| {
let event = event.clone();
async move {
while let Some(head) = python.request_head().await {
let length = head.content_length();
event.send(head.path.into_bytes()).unwrap();
let Some(length) = length else {
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 4\r\n\r\nnext")
.await;
continue;
};
python
.send("HTTP/1.1 413 Payload Too Large\r\ncontent-length: 2\r\n\r\n{}")
.await;
event.send(python.body(length).await).unwrap();
}
}
})
.await;
let gateway = Gateway::start(upstream).await;
let upload = b"GET /smuggled HTTP/1.1\r\nhost: x\r\n\r\n".repeat(1024);
let (first_half, second_half) = upload.split_at(upload.len() / 2);
let mut raw = gateway.connect().await;
raw.send(format!(
"POST /v1/files HTTP/1.1\r\nhost: x\r\ncontent-length: {}\r\n\r\n",
upload.len()
))
.await;
raw.send(first_half).await;
let rejected = within(raw.response_head()).await.unwrap();
assert_eq!(rejected.status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(raw.body(2).await, b"{}");
raw.send(second_half).await;
raw.send("GET /next HTTP/1.1\r\nhost: x\r\n\r\n").await;
let next = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(next.content_length().unwrap()).await, b"next");
assert_eq!(within(events.recv()).await.unwrap(), b"/v1/files");
assert_eq!(within(events.recv()).await.unwrap(), upload);
assert_eq!(within(events.recv()).await.unwrap(), b"/next");
}

View file

@ -0,0 +1,21 @@
use litellm_gateway_forward::Upstream;
use rstest::rstest;
#[rstest]
#[case::https("https://127.0.0.1:4000")]
#[case::public("http://192.0.2.1:4000")]
#[case::hostname("http://localhost:4000")]
#[case::ipv6("http://[::1]:4000")]
#[case::path("http://127.0.0.1:4000/api")]
#[case::query("http://127.0.0.1:4000/?x=y")]
#[case::credentials("http://user@127.0.0.1:4000")]
fn rejects_anything_but_a_loopback_http_origin(#[case] upstream: &str) {
assert!(upstream.parse::<Upstream>().is_err());
}
#[rstest]
#[case::standard("http://127.0.0.1:4000")]
#[case::loopback_range("http://127.0.0.2:4000/")]
fn accepts_a_loopback_http_origin(#[case] upstream: &str) {
assert!(upstream.parse::<Upstream>().is_ok());
}

View file

@ -0,0 +1,719 @@
mod support;
use std::{
net::SocketAddr,
sync::Arc,
time::{Duration, Instant},
};
use axum::{
Router,
http::{HeaderValue, StatusCode},
response::IntoResponse,
};
use futures_util::{SinkExt, StreamExt, future::join_all};
use litellm_gateway_forward::PEER_HEADER;
use rstest::rstest;
use support::{DRAIN, Gateway, Head, Raw, raw_upstream, serve, within};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
sync::{Barrier, mpsc},
};
use tokio_tungstenite::{
WebSocketStream, accept_hdr_async, client_async,
tungstenite::{
Error, Message,
client::IntoClientRequest,
handshake::{
derive_accept_key,
server::{ErrorResponse, Request as Handshake, Response as Accepted},
},
protocol::{CloseFrame, frame::coding::CloseCode},
},
};
const KEY: &str = "dGhlIHNhbXBsZSBub25jZQ==";
async fn connect(
address: SocketAddr,
connection: &'static str,
) -> Result<WebSocketStream<TcpStream>, Box<Error>> {
let mut request = format!("ws://{address}/v1/realtime?model=m")
.into_client_request()
.unwrap();
let headers = request.headers_mut();
headers.insert("authorization", HeaderValue::from_static("Bearer test"));
headers.insert(
"sec-websocket-protocol",
HeaderValue::from_static("realtime"),
);
headers.insert("connection", HeaderValue::from_static(connection));
let stream = TcpStream::connect(address).await.unwrap();
let (socket, response) = client_async(request, stream).await.map_err(Box::new)?;
assert_eq!(response.headers()["sec-websocket-protocol"], "realtime");
Ok(socket)
}
/// Greets, echoes every message, and closes with 4000 when told to "bye".
#[expect(
clippy::result_large_err,
reason = "tungstenite's handshake callback returns ErrorResponse"
)]
async fn echo() -> SocketAddr {
raw_upstream(|python| async move {
let callback = |request: &Handshake, mut response: Accepted| {
assert_eq!(request.uri(), "/v1/realtime?model=m");
assert_eq!(request.headers()["authorization"], "Bearer test");
assert!(request.headers().contains_key(PEER_HEADER));
response.headers_mut().insert(
"sec-websocket-protocol",
HeaderValue::from_static("realtime"),
);
Ok::<_, ErrorResponse>(response)
};
let mut socket = accept_hdr_async(python.into_stream(), callback)
.await
.unwrap();
socket.send(Message::text("greeting")).await.unwrap();
while let Some(Ok(message)) = socket.next().await {
if message == Message::text("bye") {
socket
.close(Some(CloseFrame {
code: CloseCode::Library(4000),
reason: "done".into(),
}))
.await
.unwrap();
continue;
}
if message.is_close() {
break;
}
socket.send(message).await.unwrap();
}
})
.await
}
fn handshake(target: &str, headers: &str) -> String {
format!(
"GET {target} HTTP/1.1\r\nhost: public.example\r\nconnection: Upgrade\r\nupgrade: websocket\r\nsec-websocket-version: 13\r\nsec-websocket-key: {KEY}\r\n{headers}\r\n"
)
}
/// The 101 uvicorn writes for `handshake`, with `headers` added.
fn switching(handshake: &Head, headers: &str) -> String {
let accept = derive_accept_key(handshake.header("sec-websocket-key").unwrap());
format!(
"HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-accept: {accept}\r\n{headers}\r\n"
)
}
fn values(head: &Head, name: &str) -> Vec<String> {
head.headers
.iter()
.filter(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(_, value)| String::from_utf8(value.clone()).unwrap())
.collect()
}
/// Accepts with `headers` in the 101, hands the handshake head to the test, then echoes bytes.
async fn byte_echo(headers: &'static str) -> (SocketAddr, mpsc::UnboundedReceiver<Head>) {
let (sender, handshakes) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let sender = sender.clone();
async move {
let handshake = python.request_head().await.unwrap();
python.send(switching(&handshake, headers)).await;
sender.send(handshake).unwrap();
echo_bytes(python).await;
}
})
.await;
(upstream, handshakes)
}
async fn echo_bytes(python: Raw) {
let mut stream = python.into_stream();
let (mut read, mut write) = stream.split();
tokio::io::copy(&mut read, &mut write).await.ok();
}
async fn assert_echoes(socket: &mut TcpStream, message: &[u8]) {
socket.write_all(message).await.unwrap();
let mut echoed = vec![0; message.len()];
within(socket.read_exact(&mut echoed)).await.unwrap();
assert_eq!(echoed, message);
}
async fn open(gateway: &Gateway, handshake: String) -> (TcpStream, Head) {
let mut raw = gateway.connect().await;
raw.send(handshake).await;
let switched = within(raw.response_head()).await.unwrap();
assert_eq!(switched.status, StatusCode::SWITCHING_PROTOCOLS);
(raw.into_stream(), switched)
}
#[rstest]
#[tokio::test]
async fn relays_messages_both_ways(
#[values(
"Upgrade",
"keep-alive, Upgrade",
"upgrade",
"Upgrade, Sec-WebSocket-Key, Sec-WebSocket-Version"
)]
connection: &'static str,
#[values(
Message::text("hello"),
Message::binary(vec![0, 1, 2]),
Message::binary(vec![7; 4 * 1024 * 1024])
)]
message: Message,
) {
let gateway = Gateway::start(echo().await).await;
let mut socket = within(connect(gateway.address, connection)).await.unwrap();
assert_eq!(
socket.next().await.unwrap().unwrap(),
Message::text("greeting")
);
socket.send(message.clone()).await.unwrap();
assert_eq!(within(socket.next()).await.unwrap().unwrap(), message);
socket.close(None).await.unwrap();
while socket.next().await.is_some() {}
drop(socket);
within(gateway.shutdown()).await.unwrap();
}
#[rstest]
#[tokio::test]
async fn relays_a_close_python_initiates() {
let gateway = Gateway::start(echo().await).await;
let mut socket = within(connect(gateway.address, "Upgrade")).await.unwrap();
socket.next().await.unwrap().unwrap();
socket.send(Message::text("bye")).await.unwrap();
let Message::Close(Some(frame)) = within(socket.next()).await.unwrap().unwrap() else {
panic!("expected python's close frame");
};
assert_eq!(frame.code, CloseCode::Library(4000));
assert_eq!(frame.reason, "done");
}
#[rstest]
#[tokio::test]
async fn passes_an_upstream_rejection_through() {
let upstream = serve(
Router::new()
.fallback(|| async { (StatusCode::FORBIDDEN, "origin not allowed").into_response() }),
)
.await;
let gateway = Gateway::start(upstream).await;
let error = within(connect(gateway.address, "Upgrade"))
.await
.unwrap_err();
let Error::Http(response) = *error else {
panic!("expected the upstream rejection, got {error}");
};
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(response.body().as_deref(), Some(&b"origin not allowed"[..]));
}
/// The idle timeout only covers a connection waiting for its next HTTP request, and a realtime
/// session may sit silent between turns.
#[rstest]
#[tokio::test]
async fn keeps_a_quiet_socket_open_past_the_keepalive() {
let gateway = Gateway::with_keepalive(echo().await, Duration::from_millis(400)).await;
let mut socket = within(connect(gateway.address, "Upgrade")).await.unwrap();
socket.next().await.unwrap().unwrap();
tokio::time::sleep(Duration::from_millis(1200)).await;
socket.send(Message::text("still here")).await.unwrap();
assert_eq!(
within(socket.next()).await.unwrap().unwrap(),
Message::text("still here")
);
}
/// Browsers carry the API key in a subprotocol, Python accepts with the first one it was offered,
/// and uvicorn negotiates permessage-deflate, so every handshake header must cross unchanged.
#[rstest]
#[tokio::test]
async fn handshake_headers_cross_unchanged_both_ways() {
let (upstream, mut handshakes) = byte_echo(
"sec-websocket-protocol: realtime\r\nsec-websocket-extensions: permessage-deflate; server_max_window_bits=12; client_max_window_bits=12\r\nset-cookie: a=1\r\nset-cookie: b=2\r\nx-litellm-call-id: abc\r\n",
)
.await;
let gateway = Gateway::start(upstream).await;
let target = "/v1/realtime?model=gpt-realtime&api-key=sk%2Fa%2Bb%3D&dup=1&dup=2";
let (_socket, switched) = open(
&gateway,
handshake(
target,
"sec-websocket-protocol: realtime, openai-insecure-api-key.sk-websocket-test, openai-beta.realtime-v1\r\nsec-websocket-protocol: second-line\r\nsec-websocket-extensions: permessage-deflate; client_max_window_bits\r\ncookie: token=abc\r\n",
),
)
.await;
let handshake = within(handshakes.recv()).await.unwrap();
assert_eq!(handshake.path, target);
assert_eq!(
values(&handshake, "sec-websocket-protocol"),
[
"realtime, openai-insecure-api-key.sk-websocket-test, openai-beta.realtime-v1",
"second-line"
]
);
assert_eq!(
values(&handshake, "sec-websocket-extensions"),
["permessage-deflate; client_max_window_bits"]
);
assert_eq!(values(&handshake, "cookie"), ["token=abc"]);
assert_eq!(values(&switched, "sec-websocket-protocol"), ["realtime"]);
assert_eq!(
values(&switched, "sec-websocket-extensions"),
["permessage-deflate; server_max_window_bits=12; client_max_window_bits=12"]
);
assert_eq!(values(&switched, "set-cookie"), ["a=1", "b=2"]);
assert_eq!(values(&switched, "x-litellm-call-id"), ["abc"]);
}
#[rstest]
#[tokio::test]
async fn invents_no_subprotocol_or_extension() {
let (upstream, mut handshakes) = byte_echo("").await;
let gateway = Gateway::start(upstream).await;
let (_socket, switched) = open(&gateway, handshake("/v1/realtime", "")).await;
let handshake = within(handshakes.recv()).await.unwrap();
for name in ["sec-websocket-protocol", "sec-websocket-extensions"] {
assert!(handshake.header(name).is_none());
assert!(switched.header(name).is_none());
}
}
#[rstest]
#[case::capitalized_upgrade("Upgrade: WebSocket\r\nConnection: keep-alive, Upgrade\r\n")]
#[case::uppercase("UPGRADE: WEBSOCKET\r\nCONNECTION: UPGRADE\r\n")]
#[case::split_connection("Upgrade: websocket\r\nConnection: keep-alive\r\nConnection: Upgrade\r\n")]
#[tokio::test]
async fn accepts_any_spelling_of_the_upgrade_headers(#[case] upgrade: &str) {
let (upstream, _handshakes) = byte_echo("").await;
let gateway = Gateway::start(upstream).await;
let (mut socket, _) = open(
&gateway,
format!(
"GET /v1/realtime HTTP/1.1\r\nhost: x\r\n{upgrade}sec-websocket-version: 13\r\nsec-websocket-key: {KEY}\r\n\r\n"
),
)
.await;
socket.write_all(b"ping").await.unwrap();
let mut echoed = [0; 4];
within(socket.read_exact(&mut echoed)).await.unwrap();
assert_eq!(&echoed, b"ping");
}
/// Compressed frames set RSV1 and every client frame is masked, so the socket is relayed as bytes,
/// never re-framed.
#[rstest]
#[tokio::test]
async fn relays_socket_bytes_exactly() {
let (upstream, _handshakes) = byte_echo("").await;
let gateway = Gateway::start(upstream).await;
let (socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
let sent: Vec<u8> = (0..3_000_017u32)
.map(|index| index.wrapping_mul(2_654_435_761).to_be_bytes()[1])
.collect();
let (mut read, mut write) = socket.into_split();
let writing = sent.clone();
let writer = tokio::spawn(async move {
for chunk in writing.chunks(7919) {
write.write_all(chunk).await.unwrap();
}
write
});
let mut echoed = vec![0; sent.len()];
within(read.read_exact(&mut echoed)).await.unwrap();
assert!(echoed == sent);
drop(writer.await.unwrap());
}
/// uvicorn writes the 101, an error event and a close frame back to back and then closes, so they
/// share a segment with the FIN, and a client may send its first frame with the handshake.
#[rstest]
#[tokio::test]
async fn keeps_bytes_that_arrive_with_the_handshake() {
let (early, mut received) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let early = early.clone();
async move {
let handshake = python.request_head().await.unwrap();
let mut segment = switching(&handshake, "").into_bytes();
segment.extend(b"\x81\x05error\x88\x08\x03\xf0denied");
python.send(segment).await;
early.send(within(python.body(6)).await).unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(handshake("/v1/realtime", "") + "early!").await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::SWITCHING_PROTOCOLS
);
assert_eq!(within(received.recv()).await.unwrap(), b"early!");
assert_eq!(
within(raw.until_closed()).await,
b"\x81\x05error\x88\x08\x03\xf0denied"
);
}
/// Python frees a realtime session's budget and parallel slot when its socket closes, so a client
/// that disappears without a close frame must still close Python's socket.
#[rstest]
#[case::fin(false)]
#[case::reset(true)]
#[tokio::test]
async fn a_vanished_client_closes_the_python_socket(#[case] reset: bool) {
let (event, mut events) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let event = event.clone();
async move {
let handshake = python.request_head().await.unwrap();
python.send(switching(&handshake, "")).await;
event.send("open").unwrap();
python.closed().await;
event.send("closed").unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let (socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
assert_eq!(within(events.recv()).await, Some("open"));
if reset {
#[expect(deprecated, reason = "a zero linger is how a test sends a TCP reset")]
socket.set_linger(Some(Duration::ZERO)).unwrap();
}
drop(socket);
assert_eq!(within(events.recv()).await, Some("closed"));
}
#[rstest]
#[case::fin(false)]
#[case::reset(true)]
#[tokio::test]
async fn a_vanished_python_ends_the_client_socket(#[case] reset: bool) {
let upstream = raw_upstream(move |mut python: Raw| async move {
let handshake = python.request_head().await.unwrap();
python.send(switching(&handshake, "")).await;
let socket = python.into_stream();
if reset {
#[expect(deprecated, reason = "a zero linger is how a test sends a TCP reset")]
socket.set_linger(Some(Duration::ZERO)).unwrap();
}
drop(socket);
})
.await;
let gateway = Gateway::start(upstream).await;
let (mut socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
let mut rest = Vec::new();
assert!(matches!(
within(socket.read_to_end(&mut rest)).await,
Ok(0) | Err(_)
));
}
#[rstest]
#[tokio::test]
async fn shutdown_closes_open_sockets_after_drain() {
let gateway = Gateway::start(echo().await).await;
let mut socket = within(connect(gateway.address, "Upgrade")).await.unwrap();
socket.next().await.unwrap().unwrap();
let started = Instant::now();
within(gateway.shutdown()).await.unwrap();
assert!(started.elapsed() >= DRAIN);
assert!(!matches!(socket.next().await, Some(Ok(Message::Text(_)))));
}
#[rstest]
#[tokio::test]
async fn shutdown_relays_the_close_python_sends_while_draining() {
let gateway = Gateway::start(echo().await).await;
let mut socket = within(connect(gateway.address, "Upgrade")).await.unwrap();
socket.next().await.unwrap().unwrap();
let server = gateway.shutdown();
tokio::time::sleep(Duration::from_millis(100)).await;
socket.send(Message::text("bye")).await.unwrap();
let Message::Close(Some(frame)) = within(socket.next()).await.unwrap().unwrap() else {
panic!("expected python's close frame");
};
assert_eq!(frame.code, CloseCode::Library(4000));
while socket.next().await.is_some() {}
drop(socket);
let started = Instant::now();
within(server).await.unwrap();
assert!(started.elapsed() < DRAIN / 2);
}
#[rstest]
#[tokio::test]
async fn refuses_new_sockets_while_draining() {
let gateway = Gateway::start(echo().await).await;
let mut open = within(connect(gateway.address, "Upgrade")).await.unwrap();
open.next().await.unwrap().unwrap();
let address = gateway.address;
let server = gateway.shutdown();
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(
TcpStream::connect(address).await.is_err() || connect(address, "Upgrade").await.is_err()
);
open.send(Message::text("still open")).await.unwrap();
assert_eq!(
within(open.next()).await.unwrap().unwrap(),
Message::text("still open")
);
drop(open);
within(server).await.unwrap();
}
/// uvicorn never half-closes: once Python closes the socket nothing more can cross it, so the
/// relay must end instead of waiting for the client to close its side too.
#[rstest]
#[tokio::test]
async fn relay_ends_when_python_closes_while_the_client_holds_its_socket() {
let upstream = raw_upstream(move |mut python: Raw| async move {
let handshake = python.request_head().await.unwrap();
python.send(switching(&handshake, "")).await;
})
.await;
let gateway = Gateway::start(upstream).await;
let (mut socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
assert_eq!(within(socket.read(&mut [0; 1])).await.unwrap(), 0);
let started = Instant::now();
within(gateway.shutdown()).await.unwrap();
assert!(started.elapsed() < DRAIN / 2);
drop(socket);
}
/// uvicorn answers a handshake Python closes before accepting with a 403, and one Python denies
/// through `websocket.http.response` with any status, headers and body, then drops the socket. The
/// client gets that response whole and keeps a connection that still reaches Python.
#[rstest]
#[case::closed_before_accept("403 Forbidden", None, "")]
#[case::denial_response(
"401 Unauthorized",
Some("Bearer realm=\"litellm\""),
"{\"error\":\"invalid api key\"}"
)]
#[tokio::test]
async fn a_denied_handshake_reaches_the_client_whole(
#[case] status: &'static str,
#[case] authenticate: Option<&'static str>,
#[case] body: &'static str,
) {
let upstream = raw_upstream(move |mut python: Raw| async move {
python.request_head().await.unwrap();
let authenticate = authenticate
.map(|value| format!("www-authenticate: {value}\r\n"))
.unwrap_or_default();
python
.send(format!(
"HTTP/1.1 {status}\r\ndate: Tue, 03 Nov 2026 08:00:00 GMT\r\nconnection: close\r\ncontent-length: {}\r\ncontent-type: text/plain; charset=utf-8\r\n{authenticate}\r\n{body}",
body.len()
))
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
for _ in 0..2 {
raw.send(handshake("/v1/realtime", "")).await;
let denied = within(raw.response_head()).await.unwrap();
assert_eq!(denied.status.as_str(), &status[..3]);
assert_eq!(
values(&denied, "www-authenticate"),
Vec::from_iter(authenticate.map(String::from))
);
assert!(denied.header("sec-websocket-accept").is_none());
let length = denied.content_length().unwrap();
assert_eq!(within(raw.body(length)).await, body.as_bytes());
}
}
/// Only Python's EOF ends a relay, so a client that half-closes after its close frame still gets
/// everything Python sends before closing its own side.
#[rstest]
#[tokio::test]
async fn a_client_half_close_still_receives_what_python_sends_after_it() {
let upstream = raw_upstream(|mut python: Raw| async move {
let handshake = python.request_head().await.unwrap();
python.send(switching(&handshake, "")).await;
let received = python.until_closed().await;
python.send(received).await;
})
.await;
let gateway = Gateway::start(upstream).await;
let (mut socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
let close = b"\x88\x82\x01\x02\x03\x04\x02\xea";
socket.write_all(close).await.unwrap();
socket.shutdown().await.unwrap();
let mut replied = Vec::new();
within(socket.read_to_end(&mut replied)).await.unwrap();
assert_eq!(replied, close);
}
/// Python authenticates every handshake before accepting it, so sessions opened together must all
/// reach Python before any of them is accepted, and each must stay on its own socket.
#[rstest]
#[tokio::test]
async fn opens_many_sockets_at_once_without_crossing_them() {
const SOCKETS: usize = 64;
let everyone = Arc::new(Barrier::new(SOCKETS));
let upstream = raw_upstream(move |mut python: Raw| {
let everyone = everyone.clone();
async move {
let handshake = python.request_head().await.unwrap();
everyone.wait().await;
python.send(switching(&handshake, "")).await;
echo_bytes(python).await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let gateway = &gateway;
within(join_all((0..SOCKETS).map(|index| async move {
let (mut socket, _) = open(gateway, handshake("/v1/realtime", "")).await;
assert_echoes(&mut socket, format!("socket {index}").as_bytes()).await;
})))
.await;
}
/// Python resolves the key, budget and model before it accepts, and nothing bounds how long that
/// takes, so the idle timeout must not cut a handshake waiting on its 101.
#[rstest]
#[tokio::test]
async fn waits_for_a_101_slower_than_the_keepalive() {
let upstream = raw_upstream(|mut python: Raw| async move {
let handshake = python.request_head().await.unwrap();
tokio::time::sleep(Duration::from_millis(1200)).await;
python.send(switching(&handshake, "")).await;
echo_bytes(python).await;
})
.await;
let gateway = Gateway::with_keepalive(upstream, Duration::from_millis(400)).await;
let (mut socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
assert_echoes(&mut socket, b"late").await;
}
/// A 101 the client did not ask for, or to a protocol other than the one it asked for, would hand
/// the client a socket it cannot speak, so it is a 502 and Python's socket is closed.
#[rstest]
#[case::plain_request("GET /v1/models HTTP/1.1\r\nhost: x\r\n\r\n".to_owned(), "websocket")]
#[case::other_protocol(handshake("/v1/realtime", ""), "h2c")]
#[tokio::test]
async fn an_unrequested_switch_is_a_502_that_closes_python(
#[case] request: String,
#[case] protocol: &'static str,
) {
let (closed, mut closes) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let closed = closed.clone();
async move {
python.request_head().await.unwrap();
python
.send(format!(
"HTTP/1.1 101 Switching Protocols\r\nconnection: upgrade\r\nupgrade: {protocol}\r\n\r\n"
))
.await;
python.closed().await;
closed.send(()).unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(request).await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::BAD_GATEWAY
);
within(closes.recv()).await.unwrap();
}
/// A realtime session streams audio for as long as the client reads it, so a client that stops
/// reading must stall Python's writes instead of piling them up in the gateway.
#[rstest]
#[tokio::test]
async fn a_client_that_stops_reading_stalls_python() {
let (sent, mut totals) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let sent = sent.clone();
async move {
let handshake = python.request_head().await.unwrap();
python.send(switching(&handshake, "")).await;
python.body(2).await;
let mut stream = python.into_stream();
let chunk = vec![0x82; 64 * 1024];
let mut total = 0;
while let Ok(Ok(())) =
tokio::time::timeout(Duration::from_millis(300), stream.write_all(&chunk)).await
{
total += chunk.len();
}
sent.send(total).unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let (mut socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
socket.write_all(b"go").await.unwrap();
let total = within(totals.recv()).await.unwrap();
assert!(
total < 64 << 20,
"python wrote {total} bytes into a stalled socket"
);
}
/// Python closes a session that is still streaming audio by sending an error event and a close
/// frame and dropping its socket with the client's next frames unread, which resets it. Those last
/// bytes reached the client when it talked to uvicorn directly, so they must reach it through the
/// relay too, even though writing the client's frames to Python now fails.
#[rstest]
#[tokio::test]
async fn python_closing_mid_stream_still_delivers_its_last_frames() {
const LAST: &[u8] = b"\x81\x05error\x88\x02\x03\xf0";
let upstream = raw_upstream(|mut python: Raw| async move {
let handshake = python.request_head().await.unwrap();
python.send(switching(&handshake, "")).await;
python.body(1).await;
tokio::time::sleep(Duration::from_millis(20)).await;
python.send(LAST).await;
})
.await;
let gateway = Gateway::start(upstream).await;
for _ in 0..20 {
let (mut socket, _) = open(&gateway, handshake("/v1/realtime", "")).await;
let (mut read, mut write) = socket.split();
let streaming = async {
while write.write_all(b"\x82\x80\0\0\0\0").await.is_ok() {
tokio::time::sleep(Duration::from_micros(200)).await;
}
std::future::pending().await
};
let mut received = Vec::new();
let receiving = async {
let mut chunk = [0; 4096];
while let Ok(read @ 1..) = read.read(&mut chunk).await {
received.extend_from_slice(&chunk[..read]);
}
};
within(async {
tokio::select! {
() = streaming => {}
() = receiving => {}
}
})
.await;
assert_eq!(received, LAST);
}
}

View file

@ -12,6 +12,7 @@ envy = "0.4.2"
http-body-util = "0.1"
litellm-inference.workspace = true
litellm-gateway-inference.workspace = true
litellm-gateway-forward.workspace = true
litellm-gateway-mcp.workspace = true
tokio-util = "0.7"
thiserror.workspace = true

View file

@ -10,7 +10,7 @@ use serde_json::json;
mod settings;
use settings::{Settings, UiSettings};
use settings::{LogSettings, Settings, UiSettings};
struct StderrSink {
level: Level,
@ -41,6 +41,15 @@ impl Sink for StderrSink {
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
if let Some(forward) = litellm_gateway_forward::Settings::from_env()? {
let log: LogSettings = settings::from_iter(std::env::vars_os())?;
Logger::new(StderrSink {
level: log.log_level(),
})
.install_global()?;
litellm_gateway_forward::run(forward, shutdown_signal()).await?;
return Ok(());
}
let settings: Settings = settings::from_iter(std::env::vars_os())?;
let level = settings.log_level();
Logger::new(StderrSink { level }).install_global()?;
@ -126,7 +135,20 @@ async fn shutdown_signal() {
}
}
}
#[cfg(not(unix))]
// Windows support exists for local CLI runs only, the proxy is never deployed on Windows. The supervisor
// stops the gateway with CTRL_BREAK_EVENT, which has to drain the same way SIGTERM does.
#[cfg(windows)]
{
match tokio::signal::windows::ctrl_break() {
Ok(mut ctrl_break) => {
tokio::select! { _ = tokio::signal::ctrl_c() => (), _ = ctrl_break.recv() => () }
}
Err(_) => {
let _ = tokio::signal::ctrl_c().await;
}
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = tokio::signal::ctrl_c().await;
}

View file

@ -4,6 +4,23 @@ use litellm_secret_value::SecretValue;
use litellm_tracing::Level;
use serde::{Deserialize, de::DeserializeOwned};
#[derive(Deserialize)]
pub(super) struct LogSettings {
rust_log: Option<String>,
}
impl LogSettings {
pub fn log_level(&self) -> Level {
log_level(self.rust_log.as_deref())
}
}
fn log_level(rust_log: Option<&str>) -> Level {
rust_log
.and_then(|value| value.parse().ok())
.unwrap_or(Level::INFO)
}
#[derive(Deserialize)]
#[serde(default)]
pub(super) struct Settings {
@ -26,10 +43,7 @@ impl Default for Settings {
impl Settings {
pub fn log_level(&self) -> Level {
self.rust_log
.as_deref()
.and_then(|value| value.parse().ok())
.unwrap_or(Level::INFO)
log_level(self.rust_log.as_deref())
}
}

View file

@ -188,6 +188,8 @@ struct RequestSpec {
web_search: Option<bool>,
route_handler: Option<String>,
decisions_media: Option<bool>,
batch_create: Option<bool>,
embedding_batch: Option<bool>,
wildcard_request: Option<String>,
unrouted: Option<bool>,
passthrough_on_no_deployment: Option<bool>,
@ -255,6 +257,8 @@ pub(crate) fn parse_request(value: Value, model: Option<&str>) -> Result<RouterR
web_search: spec.web_search.unwrap_or(false),
route_handler: spec.route_handler,
decisions_media: spec.decisions_media.unwrap_or(false),
batch_create: spec.batch_create.unwrap_or(false),
embedding_batch: spec.embedding_batch.unwrap_or(false),
wildcard_request: spec.wildcard_request,
unrouted: spec.unrouted.unwrap_or(false),
passthrough_on_no_deployment: spec.passthrough_on_no_deployment.unwrap_or(false),

View file

@ -68,7 +68,12 @@ pub(crate) enum Stage {
/// Pre-call checks and sub-routers: return the deployments that remain.
Plugins,
/// A strategy router-core does not implement: return the candidates with the pick first.
Strategy(String),
/// When candidates share an id, `records` holds each candidate's deployment, in order, and the
/// host answers with the pick's position, so a pick splits over every entry as Python's does.
Strategy {
strategy: String,
records: Vec<Value>,
},
/// Tag routing: return the deployments that remain.
Tags,
/// `enable_pre_call_checks`: return the facts the filter decides by.
@ -79,6 +84,10 @@ pub(crate) enum Stage {
RouteIncapable { handler: String },
/// `_decisions_deployment_refuses_media`: return the candidates that refuse the call's media.
MediaRefusing,
/// `deployments_admitting_embedding_batch`: return the candidates the embedding pick keeps.
EmbeddingBatch,
/// The override strategy's pre-call check on a deployment named by id.
OverrideCheck(String),
/// The routing plugins: run them when `run`, then return the candidate models they left.
RoutingPlugins { run: bool },
/// The host's `CustomLogger` deployment filters: return the ids that remain, or a failure.
@ -163,6 +172,8 @@ pub(crate) enum HostCall {
/// The name the attempt resolved: the requested name or the fallback target.
model: String,
model_group: String,
/// The group a pre-routing hook selected for `model`, when it differs.
routed: Option<String>,
/// The `order` level of a same-group order fallback.
target_order: Option<i64>,
/// Every deployment `model` resolved to for this caller, the picked one included.
@ -279,6 +290,8 @@ pub(crate) enum HostCallResponse {
RefuseFallbacks(bool),
/// The candidate ids that remain, pick first.
Select(Vec<String>),
/// A strategy's pick among candidates sharing an id: positions in the candidates, pick first.
Positions(Vec<usize>),
/// The model group to resolve instead, a custom strategy's deployment, or `None`.
PreRoute(Option<PreRouted>),
/// The facts a `pre_call` select step asked for.
@ -309,9 +322,11 @@ impl HostCallResponse {
Self::Slept => StepKind::Sleep,
Self::AllowFallback(_) => StepKind::AllowFallback,
Self::RefuseFallbacks(_) => StepKind::RefuseFallbacks,
Self::Select(_) | Self::PreCall(_) | Self::Models(_) | Self::Filtered(_) => {
StepKind::Select
}
Self::Select(_)
| Self::Positions(_)
| Self::PreCall(_)
| Self::Models(_)
| Self::Filtered(_) => StepKind::Select,
Self::PreRoute(_) => StepKind::PreRoute,
Self::Cache(_) => StepKind::Cache,
Self::Secrets(_) => StepKind::Secrets,
@ -343,6 +358,13 @@ impl HostCallResponse {
{
return Err(DriveError::UnknownCandidate { id: id.clone() });
}
if let (Self::Positions(positions), HostCall::Select { candidates, .. }) = (self, call)
&& let Some(position) = positions.iter().find(|p| **p >= candidates.len())
{
return Err(DriveError::UnknownCandidate {
id: format!("#{position}"),
});
}
if let (Self::Secrets(values), HostCall::Secrets { refs, .. }) = (self, call)
&& values.len() != refs.len()
{
@ -654,6 +676,28 @@ impl RouterCache for StepCache {
}
/// A deployment as Python spells a `model_list` entry, with its id in `model_info`.
/// Whether two candidates share an id, which a pick answered by id can't tell apart.
fn shares_ids(candidates: &[Arc<Deployment>]) -> bool {
let mut seen = std::collections::HashSet::new();
!candidates.iter().all(|d| seen.insert(d.id.as_str()))
}
/// The candidates a host answer names, in its order. An id names every candidate that carries
/// it, so deployments sharing an id stay together through a filter, as Python's list keeps them.
fn answered_by_id(candidates: &[Arc<Deployment>], ids: &[String]) -> Vec<Arc<Deployment>> {
let mut taken = vec![false; candidates.len()];
let mut kept = Vec::new();
for id in ids {
for (position, deployment) in candidates.iter().enumerate() {
if !taken[position] && deployment.id == *id {
taken[position] = true;
kept.push(deployment.clone());
}
}
}
kept
}
pub(crate) fn deployment_record(deployment: &Deployment) -> Value {
deployment.record()
}
@ -693,6 +737,7 @@ impl Host for StepHost {
deployment: deployment_record(&attempt.deployment),
model: attempt.name.clone(),
model_group: attempt.model_group.clone(),
routed: attempt.routed.clone(),
target_order: attempt.target_order,
candidate_ids: attempt.candidate_ids.clone(),
retry: attempt.retry,
@ -736,13 +781,22 @@ impl Host for StepHost {
let call = HostCall::Select {
stage: match stage {
SelectStage::Plugins => Stage::Plugins,
SelectStage::Strategy(strategy) => Stage::Strategy(strategy.to_string()),
SelectStage::Strategy(strategy) => Stage::Strategy {
strategy: strategy.to_string(),
records: if shares_ids(&candidates) {
candidates.iter().map(|d| deployment_record(d)).collect()
} else {
Vec::new()
},
},
SelectStage::Tags => Stage::Tags,
SelectStage::TextOnly => Stage::TextOnly,
SelectStage::RouteIncapable { handler } => Stage::RouteIncapable {
handler: handler.clone(),
},
SelectStage::MediaRefusing => Stage::MediaRefusing,
SelectStage::EmbeddingBatch => Stage::EmbeddingBatch,
SelectStage::OverrideCheck(strategy) => Stage::OverrideCheck(strategy.to_string()),
},
pool: ctx.pool.iter().map(|d| d.id.clone()).collect(),
model_group: ctx.model_group.to_owned(),
@ -751,13 +805,14 @@ impl Host for StepHost {
group: group.map(str::to_owned),
candidates: candidates.iter().map(|d| d.id.clone()).collect(),
};
let HostCallResponse::Select(ids) = answered(call_host(call).await)? else {
unreachable!("{CHECKED}");
};
Ok(ids
.iter()
.filter_map(|id| candidates.iter().find(|d| d.id == *id).cloned())
.collect())
match answered(call_host(call).await)? {
HostCallResponse::Select(ids) => Ok(answered_by_id(&candidates, &ids)),
HostCallResponse::Positions(positions) => Ok(positions
.iter()
.map(|position| candidates[*position].clone())
.collect()),
_ => unreachable!("{CHECKED}"),
}
}
async fn pre_route(&self, pre: &PreRoute<'_>) -> Result<Option<PreRouted>, Error> {
@ -855,10 +910,7 @@ impl Host for StepHost {
unreachable!("{CHECKED}");
};
let ids = result.map_err(Error::Attempt)?;
Ok(ids
.iter()
.filter_map(|id| candidates.iter().find(|d| d.id == *id).cloned())
.collect())
Ok(answered_by_id(&candidates, &ids))
}
async fn allow_fallback(
@ -922,6 +974,7 @@ impl Host for StepHost {
| RouterEvent::Blocked { .. }
| RouterEvent::CooldownSet { .. }
| RouterEvent::Selected { .. }
| RouterEvent::PickStarted { .. }
) {
return;
}
@ -1461,7 +1514,7 @@ mod tests {
let mut driver = start(&router, "primary");
let step = store.resume(&mut driver, None);
let Step::HostCall(HostCall::Select {
stage: Stage::Strategy(strategy),
stage: Stage::Strategy { strategy, records },
candidates,
..
}) = step
@ -1470,6 +1523,7 @@ mod tests {
};
assert_eq!(strategy, "least-busy");
assert_eq!(candidates, ["a1", "a2"]);
assert!(records.is_empty(), "distinct ids send no records");
let step = store.resume(
&mut driver,
Some(HostCallResponse::Select(vec!["a2".to_owned()])),
@ -1480,6 +1534,40 @@ mod tests {
);
}
#[rstest]
fn a_pick_among_deployments_sharing_an_id_is_answered_by_position() {
let mut second = deployment("primary", "a1");
second["litellm_params"]["api_base"] = json!("https://second.example");
let router = router(
json!({
"model_list": [deployment("primary", "a1"), second],
"routing_strategy": "least-busy",
}),
json!({}),
);
let mut store = Store::default();
let mut driver = start(&router, "primary");
let step = store.resume(&mut driver, None);
let Step::HostCall(HostCall::Select {
stage: Stage::Strategy { records, .. },
..
}) = step
else {
panic!("a host strategy should ask for a selection, got {step:?}");
};
assert_eq!(
records.len(),
2,
"each candidate sharing an id sends its record"
);
let step = store.resume(&mut driver, Some(HostCallResponse::Positions(vec![1])));
assert!(
matches!(&step, Step::HostCall(HostCall::Attempt { deployment, .. })
if deployment["litellm_params"]["api_base"] == "https://second.example"),
"expected the second entry, got {step:?}"
);
}
#[rstest]
fn a_selection_is_driven_through_cache_steps(pair: Router) {
let request = RouterRequest {

View file

@ -28,7 +28,7 @@ use litellm_router_core::{
use pyo3::{
exceptions::{PyRuntimeError, PyValueError},
prelude::*,
types::{PyBool, PyDict, PyList, PyString},
types::{PyBool, PyDict, PyList, PyString, PyTuple},
};
use serde_json::Value;
@ -457,7 +457,7 @@ impl RouterCoreHandle {
}
/// Record a success a logging callback saw, driven like `report_failure`; it ends with
/// `done` (`key`: the success counter's key, or None for an unknown deployment).
/// `done` (`key`: the tokens counter's key when usage was added, else None).
/// `usage_model` is the model its usage is keyed by, and `tracks_usage` the host's answer to
/// whether it counts any (see `Output::tracks_usage`). `callbacks`: see `report_failure`.
#[pyo3(signature = (id, total_tokens, requests, usage_model=None, tracks_usage=None, callbacks=None))]
@ -1193,6 +1193,12 @@ fn host_call_response(
}
Ok(HostCallResponse::Filtered(Ok(outcome.extract()?)))
}
HostCall::Select {
stage: Stage::Strategy { records, .. },
..
} if !records.is_empty() => Ok(HostCallResponse::Positions(
outcome.ok_or_else(missing)?.extract()?,
)),
HostCall::Select { .. } => Ok(HostCallResponse::Select(
outcome.ok_or_else(missing)?.extract()?,
)),
@ -1285,6 +1291,15 @@ fn pre_route_outcome(outcome: Option<Bound<'_, PyAny>>) -> PyResult<Option<PreRo
if let Ok(model) = outcome.cast::<PyString>() {
return Ok(Some(PreRouted::Model(model.to_str()?.to_owned())));
}
// `(model, group)`: the model to resolve, served as the group a session binding stamped.
if let Ok(pair) = outcome.cast::<PyTuple>()
&& pair.len() == 2
{
return Ok(Some(PreRouted::Bound {
model: pair.get_item(0)?.extract()?,
group: pair.get_item(1)?.extract()?,
}));
}
let spec: DeploymentSpec = serde_json::from_value(document(&outcome)?)
.map_err(|error| PyValueError::new_err(error.to_string()))?;
let deployment = Deployment::from_spec(spec)
@ -1401,7 +1416,7 @@ fn cause_items(dict: &Bound<'_, PyDict>, cause: RetryCause) -> PyResult<()> {
fn pick_items(dict: &Bound<'_, PyDict>, error: &Error) -> PyResult<()> {
error_items(dict, error)?;
match error {
Error::NoHealthyDeployments { model } | Error::UnknownModel { model } => {
Error::NoHealthyDeployments { model, .. } | Error::UnknownModel { model } => {
dict.set_item("failed_model", model)
}
_ => Ok(()),
@ -1443,6 +1458,10 @@ fn error_items(dict: &Bound<'_, PyDict>, error: &Error) -> PyResult<()> {
dict.set_item("error_model", model)?;
dict.set_item("error_detail", format!("{until} {timezone}"))
}
Error::NoHealthyDeployments {
request_ids: Some(ids),
..
} => dict.set_item("error_request_ids", PyList::new(dict.py(), ids)?),
Error::NonNumericWeight { metric } => dict.set_item("error_detail", metric),
Error::MissingRoutingGroup { group } => dict.set_item("error_model", group),
Error::ModelInfo { exception, detail } => {
@ -1637,6 +1656,10 @@ fn events_list(py: Python<'_>, events: Vec<RouterEvent>) -> PyResult<Bound<'_, P
dict.set_item("deployment_id", deployment_id)?;
dict.set_item("cooldown_time", cooldown.as_secs_f64())?;
}
RouterEvent::PickStarted { model } => {
dict.set_item("kind", "pick_started")?;
dict.set_item("model", model)?;
}
RouterEvent::Selected {
deployment_id,
pick,
@ -1685,6 +1708,7 @@ fn host_call_items(py: Python<'_>, dict: &Bound<'_, PyDict>, call: HostCall) ->
deployment,
model,
model_group,
routed,
target_order,
candidate_ids,
retry,
@ -1696,6 +1720,7 @@ fn host_call_items(py: Python<'_>, dict: &Bound<'_, PyDict>, call: HostCall) ->
max_retries,
model_group_size,
} => {
dict.set_item("routed", routed)?;
dict.set_item("scope", scope)?;
dict.set_item("max_retries", max_retries)?;
dict.set_item("model_group_size", model_group_size)?;
@ -1729,7 +1754,12 @@ fn host_call_items(py: Python<'_>, dict: &Bound<'_, PyDict>, call: HostCall) ->
} => {
let (stage, strategy) = match stage {
Stage::Plugins => ("plugins", None),
Stage::Strategy(strategy) => ("strategy", Some(strategy)),
Stage::Strategy { strategy, records } => {
if !records.is_empty() {
dict.set_item("records", to_py(py, &Value::Array(records))?)?;
}
("strategy", Some(strategy))
}
Stage::Tags => ("tags", None),
Stage::PreCall => ("pre_call", None),
Stage::TextOnly => ("text_only", None),
@ -1738,6 +1768,8 @@ fn host_call_items(py: Python<'_>, dict: &Bound<'_, PyDict>, call: HostCall) ->
("route_incapable", None)
}
Stage::MediaRefusing => ("media_refusing", None),
Stage::EmbeddingBatch => ("embedding_batch", None),
Stage::OverrideCheck(strategy) => ("override_check", Some(strategy)),
Stage::ProviderRequest => ("provider_request", None),
Stage::CallbackFilters {
excluded_ids,

View file

@ -4,13 +4,7 @@
//! `should_retry_this_error` and `_time_to_sleep_before_retry` in `litellm/router.py`, and
//! `run_async_fallback` in `router_utils/fallback_event_handlers.py`.
use std::{
borrow::Cow,
future::Future,
pin::Pin,
sync::Arc,
time::{Duration, Instant},
};
use std::{borrow::Cow, future::Future, pin::Pin, sync::Arc, time::Duration};
use serde_json::{Map, Value};
@ -29,7 +23,7 @@ use crate::{
host_index::python_str,
lookup::Lookup,
mock::MockFailure,
outcome::OutcomeWrite,
outcome::{OutcomeCallbacks, OutcomeWrite},
prerouting::{PreRoute, PreRouted},
registry::{ResolveKind, ResolveScope},
retry::{RetryContext, resolve_retry_policy, should_retry},
@ -63,6 +57,12 @@ pub struct RouterResponse {
struct Failed {
error: Box<Error>,
deployment_id: Option<String>,
/// The group a pre-routing hook rewrote the level's name to for the failed attempt (an auto
/// router's tier), which its order fallbacks and fallback lookup key off
/// (`get_pre_routing_selection`).
routed: Option<String>,
/// The group the host stamped that attempt as served for ([`Candidates::served_as`]).
served_as: Option<String>,
}
impl From<Error> for Failed {
@ -70,6 +70,8 @@ impl From<Error> for Failed {
Self {
error: Box::new(error),
deployment_id: None,
routed: None,
served_as: None,
}
}
}
@ -103,6 +105,8 @@ struct Target {
/// `_failover_excluded_ids` in the level's metadata: the deployments weighted failover
/// already excluded on the way here.
failover_excluded: Arc<[String]>,
/// The group a pre-routing hook selected for the level's failed attempt, if it rewrote it.
routed: Option<String>,
}
/// A step of a level's fallback chain: a configured target, or an order level of the group.
@ -166,10 +170,18 @@ fn unattempted_chain(
target: &Target,
at: FallbackHop,
attempted: &[Tried],
served: (Option<&str>, Option<&str>),
) -> bool {
let mut lookup = vec![target.group.as_str()];
if request.model != target.group {
lookup.push(request.model.as_str());
let (routed, served_as) = served;
let mut lookup: Vec<&str> = Vec::new();
for group in routed
.into_iter()
.chain(served_as)
.chain([target.group.as_str(), request.model.as_str()])
{
if !lookup.contains(&group) {
lookup.push(group);
}
}
list.lookup_groups(&lookup, lists.keys)
.is_some_and(|targets| {
@ -285,6 +297,7 @@ impl Core {
params: None,
excluded: Arc::from([]),
failover_excluded: Arc::from([]),
routed: None,
};
let at = FallbackHop::default();
// A fallbacks mock stands in for the requested group's retry loop: no pick, no attempt.
@ -343,6 +356,8 @@ impl Core {
let Failed {
error,
deployment_id: failed_id,
routed,
served_as,
} = failed;
let error = *error;
self.level_failed(at, &target, &error, false);
@ -360,7 +375,14 @@ impl Core {
self.level_failed(at, &target, &raised, true);
return Err(raised);
}
let (targets, order_path) = self.fallback_targets(snapshot, request, &target, &error);
let (targets, order_path) = self.fallback_targets(
snapshot,
request,
&target,
routed.as_deref(),
served_as.as_deref(),
&error,
);
if !order_path {
self.host.observe(&RouterEvent::FallingBack {
level: at.level,
@ -368,6 +390,7 @@ impl Core {
});
}
let mut target = target;
target.routed = routed;
// `_maybe_run_weighted_failover`: its own `run_async_fallback`, before the regular one.
let failover = if order_path {
None
@ -463,7 +486,12 @@ impl Core {
if at.depth >= max_fallbacks {
return Err(None);
}
let failed = Tried::Target(FallbackTarget::Name(target.group.clone()));
let failed = Tried::Target(FallbackTarget::Name(
target
.routed
.clone()
.unwrap_or_else(|| target.group.clone()),
));
if !chain.attempted.contains(&failed) {
chain.attempted.push(failed);
}
@ -488,17 +516,34 @@ impl Core {
let mut unroutable: Option<Value> = None;
for next in targets {
let (tried, group, order) = match &next {
Next::Order(group, order) => (
Tried::Order(group.clone(), *order),
group.clone(),
Some(*order),
),
Next::Order(group, order) => {
// An order level of the group a pre-routing hook selected passes the
// fallback gates as any group the level did not serve does.
if *group != target.group {
match self.host.allow_fallback(request, group).await {
Ok(true) => {}
Ok(false) => continue,
Err(raised) => return Err(Some(Error::Attempt(raised))),
}
}
(
Tried::Order(group.clone(), *order),
group.clone(),
Some(*order),
)
}
Next::Failover(group, excluded) => {
let mut key = excluded.to_vec();
key.sort();
(Tried::Failover(group.clone(), key), group.clone(), None)
}
Next::Fallback(FallbackTarget::Name(name)) if *name == target.group => continue,
// The group that just failed: the pre-routing selection when there was one, so
// a subagent bound to another tier can fall back to the model it asked for.
Next::Fallback(FallbackTarget::Name(name))
if *name == target.routed.as_deref().unwrap_or(&target.group) =>
{
continue;
}
// A provider-scoped request never leaves its group; a dict target with no
// `model` names no group, so it is skipped too.
Next::Fallback(fallback)
@ -573,6 +618,7 @@ impl Core {
params: params.clone(),
excluded,
failover_excluded: target.failover_excluded.clone(),
routed: None,
};
let parent = at;
let at = FallbackHop {
@ -704,6 +750,8 @@ impl Core {
snapshot: &RouterStateSnapshot,
request: &RouterRequest,
target: &Target,
routed: Option<&str>,
served_as: Option<&str>,
error: &Error,
) -> (Option<Vec<Next>>, bool) {
// A pick's error decides by its exception's classes as an attempt's does: a pre-call
@ -711,11 +759,19 @@ impl Core {
let failure = retried_failure(error);
let is_a = |name: &str| failure.as_ref().is_some_and(|f| f.is_a(name));
let lists = Lists::of(snapshot, request);
// `fallback_lookup_groups`: the group being served, then the group the request was for.
let mut lookup = vec![target.group.as_str()];
if request.model != target.group {
lookup.push(request.model.as_str());
// `fallback_lookup_groups`: the group a pre-routing hook selected, the group being served,
// then the group the request was for.
let mut lookup: Vec<&str> = routed.into_iter().collect();
for group in served_as
.into_iter()
.chain([target.group.as_str(), request.model.as_str()])
{
if !lookup.contains(&group) {
lookup.push(group);
}
}
// `order_model_group`: the pre-routing selection's order levels, else the level's own.
let order_group = routed.unwrap_or(target.group.as_str());
let chain = |list: &Fallbacks| {
if list.is_client_side(lists.keys) {
Some(list.as_chain())
@ -734,7 +790,7 @@ impl Core {
if !skip_order {
// A routing group's members, with a priority group's priorities as their order.
let listing_team = request.listing_team_id.as_deref();
let mut orders: Vec<i64> = group_members(snapshot, &target.group, listing_team)
let mut orders: Vec<i64> = group_members(snapshot, order_group, listing_team)
.iter()
.filter(|d| d.listed_for_team(listing_team))
.filter_map(|d| d.order())
@ -742,11 +798,14 @@ impl Core {
orders.sort_unstable();
orders.dedup();
if orders.len() > 1 {
let current = target.order.unwrap_or(orders[0]);
let current = target
.order
.filter(|_| routed.is_none())
.unwrap_or(orders[0]);
let mut targets: Vec<Next> = orders
.into_iter()
.filter(|order| *order > current)
.map(|order| Next::Order(target.group.clone(), order))
.map(|order| Next::Order(order_group.to_owned(), order))
.collect();
if let Some(list) = lists.fallbacks {
targets.extend(fallbacks_of(chain(list).unwrap_or_default()));
@ -879,6 +938,8 @@ impl Core {
return Err(Failed {
error: Box::new(Error::Attempt(AttemptError::host_raised(&["Exception"]))),
deployment_id: None,
routed: None,
served_as: None,
});
}
let Some(first_failure) = retried_failure(&failed.error) else {
@ -965,6 +1026,8 @@ impl Core {
return Err(Failed {
error: Box::new(Error::Attempt(AttemptError::host_raised(&["Exception"]))),
deployment_id: None,
routed: None,
served_as: None,
});
}
if num_retries == 0 {
@ -1162,7 +1225,7 @@ impl Core {
.unrouted_attempt(snapshot, op, request, target, (retry, max_retries), at)
.await;
}
let pick_started = Instant::now();
let pick_started = self.health.now_time();
let (deployment, candidates) = match self
.picked(snapshot, op, request, target, inputs, retry, at)
.await
@ -1179,7 +1242,11 @@ impl Core {
self.host.observe(&RouterEvent::Selected {
model_group: candidates.model_group.clone(),
deployment_id: deployment.id.clone(),
pick: pick_started.elapsed(),
pick: self
.health
.now_time()
.duration_since(pick_started)
.unwrap_or_default(),
});
if !self.host.supports(op, deployment.provider()) {
return Err(Error::Config(ConfigError::Unsupported(Unsupported::Op {
@ -1205,7 +1272,7 @@ impl Core {
},
None,
snapshot.settings.dynamic.default_ref(),
jiff::Timestamp::now(),
self.health.timestamp(),
),
Ok(None)
);
@ -1219,6 +1286,7 @@ impl Core {
} else {
candidates.model_group.clone()
},
routed: routed_name(target, &candidates),
target_order: target.order,
candidate_ids: candidates.all.iter().map(|d| d.id.clone()).collect(),
retry,
@ -1236,23 +1304,43 @@ impl Core {
// the stream's end.
match self.host.invoke(&attempt).await {
Ok(output) => {
// `_should_raise_content_policy_error`: a blocked response is raised only when
// a content-policy fallback would serve it, and counts as no failure.
let routed = routed_name(target, &candidates);
let served = (routed.as_deref(), candidates.served_as.as_deref());
let raised = match output.blocked {
Some(Blocked::ContentFilter) => self.has_content_policy_fallback(
snapshot, request, target, at, attempted, served,
),
Some(Blocked::Refusal) => self.refusal_fallback_available(
snapshot, request, target, at, attempted, served,
),
None => false,
};
let tracks = output
.tracks_usage
.unwrap_or_else(|| deployment.tracks_usage());
// A shared logging object logs the success of the response that serves the
// request alone, so a raised blocked response counts its request and no success.
let callbacks = match raised && request.outcome_callbacks.shared_logging {
true => OutcomeCallbacks {
success: false,
..request.outcome_callbacks
},
false => request.outcome_callbacks,
};
let recorded = match (output.deferred, tracks) {
(true, true) => {
let tokens = output.total_tokens as f64;
self.health.add_usage(&deployment, None, tokens, 1.0).await
self.health
.add_usage(&deployment, None, tokens, 1.0)
.await
.map(|_| ())
}
(true, false) => Ok(()),
(false, _) => {
self.health
.record_success(
request.outcome_callbacks,
&deployment,
output.total_tokens,
tracks,
)
.record_success(callbacks, &deployment, output.total_tokens, tracks)
.await
}
};
@ -1262,16 +1350,6 @@ impl Core {
self.host.observe(&RouterEvent::Succeeded {
deployment_id: deployment.id.clone(),
});
// `_should_raise_content_policy_error`: a blocked response is raised only when
// a content-policy fallback would serve it, and counts as no failure.
let raised =
match output.blocked {
Some(Blocked::ContentFilter) => self
.has_content_policy_fallback(snapshot, request, target, at, attempted),
Some(Blocked::Refusal) => self
.refusal_fallback_available(snapshot, request, target, at, attempted),
None => false,
};
if let Some(blocked) = output.blocked.filter(|_| raised) {
self.host.observe(&RouterEvent::Blocked {
level: at.level,
@ -1284,6 +1362,8 @@ impl Core {
return Err(Failed {
error: Box::new(Error::Attempt(failure)),
deployment_id: Some(deployment.id.clone()),
routed: routed_name(target, &candidates),
served_as: candidates.served_as.clone(),
});
}
Ok(RouterResponse {
@ -1303,6 +1383,8 @@ impl Core {
Err(Failed {
error: Box::new(Error::Attempt(failure)),
deployment_id: Some(deployment.id.clone()),
routed: routed_name(target, &candidates),
served_as: candidates.served_as.clone(),
})
}
}
@ -1325,6 +1407,9 @@ impl Core {
&snapshot.settings.routing_strategy,
request,
)?;
self.host.observe(&RouterEvent::PickStarted {
model: target.group.clone(),
});
let routed = self
.pre_routed(PreRoute {
op,
@ -1334,22 +1419,25 @@ impl Core {
retry,
})
.await?;
let (routed, served_as) = match routed {
PreRouted::Bound { model, group } => (PreRouted::Model(model), Some(group)),
other => (other, None),
};
match routed {
PreRouted::Model(name) => {
snapshot.missing_routing_group(request, &name)?;
let candidates = self
let mut candidates = self
.candidates(snapshot, op, request, &name, inputs)
.await?;
candidates.served_as = served_as;
if candidates.healthy.is_empty() {
return Err(Error::NoHealthyDeployments {
model: candidates.failed_model(&snapshot.registry),
}
.into());
return Err(candidates.none_healthy(&snapshot.registry).into());
}
let deployment = self.pick(snapshot, op, request, &candidates).await?;
Ok((deployment, candidates))
}
// A custom strategy's pick is served as is, for the requested name.
PreRouted::Bound { .. } => unreachable!("mapped to a model above"),
PreRouted::Deployment(deployment) => {
let candidates = Candidates {
name: target.group.clone(),
@ -1358,6 +1446,7 @@ impl Core {
all: vec![deployment.clone()],
healthy: vec![deployment.clone()],
wildcard_request: None,
served_as: None,
};
Ok((deployment, candidates))
}
@ -1383,6 +1472,7 @@ impl Core {
deployment,
name: target.group.clone(),
model_group: target.group.clone(),
routed: None,
target_order: target.order,
candidate_ids: Vec::new(),
retry,
@ -1417,10 +1507,11 @@ impl Core {
target: &Target,
at: FallbackHop,
attempted: &[Tried],
served: (Option<&str>, Option<&str>),
) -> bool {
let lists = Lists::of(snapshot, request);
match lists.content_policy {
Some(list) => unattempted_chain(list, &lists, request, target, at, attempted),
Some(list) => unattempted_chain(list, &lists, request, target, at, attempted, served),
None => snapshot.settings.dynamic.fallbacks.has_star(),
}
}
@ -1434,20 +1525,22 @@ impl Core {
target: &Target,
at: FallbackHop,
attempted: &[Tried],
served: (Option<&str>, Option<&str>),
) -> bool {
if request.disable_fallbacks {
return false;
}
let lists = Lists::of(snapshot, request);
if lists.content_policy.is_some() {
return self.has_content_policy_fallback(snapshot, request, target, at, attempted);
return self
.has_content_policy_fallback(snapshot, request, target, at, attempted, served);
}
if snapshot.settings.dynamic.fallbacks.has_star() {
return true;
}
lists
.fallbacks
.is_some_and(|list| unattempted_chain(list, &lists, request, target, at, attempted))
lists.fallbacks.is_some_and(|list| {
unattempted_chain(list, &lists, request, target, at, attempted, served)
})
}
/// `async_deployment_callback_on_failure`, when it runs for this failure.
@ -1553,3 +1646,8 @@ impl Core {
Ok(())
}
}
/// The name a pre-routing hook rewrote the level's group to for this pick, if it did.
fn routed_name(target: &Target, candidates: &Candidates) -> Option<String> {
(candidates.name != target.group).then(|| candidates.name.clone())
}

View file

@ -37,6 +37,9 @@ pub struct StreamOrigin {
pub attempted_retries: u32,
/// The budget the first stream retry committed to (`committed_retry_budget_for_request`).
pub committed_budget: Option<u32>,
/// The group a pre-routing hook selected for `group`, which the fallback lookup keys on first.
#[serde(default)]
pub routed: Option<String>,
}
/// What may still take over a stream that fails before content.
@ -61,14 +64,22 @@ impl StreamOrigin {
params: None,
excluded: Arc::from([]),
failover_excluded: Arc::from([]),
routed: self.routed.clone(),
}
}
/// `fallback_lookup_groups`: the served group, then the group the request was for.
fn lookup<'a>(&'a self, request: &'a RouterRequest) -> Vec<&'a str> {
let mut lookup = vec![self.group.as_str()];
if request.model != self.group {
lookup.push(request.model.as_str());
let mut lookup: Vec<&str> = Vec::new();
for group in self
.routed
.as_deref()
.into_iter()
.chain([self.group.as_str(), request.model.as_str()])
{
if !lookup.contains(&group) {
lookup.push(group);
}
}
lookup
}
@ -186,7 +197,10 @@ impl Router {
scope: 0,
},
&mut chain,
Failed::from(Error::Attempt(failure)),
Failed {
routed: origin.routed.clone(),
..Failed::from(Error::Attempt(failure))
},
)
.await
}

View file

@ -40,7 +40,13 @@ pub enum Error {
#[error("no deployment serves model `{model}`")]
UnknownModel { model: String },
#[error("no deployment of `{model}` is available")]
NoHealthyDeployments { model: String },
NoHealthyDeployments {
model: String,
/// The ids of the deployments the request could route to before the cooldown filter
/// (`request_deployments`), when the candidate list came up empty; `None` when the
/// strategy refused every candidate.
request_ids: Option<Vec<String>>,
},
#[error("the attempt failed")]
Attempt(#[from] AttemptError),
#[error("the routing cache failed")]
@ -201,8 +207,9 @@ impl Error {
Self::UnknownModel { model } => Self::UnknownModel {
model: model.clone(),
},
Self::NoHealthyDeployments { model } => Self::NoHealthyDeployments {
Self::NoHealthyDeployments { model, request_ids } => Self::NoHealthyDeployments {
model: model.clone(),
request_ids: request_ids.clone(),
},
Self::Paused { model } => Self::Paused {
model: model.clone(),

View file

@ -247,6 +247,10 @@ impl Health {
self.clock.now()
}
pub(crate) fn timestamp(&self) -> jiff::Timestamp {
jiff::Timestamp::try_from(self.clock.now()).unwrap_or(jiff::Timestamp::UNIX_EPOCH)
}
fn now(&self) -> f64 {
unix_seconds(self.clock.now())
}
@ -554,35 +558,35 @@ impl Health {
return Ok(());
}
callbacks
.record(
OutcomeWrite::AttemptUsage,
self.add_usage(deployment, None, total_tokens as f64, 1.0),
)
.record(OutcomeWrite::AttemptUsage, async {
self.add_usage(deployment, None, total_tokens as f64, 1.0)
.await
.map(|_| ())
})
.await
}
/// `_increment_deployment_usage`, for a deployment that tracks usage: tokens and requests
/// under `model` (metadata's `deployment`, which a wildcard route fills; else the
/// deployment's own), unless there is nothing to add.
/// deployment's own), unless there is nothing to add. Returns the tokens counter's key when
/// it added to it.
pub async fn add_usage(
&self,
deployment: &Deployment,
model: Option<&str>,
total_tokens: f64,
requests: f64,
) -> Result<(), Error> {
) -> Result<Option<String>, Error> {
if total_tokens <= 0.0 && requests <= 0.0 {
return Ok(());
return Ok(None);
}
let minute = current_minute(self.clock.now());
let model = model.unwrap_or(&deployment.params.model);
let tpm_key = usage_key(&deployment.id, model, UsageMetric::Tpm, &minute);
self.cache
.async_increment_usage(
&[
(
usage_key(&deployment.id, model, UsageMetric::Tpm, &minute),
total_tokens,
),
(tpm_key.clone(), total_tokens),
(
usage_key(&deployment.id, model, UsageMetric::Rpm, &minute),
requests,
@ -591,7 +595,7 @@ impl Health {
Some(USAGE_TTL),
)
.await?;
Ok(())
Ok(Some(tpm_key))
}
/// `async_deployment_callback_on_failure`: a failed request counts against the deployment's

View file

@ -83,6 +83,13 @@ pub struct RouterRequest {
/// A Decisions call carrying audio or videos: the deployments that refuse them are skipped
/// unless that leaves nothing (`_without_decisions_deployments_refusing_media`).
pub decisions_media: bool,
/// A batch create (`batch_create_routing`): when the caller may use a deployment declared
/// `model_info.mode: batch`, the Azure deployments that are not are skipped
/// (`without_deployments_that_cannot_batch`).
pub batch_create: bool,
/// An embedding pick: the host keeps the candidates whose `max_embedding_batch_size` admits
/// the input (`deployments_admitting_embedding_batch`).
pub embedding_batch: bool,
/// `f"{provider}/{model}"` for a lookup that cannot ask the host
/// (`_core_get_routable_deployments`); a pick asks [`Host::provider_request`].
pub wildcard_request: Option<String>,
@ -291,6 +298,9 @@ pub struct Attempt {
pub name: String,
/// The model group being served, after fallbacks.
pub model_group: String,
/// The group a pre-routing hook selected for `name`, when it differs (the tier stamp the
/// fallback lookup keys on first).
pub routed: Option<String>,
/// The `order` level an order fallback targets in the same group.
pub target_order: Option<i64>,
/// Every deployment `name` resolved to for this caller, the picked one included.
@ -383,11 +393,22 @@ pub enum SelectStage {
/// `_decisions_deployment_refuses_media`: return the candidates that refuse the audio or
/// videos a Decisions call carries.
MediaRefusing,
/// `deployments_admitting_embedding_batch`: return the candidates that admit the embedding
/// input, or what the pick keeps when none does (`deployments_when_none_admits_embedding_batch`).
EmbeddingBatch,
/// `_async_override_selector_pre_call_check`: a deployment named by id under a per-request
/// strategy override still passes that strategy's pre-call check (rpm accounting); return the
/// candidates, or raise its refusal.
OverrideCheck(RoutingStrategy),
}
/// Routing events, delivered through [`Host::observe`].
#[derive(Clone, Debug, PartialEq)]
pub enum RouterEvent {
/// A pick for `model` (the level's group) begins: its route phase opens.
PickStarted {
model: String,
},
Selected {
model_group: String,
deployment_id: String,

View file

@ -366,7 +366,7 @@ impl Router {
})
.await?;
let name = match routed {
PreRouted::Model(name) => name,
PreRouted::Model(name) | PreRouted::Bound { model: name, .. } => name,
PreRouted::Deployment(deployment) => return Ok(deployment),
};
snapshot.missing_routing_group(request, &name)?;
@ -374,6 +374,10 @@ impl Router {
.core
.candidates(&snapshot, op, request, &name, &SelectInputs::default())
.await?;
// An empty candidate list names what the request could route to before the cooldown filter.
if candidates.healthy.is_empty() && !candidates.kind.is_single() {
return Err(candidates.none_healthy(&snapshot.registry));
}
self.core.pick(&snapshot, op, request, &candidates).await
}
@ -398,9 +402,7 @@ impl Router {
.await?;
// `_core_async_get_healthy_deployments` raises when nothing is left.
if candidates.healthy.is_empty() {
return Err(Error::NoHealthyDeployments {
model: candidates.failed_model(&snapshot.registry),
});
return Err(candidates.none_healthy(&snapshot.registry));
}
Ok(candidates)
}
@ -434,7 +436,7 @@ impl Router {
/// A success a logging callback saw (`deployment_callback_on_success`): counted for a
/// configured deployment, with its tokens and requests when it tracks usage. Returns the
/// success counter's key, or `None` for an unknown deployment.
/// tokens counter's key when it added usage (`_increment_deployment_usage`), else `None`.
pub async fn report_success(
&self,
id: &str,
@ -462,22 +464,22 @@ impl Router {
let Some(deployment) = snapshot.registry.deployment(id) else {
return Ok(None);
};
let key = self.core.health.count_success(id).await?;
if report
self.core.health.count_success(id).await?;
if !report
.tracks_usage
.unwrap_or_else(|| deployment.tracks_usage())
{
self.core
.health
.add_usage(
&deployment,
report.usage_model.as_deref(),
total_tokens,
requests,
)
.await?;
return Ok(None);
}
Ok(Some(key))
self.core
.health
.add_usage(
&deployment,
report.usage_model.as_deref(),
total_tokens,
requests,
)
.await
}
/// `sync_deployment_callback_on_success`: count a success against `id`, configured or not,

View file

@ -433,6 +433,10 @@ impl<'a> Lookup<'a> {
.collect()
}
pub fn has_team_wildcards(&self, team_id: &str) -> bool {
self.host.team_patterns.iter().any(|(t, _)| t == team_id)
}
/// The deployments `team_id`'s own wildcard pattern routes `name` to
/// (`_core_team_pattern_routers`, keyed by `team_public_model_name`).
pub fn team_wildcard(&self, name: &str, team_id: &str) -> Vec<Arc<Deployment>> {

View file

@ -28,6 +28,10 @@ pub struct OutcomeCallbacks {
pub failure: bool,
/// The attempt runs through `make_call`, which counts its usage whatever the callbacks do.
pub make_call: bool,
/// The request's attempts log on one logging object the caller passed (`litellm_logging_obj`),
/// which logs one success a request, the response that serves it: an attempt whose blocked
/// response is raised for a fallback counts no success.
pub shared_logging: bool,
}
impl Default for OutcomeCallbacks {
@ -36,6 +40,7 @@ impl Default for OutcomeCallbacks {
success: true,
failure: true,
make_call: true,
shared_logging: false,
}
}
}
@ -78,21 +83,25 @@ mod tests {
success: true,
failure: true,
make_call: true,
shared_logging: false,
};
const UNBOUND: OutcomeCallbacks = OutcomeCallbacks {
success: false,
failure: false,
make_call: true,
shared_logging: false,
};
const UNBOUND_WITHOUT_MAKE_CALL: OutcomeCallbacks = OutcomeCallbacks {
success: false,
failure: false,
make_call: false,
shared_logging: false,
};
const BOUND_SYNC: OutcomeCallbacks = OutcomeCallbacks {
success: false,
failure: true,
make_call: true,
shared_logging: false,
};
#[rstest]

View file

@ -33,6 +33,9 @@ pub struct PreRoute<'a> {
pub enum PreRouted {
/// Resolve this model group instead of the requested name.
Model(String),
/// Resolve `model`, served as `group`: the group a session binding stamped on the request,
/// which the level's fallbacks also look up.
Bound { model: String, group: String },
/// A custom strategy's pick: serve this deployment, without resolving or filtering.
Deployment(Arc<Deployment>),
}

View file

@ -234,6 +234,23 @@ impl Deployment {
/// `_deployment_supports_web_search`: `model_info.supports_web_search` when it is set, read
/// for truthiness, else true.
/// `is_batch_capable`: declared `model_info.mode: batch`.
pub(crate) fn is_batch_capable(&self) -> bool {
self.model_info.raw.get("mode").and_then(Value::as_str) == Some("batch")
}
/// `_cannot_run_batches`: an Azure (or Azure AI) deployment not declared batch-capable, by
/// its `custom_llm_provider`, else its model's provider prefix.
pub(crate) fn cannot_run_batches(&self) -> bool {
let provider = self.params.custom_llm_provider.as_deref().or_else(|| {
self.params
.model
.split_once('/')
.map(|(provider, _)| provider)
});
matches!(provider, Some("azure" | "azure_ai")) && !self.is_batch_capable()
}
pub(crate) fn supports_web_search(&self) -> bool {
self.model_info
.raw

View file

@ -223,14 +223,20 @@ pub(crate) fn wildcard_name<'a>(
registry: &'a Registry,
name: &'a str,
specific_deployment: bool,
team_id: Option<&str>,
) -> Option<&'a str> {
let model = registry.alias_of(name).unwrap_or(name);
(registry.has_wildcards()
let lookup = crate::lookup::Lookup::new(registry);
let team_patterns = team_id.is_some_and(|team| lookup.has_team_wildcards(team));
let team_misses = || team_id.is_none_or(|team| lookup.team_wildcard(model, team).is_empty());
let global_misses = || registry.has_wildcards() && registry.wildcard_for(model).is_none();
((team_patterns || registry.has_wildcards())
&& !specific_deployment
&& !registry.has_name(model)
&& (registry.has_name(name) || registry.deployment(name).is_none())
&& registry.routing_group_named(model).is_none()
&& registry.wildcard_for(model).is_none())
&& team_misses()
&& (team_patterns || global_misses()))
.then_some(model)
}
@ -339,15 +345,21 @@ pub fn resolve_request(
let kept = reserved(model, deployments, caller, now)?;
return resolved(ResolveKind::Group, model, kept);
}
// `_core_wildcard_route_deployments`: the team's own pattern, else the proxy-wide one.
let team_owned = team_id
.map(|team| crate::lookup::Lookup::new(registry).team_wildcard(model, team))
.filter(|deployments| !deployments.is_empty());
if let Some(deployments) = team_owned {
// `_core_wildcard_route_deployments`: the team's own pattern, else the proxy-wide one,
// each tried as spelled and then under the name's provider (`get_pattern`).
let team_owned = team_id.and_then(|team| {
let lookup = crate::lookup::Lookup::new(registry);
[Some(model), caller.wildcard_request]
.into_iter()
.flatten()
.map(|request| (request, lookup.team_wildcard(request, team)))
.find(|(_, deployments)| !deployments.is_empty())
});
if let Some((request, deployments)) = team_owned {
let routed = deployments.iter().flat_map(|deployment| {
let public = deployment.model_info.team_public_model_name.as_deref();
let pattern = public.unwrap_or(model);
routed_wildcard(pattern, model, std::slice::from_ref(deployment))
let pattern = public.unwrap_or(request);
routed_wildcard(pattern, request, std::slice::from_ref(deployment))
});
let kept = reserved(model, routed.collect(), caller, now)?;
return resolved(ResolveKind::Wildcard, model, kept);
@ -428,6 +440,7 @@ pub fn resolve_request(
mod tests {
use std::collections::BTreeMap;
use rstest::rstest;
use serde_json::{Value, json};
use super::*;
@ -544,8 +557,11 @@ mod tests {
#[test]
fn a_name_no_pattern_matches_is_tried_under_its_provider() {
let registry = registry(wildcard_group());
assert_eq!(wildcard_name(&registry, "gpt-4o", false), Some("gpt-4o"));
assert_eq!(wildcard_name(&registry, "openai/gpt-4o", false), None);
assert_eq!(
wildcard_name(&registry, "gpt-4o", false, None),
Some("gpt-4o")
);
assert_eq!(wildcard_name(&registry, "openai/gpt-4o", false, None), None);
let caller = Caller {
wildcard_request: Some("openai/gpt-4o"),
..Caller::default()
@ -564,6 +580,48 @@ mod tests {
assert_eq!(resolution.deployments[0].params.model, "openai/gpt-4o");
}
#[rstest]
fn a_bare_name_is_tried_under_its_provider_against_the_teams_own_wildcard() {
let registry = registry(json!([
{"model_name": "model_name_tw_1", "litellm_params": {"model": "openai/*"},
"model_info": {"id": "tw", "team_id": "TW", "team_public_model_name": "openai/*"}},
{"model_name": "g", "litellm_params": {"model": "openai/g"}, "model_info": {"id": "g"}},
]));
// No proxy-wide wildcard: only the team's patterns call for the provider spelling.
assert_eq!(
wildcard_name(&registry, "gpt-4o-mini", false, Some("TW")),
Some("gpt-4o-mini")
);
assert_eq!(wildcard_name(&registry, "gpt-4o-mini", false, None), None);
assert_eq!(
wildcard_name(&registry, "openai/gpt-4o-mini", false, Some("TW")),
None
);
let resolve = |team_id| {
let caller = Caller {
team_id,
wildcard_request: Some("openai/gpt-4o-mini"),
..Caller::default()
};
resolve_request(
&registry,
"gpt-4o-mini",
false,
caller,
None,
None,
Timestamp::now(),
)
.unwrap()
};
let resolution = resolve(Some("TW")).unwrap();
assert_eq!(resolution.kind, ResolveKind::Wildcard);
assert_eq!(resolution.group, "gpt-4o-mini");
assert_eq!(ids(Some(resolution.clone())), ["tw"]);
assert_eq!(resolution.deployments[0].params.model, "openai/gpt-4o-mini");
assert!(resolve(Some("OTHER")).is_none());
}
#[test]
fn a_deployment_named_by_id_refuses_the_endpoint_like_any_other() {
let registry = registry(json!([

View file

@ -16,7 +16,7 @@ use crate::{
host::{RouterRequest, RoutingContext, SelectStage},
registry::{Deployment, Registry, ResolveKind},
resolve::{Caller, resolve_request},
strategy::{StrategyScope, routing_context},
strategy::{StrategyScope, request_override, routing_context},
};
/// Randomness for the shuffle and retry jitter, injectable so tests are deterministic.
@ -77,11 +77,23 @@ pub struct Candidates {
/// The provider-prefixed spelling the name resolved under (`get_pattern`), when the host
/// was asked for one.
pub wildcard_request: Option<String>,
/// The group the host stamped the pick as served for when a pre-routing hook rewrote the name
/// (a Claude Code subagent's bound router): a fallback lookup key.
pub served_as: Option<String>,
}
impl Candidates {
/// The `model` a no-deployments error names: what `_common_checks_available_deployment`
/// returned, so the alias-resolved name a wildcard serves and not its pattern.
/// The error an empty candidate list raises: it names the deployments the request could
/// route to before the cooldown filter.
pub(crate) fn none_healthy(&self, registry: &Registry) -> Error {
Error::NoHealthyDeployments {
model: self.failed_model(registry),
request_ids: Some(self.all.iter().map(|d| d.id.clone()).collect()),
}
}
pub(crate) fn failed_model(&self, registry: &Registry) -> String {
let model = match self.kind {
ResolveKind::Wildcard => registry.alias_of(&self.name).unwrap_or(&self.name),
@ -269,8 +281,12 @@ impl Core {
// No deployment for the name: route to the first default fallback.
let default_target = crate::resolve::default_target(&snapshot.settings.dynamic);
// `get_pattern`: a name no pattern matches is tried again under its inferred provider.
let wildcard_name =
crate::resolve::wildcard_name(registry, name, request.specific_deployment);
let wildcard_name = crate::resolve::wildcard_name(
registry,
name,
request.specific_deployment,
request.team_id.as_deref(),
);
let wildcard_request = match wildcard_name {
Some(model) => {
let scope = StrategyScope::Default;
@ -296,7 +312,7 @@ impl Core {
caller,
default_target,
snapshot.settings.dynamic.default_ref(),
jiff::Timestamp::now(),
self.health.timestamp(),
)?
.ok_or_else(|| Error::UnknownModel {
// The name `_common_checks_available_deployment` looked for, past the alias.
@ -466,6 +482,7 @@ impl Core {
all,
healthy,
wildcard_request,
served_as: None,
});
}
@ -503,6 +520,7 @@ impl Core {
all,
healthy,
wildcard_request,
served_as: None,
});
}
@ -602,6 +620,34 @@ impl Core {
}
}
// `deployments_admitting_embedding_batch`: an embedding pick keeps the deployments whose
// input limit admits the batch; when none does, the host keeps what the pick waits for or
// the 400 names.
if request.embedding_batch && !resolution.kind.is_single() && !healthy.is_empty() {
let mut ctx = self.context(
snapshot,
op,
request,
&resolution.group,
name,
StrategyScope::Default,
);
ctx.pool = &all;
healthy = self
.host
.select(&SelectStage::EmbeddingBatch, &ctx, healthy)
.await?;
}
// `without_deployments_that_cannot_batch`: a batch create on a group the caller may use a
// batch deployment of skips the Azure deployments that cannot run batches.
if request.batch_create
&& !resolution.kind.is_single()
&& healthy.iter().any(|d| d.is_batch_capable())
{
healthy.retain(|d| !d.cannot_run_batches());
}
if let Some(pinned) = request.pinned_deployment_id.as_deref()
&& healthy.iter().any(|d| d.id == pinned)
{
@ -653,6 +699,7 @@ impl Core {
all,
healthy,
wildcard_request,
served_as: None,
})
}
@ -691,14 +738,43 @@ impl Core {
) -> Result<Arc<Deployment>, Error> {
let no_deployment = || Error::NoHealthyDeployments {
model: candidates.failed_model(&snapshot.registry),
request_ids: None,
};
// A deployment named by its id is returned as is, before any strategy runs.
// A deployment named by its id is returned as is, before any strategy runs, past a
// per-request strategy override's pre-call check.
if candidates.kind.is_single() {
return candidates
let named = candidates
.healthy
.first()
.cloned()
.ok_or_else(no_deployment);
.ok_or_else(no_deployment)?;
if let Some(strategy) = request_override(request.routing_strategy.as_deref())
&& !matches!(
strategy,
RoutingStrategy::SimpleShuffle | RoutingStrategy::Unset
)
{
let ctx = self.context(
snapshot,
op,
request,
&candidates.model_group,
&candidates.name,
StrategyScope::Override,
);
let kept = self
.host
.select(
&SelectStage::OverrideCheck(strategy),
&ctx,
vec![named.clone()],
)
.await?;
if kept.is_empty() {
return Err(no_deployment());
}
}
return Ok(named);
}
let (strategy, scope) = routing_context(
&snapshot.registry,

View file

@ -1755,3 +1755,57 @@ async fn a_listed_pass_through_pick_names_the_group_an_alias_resolves_to(config:
Error::NoPassThroughDeployments { model } if model == "primary"
));
}
struct StoppedClock(u64);
impl litellm_router_core::health::Clock for StoppedClock {
fn now(&self) -> std::time::SystemTime {
std::time::UNIX_EPOCH + Duration::from_secs(self.0)
}
}
fn utc_hour(hour: u64) -> u64 {
1_767_225_600 + hour * 3_600
}
#[rstest]
#[case::inside_the_window(utc_hour(10), vec!["open"])]
#[case::outside_the_window(utc_hour(20), vec!["open", "reserved"])]
#[tokio::test]
async fn access_windows_follow_the_routers_clock(#[case] now: u64, #[case] expected: Vec<&str>) {
let config: RouterConfig = serde_json::from_value(json!({
"model_list": [
{"model_name": "chat", "litellm_params": {"model": "openai/a"}, "model_info": {"id": "open"}},
{"model_name": "chat", "litellm_params": {"model": "openai/b"}, "model_info": {
"id": "reserved",
"access_windows": [{"start": "09:00", "end": "17:00", "timezone": "UTC", "team_ids": ["batch"]}],
}},
]
}))
.unwrap();
let router = Router::builder(
config,
RouterDynamicConfig::default(),
Arc::new(ScriptedHost::default()),
)
.randomness(Arc::new(SeededRandomness::new(7)))
.clock(Arc::new(StoppedClock(now)))
.build()
.unwrap();
let mut picked = std::collections::BTreeSet::new();
for _ in 0..40 {
let deployment = router
.select(&Op::from("acompletion"), &request_for("chat"))
.await
.unwrap();
picked.insert(deployment.id.clone());
}
assert_eq!(picked.into_iter().collect::<Vec<_>>(), expected);
}
fn request_for(model: &str) -> RouterRequest {
RouterRequest {
model: model.to_owned(),
..RouterRequest::default()
}
}

View file

@ -7,6 +7,7 @@ from litellm.proxy.db.daily_spend_bulk_upsert import DAILY_SPEND_TABLES, build_b
from litellm.proxy.db.db_span import db_span
from litellm.proxy.db.db_transaction_queue.window_spend_update_queue import WindowSpendTransaction
from litellm.proxy.db.model_usage_rollup import queue_model_usage_upsert
from litellm.proxy.db.rollup_lock_timeout import apply_rollup_lock_timeout
from litellm.repositories.accounting_delivery_repository import DeliveryProjection, LedgerTransaction
if TYPE_CHECKING:
@ -25,6 +26,7 @@ async def apply_deliveries(
from litellm.proxy.guardrails.usage_tracking import UsageUnitIncrement, UsageUnitKey, upsert_usage_unit_row
contributions: Final = project_deliveries(deliveries)
await apply_rollup_lock_timeout(transaction)
await writer.apply_accounting_entities(
prisma_client, proxy_logging_obj, transaction, entity_transactions(contributions)
)

View file

@ -1,30 +1,55 @@
from typing import Final
from prometheus_client import Gauge, Histogram
from dataclasses import dataclass
from typing import TYPE_CHECKING, Final
from litellm.repositories.accounting_delivery_repository import DeliveryMetrics
_PENDING: Final = Gauge("litellm_accounting_pending", "Pending SpendLogs deliveries", multiprocess_mode="livemax")
_PARKED: Final = Gauge("litellm_accounting_parked", "Parked SpendLogs deliveries", multiprocess_mode="livemax")
_OLDEST: Final = Gauge(
"litellm_accounting_oldest_pending_seconds",
"Age of the oldest pending SpendLogs delivery",
multiprocess_mode="livemax",
)
_BATCH_TIME: Final = Histogram("litellm_accounting_batch_seconds", "SpendLogs delivery worker batch time")
_BATCH_COUNT: Final = Gauge(
"litellm_accounting_batch_deliveries", "Retained batch deliveries", multiprocess_mode="livemax"
)
_TABLE_BYTES: Final = Gauge(
"litellm_accounting_delivery_table_bytes", "Delivery table size in bytes", multiprocess_mode="livemax"
)
if TYPE_CHECKING:
from prometheus_client import Gauge, Histogram
@dataclass(frozen=True, slots=True)
class _Instruments:
pending: "Gauge"
parked: "Gauge"
oldest: "Gauge"
batch_time: "Histogram"
batch_count: "Gauge"
table_bytes: "Gauge"
def _instruments() -> _Instruments | None:
try:
# prometheus-client ships only in the proxy-runtime extra, so a plain litellm[proxy] install lands here
from prometheus_client import Gauge, Histogram
except ImportError:
return None
return _Instruments(
pending=Gauge("litellm_accounting_pending", "Pending SpendLogs deliveries", multiprocess_mode="livemax"),
parked=Gauge("litellm_accounting_parked", "Parked SpendLogs deliveries", multiprocess_mode="livemax"),
oldest=Gauge(
"litellm_accounting_oldest_pending_seconds",
"Age of the oldest pending SpendLogs delivery",
multiprocess_mode="livemax",
),
batch_time=Histogram("litellm_accounting_batch_seconds", "SpendLogs delivery worker batch time"),
batch_count=Gauge(
"litellm_accounting_batch_deliveries", "Retained batch deliveries", multiprocess_mode="livemax"
),
table_bytes=Gauge(
"litellm_accounting_delivery_table_bytes", "Delivery table size in bytes", multiprocess_mode="livemax"
),
)
_INSTRUMENTS: Final = _instruments()
def record_deliveries(metrics: DeliveryMetrics, seconds: float) -> None:
_PENDING.set(metrics.pending_count)
_PARKED.set(metrics.parked_count)
_OLDEST.set(max(0.0, metrics.oldest_pending_seconds))
_BATCH_TIME.observe(seconds)
_BATCH_COUNT.set(metrics.batch_count)
_TABLE_BYTES.set(metrics.table_bytes)
if _INSTRUMENTS is None:
return
_INSTRUMENTS.pending.set(metrics.pending_count)
_INSTRUMENTS.parked.set(metrics.parked_count)
_INSTRUMENTS.oldest.set(max(0.0, metrics.oldest_pending_seconds))
_INSTRUMENTS.batch_time.observe(seconds)
_INSTRUMENTS.batch_count.set(metrics.batch_count)
_INSTRUMENTS.table_bytes.set(metrics.table_bytes)

View file

@ -14,6 +14,7 @@ if TYPE_CHECKING:
from litellm.router import Router
_FIELDS: Final = TypeAdapter(dict[str, object])
_JSON_SAFE_INTEGER: Final = 2**53 - 1
def _mapping(value: object) -> Mapping[str, object] | None:
@ -86,6 +87,7 @@ def build_accounting_payload(
"metadata": accounting_metadata,
},
non_finite_as_null=True,
integer_limit=_JSON_SAFE_INTEGER,
)
)

View file

@ -14,6 +14,7 @@ from litellm.accounting.metrics import record_deliveries
from litellm.accounting.projection import Contribution
from litellm.repositories.accounting_delivery_repository import (
AccountingDeliveryRepository,
DeliveryBatchResult,
DeliveryProjection,
LedgerDatabase,
LedgerTransaction,
@ -34,6 +35,14 @@ class _AccountingAlerts(Protocol):
_JOB: Final = "accounting_delivery"
def _filled(result: DeliveryBatchResult, batch_size: int) -> bool:
return result.applied + len(result.parked) >= batch_size
def _progressed(result: DeliveryBatchResult) -> bool:
return bool(result.applied or result.failed)
async def flush_accounting_deliveries(
writer: "DBSpendUpdateWriter", prisma_client: "PrismaClient", proxy_logging_obj: "ProxyLogging"
) -> None:
@ -54,9 +63,9 @@ async def flush_accounting_deliveries(
)
repository: Final = AccountingDeliveryRepository(database)
started: Final = time.monotonic()
batch_size: Final = int(os.environ.get("LITELLM_ACCOUNTING_DELIVERY_BATCH_SIZE", "10000"))
batch_size: Final = int(os.environ.get("LITELLM_ACCOUNTING_DELIVERY_BATCH_SIZE", "500"))
async def run_batch(*, retry_only: bool) -> bool:
async def run_batch(*, retry_only: bool) -> DeliveryBatchResult:
result: Final = await repository.apply_pending(apply, batch_size=batch_size, retry_only=retry_only)
if result.applied:
await writer.invalidate_accounting_entities(applied, proxy_logging_obj)
@ -68,17 +77,25 @@ async def flush_accounting_deliveries(
proxy_logging_obj,
message=f"Accounting delivery parked {len(result.parked)} requests. Included spend totals require repair.",
)
return bool(result.applied or result.failed)
return result
await run_batch(retry_only=False)
fresh_deadline: Final = time.monotonic() + 5
for _ in range(batch_size):
if not _filled(await run_batch(retry_only=False), batch_size) or time.monotonic() >= fresh_deadline:
break
retry_deadline: Final = time.monotonic() + 5
for _ in range(batch_size):
if time.monotonic() >= retry_deadline or not await run_batch(retry_only=True):
if time.monotonic() >= retry_deadline or not _progressed(await run_batch(retry_only=True)):
break
retention_days: Final = int(os.environ.get("LITELLM_ACCOUNTING_DELIVERY_RETENTION_DAYS", "1"))
cleanup_deadline: Final = time.monotonic() + 5
for _ in range(batch_size):
if (
await repository.cleanup_applied(retention_days=retention_days, batch_size=batch_size * 2)
< batch_size * 2
or time.monotonic() >= cleanup_deadline
):
break
await repository.cleanup_applied(
retention_days=int(os.environ.get("LITELLM_ACCOUNTING_DELIVERY_RETENTION_DAYS", "1")),
batch_size=batch_size * 2,
)
metrics: Final = await repository.metrics()
record_deliveries(metrics, time.monotonic() - started)
if metrics.batch_count >= int(

View file

@ -641,9 +641,11 @@ def extract_file_access_credentials(
"bucket_name",
"s3_endpoint_url",
"s3_region_name",
"s3_bucket_name",
"s3_output_bucket_name",
"allow_legacy_cloud_file_ids",
"timeout",
"max_retries",
"_litellm_internal_model_credentials",
*AWS_CREDENTIAL_KWARGS_KEYS,
# A federated deployment holds no api_key, so without these the fetch that reads a
# finished batch's output has nothing to authenticate with and its cost is never billed.

View file

@ -22,7 +22,6 @@ from openai.types.batch import BatchRequestCounts
import litellm
from litellm._logging import verbose_logger
from litellm.litellm_core_utils.get_litellm_params import add_trusted_model_credentials_to_litellm_params
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.anthropic.batches.handler import AnthropicBatchesHandler
from litellm.llms.azure.batches.handler import AzureBatchesAPI
@ -585,7 +584,6 @@ def retrieve_batch(
custom_llm_provider=custom_llm_provider,
**kwargs,
)
add_trusted_model_credentials_to_litellm_params(litellm_params, kwargs)
if litellm_logging_obj is not None:
litellm_logging_obj.update_from_kwargs(
kwargs=kwargs,

View file

@ -41,12 +41,14 @@ from litellm.litellm_core_utils.allowed_tools_tool_choice import (
)
from litellm.litellm_core_utils.core_helpers import drops_unsupported_params
from litellm.litellm_core_utils.hidden_params import get_hidden_params, get_or_create_hidden_params
from litellm.litellm_core_utils.prompt_templates.common_utils import (
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
prompt_cache_breakpoint_with_readable_mode,
responses_reasoning_items_from_thinking_blocks,
whole_prompt_cache_breakpoint_or_none,
with_prompt_cache_breakpoint,
)
from litellm.litellm_core_utils.prompt_templates.reasoning_utils import (
responses_reasoning_items_from_thinking_blocks,
)
from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
from litellm.llms.base_llm.bridges.completion_transformation import (
CompletionTransformationBridge,

View file

@ -28,7 +28,7 @@ GITHUB_COPILOT_PER_USER_AUTH_TYPE: Final = "per_user_oauth"
GITHUB_COPILOT_AUTH_TYPE_KEY: Final = "github_copilot_auth_type"
GITHUB_COPILOT_HOST_KEY: Final = "github_copilot_host"
GITHUB_COPILOT_DEFAULT_HOST: Final = "github.com"
GITHUB_COPILOT_USER_TOKEN_SAFETY_MARGIN_SECONDS: Final = 60
GITHUB_COPILOT_USER_SESSION_TTL_SECONDS: Final = 1800
GITHUB_COPILOT_USER_CREDENTIAL_CACHE_TTL_SECONDS: Final = 60
GITHUB_COPILOT_DEVICE_FLOW_CACHE_PREFIX: Final = "github_copilot_device_flow"
USER_PROVIDER_CREDENTIAL_CACHE_PREFIX: Final = "user_provider_credential"

View file

@ -38,7 +38,6 @@ import litellm
from litellm import get_secret_str
from litellm.files.streaming import FileContentStreamingResponse
from litellm.files.types import FileContentProvider, FileContentStreamingResult, FileRetrieveProvider
from litellm.litellm_core_utils.get_litellm_params import add_trusted_model_credentials_to_litellm_params
from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.azure.common_utils import get_azure_credentials
@ -422,10 +421,6 @@ def file_retrieve(
)
if provider_config is not None:
litellm_params_dict: Final = get_litellm_params(**kwargs)
add_trusted_model_credentials_to_litellm_params(
litellm_params_dict=litellm_params_dict,
kwargs=kwargs,
)
litellm_params_dict["api_key"] = optional_params.api_key
litellm_params_dict["api_base"] = optional_params.api_base
@ -544,10 +539,6 @@ def file_delete(
pass
optional_params: Final = GenericLiteLLMParams(**kwargs)
litellm_params_dict: Final = get_litellm_params(**kwargs)
add_trusted_model_credentials_to_litellm_params(
litellm_params_dict=litellm_params_dict,
kwargs=kwargs,
)
### TIMEOUT LOGIC ###
timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
# set timeout for 10 minutes by default
@ -737,10 +728,6 @@ def file_list(
)
if provider_config is not None:
litellm_params_dict: Final = get_litellm_params(**kwargs)
add_trusted_model_credentials_to_litellm_params(
litellm_params_dict=litellm_params_dict,
kwargs=kwargs,
)
litellm_params_dict["api_key"] = optional_params.api_key
litellm_params_dict["api_base"] = optional_params.api_base
@ -890,10 +877,6 @@ def file_content(
try:
optional_params: Final = GenericLiteLLMParams(**kwargs)
litellm_params_dict: Final = get_litellm_params(**kwargs)
add_trusted_model_credentials_to_litellm_params(
litellm_params_dict=litellm_params_dict,
kwargs=kwargs,
)
### TIMEOUT LOGIC ###
timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600
client: Final = kwargs.get("client")

View file

@ -26,18 +26,18 @@ from litellm.exceptions import UnsupportedParamsError
from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.custom_prompt_management import CustomPromptManagement
from litellm.integrations.prompt_management_base import PromptManagementClient
from litellm.litellm_core_utils.prompt_templates.common_utils import (
from litellm.litellm_core_utils.prompt_templates.factory import (
tool_call_ids_answered_by_client,
tool_call_ids_answered_in,
)
from litellm.litellm_core_utils.prompt_templates.mid_conversation_system import string_field
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
PROMPT_CACHE_BREAKPOINT_DROP_PARAMS_HINT,
cache_control_as_prompt_cache_breakpoint,
prompt_cache_breakpoint_as_cache_control,
with_prompt_cache_breakpoint,
without_prompt_cache_breakpoints,
)
from litellm.litellm_core_utils.prompt_templates.factory import (
tool_call_ids_answered_by_client,
tool_call_ids_answered_in,
)
from litellm.litellm_core_utils.prompt_templates.mid_conversation_system import string_field
from litellm.llms.anthropic.common_utils import (
is_claude_code_one_shot_subagent_request,
supports_anthropic_cache_control,

View file

@ -898,6 +898,11 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac
def redacts_messages_itself(self) -> bool:
return False
def exempt_from_message_redaction(self) -> bool:
"""Router pre-call checks that key routing off the request and never log it return True, so
`turn_off_message_logging` leaves the success event they receive unredacted."""
return False
def redact_standard_logging_payload_from_model_call_details(self, model_call_details: dict) -> dict:
"""
Redacts or excludes fields from StandardLoggingPayload before callbacks receive it.

View file

@ -71,12 +71,12 @@ if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
_TERMINAL_STATUSES: Final = frozenset(
{"completed", "failed", "cancelled", "incomplete", "budget_exceeded", "requires_action"}
{"completed", "failed", "cancelled", "incomplete", "budget_exceeded", "requires_action", "requires_continuation"}
)
_POLLABLE_STATUSES: Final = frozenset({"in_progress", "queued"})
_STATUSES_THAT_PRODUCED_OUTPUT: Final = frozenset({"completed", "requires_action"})
_STATUSES_THAT_PRODUCED_OUTPUT: Final = frozenset({"completed", "requires_action", "requires_continuation"})
SettlementOutcome: TypeAlias = Literal["billed", "released", "unsettled"]

View file

@ -95,6 +95,7 @@ async def acreate(
response_mime_type: str | None = None,
# Continuation
previous_interaction_id: str | None = None,
continuation_token: str | None = None,
# Extra params
extra_headers: dict[str, str] | None = None,
extra_body: Mapping[str, object] | None = None,
@ -129,6 +130,7 @@ async def acreate(
response_format: JSON schema for response format
response_mime_type: MIME type of the response
previous_interaction_id: ID of previous interaction for continuation
continuation_token: Token from a `requires_continuation` interaction to resume its long decode
extra_headers: Additional headers
extra_body: Additional body parameters
timeout: Request timeout
@ -164,6 +166,7 @@ async def acreate(
response_format=response_format,
response_mime_type=response_mime_type,
previous_interaction_id=previous_interaction_id,
continuation_token=continuation_token,
extra_headers=extra_headers,
extra_body=extra_body,
timeout=timeout,
@ -224,6 +227,7 @@ def create(
response_mime_type: str | None = None,
# Continuation
previous_interaction_id: str | None = None,
continuation_token: str | None = None,
# Extra params
extra_headers: dict[str, str] | None = None,
extra_body: Mapping[str, object] | None = None,
@ -262,6 +266,7 @@ def create(
response_format: JSON schema for response format
response_mime_type: MIME type of the response
previous_interaction_id: ID of previous interaction for continuation
continuation_token: Token from a `requires_continuation` interaction to resume its long decode
extra_headers: Additional headers
extra_body: Additional body parameters
timeout: Request timeout

View file

@ -20,6 +20,7 @@ INTERACTIONS_API_OPTIONAL_PARAMS: Final = {
"response_format",
"response_mime_type",
"previous_interaction_id",
"continuation_token",
"agent_config",
}

View file

@ -2,12 +2,10 @@ import posixpath
import re
from collections.abc import Mapping, Sequence
from itertools import accumulate, repeat
from types import MappingProxyType
from typing import Final
from urllib.parse import quote, unquote
from litellm._uuid import uuid
from litellm.litellm_core_utils.core_helpers import as_str_mapping
VERTEX_AI_MANAGED_GCS_PREFIX: Final = "litellm-vertex-files/"
BEDROCK_MANAGED_S3_BATCH_PREFIX: Final = "litellm-bedrock-files-"
@ -19,7 +17,6 @@ BEDROCK_MANAGED_S3_PREFIXES: Final = (
BEDROCK_MANAGED_S3_OUTPUT_PREFIX,
)
MANAGED_CLOUD_STORAGE_SCHEMES: Final = ("s3://", "gs://")
_MAPPING_PROXY_TYPE: Final[type] = type(MappingProxyType({}))
MAX_FILE_ID_DECODE_PASSES: Final = 8
@ -138,13 +135,7 @@ def encode_s3_object_key_for_url(object_key: str) -> str:
def should_allow_legacy_cloud_file_ids(
litellm_params: Mapping[str, object] | None = None,
) -> bool:
value = None
if isinstance(litellm_params, Mapping):
trusted_model_credentials: Final = litellm_params.get("_litellm_internal_model_credentials")
if isinstance(trusted_model_credentials, _MAPPING_PROXY_TYPE):
trusted_mapping: Final = as_str_mapping(trusted_model_credentials)
value = trusted_mapping.get("allow_legacy_cloud_file_ids") if trusted_mapping is not None else None
value: Final = litellm_params.get("allow_legacy_cloud_file_ids") if litellm_params is not None else None
if isinstance(value, bool):
return value
if isinstance(value, str):

View file

@ -1,7 +1,6 @@
import reprlib
from collections.abc import Mapping, MutableMapping
from collections.abc import Mapping
from dataclasses import dataclass, fields
from types import MappingProxyType
from typing import Final, cast
from pydantic import TypeAdapter, ValidationError
@ -61,6 +60,9 @@ OPTIONAL_KWARGS_KEYS: Final = (
"client_side_timeout",
"gcs_bucket_name",
"bucket_name",
"s3_bucket_name",
"s3_output_bucket_name",
"allow_legacy_cloud_file_ids",
"s3_endpoint_url",
"s3_region_name",
"s3_access_key_id",
@ -292,19 +294,3 @@ def get_litellm_params(
litellm_params[key] = kwargs[key]
return litellm_params
def add_trusted_model_credentials_to_litellm_params(
litellm_params_dict: MutableMapping[str, object], kwargs: Mapping[str, object]
) -> None:
"""
Carry the immutable server-side credential snapshot into litellm_params.
get_litellm_params has a fixed signature, so callers that need the snapshot to
survive into the logging object and the downstream file read have to re-add it. Only
a MappingProxyType is accepted, since providers resolve trusted configuration such
as a Bedrock file bucket from it and must not read a request-supplied mapping.
"""
trusted_model_credentials: Final = kwargs.get("_litellm_internal_model_credentials")
if isinstance(trusted_model_credentials, MappingProxyType):
litellm_params_dict["_litellm_internal_model_credentials"] = trusted_model_credentials

View file

@ -4074,12 +4074,11 @@ class Logging(LiteLLMLoggingBaseClass):
start_time=start_time,
end_time=end_time,
)
if (
callable(callback) is True and is_sync_request and customLogger is not None
): # custom logger functions
if callable(callback) is True and is_sync_request: # custom logger functions
function_logger = customLogger if customLogger is not None else CustomLogger()
print_verbose(f"success callbacks: Running Custom Callback Function - {callback}")
customLogger.log_event(
function_logger.log_event(
kwargs=call_details,
response_obj=result,
start_time=start_time,
@ -4406,7 +4405,11 @@ class Logging(LiteLLMLoggingBaseClass):
if isinstance(callback, CustomLogger): # custom logger class
from litellm.integrations.shadow_eval_logger import ShadowEvalLogger
model_call_details: dict = self.model_call_details
model_call_details: dict = (
self._model_call_details_with_request_messages()
if callback.exempt_from_message_redaction()
else self.model_call_details
)
##################################
# call redaction hook for custom logger
model_call_details = callback.redact_standard_logging_payload_from_model_call_details(
@ -4970,6 +4973,21 @@ class Logging(LiteLLMLoggingBaseClass):
) -> None:
executor.submit(self.success_handler, result, start_time, end_time, cache_hit)
def _model_call_details_with_request_messages(self) -> dict[str, object]: # mutable-ok: loggers take a dict
"""The success-event payload with the request messages put back where `turn_off_message_logging`
redacted them in place, for a callback that routes on the request and never logs it."""
request_messages: Final = cast(object, self.messages) # cast-ok: the request messages are only put back as-is
standard_logging_object: Final = self.model_call_details.get("standard_logging_object")
return {
**self.model_call_details,
"messages": request_messages,
**(
{"standard_logging_object": {**standard_logging_object, "messages": request_messages}}
if isinstance(standard_logging_object, dict)
else {}
),
}
def _get_completed_success_callbacks(
self, *, asynchronous: bool
) -> tuple[str | Callable[..., object] | CustomLogger, ...]:

View file

@ -19,7 +19,7 @@ from litellm.constants import (
VLLM_CHOICE_FIELDS,
)
from litellm.litellm_core_utils.hidden_params import get_hidden_params
from litellm.litellm_core_utils.prompt_templates.common_utils import (
from litellm.litellm_core_utils.prompt_templates.reasoning_utils import (
extract_reasoning_content,
)
from litellm.llms.ollama.common_utils import OllamaResponseIdNormalizer
@ -1072,9 +1072,10 @@ def convert_to_model_response_object(
if isinstance(e, APIError):
raise
hide_reply: Final = response_type == "audio_transcription"
received_args: Final = dict(
response_object=response_object,
model_response_object=model_response_object,
response_object="<hidden>" if hide_reply else response_object,
model_response_object="<hidden>" if hide_reply else model_response_object,
response_type=response_type,
stream=stream,
start_time=start_time,

File diff suppressed because it is too large Load diff

View file

@ -4291,7 +4291,7 @@ def _convert_to_bedrock_tool_call_invoke(
- extract name
- extract id
"""
from litellm.litellm_core_utils.prompt_templates.common_utils import (
from litellm.litellm_core_utils.prompt_templates.tool_call_json_repair import (
split_concatenated_json_objects,
)
@ -5911,7 +5911,7 @@ def _bedrock_tools_pt(
description = name
defs = parameters.pop("$defs", {})
defs_copy = copy.deepcopy(defs) if isinstance(defs, dict) else {}
defs_copy = defs if isinstance(defs, dict) else {}
# Expand $ref references in parameters using the definitions
# Note: We don't pre-flatten defs as that causes exponential memory growth
# with circular references (see issue #19098). unpack_defs handles nested

View file

@ -0,0 +1,635 @@
import io
import mimetypes
import re
from collections.abc import Mapping
from os import PathLike
from pathlib import Path
from typing import Final, cast # noqa: TID251 # Existing casts retained unchanged in this pure move
from litellm import verbose_logger
from litellm.litellm_core_utils.batch_utils import InMemoryFile
from litellm.types.llms.openai import (
AllMessageValues,
ChatCompletionFileObject,
)
from litellm.types.utils import (
ExtractedFileData,
FileTypes,
SpecialEnums,
)
def get_format_from_file_id(file_id: str | None) -> str | None:
"""
Gets format from file id
unified_file_id = litellm_proxy:{};unified_id,{}
If not a unified file id, returns 'file' as default format
"""
from litellm.proxy.openai_files_endpoints.common_utils import (
convert_b64_uid_to_unified_uid,
)
if not file_id:
return None
try:
transformed_file_id: Final = convert_b64_uid_to_unified_uid(file_id)
if transformed_file_id.startswith(SpecialEnums.LITELM_MANAGED_FILE_ID_PREFIX.value):
match: Final = re.match(
f"{SpecialEnums.LITELM_MANAGED_FILE_ID_PREFIX.value}:(.*?);unified_id",
transformed_file_id,
)
if match:
return match.group(1)
return None
except Exception:
return None
def update_messages_with_model_file_ids(
messages: list[AllMessageValues],
model_id: str | None,
model_file_id_mapping: dict[str, dict[str, str]],
) -> list[AllMessageValues]:
"""
Updates messages with model file ids.
For managed files (unified file IDs), uses model_file_id_mapping if it
resolves the id, otherwise decodes the base64-encoded unified file ID
and extracts the llm_output_file_id directly. Mirrors the Responses-API
sibling `update_responses_input_with_model_file_ids`.
model_file_id_mapping: Dict[str, Dict[str, str]] = {
"litellm_proxy/file_id": {
"model_id": "provider_file_id"
}
}
"""
from litellm.proxy.openai_files_endpoints.common_utils import (
convert_b64_uid_to_unified_uid,
get_original_file_id,
is_base64_encoded_unified_file_id,
is_model_embedded_id,
)
for message in messages:
if message.get("role") == "user":
content = message.get("content")
if content:
if isinstance(content, str):
continue
for c in content:
if not isinstance(c, dict):
# Content list items aren't always dicts. e.g.
# text_completion forwards a token-ids list/list-of-
# lists through this path. Skip non-dict items
# instead of indexing into them.
continue
if c.get("type") == "file":
file_object = cast(ChatCompletionFileObject, c)
file_object_file_field = file_object.get("file")
if not isinstance(file_object_file_field, dict):
# Content block has `type: "file"` but not the
# OpenAI Chat Completions shape (e.g. a LangChain
# v1 standardized file block, or a provider-native
# shape that also uses `type: "file"`). Nothing to
# remap here, so skip instead of crashing.
continue
file_id = file_object_file_field.get("file_id")
format = file_object_file_field.get("format", get_format_from_file_id(file_id))
if file_id:
provider_file_id = (
model_file_id_mapping.get(file_id, {}).get(model_id)
if model_file_id_mapping and model_id is not None
else None
)
if not provider_file_id and is_base64_encoded_unified_file_id(file_id):
unified_file_id = convert_b64_uid_to_unified_uid(file_id)
if "llm_output_file_id," in unified_file_id:
provider_file_id = unified_file_id.split("llm_output_file_id,")[1].split(";")[0]
if not provider_file_id and is_model_embedded_id(file_id):
provider_file_id = get_original_file_id(file_id)
file_object_file_field["file_id"] = provider_file_id or file_id
if format:
file_object_file_field["format"] = format
return messages
def update_responses_input_with_model_file_ids(
input: object,
model_id: str | None = None,
model_file_id_mapping: Mapping[str, Mapping[str, str]] | None = None,
) -> object:
"""
Updates responses API input with provider-specific file IDs.
File IDs are always inside the content array, not as direct input_file items.
For managed files (unified file IDs), uses model_file_id_mapping if provided,
otherwise decodes the base64-encoded unified file ID and extracts the llm_output_file_id directly.
Args:
input: The responses API input parameter
model_id: The model ID to use for looking up provider-specific file IDs
model_file_id_mapping: Dictionary mapping litellm file IDs to provider file IDs
Format: {"litellm_file_id": {"model_id": "provider_file_id"}}
"""
from litellm.proxy.openai_files_endpoints.common_utils import (
convert_b64_uid_to_unified_uid,
get_original_file_id,
is_base64_encoded_unified_file_id,
is_model_embedded_id,
)
if isinstance(input, str):
return input
if not isinstance(input, list):
return input
updated_input: Final = []
for item in input:
if not isinstance(item, dict):
updated_input.append(item)
continue
updated_item = item.copy()
content = item.get("content")
if isinstance(content, list):
updated_content = []
for content_item in content:
if isinstance(content_item, dict) and content_item.get("type") == "input_file":
file_id = content_item.get("file_id")
if isinstance(file_id, str) and file_id:
provider_file_id = file_id # Default to original
# Check if we have a mapping for this file ID
if model_file_id_mapping and model_id and file_id in model_file_id_mapping:
# Use the model-specific file ID from mapping
provider_file_id = model_file_id_mapping.get(file_id, {}).get(model_id) or file_id
updated_content_item = content_item.copy()
updated_content_item["file_id"] = provider_file_id
updated_content.append(updated_content_item)
else:
# Check if this is a base64-encoded unified file ID without mapping
is_unified_file_id = is_base64_encoded_unified_file_id(file_id)
if is_unified_file_id:
# Fallback: decode unified file ID
unified_file_id = convert_b64_uid_to_unified_uid(file_id)
if "llm_output_file_id," in unified_file_id:
provider_file_id = unified_file_id.split("llm_output_file_id,")[1].split(";")[0]
updated_content_item = content_item.copy()
updated_content_item["file_id"] = provider_file_id
updated_content.append(updated_content_item)
elif is_model_embedded_id(file_id):
updated_content_item = content_item.copy()
updated_content_item["file_id"] = get_original_file_id(file_id)
updated_content.append(updated_content_item)
else:
# Not a managed file, keep as-is
updated_content.append(content_item)
else:
updated_content.append(content_item)
else:
updated_content.append(content_item)
updated_item["content"] = updated_content
updated_input.append(updated_item)
return updated_input
def _decode_vector_store_ids_in_tools(
tools: list[dict[str, object]] | None,
) -> list[dict[str, object]] | None:
"""
Decodes unified (LiteLLM-managed) vector_store_ids in file_search tools to
provider-native IDs. Non-unified IDs are passed through unchanged.
This runs unconditionally — no file-ID mapping is required.
"""
if not tools or not isinstance(tools, list):
return tools
from litellm.llms.base_llm.managed_resources.utils import (
is_base64_encoded_unified_id,
parse_unified_id,
)
updated_tools: Final = []
for tool in tools:
if not isinstance(tool, dict) or tool.get("type") != "file_search":
updated_tools.append(tool)
continue
vector_store_ids = tool.get("vector_store_ids")
if not isinstance(vector_store_ids, list):
updated_tools.append(tool)
continue
decoded_ids = []
for vs_id in vector_store_ids:
if not isinstance(vs_id, str) or not is_base64_encoded_unified_id(vs_id):
decoded_ids.append(vs_id)
continue
parsed = parse_unified_id(vs_id)
provider_resource_id = parsed.get("provider_resource_id") if parsed else None
if not provider_resource_id:
verbose_logger.warning(
"file_search tool contains unified vector_store_id '%s' that could "
"not be decoded to a provider resource ID — passing original ID. "
"Ensure the vector store was created via LiteLLM.",
vs_id,
)
decoded_ids.append(vs_id)
else:
decoded_ids.append(provider_resource_id)
updated_tools.append({**tool, "vector_store_ids": decoded_ids})
return updated_tools
def update_responses_tools_with_model_file_ids(
tools: list[dict[str, object]] | None,
model_id: str | None = None,
model_file_id_mapping: Mapping[str, Mapping[str, str]] | None = None,
) -> list[dict[str, object]] | None:
"""
Updates responses API tools with provider-specific file IDs.
Pass 1 (always): decode unified vector_store_ids in file_search tools.
Pass 2 (needs mapping): map code_interpreter container file_ids to provider IDs.
Args:
tools: The responses API tools parameter
model_id: The model ID to use for looking up provider-specific file IDs
model_file_id_mapping: Dictionary mapping litellm file IDs to provider file IDs
Format: {"litellm_file_id": {"model_id": "provider_file_id"}}
"""
if not tools or not isinstance(tools, list):
return tools
# Pass 1: decode unified vector_store_ids (no mapping needed)
tools = _decode_vector_store_ids_in_tools(tools) or tools
# Pass 2: map code_interpreter file IDs (requires mapping)
if not model_file_id_mapping or not model_id:
return tools
updated_tools: Final = []
for tool in tools:
if not isinstance(tool, dict):
updated_tools.append(tool)
continue
updated_tool = tool.copy()
# Handle code_interpreter with container file_ids
if tool.get("type") == "code_interpreter":
container = tool.get("container")
if isinstance(container, dict):
container_file_ids = container.get("file_ids")
if isinstance(container_file_ids, list):
updated_file_ids = []
for file_id in container_file_ids:
if isinstance(file_id, str):
# Check if we have a mapping for this file ID
if file_id in model_file_id_mapping:
# Map to provider-specific file ID
provider_file_id = model_file_id_mapping.get(file_id, {}).get(model_id) or file_id
updated_file_ids.append(provider_file_id)
else:
updated_file_ids.append(file_id)
else:
updated_file_ids.append(file_id)
# Update the tool with new file IDs
updated_container = container.copy()
updated_container["file_ids"] = updated_file_ids
updated_tool["container"] = updated_container
updated_tools.append(updated_tool)
return updated_tools
def extract_file_metadata(file_data: FileTypes) -> tuple[str | None, str | None]:
"""
Resolve (filename, content_type) without reading the file body.
Mirrors extract_file_data's metadata resolution but never calls .read(), so
it stays O(1) on large uploads. Use this when only metadata is needed (batch
detection, GCS object naming) and the body must remain a streamable Path/handle.
"""
filename: str | None = None
content_type: str | None = None
file_content: object = None
if isinstance(file_data, tuple):
if len(file_data) == 2:
filename, file_content = file_data
elif len(file_data) == 3:
filename, file_content, content_type = file_data
elif len(file_data) == 4:
filename, file_content, content_type, _ = file_data
elif isinstance(file_data, InMemoryFile):
filename = file_data.name
content_type = file_data.content_type
else:
file_content = file_data
if filename is None:
if isinstance(file_content, PathLike):
filename = Path(file_content).name
elif isinstance(file_content, io.IOBase):
name_attr: Final = getattr(file_content, "name", None)
if isinstance(name_attr, str):
filename = Path(name_attr).name
if not content_type:
guessed: Final = mimetypes.guess_type(filename)[0] if filename else None
content_type = guessed or "application/octet-stream"
return filename, content_type
def extract_file_data(file_data: FileTypes) -> ExtractedFileData:
"""
Extracts and processes file data from various input formats.
Args:
file_data: Can be a tuple of (filename, content, [content_type], [headers]) or direct file content
Returns:
ExtractedFileData containing:
- filename: Name of the file if provided
- content: The file content in bytes
- content_type: MIME type of the file
- headers: Any additional headers
"""
# Parse the file_data based on its type
filename = None
file_content = None
content_type = None
file_headers: Mapping[str, str] = {}
if isinstance(file_data, tuple):
if len(file_data) == 2:
filename, file_content = file_data
elif len(file_data) == 3:
filename, file_content, content_type = file_data
elif len(file_data) == 4:
filename, file_content, content_type, file_headers = file_data
elif isinstance(file_data, InMemoryFile):
filename = file_data.name
file_content = file_data
content_type = file_data.content_type
else:
file_content = file_data
# Convert content to bytes
if isinstance(file_content, str):
# Bare string inputs are rejected: when this helper runs in a proxy
# request handler the string came from an attacker-controlled form
# field, and opening it as a path is an arbitrary file read on the
# proxy host. SDK callers who want to upload from a path should
# either pass a pathlib.Path (a PathLike instance — see the branch
# below) or open the file themselves and pass the handle / bytes.
raise ValueError(
"extract_file_data does not accept bare str inputs. Pass bytes, "
"an open file handle, a (filename, content) tuple, or a "
"pathlib.Path. To upload a local file from a path, call "
"open(path, 'rb') yourself."
)
if isinstance(file_content, PathLike):
# PathLike (pathlib.Path) is a Python-level type that HTTP form
# values can't fabricate. Treat as a local file path for SDK
# convenience.
if filename is None:
filename = Path(file_content).name
with open(file_content, "rb") as f:
content = f.read()
elif isinstance(file_content, io.IOBase):
# If it's a file-like object
# Try to get filename from file handle if not already set
if not filename and hasattr(file_content, "name"):
filename = Path(file_content.name).name
content = file_content.read()
if isinstance(content, str):
content = content.encode("utf-8")
# Reset file pointer to beginning
file_content.seek(0)
elif isinstance(file_content, bytes):
content = file_content
else:
raise ValueError(f"Unsupported file content type: {type(file_content)}")
# Use provided content type or guess based on filename
if not content_type:
if filename:
guessed_type: Final = mimetypes.guess_type(filename)[0]
content_type = guessed_type if guessed_type else "application/octet-stream"
else:
content_type = "application/octet-stream"
return ExtractedFileData(
filename=filename,
content=content,
content_type=content_type,
headers=file_headers,
)
def get_image_mime_type_from_url(url: str) -> str | None:
"""
Get mime type for common image URLs
See gemini mime types: https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/image-understanding#image-requirements
Supported by Gemini:
application/pdf
audio/mpeg
audio/mp3
audio/wav
audio/ogg
image/png
image/jpeg
image/webp
text/plain
video/mov
video/mpeg
video/mp4
video/mpg
video/avi
video/wmv
video/mpegps
video/flv
"""
from urllib.parse import urlparse
url = url.lower()
# Parse URL to extract path without query parameters
# This handles URLs like: https://example.com/image.jpg?signature=...
parsed: Final = urlparse(url)
path: Final = parsed.path
# Map file extensions to mime types
mime_types: Final = {
# Images
(".jpg", ".jpeg"): "image/jpeg",
(".png",): "image/png",
(".webp",): "image/webp",
# Videos
(".mp4",): "video/mp4",
(".mov",): "video/mov",
(".mpeg", ".mpg"): "video/mpeg",
(".avi",): "video/avi",
(".wmv",): "video/wmv",
(".mpegps",): "video/mpegps",
(".flv",): "video/flv",
# Audio
(".mp3",): "audio/mp3",
(".wav",): "audio/wav",
(".mpeg",): "audio/mpeg",
(".ogg",): "audio/ogg",
# Documents
(".pdf",): "application/pdf",
(".txt",): "text/plain",
}
# Check each extension group against the URL
for extensions, mime_type in mime_types.items():
if any(path.endswith(ext) for ext in extensions):
return mime_type
return None
_get_image_mime_type_from_url = get_image_mime_type_from_url
def infer_content_type_from_url_and_content(
url: str,
content: bytes,
current_content_type: str | None = None,
) -> str:
"""
Infer content type from URL extension and binary content when content-type header is missing or generic.
This helper implements a fallback strategy for determining MIME types when HTTP headers
are missing or provide generic values (like binary/octet-stream). It's commonly used
when processing images and documents from various sources (S3, URLs, etc.).
Fallback Strategy:
1. If current_content_type is valid (not None and not generic octet-stream), return it
2. Try to infer from URL extension (handles query parameters)
3. Try to detect from binary content signature (magic bytes)
4. Raise ValueError if all methods fail
Args:
url: The URL of the content (used to extract file extension)
content: The binary content (first ~100 bytes are sufficient for detection)
current_content_type: The current content-type from headers (may be None or generic)
Returns:
str: The inferred MIME type (e.g., "image/png", "application/pdf")
Raises:
ValueError: If content type cannot be determined by any method
Example:
>>> content_type = infer_content_type_from_url_and_content(
... url="https://s3.amazonaws.com/bucket/image.png?AWSAccessKeyId=123",
... content=png_binary_data,
... current_content_type="binary/octet-stream"
... )
>>> print(content_type)
"image/png"
"""
from litellm.litellm_core_utils.token_counter import get_image_type
media_type: Final = current_content_type.split(";", 1)[0].strip().lower() if current_content_type else None
# If we have a valid content type that's not generic, use it
if media_type and media_type not in [
"binary/octet-stream",
"application/octet-stream",
]:
return media_type
# Extension to MIME type mapping
# Supports images, documents, and other common file types
extension_to_mime: Final = {
# Image formats
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"webp": "image/webp",
# Document formats
"pdf": "application/pdf",
"csv": "text/csv",
"doc": "application/msword",
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xls": "application/vnd.ms-excel",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"html": "text/html",
"txt": "text/plain",
"md": "text/markdown",
}
# Try to infer from URL extension
if url:
extension: Final = url.split(".")[-1].lower().split("?")[0] # Remove query params
inferred_type: Final = extension_to_mime.get(extension)
if inferred_type:
return inferred_type
# Try to detect from binary content signature (magic bytes)
if content:
detected_type: Final = get_image_type(content[:100])
if detected_type:
type_to_mime: Final = {
"png": "image/png",
"jpeg": "image/jpeg",
"gif": "image/gif",
"webp": "image/webp",
"heic": "image/heic",
}
if detected_type in type_to_mime:
return type_to_mime[detected_type]
# If all fallbacks failed, raise error
raise ValueError(f"Unable to determine content type from URL: {url}. Response content-type: {current_content_type}")
def get_file_ids_from_messages(messages: list[AllMessageValues]) -> list[str]:
"""
Gets file ids from messages
"""
file_ids: Final = []
for message in messages:
if message.get("role") == "user":
content = message.get("content")
if content:
if isinstance(content, str):
continue
for c in content:
if isinstance(c, dict) and c["type"] == "file":
file_object = cast(ChatCompletionFileObject, c)
file_object_file_field = file_object.get("file")
if not isinstance(file_object_file_field, dict):
# Content block has `type: "file"` but not the
# OpenAI Chat Completions shape. No file_id to
# extract, so skip instead of raising KeyError.
continue
file_id = file_object_file_field.get("file_id")
if file_id:
file_ids.append(file_id)
return file_ids

View file

@ -21,7 +21,9 @@ import litellm
from litellm import verbose_logger
from litellm.caching.caching import InMemoryCache
from litellm.constants import MAX_IMAGE_URL_DOWNLOAD_SIZE_MB, NON_LLM_CONNECTION_TIMEOUT
from litellm.litellm_core_utils.prompt_templates.common_utils import infer_content_type_from_url_and_content
from litellm.litellm_core_utils.prompt_templates.file_id_utils import (
infer_content_type_from_url_and_content,
)
from litellm.litellm_core_utils.url_utils import SSRFError, async_safe_get, safe_get
from litellm.types.llms.openai import AllMessageValues

View file

@ -0,0 +1,471 @@
import re
from collections.abc import Callable, Iterator, Mapping
from graphlib import CycleError, TopologicalSorter
from itertools import chain, islice
from types import MappingProxyType
from typing import Final
from pydantic import TypeAdapter
_TOP_LEVEL_SCHEMA_COMBINATORS: Final = ("allOf", "anyOf", "oneOf")
_OPENAI_REJECTED_TOP_LEVEL_SCHEMA_KEYS: Final = ("enum", "const", "not")
_LOCAL_SCHEMA_REF_PREFIXES: Final = (("#/$defs/", "$defs"), ("#/definitions/", "definitions"))
_MAX_SCHEMA_FLATTEN_DEPTH: Final = 32
_EMPTY_SCHEMA: Final[Mapping[str, object]] = MappingProxyType({})
def _schema_properties(schema: Mapping[str, object]) -> Mapping[str, object]:
properties: Final = schema.get("properties")
return properties if isinstance(properties, dict) else _EMPTY_SCHEMA
def _schema_branches(schema: Mapping[str, object], combinator: str) -> tuple[object, ...]:
branches: Final = schema.get(combinator)
return tuple(branches) if isinstance(branches, list) else ()
def _schema_required_names(schema: Mapping[str, object]) -> frozenset[str]:
required: Final = schema.get("required")
if not isinstance(required, list):
return frozenset()
return frozenset(name for name in required if isinstance(name, str))
def _combinator_required_names(combinator: str, branches: tuple[Mapping[str, object], ...]) -> frozenset[str]:
branch_names: Final = tuple(_schema_required_names(branch) for branch in branches)
if not branch_names:
return frozenset()
if combinator == "allOf":
return branch_names[0].union(*branch_names[1:])
return branch_names[0].intersection(*branch_names[1:])
def _resolve_local_schema_ref(root: Mapping[str, object], ref: str) -> Mapping[str, object] | None:
matched: Final = next(
((prefix, container) for prefix, container in _LOCAL_SCHEMA_REF_PREFIXES if ref.startswith(prefix)),
None,
)
if matched is None:
return None
prefix, container = matched
definitions: Final = root.get(container)
if not isinstance(definitions, dict):
return None
target: Final = definitions.get(ref[len(prefix) :])
return target if isinstance(target, dict) else None
def _mergeable_branch(
root: Mapping[str, object],
branch: object,
seen_refs: frozenset[str],
depth: int,
expanded_refs: dict[str, Mapping[str, object] | None], # mutable-ok: per-call memo bounding repeated $ref work
) -> Mapping[str, object] | None:
if not isinstance(branch, dict) or depth > _MAX_SCHEMA_FLATTEN_DEPTH:
return None
ref: Final = branch.get("$ref")
if not isinstance(ref, str):
flattened: Final = _flatten_schema_against_root(branch, root, seen_refs, depth, expanded_refs)
if any(combinator in flattened for combinator in _TOP_LEVEL_SCHEMA_COMBINATORS):
return None
return flattened
if ref in expanded_refs:
return expanded_refs[ref]
if ref in seen_refs:
return None
target: Final = _resolve_local_schema_ref(root, ref)
expanded: Final = (
None
if target is None
else _mergeable_branch(root, target, seen_refs | frozenset((ref,)), depth + 1, expanded_refs)
)
expanded_refs[ref] = expanded
return expanded
def _is_object_schema(schema: Mapping[str, object]) -> bool:
return schema.get("type") == "object" or ("type" not in schema and "properties" in schema)
def _flatten_schema_against_root(
schema: Mapping[str, object],
root: Mapping[str, object],
seen_refs: frozenset[str],
depth: int,
expanded_refs: dict[str, Mapping[str, object] | None], # mutable-ok: per-call memo bounding repeated $ref work
) -> Mapping[str, object]:
raw_branch_groups: Final = tuple(
(
combinator,
tuple(
_mergeable_branch(root, branch, seen_refs, depth + 1, expanded_refs)
for branch in _schema_branches(schema, combinator)
),
)
for combinator in _TOP_LEVEL_SCHEMA_COMBINATORS
if isinstance(schema.get(combinator), list)
)
dropped: Final = (
*(combinator for combinator, _ in raw_branch_groups),
*(key for key in _OPENAI_REJECTED_TOP_LEVEL_SCHEMA_KEYS if key in schema),
)
if not dropped:
return schema
if any(branch is None for _, group in raw_branch_groups for branch in group):
return schema
branch_groups: Final = tuple(
(combinator, tuple(branch for branch in group if branch is not None)) for combinator, group in raw_branch_groups
)
branches: Final = tuple(branch for _, group in branch_groups for branch in group)
is_object_schema: Final = _is_object_schema(schema) or (
"type" not in schema and branches != () and all(_is_object_schema(branch) for branch in branches)
)
if not is_object_schema:
return schema
merged_properties: Final = {
name: value for source in (*reversed(branches), schema) for name, value in _schema_properties(source).items()
}
required_names: Final = _schema_required_names(schema).union(
*(_combinator_required_names(combinator, group) for combinator, group in branch_groups)
)
kept: Final = MappingProxyType({key: value for key, value in schema.items() if key not in dropped})
required_update: Final = MappingProxyType({"required": sorted(required_names)}) if required_names else _EMPTY_SCHEMA
return {
**kept,
"type": "object",
"properties": merged_properties,
**required_update,
}
def flatten_top_level_schema_combinators(schema: Mapping[str, object]) -> Mapping[str, object]:
"""Merge top-level ``allOf``/``anyOf``/``oneOf`` branches into an object tool schema.
OpenAI's function-calling validator rejects tool ``parameters`` carrying
'oneOf'/'anyOf'/'allOf'/'enum'/'const'/'not' at the top level (nested uses
are accepted), while lenient backends such as the ChatGPT backend Codex
talks to natively accept them, so an MCP tool declaring a top-level union
400s through LiteLLM. Branch properties merge without clobbering (the
top-level schema wins, then earlier branches); ``required`` becomes the
top-level list plus the intersection of the branch lists for anyOf/oneOf
or their union for allOf. Branches that are local ``$ref``s
(``#/$defs/...`` or ``#/definitions/...``) are resolved first, each ref
at most once per call, and branches that are themselves combinators are
flattened recursively up to a fixed depth; a branch that cannot be fully
merged (a boolean schema, an external or cyclic ``$ref``, a non-object
union, or nesting past the depth cap) leaves the whole schema untouched so
OpenAI's own validation still applies. Non-object schemas pass through
unchanged and the input is never mutated.
"""
return _flatten_schema_against_root(schema, schema, frozenset(), 0, {})
_SUBSCHEMA_KEYWORDS: Final = frozenset(
{
"additionalItems",
"additionalProperties",
"contains",
"else",
"if",
"items",
"not",
"propertyNames",
"then",
"unevaluatedItems",
"unevaluatedProperties",
}
)
_SUBSCHEMA_LIST_KEYWORDS: Final = frozenset({"allOf", "anyOf", "items", "oneOf", "prefixItems"})
_SUBSCHEMA_MAP_KEYWORDS: Final = frozenset(
{"$defs", "definitions", "dependentSchemas", "patternProperties", "properties"}
)
_MAX_SCHEMA_NESTING: Final = 1024
def drop_non_python_regex_patterns(schema: Mapping[str, object]) -> Mapping[str, object]:
"""Drop every regex in a schema position that Python's ``re`` cannot compile.
OpenAI validates tool ``parameters`` against the 2020-12 metaschema with
``jsonschema``'s format checker, which hands each ``pattern`` value and each
``patternProperties`` key to ``re.compile``, so a regex written for an
ECMA-262 engine (Unicode property escapes such as ``\\p{Cc}``, as in Claude
Code's ``Artifact`` tool) is refused with "'...' is not a 'regex'" by every
model family on both the chat and Responses wires. Only schema positions are
walked (properties, items, combinators, ``$defs`` and the other applicators),
so a ``pattern`` key inside ``default``, ``examples``, ``const`` or vendor
extensions is data and stays. Outside strict mode the keyword is only a
hint, so dropping it costs the model a constraint and the caller nothing.
Compilable regexes and everything else pass through, the input is never
mutated, and the same object comes back when nothing was dropped. The walk
is level-order rather than recursive, rebuilt deepest level first, and stops
at more schema levels than a JSON parser admits, so a cyclic schema built in
code cannot spin it.
"""
return _schema_without_rejected_regex(schema, _is_not_python_regex)
def drop_lookaround_regex_patterns(schema: Mapping[str, object]) -> Mapping[str, object]:
"""Drop every regex in a schema position that uses a lookaround assertion.
Some Bedrock Converse families compile tool schema regexes with an engine that
has no lookahead or lookbehind and refuse the whole request over one. The ``(?=``,
``(?!``, ``(?<=`` and ``(?<!`` openers are matched textually, so an escaped literal
that spells one is dropped too, trading a hint for a request that goes through.
A ``patternProperties`` key dropped from an object closed by ``additionalProperties:
false`` leaves its value schema as that object's ``additionalProperties``, so the
names it allowed stay allowed; :func:`drop_non_python_regex_patterns` shares the walk.
"""
return _schema_without_rejected_regex(schema, _uses_regex_lookaround)
def _schema_without_rejected_regex(
schema: Mapping[str, object], rejected: Callable[[str], bool]
) -> Mapping[str, object]:
rebuilt: dict[int, Mapping[str, object]] = {} # mutable-ok: per-call memo of rewritten nodes, deepest level first
for level in reversed(tuple(islice(_schema_levels(schema), _MAX_SCHEMA_NESTING))):
rebuilt.update(
(id(node), rewritten)
for node in level
if (rewritten := _node_without_rejected_regex(node, rebuilt, rejected)) is not node
)
return rebuilt.get(id(schema), schema)
def _schema_levels(schema: Mapping[str, object]) -> Iterator[tuple[Mapping[str, object], ...]]:
frontier: tuple[Mapping[str, object], ...] = (schema,) # rebind-ok: level-order cursor, one level a round
while frontier:
yield frontier
frontier = tuple(child for node in frontier for child in _subschemas(node))
def schema_fragment_ref(ref: str) -> str:
return f"#{ref}" if ref.startswith(("/$defs/", "/definitions/")) else ref
def schema_has_unresolvable_ref(schema: Mapping[str, object]) -> bool:
definitions: Final = MappingProxyType(dict(_root_definitions(schema)))
if not _refs_in(schema) <= definitions.keys():
return True
try:
tuple(TopologicalSorter({pointer: _refs_in(body) for pointer, body in definitions.items()}).static_order())
except CycleError:
return True
return False
def schema_union_property_count(schema: Mapping[str, object]) -> int:
return sum(1 for _, node in _property_schemas(schema) if _is_union(node))
def schema_optional_property_count(schema: Mapping[str, object]) -> int:
return sum(len(_optional_property_names(node)) for node in _schema_nodes(schema))
def schema_property_count(schema: Mapping[str, object]) -> int:
return sum(len(properties) for node in _schema_nodes(schema) if (properties := _schema_at(node, "properties")))
def schema_grammar_branch_count(schema: Mapping[str, object]) -> int:
return sum(_grammar_branches(node) for node in _schema_nodes(schema))
def schema_has_open_object(schema: Mapping[str, object]) -> bool:
return any(_is_open_object(node) for node in _schema_nodes(schema))
def schema_has_lookaround_pattern(schema: Mapping[str, object]) -> bool:
return any(
isinstance(pattern := node.get("pattern"), str) and _uses_regex_lookaround(pattern)
for node in _schema_nodes(schema)
)
def schema_string_formats(schema: Mapping[str, object]) -> frozenset[str]:
return frozenset(
value for node in _schema_nodes(schema) if _may_be_string(node) and isinstance(value := node.get("format"), str)
)
def _may_be_string(node: Mapping[str, object]) -> bool:
node_type: Final = node.get("type")
return node_type is None or node_type == "string" or "string" in _list_at(node, "type")
def is_object_schema(node: Mapping[str, object]) -> bool:
node_type: Final = node.get("type")
return node_type == "object" or (isinstance(node_type, list) and "object" in node_type)
def _schema_nodes(schema: Mapping[str, object]) -> Iterator[Mapping[str, object]]:
return chain.from_iterable(islice(_schema_levels(schema), _MAX_SCHEMA_NESTING))
_SCHEMA_LIST: Final = TypeAdapter(tuple[object, ...])
def _list_at(container: Mapping[str, object], key: str) -> tuple[object, ...]:
value: Final = container.get(key)
return _SCHEMA_LIST.validate_python(value) if isinstance(value, list) else ()
def _named_schemas(container: Mapping[str, object] | None) -> Iterator[tuple[str, Mapping[str, object]]]:
if container is None:
return iter(())
return ((key, value) for key in container if (value := _schema_at(container, key)) is not None)
def _root_definitions(schema: Mapping[str, object]) -> Iterator[tuple[str, Mapping[str, object]]]:
for defs_key in ("$defs", "definitions"):
yield from ((f"#/{defs_key}/{name}", body) for name, body in _named_schemas(_schema_at(schema, defs_key)))
def _refs_in(schema: Mapping[str, object]) -> frozenset[str]:
return frozenset(
schema_fragment_ref(ref) for node in _schema_nodes(schema) if isinstance(ref := node.get("$ref"), str)
)
def _property_schemas(schema: Mapping[str, object]) -> Iterator[tuple[str, Mapping[str, object]]]:
return chain.from_iterable(_named_schemas(_schema_at(node, "properties")) for node in _schema_nodes(schema))
def _is_union(node: Mapping[str, object]) -> bool:
return isinstance(node.get("anyOf"), list) or isinstance(node.get("oneOf"), list) or len(_list_at(node, "type")) > 1
def _grammar_branches(node: Mapping[str, object]) -> int:
properties: Final = _schema_at(node, "properties")
if properties is None:
return 0
optional: Final = len(_optional_property_names(node))
return (1 << optional) * (len(properties) - optional + 1)
def _optional_property_names(node: Mapping[str, object]) -> frozenset[str]:
properties: Final = _schema_at(node, "properties")
if properties is None:
return frozenset()
return frozenset(properties) - frozenset(name for name in _list_at(node, "required") if isinstance(name, str))
def _is_open_object(node: Mapping[str, object]) -> bool:
additional_properties: Final = node.get("additionalProperties")
if additional_properties is True or isinstance(additional_properties, dict) or "patternProperties" in node:
return True
return is_object_schema(node) and "properties" not in node and additional_properties is not False
def _subschemas(node: Mapping[str, object]) -> Iterator[Mapping[str, object]]:
for key, value in node.items():
if key in _SUBSCHEMA_MAP_KEYWORDS and isinstance(value, dict):
yield from (sub for sub in value.values() if isinstance(sub, dict))
elif key in _SUBSCHEMA_LIST_KEYWORDS and isinstance(value, list):
yield from (sub for sub in value if isinstance(sub, dict))
elif key in _SUBSCHEMA_KEYWORDS and isinstance(value, dict):
yield value
def _node_without_rejected_regex(
node: Mapping[str, object],
rebuilt: Mapping[int, Mapping[str, object]],
rejected: Callable[[str], bool],
) -> Mapping[str, object]:
kept: Final = {
key: _keyword_value_rebuilt(key, value, rebuilt, rejected)
for key, value in node.items()
if key != "pattern" or not isinstance(value, str) or not rejected(value)
}
if len(kept) == len(node) and all(kept[key] is node[key] for key in kept):
return node
dropped_pattern_properties: Final = _dropped_pattern_properties(node, kept, rebuilt)
if not dropped_pattern_properties or kept.get("additionalProperties") is not False:
return kept
return {**kept, "additionalProperties": _any_of(dropped_pattern_properties)}
def _dropped_pattern_properties(
node: Mapping[str, object],
kept: Mapping[str, object],
rebuilt: Mapping[int, Mapping[str, object]],
) -> tuple[object, ...]:
before: Final = _schema_at(node, "patternProperties")
after: Final = _schema_at(kept, "patternProperties")
if before is None or after is None:
return ()
return tuple(rebuilt.get(id(sub), sub) for name, sub in before.items() if name not in after)
def _schema_at(container: Mapping[str, object], key: str) -> Mapping[str, object] | None:
value: Final = container.get(key)
return value if isinstance(value, dict) else None
def _any_of(schemas: tuple[object, ...]) -> object:
return schemas[0] if len(schemas) == 1 else {"anyOf": list(schemas)}
def _keyword_value_rebuilt(
key: str,
value: object,
rebuilt: Mapping[int, Mapping[str, object]],
rejected: Callable[[str], bool],
) -> object:
if key in _SUBSCHEMA_MAP_KEYWORDS and isinstance(value, dict):
kept: Final = {
name: rebuilt.get(id(sub), sub)
for name, sub in value.items()
if key != "patternProperties" or not isinstance(name, str) or not rejected(name)
}
return value if len(kept) == len(value) and all(kept[name] is value[name] for name in kept) else kept
if key in _SUBSCHEMA_LIST_KEYWORDS and isinstance(value, list):
items: Final = [rebuilt.get(id(sub), sub) for sub in value]
return value if all(new is old for new, old in zip(items, value, strict=True)) else items
if key in _SUBSCHEMA_KEYWORDS and isinstance(value, dict):
return rebuilt.get(id(value), value)
return value
def _is_not_python_regex(pattern: str) -> bool:
try:
re.compile(pattern)
except (re.error, RecursionError):
return True
return False
_REGEX_LOOKAROUND_RE: Final = re.compile(r"\(\?<?[=!]")
def _uses_regex_lookaround(pattern: str) -> bool:
return _REGEX_LOOKAROUND_RE.search(pattern) is not None
def flatten_combinators_and_drop_non_python_regex_patterns(schema: Mapping[str, object]) -> Mapping[str, object]:
return flatten_top_level_schema_combinators(drop_non_python_regex_patterns(schema))
def tool_with_sanitized_parameters(
tool: Mapping[str, object],
sanitize: Callable[[Mapping[str, object]], Mapping[str, object]],
) -> Mapping[str, object]:
"""Run the tool's JSON schema through ``sanitize``: ``function.parameters`` on an
OpenAI tool, ``input_schema`` on an Anthropic one. The same object comes back when
nothing changed."""
function: Final = _schema_at(tool, "function")
if function is not None:
parameters: Final = _schema_at(function, "parameters")
if parameters is None:
return tool
sanitized_parameters: Final = sanitize(parameters)
if sanitized_parameters is parameters:
return tool
return {**tool, "function": {**function, "parameters": sanitized_parameters}}
input_schema: Final = _schema_at(tool, "input_schema")
if input_schema is None:
return tool
sanitized_schema: Final = sanitize(input_schema)
return tool if sanitized_schema is input_schema else {**tool, "input_schema": sanitized_schema}

View file

@ -0,0 +1,212 @@
from collections.abc import Mapping
from typing import Final, TypeVar, cast # noqa: TID251 # Existing casts retained unchanged in this pure move
from pydantic import TypeAdapter, ValidationError
from litellm import verbose_logger
from litellm.exceptions import UnsupportedParamsError
from litellm.types.llms.openai import (
ChatCompletionCachedContent,
ChatCompletionPromptCacheBreakpoint,
PromptCacheBreakpoint,
)
_MarkedT: Final = TypeVar("_MarkedT", bound=Mapping[str, object])
PROMPT_CACHE_BREAKPOINT_DROP_PARAMS_HINT: Final = (
"set `drop_params: true` on the request or in litellm_settings (`litellm.drop_params = True` in the SDK)"
)
def with_prompt_cache_breakpoint(target: _MarkedT, marker: object) -> _MarkedT:
"""A breakpoint the client already wrote on the block wins, TTL included."""
if marker is None or target.get("prompt_cache_breakpoint") is not None:
return target
marked: Final = {**target, "prompt_cache_breakpoint": marker}
return cast(_MarkedT, marked) # cast-ok: same block shape as the input plus the marker key
_PROMPT_CACHE_BREAKPOINT: Final = TypeAdapter(PromptCacheBreakpoint)
_CHAT_COMPLETION_PROMPT_CACHE_BREAKPOINT: Final = TypeAdapter(ChatCompletionPromptCacheBreakpoint)
_AcceptedBreakpointT: Final = TypeVar("_AcceptedBreakpointT", bound=Mapping[str, object])
def _accepted_prompt_cache_breakpoint(
accepted: TypeAdapter[_AcceptedBreakpointT], marker: object
) -> _AcceptedBreakpointT | None:
try:
return accepted.validate_python(marker)
except ValidationError:
return None
def prompt_cache_breakpoint_within(
accepted: TypeAdapter[_AcceptedBreakpointT], marker: object
) -> _AcceptedBreakpointT | None:
"""The client's marker cut down to the ``accepted`` shape: an unsupported ttl is dropped and the mode kept,
and a marker whose mode the target cannot read is dropped whole."""
whole: Final = _accepted_prompt_cache_breakpoint(accepted, marker)
if whole is not None:
return whole
fields: Final = _breakpoint_fields_or_none(marker)
without_ttl: Final = (
None
if fields is None
else _accepted_prompt_cache_breakpoint(accepted, {key: item for key, item in fields.items() if key != "ttl"})
)
verbose_logger.debug(
"Dropping malformed prompt_cache_breakpoint %r under drop_params"
if without_ttl is None
else "Dropping the unsupported ttl of prompt_cache_breakpoint %r under drop_params",
marker,
)
return without_ttl
def prompt_cache_breakpoint_for_wire(marker: object, drop_params: bool) -> object:
if marker is None or not drop_params:
return marker
return prompt_cache_breakpoint_within(_PROMPT_CACHE_BREAKPOINT, marker)
def prompt_cache_breakpoint_with_readable_mode(marker: object, drop_params: bool) -> object:
"""The client's marker as written, or None under drop_params when no target could read its mode, so the
target's own config decides which ttl and keys it keeps."""
return None if prompt_cache_breakpoint_for_wire(marker, drop_params) is None else marker
def whole_prompt_cache_breakpoint_or_none(marker: object) -> PromptCacheBreakpoint | None:
return _accepted_prompt_cache_breakpoint(_PROMPT_CACHE_BREAKPOINT, marker)
def chat_completion_prompt_cache_breakpoint_for_wire(marker: object, drop_params: bool) -> object:
if marker is None or not drop_params:
return marker
return prompt_cache_breakpoint_within(_CHAT_COMPLETION_PROMPT_CACHE_BREAKPOINT, marker)
def cache_control_as_prompt_cache_breakpoint(block: _MarkedT) -> _MarkedT:
"""Anthropic's ``cache_control`` mark rewritten as OpenAI's ``prompt_cache_breakpoint`` on the same block."""
if block.get("cache_control") is None:
return block
unmarked: Final = {key: value for key, value in block.items() if key != "cache_control"}
return cast( # cast-ok: same block shape as the input with the marker key renamed
_MarkedT, with_prompt_cache_breakpoint(unmarked, PromptCacheBreakpoint(mode="explicit"))
)
def prompt_cache_breakpoint_as_cache_control(block: _MarkedT, drop_params: bool) -> _MarkedT:
"""OpenAI's ``prompt_cache_breakpoint`` mark rewritten as Anthropic's ``cache_control`` on the same block.
A ``cache_control`` the client already wrote on the block wins, TTL included."""
marker: Final = block.get("prompt_cache_breakpoint")
if marker is None:
return block
unmarked: Final = {key: value for key, value in block.items() if key != "prompt_cache_breakpoint"}
control: Final = (
None
if block.get("cache_control") is not None
else _cache_control_for_prompt_cache_breakpoint(marker, drop_params)
)
marked: Final = unmarked if control is None else {**unmarked, "cache_control": control}
return cast(_MarkedT, marked) # cast-ok: same block shape as the input with the marker key renamed
def _cache_control_for_prompt_cache_breakpoint(marker: object, drop_params: bool) -> ChatCompletionCachedContent | None:
try:
breakpoint_mark: Final = _PROMPT_CACHE_BREAKPOINT.validate_python(marker)
except ValidationError:
if not drop_params:
raise UnsupportedParamsError(
message=(
f"prompt_cache_breakpoint must be {{'mode': 'explicit'}} with an optional ttl of '30m' or '12h', got "
f"{marker!r}. Fix the marker, or "
f"{PROMPT_CACHE_BREAKPOINT_DROP_PARAMS_HINT} to drop it."
),
status_code=400,
)
verbose_logger.debug("Dropping malformed prompt_cache_breakpoint %r under drop_params", marker)
return None
ttl: Final = breakpoint_mark.get("ttl")
if ttl is not None and not drop_params:
raise UnsupportedParamsError(
message=(
f"This model's prompt cache lasts 5m, or 1h where it offers one, so prompt_cache_breakpoint "
f"ttl={ttl!r} has no equivalent. Remove the ttl, {PROMPT_CACHE_BREAKPOINT_DROP_PARAMS_HINT} to send "
"a 5m breakpoint instead, or send cache_control {'type': 'ephemeral', 'ttl': '1h'} on the block "
"where the model offers a 1h cache."
),
status_code=400,
)
return ChatCompletionCachedContent(type="ephemeral")
_BREAKPOINT_BLOCK_LIST_KEYS: Final = frozenset({"content", "tool_calls"})
_BREAKPOINT_FIELDS: Final = TypeAdapter(Mapping[str, object])
_BREAKPOINT_BLOCKS: Final = TypeAdapter(list[object])
def _breakpoint_fields_or_none(value: object) -> Mapping[str, object] | None:
try:
return _BREAKPOINT_FIELDS.validate_python(value)
except ValidationError:
return None
def _without_prompt_cache_breakpoint(value: object) -> object:
if not isinstance(value, Mapping):
return value
fields: Final = _BREAKPOINT_FIELDS.validate_python(value)
return {key: item for key, item in fields.items() if key != "prompt_cache_breakpoint"}
def _breakpoints_stripped_from(key: str, value: object) -> object:
if key in _BREAKPOINT_BLOCK_LIST_KEYS and isinstance(value, list):
return [_without_prompt_cache_breakpoint(block) for block in _BREAKPOINT_BLOCKS.validate_python(value)]
return _without_prompt_cache_breakpoint(value) if key == "function" else value
def without_prompt_cache_breakpoints(block: _MarkedT) -> _MarkedT:
"""A message or tool definition with every ``prompt_cache_breakpoint`` removed: its own, its content parts',
its tool calls' and its ``function``'s."""
stripped: Final = {
key: _breakpoints_stripped_from(key, value) for key, value in block.items() if key != "prompt_cache_breakpoint"
}
return cast(_MarkedT, stripped) # cast-ok: same block shape as the input minus the marker keys
def _part_with_chat_completion_prompt_cache_breakpoint(part: object) -> object:
if not isinstance(part, Mapping):
return part
fields: Final = _BREAKPOINT_FIELDS.validate_python(part)
marker: Final = fields.get("prompt_cache_breakpoint")
if marker is None:
return fields
unmarked: Final = {key: item for key, item in fields.items() if key != "prompt_cache_breakpoint"}
return with_prompt_cache_breakpoint(unmarked, chat_completion_prompt_cache_breakpoint_for_wire(marker, True))
def chat_completion_prompt_cache_breakpoints_for_wire(message: _MarkedT, drop_params: bool) -> _MarkedT:
content: Final = message.get("content")
if not drop_params or not isinstance(content, list):
return message
parts: Final = [
_part_with_chat_completion_prompt_cache_breakpoint(part) for part in _BREAKPOINT_BLOCKS.validate_python(content)
]
return cast(_MarkedT, {**message, "content": parts}) # cast-ok: same message shape with its parts' markers trimmed
LITELLM_RESPONSE_ONLY_MESSAGE_FIELDS: Final = frozenset(
{"thinking_blocks", "reasoning_items", "provider_specific_fields"}
)
LITELLM_INTERNAL_MESSAGE_FIELDS: Final = LITELLM_RESPONSE_ONLY_MESSAGE_FIELDS | {"reasoning_content"}

View file

@ -0,0 +1,274 @@
import base64
import binascii
import re
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from itertools import groupby
from typing import Final, cast # noqa: TID251 # Existing casts retained unchanged in this pure move
from litellm.types.llms.openai import (
ChatCompletionReasoningItem,
ChatCompletionReasoningSummaryTextBlock,
ChatCompletionRedactedThinkingBlock,
ChatCompletionThinkingBlock,
)
def _provider_text_or_none(value: object) -> str | None:
return cast(str | None, value) # cast-ok: reasoning fields arrive in untyped provider messages
def extract_reasoning_content(message: Mapping[str, object]) -> tuple[str | None, str | None]:
"""
Extract reasoning content and main content from a message.
Args:
message (dict): The message dictionary that may contain reasoning_content
Returns:
tuple[Optional[str], Optional[str]]: A tuple of (reasoning_content, content)
"""
message_content: Final = message.get("content")
if "reasoning_content" in message:
return _provider_text_or_none(message["reasoning_content"]), _provider_text_or_none(message_content)
elif "reasoning" in message:
return _provider_text_or_none(message["reasoning"]), _provider_text_or_none(message_content)
elif isinstance(message_content, str):
return parse_content_for_reasoning(message_content)
return None, _provider_text_or_none(message_content)
_extract_reasoning_content = extract_reasoning_content
def _readable_thinking_text(block: Mapping[str, object]) -> str:
"""The text a chat model can read back, empty for redacted blocks and malformed ones."""
if block.get("type") != "thinking":
return ""
return str(block.get("thinking") or "")
def reasoning_content_from_thinking_blocks(
thinking_blocks: Iterable[ChatCompletionThinkingBlock | ChatCompletionRedactedThinkingBlock],
) -> str:
"""Flatten Anthropic thinking blocks into the `reasoning_content` string chat models expect.
Redacted blocks carry no readable text, so they contribute nothing.
"""
return "\n".join(text for block in thinking_blocks if (text := _readable_thinking_text(block)))
ENCRYPTED_REASONING_SIGNATURE_PREFIX: Final = "litellm_encrypted_reasoning:"
def encrypted_reasoning_signature(encrypted_content: str) -> str:
"""The opaque value a Responses API reasoning item's `encrypted_content` travels in.
Anthropic clients echo a thinking block's `signature` and a redacted block's `data`
back verbatim, so either field can carry the encrypted reasoning across turns; the
prefix tells the two apart from a signature Anthropic minted.
"""
return f"{ENCRYPTED_REASONING_SIGNATURE_PREFIX}{encrypted_content}"
def _carries_encrypted_reasoning(signature: object) -> bool:
return isinstance(signature, str) and signature.startswith(ENCRYPTED_REASONING_SIGNATURE_PREFIX)
def encrypted_content_from_signature(signature: object) -> str | None:
if not isinstance(signature, str) or not _carries_encrypted_reasoning(signature):
return None
return signature.removeprefix(ENCRYPTED_REASONING_SIGNATURE_PREFIX) or None
def _encrypted_reasoning_field(block: Mapping[str, object]) -> object:
match block.get("type"):
case "thinking":
return block.get("signature")
case "redacted_thinking":
return block.get("data")
case _:
return None
def encrypted_content_of_block(block: Mapping[str, object]) -> str | None:
return encrypted_content_from_signature(_encrypted_reasoning_field(block))
def is_encrypted_reasoning_block(block: object) -> bool:
"""A thinking or redacted_thinking block carrying Responses API encrypted reasoning.
Only the Responses API that minted the content can read it back, so an Anthropic
backend has to drop such a block rather than fail signature verification on it.
"""
if not isinstance(block, Mapping):
return False
mapping: Final = cast(Mapping[str, object], block) # cast-ok: narrowed by isinstance
return _carries_encrypted_reasoning(_encrypted_reasoning_field(mapping))
def is_unsignable_thinking_block(block: object) -> bool:
"""A thinking block Anthropic cannot accept on input.
Anthropic verifies the signature cryptographically, so a block with a null,
empty, or missing signature (e.g. from an open-source reasoning model) is
rejected with a 400, and so is a block whose signature or data carries
another provider's encrypted reasoning. A signed block is kept whatever its
text, since ``display: omitted`` returns signed blocks with empty ``thinking``.
`redacted_thinking` blocks carry no signature and are always kept.
"""
if is_encrypted_reasoning_block(block):
return True
if not isinstance(block, Mapping):
return False
mapping: Final = cast(Mapping[str, object], block) # cast-ok: narrowed by isinstance
if mapping.get("type") != "thinking":
return False
signature: Final = mapping.get("signature")
return not (isinstance(signature, str) and len(signature) > 0)
def has_blank_redacted_data(block: object) -> bool:
match block:
case {"type": "redacted_thinking", "data": str() as data}:
return not data.strip()
case {"type": "redacted_thinking"}:
return True
case _:
return False
def native_redacted_thinking_data(data: str) -> str:
"""Claude's own `data` string for a redacted_thinking block.
Bedrock Converse carries it base64-wrapped as `redactedContent`, and LiteLLM passed that
wrapper through as `data` until it started decoding Converse replies, so histories saved
before then still hold it. Claude's own value never decodes twice, since its first byte
decodes to a protobuf tag outside the base64 alphabet.
"""
return _converse_wrapped_payload(data) or data
def converse_redacted_content(data: str) -> str:
"""The `redactedContent` Bedrock Converse expects for a redacted_thinking block's `data`."""
return base64.b64encode(native_redacted_thinking_data(data).encode()).decode()
def _converse_wrapped_payload(data: str) -> str | None:
try:
payload: Final = base64.b64decode(data, validate=True).decode("ascii")
_ = base64.b64decode(payload, validate=True)
except (binascii.Error, ValueError):
return None
else:
return payload
def strip_encrypted_reasoning_from_messages(
messages: object,
*,
should_strip: Callable[[Mapping[str, object]], bool] | None = None,
) -> None:
"""Drop the bridge-tagged reasoning blocks a routed deployment cannot decrypt from
Anthropic-shaped history.
The whole block goes, the way #40280 drops undecryptable Responses ``input`` items: a
provider that did not mint the block rejects it signed (a foreign signature) and unsigned
(a missing signature) alike, so keeping its text as an unsigned thinking block only moves
the 400 from the router to the provider.
Mutates the content lists in place: the router's fallback snapshot shares these
message objects, so a rebound list would replay the stripped blocks on the fallback hop.
"""
if not isinstance(messages, list):
return
for content in anthropic_content_lists(cast(list[object], messages)): # cast-ok: untyped client json
_strip_encrypted_reasoning_from_blocks(content, should_strip=should_strip)
def anthropic_content_lists(messages: Sequence[object]) -> Iterator[object]:
return (
cast(list[object], content) # cast-ok: narrowed by isinstance
for message in messages
if isinstance(message, Mapping)
for content in (cast(Mapping[str, object], message).get("content"),) # cast-ok: narrowed by isinstance
if isinstance(content, list)
)
def _strip_encrypted_reasoning_from_blocks(
content: object,
*,
should_strip: Callable[[Mapping[str, object]], bool] | None = None,
) -> None:
blocks: Final = cast(list[object], content) # cast-ok: narrowed by the caller's isinstance
kept: Final = tuple(
block
for block in blocks
if not is_encrypted_reasoning_block(block)
or (should_strip is not None and not should_strip(cast(Mapping[str, object], block)))
)
blocks[:] = kept
def _reasoning_replay_group_key(indexed_block: tuple[int, Mapping[str, object]]) -> str:
index, block = indexed_block
return f"encrypted:{index}" if is_encrypted_reasoning_block(block) else "summary"
def _reasoning_item_from_block_group(group: tuple[Mapping[str, object], ...]) -> ChatCompletionReasoningItem | None:
summary: Final[list[ChatCompletionReasoningSummaryTextBlock]] = [ # mutable-ok: API message payload
ChatCompletionReasoningSummaryTextBlock(type="summary_text", text=text)
for block in group
if (text := _readable_thinking_text(block))
]
encrypted_content: Final = encrypted_content_of_block(group[0])
if encrypted_content is not None:
return ChatCompletionReasoningItem(type="reasoning", summary=summary, encrypted_content=encrypted_content)
if not summary:
return None
return ChatCompletionReasoningItem(type="reasoning", summary=summary)
def responses_reasoning_items_from_thinking_blocks(
thinking_blocks: Iterable[Mapping[str, object]],
) -> tuple[ChatCompletionReasoningItem, ...]:
"""Build Responses API `reasoning` input items from Anthropic thinking blocks.
A block carrying encrypted reasoning replays the item it came from byte for byte;
a run of plain thinking blocks collapses into one summary-only item. No item carries
an `id`: the Responses API 404s on any id it did not mint itself and rejects an empty
one, while an item without an id is always accepted.
"""
return tuple(
item
for _, group in groupby(enumerate(thinking_blocks), key=_reasoning_replay_group_key)
if (item := _reasoning_item_from_block_group(tuple(block for _, block in group))) is not None
)
def parse_content_for_reasoning(
message_text: str | None,
) -> tuple[str | None, str | None]:
"""
Parse the content for reasoning
Returns:
- reasoning_content: The content of the reasoning
- content: The content of the message
"""
if not message_text:
return None, message_text
reasoning_match: Final = re.match(
r"<(?:think|thinking|budget:thinking)>(.*?)</(?:think|thinking|budget:thinking)>(.*)",
message_text,
re.DOTALL,
)
if reasoning_match:
return reasoning_match.group(1), reasoning_match.group(2)
return None, message_text
_parse_content_for_reasoning = parse_content_for_reasoning

View file

@ -0,0 +1,252 @@
import json
from typing import Any, Final # noqa: TID251 # Existing annotations retained unchanged in this pure move
from pydantic import TypeAdapter
from litellm import verbose_logger
from litellm.litellm_core_utils.core_helpers import as_str_mapping
_DECODED_JSON: Final = TypeAdapter(object)
def _attempt_json_repair(s: str) -> object | None:
"""
Attempt to repair truncated JSON produced by LLM tool calls.
Handles the most common truncation patterns where the model generates
valid JSON that is cut short (missing closing brackets/braces).
Returns the parsed value on success, or None if repair fails.
"""
import json
stripped: Final = s.rstrip()
if not stripped:
return None
# Track the stack of unmatched openers to respect nesting order
opener_stack: Final[list] = []
in_string = False
escape_next = False
for ch in stripped:
if escape_next:
escape_next = False
continue
if ch == "\\":
if in_string:
escape_next = True
continue
if ch == '"':
in_string = not in_string
continue
if in_string:
continue
if ch == "{":
opener_stack.append("}")
elif ch == "[":
opener_stack.append("]")
elif ch in ("}", "]"):
if opener_stack and opener_stack[-1] == ch:
opener_stack.pop()
if not opener_stack:
return None
# Remove trailing comma before we close brackets
candidate = stripped.rstrip(",")
# Close in reverse order of opening (respects nesting)
candidate += "".join(reversed(opener_stack))
try:
return _DECODED_JSON.validate_python(json.loads(candidate))
except json.JSONDecodeError:
pass
return None
def parse_tool_call_arguments(
arguments: str | None,
tool_name: str | None = None,
context: str | None = None,
) -> Any:
"""
Parse tool call arguments from a JSON string.
When the JSON is malformed (e.g. truncated by the model), this function
attempts a lightweight repair (closing unmatched brackets/braces) before
raising an error. A warning is logged whenever repair succeeds so that
callers are aware the arguments were not perfectly formed.
Args:
arguments: The JSON string containing tool arguments, or None.
tool_name: Optional name of the tool (for error messages).
context: Optional context string (e.g., "Anthropic Messages API").
Returns:
Parsed arguments (usually a dict, but may be any JSON-deserializable
type such as list, str, int, float, or None). Returns empty dict if
arguments is None or empty.
Raises:
ValueError: If the arguments string is not valid JSON and cannot be repaired.
"""
import json
if not arguments or not arguments.strip():
return {}
try:
return _DECODED_JSON.validate_python(json.loads(arguments))
except json.JSONDecodeError as original_error:
repaired: Final = _attempt_json_repair(arguments)
if repaired is not None:
verbose_logger.warning(
"Repaired truncated tool call arguments for tool '%s' (%s). Original (%d chars): %.200s%s",
tool_name or "<unknown>",
context or "unknown context",
len(arguments),
arguments,
"..." if len(arguments) > 200 else "",
)
return repaired
error_parts: Final = ["Failed to parse tool call arguments"]
if tool_name:
error_parts.append(f"for tool '{tool_name}'")
if context:
error_parts.append(f"({context})")
error_message: Final = " ".join(error_parts) + f". Error: {original_error}. Arguments: {arguments}"
raise ValueError(error_message) from original_error
def split_concatenated_json_objects(raw: str) -> list[dict[str, object]]:
"""
Split a string that contains one or more concatenated JSON objects into
a list of parsed dicts.
LLM providers (notably Bedrock Claude Sonnet 4.5) sometimes return
multiple tool-call argument objects concatenated in a single
``arguments`` string, e.g.::
'{"command":["curl",...]}{"command":["curl",...]}{"command":["curl",...]}'
``json.loads()`` fails on this with ``JSONDecodeError: Extra data``.
This helper uses ``json.JSONDecoder.raw_decode()`` to walk the string
and extract each JSON object individually.
The walk degrades gracefully: if the string is malformed or truncated
(e.g. a stream that ended mid-tool-call), whatever complete objects were
parsed before the bad tail are returned and the remainder is discarded
with a warning, rather than raising. The sole caller
(``_convert_to_bedrock_tool_call_invoke``) treats an empty result as
``input={}`` so the conversation can continue instead of hard-failing.
Returns
-------
list[dict]
A list of parsed dicts – one per JSON object found. If *raw* is
empty, whitespace-only, or wholly unparseable, an empty list is
returned.
"""
import json
raw = raw.strip()
if not raw:
return []
decoder: Final = json.JSONDecoder()
results: Final[list[dict[str, object]]] = []
idx = 0
length: Final = len(raw)
while idx < length:
# Skip whitespace between objects
while idx < length and raw[idx] in " \t\n\r":
idx += 1
if idx >= length:
break
try:
decoded = decoder.raw_decode(raw, idx)
except json.JSONDecodeError as e:
verbose_logger.warning(
"split_concatenated_json_objects: discarding unparseable tool-call "
"arguments tail after %d complete object(s); decode_start=%d error=%s",
len(results),
idx,
e,
)
break
obj = as_str_mapping(_DECODED_JSON.validate_python(decoded[0]))
if obj is not None:
results.append(dict(obj))
else:
# Non-dict JSON value – wrap in empty dict (Bedrock requires
# toolUse.input to be an object).
results.append({})
idx = decoded[1]
return results
MAX_SALVAGED_TOOL_ARGUMENT_OBJECTS: Final = 8
def salvage_concatenated_tool_arguments(raw: str) -> tuple[dict[str, object], ...]:
"""Return complete concatenated JSON objects that are safe to expand.
Identical objects collapse to the first one and are not capped. More than
``MAX_SALVAGED_TOOL_ARGUMENT_OBJECTS`` objects that are not all identical
returns an empty tuple. Anything that is not a full concatenation of JSON
objects returns an empty tuple. Repeated copies of the first object are not
retained, and once the cap is passed the rest of the string is only checked.
"""
stripped: Final = raw.strip()
if not stripped:
return ()
decoder: Final = json.JSONDecoder()
length: Final = len(stripped)
idx = 0 # rebind-ok: cursor walks the concatenated JSON string
count = 0 # rebind-ok: counts complete objects without retaining duplicates
kept = () # rebind-ok: holds at most one object past the salvage cap
exceeded = False # rebind-ok: cap already passed, the tail is only validated
while idx < length:
while idx < length and stripped[idx] in " \t\n\r":
idx += 1
if idx >= length:
break
try:
decoded = decoder.raw_decode(stripped, idx)
except json.JSONDecodeError:
return ()
decoded_object = as_str_mapping(_DECODED_JSON.validate_python(decoded[0]))
if decoded_object is None:
return ()
idx = decoded[1]
if exceeded:
continue
obj = dict(decoded_object)
count += 1
if not kept:
kept = (obj,)
continue
if obj == kept[0] and len(kept) == 1:
continue
if len(kept) == 1 and count > 2 and count - 1 > MAX_SALVAGED_TOOL_ARGUMENT_OBJECTS:
exceeded = True
continue
if len(kept) == 1 and count > 2:
kept = (kept[0],) * (count - 1)
if len(kept) >= MAX_SALVAGED_TOOL_ARGUMENT_OBJECTS:
exceeded = True
continue
kept = (*kept, obj)
if exceeded:
return ()
return kept

View file

@ -0,0 +1,259 @@
import base64
import re
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from itertools import chain
from typing import Final, cast # noqa: TID251 # Existing casts retained unchanged in this pure move
from litellm.litellm_core_utils.core_helpers import as_str_mapping
@dataclass(frozen=True, slots=True)
class _TPMMediaProjection:
content: object
media: tuple[Mapping[str, object], ...] = ()
def _tpm_image_part(url: str, detail: object = "auto") -> Mapping[str, object]:
return {"type": "image_url", "image_url": {"url": url, "detail": detail}}
def _tpm_blank_fields(fields: Mapping[str, object], names: tuple[str, ...]) -> Mapping[str, object]:
return {key: "" if key in names and isinstance(value, str) else value for key, value in fields.items()}
def _tpm_file_media(part: Mapping[str, object]) -> _TPMMediaProjection:
from litellm.litellm_core_utils.prompt_templates.factory import parse_mime_type
nested: Final = part.get("type") == "file"
fields: Final = as_str_mapping(part.get("file")) if nested else part
if fields is None:
return _TPMMediaProjection(part)
raw_data: Final = fields.get("file_data")
data: Final = raw_data if isinstance(raw_data, str) else ""
declared: Final = next(
(
value
for key in ("format", "mime_type", "content_type")
if isinstance(value := fields.get(key), str) and value
),
"",
)
mime: Final = (declared or parse_mime_type(data[:256]) or "").split(";", 1)[0].strip().lower()
if not mime.startswith(("image/", "audio/")):
return _TPMMediaProjection(part)
raw_url: Final = fields.get("file_url") or fields.get("file_id")
url: Final = data or (raw_url if isinstance(raw_url, str) else "")
header_end: Final = data.find(",", 0, 256)
encoded: Final = (
data[header_end + 1 :]
if header_end >= 0 and data[:header_end].endswith(";base64")
else ""
if data.startswith(("data:", "https://", "http://", "gs://"))
else data
)
media: Final = (
_tpm_image_part(
url
if not data or url.startswith(("data:", "https://", "http://", "gs://"))
else f"data:{mime};base64,{url}",
fields.get("detail", "auto"),
)
if mime.startswith("image/")
else {"type": "input_audio", "input_audio": {"data": encoded, "format": mime.removeprefix("audio/")}}
)
projected: Final = _tpm_blank_fields(fields, ("file_data", "file_url"))
return _TPMMediaProjection({**part, "file": projected} if nested else projected, (media,))
def _tpm_media_leaf(value: object) -> _TPMMediaProjection:
part: Final = as_str_mapping(value)
if part is None:
return _TPMMediaProjection(value)
kind: Final = part.get("type")
if kind in ("file", "input_file"):
return _tpm_file_media(part)
if kind == "input_audio":
audio: Final = as_str_mapping(part.get("input_audio"))
return _TPMMediaProjection(
{**part, "input_audio": _tpm_blank_fields(audio, ("data",))} if audio is not None else value,
({"type": "input_audio", "input_audio": part.get("input_audio")},),
)
if kind in ("image_url", "input_image", "image", "computer_screenshot"):
image: Final = as_str_mapping(part.get("image_url"))
source: Final = as_str_mapping(part.get("source"))
canonical: Final = _tpm_image_part(
_image_part_url({**part, "type": "input_image"} if kind == "computer_screenshot" else part) or "",
(image or part).get("detail", part.get("detail", "auto")),
)
projected: Final = (
{**part, "image_url": _tpm_blank_fields(image, ("url",))}
if image is not None and kind in ("image_url", "input_image", "computer_screenshot")
else {**part, "source": _tpm_blank_fields(source, ("data", "url"))}
if source is not None and kind == "image" and source.get("type") in ("base64", "url")
else _tpm_blank_fields(part, ("image_url", "url"))
)
return _TPMMediaProjection(projected, (canonical,))
return _TPMMediaProjection(value)
def _tpm_media_list(value: object, split: Callable[[object], _TPMMediaProjection]) -> _TPMMediaProjection:
if not isinstance(value, (list, tuple)):
return _TPMMediaProjection(value)
parts: Final = cast(Sequence[object], value) # cast-ok: finite JSON content arrays
projected: Final = tuple(map(split, parts))
media: Final = tuple(chain.from_iterable(part.media for part in projected))
content: Final = tuple(part.content for part in projected)
return _TPMMediaProjection(parts if not media else content if isinstance(value, tuple) else list(content), media)
def _tpm_replace_field(part: Mapping[str, object], key: str, projection: _TPMMediaProjection) -> _TPMMediaProjection:
return _TPMMediaProjection({**part, key: projection.content} if projection.media else part, projection.media)
def _tpm_document_media(value: object) -> _TPMMediaProjection:
part: Final = as_str_mapping(value)
source: Final = as_str_mapping(part.get("source")) if part is not None else None
if part is None or part.get("type") != "document" or source is None or source.get("type") != "content":
return _tpm_media_leaf(value)
content: Final = _tpm_media_list(source.get("content"), _tpm_media_leaf)
return _tpm_replace_field(part, "source", _tpm_replace_field(source, "content", content))
def _tpm_tool_result_media(value: object) -> _TPMMediaProjection:
part: Final = as_str_mapping(value)
if part is None or part.get("type") != "tool_result":
return _tpm_document_media(value)
return _tpm_replace_field(part, "content", _tpm_media_list(part.get("content"), _tpm_document_media))
def _tpm_code_output_media(value: object) -> _TPMMediaProjection:
part: Final = as_str_mapping(value)
url: Final = part.get("url") if part is not None else None
if part is None or part.get("type") != "image" or not isinstance(url, str) or not url:
return _TPMMediaProjection(value)
return _TPMMediaProjection(_tpm_blank_fields(part, ("url",)), (_tpm_image_part(url),))
def _tpm_input_media(value: object) -> _TPMMediaProjection:
part: Final = as_str_mapping(value)
if part is None:
return _TPMMediaProjection(value)
kind: Final = part.get("type")
if kind in ("function_call_output", "custom_tool_call_output"):
return _tpm_replace_field(part, "output", _tpm_media_list(part.get("output"), _tpm_tool_result_media))
if kind == "computer_call_output":
return _tpm_replace_field(part, "output", _tpm_media_leaf(part.get("output")))
if kind == "code_interpreter_call":
return _tpm_replace_field(part, "outputs", _tpm_media_list(part.get("outputs"), _tpm_code_output_media))
result: Final = part.get("result")
if kind == "image_generation_call" and isinstance(result, str) and result:
return _TPMMediaProjection(
_tpm_blank_fields(part, ("result",)),
(_tpm_image_part("data:application/octet-stream;base64," + result),),
)
if kind == "message" or (kind is None and isinstance(part.get("role"), str)):
return _tpm_replace_field(part, "content", _tpm_media_list(part.get("content"), _tpm_tool_result_media))
return _tpm_tool_result_media(value)
def split_media_for_tpm(value: object) -> tuple[object, tuple[Mapping[str, object], ...]]:
projection: Final = _tpm_media_list(value, _tpm_input_media)
return projection.content, projection.media
_TPM_EMBEDDING_FILE_MIME_PREFIXES: Final = ("application/pdf", "video/")
def _tpm_embedding_file(data_uri: str) -> tuple[Mapping[str, object], ...]:
from litellm.litellm_core_utils.prompt_templates.factory import parse_mime_type
mime: Final = (parse_mime_type(data_uri[:256]) or "").strip().lower()
if not mime.startswith(_TPM_EMBEDDING_FILE_MIME_PREFIXES):
return ()
return ({"type": "file", "file": {"file_data": data_uri, "format": mime}},)
_BASE64_PAYLOAD: Final = re.compile(r"[A-Za-z0-9+/]*={0,2}")
def _is_base64_data_uri(value: str) -> bool:
header_end: Final = value.find(",", 0, 256)
if header_end < 0 or not value[:header_end].endswith(";base64"):
return False
payload_start: Final = header_end + 1
if (len(value) - payload_start) % 4 or _BASE64_PAYLOAD.fullmatch(value, payload_start) is None:
return False
last_quantum: Final = value[max(payload_start, len(value) - 4) :]
return base64.b64encode(base64.b64decode(last_quantum)).decode("ascii") == last_quantum
def _tpm_embedding_file_block(part: Mapping[str, object]) -> _TPMMediaProjection:
projection: Final = _tpm_file_media(part)
fields: Final = as_str_mapping(part.get("file"))
data: Final = fields.get("file_data") if fields is not None else None
if projection.media or fields is None or not isinstance(data, str) or not _is_base64_data_uri(data):
return projection
media: Final = _tpm_embedding_file(data)
return _TPMMediaProjection({**part, "file": _tpm_blank_fields(fields, ("file_data",))} if media else part, media)
def _tpm_embedding_leaf(value: object) -> _TPMMediaProjection:
part: Final = as_str_mapping(value)
if part is not None and part.get("type") == "file":
return _tpm_embedding_file_block(part)
if not isinstance(value, str) or not value.startswith("data:"):
return _tpm_media_leaf(value)
if not _is_base64_data_uri(value):
return _TPMMediaProjection(value)
media: Final = _tpm_file_media({"file_data": value}).media or _tpm_embedding_file(value)
return _TPMMediaProjection("" if media else value, media)
def _is_json_array(value: object) -> bool:
return isinstance(value, (list, tuple))
def _tpm_embedding_item(value: object) -> _TPMMediaProjection:
return _tpm_media_list(value, _tpm_embedding_leaf) if _is_json_array(value) else _tpm_embedding_leaf(value)
def split_embedding_media_for_tpm(value: object) -> tuple[object, tuple[Mapping[str, object], ...]]:
projection: Final = (
_tpm_media_list(value, _tpm_embedding_item) if _is_json_array(value) else _tpm_embedding_leaf(value)
)
return projection.content, projection.media
def embedding_input_is_all_media(value: object) -> bool:
items: Final = cast(Sequence[object], value) if _is_json_array(value) else (value,) # cast-ok: JSON input array
return all(_tpm_embedding_leaf(item).media for item in items)
def anthropic_image_source_to_openai_url(image_source: Mapping[str, object]) -> str | None:
"""Data or remote URL for an Anthropic ``source`` block, in the form chat completions expects."""
source_type: Final = image_source.get("type")
if source_type == "base64":
media_type: Final = image_source.get("media_type") or "image/jpeg"
image_data: Final = image_source.get("data") or ""
return f"data:{media_type};base64,{image_data}" if image_data else None
if source_type == "url":
url: Final = image_source.get("url")
return url if isinstance(url, str) else ""
return None
def _image_part_url(part: Mapping[str, object]) -> str | None:
"""The image URL carried by one content part, whichever of the three dialects wrote it."""
part_type: Final = part.get("type")
if part_type in ("image_url", "input_image"):
image_url: Final = part.get("image_url") or part.get("url")
if isinstance(image_url, str):
return image_url
image_fields: Final = as_str_mapping(image_url)
url: Final = image_fields.get("url") if image_fields is not None else None
return url if isinstance(url, str) else None
if part_type == "image":
source: Final = part.get("source")
return anthropic_image_source_to_openai_url(source) if isinstance(source, Mapping) else None
return None

View file

@ -409,7 +409,7 @@ def deployments_the_caller_may_use(
return ()
_WEB_SEARCH_TOOL_TYPES: Final = frozenset({"web_search", "web_search_preview"})
_WEB_SEARCH_TOOL_KEYS: Final = frozenset({"googleSearch", "google_search"})
def _deployment_supports_web_search(deployment: dict) -> bool:
@ -433,11 +433,18 @@ def _deployment_supports_web_search(deployment: dict) -> bool:
def is_web_search_request(request_kwargs: Mapping[str, object]) -> bool:
"""OpenAI ``web_search`` / ``web_search_preview``, Anthropic ``web_search_<version>``, Gemini
``googleSearch`` / ``google_search``."""
tools: Final[object] = request_kwargs.get("tools")
return isinstance(tools, (list, tuple)) and any(
isinstance(tool, dict)
and isinstance(tool_type := tool.get("type"), str)
and tool_type in _WEB_SEARCH_TOOL_TYPES
and (
any(key in tool for key in _WEB_SEARCH_TOOL_KEYS)
or (
isinstance(tool_type := tool.get("type"), str)
and (tool_type == "web_search" or tool_type.startswith("web_search_"))
)
)
for tool in tools
)

View file

@ -19,6 +19,12 @@ def _finite_or_none(value: float | None) -> float | None:
return None if isinstance(value, float) and not math.isfinite(value) else value
def _bounded(value: float | None, integer_limit: int | None) -> float | None:
if integer_limit is None or isinstance(value, bool) or not isinstance(value, int):
return value
return max(-integer_limit, min(integer_limit, value))
def safe_json_structure(
data: object,
max_depth: int = DEFAULT_MAX_RECURSE_DEPTH,
@ -26,12 +32,14 @@ def safe_json_structure(
key: str | None = None,
*,
non_finite_as_null: bool = False,
integer_limit: int | None = None,
) -> object:
"""
Rebuild data out of JSON-native pieces while detecting circular references.
If a circular reference is detected then a marker string is returned.
NUL bytes are stripped from strings to prevent PostgreSQL 22P05 errors. With
non_finite_as_null, NaN and infinite floats become null, since jsonb rejects them.
With integer_limit, integers are clamped to that magnitude.
value_transform, when given, is applied to every string leaf (and to the
str() fallback for non-serializable objects) with the mapping key the leaf
@ -51,7 +59,8 @@ def safe_json_structure(
cleaned = obj.replace("\x00", "") if "\x00" in obj else obj
return _transform(key, cleaned)
if isinstance(obj, (int, float, bool, type(None))):
return _finite_or_none(obj) if non_finite_as_null else obj
bounded: Final = _bounded(obj, integer_limit)
return _finite_or_none(bounded) if non_finite_as_null else bounded
# Check for circular reference.
if id(obj) in seen:
return "CircularReference Detected"

View file

@ -706,7 +706,7 @@ def _data_uri_media_scope(model: str, media: Sequence[Mapping[str, object]]) ->
def split_embedding_input_tokens(
value: _EmbeddingInputT, media_models: Callable[[], Sequence[str]], fallback_model: str | None = None
) -> tuple[_EmbeddingInputT, int]:
from litellm.litellm_core_utils.prompt_templates.common_utils import (
from litellm.litellm_core_utils.prompt_templates.tpm_media_utils import (
embedding_input_is_all_media,
split_embedding_media_for_tpm,
)

View file

@ -37,18 +37,9 @@ from litellm.litellm_core_utils.core_helpers import (
from litellm.litellm_core_utils.prompt_templates.common_utils import (
DEFS_MAX_INLINED_BYTES,
invalid_type_message,
is_object_schema,
is_present_non_string,
is_unhashable_value_behind,
sanitize_input_schema_for_anthropic,
schema_fragment_ref,
schema_grammar_branch_count,
schema_has_lookaround_pattern,
schema_has_open_object,
schema_has_unresolvable_ref,
schema_optional_property_count,
schema_string_formats,
schema_union_property_count,
unpack_defs,
)
from litellm.litellm_core_utils.prompt_templates.image_handling import (
@ -59,6 +50,17 @@ from litellm.litellm_core_utils.prompt_templates.image_handling import (
inline_remote_image_urls,
is_unformatted_pdf_link_image,
)
from litellm.litellm_core_utils.prompt_templates.json_schema_utils import (
is_object_schema,
schema_fragment_ref,
schema_grammar_branch_count,
schema_has_lookaround_pattern,
schema_has_open_object,
schema_has_unresolvable_ref,
schema_optional_property_count,
schema_string_formats,
schema_union_property_count,
)
from litellm.litellm_core_utils.prompt_templates.mid_conversation_system import (
message_field,
parts_of,
@ -827,11 +829,11 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
return cls._raise_invalid_reasoning_effort(model, value, llm_provider)
def get_supported_openai_params(self, model: str):
sampling_params: Final = ("temperature", "top_p") if self._supports_sampling_params(model) else ()
params: Final = [
"stream",
"stop",
"temperature",
"top_p",
*sampling_params,
"max_tokens",
"max_completion_tokens",
"tools",

View file

@ -29,17 +29,19 @@ from litellm.constants import (
)
from litellm.exceptions import UnsupportedParamsError
from litellm.litellm_core_utils.core_helpers import as_str_mapping, lax_bool
from litellm.litellm_core_utils.prompt_templates.common_utils import (
get_file_ids_from_messages,
is_encrypted_reasoning_block,
native_redacted_thinking_data,
)
from litellm.litellm_core_utils.prompt_templates.factory import THOUGHT_SIGNATURE_SEPARATOR
from litellm.litellm_core_utils.prompt_templates.file_id_utils import (
get_file_ids_from_messages,
)
from litellm.litellm_core_utils.prompt_templates.mid_conversation_system import (
find_anthropic_server_tool_result,
message_field,
parts_of,
)
from litellm.litellm_core_utils.prompt_templates.reasoning_utils import (
is_encrypted_reasoning_block,
native_redacted_thinking_data,
)
from litellm.litellm_core_utils.reasoning_effort_utils import DroppedThinkingBudget, non_numeric_thinking_budget_error
from litellm.litellm_core_utils.url_utils import join_api_base
from litellm.llms.anthropic.wif import (

View file

@ -21,7 +21,9 @@ import httpx
from openai.types.file_deleted import FileDeleted
from pydantic import ConfigDict, TypeAdapter
from litellm.litellm_core_utils.prompt_templates.common_utils import extract_file_data
from litellm.litellm_core_utils.prompt_templates.file_id_utils import (
extract_file_data,
)
from litellm.litellm_core_utils.url_utils import encode_url_path_segment, join_api_base
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.base_llm.files.transformation import (

View file

@ -123,10 +123,9 @@ def _extract_proxy_litellm_metadata(
def _requested_router(kwargs: Mapping[str, object]) -> "Router | None":
from litellm.router import Router
from litellm.router_python_core import PythonCore
requested: Final = kwargs.get("litellm_router")
return requested if isinstance(requested, (Router, PythonCore)) else None # pyright: ignore[reportReturnType] # the router passes its core, which carries Router's members
return requested if isinstance(requested, Router) else None
def request_safeguards_evaluator(

View file

@ -123,15 +123,23 @@ def create_tool_name_mapping(
from openai.types.chat.chat_completion_chunk import Choice as OpenAIStreamingChoice
from litellm.litellm_core_utils.prompt_templates.common_utils import (
anthropic_image_source_to_openai_url,
anthropic_inline_document,
parse_tool_call_arguments,
reasoning_content_from_thinking_blocks,
with_prompt_cache_breakpoint,
)
from litellm.litellm_core_utils.prompt_templates.factory import (
THOUGHT_SIGNATURE_SEPARATOR,
)
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
with_prompt_cache_breakpoint,
)
from litellm.litellm_core_utils.prompt_templates.reasoning_utils import (
reasoning_content_from_thinking_blocks,
)
from litellm.litellm_core_utils.prompt_templates.tool_call_json_repair import (
parse_tool_call_arguments,
)
from litellm.litellm_core_utils.prompt_templates.tpm_media_utils import (
anthropic_image_source_to_openai_url,
)
from litellm.litellm_core_utils.reasoning_effort_utils import (
reasoning_effort_from_thinking,
reasoning_effort_from_thinking_silently,

View file

@ -20,7 +20,7 @@ from litellm.litellm_core_utils.asyncify import (
run_async_function, # pyright: ignore[reportUnknownVariableType] # untyped helper
)
from litellm.litellm_core_utils.core_helpers import as_str_mapping, drops_unsupported_params
from litellm.litellm_core_utils.prompt_templates.common_utils import (
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
cache_control_as_prompt_cache_breakpoint,
prompt_cache_breakpoint_with_readable_mode,
with_prompt_cache_breakpoint,

View file

@ -12,7 +12,7 @@ from litellm import verbose_logger
from litellm._logging import redact_internal_details_from_client_message
from litellm._uuid import uuid
from litellm.exceptions import APIError, MidStreamFallbackError
from litellm.litellm_core_utils.prompt_templates.common_utils import (
from litellm.litellm_core_utils.prompt_templates.reasoning_utils import (
encrypted_reasoning_signature,
)
from litellm.llms.anthropic.messages.native.utils import (

View file

@ -14,9 +14,13 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import (
TOOL_RESULT_IMAGE_BOUNDARY,
TOOL_RESULT_IMAGE_PLACEHOLDER,
anthropic_inline_document,
)
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
with_prompt_cache_breakpoint,
)
from litellm.litellm_core_utils.prompt_templates.reasoning_utils import (
encrypted_reasoning_signature,
responses_reasoning_items_from_thinking_blocks,
with_prompt_cache_breakpoint,
)
from litellm.litellm_core_utils.reasoning_effort_utils import (
reasoning_effort_from_thinking,

View file

@ -14,17 +14,21 @@ from litellm.integrations.anthropic_cache_control_hook import deployment_prompt_
from litellm.litellm_core_utils.allowed_tools_tool_choice import is_allowed_tools_tool_choice
from litellm.litellm_core_utils.core_helpers import drops_unsupported_params
from litellm.litellm_core_utils.prompt_templates.common_utils import (
chat_completion_prompt_cache_breakpoints_for_wire,
drop_tool_reference_parts_from_tool_messages,
flatten_combinators_and_drop_non_python_regex_patterns,
hoist_images_from_tool_messages,
system_messages_first,
tool_with_sanitized_parameters,
without_prompt_cache_breakpoints,
)
from litellm.litellm_core_utils.prompt_templates.factory import (
convert_to_azure_openai_messages,
)
from litellm.litellm_core_utils.prompt_templates.json_schema_utils import (
flatten_combinators_and_drop_non_python_regex_patterns,
tool_with_sanitized_parameters,
)
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
chat_completion_prompt_cache_breakpoints_for_wire,
without_prompt_cache_breakpoints,
)
from litellm.llms.base_llm.base_utils import map_developer_role_to_system_role
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.openai.chat.gpt_reasoning_transformation import GPT_REASONING_SERIES_MARKERS

View file

@ -11,7 +11,9 @@ from pydantic import TypeAdapter
from litellm._logging import verbose_logger
from litellm.constants import AZURE_DEFAULT_RESPONSES_API_VERSION
from litellm.litellm_core_utils.prompt_templates.common_utils import prompt_cache_breakpoint_within
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
prompt_cache_breakpoint_within,
)
from litellm.litellm_core_utils.url_utils import encode_url_path_segment
from litellm.llms.azure.chat.gpt_reasoning_transformation import AzureOpenAIGPT5Config
from litellm.llms.azure.common_utils import BaseAzureLLM

View file

@ -21,6 +21,8 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import (
drop_tool_reference_parts_from_tool_messages,
filter_value_from_dict,
is_pdf_file_part,
)
from litellm.litellm_core_utils.prompt_templates.prompt_cache_breakpoint_utils import (
prompt_cache_breakpoint_for_wire,
with_prompt_cache_breakpoint,
)

Some files were not shown because too many files have changed in this diff Show more