Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

58.0 KB
Raw Blame
"""Live /chat/completions coverage: the #28991 regression net plus per-provider
OpenAI-compatible translation.

GH #28991 broke /chat/completions (and /responses) for most models on some
releases: a clean 200 came back but with no real completion. A status check
alone would not have caught it, so TestChatCompletionsRegression asserts the
product promise - a non-empty assistant message and a real model name in the
body - across the three providers wired into the gateway config (OpenAI,
Anthropic, Gemini). A regression that empties the completion for any provider
fails that provider's row here.

The per-provider classes below cover the OpenAI-compatible /chat/completions
translation for providers customers reach by registering their own deployment
via /model/new (Cohere, Gemini, hosted_vllm, Anthropic), each deleted on teardown.
"""

from __future__ import annotations

import base64
import os
from pathlib import Path
from typing import Final

import pytest
from pydantic import BaseModel

from e2e_config import unique_marker
from e2e_http import StreamingResponse, unwrap
from e2e_metadata import Capability, Domain, Mode, Provider, Route, Subject, meta
from lifecycle import ResourceManager
from models import (
    ChatBody,
    ChatMessage,
    ChatResponse,
    ChatTool,
    ChatToolFunction,
    ImageContentPart,
    ImageUrl,
    LiteLLMParamsBody,
    TextContentPart,
    ThinkingParam,
)
from passthrough_client import PassthroughClient

pytestmark = pytest.mark.e2e

COHERE_BACKEND = "cohere/command-r-08-2024"
GEMINI_BACKEND = "gemini/gemini-2.5-flash"
VERTEX_BACKEND: Final = "vertex_ai/gemini-2.5-flash"
AZURE_OPENAI_BACKEND: Final = "azure/gpt-5.4-nano"
AZURE_OPENAI_API_VERSION: Final = "v1"
AZURE_FOUNDRY_BACKEND: Final = "azure_ai/claude-haiku-4-5"
OPENAI_BACKEND = "openai/gpt-5.6"
ANTHROPIC_BACKEND = "anthropic/claude-haiku-4-5-20251001"
BEDROCK_CONVERSE_BACKEND = "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0"
BEDROCK_NOVA_BACKEND: Final = "bedrock/us.amazon.nova-2-lite-v1:0"
VERTEX_MISTRAL_BACKEND: Final = "vertex_ai/mistral-small-2503"
VERTEX_GPT_OSS_BACKEND: Final = "vertex_ai/openai/gpt-oss-120b-maas"
VERTEX_PARTNER_BACKENDS: Final = (
    pytest.param(
        VERTEX_MISTRAL_BACKEND,
        marks=(
            pytest.mark.skip(
                reason="the e2e Vertex project has no access to mistral-small-2503 (404 publisher model not found)"
            ),
            meta(
                Subject(
                    domain=Domain.LLM_TRANSLATION,
                    route=Route.CHAT_COMPLETIONS,
                    providers=(Provider.VERTEX_AI,),
                    models=(VERTEX_MISTRAL_BACKEND,),
                    mode=Mode.STREAM,
                )
            ),
        ),
    ),
    pytest.param(
        VERTEX_GPT_OSS_BACKEND,
        marks=(
            pytest.mark.skip(reason="never served by the e2e Vertex project (60s read timeout, no headers)"),
            meta(
                Subject(
                    domain=Domain.LLM_TRANSLATION,
                    route=Route.CHAT_COMPLETIONS,
                    providers=(Provider.VERTEX_AI,),
                    models=(VERTEX_GPT_OSS_BACKEND,),
                    mode=Mode.STREAM,
                )
            ),
        ),
    ),
)
PDF_DOCUMENT_URL: Final = (
    "https://cdn.jsdelivr.net/gh/BerriAI/litellm"
    "@d769e81c90d453240c61fc572cdb27fae06a89d0"
    "/tests/llm_translation/fixtures/dummy.pdf"
)
PDF_DOCUMENT_TEXT: Final = "test pdf file"


class _StreamToolCallFunction(BaseModel):
    name: str | None = None
    arguments: str | None = None


class _StreamToolCall(BaseModel):
    function: _StreamToolCallFunction = _StreamToolCallFunction()


class _StreamDelta(BaseModel):
    content: str | None = None
    tool_calls: list[_StreamToolCall] | None = None


class _StreamChoice(BaseModel):
    delta: _StreamDelta = _StreamDelta()


class _StreamChunk(BaseModel):
    choices: list[_StreamChoice] = []


def _streamed_tool_call(events: list[str]) -> tuple[str, str]:
    """Reassemble the tool call streamed across chunks: the name arrives once and the
    arguments arrive as fragments, so concatenating both and parsing the arguments as
    JSON catches a stream that never completes the call or splits its argument JSON."""
    chunks = [_StreamChunk.model_validate_json(event) for event in events]
    calls = [call for chunk in chunks for choice in chunk.choices for call in (choice.delta.tool_calls or [])]
    name = "".join(call.function.name or "" for call in calls)
    arguments = "".join(call.function.arguments or "" for call in calls)
    return name, arguments


_FIXTURES_DIR: Final = Path(__file__).parent / "fixtures"
CAT_IMAGE: Final = _FIXTURES_DIR / "cat.jpg"
OPENAI_VISION_BACKEND = "openai/gpt-4o"


def _cat_image_data_url() -> str:
    return "data:image/jpeg;base64," + base64.b64encode(CAT_IMAGE.read_bytes()).decode()


def _vision_messages() -> list[ChatMessage]:
    return [
        ChatMessage(
            role="user",
            content=[
                TextContentPart(text="What animal is in this image? Answer in one word."),
                ImageContentPart(image_url=ImageUrl(url=_cat_image_data_url())),
            ],
        )
    ]


def _assert_describes_cat(response: ChatResponse) -> None:
    assert response.choices, f"vision returned no choices: {response}"
    choice = response.choices[0]
    content = (choice.message.content if choice.message else None) or ""
    assert any(term in content.lower() for term in ("cat", "feline", "kitten", "kitty")), (
        f"vision response did not describe the image: {content[:200]!r} "
        f"(finish_reason={choice.finish_reason!r}, usage={response.usage})"
    )


def _streamed_text(events: list[str]) -> str:
    """Concatenate the delta content across streamed chunks. Parsing every event as
    JSON also fails loudly on a truncated or garbled chunk (the vertex/gemini image
    streaming regression class), so an incomplete stream cannot pass as content."""
    chunks = [_StreamChunk.model_validate_json(event) for event in events]
    return "".join(choice.delta.content or "" for chunk in chunks for choice in chunk.choices)


def _assert_streamed_completion(result: StreamingResponse) -> None:
    """A streamed /chat/completions must deliver real content, not a clean-but-empty
    stream (the #28991 class on the streaming path)."""
    assert result.ok and result.is_streaming, f"stream was not established: {result}"
    assert result.stream_error is None, f"stream carried an error event: {result.stream_error}"
    assert len(result.stream_events) > 1, f"stream did not deliver multiple data events: {result}"
    assert _streamed_text(result.stream_events).strip(), (
        f"stream completed with no content deltas: {result.stream_events[:3]}"
    )


def _bedrock_params() -> LiteLLMParamsBody:
    return LiteLLMParamsBody(
        model=BEDROCK_CONVERSE_BACKEND,
        aws_access_key_id="os.environ/AWS_ACCESS_KEY_ID",
        aws_secret_access_key="os.environ/AWS_SECRET_ACCESS_KEY",
        aws_region_name="os.environ/AWS_REGION",
    )


class _WeatherArgs(BaseModel):
    location: str


_WEATHER_TOOL = ChatTool(
    function=ChatToolFunction(
        name="get_weather",
        description="Get the current weather for a location",
        parameters={
            "type": "object",
            "properties": {"location": {"type": "string"}},
            "required": ["location"],
        },
    )
)


def _assert_weather_tool_call(response: ChatResponse) -> None:
    """The model, forced to call the tool, must return a get_weather call whose
    arguments parse as JSON and carry a location. A regression that drops tool_calls
    or emits malformed argument JSON fails here rather than passing on a 200."""
    assert response.choices, f"chat returned no choices: {response}"
    message = response.choices[0].message
    calls = message.tool_calls if message else None
    assert calls, f"model returned no tool call for a tool-forced prompt: {response}"
    weather = next((call for call in calls if call.function.name == "get_weather"), None)
    assert weather is not None, f"expected a get_weather call, got {[c.function.name for c in calls]}"
    assert weather.function.arguments, f"get_weather call carried no arguments: {weather}"
    args = _WeatherArgs.model_validate_json(weather.function.arguments)
    assert args.location.strip(), f"get_weather arguments missing location: {weather.function.arguments}"


class _Person(BaseModel):
    name: str
    age: int


_PERSON_SCHEMA: dict[str, object] = {
    "type": "json_schema",
    "json_schema": {
        "name": "person",
        "strict": True,
        "schema": {
            "type": "object",
            "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
            "required": ["name", "age"],
            "additionalProperties": False,
        },
    },
}

OPENAI_CHAT_MODEL: Final = "gpt-5.5"
ANTHROPIC_CHAT_MODEL: Final = "claude-haiku-4-5"
GEMINI_FLASH_MODEL: Final = "gemini-2.5-flash"

CHAT_MODELS: Final = (
    pytest.param(
        OPENAI_CHAT_MODEL,
        "openai",
        id=f"{OPENAI_CHAT_MODEL}-openai",
        marks=meta(
            Subject(
                domain=Domain.LLM_TRANSLATION,
                route=Route.CHAT_COMPLETIONS,
                providers=(Provider.OPENAI,),
                models=(OPENAI_CHAT_MODEL,),
                mode=Mode.NONSTREAM,
            )
        ),
    ),
    pytest.param(
        ANTHROPIC_CHAT_MODEL,
        "anthropic",
        id=f"{ANTHROPIC_CHAT_MODEL}-anthropic",
        marks=meta(
            Subject(
                domain=Domain.LLM_TRANSLATION,
                route=Route.CHAT_COMPLETIONS,
                providers=(Provider.ANTHROPIC,),
                models=(ANTHROPIC_CHAT_MODEL,),
                mode=Mode.NONSTREAM,
            )
        ),
    ),
    pytest.param(
        GEMINI_FLASH_MODEL,
        "gemini",
        id=f"{GEMINI_FLASH_MODEL}-gemini",
        marks=meta(
            Subject(
                domain=Domain.LLM_TRANSLATION,
                route=Route.CHAT_COMPLETIONS,
                providers=(Provider.GEMINI,),
                models=(GEMINI_FLASH_MODEL,),
                mode=Mode.NONSTREAM,
            )
        ),
    ),
)


class TestChatCompletionsRegression:
    @pytest.mark.parametrize(("model", "route"), CHAT_MODELS)
    @pytest.mark.covers(
        "llm.chat_completions.openai.basic.nonstream.works",
        "llm.chat_completions.anthropic.basic.nonstream.works",
        exercised_on=[],
    )
    def test_chat_returns_real_completion(
        self, client: PassthroughClient, scoped_key: str, model: str, route: str
    ) -> None:
        response = unwrap(
            client.proxy.chat(
                scoped_key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=f"reply with one word {unique_marker()}",
                        )
                    ],
                    max_tokens=512,
                ),
            )
        )

        assert (
            response.model
        ), f"{model} ({route}): response carried no model name: {response}"
        assert (
            response.choices
        ), f"{model} ({route}): response had no choices: {response}"
        message = response.choices[0].message
        assert (
            message is not None and message.content and message.content.strip()
        ), f"{model} ({route}): 200 with an empty completion (#28991): {response}"


class TestCohereChat:
    """Cohere via the OpenAI-compatible /chat/completions path."""

    @pytest.mark.covers(
        "llm.chat_completions.cohere.basic.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.COHERE,),
            models=(COHERE_BACKEND,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_cohere_chat_returns_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        cohere_key = os.environ["COHERE_API_KEY"]
        model = f"e2e-cohere-chat-{unique_marker()}"
        model_id = client.proxy.create_model(
            model,
            LiteLLMParamsBody(model=COHERE_BACKEND, api_key=cohere_key),
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=f"Reply with the single word pong. {unique_marker()}",
                        )
                    ],
                    max_tokens=32,
                ),
            )
        )
        assert response.choices, f"cohere chat returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content and content.strip(), f"cohere empty content: {response}"


class TestGeminiChatCompletions:
    """Gemini via the OpenAI-compatible /chat/completions path, with cost logging.

    Complements the native /gemini passthrough suite by covering the translation
    path customers use when they keep the OpenAI SDK.
    """

    @pytest.mark.covers(
        "llm.chat_completions.gemini.basic.nonstream.works",
        "llm.chat_completions.gemini.basic.nonstream.cost_logged",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.GEMINI,),
            models=(GEMINI_BACKEND,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_gemini_chat_returns_content_and_logs_cost(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-gemini-chat-{unique_marker()}"
        model_id = client.proxy.create_model(
            model,
            LiteLLMParamsBody(model=GEMINI_BACKEND, api_key="os.environ/GEMINI_API_KEY"),
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()
        tag = f"e2e-gemini-chat-{unique_marker()}"

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=f"Reply with the single word pong. marker={tag}",
                        )
                    ],
                    max_tokens=64,
                    reasoning_effort="none",
                ),
            )
        )
        assert response.choices, f"gemini chat returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content, f"gemini chat returned empty content: {response}"

        rows = client.proxy.poll_logs_for_key(
            key,
            min_rows=1,
            predicate=lambda rs: any((r.spend or 0) > 0 for r in rs),
        )
        assert rows, f"no SpendLogs row for gemini chat on key ending ...{key[-6:]}"
        row = rows[0]
        assert (row.spend or 0) > 0, f"gemini chat was not costed: {row}"
        assert row.status == "success", f"gemini chat spend status={row.status!r}"


class TestVertexChatCompletions:
    def _register(self, client: PassthroughClient, resources: ResourceManager, prefix: str) -> str:
        model = f"{prefix}-{unique_marker()}"
        model_id = client.proxy.create_model(
            model,
            LiteLLMParamsBody(
                model=VERTEX_BACKEND,
                vertex_project="os.environ/VERTEXAI_PROJECT",
                vertex_location="us-central1",
            ),
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        return model

    @pytest.mark.covers(
        "llm.chat_completions.vertex.basic.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.VERTEX_AI,),
            models=(VERTEX_BACKEND,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_vertex_chat_returns_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-vertex-chat")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=f"Reply with the single word pong. {unique_marker()}",
                        )
                    ],
                    max_tokens=32,
                ),
            )
        )
        assert response.choices, f"vertex chat returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content and content.strip(), f"vertex chat returned empty content: {response}"

    @pytest.mark.covers(
        "llm.chat_completions.vertex.tool_use.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.VERTEX_AI,),
            models=(VERTEX_BACKEND,),
            capabilities=(Capability.FUNCTION_CALLING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_vertex_chat_returns_tool_call(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-vertex-tool")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content="What is the weather in San Francisco? Use the get_weather tool.",
                        )
                    ],
                    tools=[_WEATHER_TOOL],
                    tool_choice="required",
                    max_tokens=128,
                ),
            )
        )
        _assert_weather_tool_call(response)

    @pytest.mark.covers(
        "llm.chat_completions.vertex.vision.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.VERTEX_AI,),
            models=(VERTEX_BACKEND,),
            capabilities=(Capability.VISION,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_vertex_chat_vision_describes_image(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-vertex-vision")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key, ChatBody(model=model, messages=_vision_messages(), max_tokens=32, reasoning_effort="none")
            )
        )
        _assert_describes_cat(response)

    @pytest.mark.covers(
        "llm.chat_completions.vertex.basic.stream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.VERTEX_AI,),
            models=(VERTEX_BACKEND,),
            mode=Mode.STREAM,
        )
    )
    def test_vertex_chat_streams_real_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-vertex-stream")
        key = resources.key()

        result = client.proxy.chat_stream(
            key,
            ChatBody(
                model=model,
                messages=[
                    ChatMessage(
                        role="user",
                        content=f"Count from 1 to 5, one number per line. {unique_marker()}",
                    )
                ],
                max_tokens=64,
                stream=True,
            ),
        )
        _assert_streamed_completion(result)


class TestAzureOpenAIChatCompletions:
    def _register(self, client: PassthroughClient, resources: ResourceManager, prefix: str) -> str:
        model = f"{prefix}-{unique_marker()}"
        model_id = client.proxy.create_model(
            model,
            LiteLLMParamsBody(
                model=AZURE_OPENAI_BACKEND,
                api_base="os.environ/AZURE_API_BASE",
                api_key="os.environ/AZURE_API_KEY",
                api_version=AZURE_OPENAI_API_VERSION,
            ),
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        return model

    @pytest.mark.covers(
        "llm.chat_completions.azure_openai.basic.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.AZURE,),
            models=(AZURE_OPENAI_BACKEND,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_azure_openai_chat_returns_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-azure-openai-chat")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=f"Reply with the single word pong. {unique_marker()}",
                        )
                    ],
                    max_tokens=32,
                ),
            )
        )
        assert response.choices, f"azure openai chat returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content and content.strip(), f"azure openai chat returned empty content: {response}"

    @pytest.mark.covers(
        "llm.chat_completions.azure_openai.tool_use.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.AZURE,),
            models=(AZURE_OPENAI_BACKEND,),
            capabilities=(Capability.FUNCTION_CALLING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_azure_openai_chat_returns_tool_call(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-azure-openai-tool")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content="What is the weather in San Francisco? Use the get_weather tool.",
                        )
                    ],
                    tools=[_WEATHER_TOOL],
                    tool_choice="required",
                    max_tokens=128,
                ),
            )
        )
        _assert_weather_tool_call(response)


class TestAzureFoundryChatCompletions:
    @pytest.mark.covers(
        "llm.chat_completions.azure_foundry.basic.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.AZURE_AI,),
            models=(AZURE_FOUNDRY_BACKEND,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_azure_foundry_chat_returns_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-azure-foundry-chat-{unique_marker()}"
        model_id = client.proxy.create_model(
            model,
            LiteLLMParamsBody(
                model=AZURE_FOUNDRY_BACKEND,
                api_base="os.environ/AZURE_AI_API_BASE",
                api_key="os.environ/AZURE_AI_API_KEY",
            ),
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=f"Reply with the single word pong. {unique_marker()}",
                        )
                    ],
                    max_tokens=32,
                ),
            )
        )
        assert response.choices, f"azure foundry chat returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content and content.strip(), f"azure foundry chat returned empty content: {response}"


class TestHostedVllmChat:
    """hosted_vllm (self-hosted OpenAI-compatible server) via /chat/completions."""

    @pytest.mark.covers(
        "llm.chat_completions.hosted_vllm.basic.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.HOSTED_VLLM,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_hosted_vllm_chat_returns_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        api_base = os.environ.get("HOSTED_VLLM_API_BASE")
        if api_base is None:
            pytest.skip(
                "set HOSTED_VLLM_API_BASE (the live vLLM server this deployment targets)"
            )
        backend = (
            os.environ.get("HOSTED_VLLM_MODEL")
            or "Qwen/Qwen2.5-0.5B-Instruct-GGUF:Q4_K_M"
        ).strip()
        model = f"e2e-vllm-chat-{unique_marker()}"
        model_id = client.proxy.create_model(
            model,
            LiteLLMParamsBody(
                model=f"hosted_vllm/{backend}",
                api_base=api_base,
            ),
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=f"Reply with the single word pong. {unique_marker()}",
                        )
                    ],
                    max_tokens=32,
                ),
            )
        )
        assert response.choices, f"hosted_vllm chat returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content and content.strip(), f"hosted_vllm empty content: {response}"


class TestOpenAIChatCompletions:
    """OpenAI /chat/completions, the SDK path the customer runs against the proxy.

    The streamed call must deliver real content deltas (a clean-but-empty stream is
    the regression), and a non-streamed call must be costed so per-request spend and
    the response-cost header stay accurate.
    """

    @pytest.mark.covers(
        "llm.chat_completions.openai.basic.stream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.OPENAI,),
            models=(OPENAI_BACKEND,),
            mode=Mode.STREAM,
        )
    )
    def test_openai_chat_streams_real_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-openai-chat-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        result = client.proxy.chat_stream(
            key,
            ChatBody(
                model=model,
                messages=[
                    ChatMessage(role="user", content=f"Count from 1 to 5, one number per line. {unique_marker()}")
                ],
                max_tokens=64,
                stream=True,
            ),
        )
        _assert_streamed_completion(result)

    @pytest.mark.covers(
        "llm.chat_completions.openai.basic.nonstream.cost_logged",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.SPEND_BUDGETS,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.OPENAI,),
            models=(OPENAI_BACKEND,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_openai_chat_logs_cost(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-openai-cost-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[ChatMessage(role="user", content=f"Reply with the single word pong. {unique_marker()}")],
                    max_tokens=16,
                ),
            )
        )
        assert response.choices, f"openai chat returned no choices: {response}"

        rows = client.proxy.poll_logs_for_key(
            key, min_rows=1, predicate=lambda rs: any((r.spend or 0) > 0 for r in rs)
        )
        priced = [r for r in rows if (r.spend or 0) > 0]
        assert priced, f"openai chat was not costed on key ...{key[-6:]}: {rows}"
        assert priced[0].status == "success", f"openai chat spend status={priced[0].status!r}"

    @pytest.mark.covers(
        "llm.chat_completions.openai.tool_use.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.OPENAI,),
            models=(OPENAI_BACKEND,),
            capabilities=(Capability.FUNCTION_CALLING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_openai_chat_returns_tool_call(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-openai-tool-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(role="user", content="What is the weather in San Francisco? Use the get_weather tool.")
                    ],
                    tools=[_WEATHER_TOOL],
                    tool_choice="required",
                    max_tokens=128,
                    reasoning_effort="none",
                ),
            )
        )
        _assert_weather_tool_call(response)

    @pytest.mark.covers(
        "llm.chat_completions.openai.structured_output.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.OPENAI,),
            models=(OPENAI_BACKEND,),
            capabilities=(Capability.RESPONSE_SCHEMA,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_openai_chat_structured_output_conforms_to_schema(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-openai-schema-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[ChatMessage(role="user", content="Extract the person. John Doe is 42 years old.")],
                    response_format=_PERSON_SCHEMA,
                    max_tokens=128,
                ),
            )
        )
        assert response.choices, f"structured output returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content, f"structured output returned empty content: {response}"
        person = _Person.model_validate_json(content)
        assert person.name.strip() and person.age == 42, (
            f"schema-constrained extraction was wrong: {person}"
        )

    @pytest.mark.covers(
        "llm.chat_completions.openai.thinking.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.OPENAI,),
            models=(OPENAI_BACKEND,),
            capabilities=(Capability.REASONING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_openai_chat_reasoning_reports_reasoning_tokens(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-openai-reasoning-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        # The prompt and effort have to make the model actually think,
                        # otherwise this asserts something the model is free not to do:
                        # at reasoning_effort="low" a one-step arithmetic question comes
                        # back with reasoning_tokens=0, which is correct behavior and not
                        # a reporting bug. Verified against the live model:
                        # low + "60 miles in 1.5 hours" -> reasoning_tokens=0,
                        # high + the prompt below       -> reasoning_tokens=90.
                        # What is under test is that litellm surfaces the field, so the
                        # request has to be one where the field is populated.
                        ChatMessage(
                            role="user",
                            content=(
                                "Prove that the sum of two odd integers is even, then find the "
                                "smallest prime p greater than 100 such that p+2 is also prime."
                            ),
                        )
                    ],
                    reasoning_effort="high",
                    max_tokens=3000,
                ),
            )
        )
        assert response.choices, f"reasoning call returned no choices: {response}"
        message = response.choices[0].message
        assert message and message.content and message.content.strip(), f"reasoning call had no answer: {response}"
        details = response.usage.completion_tokens_details if response.usage else None
        assert details and details.reasoning_tokens and details.reasoning_tokens > 0, (
            f"a reasoning model must report reasoning tokens, got usage={response.usage}"
        )

    @pytest.mark.covers(
        "llm.chat_completions.openai.vision.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.OPENAI,),
            models=(OPENAI_VISION_BACKEND,),
            capabilities=(Capability.VISION,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_openai_chat_vision_describes_image(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-openai-vision-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=OPENAI_VISION_BACKEND, api_key="os.environ/OPENAI_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(client.proxy.chat(key, ChatBody(model=model, messages=_vision_messages(), max_tokens=32)))
        _assert_describes_cat(response)

    @pytest.mark.covers(
        "llm.chat_completions.openai.tool_use.stream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.OPENAI,),
            models=(OPENAI_BACKEND,),
            capabilities=(Capability.FUNCTION_CALLING,),
            mode=Mode.STREAM,
        )
    )
    def test_openai_chat_streams_tool_call(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-openai-tool-stream-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        result = client.proxy.chat_stream(
            key,
            ChatBody(
                model=model,
                messages=[
                    ChatMessage(role="user", content="What is the weather in San Francisco? Use the get_weather tool.")
                ],
                tools=[_WEATHER_TOOL],
                tool_choice="required",
                max_tokens=128,
                reasoning_effort="none",
                stream=True,
            ),
        )
        assert result.ok and result.is_streaming, f"tool stream was not established: {result}"
        assert result.stream_error is None, f"tool stream carried an error event: {result.stream_error}"
        name, arguments = _streamed_tool_call(result.stream_events)
        assert name == "get_weather", f"streamed tool call named {name!r}: {result.stream_events[:5]}"
        args = _WeatherArgs.model_validate_json(arguments)
        assert args.location.strip(), f"streamed tool call arguments missing location: {arguments!r}"


class TestBedrockConverseChatCompletions:
    """Bedrock Converse via /chat/completions, the customer's AWS stack. A non-OpenAI
    provider must return real content on both the non-streamed and streamed paths.
    """

    def _register(self, client: PassthroughClient, resources: ResourceManager, prefix: str) -> str:
        model = f"{prefix}-{unique_marker()}"
        model_id = client.proxy.create_model(model, _bedrock_params())
        resources.defer(lambda: client.proxy.delete_model(model_id))
        return model

    @pytest.mark.covers(
        "llm.chat_completions.bedrock_converse.basic.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.BEDROCK,),
            models=(BEDROCK_CONVERSE_BACKEND,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_bedrock_converse_chat_returns_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-bedrock-chat")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[ChatMessage(role="user", content=f"Reply with the single word pong. {unique_marker()}")],
                    max_tokens=32,
                ),
            )
        )
        assert response.choices, f"bedrock converse chat returned no choices: {response}"
        content = response.choices[0].message.content if response.choices[0].message else None
        assert content and content.strip(), f"bedrock converse returned empty content: {response}"

    @pytest.mark.covers(
        "llm.chat_completions.bedrock_converse.basic.stream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.BEDROCK,),
            models=(BEDROCK_CONVERSE_BACKEND,),
            mode=Mode.STREAM,
        )
    )
    def test_bedrock_converse_chat_streams_real_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-bedrock-stream")
        key = resources.key()

        result = client.proxy.chat_stream(
            key,
            ChatBody(
                model=model,
                messages=[
                    ChatMessage(role="user", content=f"Count from 1 to 5, one number per line. {unique_marker()}")
                ],
                max_tokens=64,
                stream=True,
            ),
        )
        _assert_streamed_completion(result)

    @pytest.mark.covers(
        "llm.chat_completions.bedrock_converse.tool_use.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.BEDROCK,),
            models=(BEDROCK_CONVERSE_BACKEND,),
            capabilities=(Capability.FUNCTION_CALLING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_bedrock_converse_chat_returns_tool_call(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-bedrock-tool")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(role="user", content="What is the weather in San Francisco? Use the get_weather tool.")
                    ],
                    tools=[_WEATHER_TOOL],
                    tool_choice="required",
                    max_tokens=128,
                ),
            )
        )
        _assert_weather_tool_call(response)

    @pytest.mark.covers(
        "llm.chat_completions.bedrock_converse.thinking.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.BEDROCK,),
            models=(BEDROCK_CONVERSE_BACKEND,),
            capabilities=(Capability.REASONING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_bedrock_converse_chat_returns_reasoning(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-bedrock-thinking")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[ChatMessage(role="user", content="What is 17 times 23? Think it through step by step.")],
                    thinking=ThinkingParam(type="enabled", budget_tokens=1024),
                    max_tokens=2048,
                ),
            )
        )
        assert response.choices, f"bedrock thinking returned no choices: {response}"
        message = response.choices[0].message
        assert message and message.content and message.content.strip(), (
            f"bedrock thinking returned no answer content: {response}"
        )
        assert message.reasoning_content and message.reasoning_content.strip(), (
            "thinking was enabled but no reasoning_content came back on the Bedrock Converse path"
        )

    @pytest.mark.covers(
        "llm.chat_completions.bedrock_converse.vision.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.BEDROCK,),
            models=(BEDROCK_CONVERSE_BACKEND,),
            capabilities=(Capability.VISION,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_bedrock_converse_chat_vision_describes_image(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-bedrock-vision")
        key = resources.key()

        response = unwrap(client.proxy.chat(key, ChatBody(model=model, messages=_vision_messages(), max_tokens=32)))
        _assert_describes_cat(response)

    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.BEDROCK,),
            models=(BEDROCK_NOVA_BACKEND,),
            capabilities=(Capability.PDF_INPUT,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_bedrock_converse_reads_a_pdf_sent_by_url(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = f"e2e-bedrock-document-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, _bedrock_params().model_copy(update={"model": BEDROCK_NOVA_BACKEND})
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=[
                                TextContentPart(text="What title text is in this document? Reply with it only."),
                                ImageContentPart(image_url=ImageUrl(url=PDF_DOCUMENT_URL)),
                            ],
                        )
                    ],
                    max_tokens=64,
                ),
            )
        )
        message = response.choices[0].message if response.choices else None
        content = (message.content if message else "") or ""
        assert PDF_DOCUMENT_TEXT in content.lower(), f"model did not read the PDF document block: {response}"


class _PartnerDelta(BaseModel):
    role: str | None = None
    content: str | None = None


class _PartnerChoice(BaseModel):
    delta: _PartnerDelta = _PartnerDelta()
    finish_reason: str | None = None


class _PartnerChunk(BaseModel):
    choices: list[_PartnerChoice] = []


class TestVertexPartnerChatCompletions:
    @pytest.mark.parametrize("backend", VERTEX_PARTNER_BACKENDS)
    def test_vertex_partner_model_streams_openai_shaped_chunks(
        self, client: PassthroughClient, resources: ResourceManager, backend: str
    ) -> None:
        model = f"e2e-vertex-partner-{unique_marker()}"
        model_id = client.proxy.create_model(
            model,
            LiteLLMParamsBody(
                model=backend, vertex_project="os.environ/VERTEXAI_PROJECT", vertex_location="us-central1"
            ),
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        key = resources.key()

        result = client.proxy.chat_stream(
            key,
            ChatBody(
                model=model,
                messages=[
                    ChatMessage(role="user", content=f"Count from 1 to 5, one number per line. {unique_marker()}")
                ],
                max_tokens=256,
                stream=True,
            ),
        )
        assert result.ok and result.is_streaming, f"stream was not established: {result}"
        assert result.stream_error is None, f"stream carried an error event: {result.stream_error}"
        assert result.stream_done, "stream must terminate with [DONE]"
        chunks = tuple(_PartnerChunk.model_validate_json(event) for event in result.stream_events)
        choices = tuple(choice for chunk in chunks for choice in chunk.choices)
        assert choices and choices[0].delta.role == "assistant", (
            f"first chunk must carry the assistant role: {chunks[:2]}"
        )
        terminal = tuple(index for index, choice in enumerate(choices) if choice.finish_reason is not None)
        assert len(terminal) == 1, f"expected exactly one terminal choice: {[c.finish_reason for c in choices]}"
        text = "".join(choice.delta.content or "" for choice in choices[: terminal[0] + 1])
        assert "5" in text, f"streamed text lost the requested content: {text!r}"


class TestAnthropicChatCompletions:
    """Anthropic via the OpenAI-compatible /chat/completions path, the translation
    customers on the OpenAI SDK rely on when they route to Claude. The streamed call
    must deliver real content deltas, and a tool-forced call must come back as a
    well-formed tool_call on both the non-streamed and streamed paths.
    """

    def _register(self, client: PassthroughClient, resources: ResourceManager, prefix: str) -> str:
        model = f"{prefix}-{unique_marker()}"
        model_id = client.proxy.create_model(
            model, LiteLLMParamsBody(model=ANTHROPIC_BACKEND, api_key="os.environ/ANTHROPIC_API_KEY")
        )
        resources.defer(lambda: client.proxy.delete_model(model_id))
        return model

    @pytest.mark.covers(
        "llm.chat_completions.anthropic.structured_output.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.ANTHROPIC,),
            models=(ANTHROPIC_BACKEND,),
            capabilities=(Capability.RESPONSE_SCHEMA,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_anthropic_chat_structured_output_conforms_to_schema(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-anthropic-schema")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content="Extract the person. John Doe is 42 years old.",
                        )
                    ],
                    response_format=_PERSON_SCHEMA,
                    max_tokens=128,
                ),
            )
        )
        assert response.choices, f"anthropic structured output returned no choices: {response}"
        message = response.choices[0].message
        content = message.content if message else None
        assert content, f"anthropic structured output returned empty content: {response}"
        person = _Person.model_validate_json(content)
        assert person.name.strip() and person.age == 42, f"anthropic schema output was wrong: {person}"

    @pytest.mark.covers(
        "llm.chat_completions.anthropic.thinking.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.ANTHROPIC,),
            models=(ANTHROPIC_BACKEND,),
            capabilities=(Capability.REASONING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_anthropic_chat_returns_thinking_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-anthropic-thinking")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(
                            role="user",
                            content=(
                                "Prove that the sum of two odd integers is even, then find the smallest prime "
                                "greater than 100 such that p+2 is also prime."
                            ),
                        )
                    ],
                    thinking=ThinkingParam(type="enabled", budget_tokens=1024),
                    max_tokens=2048,
                ),
            )
        )
        assert response.choices, f"anthropic thinking returned no choices: {response}"
        message = response.choices[0].message
        assert message and message.content and message.content.strip(), (
            f"anthropic thinking returned no answer content: {response}"
        )
        assert message.reasoning_content and message.reasoning_content.strip(), (
            f"anthropic thinking returned no reasoning content: {response}"
        )

    @pytest.mark.covers(
        "llm.chat_completions.anthropic.vision.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.ANTHROPIC,),
            models=(ANTHROPIC_BACKEND,),
            capabilities=(Capability.VISION,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_anthropic_chat_vision_describes_image(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-anthropic-vision")
        key = resources.key()

        response = unwrap(client.proxy.chat(key, ChatBody(model=model, messages=_vision_messages(), max_tokens=32)))
        _assert_describes_cat(response)

    @pytest.mark.covers(
        "llm.chat_completions.anthropic.basic.stream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.ANTHROPIC,),
            models=(ANTHROPIC_BACKEND,),
            mode=Mode.STREAM,
        )
    )
    def test_anthropic_chat_streams_real_content(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-anthropic-stream")
        key = resources.key()

        result = client.proxy.chat_stream(
            key,
            ChatBody(
                model=model,
                messages=[
                    ChatMessage(role="user", content=f"Count from 1 to 5, one number per line. {unique_marker()}")
                ],
                max_tokens=64,
                stream=True,
            ),
        )
        _assert_streamed_completion(result)

    @pytest.mark.covers(
        "llm.chat_completions.anthropic.tool_use.nonstream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.ANTHROPIC,),
            models=(ANTHROPIC_BACKEND,),
            capabilities=(Capability.FUNCTION_CALLING,),
            mode=Mode.NONSTREAM,
        )
    )
    def test_anthropic_chat_returns_tool_call(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-anthropic-tool")
        key = resources.key()

        response = unwrap(
            client.proxy.chat(
                key,
                ChatBody(
                    model=model,
                    messages=[
                        ChatMessage(role="user", content="What is the weather in San Francisco? Use the get_weather tool.")
                    ],
                    tools=[_WEATHER_TOOL],
                    tool_choice="required",
                    max_tokens=128,
                ),
            )
        )
        _assert_weather_tool_call(response)

    @pytest.mark.covers(
        "llm.chat_completions.anthropic.tool_use.stream.works",
        exercised_on=["chat_completions"],
    )
    @meta(
        Subject(
            domain=Domain.LLM_TRANSLATION,
            route=Route.CHAT_COMPLETIONS,
            providers=(Provider.ANTHROPIC,),
            models=(ANTHROPIC_BACKEND,),
            capabilities=(Capability.FUNCTION_CALLING,),
            mode=Mode.STREAM,
        )
    )
    def test_anthropic_chat_streams_tool_call(
        self, client: PassthroughClient, resources: ResourceManager
    ) -> None:
        model = self._register(client, resources, "e2e-anthropic-tool-stream")
        key = resources.key()

        result = client.proxy.chat_stream(
            key,
            ChatBody(
                model=model,
                messages=[
                    ChatMessage(role="user", content="What is the weather in San Francisco? Use the get_weather tool.")
                ],
                tools=[_WEATHER_TOOL],
                tool_choice="required",
                max_tokens=128,
                stream=True,
            ),
        )
        assert result.ok and result.is_streaming, f"tool stream was not established: {result}"
        assert result.stream_error is None, f"tool stream carried an error event: {result.stream_error}"
        name, arguments = _streamed_tool_call(result.stream_events)
        assert name == "get_weather", f"streamed tool call named {name!r}: {result.stream_events[:5]}"
        args = _WeatherArgs.model_validate_json(arguments)
        assert args.location.strip(), f"streamed tool call arguments missing location: {arguments!r}"