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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@ keywords = ["benchmark", "llm-agents", "acp", "agent-evaluation", "multi-turn",
dependencies = [
"agent-client-protocol>=0.10",
"httpx>=0.27.0",
# Keep TLS clients and LiteLLM/Daytona on patched transitive releases.
"certifi>=2026.10.19",
"aiohttp>=3.14.4",
"anyio>=4.0",
"pydantic>=2.7",
"pyyaml>=6.0",
"rich>=13.0",
# Denylist egress mints TLS certificates on both Docker and Daytona.
"cryptography>=44",
"cryptography>=50",
# Dataset registry bench_version checks (PEP 440 specifier sets).
"packaging>=24",
"litellm[proxy]==1.91.5",
"litellm[proxy]==1.103.3",
"google-cloud-aiplatform>=1.133.0,<2.0",
"tomli-w>=1.0",
"typer>=0.9",
Expand Down
2 changes: 1 addition & 1 deletion src/benchflow/continue_run/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def __call__(self, request_body: dict[str, Any]) -> dict[str, Any]:

response = litellm.completion(**self.build_kwargs(request_body))
dump = getattr(response, "model_dump", None)
return dump() if callable(dump) else dict(response)
return dump() if callable(dump) else dict(cast(Any, response))


def stitched_trajectory_lines(
Expand Down
17 changes: 10 additions & 7 deletions src/benchflow/providers/litellm_bedrock_patch.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""LiteLLM startup patch for Bedrock Claude 4.8+ adaptive thinking.

LiteLLM 1.89.0 knows the direct Anthropic Claude 4.8+ IDs, but Bedrock
inference-profile IDs such as ``us.anthropic.claude-opus-4-8`` still need to be
classified as adaptive-thinking models before the Bedrock Converse transform is
called. This module is loaded inside the LiteLLM proxy process via
``sitecustomize`` and is intentionally inert for every non-4.8+ model.
LiteLLM 1.89.0 did not classify Bedrock inference-profile IDs such as
``us.anthropic.claude-opus-4-8`` as adaptive-thinking models; 1.103.3 does, and
the gate below keeps that classification for the Bedrock Converse transform
either way. The module also applies the run-level reasoning-effort override and
clamp. It is loaded inside the LiteLLM proxy process via ``sitecustomize`` and is
intentionally inert for every non-4.8+ model.
"""

from __future__ import annotations
Expand Down Expand Up @@ -62,10 +63,12 @@ def _patch_anthropic_gate() -> None:

original = AnthropicConfig._is_adaptive_thinking_model

def gate(model: str) -> bool:
# LiteLLM passes the provider as a second argument (e.g. "bedrock"), so
# forward whatever the caller sent instead of fixing the vendor signature.
def gate(model: str, *args: Any, **kwargs: Any) -> bool:
if _is_new_bedrock_claude(model):
return True
return original(model or "")
return original(model or "", *args, **kwargs)

setattr( # noqa: B010 - avoids static type narrowing on monkey-patched vendor API
AnthropicConfig,
Expand Down
9 changes: 5 additions & 4 deletions src/benchflow/providers/litellm_bedrock_preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ class BedrockPatchPreflightError(RuntimeError):
BEDROCK_PATCH_PREFLIGHT_SOURCE = """\
import sys

# Probe with versioned/profile-shaped Bedrock IDs: stock litellm 1.89.0
# resolves the Opus bare alias through its cost map, so only the versioned form
# discriminates patched from stock (#602). Fable 5 is profile-shaped today.
# Probe with versioned/profile-shaped Bedrock IDs (#602). Fable 5 is
# profile-shaped today. Call the gate the way the Bedrock transforms do, with
# the provider as the second argument, so a gate that cannot take that call
# fails here rather than on the first proxied request.
PROBES = [
"us.anthropic.claude-opus-4-8-20251101-v1:0",
"us.anthropic.claude-fable-5",
Expand All @@ -37,7 +38,7 @@ class BedrockPatchPreflightError(RuntimeError):
from litellm.llms.anthropic.chat.transformation import AnthropicConfig

for probe in PROBES:
if not AnthropicConfig._is_adaptive_thinking_model(probe):
if not AnthropicConfig._is_adaptive_thinking_model(probe, "bedrock"):
failures.append(
"adaptive-thinking gate inactive: "
f"_is_adaptive_thinking_model({probe!r}) is False"
Expand Down
34 changes: 17 additions & 17 deletions src/benchflow/providers/litellm_gemini_passthrough_patch.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
"""Backport Gemini pass-through streaming logging for LiteLLM 1.89/1.91.

Those releases classify every native ``generateContent`` URL as Vertex AI and
send its streamed response through the Vertex logger. That happens to work for
Gemini model names present in both catalogs, but it rejects Google AI Studio
Gemma names and drops the entire callback — including token usage and provider
trajectory evidence. LiteLLM added a dedicated Gemini endpoint type later.

The proxy imports this module from ``sitecustomize``. It patches only the old
vendor shape (no ``EndpointType.GEMINI``) and only Google AI Studio-style model
paths, leaving Vertex and every other provider untouched.
"""Send Google AI Studio pass-through streams to LiteLLM's Gemini logger.

LiteLLM's pass-through route classifies every native ``generateContent`` URL as
Vertex AI and sends its streamed response through the Vertex logger. That
happens to work for Gemini model names present in both catalogs, but it rejects
Google AI Studio Gemma names and drops the entire callback, including token
usage and provider trajectory evidence. LiteLLM 1.100 added an
``EndpointType.GEMINI`` logging branch, yet the pass-through route still
classifies these URLs as Vertex AI.

The proxy imports this module from ``sitecustomize``. It intercepts only Google
AI Studio-style model paths that LiteLLM classified as Vertex AI, leaving real
Vertex paths and every other provider untouched.
"""

from __future__ import annotations
Expand Down Expand Up @@ -49,11 +51,6 @@ def _apply_patch() -> None:
except Exception:
return

# Newer LiteLLM releases have their own Gemini dispatch branch. Do not
# replace supported vendor behavior after the pinned dependency advances.
if hasattr(EndpointType, "GEMINI"):
return

original = PassThroughStreamingHandler._build_passthrough_logging_result
if getattr(original, "__benchflow_gemini_passthrough_patch__", False):
return
Expand All @@ -70,7 +67,10 @@ def build_passthrough_logging_result(
end_time: Any,
model: str | None,
) -> tuple[Any, dict[str, Any]]:
if not _is_google_ai_studio_generate_content(url_route):
# Keep vendor behavior for anything LiteLLM did not misroute to Vertex.
if endpoint_type != EndpointType.VERTEX_AI or not (
_is_google_ai_studio_generate_content(url_route)
):
return original(
litellm_logging_obj=litellm_logging_obj,
passthrough_success_handler_obj=passthrough_success_handler_obj,
Expand Down
16 changes: 13 additions & 3 deletions src/benchflow/providers/litellm_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@

logger = logging.getLogger(__name__)

LITELLM_VERSION_SPEC = "litellm[proxy]==1.91.5"
LITELLM_VERSION_SPEC = "litellm[proxy]==1.103.3"
LITELLM_SANDBOX_ROOT = "/tmp/benchflow-litellm"
_CALLBACK_MODULE = "benchflow_litellm_callback"
_PATCH_MODULE = "benchflow_litellm_bedrock_patch"
Expand Down Expand Up @@ -1057,7 +1057,17 @@ async def _ensure_sandbox_litellm(
# stdlib-venv fallback for images that have a working venv and lack uv.
requirements = " ".join(
shlex.quote(requirement)
for requirement in (LITELLM_VERSION_SPEC, "boto3>=1.40", *extra_requirements)
# Sandbox proxy environments are installed independently of this
# project's lock. Keep these security-sensitive versions aligned with
# the reviewed lock instead of selecting a new release on reprovision.
for requirement in (
LITELLM_VERSION_SPEC,
"certifi==2026.10.23",
"aiohttp==3.14.5",
"cryptography==50.0.2",
"boto3>=1.40",
*extra_requirements,
)
)
command = f"""
set -eu
Expand All @@ -1075,7 +1085,7 @@ async def _ensure_sandbox_litellm(
PY="$(command -v python3 || command -v python)"
if [ ! -x {vq}/bin/python ]; then
"$PY" -m venv {vq} 2>/dev/null || (
"$PY" -m pip install --user -q virtualenv &&
"$PY" -m pip install --user -q 'virtualenv==21.14.13' &&
"$PY" -m virtualenv {vq}
)
fi
Expand Down
72 changes: 68 additions & 4 deletions tests/test_litellm_gemini_passthrough_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_google_ai_studio_path_detection_excludes_vertex() -> None:
)


def test_old_litellm_routes_gemma_streams_through_gemini_logger(monkeypatch) -> None:
def test_ai_studio_gemma_streams_use_gemini_logger(monkeypatch) -> None:
"""Guards PR #1030: Gemma usage must not be dropped by the Vertex logger."""
from litellm.proxy.pass_through_endpoints.llm_provider_handlers.gemini_passthrough_logging_handler import (
GeminiPassthroughLoggingHandler,
Expand All @@ -29,9 +29,6 @@ def test_old_litellm_routes_gemma_streams_through_gemini_logger(monkeypatch) ->
)
from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType

if hasattr(EndpointType, "GEMINI"):
return

seen: dict[str, object] = {}

def fake_gemini_handler(**kwargs):
Expand Down Expand Up @@ -61,3 +58,70 @@ def fake_gemini_handler(**kwargs):
assert response == "gemma-response"
assert kwargs["model"] == "gemma-4-31b-it"
assert seen["all_chunks"] == ['data: {"usageMetadata":{"promptTokenCount":1}}']


def test_ai_studio_path_with_non_vertex_label_is_left_to_litellm(monkeypatch) -> None:
"""PR #1166 guards the LiteLLM 1.103 bump of PR #1030's patch: only streams LiteLLM
labelled Vertex AI are rerouted, so any other label keeps vendor dispatch."""
from litellm.proxy.pass_through_endpoints.llm_provider_handlers.gemini_passthrough_logging_handler import (
GeminiPassthroughLoggingHandler,
)
from litellm.proxy.pass_through_endpoints.streaming_handler import (
PassThroughStreamingHandler,
)
from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType

calls: list[dict[str, object]] = []

def fake_gemini_handler(**kwargs):
calls.append(kwargs)
return {"result": "gemma-response", "kwargs": {"model": "gemma-4-31b-it"}}

monkeypatch.setattr(
GeminiPassthroughLoggingHandler,
"_handle_logging_gemini_collected_chunks",
staticmethod(fake_gemini_handler),
)
_, kwargs = PassThroughStreamingHandler._build_passthrough_logging_result(
litellm_logging_obj=SimpleNamespace(),
passthrough_success_handler_obj=SimpleNamespace(),
url_route=(
"https://generativelanguage.googleapis.com/v1beta/models/"
"gemma-4-31b-it:streamGenerateContent?alt=sse"
),
request_body={"contents": []},
endpoint_type=EndpointType.GENERIC,
start_time=datetime.now(),
raw_bytes=[b'data: {"usageMetadata":{"promptTokenCount":1}}\n\n'],
end_time=datetime.now(),
model=None,
)

assert calls == []
assert kwargs == {}


def test_gemma_patch_stays_installed_while_litellm_misroutes_ai_studio() -> None:
"""PR #1166 guards PR #1030 across the LiteLLM 1.103 bump: LiteLLM now has an
``EndpointType.GEMINI`` branch, but its pass-through route still classifies
AI Studio URLs as Vertex AI, so the patch must not switch itself off."""
from litellm.proxy.pass_through_endpoints.pass_through_endpoints import (
HttpPassThroughEndpointHelpers,
)
from litellm.proxy.pass_through_endpoints.streaming_handler import (
PassThroughStreamingHandler,
)
from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType

url = (
"https://generativelanguage.googleapis.com/v1beta/models/"
"gemma-4-31b-it:streamGenerateContent?alt=sse"
)
assert (
HttpPassThroughEndpointHelpers.get_endpoint_type(url) == EndpointType.VERTEX_AI
)
assert getattr(
PassThroughStreamingHandler._build_passthrough_logging_result,
"__benchflow_gemini_passthrough_patch__",
False,
)
37 changes: 35 additions & 2 deletions tests/test_litellm_hardening.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,10 +557,12 @@ def test_bedrock_patch_recognizes_bedrock_opus_48_as_adaptive_thinking():
# recognizes 4-6/4-7 natively, so the patch must not regress those — it
# delegates to the original — and must not over-trigger on plain models.)
assert (
AnthropicConfig._is_adaptive_thinking_model("us.anthropic.claude-opus-4-8")
AnthropicConfig._is_adaptive_thinking_model(
"us.anthropic.claude-opus-4-8", "bedrock"
)
is True
)
assert AnthropicConfig._is_adaptive_thinking_model("gpt-4o") is False
assert AnthropicConfig._is_adaptive_thinking_model("gpt-4o", "bedrock") is False


def test_bedrock_patch_flags_cost_map_when_entry_present():
Expand Down Expand Up @@ -693,6 +695,37 @@ def test_bedrock_patch_preflight_fails_closed_when_patch_not_loaded(tmp_path):
assert "inactive" in result.stdout


def test_bedrock_patch_preflight_rejects_gate_without_provider_argument(tmp_path):
"""PR #1166 guards PR #668's preflight (issue #602) across the LiteLLM 1.103 bump: the
Bedrock transforms now call the adaptive-thinking gate with the provider as a
second argument, so a gate that only accepts the model must fail the
preflight instead of raising TypeError on every proxied Bedrock request."""
import os
import subprocess
import sys

(tmp_path / "sitecustomize.py").write_text(
"from litellm.llms.anthropic.chat.transformation import AnthropicConfig\n"
"from litellm.llms.bedrock.chat.converse_transformation import (\n"
" AmazonConverseConfig,\n"
")\n"
"AnthropicConfig._is_adaptive_thinking_model = staticmethod(lambda model: True)\n"
"AmazonConverseConfig._handle_reasoning_effort_parameter"
".__benchflow_bedrock_patch__ = True\n"
)
env = dict(os.environ)
env["PYTHONPATH"] = str(tmp_path)
result = subprocess.run(
[sys.executable, "-c", preflight_mod.BEDROCK_PATCH_PREFLIGHT_SOURCE],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode != 0
assert "anthropic transform unavailable" in result.stdout


@pytest.mark.asyncio
async def test_sandbox_litellm_bedrock_route_runs_preflight():
"""Guards PR #668 / issue #602 wiring: a Bedrock 4.8+ sandbox route must run the
Expand Down
Loading
Loading