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]

412 KB
Raw Blame
import base64
import copy
import json
import os
import re
from collections.abc import Iterator, Mapping
from typing import Final
from unittest.mock import MagicMock, Mock, patch

import httpx
import pytest
import respx

import litellm
from litellm import ModelResponse, Router, completion
from litellm.litellm_core_utils.prompt_templates.factory import (
    _bedrock_converse_messages_pt,
    _bedrock_tools_pt,
)
from litellm.litellm_core_utils.prompt_templates.mid_conversation_system import CONVERTED_SYSTEM_NOTE
from litellm.llms.anthropic.chat.transformation import (
    NATIVE_OUTPUT_MAX_GRAMMAR_BRANCHES,
    NATIVE_OUTPUT_MAX_OPTIONAL_PARAMETERS,
    NATIVE_OUTPUT_MAX_UNION_PARAMETERS,
)
from litellm.llms.bedrock.common_utils import BEDROCK_NATIVE_OUTPUT_MAX_PROPERTIES
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
from litellm.types.llms.bedrock import ContentBlock, ConverseTokenUsageBlock, RequestObject
from litellm.types.llms.openai import AllMessageValues


def test_transform_usage():
    usage = ConverseTokenUsageBlock(
        **{
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 1789,
            "cacheWriteInputTokens": 1789,
            "inputTokens": 3,
            "outputTokens": 401,
            "totalTokens": 2193,
        }
    )
    config = AmazonConverseConfig()
    openai_usage = config.transform_usage(usage)
    assert (
        openai_usage.prompt_tokens
        == usage["inputTokens"] + usage["cacheReadInputTokens"] + usage["cacheWriteInputTokens"]
    )
    assert openai_usage.completion_tokens == usage["outputTokens"]
    assert openai_usage.total_tokens == usage["totalTokens"]
    assert openai_usage.prompt_tokens_details.cached_tokens == usage["cacheReadInputTokens"]
    assert openai_usage._cache_creation_input_tokens == usage["cacheWriteInputTokens"]
    assert openai_usage._cache_read_input_tokens == usage["cacheReadInputTokens"]
    # completion_tokens_details should always be populated
    assert openai_usage.completion_tokens_details is not None
    assert openai_usage.completion_tokens_details.reasoning_tokens == 0
    assert openai_usage.completion_tokens_details.text_tokens == usage["outputTokens"]


def test_transform_usage_with_cache_details():
    """cacheDetails should split cacheWriteInputTokens into the 5m/1h TTL breakdown
    so cost calc can bill the 1h portion at its own (higher) rate instead of
    defaulting the whole write to the 5m rate. See issue #36760."""
    usage = ConverseTokenUsageBlock(
        **{
            "inputTokens": 76,
            "outputTokens": 259,
            "totalTokens": 335,
            "cacheWriteInputTokens": 362,
            "cacheDetails": [
                {"inputTokens": 74, "ttl": "1h"},
                {"inputTokens": 288, "ttl": "5m"},
            ],
        }
    )
    config = AmazonConverseConfig()
    openai_usage = config.transform_usage(usage)
    details = openai_usage.prompt_tokens_details.cache_creation_token_details
    assert details is not None
    assert details.ephemeral_1h_input_tokens == 74
    assert details.ephemeral_5m_input_tokens == 288


def test_transform_usage_with_mismatched_cache_details_falls_back():
    """An unrecognized ttl or partial breakdown must not silently understate
    cache-write cost, so the split is only used when it fully accounts for
    cacheWriteInputTokens."""
    usage = ConverseTokenUsageBlock(
        **{
            "inputTokens": 76,
            "outputTokens": 259,
            "totalTokens": 335,
            "cacheWriteInputTokens": 362,
            "cacheDetails": [{"inputTokens": 74, "ttl": "1h"}],  # missing the 5m entry
        }
    )
    config = AmazonConverseConfig()
    openai_usage = config.transform_usage(usage)
    assert getattr(openai_usage.prompt_tokens_details, "cache_creation_token_details", None) is None


def test_transform_usage_without_cache_details_stays_none():
    """No cacheDetails in the response (older models/regions) should leave
    cache_creation_token_details unset, same as before this field existed."""
    usage = ConverseTokenUsageBlock(
        **{
            "inputTokens": 3,
            "outputTokens": 401,
            "totalTokens": 2193,
            "cacheWriteInputTokens": 1789,
        }
    )
    config = AmazonConverseConfig()
    openai_usage = config.transform_usage(usage)
    assert getattr(openai_usage.prompt_tokens_details, "cache_creation_token_details", None) is None


def test_bedrock_converse_1h_cache_write_billed_at_1h_rate(monkeypatch):
    """Regression for issue #36760: without the cacheDetails split, the whole
    write is billed at the (cheaper) 5m rate."""
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))
    usage = ConverseTokenUsageBlock(
        **{
            "inputTokens": 16,
            "outputTokens": 4,
            "totalTokens": 11652,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokens": 11632,
            "cacheDetails": [{"inputTokens": 11632, "ttl": "1h"}],
        }
    )
    openai_usage = AmazonConverseConfig().transform_usage(usage)
    model = "bedrock/converse/global.anthropic.claude-opus-4-8"
    prompt_cost, completion_cost = litellm.cost_calculator.cost_per_token(model=model, usage_object=openai_usage)
    model_info = litellm.get_model_info(model=model)
    expected_prompt_cost = (
        16 * model_info["input_cost_per_token"] + 11632 * model_info["cache_creation_input_token_cost_above_1hr"]
    )
    assert prompt_cost == pytest.approx(expected_prompt_cost)
    assert prompt_cost > 16 * model_info["input_cost_per_token"] + 11632 * model_info["cache_creation_input_token_cost"]
    assert completion_cost == pytest.approx(4 * model_info["output_cost_per_token"])


@pytest.mark.parametrize(
    "usage, expected_prompt_tokens, expected_cached_tokens, expected_cache_creation_tokens",
    [
        pytest.param(
            {
                "inputTokens": 5,
                "outputTokens": 3,
                "totalTokens": 12270,
                "cacheReadInputTokenCount": 12262,
                "cacheWriteInputTokenCount": 0,
            },
            12267,
            12262,
            0,
            id="invoke-model-cache-read",
        ),
        pytest.param(
            {
                "inputTokens": 5,
                "outputTokens": 3,
                "totalTokens": 12270,
                "cacheReadInputTokenCount": 0,
                "cacheWriteInputTokenCount": 12262,
            },
            12267,
            0,
            12262,
            id="invoke-model-cache-write",
        ),
        pytest.param(
            {
                "inputTokens": 5,
                "outputTokens": 3,
                "cacheReadInputTokenCount": 12262,
                "cacheWriteInputTokenCount": 0,
            },
            12267,
            12262,
            0,
            id="invoke-model-streaming-metadata-without-totalTokens",
        ),
    ],
)
def test_transform_usage_reads_invoke_model_count_suffixed_cache_keys(
    usage, expected_prompt_tokens, expected_cached_tokens, expected_cache_creation_tokens
):
    """InvokeModel Nova reports ``cacheReadInputTokenCount`` and ``cacheWriteInputTokenCount``
    where Converse reports the un-suffixed keys, and ``inputTokens`` excludes both."""
    openai_usage = AmazonConverseConfig().transform_usage(ConverseTokenUsageBlock(**usage))
    assert openai_usage.prompt_tokens == expected_prompt_tokens
    assert openai_usage.prompt_tokens_details.cached_tokens == expected_cached_tokens
    assert openai_usage._cache_read_input_tokens == expected_cached_tokens
    assert openai_usage._cache_creation_input_tokens == expected_cache_creation_tokens
    assert openai_usage.completion_tokens == 3
    assert openai_usage.total_tokens == 12270


def test_bedrock_invoke_nova_cache_read_billed_at_discounted_rate(monkeypatch):
    """Nova cache reads are billed at the entry's discounted cache read rate; without a
    ``cache_read_input_token_cost`` entry the cached tokens were billed at nothing."""
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))
    usage = ConverseTokenUsageBlock(
        **{
            "inputTokens": 5,
            "outputTokens": 3,
            "totalTokens": 12270,
            "cacheReadInputTokenCount": 12262,
            "cacheWriteInputTokenCount": 0,
        }
    )
    openai_usage = AmazonConverseConfig().transform_usage(usage)
    model = "bedrock/invoke/us.amazon.nova-pro-v1:0"
    prompt_cost, completion_cost = litellm.cost_calculator.cost_per_token(model=model, usage_object=openai_usage)
    model_info = litellm.get_model_info(model=model)
    assert 0 < model_info["cache_read_input_token_cost"] < model_info["input_cost_per_token"]
    assert prompt_cost == pytest.approx(
        5 * model_info["input_cost_per_token"] + 12262 * model_info["cache_read_input_token_cost"]
    )
    assert prompt_cost > 5 * model_info["input_cost_per_token"]
    assert completion_cost == pytest.approx(3 * model_info["output_cost_per_token"])


def test_transform_usage_with_reasoning_content():
    """Test that completion_tokens_details correctly tracks reasoning vs text tokens."""
    usage = ConverseTokenUsageBlock(
        **{
            "inputTokens": 10,
            "outputTokens": 100,
            "totalTokens": 110,
        }
    )
    config = AmazonConverseConfig()
    reasoning_text = "Let me think about this step by step."
    openai_usage = config.transform_usage(usage, reasoning_content=reasoning_text)
    assert openai_usage.completion_tokens_details is not None
    assert openai_usage.completion_tokens_details.reasoning_tokens > 0
    assert openai_usage.completion_tokens_details.text_tokens == (
        usage["outputTokens"] - openai_usage.completion_tokens_details.reasoning_tokens
    )


def test_transform_system_message():
    config = AmazonConverseConfig()

    # Case 1:
    # System message popped
    # User message remains
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages.copy())
    assert len(out_messages) == 1
    assert out_messages[0]["role"] == "user"
    assert len(system_blocks) == 1
    assert system_blocks[0]["text"] == "You are a helpful assistant."

    # Case 2: System message with list content (type text)
    messages = [
        {
            "role": "system",
            "content": [
                {"type": "text", "text": "System prompt 1"},
                {"type": "text", "text": "System prompt 2"},
            ],
        },
        {"role": "user", "content": "Hi!"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages.copy())
    assert len(out_messages) == 1
    assert out_messages[0]["role"] == "user"
    assert len(system_blocks) == 2
    assert system_blocks[0]["text"] == "System prompt 1"
    assert system_blocks[1]["text"] == "System prompt 2"

    # Case 3: System message with cache_control (should add cachePoint)
    messages = [
        {
            "role": "system",
            "content": "Cache this!",
            "cache_control": {"type": "ephemeral"},
        },
        {"role": "user", "content": "Hi!"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages.copy())
    assert len(out_messages) == 1
    assert len(system_blocks) == 2
    assert system_blocks[0]["text"] == "Cache this!"
    assert "cachePoint" in system_blocks[1]
    assert system_blocks[1]["cachePoint"]["type"] == "default"

    # Case 3b: System message with two blocks, one with cache_control and one without
    messages = [
        {
            "role": "system",
            "content": [
                {
                    "type": "text",
                    "text": "Cache this!",
                    "cache_control": {"type": "ephemeral"},
                },
                {"type": "text", "text": "Don't cache this!"},
            ],
        },
        {"role": "user", "content": "Hi!"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages.copy())
    assert len(out_messages) == 1
    assert len(system_blocks) == 3
    assert system_blocks[0]["text"] == "Cache this!"
    assert "cachePoint" in system_blocks[1]
    assert system_blocks[1]["cachePoint"]["type"] == "default"
    assert system_blocks[2]["text"] == "Don't cache this!"

    # Case 4: Non-system messages are not affected
    messages = [
        {"role": "user", "content": "Hello!"},
        {"role": "assistant", "content": "Hi!"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages.copy())
    assert len(out_messages) == 2
    assert out_messages[0]["role"] == "user"
    assert out_messages[1]["role"] == "assistant"
    assert system_blocks == []


@pytest.mark.parametrize(
    ("system", "expected_system"),
    [
        ("You are an AI", [{"text": "You are an AI"}]),
        ([{"type": "text", "text": "You are an AI"}], [{"text": "You are an AI"}]),
        ("", []),
    ],
)
def test_bedrock_system_prompt_variants_keep_continue_message(
    system: str | list[dict[str, str]], expected_system: list[dict[str, str]]
) -> None:
    request: Final = AmazonConverseConfig()._transform_request(
        model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        messages=[
            {"role": "system", "content": system},
            {"role": "assistant", "content": "hey, how's it going?"},
        ],
        optional_params={"maxTokens": 100, "temperature": 0.3},
        litellm_params={"user_continue_message": {"role": "user", "content": "Be a good bot!"}},
        headers={},
    )

    assert request.get("system", []) == expected_system
    assert request["messages"] == [
        {"role": "user", "content": [{"text": "Be a good bot!"}]},
        {"role": "assistant", "content": [{"text": "hey, how's it going?"}]},
        {"role": "user", "content": [{"text": "Be a good bot!"}]},
    ]


@pytest.mark.respx(assert_all_called=True)
def test_bedrock_json_schema_description_is_sent_in_request(respx_mock: respx.Router) -> None:
    description: Final = "Find the meaning inside a poem"
    route: Final = respx_mock.post(
        "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.amazon.nova-pro-v1%3A0/converse"
    ).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )
    litellm.completion(
        model="bedrock/us.amazon.nova-pro-v1:0",
        messages=[{"role": "user", "content": "What is the meaning of this poem?"}],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "meaning_reasoning",
                "description": description,
                "schema": {
                    "type": "object",
                    "properties": {"meaning": {"type": "string"}},
                },
            },
        },
        aws_access_key_id="AKIADESCRIPTIONKEY",
        aws_secret_access_key="description-secret",
        aws_region_name="us-west-2",
        client=HTTPHandler(),
    )
    request_body: Final = json.loads(route.calls[0].request.content)

    assert request_body["toolConfig"]["tools"][0]["toolSpec"]["description"] == description


def test_bedrock_empty_text_block_is_removed_from_converse_request() -> None:
    request: Final = AmazonConverseConfig()._transform_request(
        model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": ""},
                    {"type": "text", "text": "Hey, how's it going?"},
                ],
            }
        ],
        optional_params={"maxTokens": 10},
        litellm_params={},
        headers={},
    )

    assert request["messages"] == [{"role": "user", "content": [{"text": "Hey, how's it going?"}]}]


@pytest.mark.asyncio
async def test_bedrock_max_completion_tokens_become_converse_max_tokens() -> None:
    requests: Final[list[httpx.Request]] = []

    def respond(request: httpx.Request) -> httpx.Response:
        requests.append(request)
        return httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
            request=request,
        )

    await litellm.acompletion(
        model="bedrock/converse/mistral.mistral-large-2407-v1:0",
        messages=[{"role": "user", "content": "Hello!"}],
        max_completion_tokens=10,
        aws_access_key_id="AKIAMAXTOKENKEY",
        aws_secret_access_key="max-token-secret",
        aws_region_name="us-west-2",
        client=AsyncHTTPHandler(transport=httpx.MockTransport(respond)),
    )
    request: Final = requests[0]
    request_body: Final = json.loads(request.content)

    assert request.url.path.endswith("/converse")
    assert request_body["inferenceConfig"] == {"maxTokens": 10}


@pytest.mark.parametrize("parameter", ["top_k", "topK"])
@pytest.mark.respx(assert_all_called=True)
def test_bedrock_nova_top_k_aliases_are_forwarded(parameter: str, respx_mock: respx.Router) -> None:
    route: Final = respx_mock.post(
        "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.amazon.nova-pro-v1%3A0/converse"
    ).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )
    litellm.completion(
        model="bedrock/us.amazon.nova-pro-v1:0",
        messages=[{"role": "user", "content": "Hello, world!"}],
        aws_access_key_id="AKIANOVATOPKKEY",
        aws_secret_access_key="nova-top-k-secret",
        aws_region_name="us-west-2",
        client=HTTPHandler(),
        **{parameter: 10},
    )
    request_body: Final = json.loads(route.calls[0].request.content)

    assert request_body["additionalModelRequestFields"]["inferenceConfig"]["topK"] == 10


@pytest.mark.parametrize(
    ("model_id", "expected_url"),
    [
        (
            "arn:aws:bedrock:us-west-2:888602223428:provisioned-model/8fxff74qyhs3",
            "https://bedrock-runtime.us-west-2.amazonaws.com/model/"
            "arn%3Aaws%3Abedrock%3Aus-west-2%3A888602223428%3Aprovisioned-model%2F8fxff74qyhs3/converse",
        ),
        (
            "arn:aws:bedrock:eu-central-1:000000000000:application-inference-profile/a0a0a0a0a0a0",
            "https://bedrock-runtime.eu-central-1.amazonaws.com/model/"
            "arn%3Aaws%3Abedrock%3Aeu-central-1%3A000000000000%3Aapplication-inference-profile%2Fa0a0a0a0a0a0/converse",
        ),
    ],
)
@pytest.mark.respx(assert_all_called=True)
def test_bedrock_model_id_arn_sets_converse_url_and_region(
    model_id: str, expected_url: str, respx_mock: respx.Router, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setenv("AWS_REGION_NAME", "ap-south-1")
    route: Final = respx_mock.post(expected_url).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )

    response: Final = litellm.completion(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=[{"role": "user", "content": "What's AWS?"}],
        model_id=model_id,
        aws_access_key_id="AKIAPTUMODELKEY",
        aws_secret_access_key="ptu-model-secret",
        client=HTTPHandler(),
    )

    assert response.choices[0].message.content == "ok"
    assert str(route.calls[0].request.url) == expected_url


@pytest.mark.respx(assert_all_called=True)
def test_bedrock_application_profile_model_and_model_id_use_same_route(respx_mock: respx.Router) -> None:
    application_profile_arn: Final = (
        "arn:aws:bedrock:eu-central-1:000000000000:application-inference-profile/profile-id"
    )
    route: Final = respx_mock.post(
        "https://bedrock-runtime.eu-central-1.amazonaws.com/model/"
        "arn%3Aaws%3Abedrock%3Aeu-central-1%3A000000000000%3Aapplication-inference-profile%2Fprofile-id/converse"
    ).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "profile"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )
    model_args: Final = {
        "messages": [{"role": "user", "content": "select the application profile"}],
        "aws_access_key_id": "AKIAPROFILEKEY",
        "aws_secret_access_key": "profile-secret",
        "client": HTTPHandler(),
    }
    litellm.completion(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        model_id=application_profile_arn,
        **model_args,
    )
    litellm.completion(model=f"bedrock/converse/{application_profile_arn}", **model_args)

    assert route.call_count == 2


_PROFILE_ARN: Final = "arn:aws:bedrock:us-east-1:000000000000:application-inference-profile/profile-id"
_PROFILE_ARN_CONVERSE_URL: Final = (
    "https://bedrock-runtime.us-east-1.amazonaws.com/model/"
    "arn%3Aaws%3Abedrock%3Aus-east-1%3A000000000000%3Aapplication-inference-profile%2Fprofile-id/converse"
)


def _routed_profile_request_body(
    respx_mock: respx.Router, litellm_params: dict, model_info: dict, **completion_kwargs: object
) -> dict:
    route: Final = respx_mock.post(_PROFILE_ARN_CONVERSE_URL).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )
    router: Final = litellm.Router(
        model_list=[
            {
                "model_name": "claude",
                "litellm_params": {
                    "model": f"bedrock/{_PROFILE_ARN}",
                    "aws_access_key_id": "AKIAPROFILEKEY",
                    "aws_secret_access_key": "profile-secret",
                    "aws_region_name": "us-east-1",
                    **litellm_params,
                },
                "model_info": model_info,
            }
        ]
    )
    router.completion(
        model="claude",
        max_tokens=16000,
        drop_params=True,
        client=HTTPHandler(),
        **{"messages": [{"role": "user", "content": "hi"}], **completion_kwargs},
    )
    return json.loads(route.calls[0].request.content)


def _routed_profile_request_fields(
    respx_mock: respx.Router, litellm_params: dict, model_info: dict, thinking: dict
) -> dict:
    return _routed_profile_request_body(respx_mock, litellm_params, model_info, thinking=thinking).get(
        "additionalModelRequestFields", {}
    )


@pytest.mark.parametrize(
    ("litellm_params", "model_info"),
    [
        ({}, {"base_model": "us.anthropic.claude-opus-4-8"}),
        ({"base_model": "bedrock/us.anthropic.claude-opus-4-8"}, {}),
    ],
    ids=["model_info", "litellm_params"],
)
@pytest.mark.respx(assert_all_called=True)
def test_application_profile_arn_keeps_adaptive_thinking_when_base_model_is_adaptive(
    litellm_params: dict, model_info: dict, respx_mock: respx.Router, local_model_cost_map: None
) -> None:
    thinking: Final = {"type": "adaptive", "display": "summarized"}

    fields: Final = _routed_profile_request_fields(respx_mock, litellm_params, model_info, thinking)

    assert fields["thinking"] == thinking


@pytest.mark.respx(assert_all_called=True)
def test_application_profile_arn_drops_disabled_thinking_when_base_model_always_thinks(
    respx_mock: respx.Router, local_model_cost_map: None
) -> None:
    fields: Final = _routed_profile_request_fields(
        respx_mock, {}, {"base_model": "us.anthropic.claude-fable-5"}, {"type": "disabled"}
    )

    assert "thinking" not in fields


@pytest.mark.respx(assert_all_called=True)
def test_application_profile_arn_without_base_model_warns_when_adaptive_thinking_becomes_a_budget(
    respx_mock: respx.Router, local_model_cost_map: None, caplog: pytest.LogCaptureFixture
) -> None:
    with caplog.at_level("WARNING"):
        fields: Final = _routed_profile_request_fields(respx_mock, {}, {}, {"type": "adaptive"})

    assert fields["thinking"]["type"] == "enabled"
    assert any(
        _PROFILE_ARN in record.getMessage() and "`base_model`" in record.getMessage() for record in caplog.records
    )


_CACHED_FOR_AN_HOUR: Final = {"type": "ephemeral", "ttl": "1h"}
_OPUS: Final = "us.anthropic.claude-opus-4-8"
_LLAMA: Final = "us.meta.llama3-3-70b-instruct-v1:0"


def _cache_points(node: object) -> Iterator[object]:
    if isinstance(node, dict):
        yield from ((node["cachePoint"],) if "cachePoint" in node else ())
        yield from (point for value in node.values() for point in _cache_points(value))
    elif isinstance(node, list):
        yield from (point for item in node for point in _cache_points(item))


@pytest.mark.parametrize(
    ("model_info", "expected_cache_point"),
    [
        ({"base_model": _OPUS}, {"type": "default", "ttl": "1h"}),
        ({"base_model": _OPUS, "supports_prompt_cache_breakpoint": False}, None),
        ({"base_model": _OPUS, "supports_prompt_cache_breakpoint": True}, {"type": "default", "ttl": "1h"}),
        ({"base_model": _LLAMA}, None),
        ({"base_model": _LLAMA, "supports_prompt_cache_breakpoint": True}, {"type": "default"}),
    ],
    ids=[
        "base_model_allows",
        "deployment_disables",
        "deployment_enables_keeps_ttl",
        "base_model_disallows",
        "deployment_enables",
    ],
)
@pytest.mark.respx(assert_all_called=True)
def test_application_profile_arn_cache_points_follow_deployment_setting_then_base_model(
    model_info: dict, expected_cache_point: dict | None, respx_mock: respx.Router, local_model_cost_map: None
) -> None:
    body: Final = _routed_profile_request_body(
        respx_mock,
        {},
        model_info,
        messages=[
            {"role": "system", "content": [{"type": "text", "text": "sys", "cache_control": _CACHED_FOR_AN_HOUR}]},
            {"role": "user", "content": [{"type": "text", "text": "hi", "cache_control": _CACHED_FOR_AN_HOUR}]},
        ],
        tools=[
            {
                "type": "function",
                "function": {"name": "lookup", "parameters": {"type": "object", "properties": {}}},
                "cache_control": _CACHED_FOR_AN_HOUR,
            }
        ],
    )

    expected: Final = [] if expected_cache_point is None else [expected_cache_point] * 3
    assert list(_cache_points(body)) == expected, body


@pytest.mark.respx(assert_all_called=True)
def test_bedrock_cross_region_inference_profile_keeps_prefix_in_converse_url(respx_mock: respx.Router) -> None:
    route: Final = respx_mock.post(
        "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.meta.llama3-3-70b-instruct-v1%3A0/converse"
    ).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "routed"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )

    response: Final = litellm.completion(
        model="bedrock/us.meta.llama3-3-70b-instruct-v1:0",
        messages=[{"role": "user", "content": "route to the cross-region model"}],
        aws_access_key_id="AKIACROSSREGIONKEY",
        aws_secret_access_key="cross-region-secret",
        aws_region_name="us-west-2",
        client=HTTPHandler(),
    )

    assert response.choices[0].message.content == "routed"
    assert route.call_count == 1


@pytest.mark.respx(assert_all_called=True)
def test_bedrock_converse_like_proxy_uses_bearer_api_key(respx_mock: respx.Router) -> None:
    route: Final = respx_mock.post("https://some-api-url/models").mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )
    response: Final = litellm.completion(
        model="bedrock/converse_like/us.amazon.nova-pro-v1:0",
        messages=[{"role": "user", "content": "Tell me a joke"}],
        api_key="Token",
        api_base="https://some-api-url/models",
        client=HTTPHandler(),
    )
    request: Final = route.calls[0].request

    assert request.headers["authorization"] == "Bearer Token"
    assert "x-amz-date" not in request.headers
    assert response.choices[0].message.content == "ok"


def test_transform_thinking_blocks_unwraps_redacted_content_to_claude_native_data():
    """Converse returns Claude's redacted data base64-wrapped. Handing it out as is made the Anthropic API and
    Bedrock Invoke 400 with "Invalid `data` in `redacted_thinking` block" when the history was replayed there."""
    native_data: Final = "EmwKAhgBEgy3va3pzix/LafPsn4aDFIT2Xlxh0L5L8rLVyIwxtE3rAFBa8cr3qpP"
    thinking_blocks: Final = [
        {"reasoningText": {"text": "This is a test", "signature": "test_signature"}},
        {"redactedContent": base64.b64encode(native_data.encode()).decode()},
    ]

    transformed_thinking_blocks: Final = AmazonConverseConfig()._transform_thinking_blocks(thinking_blocks)

    assert transformed_thinking_blocks == [
        {"type": "thinking", "thinking": "This is a test", "signature": "test_signature"},
        {"type": "redacted_thinking", "data": native_data},
    ]


def test_apply_tool_call_transformation_if_needed():
    from litellm.types.utils import Message

    config = AmazonConverseConfig()
    tool_calls = [
        {
            "type": "function",
            "function": {
                "name": "test_function",
                "arguments": "test_arguments",
            },
        },
    ]
    tool_response = {
        "type": "function",
        "name": "test_function",
        "parameters": {"test": "test"},
    }
    message = Message(
        role="user",
        content=json.dumps(tool_response),
    )
    transformed_message, _ = config.apply_tool_call_transformation_if_needed(message, tool_calls)
    assert len(transformed_message.tool_calls) == 1
    assert transformed_message.tool_calls[0].function.name == "test_function"
    assert transformed_message.tool_calls[0].function.arguments == json.dumps(tool_response["parameters"])


def test_transform_tool_call_with_cache_control():
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig

    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "Am I lost?"}]

    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_location",
                "description": "Get the user's location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                    },
                    "required": ["location"],
                },
            },
            "cache_control": {"type": "ephemeral"},
        },
    ]

    result = config._transform_request(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"tools": tools},
        litellm_params={},
        headers={},
    )

    assert "toolConfig" in result
    assert "tools" in result["toolConfig"]

    assert len(result["toolConfig"]["tools"]) == 2

    function_out_msg = result["toolConfig"]["tools"][0]
    print(function_out_msg)
    assert function_out_msg["toolSpec"]["name"] == "get_location"
    assert function_out_msg["toolSpec"]["description"] == "Get the user's location"
    assert function_out_msg["toolSpec"]["inputSchema"]["json"]["properties"]["location"]["type"] == "string"

    transformed_cache_msg = result["toolConfig"]["tools"][1]
    assert "cachePoint" in transformed_cache_msg
    assert transformed_cache_msg["cachePoint"]["type"] == "default"


def test_reasoning_with_forced_tool_choice_switches_to_auto():
    config = AmazonConverseConfig()

    non_default_params = {
        "tools": [
            {
                "type": "function",
                "function": {"name": "get_current_weather", "parameters": {}},
            }
        ],
        "tool_choice": "required",
        "reasoning_effort": "low",
    }

    optional_params = config.map_openai_params(
        model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        non_default_params=non_default_params,
        optional_params={},
        drop_params=False,
    )

    assert optional_params["tool_choice"] == {"auto": {}}


@pytest.mark.parametrize(
    "model, param, value, expected_max_tokens",
    [
        ("us.openai.gpt-6-astra", "max_tokens", 1, 16),
        ("us.openai.gpt-6-astra", "max_completion_tokens", 1, 16),
        ("us.openai.gpt-6-astra", "max_tokens", 64, 64),
        ("us.xai.grok-4.6", "max_tokens", 1, 16),
        ("global.xai.grok-4.6", "max_completion_tokens", 1, 16),
        ("us.xai.grok-4.6", "max_tokens", 32, 32),
        ("us.moonshotai.kimi-k3", "max_tokens", 1, 16),
        ("global.moonshotai.kimi-k3", "max_completion_tokens", 1, 16),
        ("moonshotai.kimi-k3", "max_tokens", 64, 64),
        (
            "arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.moonshotai.kimi-k3",
            "max_tokens",
            1,
            16,
        ),
        ("moonshotai.kimi-k2.5", "max_tokens", 1, 1),
        ("anthropic.claude-sonnet-4-5-20250929-v1:0", "max_tokens", 1, 1),
        ("arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.openai.gpt-6-astra", "max_tokens", 1, 16),
        ("arn:aws:bedrock:us-east-1:123456789012:inference-profile/global.xai.grok-4.6", "max_tokens", 1, 16),
        ("arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123xyz", "max_tokens", 1, 1),
    ],
)
def test_map_openai_params_enforces_minimum_max_tokens_for_openai_compat_models(
    model: str, param: str, value: int, expected_max_tokens: int
):
    optional_params = AmazonConverseConfig().map_openai_params(
        non_default_params={param: value},
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert optional_params["maxTokens"] == expected_max_tokens


@pytest.mark.parametrize(
    "model",
    [
        "us.openai.gpt-5.6-sol",
        "global.openai.gpt-5.6-terra",
        "bedrock/converse/us.openai.gpt-5.6-luna",
        "us.openai.gpt-6-astra",
        "bedrock/converse/global.openai.gpt-6-astra",
    ],
)
def test_reasoning_effort_maps_to_reasoning_effort_for_openai_gpt5_converse(model, local_model_cost_map):
    """OpenAI GPT-5.x on Bedrock Converse routes reasoning_effort to
    ``additionalModelRequestFields.reasoning.effort`` rather than Anthropic ``thinking``."""
    config = AmazonConverseConfig()

    assert "reasoning_effort" in config.get_supported_openai_params(model=model)

    optional_params = config.map_openai_params(
        non_default_params={"reasoning_effort": "high"},
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert optional_params["reasoning"] == {"effort": "high"}
    assert "thinking" not in optional_params
    assert "reasoning_effort" not in optional_params

    _, additional_request_params, _, _ = config._prepare_request_params(optional_params, model)
    assert additional_request_params["reasoning"] == {"effort": "high"}
    assert "thinking" not in additional_request_params


@pytest.mark.parametrize(
    "model",
    [
        "us.openai.gpt-5.6-luna",
        "bedrock/converse/global.openai.gpt-5.6-terra",
        "us.openai.gpt-6-astra",
    ],
)
def test_openai_gpt5_converse_rejects_effort_level_disabled_in_model_map(model, local_model_cost_map):
    config = AmazonConverseConfig()
    assert litellm.utils.is_explicitly_disabled_factory(
        model=model, custom_llm_provider="bedrock_converse", key="supports_minimal_reasoning_effort"
    )

    with pytest.raises(litellm.utils.UnsupportedParamsError, match="minimal"):
        config.map_openai_params(
            non_default_params={"reasoning_effort": "minimal"},
            optional_params={},
            model=model,
            drop_params=False,
        )

    optional_params = config.map_openai_params(
        non_default_params={"reasoning_effort": "minimal"},
        optional_params={},
        model=model,
        drop_params=True,
    )
    _, additional_request_params, _, _ = config._prepare_request_params(optional_params, model)
    assert "reasoning" not in additional_request_params
    assert "thinking" not in additional_request_params


@pytest.mark.parametrize(
    "model",
    [
        "us.openai.gpt-5.6-sol",
        "bedrock/converse/global.openai.gpt-5.6-luna",
        "us.openai.gpt-6-astra",
    ],
)
def test_openai_gpt5_converse_never_forwards_thinking(model, local_model_cost_map):
    """GPT-5.x on Converse must never send Anthropic ``thinking``/``output_config`` (Bedrock rejects them).

    Regression: ``thinking`` is not advertised as supported, and even when supplied alongside
    ``reasoning_effort`` in either order it never survives into the request."""
    config = AmazonConverseConfig()

    supported = config.get_supported_openai_params(model=model)
    assert "thinking" not in supported
    assert "output_config" not in supported

    thinking_block = {"type": "enabled", "budget_tokens": 2048}
    for non_default_params in (
        {"reasoning_effort": "high", "thinking": thinking_block},
        {"thinking": thinking_block, "reasoning_effort": "high"},
    ):
        optional_params = config.map_openai_params(
            non_default_params=dict(non_default_params),
            optional_params={},
            model=model,
            drop_params=False,
        )
        _, additional_request_params, _, _ = config._prepare_request_params(optional_params, model)
        assert additional_request_params["reasoning"] == {"effort": "high"}
        assert "thinking" not in additional_request_params


@pytest.mark.parametrize(
    "model",
    [
        "bedrock/converse/us.anthropic.claude-opus-4-5-20251101-v1:0",
        "bedrock/converse/us.anthropic.claude-opus-4-6-v1",
        "bedrock/converse/us.anthropic.claude-opus-4-7",
    ],
)
def test_reasoning_effort_none_omits_thinking_for_anthropic_converse(model):
    """reasoning_effort="none" must omit thinking from the Bedrock Converse request."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"reasoning_effort": "none"},
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert "thinking" not in optional_params


@pytest.mark.parametrize(
    "model,effort,expected_effort",
    [
        ("bedrock/converse/us.anthropic.claude-opus-4-7", "low", "low"),
        ("bedrock/converse/us.anthropic.claude-opus-4-7", "medium", "medium"),
        ("bedrock/converse/us.anthropic.claude-opus-4-7", "high", "high"),
        ("bedrock/converse/us.anthropic.claude-opus-4-7", "xhigh", "xhigh"),
        ("bedrock/converse/us.anthropic.claude-opus-4-7", "max", "max"),
        ("bedrock/converse/us.anthropic.claude-opus-4-6-v1", "xhigh", "max"),
        ("bedrock/converse/us.anthropic.claude-opus-4-6-v1", "max", "max"),
        ("bedrock/converse/us.anthropic.claude-sonnet-4-6", "high", "high"),
        ("bedrock/converse/us.anthropic.claude-sonnet-4-6", "minimal", "low"),
    ],
)
def test_reasoning_effort_sets_output_config_for_adaptive_models_converse(model, effort, expected_effort):
    """Adaptive Claude 4.6 / 4.7 on Bedrock Converse routes the tier via ``output_config.effort``."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"reasoning_effort": effort},
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert optional_params["thinking"]["type"] == "adaptive"
    assert optional_params["output_config"] == {"effort": expected_effort}


@pytest.mark.parametrize(
    "model",
    [
        "bedrock/converse/us.anthropic.claude-opus-4-7",
        "bedrock/converse/us.anthropic.claude-opus-4-6-v1",
        "bedrock/converse/us.anthropic.claude-sonnet-4-6",
    ],
)
def test_output_config_effort_forwarded_into_additional_request_fields(model):
    """``output_config`` rides along inside ``additionalModelRequestFields``."""
    config = AmazonConverseConfig()
    messages = [{"role": "user", "content": "hi"}]

    result = config._transform_request(
        model=model,
        messages=messages,
        optional_params={
            "maxTokens": 256,
            "thinking": {"type": "adaptive"},
            "output_config": {"effort": "high"},
        },
        litellm_params={},
        headers={},
    )

    additional = result.get("additionalModelRequestFields", {})
    assert additional.get("output_config") == {"effort": "high"}


_ARTIFACT_DATA_ID_PATTERN: Final = r"^(?!\.\.?(?:\/|$))[A-Za-z0-9_\-.~:@+]{1,200}$"
_ARTIFACT_DATA_INPUT_SCHEMA: Final = {
    "type": "object",
    "properties": {
        "collection": {"type": "string", "pattern": _ARTIFACT_DATA_ID_PATTERN, "description": "Collection"},
        "doc_id": {"type": "string", "pattern": _ARTIFACT_DATA_ID_PATTERN},
        "writes": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {"doc_id": {"type": "string", "pattern": _ARTIFACT_DATA_ID_PATTERN}},
            },
        },
        "limit": {"type": "integer", "minimum": 1},
    },
    "required": ["collection"],
}
_ARTIFACT_DATA_ANTHROPIC_TOOL: Final = {
    "name": "ArtifactData",
    "description": "Read a shared database",
    "input_schema": _ARTIFACT_DATA_INPUT_SCHEMA,
}
_ARTIFACT_DATA_OPENAI_TOOL: Final = {
    "type": "function",
    "function": {
        "name": "ArtifactData",
        "description": "Read a shared database",
        "parameters": _ARTIFACT_DATA_INPUT_SCHEMA,
    },
}
_LOOKAROUND_FREE_PROPERTIES: Final = {
    "collection": {"type": "string", "description": "Collection"},
    "doc_id": {"type": "string"},
    "writes": {"type": "array", "items": {"type": "object", "properties": {"doc_id": {"type": "string"}}}},
    "limit": {"type": "integer", "minimum": 1},
}


def _converse_tools(model, tools, litellm_params=None):
    request = AmazonConverseConfig()._transform_request(
        model=model,
        messages=[{"role": "user", "content": "hi"}],
        optional_params={"tools": copy.deepcopy(tools)},
        litellm_params=litellm_params or {},
        headers={},
    )
    return request["toolConfig"]["tools"]


def _tool_schema_properties(model, tool, litellm_params=None):
    return _converse_tools(model, [tool], litellm_params)[0]["toolSpec"]["inputSchema"]["json"]["properties"]


@pytest.mark.parametrize(
    "tool", [_ARTIFACT_DATA_ANTHROPIC_TOOL, _ARTIFACT_DATA_OPENAI_TOOL], ids=["anthropic-shape", "openai-shape"]
)
@pytest.mark.parametrize(
    "model",
    [
        "global.moonshotai.kimi-k3",
        "us.moonshotai.kimi-k3",
        "moonshotai.kimi-k3",
        "us-east-1/us.moonshotai.kimi-k3",
        "us.xai.grok-4.6",
        "us-gov.xai.grok-4.6",
        "global.xai.grok-4.7",
        "us.xai.grok-4.7",
    ],
)
def test_transform_request_drops_lookaround_regex_for_models_the_cost_map_flags(tool, model):
    """Kimi K3 and Grok 4.6/4.7 refuse the whole request over a lookaround in a tool schema regex."""
    tools = _converse_tools(model, [tool])

    json_schema = tools[0]["toolSpec"]["inputSchema"]["json"]
    assert json_schema["properties"] == _LOOKAROUND_FREE_PROPERTIES
    assert json_schema["required"] == ["collection"]


@pytest.mark.parametrize(
    "model",
    [
        "us.anthropic.claude-sonnet-4-6",
        "us.amazon.nova-pro-v1:0",
        "us.meta.llama4-maverick-17b-instruct-v1:0",
        "us.openai.gpt-5.6-sol",
    ],
)
def test_transform_request_keeps_lookaround_regex_for_models_that_accept_it(model):
    assert _tool_schema_properties(model, _ARTIFACT_DATA_ANTHROPIC_TOOL) == _ARTIFACT_DATA_INPUT_SCHEMA["properties"]


@pytest.mark.parametrize(
    "model",
    [
        "us.amazon.nova-lite-v1:0",
        "us.moonshotai.kimi-k4",
        "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123",
    ],
)
def test_transform_request_drops_lookaround_regex_when_the_deployment_model_info_opts_in(model):
    """A deployment's ``model_info`` flag covers a model the cost map does not know, an inference profile included."""
    properties = _tool_schema_properties(
        model, _ARTIFACT_DATA_ANTHROPIC_TOOL, {"model_info": {"supports_regex_lookaround": False}}
    )

    assert properties == _LOOKAROUND_FREE_PROPERTIES


def test_transform_request_keeps_lookaround_regex_when_the_deployment_model_info_opts_out():
    properties = _tool_schema_properties(
        "global.moonshotai.kimi-k3", _ARTIFACT_DATA_ANTHROPIC_TOOL, {"model_info": {"supports_regex_lookaround": True}}
    )

    assert properties["doc_id"]["pattern"] == _ARTIFACT_DATA_ID_PATTERN


def test_transform_request_resolves_an_inference_profile_through_its_base_model():
    properties = _tool_schema_properties(
        "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123",
        _ARTIFACT_DATA_ANTHROPIC_TOOL,
        {"base_model": "bedrock/global.moonshotai.kimi-k3"},
    )

    assert properties == _LOOKAROUND_FREE_PROPERTIES


_APPLICATION_PROFILE_ARN: Final = "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/abc123"


@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize(
    "model, optional_params, litellm_params, replays_redacted",
    [
        ("us.anthropic.claude-sonnet-4-6", {}, {}, True),
        ("arn:aws:bedrock:us-west-2:123456789012:inference-profile/us.anthropic.claude-sonnet-4-6", {}, {}, True),
        ("anthropic.claude-sonnet-4-6", {"model_id": _APPLICATION_PROFILE_ARN}, {}, True),
        (_APPLICATION_PROFILE_ARN, {}, {"base_model": "anthropic.claude-sonnet-4-6"}, True),
        (_APPLICATION_PROFILE_ARN, {}, {"base_model": "bedrock/us.anthropic.claude-sonnet-4-6"}, True),
        (_APPLICATION_PROFILE_ARN, {}, {"base_model": "claude-sonnet-4-6"}, True),
        (_APPLICATION_PROFILE_ARN, {}, {}, False),
        (_APPLICATION_PROFILE_ARN, {}, {"base_model": "us.amazon.nova-pro-v1:0"}, False),
        ("us.amazon.nova-pro-v1:0", {}, {}, False),
        ("us.amazon.nova-pro-v1:0", {}, {"base_model": "anthropic.claude-sonnet-4-6"}, False),
    ],
)
async def test_transform_request_replays_redacted_thinking_only_to_claude(
    use_async: bool,
    model: str,
    optional_params: dict[str, str],
    litellm_params: dict[str, str],
    replays_redacted: bool,
):
    """A model id that names its model decides on its own. An application inference profile ARN hides its model,
    so the deployment's ``base_model`` is what marks it as Claude, and without one the redacted block is dropped
    the way it is for every non-Claude target."""
    redacted_data: Final = base64.b64encode(
        b"EmwKAhgBEgy3va3pzix/LafPsn4aDFIT2Xlxh0L5L8rLVyIwxtE3rAFBa8cr3qpP"
    ).decode()
    messages: Final = [
        {"role": "user", "content": "hi"},
        {
            "role": "assistant",
            "content": "hello",
            "thinking_blocks": [{"type": "redacted_thinking", "data": redacted_data}],
        },
        {"role": "user", "content": "again"},
    ]
    config: Final = AmazonConverseConfig()
    kwargs: Final = dict(
        model=model, messages=messages, optional_params=dict(optional_params), litellm_params=dict(litellm_params)
    )

    request: Final = (
        await config._async_transform_request(**kwargs) if use_async else config._transform_request(**kwargs)
    )

    assert request["messages"][1] == {
        "role": "assistant",
        "content": [{"reasoningContent": {"redactedContent": redacted_data}}, {"text": "hello"}]
        if replays_redacted
        else [{"text": "hello"}],
    }


def test_transform_request_drops_lookaround_regex_around_pre_formatted_tool_blocks():
    """Blocks that arrive already in Bedrock shape, like Nova's grounding ``systemTool``, pass through as sent."""
    grounding: Final = {"systemTool": {"name": "nova_grounding"}}

    tools = _converse_tools("global.moonshotai.kimi-k3", [_ARTIFACT_DATA_OPENAI_TOOL, grounding])

    assert tools[0]["toolSpec"]["inputSchema"]["json"]["properties"] == _LOOKAROUND_FREE_PROPERTIES
    assert tools[1] == grounding


def test_reasoning_effort_requests_summarized_display_converse():
    """Regression LIT-5714: adaptive thinking synthesized from reasoning_effort must
    request the summarized display, otherwise the provider returns a blank thinking
    block and reasoning_content is always empty."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"reasoning_effort": "high"},
        optional_params={},
        model="bedrock/converse/us.anthropic.claude-opus-4-7",
        drop_params=False,
    )

    assert optional_params["thinking"]["type"] == "adaptive"
    assert optional_params["thinking"]["display"] == "summarized"


def test_thinking_request_adds_output_tokens_details_response_path():
    """Regression LIT-5714: the Converse usage block has no thinking-token field, so
    thinking requests must ask for ``/usage/output_tokens_details`` via
    ``additionalModelResponseFieldPaths``."""
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="bedrock/converse/us.anthropic.claude-opus-4-7",
        messages=[{"role": "user", "content": "hi"}],
        optional_params={
            "maxTokens": 256,
            "thinking": {"type": "adaptive", "display": "summarized"},
            "output_config": {"effort": "high"},
        },
        litellm_params={},
        headers={},
    )

    assert result["additionalModelResponseFieldPaths"] == ("/usage/output_tokens_details",)


def test_request_without_thinking_omits_response_field_paths():
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="bedrock/converse/us.anthropic.claude-opus-4-7",
        messages=[{"role": "user", "content": "hi"}],
        optional_params={"maxTokens": 256},
        litellm_params={},
        headers={},
    )

    assert "additionalModelResponseFieldPaths" not in result


def test_transform_usage_prefers_provider_reasoning_tokens():
    """Regression LIT-5714: provider-reported thinking tokens must win over the
    token_counter estimate derived from visible reasoning text."""
    config = AmazonConverseConfig()

    usage = config.transform_usage(
        {"inputTokens": 40, "outputTokens": 3002, "totalTokens": 3042},
        reasoning_content="a short reasoning summary",
        thinking_ran=True,
        provider_reasoning_tokens=1033,
    )

    assert usage.completion_tokens_details.reasoning_tokens == 1033
    assert usage.completion_tokens_details.text_tokens == 3002 - 1033


def test_transform_usage_falls_back_to_estimate_without_provider_tokens():
    config = AmazonConverseConfig()

    usage = config.transform_usage(
        {"inputTokens": 40, "outputTokens": 300, "totalTokens": 340},
        reasoning_content="a short reasoning summary",
        thinking_ran=True,
    )

    assert usage.completion_tokens_details.reasoning_tokens > 0
    assert usage.completion_tokens_details.reasoning_tokens < 300


def test_thinking_tokens_parsed_from_additional_model_response_fields():
    parsed = AmazonConverseConfig.thinking_tokens_from_additional_fields(
        {"usage": {"output_tokens_details": {"thinking_tokens": 92}}}
    )
    assert parsed == 92
    assert AmazonConverseConfig.thinking_tokens_from_additional_fields(None) is None
    assert AmazonConverseConfig.thinking_tokens_from_additional_fields({"usage": {}}) is None


@pytest.mark.parametrize(
    "model,effort,expected_effort",
    [
        ("bedrock/converse/us.anthropic.claude-opus-4-7", "max", "max"),
        ("bedrock/converse/us.anthropic.claude-opus-4-6-v1", "xhigh", "max"),
    ],
)
def test_explicit_output_config_effort_mapped_for_adaptive_thinking_converse(model, effort, expected_effort):
    """Regression: Claude Code drives adaptive thinking as ``thinking: {"type":
    "adaptive"}`` plus ``output_config: {"effort": ...}``. ``output_config`` must
    be a supported openai param and survive ``map_openai_params`` (clamped to the
    model's Bedrock effort ceiling), otherwise the Converse request carries
    adaptive thinking without an effort tier and Bedrock streams zero
    ``reasoningContent`` blocks."""
    config = AmazonConverseConfig()

    assert "output_config" in config.get_supported_openai_params(model)

    optional_params = config.map_openai_params(
        non_default_params={
            "thinking": {"type": "adaptive"},
            "output_config": {"effort": effort},
        },
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert optional_params["thinking"] == {"type": "adaptive"}
    assert optional_params["output_config"] == {"effort": expected_effort}


def test_output_config_supported_param_for_arn_models_converse():
    """ARN model ids hide the underlying Claude model, so ``output_config`` must
    be in the blanket ARN supported-params list too."""
    config = AmazonConverseConfig()
    arn_model = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abcdef123456"
    assert "output_config" in config.get_supported_openai_params(arn_model)


def test_output_config_effort_forwarded_for_application_inference_profile_arn():
    """Regression: opaque application inference profile ARNs cannot resolve a
    base model, so the anthropic-only serialization gate dropped ``output_config``
    while still sending ``thinking``: adaptive thinking with no effort tier, and
    Bedrock streams zero ``reasoningContent`` blocks. The effort must be forwarded
    verbatim (ceilings and capability gates are unknowable behind the alias) for
    Bedrock to enforce."""
    config = AmazonConverseConfig()
    arn_model = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abcdef123456"

    result = config._transform_request(
        model=arn_model,
        messages=[{"role": "user", "content": "hi"}],
        optional_params={
            "maxTokens": 256,
            "thinking": {"type": "adaptive"},
            "output_config": {"effort": "max"},
        },
        litellm_params={},
        headers={},
    )

    additional = result.get("additionalModelRequestFields", {})
    assert additional.get("thinking") == {"type": "adaptive"}
    assert additional.get("output_config") == {"effort": "max"}


def test_output_config_format_translated_to_native_output_config_converse():
    """``output_config.format`` becomes Bedrock ``outputConfig`` and is not forwarded raw."""
    config = AmazonConverseConfig()
    schema = {
        "type": "object",
        "properties": {"answer": {"type": "string"}},
    }

    result = config._transform_request(
        model="bedrock/converse/us.anthropic.claude-sonnet-4-6",
        messages=[{"role": "user", "content": "hi"}],
        optional_params={
            "maxTokens": 256,
            "thinking": {"type": "adaptive"},
            "output_config": {
                "effort": "max",
                "format": {"type": "json_schema", "schema": schema},
            },
        },
        litellm_params={},
        headers={},
    )

    additional = result.get("additionalModelRequestFields", {})
    assert additional.get("output_config") == {"effort": "max"}
    assert "format" not in additional["output_config"]
    assert result["outputConfig"]["textFormat"]["type"] == "json_schema"
    parsed_schema = json.loads(result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"])
    assert parsed_schema == {**schema, "additionalProperties": False}


def test_output_config_format_dropped_on_unsupported_converse_model_warns(caplog):
    """When Converse model lacks native structured-output support, the silently
    dropped ``output_config.format`` must surface as a warning so callers can
    diagnose plain-text responses."""
    config = AmazonConverseConfig()
    schema = {
        "type": "object",
        "properties": {"answer": {"type": "string"}},
    }

    with caplog.at_level("WARNING"):
        result = config._transform_request(
            model="bedrock/converse/us.anthropic.claude-3-haiku-20240307-v1:0",
            messages=[{"role": "user", "content": "hi"}],
            optional_params={
                "maxTokens": 256,
                "output_config": {
                    "format": {"type": "json_schema", "schema": schema},
                },
            },
            litellm_params={},
            headers={},
        )

    assert "outputConfig" not in result
    assert any("dropping `output_config.format`" in record.getMessage() for record in caplog.records)


def test_output_config_normalized_marker_does_not_leak_into_optional_params():
    """The internal ``_output_config_normalized`` marker set by
    ``_handle_reasoning_effort_parameter`` must be consumed during request
    preparation so it does not linger on the caller's ``optional_params``."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"reasoning_effort": "xhigh"},
        optional_params={},
        model="bedrock/converse/us.anthropic.claude-opus-4-6-v1",
        drop_params=False,
    )
    assert optional_params.get("_output_config_normalized") is True

    config._transform_request(
        model="bedrock/converse/us.anthropic.claude-opus-4-6-v1",
        messages=[{"role": "user", "content": "hi"}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert "_output_config_normalized" not in optional_params


@pytest.mark.parametrize(
    "model,expected_effort",
    [
        ("bedrock/converse/us.anthropic.claude-opus-4-5-20251101-v1:0", "high"),
        ("bedrock/converse/us.anthropic.claude-opus-4-6-v1", "max"),
        ("bedrock/converse/us.anthropic.claude-opus-4-7", "xhigh"),
    ],
)
def test_output_config_effort_normalized_for_bedrock_converse_opus(model, expected_effort):
    """Bedrock Converse accepts ``xhigh`` and forwards the provider-safe effort."""
    config = AmazonConverseConfig()

    result = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "hi"}],
        optional_params={
            "maxTokens": 256,
            "thinking": {"type": "adaptive"},
            "output_config": {"effort": "xhigh"},
        },
        litellm_params={},
        headers={},
    )

    additional = result.get("additionalModelRequestFields", {})
    assert additional.get("output_config") == {"effort": expected_effort}


@pytest.mark.parametrize(
    "effort",
    ["disabled", "invalid", ""],
)
def test_reasoning_effort_garbage_raises_bad_request_converse(effort):
    """Unmapped reasoning_effort on Bedrock Converse Anthropic raises BadRequestError."""
    config = AmazonConverseConfig()

    with pytest.raises(litellm.exceptions.BadRequestError):
        config.map_openai_params(
            non_default_params={"reasoning_effort": effort},
            optional_params={},
            model="bedrock/converse/us.anthropic.claude-opus-4-7",
            drop_params=False,
        )


@pytest.mark.parametrize(
    "model",
    [
        "bedrock/converse/us.anthropic.claude-sonnet-4-6",
        "bedrock/converse/global.anthropic.claude-sonnet-4-6",
        "bedrock/converse/eu.anthropic.claude-sonnet-4-6",
        "bedrock/converse/au.anthropic.claude-sonnet-4-6",
    ],
)
def test_output_config_effort_max_passes_through_on_sonnet_46_variants(model):
    """``effort='max'`` flows through for every Bedrock Converse Sonnet 4.6 id."""
    config = AmazonConverseConfig()
    messages = [{"role": "user", "content": "hi"}]

    result = config._transform_request(
        model=model,
        messages=messages,
        optional_params={
            "maxTokens": 256,
            "output_config": {"effort": "max"},
        },
        litellm_params={},
        headers={},
    )

    additional = result.get("additionalModelRequestFields", {})
    assert additional.get("output_config") == {"effort": "max"}


def test_get_supported_openai_params():
    config = AmazonConverseConfig()
    supported_params = config.get_supported_openai_params(
        model="bedrock/converse/us.anthropic.claude-sonnet-4-20250514-v1:0"
    )
    assert "tools" in supported_params
    assert "tool_choice" in supported_params
    assert "thinking" in supported_params
    assert "reasoning_effort" in supported_params


@pytest.mark.parametrize(
    "model",
    [
        "bedrock/us.deepseek.r1-v1:0",
        "bedrock/converse/us.deepseek.r1-v1:0",
        "bedrock/deepseek.v3-v1:0",
        "bedrock/deepseek.v3.2",
    ],
)
def test_bedrock_deepseek_does_not_advertise_thinking(model):
    """DeepSeek reasons natively on Bedrock and does not take the Anthropic-shaped `thinking`
    field (R1 400s on it, V3 ignores it), so it must not be advertised as supported."""
    config = AmazonConverseConfig()
    supported_params = config.get_supported_openai_params(model=model)
    assert "thinking" not in supported_params
    assert "output_config" not in supported_params


@pytest.mark.parametrize("model", ["bedrock/us.deepseek.r1-v1:0", "bedrock/converse/us.deepseek.r1-v1:0"])
def test_bedrock_deepseek_r1_does_not_advertise_reasoning_effort(model):
    """DeepSeek R1 always reasons and returns a 400 for any reasoning_effort shape."""
    config = AmazonConverseConfig()
    assert "reasoning_effort" not in config.get_supported_openai_params(model=model)


@pytest.mark.parametrize("model", ["bedrock/deepseek.v3-v1:0", "bedrock/deepseek.v3.2", "bedrock/us.deepseek.v3.2"])
def test_bedrock_deepseek_v3_advertises_reasoning_effort(model):
    """DeepSeek V3 on Bedrock accepts a raw reasoning_effort in additionalModelRequestFields."""
    config = AmazonConverseConfig()
    assert "reasoning_effort" in config.get_supported_openai_params(model=model)


@pytest.mark.parametrize("model", ["us.deepseek.r1-v1:0", "deepseek.v3.2"])
def test_bedrock_deepseek_thinking_raises_without_drop_params(model):
    """Passing `thinking` to Bedrock DeepSeek must fail client-side with a clear
    UnsupportedParamsError instead of leaking through to Bedrock."""
    with pytest.raises(litellm.UnsupportedParamsError):
        litellm.utils.get_optional_params(
            model=model,
            custom_llm_provider="bedrock",
            thinking={"type": "enabled", "budget_tokens": 1024},
        )


def test_bedrock_deepseek_r1_reasoning_effort_raises_without_drop_params():
    with pytest.raises(litellm.UnsupportedParamsError):
        litellm.utils.get_optional_params(
            model="us.deepseek.r1-v1:0",
            custom_llm_provider="bedrock",
            reasoning_effort="high",
        )


@pytest.mark.parametrize("model", ["us.deepseek.r1-v1:0", "deepseek.v3.2"])
def test_bedrock_deepseek_thinking_dropped_does_not_leak_into_request(model):
    """With drop_params, `thinking` is dropped rather than forwarded into
    additionalModelRequestFields for Bedrock DeepSeek."""
    optional_params = litellm.utils.get_optional_params(
        model=model,
        custom_llm_provider="bedrock",
        thinking={"type": "enabled", "budget_tokens": 1024},
        drop_params=True,
    )
    assert "thinking" not in optional_params

    config = AmazonConverseConfig()
    request = config._transform_request(
        model=f"bedrock/converse/{model}",
        messages=[{"role": "user", "content": "Say hi in one word."}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )
    assert "thinking" not in (request.get("additionalModelRequestFields") or {})


@pytest.mark.parametrize("param", ["thinking", "reasoning_effort"])
def test_bedrock_deepseek_r1_reasoning_params_not_forwarded_by_map(param):
    """Even when map_openai_params is called directly (bypassing the supported-params
    gate), DeepSeek R1 must not forward thinking/reasoning_effort into
    additionalModelRequestFields, since Bedrock rejects both with a 400."""
    config = AmazonConverseConfig()
    model = "bedrock/converse/us.deepseek.r1-v1:0"
    value = {"type": "enabled", "budget_tokens": 1024} if param == "thinking" else "high"

    optional_params = config.map_openai_params(
        non_default_params={param: value, "max_tokens": 100},
        optional_params={},
        model=model,
        drop_params=False,
    )
    assert "thinking" not in optional_params
    assert "reasoning_effort" not in optional_params

    request = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "Say hi in one word."}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )
    assert request.get("additionalModelRequestFields") is None


def test_bedrock_deepseek_v3_reasoning_effort_forwarded_raw():
    """DeepSeek V3 takes reasoning_effort verbatim in additionalModelRequestFields, never
    converted into the Anthropic `thinking` block that Claude models get."""
    config = AmazonConverseConfig()
    model = "bedrock/deepseek.v3.2"
    optional_params = config.map_openai_params(
        non_default_params={"reasoning_effort": "high", "max_tokens": 100},
        optional_params={},
        model=model,
        drop_params=False,
    )
    assert "thinking" not in optional_params

    request = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "Say hi in one word."}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )
    assert request["additionalModelRequestFields"] == {"reasoning_effort": "high"}


def test_bedrock_deepseek_v3_thinking_dropped_by_map():
    config = AmazonConverseConfig()
    optional_params = config.map_openai_params(
        non_default_params={"thinking": {"type": "enabled", "budget_tokens": 1024}, "max_tokens": 100},
        optional_params={},
        model="bedrock/deepseek.v3.2",
        drop_params=False,
    )
    assert "thinking" not in optional_params
    assert "reasoning_effort" not in optional_params


@pytest.mark.parametrize(
    "model, param, value, kept_key",
    [
        (
            "bedrock/us.anthropic.claude-opus-4-20250514-v1:0",
            "thinking",
            {"type": "enabled", "budget_tokens": 1024},
            "thinking",
        ),
        (
            "bedrock/arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123",
            "thinking",
            {"type": "enabled", "budget_tokens": 1024},
            "thinking",
        ),
        (
            "bedrock/openai.gpt-oss-safeguard-20b-1:0",
            "reasoning_effort",
            "high",
            "reasoning_effort",
        ),
        (
            "bedrock/us.amazon.nova-2-lite-v1:0",
            "reasoning_effort",
            "high",
            "reasoningConfig",
        ),
    ],
)
def test_bedrock_non_deepseek_reasoning_params_preserved(model, param, value, kept_key):
    """The DeepSeek leak fix must only drop reasoning request params for DeepSeek.

    Claude behind an application-inference-profile ARN, gpt-oss-safeguard (absent from the
    cost map so `supports_reasoning` is False), and Nova 2 all reason via a request param and
    must keep it. Regression guard against gating the drop on a positive allowlist, which
    silently degraded reasoning for anything the allowlist/ARN introspection missed."""
    config = AmazonConverseConfig()
    optional_params = config.map_openai_params(
        non_default_params={param: value, "max_tokens": 100},
        optional_params={},
        model=model,
        drop_params=False,
    )
    assert kept_key in optional_params


def test_get_supported_openai_params_bedrock_converse():
    """
    Test that all documented bedrock converse models have the same set of supported openai params when using
    `bedrock/converse/` or `bedrock/` prefix.

    Note: This test is critical for routing, if we ever remove `litellm.BEDROCK_CONVERSE_MODELS`,
    please update this test to read `bedrock_converse` models from the model cost map.
    """
    for model in litellm.BEDROCK_CONVERSE_MODELS:
        print(f"Testing model: {model}")
        config = AmazonConverseConfig()
        supported_params_without_prefix = config.get_supported_openai_params(model=model)

        supported_params_with_prefix = config.get_supported_openai_params(model=f"bedrock/converse/{model}")

        assert set(supported_params_without_prefix) == set(supported_params_with_prefix), (
            f"Supported params mismatch for model: {model}. Without prefix: {supported_params_without_prefix}, With prefix: {supported_params_with_prefix}"
        )
        print(f"✅ Passed for model: {model}")


@pytest.mark.parametrize(
    "tools, model, expected_marker",
    [
        pytest.param(
            [{"type": "function", "function": {"name": "f", "parameters": {"type": "object", "properties": {}}}}],
            "anthropic.claude-sonnet-4-5-20250929-v1:0",
            "dep-bedrock",
            id="tools-present-so-the-cachepoint-is-placed",
        ),
        pytest.param(None, "anthropic.claude-sonnet-4-5-20250929-v1:0", None, id="no-tools-so-nothing-is-placed"),
        pytest.param(
            [{"type": "function", "function": {"name": "f", "parameters": {"type": "object", "properties": {}}}}],
            "global.openai.gpt-6-astra",
            None,
            id="openai-family-implicit-caching-only",
        ),
    ],
)
def test_tool_config_cachepoint_is_credited_only_where_it_is_placed(tools, model, expected_marker):
    """Spend attribution credits the gateway for breakpoints it placed, and a tool_config
    point becomes one here or nowhere.

    The hook that reads the configuration cannot record it: whether a cachePoint lands
    depends on this provider and on the request carrying tools, neither of which the hook
    sees, so marking on the point's presence credited request shapes that inject nothing.
    """
    bucket: dict = {"user_api_key": "sk-test"}
    optional_params = {"cache_control_injection_points": [{"location": "tool_config"}]}
    if tools is not None:
        optional_params["tools"] = tools

    data = AmazonConverseConfig()._transform_request_helper(
        model=model,
        system_content_blocks=[],
        optional_params=optional_params,
        messages=[{"role": "user", "content": "hi"}],
        litellm_params={"metadata": bucket, "litellm_metadata": None, "model_info": {"id": "dep-bedrock"}},
    )

    placed = "cachePoint" in json.dumps(data.get("toolConfig", {}))
    assert placed is (expected_marker is not None)
    assert bucket.get("litellm_gateway_injected_cache") == expected_marker


def test_transform_request_helper_includes_anthropic_beta_and_tools():
    """Test _transform_request_helper includes anthropic_beta for computer tools."""
    config = AmazonConverseConfig()
    system_content_blocks = []
    optional_params = {
        "anthropic_beta": ["computer-use-2025-01-24"],
        "tools": [
            {
                "type": "computer_20250124",
                "name": "computer",
                "display_height_px": 768,
                "display_width_px": 1024,
                "display_number": 0,
            }
        ],
        "some_other_param": 123,
    }
    data = config._transform_request_helper(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        system_content_blocks=system_content_blocks,
        optional_params=optional_params,
        messages=None,
    )
    assert "additionalModelRequestFields" in data
    fields = data["additionalModelRequestFields"]
    assert "anthropic_beta" in fields
    assert fields["anthropic_beta"] == ["computer-use-2025-01-24"]
    # Verify computer tool is included
    assert "tools" in fields
    assert len(fields["tools"]) == 1
    assert fields["tools"][0]["type"] == "computer_20250124"


def test_config_blocks_do_not_leak_into_inference_config():
    """Regression: inferenceConfig was built before the config blocks were popped, so a dead
    nested copy of each block (guardrailConfig, performanceConfig, serviceTier) rode inside
    inferenceConfig alongside the real top-level one."""
    data = AmazonConverseConfig()._transform_request_helper(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        system_content_blocks=[],
        optional_params={
            "maxTokens": 100,
            "guardrailConfig": {"guardrailIdentifier": "gr-id", "guardrailVersion": "DRAFT"},
            "performanceConfig": {"latency": "optimized"},
            "serviceTier": {"type": "priority"},
        },
        messages=[{"role": "user", "content": "hi"}],
    )

    assert data["inferenceConfig"] == {"maxTokens": 100}
    assert data["guardrailConfig"] == {"guardrailIdentifier": "gr-id", "guardrailVersion": "DRAFT"}
    assert data["performanceConfig"] == {"latency": "optimized"}
    assert data["serviceTier"] == {"type": "priority"}


@pytest.mark.parametrize(
    "model",
    [
        "anthropic.claude-opus-4-8",
        "us.anthropic.claude-opus-4-8",
        "amazon.nova-pro-v1:0",
        "us.meta.llama4-maverick-17b-instruct-v1:0",
        "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abcdef123456",
        "arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.amazon.nova-pro-v1:0",
    ],
)
def test_client_metadata_stripped_from_converse_request(model):
    data = AmazonConverseConfig()._transform_request_helper(
        model=model,
        system_content_blocks=[],
        optional_params={
            "maxTokens": 16,
            "anthropic_beta": ["computer-use-2025-01-24"],
            "client_metadata": {"originator": "codex_cli_rs"},
        },
        messages=None,
    )

    fields = data["additionalModelRequestFields"]
    assert "client_metadata" not in fields
    assert fields["anthropic_beta"] == ["computer-use-2025-01-24"]


def test_parallel_tool_calls_config_kept_for_sonnet_5(monkeypatch):
    old_env = os.environ.get("LITELLM_LOCAL_MODEL_COST_MAP")
    old_cost = litellm.model_cost
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    litellm.model_cost = litellm.get_model_cost_map(url="")
    try:
        config = AmazonConverseConfig()
        optional_params = config.map_openai_params(
            model="anthropic.claude-sonnet-5",
            non_default_params={"parallel_tool_calls": False},
            optional_params={},
            drop_params=False,
        )

        data = config._transform_request_helper(
            model="anthropic.claude-sonnet-5",
            system_content_blocks=[],
            optional_params=optional_params,
            messages=None,
        )

        assert data["additionalModelRequestFields"]["tool_choice"] == {
            "type": "auto",
            "disable_parallel_tool_use": True,
        }
    finally:
        litellm.model_cost = old_cost
        if old_env is None:
            os.environ.pop("LITELLM_LOCAL_MODEL_COST_MAP", None)
        else:
            monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", old_env)


def test_parallel_tool_calls_config_dropped_for_ttl_only_model(
    monkeypatch: pytest.MonkeyPatch,
):
    model = "anthropic.claude-fable-5"
    monkeypatch.setitem(
        litellm.model_cost,
        model,
        {"cache_creation_input_token_cost_above_1hr": 2e-05},
    )
    config = AmazonConverseConfig()
    optional_params = config.map_openai_params(
        model=model,
        non_default_params={"parallel_tool_calls": False},
        optional_params={},
        drop_params=False,
    )

    data = config._transform_request_helper(
        model=model,
        system_content_blocks=[],
        optional_params=optional_params,
        messages=None,
    )

    assert "tool_choice" not in data.get("additionalModelRequestFields", {})


def test_transform_response_with_computer_use_tool():
    """Test response transformation with computer use tool call."""

    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    # Simulate a Bedrock Converse response with a computer-use tool call
    response_json = {
        "additionalModelResponseFields": {},
        "metrics": {"latencyMs": 100.0},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_123",
                            "name": "computer",
                            "input": {
                                "display_height_px": 768,
                                "display_width_px": 1024,
                                "display_number": 0,
                            },
                        }
                    }
                ],
            }
        },
        "stopReason": "tool_use",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 5,
            "totalTokens": 15,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    # Mock httpx.Response
    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()
    optional_params = {
        "tools": [
            {
                "type": "computer_20250124",
                "function": {
                    "name": "computer",
                    "parameters": {
                        "display_height_px": 768,
                        "display_width_px": 1024,
                        "display_number": 0,
                    },
                },
            }
        ]
    }
    # Call the transformation logic
    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )
    # Check that the tool call is present in the returned message
    assert result.choices[0].message.tool_calls is not None
    assert len(result.choices[0].message.tool_calls) == 1
    tool_call = result.choices[0].message.tool_calls[0]
    assert tool_call.function.name == "computer"
    args = json.loads(tool_call.function.arguments)
    assert args["display_height_px"] == 768
    assert args["display_width_px"] == 1024
    assert args["display_number"] == 0


def test_transform_response_with_bash_tool():
    """Test response transformation with bash tool call."""

    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    # Simulate a Bedrock Converse response with a bash tool call
    response_json = {
        "additionalModelResponseFields": {},
        "metrics": {"latencyMs": 100.0},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_456",
                            "name": "bash",
                            "input": {"command": "ls -la *.py"},
                        }
                    }
                ],
            }
        },
        "stopReason": "tool_use",
        "usage": {
            "inputTokens": 8,
            "outputTokens": 3,
            "totalTokens": 11,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    # Mock httpx.Response
    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()
    optional_params = {
        "tools": [
            {
                "type": "bash_20241022",
                "function": {
                    "name": "bash",
                    "parameters": {},
                },
            }
        ]
    }
    # Call the transformation logic
    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )
    # Check that the tool call is present in the returned message
    assert result.choices[0].message.tool_calls is not None
    assert len(result.choices[0].message.tool_calls) == 1
    tool_call = result.choices[0].message.tool_calls[0]
    assert tool_call.function.name == "bash"
    args = json.loads(tool_call.function.arguments)
    assert args["command"] == "ls -la *.py"


def test_transform_response_with_structured_response_being_called():
    """Test response transformation with structured response."""
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    # Simulate a Bedrock Converse response with a bash tool call
    response_json = {
        "additionalModelResponseFields": {},
        "metrics": {"latencyMs": 100.0},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_456",
                            "name": "json_tool_call",
                            "input": {
                                "Current_Temperature": 62,
                                "Weather_Explanation": "San Francisco typically has mild, cool weather year-round due to its coastal location and marine influence. The city is known for its fog, moderate temperatures, and relatively stable climate with little seasonal variation.",
                            },
                        }
                    }
                ],
            }
        },
        "stopReason": "tool_use",
        "usage": {
            "inputTokens": 8,
            "outputTokens": 3,
            "totalTokens": 11,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    # Mock httpx.Response
    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()
    optional_params = {
        "json_mode": True,
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get the current weather in a given location",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "location": {
                                "type": "string",
                                "description": "The city and state, e.g. San Francisco, CA",
                            },
                            "unit": {
                                "type": "string",
                                "enum": ["celsius", "fahrenheit"],
                            },
                        },
                        "required": ["location"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "json_tool_call",
                    "parameters": {
                        "$schema": "http://json-schema.org/draft-07/schema#",
                        "type": "object",
                        "required": ["Weather_Explanation", "Current_Temperature"],
                        "properties": {
                            "Weather_Explanation": {
                                "type": ["string", "null"],
                                "description": "1-2 sentences explaining the weather in the location",
                            },
                            "Current_Temperature": {
                                "type": ["number", "null"],
                                "description": "Current temperature in the location",
                            },
                        },
                        "additionalProperties": False,
                    },
                },
            },
        ],
    }
    # Call the transformation logic
    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )
    # Check that the tool call is present in the returned message
    assert result.choices[0].message.tool_calls is None

    assert result.choices[0].message.content is not None
    assert (
        result.choices[0].message.content
        == '{"Current_Temperature": 62, "Weather_Explanation": "San Francisco typically has mild, cool weather year-round due to its coastal location and marine influence. The city is known for its fog, moderate temperatures, and relatively stable climate with little seasonal variation."}'
    )


def test_transform_response_with_structured_response_calling_tool():
    """Test response transformation with structured response."""
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    # Simulate a Bedrock Converse response with a bash tool call
    response_json = {
        "metrics": {"latencyMs": 1148},
        "output": {
            "message": {
                "content": [
                    {"text": "I'll check the current weather in San Francisco for you."},
                    {
                        "toolUse": {
                            "input": {
                                "location": "San Francisco, CA",
                                "unit": "celsius",
                            },
                            "name": "get_weather",
                            "toolUseId": "tooluse_oKk__QrqSUmufMw3Q7vGaQ",
                        }
                    },
                ],
                "role": "assistant",
            }
        },
        "stopReason": "tool_use",
        "usage": {
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
            "inputTokens": 534,
            "outputTokens": 69,
            "totalTokens": 603,
        },
    }

    # Mock httpx.Response
    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()
    optional_params = {
        "json_mode": True,
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get the current weather in a given location",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "location": {
                                "type": "string",
                                "description": "The city and state, e.g. San Francisco, CA",
                            },
                            "unit": {
                                "type": "string",
                                "enum": ["celsius", "fahrenheit"],
                            },
                        },
                        "required": ["location"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "json_tool_call",
                    "parameters": {
                        "$schema": "http://json-schema.org/draft-07/schema#",
                        "type": "object",
                        "required": ["Weather_Explanation", "Current_Temperature"],
                        "properties": {
                            "Weather_Explanation": {
                                "type": ["string", "null"],
                                "description": "1-2 sentences explaining the weather in the location",
                            },
                            "Current_Temperature": {
                                "type": ["number", "null"],
                                "description": "Current temperature in the location",
                            },
                        },
                        "additionalProperties": False,
                    },
                },
            },
        ],
    }
    # Call the transformation logic
    result = config._transform_response(
        model="bedrock/eu.anthropic.claude-sonnet-4-20250514-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )
    # Check that the tool call is present in the returned message
    assert result.choices[0].message.tool_calls is not None
    assert len(result.choices[0].message.tool_calls) == 1
    assert result.choices[0].message.tool_calls[0].function.name == "get_weather"
    assert (
        result.choices[0].message.tool_calls[0].function.arguments
        == '{"location": "San Francisco, CA", "unit": "celsius"}'
    )


def _mock_converse_response() -> MagicMock:
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.headers = {}
    mock_response.json.return_value = {
        "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
        "stopReason": "end_turn",
        "usage": {"inputTokens": 10, "outputTokens": 5, "totalTokens": 15},
    }
    mock_response.text = json.dumps(mock_response.json.return_value)
    return mock_response


async def _acompletion_captured_request_body(tools: list, messages: list) -> dict:
    from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler

    client = AsyncHTTPHandler()
    with patch.object(client, "post", return_value=_mock_converse_response()) as mock_post:
        response = await litellm.acompletion(
            model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
            messages=messages,
            tools=tools,
            aws_access_key_id="fake-access-key",
            aws_secret_access_key="fake-secret-key",
            aws_region_name="us-west-2",
            client=client,
        )

    assert response.choices[0].message.content == "ok"
    mock_post.assert_called_once()
    assert mock_post.call_args.kwargs["url"].endswith("/converse")
    return json.loads(mock_post.call_args.kwargs["data"])


@pytest.mark.asyncio
async def test_bedrock_bash_tool_acompletion():
    """Bash tool rides acompletion into the converse request body without any network call."""
    tools = [
        {
            "type": "bash_20241022",
            "name": "bash",
        }
    ]
    messages = [{"role": "user", "content": "run ls command and find all python files"}]

    request_body = await _acompletion_captured_request_body(tools=tools, messages=messages)

    additional_fields = request_body["additionalModelRequestFields"]
    assert additional_fields["tools"] == [{"type": "bash_20241022", "name": "bash"}]
    assert "anthropic_beta" in additional_fields
    assert request_body["messages"][0]["content"][0]["text"] == "run ls command and find all python files"


@pytest.mark.asyncio
async def test_bedrock_computer_use_acompletion():
    """Test Bedrock computer use with acompletion function."""

    # Test with computer use tool
    tools = [
        {
            "type": "computer_20250124",
            "name": "computer",
            "display_height_px": 768,
            "display_width_px": 1024,
            "display_number": 0,
        }
    ]

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Go to the bedrock console"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
                    },
                },
            ],
        }
    ]

    request_body = await _acompletion_captured_request_body(tools=tools, messages=messages)

    additional_fields = request_body["additionalModelRequestFields"]
    assert additional_fields["anthropic_beta"] == ["computer-use-2025-01-24"]
    computer_tools = [tool for tool in additional_fields["tools"] if tool.get("type") == "computer_20250124"]
    assert computer_tools[0]["display_height_px"] == 768
    assert computer_tools[0]["display_width_px"] == 1024
    image_blocks = [block for block in request_body["messages"][0]["content"] if "image" in block]
    assert image_blocks[0]["image"]["format"] == "png"
    assert image_blocks[0]["image"]["source"]["bytes"]


@pytest.mark.asyncio
async def test_transformation_directly():
    """Test the transformation directly to verify the request structure."""

    config = AmazonConverseConfig()

    tools = [
        {
            "type": "computer_20250124",
            "name": "computer",
            "display_height_px": 768,
            "display_width_px": 1024,
            "display_number": 0,
        },
        {
            "type": "bash_20241022",
            "name": "bash",
        },
    ]

    messages = [{"role": "user", "content": "run ls command and find all python files"}]

    # Transform request
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"tools": tools},
        litellm_params={},
        headers={},
    )

    # Verify the structure
    assert "additionalModelRequestFields" in request_data
    additional_fields = request_data["additionalModelRequestFields"]

    # Check that anthropic_beta is set correctly for computer use
    assert "anthropic_beta" in additional_fields
    assert additional_fields["anthropic_beta"] == ["computer-use-2025-01-24"]

    # Check that tools are present
    assert "tools" in additional_fields
    assert len(additional_fields["tools"]) == 2

    # Verify tool types
    tool_types = [tool.get("type") for tool in additional_fields["tools"]]
    assert "computer_20250124" in tool_types
    assert "bash_20241022" in tool_types


def test_transform_request_helper_includes_anthropic_beta_and_tools_bash():
    """Test _transform_request_helper includes anthropic_beta for bash tools."""
    config = AmazonConverseConfig()
    system_content_blocks = []
    optional_params = {
        "anthropic_beta": ["computer-use-2025-01-24"],
        "tools": [
            {
                "type": "bash_20241022",
                "name": "bash",
            }
        ],
        "some_other_param": 123,
    }
    data = config._transform_request_helper(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        system_content_blocks=system_content_blocks,
        optional_params=optional_params,
        messages=None,
    )
    assert "additionalModelRequestFields" in data
    fields = data["additionalModelRequestFields"]
    assert "anthropic_beta" in fields
    assert fields["anthropic_beta"] == ["computer-use-2025-01-24"]
    # Verify bash tool is included
    assert "tools" in fields
    assert len(fields["tools"]) == 1
    assert fields["tools"][0]["type"] == "bash_20241022"


def test_transform_request_with_multiple_tools():
    """Test transformation with multiple tools including computer, bash, and function tools."""
    config = AmazonConverseConfig()

    # Use the exact payload from the user's error
    tools = [
        {
            "type": "computer_20250124",
            "function": {
                "name": "computer",
                "parameters": {
                    "display_height_px": 768,
                    "display_width_px": 1024,
                    "display_number": 0,
                },
            },
        },
        {
            "type": "bash_20241022",
            "name": "bash",
        },
        {
            "type": "text_editor_20241022",
            "name": "str_replace_editor",
        },
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                    },
                    "required": ["location"],
                },
            },
        },
    ]

    messages = [{"role": "user", "content": "run ls command and find all python files"}]

    # Transform request
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"tools": tools},
        litellm_params={},
        headers={},
    )

    # Verify the structure
    assert "additionalModelRequestFields" in request_data
    additional_fields = request_data["additionalModelRequestFields"]

    # Check that anthropic_beta is set correctly for computer use
    assert "anthropic_beta" in additional_fields
    assert additional_fields["anthropic_beta"] == ["computer-use-2025-01-24"]

    # Check that tools are present
    assert "tools" in additional_fields
    assert len(additional_fields["tools"]) == 3  # computer, bash, text_editor tools

    # Verify tool types
    tool_types = [tool.get("type") for tool in additional_fields["tools"]]
    assert "computer_20250124" in tool_types
    assert "bash_20241022" in tool_types
    assert "text_editor_20241022" in tool_types

    # Function tools are processed separately and not included in computer use tools
    # They would be in toolConfig if present


def test_transform_request_with_computer_tool_only():
    """Test transformation with only computer tool."""
    config = AmazonConverseConfig()

    tools = [
        {
            "type": "computer_20250124",
            "name": "computer",
            "display_height_px": 768,
            "display_width_px": 1024,
            "display_number": 0,
        }
    ]

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Go to the bedrock console"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
                    },
                },
            ],
        }
    ]

    # Transform request
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"tools": tools},
        litellm_params={},
        headers={},
    )

    # Verify the structure
    assert "additionalModelRequestFields" in request_data
    additional_fields = request_data["additionalModelRequestFields"]

    # Check that anthropic_beta is set correctly for computer use
    assert "anthropic_beta" in additional_fields
    assert additional_fields["anthropic_beta"] == ["computer-use-2025-01-24"]

    # Check that tools are present
    assert "tools" in additional_fields
    assert len(additional_fields["tools"]) == 1
    assert additional_fields["tools"][0]["type"] == "computer_20250124"


def test_transform_request_with_bash_tool_only():
    """Test transformation with only bash tool."""
    config = AmazonConverseConfig()

    tools = [
        {
            "type": "bash_20241022",
            "name": "bash",
        }
    ]

    messages = [{"role": "user", "content": "run ls command and find all python files"}]

    # Transform request
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"tools": tools},
        litellm_params={},
        headers={},
    )

    # Verify the structure
    assert "additionalModelRequestFields" in request_data
    additional_fields = request_data["additionalModelRequestFields"]

    # Check that anthropic_beta is set correctly for computer use
    assert "anthropic_beta" in additional_fields
    assert additional_fields["anthropic_beta"] == ["computer-use-2025-01-24"]

    # Check that tools are present
    assert "tools" in additional_fields
    assert len(additional_fields["tools"]) == 1
    assert additional_fields["tools"][0]["type"] == "bash_20241022"


def test_transform_request_with_text_editor_tool():
    """Test transformation with text editor tool."""
    config = AmazonConverseConfig()

    tools = [
        {
            "type": "text_editor_20241022",
            "name": "str_replace_editor",
        }
    ]

    messages = [{"role": "user", "content": "Edit this text file"}]

    # Transform request
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"tools": tools},
        litellm_params={},
        headers={},
    )

    # Verify the structure
    assert "additionalModelRequestFields" in request_data
    additional_fields = request_data["additionalModelRequestFields"]

    # Check that anthropic_beta is set correctly for computer use
    assert "anthropic_beta" in additional_fields
    assert additional_fields["anthropic_beta"] == ["computer-use-2025-01-24"]

    # Check that tools are present
    assert "tools" in additional_fields
    assert len(additional_fields["tools"]) == 1
    assert additional_fields["tools"][0]["type"] == "text_editor_20241022"


def test_transform_request_with_function_tool():
    """Test transformation with function tool."""
    config = AmazonConverseConfig()

    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                    },
                    "required": ["location"],
                },
            },
        }
    ]

    messages = [{"role": "user", "content": "What's the weather like in San Francisco?"}]

    # Transform request
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"tools": tools},
        litellm_params={},
        headers={},
    )

    # Verify the structure
    # Function tools are not computer use tools, so they don't get anthropic_beta —
    # additionalModelRequestFields should be absent (not serialized as empty {})
    assert "additionalModelRequestFields" not in request_data

    assert "toolConfig" in request_data
    assert "tools" in request_data["toolConfig"]
    assert len(request_data["toolConfig"]["tools"]) == 1
    assert request_data["toolConfig"]["tools"][0]["toolSpec"]["name"] == "get_weather"


def test_map_openai_params_with_response_format():
    """Test map_openai_params with response_format."""
    config = AmazonConverseConfig()

    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                    },
                    "required": ["location"],
                },
            },
        }
    ]

    json_schema = {
        "type": "json_schema",
        "json_schema": {
            "name": "WeatherResult",
            "schema": {
                "$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "required": ["Weather_Explanation", "Current_Temperature"],
                "properties": {
                    "Weather_Explanation": {
                        "type": ["string", "null"],
                        "description": "1-2 sentences explaining the weather in the location",
                    },
                    "Current_Temperature": {
                        "type": ["number", "null"],
                        "description": "Current temperature in the location",
                    },
                },
                "additionalProperties": False,
            },
            "strict": False,
        },
    }

    optional_params = config.map_openai_params(
        non_default_params={"response_format": json_schema},
        optional_params={"tools": tools},
        model="eu.anthropic.claude-sonnet-4-20250514-v1:0",
        drop_params=False,
    )

    assert "tools" in optional_params
    assert len(optional_params["tools"]) == 2
    assert optional_params["tools"][1]["type"] == "function"
    assert optional_params["tools"][1]["function"]["name"] == "json_tool_call"


@pytest.mark.asyncio
async def test_assistant_message_cache_control():
    """Test that assistant messages with cache_control generate cachePoint blocks."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    # Test assistant message with string content and cache_control
    messages = [
        {"role": "user", "content": "Hello"},
        {
            "role": "assistant",
            "content": "Hi there!",
            "cache_control": {"type": "ephemeral"},
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    # Should have user message and assistant message
    assert len(result) == 2
    assert result[0]["role"] == "user"
    assert result[1]["role"] == "assistant"

    # Assistant message should have text content and cachePoint
    assistant_content = result[1]["content"]
    assert len(assistant_content) == 2
    assert assistant_content[0]["text"] == "Hi there!"
    assert "cachePoint" in assistant_content[1]
    assert assistant_content[1]["cachePoint"]["type"] == "default"


@pytest.mark.asyncio
async def test_assistant_message_list_content_cache_control():
    """Test assistant messages with list content and cache_control."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "Hello"},
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "This should be cached",
                    "cache_control": {"type": "ephemeral"},
                }
            ],
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    # Assistant message should have text content and cachePoint
    assistant_content = result[1]["content"]
    assert len(assistant_content) == 2
    assert assistant_content[0]["text"] == "This should be cached"
    assert "cachePoint" in assistant_content[1]
    assert assistant_content[1]["cachePoint"]["type"] == "default"


@pytest.mark.asyncio
async def test_tool_message_cache_control():
    """Test that tool messages with cache_control generate cachePoint blocks."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "What's the weather?"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_123",
                    "type": "function",
                    "function": {"name": "get_weather", "arguments": "{}"},
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "call_123",
            "content": [
                {
                    "type": "text",
                    "text": "Weather data: sunny, 25°C",
                    "cache_control": {"type": "ephemeral"},
                }
            ],
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    # Should have user, assistant, and user (tool results) messages
    assert len(result) == 3

    # Last message should contain tool result and cachePoint
    tool_message_content = result[2]["content"]
    assert len(tool_message_content) == 2

    # First should be tool result
    assert "toolResult" in tool_message_content[0]
    assert tool_message_content[0]["toolResult"]["content"][0]["text"] == "Weather data: sunny, 25°C"

    # Second should be cachePoint
    assert "cachePoint" in tool_message_content[1]
    assert tool_message_content[1]["cachePoint"]["type"] == "default"


@pytest.mark.asyncio
async def test_tool_message_string_content_cache_control():
    """Test tool messages with string content and message-level cache_control."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "What's the weather?"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_123",
                    "type": "function",
                    "function": {"name": "get_weather", "arguments": "{}"},
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "call_123",
            "content": "Weather: sunny, 25°C",
            "cache_control": {"type": "ephemeral"},
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    # Last message should contain tool result and cachePoint
    tool_message_content = result[2]["content"]
    assert len(tool_message_content) == 2

    # First should be tool result
    assert "toolResult" in tool_message_content[0]
    assert tool_message_content[0]["toolResult"]["content"][0]["text"] == "Weather: sunny, 25°C"

    # Second should be cachePoint
    assert "cachePoint" in tool_message_content[1]
    assert tool_message_content[1]["cachePoint"]["type"] == "default"


@pytest.mark.asyncio
async def test_tool_message_search_results_maps_to_bedrock_search_result_block():
    """OpenAI tool message search_results should map to Bedrock searchResult blocks."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "What is Apptio?"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "tooluse_a4rBqeZNRTKj2lTskvaO4H",
                    "type": "function",
                    "function": {
                        "name": "RAGRequest",
                        "arguments": '{"query":"What is Apptio?"}',
                    },
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "tooluse_a4rBqeZNRTKj2lTskvaO4H",
            "content": "Apptio is a company that makes calls to Bedrock using passthrough APIs via LiteLLM",
            "search_results": [
                {
                    "source": "Great Source of Information About Apptio",
                    "title": "12adbd74-46bd-4a88-88b2-0048755f6eb5",
                    "content": [
                        {"text": "Apptio is a company that makes calls to Bedrock using passthrough APIs via LiteLLM"}
                    ],
                    "citations": {"enabled": True},
                }
            ],
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )
    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )
    assert result == async_result

    tool_result = result[2]["content"][0]["toolResult"]
    assert tool_result["toolUseId"] == "tooluse_a4rBqeZNRTKj2lTskvaO4H"
    assert tool_result["status"] == "success"
    assert len(tool_result["content"]) == 1
    assert "searchResult" in tool_result["content"][0]
    assert tool_result["content"][0]["searchResult"]["title"] == "12adbd74-46bd-4a88-88b2-0048755f6eb5"


@pytest.mark.asyncio
async def test_tool_message_empty_search_results_falls_back_to_content():
    """Empty search_results must not skip normal tool content processing."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "hello"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "tooluse_empty_search",
                    "type": "function",
                    "function": {"name": "lookup", "arguments": "{}"},
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "tooluse_empty_search",
            "content": "fallback tool text",
            "search_results": [],
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )
    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )
    assert result == async_result

    tool_result = result[2]["content"][0]["toolResult"]
    assert tool_result["toolUseId"] == "tooluse_empty_search"
    assert "status" not in tool_result
    assert len(tool_result["content"]) == 1
    assert tool_result["content"][0]["text"] == "fallback tool text"


def test_transform_response_omits_annotations_when_citations_not_stitched():
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 100},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "citationsContent": {
                            "content": [{"text": "cited sentence only in citations"}],
                            "citations": [
                                {
                                    "location": {
                                        "searchResultLocation": {
                                            "start": 0,
                                            "end": 5,
                                        }
                                    },
                                    "source": "https://example.com",
                                    "title": "Example",
                                }
                            ],
                        }
                    },
                    {"text": "separate assistant answer"},
                ],
            }
        },
        "stopReason": "end_turn",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 5,
            "totalTokens": 15,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=ModelResponse(),
        stream=False,
        logging_obj=None,
        optional_params={},
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    message = result.choices[0].message
    assert message.content == "separate assistant answer"
    assert message.model_dump().get("annotations") is None


def test_extract_search_results_text_counts_hidden_tool_payload():
    from litellm.litellm_core_utils.prompt_templates.common_utils import (
        convert_content_list_to_str,
        extract_search_results_text,
    )
    from litellm.litellm_core_utils.token_counter import token_counter

    hidden = "x" * 500
    message = {
        "role": "tool",
        "content": "small",
        "search_results": [
            {
                "source": "s",
                "title": "t",
                "content": [{"text": hidden}],
            }
        ],
    }

    extracted = extract_search_results_text(message["search_results"])
    assert hidden in extracted
    assert "st" in extracted
    assert len(convert_content_list_to_str(message)) > len("small")

    tokens_with_search = token_counter(
        model="gpt-3.5-turbo",
        messages=[message],
    )
    tokens_without_search = token_counter(
        model="gpt-3.5-turbo",
        messages=[{"role": "tool", "content": "small"}],
    )
    assert tokens_with_search > tokens_without_search

    huge_title = "y" * 500
    title_only_message = {
        "role": "tool",
        "content": "small",
        "search_results": [
            {"source": "s", "title": huge_title, "content": []},
        ],
    }
    assert len(extract_search_results_text(title_only_message["search_results"])) >= 500
    tokens_title_bypass = token_counter(
        model="gpt-3.5-turbo",
        messages=[title_only_message],
    )
    assert tokens_title_bypass > tokens_without_search


@pytest.mark.asyncio
async def test_assistant_tool_calls_cache_control():
    """Test that assistant tool_calls with cache_control generate cachePoint blocks."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "Calculate 2+2"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_proxy_123",
                    "type": "function",
                    "function": {"name": "calc", "arguments": "{}"},
                    "cache_control": {"type": "ephemeral"},
                }
            ],
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    # Assistant message should have tool use and cachePoint
    assistant_content = result[1]["content"]
    assert len(assistant_content) == 2

    # First should be tool use
    assert "toolUse" in assistant_content[0]
    assert assistant_content[0]["toolUse"]["name"] == "calc"
    assert assistant_content[0]["toolUse"]["toolUseId"] == "call_proxy_123"

    # Second should be cachePoint
    assert "cachePoint" in assistant_content[1]
    assert assistant_content[1]["cachePoint"]["type"] == "default"


@pytest.mark.asyncio
async def test_multiple_tool_calls_with_mixed_cache_control():
    """Test multiple tool calls where only some have cache_control."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "Do multiple calculations"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_1",
                    "type": "function",
                    "function": {"name": "calc", "arguments": '{"expr": "2+2"}'},
                    "cache_control": {"type": "ephemeral"},
                },
                {
                    "id": "call_2",
                    "type": "function",
                    "function": {"name": "calc", "arguments": '{"expr": "3+3"}'},
                    # No cache_control
                },
            ],
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    # Assistant message should have: toolUse1, cachePoint, toolUse2
    assistant_content = result[1]["content"]
    assert len(assistant_content) == 3

    # First tool use with cache
    assert "toolUse" in assistant_content[0]
    assert assistant_content[0]["toolUse"]["toolUseId"] == "call_1"

    # Cache point for first tool
    assert "cachePoint" in assistant_content[1]
    assert assistant_content[1]["cachePoint"]["type"] == "default"

    # Second tool use without cache
    assert "toolUse" in assistant_content[2]
    assert assistant_content[2]["toolUse"]["toolUseId"] == "call_2"


@pytest.mark.asyncio
async def test_no_cache_control_no_cache_point():
    """Test that messages without cache_control don't generate cachePoint blocks."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": "Hi there!"},  # No cache_control
        {
            "role": "tool",
            "tool_call_id": "call_123",
            "content": "Tool result",  # No cache_control
        },
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result

    # Assistant message should only have text content, no cachePoint
    assistant_content = result[1]["content"]
    assert len(assistant_content) == 1
    assert assistant_content[0]["text"] == "Hi there!"

    # Tool message should only have tool result, no cachePoint
    tool_content = result[2]["content"]
    assert len(tool_content) == 1
    assert "toolResult" in tool_content[0]


# ============================================================================
# Guarded Text Feature Tests
# ============================================================================


def test_guarded_text_wraps_in_guardrail_converse_content():
    """Test that guarded_text content type gets wrapped in guardContent blocks."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Regular text content"},
                {"type": "guarded_text", "text": "This should be guarded"},
                {"type": "text", "text": "More regular text"},
            ],
        }
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="us.amazon.nova-pro-v1:0",
        llm_provider="bedrock_converse",
    )

    # Should have 1 message
    assert len(result) == 1
    assert result[0]["role"] == "user"

    # Should have 3 content blocks
    content = result[0]["content"]
    assert len(content) == 3

    # First and third should be regular text
    assert "text" in content[0]
    assert content[0]["text"] == "Regular text content"
    assert "text" in content[2]
    assert content[2]["text"] == "More regular text"
    # Second should be guardContent
    assert "guardContent" in content[1]
    assert content[1]["guardContent"]["text"]["text"] == "This should be guarded"


def test_guarded_text_with_system_messages():
    """Test guarded_text with system messages using the full transformation."""
    config = AmazonConverseConfig()

    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What is the main topic of this legal document?",
                },
                {
                    "type": "guarded_text",
                    "text": "This is a set of very long instructions that you will follow. Here is a legal document that you will use to answer the user's question.",
                },
            ],
        },
    ]

    optional_params = {
        "guardrailConfig": {
            "guardrailIdentifier": "gr-abc123",
            "guardrailVersion": "DRAFT",
        }
    }

    result = config._transform_request(
        model="us.amazon.nova-pro-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    # Should have system content blocks
    assert "system" in result
    assert len(result["system"]) == 1
    assert result["system"][0]["text"] == "You are a helpful assistant."

    # Should have 1 message (system messages are removed)
    assert "messages" in result
    assert len(result["messages"]) == 1

    # User message should have both regular text and guarded text
    user_message = result["messages"][0]
    assert user_message["role"] == "user"
    content = user_message["content"]
    assert len(content) == 2

    # First should be regular text
    assert "text" in content[0]
    assert content[0]["text"] == "What is the main topic of this legal document?"
    # Second should be guardContent
    assert "guardContent" in content[1]
    assert (
        content[1]["guardContent"]["text"]["text"]
        == "This is a set of very long instructions that you will follow. Here is a legal document that you will use to answer the user's question."
    )


def test_guarded_text_with_mixed_content_types():
    """Test guarded_text with mixed content types including images."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Look at this image"},
                {
                    "type": "image_url",
                    "image_url": {"url": "data:image/png;base64,test"},
                },
                {
                    "type": "guarded_text",
                    "text": "This sensitive content should be guarded",
                },
            ],
        }
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="us.amazon.nova-pro-v1:0",
        llm_provider="bedrock_converse",
    )

    # Should have 1 message
    assert len(result) == 1
    assert result[0]["role"] == "user"

    # Should have 3 content blocks
    content = result[0]["content"]
    assert len(content) == 3

    # First should be regular text
    assert "text" in content[0]
    assert content[0]["text"] == "Look at this image"

    # Second should be image
    assert "image" in content[1]

    # Third should be guardContent
    assert "guardContent" in content[2]
    assert content[2]["guardContent"]["text"]["text"] == "This sensitive content should be guarded"


@pytest.mark.asyncio
async def test_async_guarded_text():
    """Test async version of guarded_text processing."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
    )

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Hello"},
                {"type": "guarded_text", "text": "This should be guarded"},
            ],
        }
    ]

    result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="us.amazon.nova-pro-v1:0",
        llm_provider="bedrock_converse",
    )

    # Should have 1 message
    assert len(result) == 1
    assert result[0]["role"] == "user"

    # Should have 2 content blocks
    content = result[0]["content"]
    assert len(content) == 2

    # First should be regular text
    assert "text" in content[0]
    assert content[0]["text"] == "Hello"

    # Second should be guardContent
    assert "guardContent" in content[1]
    assert content[1]["guardContent"]["text"]["text"] == "This should be guarded"


def test_guarded_text_with_tool_calls():
    """Test guarded_text with tool calls in the conversation."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What's the weather?"},
                {
                    "type": "guarded_text",
                    "text": "Please be careful with sensitive information",
                },
            ],
        },
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_123",
                    "type": "function",
                    "function": {"name": "get_weather", "arguments": "{}"},
                }
            ],
        },
        {"role": "tool", "tool_call_id": "call_123", "content": "It's sunny and 25°C"},
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="us.amazon.nova-pro-v1:0",
        llm_provider="bedrock_converse",
    )

    # Should have 3 messages
    assert len(result) == 3

    # First message (user) should have both text and guarded_text
    user_message = result[0]
    assert user_message["role"] == "user"
    content = user_message["content"]
    assert len(content) == 2

    # First should be regular text
    assert "text" in content[0]
    assert content[0]["text"] == "What's the weather?"

    # Second should be guardContent
    assert "guardContent" in content[1]
    assert content[1]["guardContent"]["text"]["text"] == "Please be careful with sensitive information"

    # Other messages should not have guardContent
    for i in range(1, 3):
        content = result[i]["content"]
        for block in content:
            assert "guardContent" not in block


def test_guarded_text_guardrail_config_preserved():
    """Test that guardrailConfig is preserved when using guarded_text."""
    config = AmazonConverseConfig()

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Hello"},
                {"type": "guarded_text", "text": "This should be guarded"},
            ],
        }
    ]

    optional_params = {
        "guardrailConfig": {
            "guardrailIdentifier": "gr-abc123",
            "guardrailVersion": "DRAFT",
        }
    }

    result = config._transform_request(
        model="us.amazon.nova-pro-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert "guardrailConfig" in result
    assert result["guardrailConfig"]["guardrailIdentifier"] == "gr-abc123"

    assert "inferenceConfig" in result
    assert "guardrailConfig" not in result["inferenceConfig"]


def test_auto_convert_last_user_message_to_guarded_text():
    """Test that last user message is automatically converted to guarded_text when guardrailConfig is present."""
    config = AmazonConverseConfig()

    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What is the main topic of this legal document?",
                }
            ],
        }
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify the conversion
    assert len(converted_messages) == 1
    assert converted_messages[0]["role"] == "user"
    assert len(converted_messages[0]["content"]) == 1
    assert converted_messages[0]["content"][0]["type"] == "guarded_text"
    assert converted_messages[0]["content"][0]["text"] == "What is the main topic of this legal document?"


def test_auto_convert_last_user_message_string_content():
    """Test that last user message with string content is automatically converted to guarded_text when guardrailConfig is present."""
    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "What is the main topic of this legal document?"}]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify the conversion
    assert len(converted_messages) == 1
    assert converted_messages[0]["role"] == "user"
    assert len(converted_messages[0]["content"]) == 1
    assert converted_messages[0]["content"][0]["type"] == "guarded_text"
    assert converted_messages[0]["content"][0]["text"] == "What is the main topic of this legal document?"


def test_no_conversion_when_no_guardrail_config():
    """Test that no conversion happens when guardrailConfig is not present."""
    config = AmazonConverseConfig()

    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What is the main topic of this legal document?",
                }
            ],
        }
    ]

    optional_params = {}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify no conversion happened
    assert converted_messages == messages


def test_no_conversion_when_guarded_text_already_present():
    """Test that no conversion happens when guarded_text is already present in the last user message."""
    config = AmazonConverseConfig()

    messages = [
        {
            "role": "user",
            "content": [{"type": "guarded_text", "text": "This is already guarded"}],
        }
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify no conversion happened
    assert converted_messages == messages


def test_auto_convert_with_mixed_content():
    """Test that only text elements are converted to guarded_text, other content types are preserved."""
    config = AmazonConverseConfig()

    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What is the main topic of this legal document?",
                },
                {
                    "type": "image_url",
                    "image_url": {"url": "https://example.com/image.jpg"},
                },
            ],
        }
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify the conversion
    assert len(converted_messages) == 1
    assert converted_messages[0]["role"] == "user"
    assert len(converted_messages[0]["content"]) == 2

    # First element should be converted to guarded_text
    assert converted_messages[0]["content"][0]["type"] == "guarded_text"
    assert converted_messages[0]["content"][0]["text"] == "What is the main topic of this legal document?"

    # Second element should remain unchanged
    assert converted_messages[0]["content"][1]["type"] == "image_url"
    assert converted_messages[0]["content"][1]["image_url"]["url"] == "https://example.com/image.jpg"


def test_auto_convert_in_full_transformation():
    """Test that the automatic conversion works in the full transformation pipeline."""
    config = AmazonConverseConfig()

    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What is the main topic of this legal document?",
                }
            ],
        }
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the full transformation
    result = config._transform_request(
        model="anthropic.claude-3-sonnet-20240229-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    # Verify the transformation worked
    assert "messages" in result
    assert len(result["messages"]) == 1

    # The message should have guardContent
    message = result["messages"][0]
    assert "content" in message
    assert len(message["content"]) == 1
    assert "guardContent" in message["content"][0]
    assert message["content"][0]["guardContent"]["text"]["text"] == "What is the main topic of this legal document?"


def test_convert_consecutive_user_messages_to_guarded_text():
    """Test that consecutive user messages at the end are converted to guarded_text."""
    config = AmazonConverseConfig()

    messages = [
        {"role": "user", "content": [{"type": "text", "text": "First user message"}]},
        {"role": "assistant", "content": "Assistant response"},
        {"role": "user", "content": [{"type": "text", "text": "Second user message"}]},
        {"role": "user", "content": [{"type": "text", "text": "Third user message"}]},
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify the conversion - only the last two user messages should be converted
    assert len(converted_messages) == 4

    # First user message should remain unchanged
    assert converted_messages[0]["role"] == "user"
    assert converted_messages[0]["content"][0]["type"] == "text"
    assert converted_messages[0]["content"][0]["text"] == "First user message"

    # Assistant message should remain unchanged
    assert converted_messages[1]["role"] == "assistant"
    assert converted_messages[1]["content"] == "Assistant response"

    # Second user message should be converted to guarded_text
    assert converted_messages[2]["role"] == "user"
    assert converted_messages[2]["content"][0]["type"] == "guarded_text"
    assert converted_messages[2]["content"][0]["text"] == "Second user message"

    # Third user message should be converted to guarded_text
    assert converted_messages[3]["role"] == "user"
    assert converted_messages[3]["content"][0]["type"] == "guarded_text"
    assert converted_messages[3]["content"][0]["text"] == "Third user message"


def test_convert_all_user_messages_when_all_consecutive():
    """Test that all user messages are converted when they are all consecutive at the end."""
    config = AmazonConverseConfig()

    messages = [
        {"role": "user", "content": [{"type": "text", "text": "First user message"}]},
        {"role": "user", "content": [{"type": "text", "text": "Second user message"}]},
        {"role": "user", "content": [{"type": "text", "text": "Third user message"}]},
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify all three user messages are converted
    assert len(converted_messages) == 3

    for i in range(3):
        assert converted_messages[i]["role"] == "user"
        assert converted_messages[i]["content"][0]["type"] == "guarded_text"

    assert converted_messages[0]["content"][0]["text"] == "First user message"
    assert converted_messages[1]["content"][0]["text"] == "Second user message"
    assert converted_messages[2]["content"][0]["text"] == "Third user message"


def test_convert_consecutive_user_messages_with_string_content():
    """Test that consecutive user messages with string content are converted to guarded_text."""
    config = AmazonConverseConfig()

    messages = [
        {"role": "assistant", "content": "Assistant response"},
        {"role": "user", "content": "First user message"},
        {"role": "user", "content": "Second user message"},
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify the conversion
    assert len(converted_messages) == 3

    # Assistant message should remain unchanged
    assert converted_messages[0]["role"] == "assistant"
    assert converted_messages[0]["content"] == "Assistant response"

    # Both user messages should be converted to guarded_text
    assert converted_messages[1]["role"] == "user"
    assert len(converted_messages[1]["content"]) == 1
    assert converted_messages[1]["content"][0]["type"] == "guarded_text"
    assert converted_messages[1]["content"][0]["text"] == "First user message"

    assert converted_messages[2]["role"] == "user"
    assert len(converted_messages[2]["content"]) == 1
    assert converted_messages[2]["content"][0]["type"] == "guarded_text"
    assert converted_messages[2]["content"][0]["text"] == "Second user message"


def test_skip_consecutive_user_messages_with_existing_guarded_text():
    """Test that consecutive user messages with existing guarded_text are skipped."""
    config = AmazonConverseConfig()

    messages = [
        {
            "role": "user",
            "content": [{"type": "guarded_text", "text": "Already guarded"}],
        },
        {"role": "user", "content": [{"type": "text", "text": "Should be converted"}]},
    ]

    optional_params = {"guardrailConfig": {"guardrailIdentifier": "gr-abc123", "guardrailVersion": "1"}}

    # Test the helper method directly
    converted_messages = config._convert_consecutive_user_messages_to_guarded_text(messages, optional_params)

    # Verify the conversion
    assert len(converted_messages) == 2

    # First message should remain unchanged (already has guarded_text)
    assert converted_messages[0]["role"] == "user"
    assert converted_messages[0]["content"][0]["type"] == "guarded_text"
    assert converted_messages[0]["content"][0]["text"] == "Already guarded"

    # Second message should be converted
    assert converted_messages[1]["role"] == "user"
    assert converted_messages[1]["content"][0]["type"] == "guarded_text"
    assert converted_messages[1]["content"][0]["text"] == "Should be converted"


def test_request_metadata_parameter_support():
    """Test that requestMetadata is in supported parameters."""
    config = AmazonConverseConfig()
    supported_params = config.get_supported_openai_params(
        model="bedrock/converse/us.anthropic.claude-sonnet-4-20250514-v1:0"
    )
    assert "requestMetadata" in supported_params


def test_request_metadata_transformation():
    """Test that requestMetadata is properly transformed to top-level field."""
    config = AmazonConverseConfig()

    request_metadata = {
        "cost_center": "engineering",
        "user_id": "user123",
        "session_id": "sess_abc123",
    }

    messages = [
        {"role": "user", "content": "Hello!"},
    ]

    # Transform request with requestMetadata
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"requestMetadata": request_metadata},
        litellm_params={},
        headers={},
    )

    # Verify that requestMetadata appears as top-level field
    assert "requestMetadata" in request_data
    assert request_data["requestMetadata"] == request_metadata


def test_request_metadata_validation():
    """Test validation of requestMetadata constraints."""
    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "Hello!"}]

    # Test valid metadata
    valid_metadata = {
        "cost_center": "engineering",
        "user_id": "user123",
    }

    # Should not raise exception
    config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"requestMetadata": valid_metadata},
        litellm_params={},
        headers={},
    )

    # Test too many items (max 16)
    too_many_items = {f"key_{i}": f"value_{i}" for i in range(17)}

    with pytest.raises(Exception, match="maximum of 16 items") as exc_info:
        config._transform_request(
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            messages=messages,
            optional_params={"requestMetadata": too_many_items},
            litellm_params={},
            headers={},
        )
    e = exc_info.value
    assert "maximum of 16 items" in str(e).lower()


def test_request_metadata_key_constraints():
    """Test key constraint validation."""
    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "Hello!"}]

    # Test key too long (max 256 characters)
    long_key = "a" * 257
    invalid_metadata = {long_key: "value"}

    with pytest.raises(Exception, match=r"(?i)key length|256 characters"):
        config._transform_request(
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            messages=messages,
            optional_params={"requestMetadata": invalid_metadata},
            litellm_params={},
            headers={},
        )

    # Test empty key
    invalid_metadata = {"": "value"}

    with pytest.raises(Exception, match=r"key '' must be 1-256 characters"):
        config._transform_request(
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            messages=messages,
            optional_params={"requestMetadata": invalid_metadata},
            litellm_params={},
            headers={},
        )


def test_request_metadata_value_constraints():
    """Test value constraint validation."""
    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "Hello!"}]

    # Test value too long (max 256 characters)
    long_value = "a" * 257
    invalid_metadata = {"key": long_value}

    with pytest.raises(Exception, match=r"(?i)value length|256 characters"):
        config._transform_request(
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            messages=messages,
            optional_params={"requestMetadata": invalid_metadata},
            litellm_params={},
            headers={},
        )

    # Test empty value (should be allowed)
    valid_metadata = {"key": ""}

    # Should not raise exception
    config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"requestMetadata": valid_metadata},
        litellm_params={},
        headers={},
    )


@pytest.mark.parametrize("metadata", [{"ticket": "a\u00a0b"}, {"a\u2003b": "ticket"}])
def test_request_metadata_rejects_whitespace_outside_ascii(metadata):
    with pytest.raises(litellm.exceptions.BadRequestError, match=r"must be [01]-256 characters of"):
        AmazonConverseConfig()._transform_request(
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            messages=[{"role": "user", "content": "Hello!"}],
            optional_params={"requestMetadata": metadata},
            litellm_params={},
            headers={},
        )


def test_request_metadata_character_pattern():
    """Test character pattern validation for keys and values."""
    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "Hello!"}]

    # Test valid characters
    valid_metadata = {
        "cost-center_2024": "engineering@team#1",
        "user:id": "$100.00",
        "session+token": "/path/to=resource",
    }

    # Should not raise exception
    config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"requestMetadata": valid_metadata},
        litellm_params={},
        headers={},
    )


def test_request_metadata_with_other_params():
    """Test that requestMetadata works alongside other parameters."""
    config = AmazonConverseConfig()

    request_metadata = {"experiment": "test_A", "user_type": "premium"}

    messages = [
        {"role": "user", "content": "What's the weather?"},
    ]

    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get the current weather",
                "parameters": {
                    "type": "object",
                    "properties": {"location": {"type": "string"}},
                    "required": ["location"],
                },
            },
        }
    ]

    # Transform request with multiple parameters including request_metadata
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={
            "requestMetadata": request_metadata,
            "tools": tools,
            "max_tokens": 100,
            "temperature": 0.7,
        },
        litellm_params={},
        headers={},
    )

    # Verify requestMetadata is at top level
    assert "requestMetadata" in request_data
    assert request_data["requestMetadata"] == request_metadata

    # Verify other parameters are also processed correctly
    assert "toolConfig" in request_data
    assert "inferenceConfig" in request_data
    assert request_data["inferenceConfig"]["temperature"] == 0.7


def test_request_metadata_empty():
    """Test handling of empty requestMetadata."""
    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "Hello!"}]

    # Empty dict should be allowed
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={"requestMetadata": {}},
        litellm_params={},
        headers={},
    )

    assert "requestMetadata" in request_data
    assert request_data["requestMetadata"] == {}


def test_request_metadata_not_provided():
    """Test that requestMetadata is not included when not provided."""
    config = AmazonConverseConfig()

    messages = [{"role": "user", "content": "Hello!"}]

    # No requestMetadata provided
    request_data = config._transform_request(
        model="anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=messages,
        optional_params={},
        litellm_params={},
        headers={},
    )

    # requestMetadata should not be in the request
    assert "requestMetadata" not in request_data


def test_empty_assistant_message_handling():
    """
    Test that empty assistant messages are handled correctly by replacing
    empty or whitespace-only content with a placeholder to prevent AWS Bedrock
    Converse API 400 Bad Request errors.
    """
    # Import the litellm module that factory.py uses to ensure we patch the correct reference
    import litellm.litellm_core_utils.prompt_templates.factory as factory_module
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    # Test case 1: Empty string content - test with modify_params=True to prevent merging
    messages = [
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": ""},  # Empty content
        {"role": "user", "content": "How are you?"},
    ]

    # Use patch to ensure we modify the litellm reference that factory.py actually uses
    # This avoids issues with module reloading during parallel test execution
    with patch.object(factory_module.litellm, "modify_params", True):
        result = _bedrock_converse_messages_pt(
            messages=messages,
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            llm_provider="bedrock_converse",
        )

        # Should have 3 messages: user, assistant (with placeholder), user
        assert len(result) == 3
        assert result[0]["role"] == "user"
        assert result[1]["role"] == "assistant"
        assert result[2]["role"] == "user"

        # Assistant message should have placeholder text instead of empty content
        # When modify_params=True, empty assistant messages get replaced with DEFAULT_ASSISTANT_CONTINUE_MESSAGE
        assert len(result[1]["content"]) == 1
        assert result[1]["content"][0]["text"] == "Please continue."

        # Test case 2: Whitespace-only content
        messages = [
            {"role": "user", "content": "Hello"},
            {"role": "assistant", "content": "   "},  # Whitespace-only content
            {"role": "user", "content": "How are you?"},
        ]

        result = _bedrock_converse_messages_pt(
            messages=messages,
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            llm_provider="bedrock_converse",
        )

        # Assistant message should have placeholder text instead of whitespace
        assert len(result[1]["content"]) == 1
        assert result[1]["content"][0]["text"] == "Please continue."

        # Test case 3: Empty list content
        messages = [
            {"role": "user", "content": "Hello"},
            {
                "role": "assistant",
                "content": [{"type": "text", "text": ""}],
            },  # Empty text in list
            {"role": "user", "content": "How are you?"},
        ]

        result = _bedrock_converse_messages_pt(
            messages=messages,
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            llm_provider="bedrock_converse",
        )

        # Assistant message should have placeholder text instead of empty text
        assert len(result[1]["content"]) == 1
        assert result[1]["content"][0]["text"] == "Please continue."

        # Test case 4: Normal content should not be affected
        messages = [
            {"role": "user", "content": "Hello"},
            {
                "role": "assistant",
                "content": "I'm doing well, thank you!",
            },  # Normal content
            {"role": "user", "content": "How are you?"},
        ]

        result = _bedrock_converse_messages_pt(
            messages=messages,
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            llm_provider="bedrock_converse",
        )

        # Assistant message should keep original content
        assert len(result[1]["content"]) == 1
        assert result[1]["content"][0]["text"] == "I'm doing well, thank you!"


def test_bedrock_converse_trailing_prefix_assistant_skips_user_continue():
    """Assistant prefill (prefix: true) must not inject a dummy user 'Please continue.' turn."""
    import litellm.litellm_core_utils.prompt_templates.factory as factory_module
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "Hello, how are you?"},
        {
            "role": "assistant",
            "content": "Good as",
            "prefix": True,
        },
    ]

    with patch.object(factory_module.litellm, "modify_params", True):
        result = _bedrock_converse_messages_pt(
            messages=list(messages),
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            llm_provider="bedrock_converse",
        )

    assert len(result) == 2
    assert result[0]["role"] == "user"
    assert result[1]["role"] == "assistant"
    assert result[1]["content"][0]["text"] == "Good as"


def test_bedrock_converse_leading_prefix_assistant_skips_user_continue():
    """Leading assistant with prefix: true should not prepend dummy user."""
    import litellm.litellm_core_utils.prompt_templates.factory as factory_module
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "assistant", "content": "Partial", "prefix": True},
        {"role": "user", "content": "Go on"},
    ]

    with patch.object(factory_module.litellm, "modify_params", True):
        result = _bedrock_converse_messages_pt(
            messages=list(messages),
            model="anthropic.claude-haiku-4-5-20251001-v1:0",
            llm_provider="bedrock_converse",
        )

    assert len(result) == 2
    assert result[0]["role"] == "assistant"
    assert result[0]["content"][0]["text"] == "Partial"
    assert result[1]["role"] == "user"


def test_is_nova_2_model():
    """Test the _is_nova_2_model() method for detecting Nova 2 models."""
    config = AmazonConverseConfig()

    # Test with amazon.nova-2-lite-v1:0
    assert config._is_nova_2_model("amazon.nova-2-lite-v1:0") is True

    # Test with regional variants
    assert config._is_nova_2_model("us.amazon.nova-2-lite-v1:0") is True
    assert config._is_nova_2_model("eu.amazon.nova-2-lite-v1:0") is True
    assert config._is_nova_2_model("apac.amazon.nova-2-lite-v1:0") is True

    # Test with other Nova 2 variants (pro, micro)
    assert config._is_nova_2_model("amazon.nova-pro-1-5-v1:0") is False
    assert config._is_nova_2_model("amazon.nova-micro-1-5-v1:0") is False
    assert config._is_nova_2_model("us.amazon.nova-pro-1-5-v1:0") is False
    assert config._is_nova_2_model("eu.amazon.nova-micro-1-5-v1:0") is False

    # Test with non-Nova-1.5 lite models (should return False)
    assert config._is_nova_2_model("amazon.nova-lite-v1:0") is False
    assert config._is_nova_2_model("amazon.nova-pro-v1:0") is False
    assert config._is_nova_2_model("amazon.nova-micro-v1:0") is False

    # Test with Nova v1:0 models (should return False)
    assert config._is_nova_2_model("us.amazon.nova-lite-v1:0") is False
    assert config._is_nova_2_model("eu.amazon.nova-pro-v1:0") is False

    # Test with completely different models (should return False)
    assert config._is_nova_2_model("anthropic.claude-haiku-4-5-20251001-v1:0") is False
    assert config._is_nova_2_model("meta.llama3-70b-instruct-v1:0") is False
    assert config._is_nova_2_model("mistral.mistral-7b-instruct-v0:2") is False


def test_thinking_with_max_completion_tokens():
    """Test that thinking respects max_completion_tokens parameter."""
    config = AmazonConverseConfig()

    # Test case 1: max_completion_tokens is specified - should NOT set maxTokens automatically
    non_default_params_with_max_completion = {
        "thinking": {"type": "enabled", "budget_tokens": 5000},
        "max_completion_tokens": 10000,
    }
    optional_params = {}

    result = config.map_openai_params(
        non_default_params=non_default_params_with_max_completion,
        optional_params=optional_params,
        model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        drop_params=False,
    )

    # Should have maxTokens set to max_completion_tokens value
    assert "maxTokens" in result
    assert result["maxTokens"] == 10000
    # Should have thinking config
    assert "thinking" in result
    assert result["thinking"]["type"] == "enabled"
    assert result["thinking"]["budget_tokens"] == 5000

    # Test case 2: max_tokens is specified - should NOT set maxTokens automatically
    non_default_params_with_max_tokens = {
        "thinking": {"type": "enabled", "budget_tokens": 5000},
        "max_tokens": 8000,
    }
    optional_params = {}

    result = config.map_openai_params(
        non_default_params=non_default_params_with_max_tokens,
        optional_params=optional_params,
        model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        drop_params=False,
    )

    # Should have maxTokens set to max_tokens value
    assert "maxTokens" in result
    assert result["maxTokens"] == 8000
    # Should have thinking config
    assert "thinking" in result
    assert result["thinking"]["type"] == "enabled"
    assert result["thinking"]["budget_tokens"] == 5000

    # Test case 3: Neither max_tokens nor max_completion_tokens specified - should set maxTokens automatically
    from litellm.constants import DEFAULT_MAX_TOKENS

    non_default_params_without_max = {
        "thinking": {"type": "enabled", "budget_tokens": 5000},
    }
    optional_params = {}

    result = config.map_openai_params(
        non_default_params=non_default_params_without_max,
        optional_params=optional_params,
        model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        drop_params=False,
    )

    # Should have maxTokens set to budget_tokens + DEFAULT_MAX_TOKENS
    assert "maxTokens" in result
    assert result["maxTokens"] == 5000 + DEFAULT_MAX_TOKENS
    # Should have thinking config
    assert "thinking" in result
    assert result["thinking"]["type"] == "enabled"
    assert result["thinking"]["budget_tokens"] == 5000


def test_anthropic_messages_converse_thinking_budget_is_preserved_in_request_body():
    model = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"
    config = AmazonConverseConfig()
    optional_params = config.map_openai_params(
        non_default_params={
            "thinking": {"type": "enabled", "budget_tokens": 1025},
            "max_tokens": 1026,
        },
        optional_params={},
        model=model,
        drop_params=False,
    )
    request = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "What is 2+2?"}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert request["additionalModelRequestFields"]["thinking"] == {
        "type": "enabled",
        "budget_tokens": 1025,
    }


def test_drop_thinking_param_when_thinking_blocks_missing():
    """
    Test that thinking param is dropped when modify_params=True and
    thinking_blocks are missing from assistant message with tool_calls.

    This prevents the Anthropic/Bedrock error:
    "Expected thinking or redacted_thinking, but found tool_use"

    Related issue: https://github.com/BerriAI/litellm/issues/14194
    """
    from litellm.utils import last_assistant_with_tool_calls_has_no_thinking_blocks

    # Save original modify_params setting
    original_modify_params = litellm.modify_params

    try:
        # Test case 1: thinking should be dropped when modify_params=True
        # and assistant message has tool_calls but no thinking_blocks
        litellm.modify_params = True

        messages_without_thinking_blocks = [
            {"role": "user", "content": "Search for weather"},
            {
                "role": "assistant",
                "content": "",
                "tool_calls": [
                    {
                        "id": "call_123",
                        "type": "function",
                        "function": {"name": "search", "arguments": "{}"},
                    }
                ],
                # No thinking_blocks - simulates OpenAI-compatible client
            },
            {"role": "tool", "content": "Weather is sunny", "tool_call_id": "call_123"},
        ]

        optional_params = {"thinking": {"type": "enabled", "budget_tokens": 1000}}

        # Verify the condition is detected
        assert last_assistant_with_tool_calls_has_no_thinking_blocks(messages_without_thinking_blocks), (
            "Should detect missing thinking_blocks"
        )

        # Simulate what _transform_request_helper does
        if (
            optional_params.get("thinking") is not None
            and messages_without_thinking_blocks is not None
            and last_assistant_with_tool_calls_has_no_thinking_blocks(messages_without_thinking_blocks)
        ):
            if litellm.modify_params:
                optional_params.pop("thinking", None)

        assert "thinking" not in optional_params, (
            "thinking param should be dropped when modify_params=True and thinking_blocks are missing"
        )

        # Test case 2: thinking should NOT be dropped when thinking_blocks are present
        messages_with_thinking_blocks = [
            {"role": "user", "content": "Search for weather"},
            {
                "role": "assistant",
                "content": "",
                "tool_calls": [
                    {
                        "id": "call_123",
                        "type": "function",
                        "function": {"name": "search", "arguments": "{}"},
                    }
                ],
                "thinking_blocks": [{"type": "thinking", "thinking": "Let me search for weather..."}],
            },
            {"role": "tool", "content": "Weather is sunny", "tool_call_id": "call_123"},
        ]

        optional_params_with_thinking = {"thinking": {"type": "enabled", "budget_tokens": 1000}}

        # Verify the condition is NOT detected when thinking_blocks are present
        assert not last_assistant_with_tool_calls_has_no_thinking_blocks(messages_with_thinking_blocks), (
            "Should NOT detect missing thinking_blocks when they are present"
        )

        # Simulate what _transform_request_helper does
        if (
            optional_params_with_thinking.get("thinking") is not None
            and messages_with_thinking_blocks is not None
            and last_assistant_with_tool_calls_has_no_thinking_blocks(messages_with_thinking_blocks)
        ):
            if litellm.modify_params:
                optional_params_with_thinking.pop("thinking", None)

        assert "thinking" in optional_params_with_thinking, (
            "thinking param should NOT be dropped when thinking_blocks are present"
        )

        # Test case 3: thinking should NOT be dropped when modify_params=False
        litellm.modify_params = False

        optional_params_no_modify = {"thinking": {"type": "enabled", "budget_tokens": 1000}}

        # Simulate what _transform_request_helper does
        if (
            optional_params_no_modify.get("thinking") is not None
            and messages_without_thinking_blocks is not None
            and last_assistant_with_tool_calls_has_no_thinking_blocks(messages_without_thinking_blocks)
        ):
            if litellm.modify_params:
                optional_params_no_modify.pop("thinking", None)

        assert "thinking" in optional_params_no_modify, "thinking param should NOT be dropped when modify_params=False"

    finally:
        # Restore original modify_params setting
        litellm.modify_params = original_modify_params


def test_create_output_config_for_response_format():
    """Test outputConfig dict creation from JSON schema."""
    config = AmazonConverseConfig()

    schema = {
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "age": {"type": "integer"},
        },
        "required": ["name", "age"],
    }

    output_config = config._create_output_config_for_response_format(
        json_schema=schema,
        name="PersonInfo",
        description="A person's info",
    )

    assert "textFormat" in output_config
    text_format = output_config["textFormat"]
    assert text_format["type"] == "json_schema"
    assert "structure" in text_format

    json_schema_def = text_format["structure"]["jsonSchema"]
    assert json_schema_def["name"] == "PersonInfo"
    assert json_schema_def["description"] == "A person's info"
    # schema field must be a JSON string, not a dict
    assert isinstance(json_schema_def["schema"], str)
    parsed_schema = json.loads(json_schema_def["schema"])
    # additionalProperties: false is injected by normalization
    expected = {**schema, "additionalProperties": False}
    assert parsed_schema == expected


def test_translate_response_format_native_output_config(monkeypatch):
    """For supported models, _translate_response_format_param should produce outputConfig."""
    old_env = os.environ.get("LITELLM_LOCAL_MODEL_COST_MAP")
    old_cost = litellm.model_cost
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    litellm.model_cost = litellm.get_model_cost_map(url="")
    try:
        config = AmazonConverseConfig()

        response_format = {
            "type": "json_schema",
            "json_schema": {
                "name": "WeatherResult",
                "description": "Weather info",
                "schema": {
                    "type": "object",
                    "properties": {
                        "temp": {"type": "number"},
                    },
                    "required": ["temp"],
                },
            },
        }

        optional_params: dict = {}
        result = config._translate_response_format_param(
            value=response_format,
            model="anthropic.claude-sonnet-4-5-20250929-v1:0",
            optional_params=optional_params,
            non_default_params={"response_format": response_format},
            is_thinking_enabled=False,
        )

        # Should have outputConfig, NOT tools
        assert "outputConfig" in result
        assert "tools" not in result
        assert "tool_choice" not in result
        assert result["json_mode"] is True
        # No fake_stream for native approach
        assert "fake_stream" not in result

        # Verify the schema content (additionalProperties: false is added by normalization)
        schema_str = result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"]
        parsed_schema = json.loads(schema_str)
        expected_schema = {
            **response_format["json_schema"]["schema"],
            "additionalProperties": False,
        }
        assert parsed_schema == expected_schema
        assert result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["name"] == "WeatherResult"
    finally:
        litellm.model_cost = old_cost
        if old_env is None:
            os.environ.pop("LITELLM_LOCAL_MODEL_COST_MAP", None)
        else:
            monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", old_env)


CAPITAL_RESPONSE_FORMAT: Final = {
    "type": "json_schema",
    "json_schema": {
        "name": "capital",
        "schema": {
            "type": "object",
            "properties": {"city": {"type": "string"}, "country": {"type": "string"}},
            "required": ["city", "country"],
            "additionalProperties": False,
        },
    },
}


ADAPTIVE_THINKING: Final = {"type": "adaptive"}


def _converse_request_for_json_schema(
    model: str, stream: bool, thinking_params: Mapping[str, object] | None = None
) -> tuple[Mapping[str, object], RequestObject]:
    config = AmazonConverseConfig()
    optional_params = config.map_openai_params(
        non_default_params={"response_format": CAPITAL_RESPONSE_FORMAT, "stream": stream, **(thinking_params or {})},
        optional_params={},
        model=model,
        drop_params=False,
    )
    request = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "Name the capital of France."}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )
    return optional_params, request


@pytest.mark.parametrize(
    ("native_profile", "tool_profile"),
    [
        ("us.anthropic.claude-opus-4-8", "anthropic.claude-opus-4-8"),
        ("global.anthropic.claude-opus-4-7", "us.anthropic.claude-opus-4-7"),
        ("anthropic.claude-opus-4-8", "us-gov.anthropic.claude-opus-4-8"),
    ],
)
@pytest.mark.parametrize("stream", [False, True])
def test_json_schema_shape_follows_each_inference_profile_own_native_output_flag(
    set_native_structured_output, native_profile, tool_profile, stream
):
    set_native_structured_output(native_profile, "bedrock")
    set_native_structured_output(tool_profile, None)

    thinking_params: Final = {"thinking": ADAPTIVE_THINKING}
    native_params, native_request = _converse_request_for_json_schema(native_profile, stream, thinking_params)
    tool_params, tool_request = _converse_request_for_json_schema(tool_profile, stream, thinking_params)

    assert native_request["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["name"] == "capital"
    assert "toolConfig" not in native_request
    assert "fake_stream" not in native_params
    assert "outputConfig" not in tool_request
    assert [tool["toolSpec"]["name"] for tool in tool_request["toolConfig"]["tools"]] == ["json_tool_call"]
    assert tool_request["toolConfig"]["toolChoice"] == {"tool": {"name": "json_tool_call"}}
    assert tool_params.get("fake_stream", False) is stream


@pytest.mark.parametrize(
    ("native_key", "thinking_params", "native"),
    [
        ("legacy", {}, True),
        ("bedrock", {}, False),
        ("bedrock", {"thinking": ADAPTIVE_THINKING}, True),
        ("bedrock", {"thinking": {"type": "enabled", "budget_tokens": 1024}}, True),
        ("bedrock", {"reasoning_effort": "low"}, True),
        ("bedrock", {"reasoning_effort": "none"}, False),
        ("bedrock", {"thinking": {"type": "disabled"}}, False),
    ],
    ids=[
        "legacy-key",
        "bedrock-key-no-thinking",
        "bedrock-key-adaptive",
        "bedrock-key-enabled",
        "bedrock-key-effort",
        "bedrock-key-effort-none",
        "bedrock-key-thinking-disabled",
    ],
)
def test_bedrock_native_output_key_applies_only_when_thinking_is_requested(
    set_native_structured_output, native_key, thinking_params, native
):
    model: Final = "us.anthropic.claude-haiku-5-5"
    set_native_structured_output(model, native_key)

    _, request = _converse_request_for_json_schema(model, False, thinking_params)

    assert ("outputConfig" in request) is native
    assert ("toolConfig" in request) is not native


def test_adaptive_thinking_is_kept_next_to_json_schema_on_a_native_output_profile(set_native_structured_output):
    model: Final = "us.anthropic.claude-opus-5"
    set_native_structured_output(model, "bedrock")
    config: Final = AmazonConverseConfig()
    thinking: Final = {"type": "adaptive", "display": "summarized"}

    optional_params: Final = config.map_openai_params(
        non_default_params={"response_format": CAPITAL_RESPONSE_FORMAT, "thinking": thinking},
        optional_params={},
        model=model,
        drop_params=False,
    )
    request: Final = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "Name the capital of France."}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert request["additionalModelRequestFields"]["thinking"] == thinking
    assert request["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["name"] == "capital"
    assert "toolConfig" not in request


_OPUS_4_8_INVOKE_RESPONSE: Final = {
    "id": "msg_1",
    "type": "message",
    "role": "assistant",
    "model": "claude-opus-4-8",
    "content": [{"type": "text", "text": '{"city": "Paris", "country": "France"}'}],
    "stop_reason": "end_turn",
    "usage": {"input_tokens": 10, "output_tokens": 5},
}


def _routed_request_body(router: Router, model_name: str, route: str) -> Mapping[str, object]:
    response: Final = _mock_converse_response()
    if route == "invoke":
        response.json.return_value = _OPUS_4_8_INVOKE_RESPONSE
        response.text = json.dumps(_OPUS_4_8_INVOKE_RESPONSE)
    client: Final = HTTPHandler()
    with patch.object(client, "post", return_value=response) as mock_post:
        router.completion(
            model=model_name,
            messages=[{"role": "user", "content": "Name the capital of France."}],
            response_format=CAPITAL_RESPONSE_FORMAT,
            thinking=ADAPTIVE_THINKING,
            client=client,
        )
    return json.loads(mock_post.call_args.kwargs["data"])


def _sends_native_output(body: Mapping[str, object], route: str) -> bool:
    if route == "converse":
        return "outputConfig" in body and "toolConfig" not in body
    output_config: Final = body.get("output_config")
    return isinstance(output_config, dict) and "format" in output_config and "tools" not in body


@pytest.mark.parametrize("route", ["converse", "invoke"])
def test_a_deployment_native_output_opt_in_stays_on_that_deployment(set_native_structured_output, route):
    set_native_structured_output("us.anthropic.claude-opus-4-8", None)
    litellm_params: Final = {
        "model": f"bedrock/{route}/us.anthropic.claude-opus-4-8",
        "aws_access_key_id": "fake-access-key",
        "aws_secret_access_key": "fake-secret-key",
        "aws_region_name": "us-east-1",
    }
    router: Final = Router(
        model_list=[
            {
                "model_name": "opted-in",
                "litellm_params": litellm_params,
                "model_info": {"supports_bedrock_native_structured_output": True},
            },
            {"model_name": "sibling", "litellm_params": litellm_params},
        ]
    )

    assert _sends_native_output(_routed_request_body(router, "opted-in", route), route)
    assert not _sends_native_output(_routed_request_body(router, "sibling", route), route)


NATIVE_OUTPUT_REJECTED_KEYWORDS: Final = frozenset({"minimum", "maximum", "uniqueItems", "oneOf"})
CONSTRAINED_PERSON_SCHEMA: Final = {
    "type": "object",
    "properties": {
        "age": {"type": "integer", "minimum": 0, "maximum": 150},
        "tags": {"type": "array", "items": {"type": "string"}, "minItems": 2, "uniqueItems": True},
        "aliases": {"type": "array", "items": {"type": "string"}, "minItems": 1},
        "contact": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
        "address": {"type": ["object", "null"], "properties": {"city": {"type": "string"}}, "required": ["city"]},
    },
    "required": ["age", "tags", "aliases", "contact", "address"],
}
RECURSIVE_TREE_SCHEMA: Final = {
    "type": "object",
    "properties": {"root": {"$ref": "#/$defs/Node"}},
    "required": ["root"],
    "$defs": {
        "Node": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "children": {"type": "array", "items": {"$ref": "#/$defs/Node"}},
            },
            "required": ["name", "children"],
        }
    },
}
OPEN_OBJECT_SCHEMA: Final = {
    "type": "object",
    "properties": {"counts": {"type": "object", "additionalProperties": {"type": "integer"}}},
    "required": ["counts"],
}
LOOKAROUND_PATTERN_SCHEMA: Final = {
    "type": "object",
    "properties": {"amount": {"type": "string", "pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$"}},
    "required": ["amount"],
}
UNKNOWN_FORMAT_SCHEMA: Final = {
    "type": "object",
    "properties": {"blob": {"type": "string", "format": "x-litellm-unlisted-format"}},
    "required": ["blob"],
}
ROOT_REF_SCHEMA: Final = {
    "type": "object",
    "properties": {"name": {"type": "string"}, "parent": {"anyOf": [{"$ref": "#"}, {"type": "null"}]}},
    "required": ["name", "parent"],
}


def _schema_keys(node: object) -> frozenset[str]:
    if isinstance(node, dict):
        return frozenset(node).union(*(_schema_keys(value) for value in node.values()))
    if isinstance(node, list):
        return frozenset().union(*(_schema_keys(item) for item in node))
    return frozenset()


def _converse_request_for_schema(model: str, schema: Mapping[str, object]) -> RequestObject:
    config: Final = AmazonConverseConfig()
    optional_params: Final = config.map_openai_params(
        non_default_params={
            "response_format": {"type": "json_schema", "json_schema": {"name": "out", "schema": schema}},
            "thinking": ADAPTIVE_THINKING,
        },
        optional_params={},
        model=model,
        drop_params=False,
    )
    return config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "Fill in a plausible example."}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )


@pytest.mark.parametrize("native_key", ["legacy", "bedrock"])
def test_native_output_schema_drops_keywords_bedrock_rejects_and_closes_objects(
    set_native_structured_output, native_key
):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, native_key)

    request: Final = _converse_request_for_schema(model, CONSTRAINED_PERSON_SCHEMA)

    sent: Final = json.loads(request["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"])
    assert not _schema_keys(sent) & NATIVE_OUTPUT_REJECTED_KEYWORDS
    assert sent["additionalProperties"] is False
    assert sent["properties"]["contact"]["anyOf"] == [{"type": "string"}, {"type": "integer"}]
    assert "minimum value: 0" in sent["properties"]["age"]["description"]
    assert "minItems" not in sent["properties"]["tags"]
    assert sent["properties"]["aliases"]["minItems"] == 1
    assert sent["properties"]["address"]["additionalProperties"] is False


@pytest.mark.parametrize("native_key", ["legacy", "bedrock"])
@pytest.mark.parametrize(
    ("schema", "kept_keyword"),
    [
        (RECURSIVE_TREE_SCHEMA, "$ref"),
        (ROOT_REF_SCHEMA, "$ref"),
        (OPEN_OBJECT_SCHEMA, "additionalProperties"),
        (LOOKAROUND_PATTERN_SCHEMA, "pattern"),
        (UNKNOWN_FORMAT_SCHEMA, "format"),
    ],
    ids=["recursive", "root-ref", "open-object", "lookaround-pattern", "unlisted-format"],
)
def test_schema_native_output_cannot_hold_keeps_the_tool_path_on_a_native_profile(
    set_native_structured_output, schema, kept_keyword, native_key
):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, native_key)

    request: Final = _converse_request_for_schema(model, schema)

    assert "outputConfig" not in request
    tool_spec: Final = request["toolConfig"]["tools"][0]["toolSpec"]
    assert tool_spec["name"] == "json_tool_call"
    assert kept_keyword in _schema_keys(tool_spec["inputSchema"]["json"])


def _shared_defs_schema(defs_key: str) -> Mapping[str, object]:
    party_ref: Final = {"$ref": f"#/{defs_key}/Party"}
    return {
        "type": "object",
        "properties": {"buyer": party_ref, "seller": party_ref, "broker": {"anyOf": [party_ref, {"type": "null"}]}},
        "required": ["buyer", "seller", "broker"],
        defs_key: {
            "Party": {
                "type": ["object", "null"],
                "properties": {"name": {"type": "string"}, "email": {"anyOf": [{"type": "string"}, {"type": "null"}]}},
                "required": ["name", "email"],
            }
        },
    }


@pytest.mark.parametrize("defs_key", ["$defs", "definitions"])
@pytest.mark.parametrize("native_key", ["legacy", "bedrock"])
def test_shared_defs_reach_native_output_once_instead_of_inlined_per_use(
    set_native_structured_output, native_key, defs_key
):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, native_key)

    request: Final = _converse_request_for_schema(model, _shared_defs_schema(defs_key))

    sent: Final = json.loads(request["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"])
    assert sent["properties"]["buyer"] == {"$ref": f"#/{defs_key}/Party"}
    assert json.dumps(sent).count('"anyOf"') == 2
    assert sent[defs_key]["Party"]["additionalProperties"] is False


def _flat_schema(property_schema: Mapping[str, object], count: int, required: bool) -> Mapping[str, object]:
    names: Final = tuple(f"field_{index}" for index in range(count))
    return {
        "type": "object",
        "properties": dict.fromkeys(names, property_schema),
        "required": list(names) if required else [],
    }


def _optional_groups_schema(count: int, group_size: int = 6) -> Mapping[str, object]:
    groups: Final = {
        f"group_{start}": _flat_schema({"type": "string"}, min(group_size, count - start), required=False)
        for start in range(0, count, group_size)
    }
    return {"type": "object", "properties": groups, "required": list(groups)}


@pytest.mark.parametrize("native_key", ["legacy", "bedrock"])
@pytest.mark.parametrize(
    ("schema_for", "limit"),
    [
        (lambda count: _flat_schema({"type": ["string", "null"]}, count, True), NATIVE_OUTPUT_MAX_UNION_PARAMETERS),
        (
            lambda count: _flat_schema({"anyOf": [{"type": "string"}, {"type": "integer"}]}, count, True),
            NATIVE_OUTPUT_MAX_UNION_PARAMETERS,
        ),
        (_optional_groups_schema, NATIVE_OUTPUT_MAX_OPTIONAL_PARAMETERS),
        (
            lambda count: _flat_schema({"type": "string"}, count, False),
            NATIVE_OUTPUT_MAX_GRAMMAR_BRANCHES.bit_length() - 1,
        ),
    ],
    ids=["type-list-unions", "any-of-unions", "optional", "optional-grammar-branches"],
)
def test_schema_past_a_native_output_size_limit_keeps_the_tool_path(
    set_native_structured_output, native_key, schema_for, limit
):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, native_key)

    at_limit: Final = _converse_request_for_schema(model, schema_for(limit))
    past_limit: Final = _converse_request_for_schema(model, schema_for(limit + 1))

    sent: Final = json.loads(at_limit["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"])
    assert sent["properties"].keys() == schema_for(limit)["properties"].keys()
    assert "outputConfig" not in past_limit
    assert past_limit["toolConfig"]["tools"][0]["toolSpec"]["name"] == "json_tool_call"


@pytest.mark.parametrize(
    ("native_key", "native_past_limit"), [("legacy", True), ("bedrock", False)], ids=["legacy-key", "bedrock-key"]
)
def test_field_count_limit_sends_the_json_tool_only_on_the_bedrock_native_key(
    set_native_structured_output, native_key, native_past_limit
):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, native_key)

    at_limit: Final = _converse_request_for_schema(
        model, _flat_schema({"type": "string"}, BEDROCK_NATIVE_OUTPUT_MAX_PROPERTIES, True)
    )
    past_limit: Final = _converse_request_for_schema(
        model, _flat_schema({"type": "string"}, BEDROCK_NATIVE_OUTPUT_MAX_PROPERTIES + 1, True)
    )

    assert "outputConfig" in at_limit
    assert ("outputConfig" in past_limit) is native_past_limit


NUMERIC_FORMAT_SCHEMA: Final = {
    "type": "object",
    "properties": {
        "count": {"type": "integer", "format": "int32"},
        "total": {"type": "integer", "format": "int64"},
        "ratio": {"type": "number", "format": "double"},
    },
    "required": ["count", "total", "ratio"],
}


@pytest.mark.parametrize("native_key", ["legacy", "bedrock"])
def test_numeric_formats_keep_native_output(set_native_structured_output, native_key):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, native_key)

    request: Final = _converse_request_for_schema(model, NUMERIC_FORMAT_SCHEMA)

    sent: Final = json.loads(request["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"])
    assert {name: field["format"] for name, field in sent["properties"].items()} == {
        "count": "int32",
        "total": "int64",
        "ratio": "double",
    }


def _doubling_defs_schema(depth: int) -> Mapping[str, object]:
    levels: Final = {
        f"Level{index}": {
            "type": "object",
            "properties": {
                "left": {"$ref": f"#/$defs/Level{index + 1}"},
                "right": {"$ref": f"#/$defs/Level{index + 1}"},
            },
            "required": ["left", "right"],
        }
        for index in range(depth)
    }
    return {
        "type": "object",
        "properties": {"root": {"$ref": "#/$defs/Level0"}},
        "required": ["root"],
        "$defs": {**levels, f"Level{depth}": {"type": "string"}},
    }


@pytest.mark.timeout(30)
def test_defs_that_double_at_every_level_reach_native_output_without_being_expanded(set_native_structured_output):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, "legacy")
    schema: Final = _doubling_defs_schema(30)

    request: Final = _converse_request_for_schema(model, schema)

    sent: Final = json.loads(request["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"])
    assert sent["$defs"].keys() == schema["$defs"].keys()
    assert sent["properties"]["root"] == {"$ref": "#/$defs/Level0"}


@pytest.mark.parametrize(
    ("native_key", "forwarded"), [("legacy", True), ("bedrock", False)], ids=["legacy-key", "bedrock-key"]
)
def test_recursive_output_config_format_follows_the_profile_native_key(
    set_native_structured_output, native_key, forwarded
):
    model: Final = "us.anthropic.claude-opus-4-8"
    set_native_structured_output(model, native_key)

    request: Final = AmazonConverseConfig()._transform_request(
        model=model,
        messages=[{"role": "user", "content": "Fill in a plausible example."}],
        optional_params={"output_config": {"format": {"type": "json_schema", "schema": RECURSIVE_TREE_SCHEMA}}},
        litellm_params={},
        headers={},
    )

    assert ("outputConfig" in request) is forwarded



def test_sonnet_4_6_json_schema_still_uses_native_output_config(monkeypatch):
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))

    optional_params, request = _converse_request_for_json_schema(model="us.anthropic.claude-sonnet-4-6", stream=True)

    assert request["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["name"] == "capital"
    assert "toolConfig" not in request
    assert "fake_stream" not in optional_params


def test_translate_response_format_fallback_tool_call():
    """For unsupported models, should fall back to tool-call approach."""
    config = AmazonConverseConfig()

    response_format = {
        "type": "json_schema",
        "json_schema": {
            "name": "WeatherResult",
            "schema": {
                "type": "object",
                "properties": {
                    "temp": {"type": "number"},
                },
            },
        },
    }

    optional_params: dict = {}
    result = config._translate_response_format_param(
        value=response_format,
        model="anthropic.claude-3-haiku-20240307-v1:0",
        optional_params=optional_params,
        non_default_params={"response_format": response_format},
        is_thinking_enabled=False,
    )

    # Should use tool-call approach, NOT outputConfig (model doesn't support native structured outputs)
    assert "outputConfig" not in result
    assert "tools" in result
    assert result["json_mode"] is True


def test_native_structured_output_no_fake_stream(monkeypatch):
    """When using native structured outputs with streaming, fake_stream should NOT be set."""
    old_env = os.environ.get("LITELLM_LOCAL_MODEL_COST_MAP")
    old_cost = litellm.model_cost
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    litellm.model_cost = litellm.get_model_cost_map(url="")
    try:
        config = AmazonConverseConfig()

        response_format = {
            "type": "json_schema",
            "json_schema": {
                "name": "Result",
                "schema": {
                    "type": "object",
                    "properties": {
                        "answer": {"type": "string"},
                    },
                },
            },
        }

        optional_params: dict = {}
        result = config._translate_response_format_param(
            value=response_format,
            model="anthropic.claude-sonnet-4-5-20250929-v1:0",
            optional_params=optional_params,
            non_default_params={"response_format": response_format, "stream": True},
            is_thinking_enabled=False,
        )

        assert "outputConfig" in result
        assert result["json_mode"] is True
        # No fake_stream for native approach
        assert "fake_stream" not in result

        # Verify the schema content
        schema_str = result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"]
        assert json.loads(schema_str) == {
            "type": "object",
            "properties": {"answer": {"type": "string"}},
            "additionalProperties": False,
        }
    finally:
        litellm.model_cost = old_cost
        if old_env is None:
            os.environ.pop("LITELLM_LOCAL_MODEL_COST_MAP", None)
        else:
            monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", old_env)


def test_transform_request_with_output_config():
    """Test that outputConfig flows through _transform_request_helper into the final request."""
    from litellm.types.llms.bedrock import (
        JsonSchemaDefinition,
        OutputConfigBlock,
        OutputFormat,
        OutputFormatStructure,
    )

    config = AmazonConverseConfig()

    output_config = OutputConfigBlock(
        textFormat=OutputFormat(
            type="json_schema",
            structure=OutputFormatStructure(
                jsonSchema=JsonSchemaDefinition(
                    schema='{"type": "object", "properties": {"x": {"type": "string"}}, "additionalProperties": false}',
                    name="TestSchema",
                )
            ),
        )
    )

    messages = [{"role": "user", "content": "test"}]
    optional_params = {
        "outputConfig": output_config,
        "json_mode": True,
    }

    result = config._transform_request(
        model="anthropic.claude-sonnet-4-5-20250929-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert "outputConfig" in result
    assert result["outputConfig"]["textFormat"]["type"] == "json_schema"
    assert result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["name"] == "TestSchema"


def test_transform_request_strips_anthropic_output_config():
    """
    output_config is Anthropic-specific and must never be forwarded to Bedrock.
    """
    config = AmazonConverseConfig()
    messages = [{"role": "user", "content": "hello"}]

    result = config._transform_request(
        model="us.amazon.nova-pro-v1:0",
        messages=messages,
        optional_params={
            "maxTokens": 64,
            "output_config": {"effort": "low"},
        },
        litellm_params={},
        headers={},
    )

    assert "outputConfig" not in result
    additional_fields = result.get("additionalModelRequestFields", {})
    assert "output_config" not in additional_fields


def test_converse_drop_params_strips_output_config_for_pre_4_5_anthropic():
    """``drop_params=True`` strips unsupported ``output_config`` on Bedrock Converse."""
    config = AmazonConverseConfig()
    messages = [{"role": "user", "content": "hi"}]

    original = litellm.drop_params
    litellm.drop_params = True
    try:
        result = config._transform_request(
            model="bedrock/converse/anthropic.claude-3-haiku-20240307-v1:0",
            messages=messages,
            optional_params={
                "maxTokens": 256,
                "output_config": {"effort": "low"},
            },
            litellm_params={},
            headers={},
        )
    finally:
        litellm.drop_params = original

    additional = result.get("additionalModelRequestFields", {})
    assert "output_config" not in additional


def test_converse_drop_params_keeps_output_config_for_supporting_anthropic():
    """``drop_params=True`` does not strip on models that support ``output_config``."""
    config = AmazonConverseConfig()
    messages = [{"role": "user", "content": "hi"}]

    original = litellm.drop_params
    litellm.drop_params = True
    try:
        result = config._transform_request(
            model="bedrock/converse/us.anthropic.claude-opus-4-7",
            messages=messages,
            optional_params={
                "maxTokens": 256,
                "thinking": {"type": "adaptive"},
                "output_config": {"effort": "high"},
            },
            litellm_params={},
            headers={},
        )
    finally:
        litellm.drop_params = original

    additional = result.get("additionalModelRequestFields", {})
    assert additional.get("output_config") == {"effort": "high"}


def test_transform_response_native_structured_output():
    """Test response handling when model returns JSON as text content (native structured output)."""
    response_json = {
        "output": {
            "message": {
                "role": "assistant",
                "content": [{"text": '{"temp": 62, "description": "Mild and foggy"}'}],
            }
        },
        "stopReason": "end_turn",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 20,
            "totalTokens": 30,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()
    # json_mode=True but no tool_call in response — native structured output path
    optional_params = {"json_mode": True}

    result = config._transform_response(
        model="anthropic.claude-sonnet-4-5-20250929-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data={},
        messages=[],
        encoding=None,
    )

    # Content should be the JSON text directly
    assert result.choices[0].message.content == '{"temp": 62, "description": "Mild and foggy"}'
    # Should NOT have tool_calls
    assert result.choices[0].message.tool_calls is None
    assert result.choices[0].finish_reason == "stop"


def test_add_additional_properties_simple_object():
    """Object schemas without additionalProperties get it set to false."""
    schema = {
        "type": "object",
        "properties": {
            "city": {"type": "string"},
            "country": {"type": "string"},
        },
        "required": ["city", "country"],
    }
    result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
    assert result["additionalProperties"] is False
    # Original should not be mutated
    assert "additionalProperties" not in schema


def test_add_additional_properties_already_set():
    """If additionalProperties is already set, don't overwrite it."""
    schema = {
        "type": "object",
        "properties": {"x": {"type": "string"}},
        "additionalProperties": True,
    }
    result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
    assert result["additionalProperties"] is True


def test_add_additional_properties_nested():
    """Recursively processes nested object types in properties, items, $defs, anyOf."""
    schema = {
        "type": "object",
        "properties": {
            "address": {
                "type": "object",
                "properties": {
                    "street": {"type": "string"},
                    "zip": {"type": "string"},
                },
            },
            "tags": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {"name": {"type": "string"}},
                },
            },
        },
        "$defs": {
            "Metadata": {
                "type": "object",
                "properties": {"key": {"type": "string"}},
            }
        },
        "anyOf": [
            {
                "type": "object",
                "properties": {"variant": {"type": "string"}},
            }
        ],
    }
    result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
    # Top-level
    assert result["additionalProperties"] is False
    # Nested property object
    assert result["properties"]["address"]["additionalProperties"] is False
    # Array items object
    assert result["properties"]["tags"]["items"]["additionalProperties"] is False
    # $defs object
    assert result["$defs"]["Metadata"]["additionalProperties"] is False
    # anyOf object
    assert result["anyOf"][0]["additionalProperties"] is False


def test_add_additional_properties_non_object():
    """Non-object schemas are returned unchanged."""
    schema = {"type": "string"}
    result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
    assert "additionalProperties" not in result
    assert result == {"type": "string"}


def test_add_additional_properties_definitions():
    """Recursively processes object types inside 'definitions' (not just '$defs')."""
    schema = {
        "type": "object",
        "properties": {
            "item": {"$ref": "#/definitions/Item"},
        },
        "definitions": {
            "Item": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "details": {
                        "type": "object",
                        "properties": {"weight": {"type": "number"}},
                    },
                },
            }
        },
    }
    result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
    # Top-level
    assert result["additionalProperties"] is False
    # definitions object
    assert result["definitions"]["Item"]["additionalProperties"] is False
    # Nested object inside definitions
    assert result["definitions"]["Item"]["properties"]["details"]["additionalProperties"] is False


def test_json_object_no_schema_skips_tool_injection(monkeypatch):
    """response_format: {type: json_object} with no schema should NOT inject
    the synthetic json_tool_call tool.

    When no schema is given, _create_json_tool_call_for_response_format builds
    a tool with an empty schema (properties: {}). The model follows the schema
    and returns {} instead of the requested JSON. Skipping tool injection lets
    the model respond naturally with the JSON the caller asked for."""
    old_env = os.environ.get("LITELLM_LOCAL_MODEL_COST_MAP")
    old_cost = litellm.model_cost
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    litellm.model_cost = litellm.get_model_cost_map(url="")
    try:
        config = AmazonConverseConfig()
        optional_params: dict = {}
        non_default_params = {"response_format": {"type": "json_object"}}

        result = config._translate_response_format_param(
            value=non_default_params["response_format"],
            model="anthropic.claude-sonnet-4-5-20250929-v1:0",
            optional_params=optional_params,
            non_default_params=non_default_params,
            is_thinking_enabled=False,
        )

        # Should NOT use native outputConfig (no schema provided)
        assert "outputConfig" not in result
        # Should NOT inject tools - empty schema causes model to return {}
        assert "tools" not in result
        assert "tool_choice" not in result
        assert result["json_mode"] is True
    finally:
        litellm.model_cost = old_cost
        if old_env is None:
            os.environ.pop("LITELLM_LOCAL_MODEL_COST_MAP", None)
        else:
            monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", old_env)


def test_output_config_applies_additional_properties():
    """_create_output_config_for_response_format normalizes the schema."""
    schema = {
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "nested": {
                "type": "object",
                "properties": {"val": {"type": "integer"}},
            },
        },
    }
    output_config = AmazonConverseConfig._create_output_config_for_response_format(
        json_schema=schema, name="test_schema"
    )
    parsed = json.loads(output_config["textFormat"]["structure"]["jsonSchema"]["schema"])
    assert parsed["additionalProperties"] is False
    assert parsed["properties"]["nested"]["additionalProperties"] is False


_TOOL_PARAM = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the weather",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The location to get weather for",
                    }
                },
                "required": ["location"],
            },
        },
    }
]


def test_parallel_tool_calls_newer_model_adds_disable_flag():
    """Newer Claude models (4.5+) should get disable_parallel_tool_use in additionalModelRequestFields."""
    config = AmazonConverseConfig()
    model = "anthropic.claude-sonnet-4-5-20250929-v1:0"
    messages = [{"role": "user", "content": "What's the weather in SF and NYC?"}]

    optional_params = config.map_openai_params(
        non_default_params={"parallel_tool_calls": False, "tools": _TOOL_PARAM},
        optional_params={},
        model=model,
        drop_params=False,
    )

    request_data = config._transform_request(
        model=model,
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert "additionalModelRequestFields" in request_data
    assert "tool_choice" in request_data["additionalModelRequestFields"]
    assert request_data["additionalModelRequestFields"]["tool_choice"]["disable_parallel_tool_use"] is True
    assert "parallel_tool_calls" not in request_data["additionalModelRequestFields"]


def test_parallel_tool_calls_flag_decoupled_from_ttl_pricing(monkeypatch):
    """
    The disable_parallel_tool_use gate must read supports_parallel_tool_use_config,
    not the 1h-TTL pricing field: a model carrying only the former still gets the flag.
    """
    from litellm.llms.bedrock.common_utils import supports_bedrock_prompt_cache_ttl

    config = AmazonConverseConfig()
    model = "anthropic.claude-parallel-tool-use-only"
    monkeypatch.setitem(litellm.model_cost, model, {"supports_parallel_tool_use_config": True})
    assert supports_bedrock_prompt_cache_ttl(model) is False
    messages = [{"role": "user", "content": "What's the weather in SF and NYC?"}]

    optional_params = config.map_openai_params(
        non_default_params={"parallel_tool_calls": False, "tools": _TOOL_PARAM},
        optional_params={},
        model=model,
        drop_params=False,
    )

    request_data = config._transform_request(
        model=model,
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert request_data["additionalModelRequestFields"]["tool_choice"]["disable_parallel_tool_use"] is True


def test_parallel_tool_calls_older_model_drops_disable_flag():
    """Older Claude models (pre-4.5) must NOT receive disable_parallel_tool_use — Bedrock rejects it."""
    config = AmazonConverseConfig()
    model = "anthropic.claude-3-haiku-20240307-v1:0"
    messages = [{"role": "user", "content": "What's the weather in SF and NYC?"}]

    optional_params = config.map_openai_params(
        non_default_params={"parallel_tool_calls": False, "tools": _TOOL_PARAM},
        optional_params={},
        model=model,
        drop_params=False,
    )

    request_data = config._transform_request(
        model=model,
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    additional = request_data.get("additionalModelRequestFields", {})
    assert "tool_choice" not in additional
    assert "parallel_tool_calls" not in additional


@pytest.mark.parametrize(
    "parallel_tool_calls, expected_disable",
    [(True, False), (False, True)],
)
def test_parallel_tool_calls_emits_typed_auto_tool_choice(parallel_tool_calls, expected_disable):
    config = AmazonConverseConfig()
    model = "us.anthropic.claude-opus-4-8"
    messages = [{"role": "user", "content": "What's the weather in SF and NYC?"}]

    optional_params = config.map_openai_params(
        non_default_params={"parallel_tool_calls": parallel_tool_calls, "tools": _TOOL_PARAM},
        optional_params={},
        model=model,
        drop_params=False,
    )

    request_data = config._transform_request(
        model=model,
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert request_data["additionalModelRequestFields"]["tool_choice"] == {
        "type": "auto",
        "disable_parallel_tool_use": expected_disable,
    }


@pytest.mark.parametrize(
    "tool_choice, expected_tool_config_choice",
    [
        ("auto", {"auto": {}}),
        ("required", {"any": {}}),
        ({"type": "function", "function": {"name": "get_current_weather"}}, {"tool": {"name": "get_current_weather"}}),
    ],
)
def test_parallel_tool_calls_with_explicit_tool_choice_omits_conflicting_type(tool_choice, expected_tool_config_choice):
    config = AmazonConverseConfig()
    model = "us.anthropic.claude-opus-4-8"
    messages = [{"role": "user", "content": "What's the weather in SF and NYC?"}]

    optional_params = config.map_openai_params(
        non_default_params={"parallel_tool_calls": False, "tool_choice": tool_choice, "tools": _TOOL_PARAM},
        optional_params={},
        model=model,
        drop_params=False,
    )

    request_data = config._transform_request(
        model=model,
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert request_data["toolConfig"]["toolChoice"] == expected_tool_config_choice
    assert request_data["additionalModelRequestFields"]["tool_choice"] == {"disable_parallel_tool_use": True}


def test_tool_choice_type_kept_when_no_tool_config_choice_conflicts():
    config = AmazonConverseConfig()
    model = "us.anthropic.claude-opus-4-8"

    optional_params = config.map_openai_params(
        non_default_params={"parallel_tool_calls": False, "tools": _TOOL_PARAM},
        optional_params={},
        model=model,
        drop_params=False,
    )

    request_data = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "What's the weather in SF and NYC?"}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert "toolChoice" not in request_data["toolConfig"]
    assert request_data["additionalModelRequestFields"]["tool_choice"] == {
        "type": "auto",
        "disable_parallel_tool_use": True,
    }


def test_drop_tool_choice_type_leaves_other_passthrough_fields_untouched():
    additional_request_params = {
        "tool_choice": {"type": "tool", "name": "get_weather", "disable_parallel_tool_use": True},
        "anthropic_beta": ["some-beta"],
    }

    AmazonConverseConfig._drop_tool_choice_type_conflicting_with_tool_config(additional_request_params)

    assert additional_request_params == {
        "tool_choice": {"name": "get_weather", "disable_parallel_tool_use": True},
        "anthropic_beta": ["some-beta"],
    }


def test_parallel_tool_use_merge_preserves_user_tool_choice_type():
    merged = AmazonConverseConfig._merge_parallel_tool_use_config(
        {"tool_choice": {"type": "tool", "name": "get_weather", "disable_parallel_tool_use": False}},
        {"tool_choice": {"type": "auto", "disable_parallel_tool_use": True}},
    )

    assert merged["tool_choice"] == {
        "type": "tool",
        "name": "get_weather",
        "disable_parallel_tool_use": True,
    }


class TestBedrockMinThinkingBudgetTokens:
    """Test that thinking.budget_tokens is clamped to the Bedrock minimum (1024)."""

    def _map_params(self, thinking_value, model="anthropic.claude-sonnet-4-5-20250929-v1:0"):
        """Helper to call map_openai_params with the given thinking value."""
        config = AmazonConverseConfig()
        non_default_params = {"thinking": thinking_value}
        optional_params = {"thinking": thinking_value}
        return config.map_openai_params(
            non_default_params=non_default_params,
            optional_params=optional_params,
            model=model,
            drop_params=False,
        )

    def test_budget_tokens_below_minimum_is_clamped(self):
        """budget_tokens < 1024 should be clamped to 1024."""
        result = self._map_params({"type": "enabled", "budget_tokens": 499})
        assert result["thinking"]["budget_tokens"] == 1024

    def test_budget_tokens_at_minimum_is_unchanged(self):
        """budget_tokens == 1024 should remain 1024."""
        result = self._map_params({"type": "enabled", "budget_tokens": 1024})
        assert result["thinking"]["budget_tokens"] == 1024

    def test_budget_tokens_above_minimum_is_unchanged(self):
        """budget_tokens > 1024 should remain unchanged."""
        result = self._map_params({"type": "enabled", "budget_tokens": 2048})
        assert result["thinking"]["budget_tokens"] == 2048

    def test_no_thinking_param_does_not_error(self):
        """When thinking is not provided, map_openai_params should not raise."""
        config = AmazonConverseConfig()
        result = config.map_openai_params(
            non_default_params={},
            optional_params={},
            model="anthropic.claude-sonnet-4-5-20250929-v1:0",
            drop_params=False,
        )
        assert "thinking" not in result or result.get("thinking") is None


def test_transform_response_with_both_json_tool_call_and_real_tool():
    """
    When Bedrock returns BOTH json_tool_call AND a real tool (get_weather),
    only the real tool should remain in tool_calls. The json_tool_call should be filtered out.
    Fixes https://github.com/BerriAI/litellm/issues/18381
    """
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 200},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_json_001",
                            "name": "json_tool_call",
                            "input": {
                                "Current_Temperature": 62,
                                "Weather_Explanation": "Mild and cool.",
                            },
                        }
                    },
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_weather_001",
                            "name": "get_weather",
                            "input": {
                                "location": "San Francisco, CA",
                                "unit": "fahrenheit",
                            },
                        }
                    },
                ],
            }
        },
        "stopReason": "tool_use",
        "usage": {
            "inputTokens": 100,
            "outputTokens": 50,
            "totalTokens": 150,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()
    optional_params = {"json_mode": True}

    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    # Only real tool should remain
    assert result.choices[0].message.tool_calls is not None
    assert len(result.choices[0].message.tool_calls) == 1
    assert result.choices[0].message.tool_calls[0].function.name == "get_weather"
    assert (
        result.choices[0].message.tool_calls[0].function.arguments
        == '{"location": "San Francisco, CA", "unit": "fahrenheit"}'
    )

    # json_tool_call content should be preserved as message text
    content = result.choices[0].message.content
    assert content is not None
    parsed = json.loads(content)
    assert parsed["Current_Temperature"] == 62
    assert parsed["Weather_Explanation"] == "Mild and cool."


def test_transform_response_does_not_mutate_optional_params():
    """
    Verify that optional_params still contains json_mode after _transform_response.
    Previously, .pop() was used which mutated the caller's dict.
    """
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 50},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_001",
                            "name": "json_tool_call",
                            "input": {"result": "ok"},
                        }
                    }
                ],
            }
        },
        "stopReason": "tool_use",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 5,
            "totalTokens": 15,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()
    optional_params = {"json_mode": True, "other_key": "value"}

    config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    # json_mode should still be in optional_params (not popped)
    assert "json_mode" in optional_params
    assert optional_params["json_mode"] is True
    assert optional_params["other_key"] == "value"


def test_streaming_filters_json_tool_call_with_real_tools():
    """
    Simulate streaming chunks where both json_tool_call and a real tool arrive.
    Verify json_tool_call chunks are converted to text content while real tool
    chunks pass through normally.
    """
    from litellm.llms.bedrock.chat.invoke_handler import AWSEventStreamDecoder
    from litellm.types.llms.bedrock import (
        ContentBlockDeltaEvent,
        ContentBlockStartEvent,
    )

    decoder = AWSEventStreamDecoder(model="test-model", json_mode=True)

    # Chunk 1: json_tool_call start
    json_start = ContentBlockStartEvent(
        toolUse={
            "toolUseId": "tooluse_json_001",
            "name": "json_tool_call",
        }
    )
    tool_use_1, _, _ = decoder._handle_converse_start_event(json_start)
    # json_tool_call start should be suppressed (return None tool_use)
    assert tool_use_1 is None
    # tool_calls_index should NOT have been incremented
    assert decoder.tool_calls_index is None

    # Chunk 2: json_tool_call delta — should become text, not tool_use
    json_delta = ContentBlockDeltaEvent(toolUse={"input": '{"temp": 62}'})
    text_2, tool_use_2, _, _, _ = decoder._handle_converse_delta_event(json_delta, index=0)
    assert text_2 == '{"temp": 62}'
    assert tool_use_2 is None

    # Chunk 3: json_tool_call stop
    stop_tool = decoder._handle_converse_stop_event(index=0)
    assert stop_tool is None
    # _current_tool_name should be reset
    assert decoder._current_tool_name is None

    # Chunk 4: real tool start
    real_start = ContentBlockStartEvent(
        toolUse={
            "toolUseId": "tooluse_weather_001",
            "name": "get_weather",
        }
    )
    tool_use_4, _, _ = decoder._handle_converse_start_event(real_start)
    assert tool_use_4 is not None
    assert tool_use_4["function"]["name"] == "get_weather"
    assert decoder.tool_calls_index == 0

    # Chunk 5: real tool delta
    real_delta = ContentBlockDeltaEvent(toolUse={"input": '{"location": "SF"}'})
    text_5, tool_use_5, _, _, _ = decoder._handle_converse_delta_event(real_delta, index=1)
    assert text_5 == ""
    assert tool_use_5 is not None
    assert tool_use_5["function"]["arguments"] == '{"location": "SF"}'


def test_streaming_without_json_mode_passes_all_tools():
    """
    Verify backward compatibility: when json_mode=False, all tools
    (including json_tool_call if present) pass through unchanged.
    """
    from litellm.llms.bedrock.chat.invoke_handler import AWSEventStreamDecoder
    from litellm.types.llms.bedrock import (
        ContentBlockDeltaEvent,
        ContentBlockStartEvent,
    )

    decoder = AWSEventStreamDecoder(model="test-model", json_mode=False)

    # json_tool_call start — should pass through when json_mode=False
    json_start = ContentBlockStartEvent(
        toolUse={
            "toolUseId": "tooluse_json_001",
            "name": "json_tool_call",
        }
    )
    tool_use, _, _ = decoder._handle_converse_start_event(json_start)
    assert tool_use is not None
    assert tool_use["function"]["name"] == "json_tool_call"
    assert decoder.tool_calls_index == 0

    # json_tool_call delta — should be a tool_use, not text
    json_delta = ContentBlockDeltaEvent(toolUse={"input": '{"data": 1}'})
    text, tool_use_delta, _, _, _ = decoder._handle_converse_delta_event(json_delta, index=0)
    assert text == ""
    assert tool_use_delta is not None
    assert tool_use_delta["function"]["arguments"] == '{"data": 1}'


def test_cache_control_injection_tool_config():
    """Test that cache_control_injection_points with location=tool_config appends cachePoint to tools."""
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "What is the weather?"},
    ]
    optional_params = {
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get weather for a location",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "location": {"type": "string"},
                        },
                        "required": ["location"],
                    },
                },
            }
        ],
        "cache_control_injection_points": [
            {"location": "tool_config"},
        ],
    }
    result = config._transform_request(
        model="anthropic.claude-3-5-haiku-20241022-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
    )
    tool_config = result["toolConfig"]
    tools = tool_config["tools"]
    # Last element should be a cachePoint block
    assert tools[-1] == {"cachePoint": {"type": "default"}}
    # First element should be the actual tool
    assert "toolSpec" in tools[0]


def test_cache_control_injection_tool_config_no_tools():
    """Test that tool_config injection is ignored when no tools are provided."""
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "Hello"},
    ]
    optional_params = {
        "cache_control_injection_points": [
            {"location": "tool_config"},
        ],
    }
    result = config._transform_request(
        model="anthropic.claude-3-5-haiku-20241022-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
    )
    assert "toolConfig" not in result


def test_cache_control_injection_tool_config_not_added_without_injection_point():
    """Test that cachePoint is NOT appended when cache_control_injection_points doesn't include tool_config."""
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "What is the weather?"},
    ]
    optional_params = {
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get weather",
                    "parameters": {
                        "type": "object",
                        "properties": {"location": {"type": "string"}},
                        "required": ["location"],
                    },
                },
            }
        ],
        "cache_control_injection_points": [
            {"location": "message", "role": "system"},
        ],
    }
    result = config._transform_request(
        model="anthropic.claude-3-5-haiku-20241022-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
    )
    tools = result["toolConfig"]["tools"]
    # No cachePoint should be appended
    assert all("cachePoint" not in tool for tool in tools)


def test_cache_control_injection_tool_config_honors_ttl_for_supported_model(monkeypatch):
    """
    Regression test: cache_control_injection_points with location=tool_config
    must honor the requested `control.ttl`, mirroring the message/system
    cache_control behavior, instead of always emitting a bare
    {"type": "default"} cachePoint with no ttl.

    Forces the bundled local cost map so `supports_bedrock_prompt_cache_ttl` (which
    reads `cache_creation_input_token_cost_above_1hr` from litellm.model_cost)
    sees this branch's pricing data rather than the network-fetched `main`
    copy, which lacks it until merge.
    """
    old_env = os.environ.get("LITELLM_LOCAL_MODEL_COST_MAP")
    old_cost = litellm.model_cost
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    litellm.model_cost = litellm.get_model_cost_map(url="")
    try:
        config = AmazonConverseConfig()
        messages = [
            {"role": "user", "content": "What is the weather?"},
        ]
        optional_params = {
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get weather for a location",
                        "parameters": {
                            "type": "object",
                            "properties": {"location": {"type": "string"}},
                            "required": ["location"],
                        },
                    },
                }
            ],
            "cache_control_injection_points": [
                {"location": "tool_config", "control": {"type": "ephemeral", "ttl": "1h"}},
            ],
        }
        result = config._transform_request(
            model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
            messages=messages,
            optional_params=optional_params,
            litellm_params={},
        )
        tools = result["toolConfig"]["tools"]
        assert tools[-1] == {"cachePoint": {"type": "default", "ttl": "1h"}}
    finally:
        litellm.model_cost = old_cost
        if old_env is None:
            os.environ.pop("LITELLM_LOCAL_MODEL_COST_MAP", None)
        else:
            monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", old_env)


def test_cache_control_injection_tool_config_honors_ttl_for_regional_model_lacking_own_pricing(monkeypatch):
    """
    Regression test: a regional pricing entry that omits
    `cache_creation_input_token_cost_above_1hr` (e.g. `jp.anthropic.claude-opus-4-7`)
    must not shadow the base model entry that carries it; the requested ttl
    survives through the base-model fallback.
    """
    old_env = os.environ.get("LITELLM_LOCAL_MODEL_COST_MAP")
    old_cost = litellm.model_cost
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    cost_map = dict(litellm.get_model_cost_map(url=""))
    cost_map["jp.anthropic.claude-opus-4-7"] = {
        k: v
        for k, v in cost_map["jp.anthropic.claude-opus-4-7"].items()
        if k != "cache_creation_input_token_cost_above_1hr"
    }
    litellm.model_cost = cost_map
    try:
        assert "cache_creation_input_token_cost_above_1hr" in litellm.model_cost["anthropic.claude-opus-4-7"]
        config = AmazonConverseConfig()
        messages = [
            {"role": "user", "content": "What is the weather?"},
        ]
        optional_params = {
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get weather for a location",
                        "parameters": {
                            "type": "object",
                            "properties": {"location": {"type": "string"}},
                            "required": ["location"],
                        },
                    },
                }
            ],
            "cache_control_injection_points": [
                {"location": "tool_config", "control": {"type": "ephemeral", "ttl": "1h"}},
            ],
        }
        result = config._transform_request(
            model="jp.anthropic.claude-opus-4-7",
            messages=messages,
            optional_params=optional_params,
            litellm_params={},
        )
        tools = result["toolConfig"]["tools"]
        assert tools[-1] == {"cachePoint": {"type": "default", "ttl": "1h"}}
    finally:
        litellm.model_cost = old_cost
        if old_env is None:
            os.environ.pop("LITELLM_LOCAL_MODEL_COST_MAP", None)
        else:
            monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", old_env)


def test_cache_control_injection_tool_config_drops_ttl_for_unsupported_model():
    """
    Models that don't support extended TTL caching (only Claude 4.5+ on
    Bedrock does) must fall back to the default cachePoint with no ttl,
    even if the caller requested one, matching message/system behavior.
    """
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "What is the weather?"},
    ]
    optional_params = {
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get weather for a location",
                    "parameters": {
                        "type": "object",
                        "properties": {"location": {"type": "string"}},
                        "required": ["location"],
                    },
                },
            }
        ],
        "cache_control_injection_points": [
            {"location": "tool_config", "control": {"type": "ephemeral", "ttl": "1h"}},
        ],
    }
    result = config._transform_request(
        model="anthropic.claude-3-5-haiku-20241022-v1:0",
        messages=messages,
        optional_params=optional_params,
        litellm_params={},
    )
    tools = result["toolConfig"]["tools"]
    assert tools[-1] == {"cachePoint": {"type": "default"}}


@pytest.mark.parametrize(
    ("model", "expects_cache_points"),
    [
        pytest.param("nvidia.nemotron-super-3-120b", False, id="mapped-model-without-prompt-caching"),
        pytest.param("us.nvidia.nemotron-super-3-120b", False, id="regional-prefix-resolves-through-base-model"),
        pytest.param(
            "us.anthropic.claude-3-5-sonnet-20240620-v1:0", False, id="claude-named-but-not-caching-on-bedrock"
        ),
        pytest.param("us.anthropic.claude-sonnet-4-5-20250929-v1:0", True, id="mapped-model-with-prompt-caching"),
        pytest.param(
            "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123",
            True,
            id="unmapped-arn-keeps-emitting",
        ),
        pytest.param("global.openai.gpt-6-astra", False, id="openai-family-implicit-caching-only"),
        pytest.param("openai.gpt-oss-120b-1:0", False, id="openai-gpt-oss"),
        pytest.param("us.openai.gpt-99-unmapped", False, id="unmapped-openai-family-still-suppressed"),
        pytest.param("us.moonshotai.kimi-k3", False, id="kimi-k3-prices-cached-tokens-but-rejects-cachepoint"),
        pytest.param("global.moonshotai.kimi-k3", False, id="kimi-k3-global-profile"),
        pytest.param("us-east-1/us.moonshotai.kimi-k3", False, id="kimi-k3-regional-route-resolves-through-profile"),
    ],
)
def test_cache_points_emitted_only_for_models_that_support_prompt_caching(model, expects_cache_points, monkeypatch):
    """Bedrock rejects cachePoint blocks for models without prompt caching support
    ("You invoked an unsupported model or your request did not allow prompt caching")
    and for models that price cached tokens yet take the marker only on their native
    endpoints ("This model doesn't support the cachePoint field", Kimi K3), and clients
    like Claude Code attach cache_control to every request, so a map-known model without
    the capability must not receive them on system, message, or tool blocks. Unmapped ids
    (application inference profile ARNs, models newer than the map) keep emitting so
    existing caching setups never silently degrade."""
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))

    body = AmazonConverseConfig()._transform_request(
        model=model,
        messages=[
            {"role": "system", "content": [{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral"}}]},
            {"role": "user", "content": [{"type": "text", "text": "hi", "cache_control": {"type": "ephemeral"}}]},
        ],
        optional_params={
            "tools": [
                {
                    "type": "function",
                    "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {}}},
                    "cache_control": {"type": "ephemeral"},
                }
            ]
        },
        litellm_params={},
        headers={},
    )

    assert ("cachePoint" in json.dumps(body["system"])) is expects_cache_points
    assert ("cachePoint" in json.dumps(body["messages"])) is expects_cache_points
    assert ("cachePoint" in json.dumps(body["toolConfig"])) is expects_cache_points
    assert body["system"][0]["text"] == "sys"
    assert body["messages"][0]["content"][0]["text"] == "hi"
    assert body["toolConfig"]["tools"][0]["toolSpec"]["name"] == "get_weather"


def test_tool_config_cachepoint_not_placed_or_credited_for_model_without_prompt_caching(monkeypatch):
    """The tool_config injection point must stand down with the rest of the cachePoint
    emission when the model cannot cache, and spend attribution must not credit the
    gateway for a breakpoint that was never placed."""
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))

    bucket: dict = {"user_api_key": "sk-test"}
    data = AmazonConverseConfig()._transform_request_helper(
        model="nvidia.nemotron-super-3-120b",
        system_content_blocks=[],
        optional_params={
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get weather",
                        "parameters": {
                            "type": "object",
                            "properties": {"location": {"type": "string"}},
                            "required": ["location"],
                        },
                    },
                }
            ],
            "cache_control_injection_points": [{"location": "tool_config"}],
        },
        messages=[{"role": "user", "content": "hi"}],
        litellm_params={"metadata": bucket, "litellm_metadata": None, "model_info": {"id": "dep-bedrock"}},
    )

    assert "cachePoint" not in json.dumps(data.get("toolConfig", {}))
    assert "litellm_gateway_injected_cache" not in bucket


def test_transform_response_finish_reason_stop_when_json_mode_filters_all_tools():
    """
    When json_mode is True and _filter_json_mode_tools strips all synthetic
    tool calls, finish_reason should be "stop", not "tool_calls".

    Bedrock returns stopReason="tool_use" for json_tool_call responses.
    After filtering, the response is plain JSON content and should not look
    like a pending tool invocation to callers.
    """
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 100},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_001",
                            "name": "json_tool_call",
                            "input": {
                                "facts": ["Bob is a software engineer"],
                            },
                        }
                    }
                ],
            }
        },
        "stopReason": "tool_use",
        "usage": {
            "inputTokens": 50,
            "outputTokens": 20,
            "totalTokens": 70,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()

    # Simulate what happens when json_tool_call was injected for a
    # json_schema request: optional_params has the synthetic tool
    optional_params = {
        "json_mode": True,
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "json_tool_call",
                    "parameters": {
                        "type": "object",
                        "additionalProperties": True,
                        "properties": {},
                    },
                },
            }
        ],
    }

    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params=optional_params,
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    # Content should have the JSON from the tool call arguments
    content = result.choices[0].message.content
    assert content is not None
    parsed = json.loads(content)
    assert parsed["facts"] == ["Bob is a software engineer"]

    # No tool_calls on the message
    assert result.choices[0].message.tool_calls is None

    # finish_reason must be "stop", not "tool_calls"
    assert result.choices[0].finish_reason == "stop"


def test_transform_response_json_mode_truncated_tool_call_keeps_length_finish_reason():
    """
    When json_mode filters out the synthetic json_tool_call but Bedrock
    stopped on max_tokens, finish_reason must stay "length", not be
    downgraded to "stop" — otherwise truncated structured output looks
    completed.
    """
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 100},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "toolUse": {
                            "toolUseId": "tooluse_001",
                            "name": "json_tool_call",
                            "input": {"a": "cut"},
                        }
                    }
                ],
            }
        },
        "stopReason": "max_tokens",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 60,
            "totalTokens": 70,
        },
    }

    class MockResponse:
        def json(self) -> dict[str, object]:
            return response_json

        @property
        def text(self) -> str:
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()

    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params={"json_mode": True},
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    assert result.choices[0].finish_reason == "length"


def test_transform_response_citations_content_maps_to_annotations():
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 100},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "citationsContent": {
                            "content": [
                                {
                                    "text": "Apptio is a company that makes calls to Bedrock using passthrough APIs via LiteLLM"
                                }
                            ],
                            "citations": [
                                {
                                    "location": {
                                        "searchResultLocation": {
                                            "start": 0,
                                            "end": 42,
                                            "searchResultIndex": 0,
                                        }
                                    },
                                    "source": "https://www.apptio.com/about",
                                    "title": "About Apptio",
                                }
                            ],
                        }
                    },
                    {"text": "."},
                ],
            }
        },
        "stopReason": "end_turn",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 5,
            "totalTokens": 15,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    model_response = ModelResponse()

    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=model_response,
        stream=False,
        logging_obj=None,
        optional_params={},
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    message = result.choices[0].message
    assert message.content.startswith("Apptio is a company")
    assert message.annotations is not None
    assert len(message.annotations) == 1
    annotation = message.annotations[0]
    assert annotation["type"] == "url_citation"
    assert annotation["url_citation"]["start_index"] == 0
    assert annotation["url_citation"]["end_index"] == 42
    assert annotation["url_citation"]["title"] == "About Apptio"
    assert annotation["url_citation"]["url"] == "https://www.apptio.com/about"


def test_transform_response_citation_null_source_title_become_empty_strings():
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 100},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "citationsContent": {
                            "content": [{"text": "Apptio is a company that makes calls to Bedrock"}],
                            "citations": [
                                {
                                    "location": {
                                        "searchResultLocation": {
                                            "start": 0,
                                            "end": 42,
                                            "searchResultIndex": 0,
                                        }
                                    },
                                    "source": None,
                                    "title": None,
                                }
                            ],
                        }
                    },
                    {"text": "."},
                ],
            }
        },
        "stopReason": "end_turn",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 5,
            "totalTokens": 15,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=ModelResponse(),
        stream=False,
        logging_obj=None,
        optional_params={},
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    message = result.choices[0].message
    annotation = message.annotations[0]
    assert annotation["url_citation"]["url"] == ""
    assert annotation["url_citation"]["title"] == ""


def test_transform_response_citations_offset_tracks_text_only_blocks():
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    leading_text = "First sentence without a citation. "
    cited_text = "Apptio is a company that makes calls to Bedrock"
    response_json = {
        "metrics": {"latencyMs": 100},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "citationsContent": {
                            "content": [{"text": leading_text}],
                        }
                    },
                    {
                        "citationsContent": {
                            "content": [{"text": cited_text}],
                            "citations": [
                                {
                                    "location": {
                                        "searchResultLocation": {
                                            "start": 0,
                                            "end": len(cited_text),
                                            "searchResultIndex": 0,
                                        }
                                    },
                                    "source": "https://www.apptio.com/about",
                                    "title": "About Apptio",
                                }
                            ],
                        }
                    },
                ],
            }
        },
        "stopReason": "end_turn",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 5,
            "totalTokens": 15,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=ModelResponse(),
        stream=False,
        logging_obj=None,
        optional_params={},
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    message = result.choices[0].message
    expected_start = len(leading_text)
    assert message.content == leading_text + cited_text
    assert message.content[expected_start : expected_start + len(cited_text)] == cited_text
    assert message.annotations is not None
    assert len(message.annotations) == 1
    assert message.annotations[0]["url_citation"]["start_index"] == expected_start
    assert message.annotations[0]["url_citation"]["end_index"] == expected_start + len(cited_text)


def test_transform_response_stitches_citations_for_whitespace_punctuation_text():
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
    from litellm.types.utils import ModelResponse

    response_json = {
        "metrics": {"latencyMs": 100},
        "output": {
            "message": {
                "role": "assistant",
                "content": [
                    {
                        "citationsContent": {
                            "content": [
                                {
                                    "text": "Apptio is a company that makes calls to Bedrock using passthrough APIs via LiteLLM"
                                }
                            ],
                            "citations": [
                                {
                                    "location": {
                                        "searchResultLocation": {
                                            "start": 0,
                                            "end": 42,
                                            "searchResultIndex": 0,
                                        }
                                    },
                                    "source": "https://www.apptio.com/about",
                                    "title": "About Apptio",
                                }
                            ],
                        }
                    },
                    {"text": " ."},
                ],
            }
        },
        "stopReason": "end_turn",
        "usage": {
            "inputTokens": 10,
            "outputTokens": 5,
            "totalTokens": 15,
            "cacheReadInputTokenCount": 0,
            "cacheReadInputTokens": 0,
            "cacheWriteInputTokenCount": 0,
            "cacheWriteInputTokens": 0,
        },
    }

    class MockResponse:
        def json(self):
            return response_json

        @property
        def text(self):
            return json.dumps(response_json)

    config = AmazonConverseConfig()
    result = config._transform_response(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        response=MockResponse(),
        model_response=ModelResponse(),
        stream=False,
        logging_obj=None,
        optional_params={},
        api_key=None,
        data=None,
        messages=[],
        encoding=None,
    )

    message = result.choices[0].message
    assert message.content.startswith("Apptio is a company")
    assert message.annotations is not None
    assert len(message.annotations) == 1
    assert message.annotations[0]["url_citation"]["start_index"] == 0
    assert message.annotations[0]["url_citation"]["end_index"] == 42


def test_bedrock_tool_message_openai_file_pdf_becomes_document():
    """
    OpenAI Chat Completions `{type: "file", file: {file_data: "data:application/pdf;...", filename}}`
    inside a tool message content list should translate to a Bedrock
    toolResult.content[].document block.
    """
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    pdf_b64 = "JVBERi0xLjQKJeLjz9MK"  # tiny "%PDF-1.4\n" header
    messages = [
        {"role": "user", "content": "Summarize the attached PDF."},
        {
            "tool_call_id": "tooluse_pdf_1",
            "role": "tool",
            "name": "fetch_document",
            "content": [
                {
                    "type": "file",
                    "file": {
                        "file_data": f"data:application/pdf;base64,{pdf_b64}",
                        "filename": "summary.pdf",
                    },
                },
            ],
        },
    ]

    translated_msg = _bedrock_converse_messages_pt(messages=messages, model="", llm_provider="")

    tool_result = translated_msg[-1]["content"][-1]["toolResult"]
    assert tool_result["toolUseId"] == "tooluse_pdf_1"
    assert len(tool_result["content"]) == 1
    block = tool_result["content"][0]
    assert "document" in block, f"expected document block, got {block}"
    assert block["document"]["format"] == "pdf"
    assert block["document"]["source"]["bytes"] == pdf_b64
    assert block["document"]["name"].startswith("DocumentPDFmessages_")
    assert block["document"]["name"].endswith("_pdf")


def test_bedrock_tool_message_image_url_pdf_data_uri_becomes_document():
    """
    Regression for the processor-returns-document-but-wrapper-drops-it bug:
    when a caller sends a PDF as an `image_url` data URI on the tool-result path,
    BedrockImageProcessor correctly returns a {"document": ...} block, but the
    tool-result wrapper only appended the "image" case, silently dropping documents.
    """
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    pdf_b64 = "JVBERi0xLjQKJeLjz9MK"
    messages = [
        {"role": "user", "content": "Summarize the attached PDF."},
        {
            "tool_call_id": "tooluse_pdf_img_1",
            "role": "tool",
            "name": "fetch_document",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:application/pdf;base64,{pdf_b64}",
                    },
                },
            ],
        },
    ]

    translated_msg = _bedrock_converse_messages_pt(messages=messages, model="", llm_provider="")

    tool_result = translated_msg[-1]["content"][-1]["toolResult"]
    assert tool_result["toolUseId"] == "tooluse_pdf_img_1"
    assert len(tool_result["content"]) == 1
    block = tool_result["content"][0]
    assert "document" in block, f"expected document block, got {block}"
    assert block["document"]["format"] == "pdf"
    assert block["document"]["source"]["bytes"] == pdf_b64


def test_bedrock_tool_message_file_id_http_url_becomes_document():
    """
    OpenAI `file.file_id` is a server-side file reference. The Bedrock
    user-message path (_process_file_message at factory.py:4796) accepts either
    `file_data` or `file_id` and forwards to BedrockImageProcessor. The
    tool-result path must match: when `file_id` is an http(s) PDF URL, it
    should resolve to a Bedrock document block, not be silently dropped.
    """
    from unittest.mock import patch

    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockImageProcessor,
        _bedrock_converse_messages_pt,
    )

    pdf_url = "https://example.com/whitepaper.pdf"
    fake_document_block = {
        "document": {
            "format": "pdf",
            "name": "fake_doc",
            "source": {"bytes": "ZmFrZQ=="},
        }
    }
    messages = [
        {"role": "user", "content": "Summarize the attached PDF."},
        {
            "tool_call_id": "tooluse_fid_1",
            "role": "tool",
            "name": "fetch_document",
            "content": [
                {
                    "type": "file",
                    "file": {
                        "file_id": pdf_url,
                        "filename": "whitepaper.pdf",
                    },
                },
            ],
        },
    ]

    with patch.object(
        BedrockImageProcessor,
        "process_image_sync",
        return_value=fake_document_block,
    ) as mock_proc:
        translated_msg = _bedrock_converse_messages_pt(messages=messages, model="", llm_provider="")

    mock_proc.assert_called_once()
    assert mock_proc.call_args.kwargs["image_url"] == pdf_url

    tool_result = translated_msg[-1]["content"][-1]["toolResult"]
    assert len(tool_result["content"]) == 1
    block = tool_result["content"][0]
    assert "document" in block, f"expected document block, got {block}"
    assert block["document"]["source"]["bytes"] == "ZmFrZQ=="


def test_bedrock_tool_message_file_without_data_or_id_raises():
    """
    The user-message path raises BadRequestError when a `type: "file"` block
    has neither `file_data` nor `file_id` (factory.py:4802-4809). The
    tool-result path must match — silently dropping the block makes the model
    see an empty tool result and obscures the caller bug.
    """
    import litellm
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    messages = [
        {"role": "user", "content": "Summarize."},
        {
            "tool_call_id": "tooluse_bad_1",
            "role": "tool",
            "name": "fetch_document",
            "content": [
                {
                    "type": "file",
                    "file": {"filename": "nothing.pdf"},
                },
            ],
        },
    ]

    with pytest.raises(litellm.BadRequestError):
        _bedrock_converse_messages_pt(messages=messages, model="", llm_provider="")


def test_bedrock_tool_message_image_url_png_still_becomes_image():
    """
    Regression: image_url with an image mime type must continue to translate
    to a Bedrock image block (not document). Locks in existing behavior after
    the document-passthrough fix.
    """
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABXvMqOgAAAABJRU5ErkJggg=="
    messages = [
        {"role": "user", "content": "Describe the attached image."},
        {
            "tool_call_id": "tooluse_png_1",
            "role": "tool",
            "name": "fetch_image",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/png;base64,{png_b64}",
                    },
                },
            ],
        },
    ]

    translated_msg = _bedrock_converse_messages_pt(messages=messages, model="", llm_provider="")

    tool_result = translated_msg[-1]["content"][-1]["toolResult"]
    assert len(tool_result["content"]) == 1
    block = tool_result["content"][0]
    assert "image" in block, f"expected image block, got {block}"
    assert "document" not in block
    assert block["image"]["format"] == "png"
    assert block["image"]["source"]["bytes"] == png_b64


def _png_tool_messages(text: str | None = None) -> list[AllMessageValues]:
    from litellm.types.llms.openai import (
        ChatCompletionImageObject,
        ChatCompletionImageUrlObject,
        ChatCompletionTextObject,
        ChatCompletionToolMessage,
        ChatCompletionUserMessage,
    )

    png_b64: Final = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABXvMqOgAAAABJRU5ErkJggg=="
    image: Final = ChatCompletionImageObject(
        type="image_url",
        image_url=ChatCompletionImageUrlObject(url=f"data:image/png;base64,{png_b64}"),
    )
    parts: Final = (ChatCompletionTextObject(type="text", text=text), image) if text is not None else (image,)
    user: Final = ChatCompletionUserMessage(role="user", content="Describe the attached image.")
    tool: Final = ChatCompletionToolMessage(role="tool", tool_call_id="tooluse_png_gpt", content=list(parts))
    return [user, tool]


def _gpt_tool_turn(text: str | None) -> list[ContentBlock]:
    from litellm.types.llms.openai import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk

    fetch_tool: Final = ChatCompletionToolParam(
        type="function",
        function=ChatCompletionToolParamFunctionChunk(
            name="fetch_image",
            description="Returns an image",
            parameters={"type": "object", "properties": {}},
        ),
    )
    body: Final = AmazonConverseConfig()._transform_request(
        model="bedrock/global.openai.gpt-6.1-sol",
        messages=_png_tool_messages(text),
        optional_params={"tools": [fetch_tool]},
        litellm_params={},
        headers={},
    )
    messages: Final = body["messages"]
    assert isinstance(messages, list)
    last: Final = messages[-1]
    assert isinstance(last, dict)
    content: Final = last["content"]
    assert isinstance(content, list)
    return [ContentBlock(**block) for block in content if isinstance(block, dict)]


def test_openai_gpt_tool_result_image_sits_beside_the_tool_result():
    """gpt-6.1-sol rejects an image nested in toolResult.content. The image has to be a sibling block."""
    turn: Final = _gpt_tool_turn("tool image")
    tool_index: Final = next(i for i, block in enumerate(turn) if "toolResult" in block)
    tool_result: Final = turn[tool_index]["toolResult"]
    assert isinstance(tool_result, dict)
    assert tool_result["toolUseId"] == "tooluse_png_gpt"
    assert tool_result["content"] == [{"text": "tool image"}]
    image: Final = turn[tool_index + 1]["image"]
    assert isinstance(image, dict)
    assert image["format"] == "png"


def test_openai_gpt_image_only_tool_result_keeps_a_text_block():
    from litellm.litellm_core_utils.prompt_templates.common_utils import TOOL_RESULT_IMAGE_PLACEHOLDER

    turn: Final = _gpt_tool_turn(None)
    tool_index: Final = next(i for i, block in enumerate(turn) if "toolResult" in block)
    tool_result: Final = turn[tool_index]["toolResult"]
    assert isinstance(tool_result, dict)
    assert tool_result["content"] == [{"text": TOOL_RESULT_IMAGE_PLACEHOLDER}]
    image: Final = turn[tool_index + 1]["image"]
    assert isinstance(image, dict)
    assert image["format"] == "png"


def test_transform_response_does_not_leak_body_on_parse_failure():
    from litellm.llms.bedrock.common_utils import BedrockError

    leaky_body = {"output": {"message": {"content": [{"text": "secret content"}]}}}

    class MockResponse:
        headers = httpx.Headers({"x-amzn-RequestId": "req-parse-failure"})

        def json(self):
            return leaky_body

        @property
        def text(self):
            return json.dumps(leaky_body)

    with patch(
        "litellm.llms.bedrock.chat.converse_transformation.ConverseResponseBlock",
        side_effect=KeyError("missing required field"),
    ):
        with pytest.raises(BedrockError) as exc_info:
            AmazonConverseConfig()._transform_response(
                model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
                response=MockResponse(),
                model_response=ModelResponse(),
                stream=False,
                logging_obj=None,
                optional_params={},
                api_key=None,
                data=None,
                messages=[],
                encoding=None,
            )

    msg = str(exc_info.value)
    assert "secret content" not in msg
    assert "Error converting to valid response block" in msg
    assert exc_info.value.response.headers["x-amzn-requestid"] == "req-parse-failure"


def test_converse_drops_sampling_params_for_models_that_removed_them():
    """Fable 5 / Opus 4.7 / 4.8 reject temperature != 1 and any top_p; with
    drop_params set, converse must drop them instead of forwarding (#30064)."""
    config = AmazonConverseConfig()

    result = config.map_openai_params(
        non_default_params={"temperature": 0.5, "top_p": 0.9},
        optional_params={},
        model="us.anthropic.claude-fable-5",
        drop_params=True,
    )

    assert "temperature" not in result
    assert "topP" not in result


def test_converse_sampling_params_raise_without_drop_params(monkeypatch):
    monkeypatch.setattr(litellm, "drop_params", False)
    config = AmazonConverseConfig()

    with pytest.raises(litellm.utils.UnsupportedParamsError, match="drop_params"):
        config.map_openai_params(
            non_default_params={"temperature": 0.5},
            optional_params={},
            model="global.anthropic.claude-opus-4-8-v1:0",
            drop_params=False,
        )


def test_converse_sampling_params_forwarded_on_models_that_accept_them():
    config = AmazonConverseConfig()

    result = config.map_openai_params(
        non_default_params={"temperature": 0.5, "top_p": 0.9},
        optional_params={},
        model="us.anthropic.claude-sonnet-4-6",
        drop_params=True,
    )

    assert result["temperature"] == 0.5
    assert result["topP"] == 0.9


def test_converse_top_k_dropped_for_models_that_removed_it():
    """``top_k`` reaches converse as a provider-specific kwarg destined for
    ``additionalModelRequestFields``, bypassing ``map_openai_params``; the
    transform must strip it for models that removed sampling params (#30064)."""
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-fable-5",
        messages=[{"role": "user", "content": "hello"}],
        optional_params={"top_k": 40},
        litellm_params={"drop_params": True},
        headers={},
    )

    assert "top_k" not in result.get("additionalModelRequestFields", {})


def test_converse_top_k_raises_without_drop_params(monkeypatch):
    monkeypatch.setattr(litellm, "drop_params", False)
    config = AmazonConverseConfig()

    with pytest.raises(litellm.utils.UnsupportedParamsError, match="drop_params"):
        config._transform_request(
            model="us.anthropic.claude-fable-5",
            messages=[{"role": "user", "content": "hello"}],
            optional_params={"top_k": 40},
            litellm_params={},
            headers={},
        )


def test_converse_top_k_forwarded_on_models_that_accept_it():
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-sonnet-4-6",
        messages=[{"role": "user", "content": "hello"}],
        optional_params={"top_k": 40},
        litellm_params={"drop_params": True},
        headers={},
    )

    assert result["additionalModelRequestFields"]["top_k"] == 40


def test_converse_top_k_zero_raises_without_drop_params(monkeypatch):
    """``top_k=0`` must hit the same gating as any other value; previously the
    truthiness check let it silently disappear on models that removed sampling
    params, diverging from the Anthropic boundary that treats ``0`` as present."""
    monkeypatch.setattr(litellm, "drop_params", False)
    config = AmazonConverseConfig()

    with pytest.raises(litellm.utils.UnsupportedParamsError, match="drop_params"):
        config._transform_request(
            model="us.anthropic.claude-fable-5",
            messages=[{"role": "user", "content": "hello"}],
            optional_params={"top_k": 0},
            litellm_params={},
            headers={},
        )


def test_converse_top_k_zero_forwarded_on_models_that_accept_it():
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-sonnet-4-6",
        messages=[{"role": "user", "content": "hello"}],
        optional_params={"top_k": 0},
        litellm_params={"drop_params": True},
        headers={},
    )

    assert result["additionalModelRequestFields"]["top_k"] == 0


@pytest.mark.asyncio
async def test_grounding_source_and_query_rendered_as_text():
    """grounding_source / query content blocks must render as plain text on the
    generate path (the model needs to see the RAG context + question). The bedrock
    converse dispatch silently drops unrecognised content types, so these would
    otherwise vanish from the prompt."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "grounding_source", "text": "Tokyo is the capital of Japan."},
                {"type": "query", "text": "What is the capital of Japan?"},
            ],
        }
    ]

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )
    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        llm_provider="bedrock_converse",
    )

    assert result == async_result
    assert len(result) == 1
    assert result[0]["role"] == "user"
    user_content = result[0]["content"]
    assert {"text": "Tokyo is the capital of Japan."} in user_content
    assert {"text": "What is the capital of Japan?"} in user_content


def _orphaned_tool_history_messages():
    return [
        {"role": "user", "content": "What's the weather in Paris?"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_abc",
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "arguments": '{"city": "Paris"}',
                    },
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "call_abc",
            "content": "Sunny, 25C",
        },
        {"role": "user", "content": "Summarize our conversation so far."},
    ]


def test_neutralize_orphaned_tool_blocks_rewrites_when_no_tools():
    """No tools= but history has tool blocks: assistant tool_calls and the tool
    result must be rewritten to text, with the structured tool fields gone and
    tool_call_id preserved, so Bedrock accepts the request without a toolConfig
    (#24158, #27138)."""
    messages = _orphaned_tool_history_messages()

    result = AmazonConverseConfig._neutralize_orphaned_tool_blocks(messages, optional_params={})

    serialized = json.dumps(result)
    assert "tool_calls" not in serialized
    assert not any(m.get("role") in ("tool", "function") for m in result)
    assert "get_weather" in serialized
    # The arguments string contains quotes; after json.dumps the literal
    # '{"city": "Paris"}' is escaped, so assert on quote-free tokens that survive.
    assert "city" in serialized and "Paris" in serialized
    assert "Sunny, 25C" in serialized
    assert "[tool call call_abc: get_weather(" in result[1]["content"]
    assert "[tool result for call_abc: Sunny, 25C]" in result[2]["content"]


@pytest.mark.parametrize("tools_value", [[], None])
def test_neutralize_orphaned_tool_blocks_rewrites_when_tools_empty(tools_value):
    """tools=[] and tools=None are 'no usable tools'; the gate must be on
    truthiness, not key presence, or these slip through and still emit
    structured tool blocks with no toolConfig."""
    messages = _orphaned_tool_history_messages()

    result = AmazonConverseConfig._neutralize_orphaned_tool_blocks(messages, optional_params={"tools": tools_value})

    serialized = json.dumps(result)
    assert "tool_calls" not in serialized
    assert "get_weather" in serialized


def test_neutralize_orphaned_tool_blocks_rewrites_tool_result_only_history():
    """A role:"tool"-only history (no assistant tool_calls) must also be
    neutralized; has_tool_call_blocks misses this, but the factory still emits a
    lone toolResult with no toolConfig."""
    messages = [
        {"role": "user", "content": "hi"},
        {"role": "tool", "tool_call_id": "call_xyz", "content": "lookup result"},
    ]

    result = AmazonConverseConfig._neutralize_orphaned_tool_blocks(messages, optional_params={})

    assert not any(m.get("role") in ("tool", "function") for m in result)
    serialized = json.dumps(result)
    assert "lookup result" in serialized
    assert "call_xyz" in serialized


def test_neutralize_orphaned_tool_blocks_non_text_result_marked_not_empty():
    """Non-text tool-result payloads (image/file) collapse to an explicit
    marker, never an empty string (Bedrock rejects empty text blocks) and never
    a silent drop."""
    messages = [
        {"role": "user", "content": "hi"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "c1",
                    "type": "function",
                    "function": {"name": "render", "arguments": "{}"},
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "c1",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": "data:image/png;base64,AAAA"},
                }
            ],
        },
    ]

    result = AmazonConverseConfig._neutralize_orphaned_tool_blocks(messages, optional_params={})

    rewritten = next(m for m in result if m.get("role") == "user" and m is not messages[0])
    text = rewritten["content"]
    assert text.strip()  # never empty
    assert "non-text tool result omitted" in text


def test_neutralize_orphaned_tool_blocks_noop_when_tools_present():
    """When a non-empty tools= is provided, tool blocks are legitimate and must
    be left untouched (returns the same object, no rewriting)."""
    messages = _orphaned_tool_history_messages()

    result = AmazonConverseConfig._neutralize_orphaned_tool_blocks(
        messages,
        optional_params={"tools": [{"type": "function", "function": {"name": "x"}}]},
    )

    assert result is messages


def test_neutralize_orphaned_tool_blocks_noop_when_no_tool_history():
    """Plain conversation with no tool blocks is returned unchanged."""
    messages = [{"role": "user", "content": "hi"}]

    result = AmazonConverseConfig._neutralize_orphaned_tool_blocks(messages, optional_params={})

    assert result is messages


def test_neutralize_orphaned_tool_blocks_logs_warning(caplog):
    """Neutralization must surface at WARNING level so a developer who forgot
    tools= sees it instead of a silent degrade."""
    messages = _orphaned_tool_history_messages()

    with caplog.at_level("WARNING"):
        AmazonConverseConfig._neutralize_orphaned_tool_blocks(messages, optional_params={})

    assert any("neutralizing orphaned tool blocks" in record.getMessage() for record in caplog.records)


def _assert_no_structured_tool_blocks(result):
    """A valid Bedrock body for a neutralized request has no tool config AND no
    structured tool blocks in messages. Checking only toolConfig is insufficient:
    deleting the raise without rewriting still leaves toolUse/toolResult, the
    exact shape Bedrock rejects."""
    assert "toolConfig" not in result
    serialized = json.dumps(result)
    assert "toolUse" not in serialized
    assert "toolResult" not in serialized


def test_transform_request_no_tools_with_tool_history_succeeds_24158(monkeypatch):
    """#24158: a compaction-style call (tool blocks in history, no tools=) must
    not raise and must send no toolConfig or structured tool blocks, on
    default settings."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=_orphaned_tool_history_messages(),
        optional_params={},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)
    serialized = json.dumps(result)
    assert "get_weather" in serialized
    assert "Sunny, 25C" in serialized


def test_transform_request_tool_unsupported_model_no_toolconfig_27138(monkeypatch):
    """#27138: a tool-incapable model with tool blocks in history and no tools=
    must not get a toolConfig/toolUse/toolResult injected (which Bedrock would
    400 on), even with modify_params on."""
    monkeypatch.setattr(litellm, "modify_params", True)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="meta.llama3-2-3b-instruct-v1:0",
        messages=_orphaned_tool_history_messages(),
        optional_params={},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)


@pytest.mark.parametrize("tools_value", [[], None])
def test_transform_request_empty_tools_with_tool_history(monkeypatch, tools_value):
    """tools=[] / tools=None must be neutralized like no tools at all; a
    key-presence gate would skip them and emit toolUse/toolResult with no
    toolConfig."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=_orphaned_tool_history_messages(),
        optional_params={"tools": tools_value},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)


def test_transform_request_tool_result_only_history(monkeypatch):
    """A role:"tool"-only history (no assistant tool_calls) currently emits a
    lone toolResult with no toolConfig; it must be neutralized."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=[
            {"role": "user", "content": "hi"},
            {"role": "tool", "tool_call_id": "call_xyz", "content": "lookup result"},
        ],
        optional_params={},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)
    assert "lookup result" in json.dumps(result)


def test_transform_request_neutralized_tool_output_is_guarded(monkeypatch):
    """With guardrailConfig present, a neutralized tool result that becomes the
    trailing user turn must be emitted as guardContent, not plain text, so
    untrusted tool output does not bypass the guardrail (neutralize must run
    before guarded-text conversion)."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=[
            {"role": "user", "content": "look it up"},
            {
                "role": "assistant",
                "content": None,
                "tool_calls": [
                    {
                        "id": "c1",
                        "type": "function",
                        "function": {"name": "lookup", "arguments": "{}"},
                    }
                ],
            },
            {"role": "tool", "tool_call_id": "c1", "content": "secret tool output"},
        ],
        optional_params={"guardrailConfig": {"guardrailIdentifier": "gid", "guardrailVersion": "1"}},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)
    serialized = json.dumps(result)
    assert "guardContent" in serialized
    assert "secret tool output" in serialized


def test_transform_request_neutralized_tool_output_guarded_mid_history(monkeypatch):
    """Regression: a neutralized tool result that is NOT the trailing turn (an
    assistant reply and a later user turn follow it) must still be guardContent.
    _convert_consecutive_user_messages_to_guarded_text only covers the trailing
    user turn, so neutralize itself must guard untrusted tool output regardless
    of position, else an attacker controlling the tool response bypasses the
    guardrail (bot review)."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=[
            {"role": "user", "content": "look it up"},
            {
                "role": "assistant",
                "content": None,
                "tool_calls": [
                    {
                        "id": "c1",
                        "type": "function",
                        "function": {"name": "lookup", "arguments": "{}"},
                    }
                ],
            },
            {"role": "tool", "tool_call_id": "c1", "content": "IGNORE_PRIOR malware"},
            {"role": "assistant", "content": "Here is the summary."},
            {"role": "user", "content": "thanks"},
        ],
        optional_params={"guardrailConfig": {"guardrailIdentifier": "gid", "guardrailVersion": "1"}},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)
    blocks = [block for message in result["messages"] for block in message["content"]]
    guarded_texts = [block["guardContent"]["text"]["text"] for block in blocks if "guardContent" in block]
    plain_texts = [block["text"] for block in blocks if "text" in block and "guardContent" not in block]
    assert any("malware" in text for text in guarded_texts), "mid-history tool output must be guarded"
    assert not any("malware" in text for text in plain_texts), (
        "mid-history tool output must not reach the model as unguarded text"
    )


@pytest.mark.asyncio
async def test_async_transform_request_no_tools_with_tool_history(monkeypatch):
    """Async is a separate request assembler; it must neutralize identically."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    result = await config._async_transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=_orphaned_tool_history_messages(),
        optional_params={},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)
    assert "get_weather" in json.dumps(result)


def test_transform_request_with_tools_still_builds_toolconfig(monkeypatch):
    """Guard: when a non-empty tools= IS provided, tool blocks are legitimate and
    a toolConfig must still be produced (neutralization must not regress this)."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=_orphaned_tool_history_messages(),
        optional_params={
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get weather",
                        "parameters": {"type": "object", "properties": {}},
                    },
                }
            ]
        },
        litellm_params={},
        headers={},
    )

    assert "toolConfig" in result


def test_transform_request_flag_off_restores_raise(monkeypatch):
    """Opt-out: with bedrock_neutralize_orphaned_tool_blocks=False and
    modify_params=False, the legacy UnsupportedParamsError contract is restored."""
    monkeypatch.setattr(litellm, "bedrock_neutralize_orphaned_tool_blocks", False)
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    with pytest.raises(litellm.utils.UnsupportedParamsError, match="without `tools="):
        config._transform_request(
            model="us.anthropic.claude-opus-4-5-20251101-v1:0",
            messages=_orphaned_tool_history_messages(),
            optional_params={},
            litellm_params={},
            headers={},
        )


def test_transform_request_flag_off_with_modify_params_restores_dummy_tool(monkeypatch):
    """Opt-out: with the flag off and modify_params=True, the legacy dummy-tool
    injection is restored (a toolConfig is produced, not neutralized text)."""
    monkeypatch.setattr(litellm, "bedrock_neutralize_orphaned_tool_blocks", False)
    monkeypatch.setattr(litellm, "modify_params", True)
    config = AmazonConverseConfig()

    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=_orphaned_tool_history_messages(),
        optional_params={},
        litellm_params={},
        headers={},
    )

    assert "toolConfig" in result
    assert "dummy_tool" in json.dumps(result)


def test_transform_request_flag_on_is_default(monkeypatch):
    """Default-on: without touching the flag, neutralization is the behavior."""
    monkeypatch.setattr(litellm, "modify_params", False)
    config = AmazonConverseConfig()

    assert litellm.bedrock_neutralize_orphaned_tool_blocks is True
    result = config._transform_request(
        model="us.anthropic.claude-opus-4-5-20251101-v1:0",
        messages=_orphaned_tool_history_messages(),
        optional_params={},
        litellm_params={},
        headers={},
    )

    _assert_no_structured_tool_blocks(result)


def _agentic_messages_with_ttl(ttl_target: str):
    """A tool-loop conversation with `ttl: 1h` cache_control at `ttl_target`:
    'user', 'tool_call' (per-tool-call, on the assistant's tool call), or
    'tool' (message-level, on the tool result - where
    `cache_control_injection_points` with `index: -1` lands mid-loop).

    Message-level cache_control on a content-less assistant message emits no
    cachePoint at all today (a separate gap, orthogonal to ttl); per-tool-call
    placement covers that message, so it's excluded from the params below."""
    user: dict = {"role": "user", "content": "optimize this kernel " * 60}
    assistant: dict = {
        "role": "assistant",
        "content": None,
        "tool_calls": [
            {
                "id": "call_1",
                "type": "function",
                "function": {"name": "evaluate", "arguments": "{}"},
            }
        ],
    }
    tool: dict = {"role": "tool", "tool_call_id": "call_1", "content": "score: 42"}
    ttl_cc = {"type": "ephemeral", "ttl": "1h"}
    if ttl_target == "user":
        user["cache_control"] = ttl_cc
    elif ttl_target == "tool_call":
        assistant["tool_calls"][0]["cache_control"] = ttl_cc
    elif ttl_target == "tool":
        tool["cache_control"] = ttl_cc
    return [user, assistant, tool]


def _collect_cache_points(result):
    return [
        block["cachePoint"] for message in result for block in message.get("content") or [] if "cachePoint" in block
    ]


@pytest.mark.parametrize("ttl_target", ["user", "tool_call", "tool"])
@pytest.mark.asyncio
async def test_message_level_cache_control_honors_ttl_for_supported_model(
    ttl_target,
):
    """Message- and tool-call-level cache_control must carry `ttl` onto the
    emitted cachePoint for models that support extended caching, mirroring the
    system-message path. Regression test for the gap left by the system-only
    fix: the message paths called `_get_cache_point_block` without `model` (or
    hardcoded `{"type": "default"}`), silently downgrading 1h to 5m."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        BedrockConverseMessagesProcessor,
        _bedrock_converse_messages_pt,
    )

    messages = _agentic_messages_with_ttl(ttl_target)

    result = _bedrock_converse_messages_pt(
        messages=messages,
        model="global.anthropic.claude-opus-4-7",
        llm_provider="bedrock_converse",
    )
    async_result = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
        messages=messages,
        model="global.anthropic.claude-opus-4-7",
        llm_provider="bedrock_converse",
    )
    assert result == async_result

    cache_points = _collect_cache_points(result)
    assert len(cache_points) == 1
    assert cache_points[0].get("ttl") == "1h"


@pytest.mark.parametrize("ttl_target", ["user", "tool_call", "tool"])
def test_message_level_cache_control_drops_ttl_for_unsupported_model(ttl_target):
    """Models outside the extended-caching allow-list must keep emitting the
    plain `{"type": "default"}` cachePoint (Bedrock rejects `ttl` for them)."""
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )

    result = _bedrock_converse_messages_pt(
        messages=_agentic_messages_with_ttl(ttl_target),
        model="anthropic.claude-3-5-sonnet-20241022-v2:0",
        llm_provider="bedrock_converse",
    )

    cache_points = _collect_cache_points(result)
    assert len(cache_points) == 1
    assert "ttl" not in cache_points[0]


@pytest.mark.parametrize(
    "model",
    [
        "bedrock/converse/us.anthropic.claude-haiku-4-5",
        "bedrock/converse/us.anthropic.claude-sonnet-4-5",
    ],
)
def test_adaptive_thinking_translated_to_legacy_on_pre_46_converse(model):
    """Raw thinking={type: adaptive} from callers like Claude Code must be
    translated to legacy thinking={type: enabled, budget_tokens} for pre-4.6
    models on Bedrock Converse rather than forwarded as-is and rejected."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"thinking": {"type": "adaptive"}, "max_tokens": 8192},
        optional_params={},
        model=model,
        drop_params=False,
    )

    thinking = optional_params.get("thinking")
    assert thinking is not None
    assert thinking["type"] == "enabled"
    assert isinstance(thinking.get("budget_tokens"), int)
    assert thinking["budget_tokens"] < 8192


@pytest.mark.parametrize(
    "model",
    [
        "bedrock/converse/us.anthropic.claude-opus-4-7",
        "bedrock/converse/us.anthropic.claude-sonnet-4-6",
    ],
)
def test_adaptive_thinking_passes_through_on_46_plus_converse(model):
    """thinking={type: adaptive} must be forwarded unchanged for 4.6+ models
    that natively support adaptive thinking."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"thinking": {"type": "adaptive"}, "max_tokens": 8192},
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert optional_params.get("thinking") == {"type": "adaptive"}


@pytest.mark.parametrize(
    "model,budget_tokens,expected_effort",
    [
        ("anthropic.claude-opus-4-8", 4096, "high"),
        ("us.anthropic.claude-opus-4-8", 2000, "low"),
        ("global.anthropic.claude-opus-4-8", 12000, "xhigh"),
        ("us.anthropic.claude-opus-4-7", 3000, "medium"),
        ("anthropic.claude-fable-5", 4096, "high"),
    ],
)
def test_legacy_thinking_translated_to_adaptive_on_adaptive_only_converse(model, budget_tokens, expected_effort):
    """Adaptive-only models (4.7+, 5 families) reject thinking={type: enabled}
    with a 400 on Bedrock Converse, so the legacy shape from callers like Claude
    Code must be upgraded to thinking={type: adaptive} + output_config.effort
    derived from budget_tokens, matching the /v1/messages passthrough."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"thinking": {"type": "enabled", "budget_tokens": budget_tokens}, "max_tokens": 64000},
        optional_params={},
        model=model,
        drop_params=False,
    )
    request = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "hi"}],
        optional_params=optional_params,
        litellm_params={},
        headers={},
    )

    assert request["additionalModelRequestFields"]["thinking"] == {"type": "adaptive"}
    assert request["additionalModelRequestFields"]["output_config"] == {"effort": expected_effort}


def test_legacy_thinking_translation_keeps_caller_output_config_effort_converse():
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={
            "output_config": {"effort": "low"},
            "thinking": {"type": "enabled", "budget_tokens": 12000},
            "max_tokens": 64000,
        },
        optional_params={},
        model="anthropic.claude-opus-4-8",
        drop_params=False,
    )

    assert optional_params["thinking"] == {"type": "adaptive"}
    assert optional_params["output_config"] == {"effort": "low"}


@pytest.mark.parametrize(
    "model",
    [
        "us.anthropic.claude-opus-4-6",
        "anthropic.claude-3-5-sonnet-20241022-v2:0",
    ],
)
def test_legacy_thinking_forwarded_verbatim_when_model_accepts_it_converse(model):
    """The 4.6 family and pre-adaptive models accept thinking={type: enabled}
    natively, so the caller's budget_tokens cap must keep applying."""
    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={"thinking": {"type": "enabled", "budget_tokens": 4096}, "max_tokens": 8192},
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert optional_params["thinking"] == {"type": "enabled", "budget_tokens": 4096}
    assert "output_config" not in optional_params


def test_adaptive_thinking_dropped_when_max_tokens_too_small_converse():
    """When max_tokens can't fit even the minimum thinking budget, the raw
    adaptive block must be dropped entirely rather than translated, so the
    Bedrock Converse request still succeeds."""
    from litellm.constants import ANTHROPIC_MIN_THINKING_BUDGET_TOKENS

    config = AmazonConverseConfig()

    optional_params = config.map_openai_params(
        non_default_params={
            "thinking": {"type": "adaptive"},
            "max_tokens": ANTHROPIC_MIN_THINKING_BUDGET_TOKENS,
        },
        optional_params={},
        model="bedrock/converse/us.anthropic.claude-sonnet-4-5",
        drop_params=False,
    )

    assert "thinking" not in optional_params


def test_converse_usage_reports_unknown_split_for_signature_only_thinking():
    config = AmazonConverseConfig()

    usage = config.transform_usage(
        ConverseTokenUsageBlock(inputTokens=32, outputTokens=581, totalTokens=613),
        reasoning_content="",
        thinking_ran=True,
    )

    assert usage.completion_tokens == 581
    assert usage.completion_tokens_details is not None
    assert usage.completion_tokens_details.reasoning_tokens is None
    assert usage.completion_tokens_details.text_tokens is None


def test_converse_usage_estimates_split_for_visible_thinking():
    config = AmazonConverseConfig()

    usage = config.transform_usage(
        ConverseTokenUsageBlock(inputTokens=32, outputTokens=581, totalTokens=613),
        reasoning_content="Let me think about how many primes there are under thirty.",
        thinking_ran=True,
    )

    assert usage.completion_tokens_details is not None
    assert usage.completion_tokens_details.reasoning_tokens > 0
    assert (
        usage.completion_tokens_details.reasoning_tokens + usage.completion_tokens_details.text_tokens
        == usage.completion_tokens
    )


def test_converse_usage_without_thinking_reports_all_output_as_text():
    config = AmazonConverseConfig()

    usage = config.transform_usage(ConverseTokenUsageBlock(inputTokens=32, outputTokens=171, totalTokens=203))

    assert usage.completion_tokens_details is not None
    assert usage.completion_tokens_details.reasoning_tokens == 0
    assert usage.completion_tokens_details.text_tokens == 171


def test_converse_transform_response_signature_only_thinking_reports_unknown_split():
    config = AmazonConverseConfig()
    raw_response = MagicMock(status_code=200)
    raw_response.text = json.dumps(
        {
            "output": {
                "message": {
                    "role": "assistant",
                    "content": [
                        {"reasoningContent": {"reasoningText": {"text": "", "signature": "sig"}}},
                        {"text": "10"},
                    ],
                }
            },
            "stopReason": "end_turn",
            "usage": {"inputTokens": 32, "outputTokens": 581, "totalTokens": 613},
        }
    )
    raw_response.json.return_value = json.loads(raw_response.text)

    response = config._transform_response(
        model="bedrock/global.anthropic.claude-opus-4-8",
        response=raw_response,
        model_response=ModelResponse(),
        stream=False,
        logging_obj=None,
        optional_params={},
        api_key=None,
        data={},
        messages=[],
        encoding=None,
    )

    assert response.choices[0].message.reasoning_content == ""

    assert response.usage.completion_tokens_details.reasoning_tokens is None
    assert response.usage.completion_tokens_details.text_tokens is None


def test_is_converse_usage_shape_distinguishes_camel_case_from_anthropic():
    config = AmazonConverseConfig()
    assert config.is_converse_usage_shape({"inputTokens": 1, "outputTokens": 2}) is True
    assert config.is_converse_usage_shape({"outputTokens": 2}) is True
    assert config.is_converse_usage_shape({"input_tokens": 1, "output_tokens": 2}) is False
    assert config.is_converse_usage_shape({}) is False


def test_usage_from_batch_output_completes_an_incomplete_block():
    """Batch output omits totalTokens and the cache counts the live API always sends."""
    usage = AmazonConverseConfig().usage_from_batch_output({"inputTokens": 2202, "outputTokens": 540})
    assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (2202, 540, 2742)


def test_usage_from_batch_output_inflates_input_by_cache_counts():
    usage = AmazonConverseConfig().usage_from_batch_output(
        {
            "inputTokens": 100,
            "outputTokens": 20,
            "totalTokens": 120,
            "cacheReadInputTokens": 800,
            "cacheWriteInputTokens": 200,
        }
    )
    assert usage.prompt_tokens == 1100
    assert usage.prompt_tokens_details.cached_tokens == 800
    assert usage.prompt_tokens_details.cache_creation_tokens == 200


def test_streaming_usage_chunk_is_transformed():
    """The streaming decoder's usage event feeds the same public transform."""
    from litellm.llms.bedrock.chat.invoke_handler import AWSEventStreamDecoder

    decoder = AWSEventStreamDecoder(model="us.amazon.nova-lite-v1:0")
    chunk = decoder.converse_chunk_parser({"usage": {"inputTokens": 11, "outputTokens": 4, "totalTokens": 15}})
    assert chunk.usage.prompt_tokens == 11
    assert chunk.usage.completion_tokens == 4
    assert chunk.usage.total_tokens == 15


def test_update_optional_params_with_thinking_tokens_bool_thinking_does_not_crash():
    config = AmazonConverseConfig()
    optional_params = {"thinking": True}
    config.update_optional_params_with_thinking_tokens(
        non_default_params={"thinking": True}, optional_params=optional_params
    )
    assert "maxTokens" not in optional_params


@pytest.mark.parametrize(
    "model, expected_dropped",
    [
        ("anthropic.claude-fable-5", True),
        ("us.anthropic.claude-fable-5", True),
        ("us.anthropic.claude-opus-4-8", False),
    ],
)
def test_disabled_thinking_omitted_for_always_on_models_converse(local_model_cost_map, model, expected_dropped):
    """Bedrock Converse: ``thinking={"type": "disabled"}`` is omitted for always-on-thinking
    models and forwarded verbatim for models that accept it."""
    config = AmazonConverseConfig()

    result = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "hi"}],
        optional_params={"maxTokens": 64, "thinking": {"type": "disabled"}},
        litellm_params={},
        headers={},
    )

    additional = result.get("additionalModelRequestFields", {})
    if expected_dropped:
        assert "thinking" not in additional
    else:
        assert additional.get("thinking") == {"type": "disabled"}


@pytest.mark.parametrize(
    "model",
    ["anthropic.claude-fable-5-1", "us.anthropic.claude-fable-5-1"],
)
@pytest.mark.parametrize(
    "tool_choice",
    ["required", {"type": "function", "function": {"name": "get_weather"}}],
)
def test_forced_tool_choice_downgraded_to_auto_on_fable_5_1_converse(local_model_cost_map, model, tool_choice):
    config = AmazonConverseConfig()

    result = config.map_tool_choice_values(model=model, tool_choice=tool_choice, drop_params=True)

    assert result == {"auto": {}}


@pytest.mark.parametrize(
    "tool_choice",
    ["required", {"type": "function", "function": {"name": "get_weather"}}],
)
def test_forced_tool_choice_raises_clean_error_on_fable_5_1_converse(local_model_cost_map, tool_choice, monkeypatch):
    monkeypatch.setattr(litellm, "drop_params", False)
    config = AmazonConverseConfig()

    with pytest.raises(litellm.utils.UnsupportedParamsError, match="forced tool use"):
        config.map_tool_choice_values(model="anthropic.claude-fable-5-1", tool_choice=tool_choice, drop_params=False)


@pytest.mark.parametrize("tool_choice", ["auto", "none"])
def test_unforced_tool_choice_unaffected_on_fable_5_1_converse(local_model_cost_map, tool_choice):
    config = AmazonConverseConfig()

    result = config.map_tool_choice_values(
        model="anthropic.claude-fable-5-1", tool_choice=tool_choice, drop_params=True
    )

    assert result == ({"auto": {}} if tool_choice == "auto" else None)


@pytest.mark.parametrize(
    "model",
    ["anthropic.claude-fable-5-1", "us.anthropic.claude-fable-5-1"],
)
def test_response_format_avoids_native_and_forced_tool_choice_on_fable_5_1_converse(
    set_native_structured_output, model
):
    """Regression: Bedrock rejects forced tool_choice for Fable 5.1, so on a profile
    without native structured output response_format must map to a tool without a
    forced tool_choice."""
    set_native_structured_output(model, None)
    config = AmazonConverseConfig()

    result = config.map_openai_params(
        non_default_params={
            "response_format": {
                "type": "json_schema",
                "json_schema": {
                    "name": "test_schema",
                    "schema": {"type": "object", "properties": {"result": {"type": "string"}}},
                },
            }
        },
        optional_params={},
        model=model,
        drop_params=False,
    )

    assert "outputConfig" not in result
    assert "tools" in result
    assert "tool_choice" not in result
    assert result.get("json_mode") is True


def test_forced_tool_choice_forwarded_on_converse_models_that_support_it(local_model_cost_map, monkeypatch):
    monkeypatch.setattr(litellm, "drop_params", False)
    config = AmazonConverseConfig()

    result = config.map_tool_choice_values(model="anthropic.claude-fable-5", tool_choice="required", drop_params=False)

    assert result == {"any": {}}


def test_transform_response_honors_json_mode_kwarg_when_optional_params_lack_it():
    response_json = {
        "metrics": {"latencyMs": 900},
        "output": {
            "message": {
                "content": [
                    {
                        "toolUse": {
                            "input": {"city": "Paris", "population": 2100000},
                            "name": "json_tool_call",
                            "toolUseId": "tooluse_invoke_nova_json",
                        }
                    }
                ],
                "role": "assistant",
            }
        },
        "stopReason": "tool_use",
        "usage": {"inputTokens": 40, "outputTokens": 20, "totalTokens": 60},
    }
    raw_response = httpx.Response(200, json=response_json, request=httpx.Request("POST", "https://bedrock.test"))
    logging_obj = MagicMock()
    result = AmazonConverseConfig().transform_response(
        model="bedrock/invoke/us.amazon.nova-micro-v1:0",
        raw_response=raw_response,
        model_response=ModelResponse(),
        logging_obj=logging_obj,
        request_data={},
        messages=[],
        optional_params={"tools": [{"type": "function", "function": {"name": "json_tool_call", "parameters": {}}}]},
        litellm_params={},
        encoding=None,
        json_mode=True,
    )
    assert result.choices[0].message.tool_calls is None
    assert json.loads(result.choices[0].message.content) == {"city": "Paris", "population": 2100000}


FINE_GRAINED_TOOL_STREAMING_BETA: Final = "fine-grained-tool-streaming-2025-05-14"
EAGER_TOOL_SCHEMA: Final = {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}


def _eager_openai_tool(**extra: object) -> dict[str, object]:
    return {"type": "function", "function": {"name": "write_file", "parameters": EAGER_TOOL_SCHEMA}, **extra}


def _eager_openai_function_tool(**extra: object) -> dict[str, object]:
    return {"type": "function", "function": {"name": "write_file", "parameters": EAGER_TOOL_SCHEMA, **extra}}


def _eager_anthropic_tool(**extra: object) -> dict[str, object]:
    return {"name": "write_file", "input_schema": EAGER_TOOL_SCHEMA, **extra}


def _converse_request(
    model: str, tools: list[dict[str, object]], headers: dict[str, object] | None = None
) -> dict[str, object]:
    return AmazonConverseConfig()._transform_request_helper(
        model=model,
        system_content_blocks=[],
        optional_params={"tools": tools},
        messages=[{"role": "user", "content": "write a big file"}],
        headers=headers,
    )


@pytest.mark.parametrize(
    "tool",
    [
        _eager_openai_tool(eager_input_streaming=True),
        _eager_openai_function_tool(eager_input_streaming=True),
        _eager_anthropic_tool(eager_input_streaming=True),
    ],
    ids=["openai_top_level", "openai_under_function", "anthropic_shape"],
)
def test_eager_input_streaming_tool_adds_fine_grained_tool_streaming_beta(tool):
    data = _converse_request("us.anthropic.claude-sonnet-4-5-20250929-v1:0", [tool])

    assert data["additionalModelRequestFields"]["anthropic_beta"] == [FINE_GRAINED_TOOL_STREAMING_BETA]
    tool_spec = data["toolConfig"]["tools"][0]["toolSpec"]
    assert tool_spec["name"] == "write_file"
    assert "eager_input_streaming" not in tool_spec
    assert "eager_input_streaming" not in tool_spec["inputSchema"]["json"]


@pytest.mark.parametrize(
    "tool",
    [
        _eager_openai_tool(eager_input_streaming=False),
        _eager_openai_function_tool(eager_input_streaming=False),
        _eager_anthropic_tool(eager_input_streaming=False),
        _eager_openai_tool(),
    ],
    ids=["openai_false", "function_false", "anthropic_false", "absent"],
)
def test_eager_input_streaming_false_or_absent_adds_no_beta(tool):
    data = _converse_request("us.anthropic.claude-sonnet-4-5-20250929-v1:0", [tool])

    assert "anthropic_beta" not in data.get("additionalModelRequestFields", {})
    assert "eager_input_streaming" not in data["toolConfig"]["tools"][0]["toolSpec"]


def test_eager_input_streaming_beta_only_on_anthropic_models():
    data = _converse_request("amazon.nova-pro-v1:0", [_eager_openai_tool(eager_input_streaming=True)])

    assert "anthropic_beta" not in data.get("additionalModelRequestFields", {})
    assert data["toolConfig"]["tools"][0]["toolSpec"]["name"] == "write_file"


def test_eager_input_streaming_beta_not_duplicated_with_client_header():
    data = _converse_request(
        "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        [_eager_openai_tool(eager_input_streaming=True)],
        headers={"anthropic-beta": f"{FINE_GRAINED_TOOL_STREAMING_BETA},interleaved-thinking-2025-05-14"},
    )

    assert data["additionalModelRequestFields"]["anthropic_beta"] == [
        FINE_GRAINED_TOOL_STREAMING_BETA,
        "interleaved-thinking-2025-05-14",
    ]


def test_eager_input_streaming_beta_never_written_back_into_client_header_list():
    headers = {"anthropic-beta": ["interleaved-thinking-2025-05-14"]}

    data = _converse_request(
        "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        [_eager_openai_tool(eager_input_streaming=True)],
        headers=headers,
    )

    assert data["additionalModelRequestFields"]["anthropic_beta"] == [
        "interleaved-thinking-2025-05-14",
        FINE_GRAINED_TOOL_STREAMING_BETA,
    ]
    assert headers == {"anthropic-beta": ["interleaved-thinking-2025-05-14"]}


def test_eager_input_streaming_non_boolean_is_a_bad_request():
    with pytest.raises(litellm.BadRequestError, match="eager_input_streaming must be a boolean"):
        _converse_request(
            "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
            [_eager_openai_tool(eager_input_streaming="true")],
        )


def test_mid_conversation_system_after_multiple_tool_results():
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "hi"},
        {
            "role": "assistant",
            "content": "calling tools",
            "tool_calls": [
                {
                    "id": "call_a",
                    "type": "function",
                    "function": {"name": "f", "arguments": "{}"},
                }
            ],
        },
        {"role": "system", "content": "reminder"},
        {"role": "tool", "tool_call_id": "call_a", "content": "r1"},
        {"role": "tool", "tool_call_id": "call_b", "content": "r2"},
        {"role": "user", "content": "done"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages)
    assert system_blocks == []
    assert [m["role"] for m in out_messages] == [
        "user",
        "assistant",
        "tool",
        "tool",
        "user",
        "user",
    ]
    assert out_messages[2]["content"] == "r1"
    assert out_messages[3]["content"] == "r2"
    # Reminder lands after ALL tool results, not between them.
    assert out_messages[4]["content"][1]["text"] == "reminder"
    assert out_messages[5]["content"] == "done"


def test_mid_conversation_system_reorders_around_a_pydantic_assistant_tool_call():
    config = AmazonConverseConfig()
    assistant = litellm.Message(
        role="assistant",
        content="calling tools",
        tool_calls=[{"id": "call_a", "type": "function", "function": {"name": "f", "arguments": "{}"}}],
    )
    messages = [
        {"role": "user", "content": "hi"},
        assistant,
        {"role": "system", "content": "reminder"},
        {"role": "tool", "tool_call_id": "call_a", "content": "r1"},
        {"role": "user", "content": "done"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages)
    assert system_blocks == []
    assert [m["role"] for m in out_messages] == ["user", "assistant", "tool", "user", "user"]
    assert out_messages[1] is assistant
    assert out_messages[3]["content"][1]["text"] == "reminder"


def test_mid_conversation_multi_system_run_after_multiple_tool_results():
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "hi"},
        {
            "role": "assistant",
            "content": "calling tools",
            "tool_calls": [
                {
                    "id": "call_a",
                    "type": "function",
                    "function": {"name": "f", "arguments": "{}"},
                }
            ],
        },
        {"role": "system", "content": "reminder 1"},
        {"role": "system", "content": "reminder 2"},
        {"role": "tool", "tool_call_id": "call_a", "content": "r1"},
        {"role": "tool", "tool_call_id": "call_b", "content": "r2"},
        {"role": "user", "content": "done"},
    ]
    out_messages, _ = config._transform_system_message(messages)
    assert [m["role"] for m in out_messages] == [
        "user",
        "assistant",
        "tool",
        "tool",
        "user",
        "user",
        "user",
    ]
    assert out_messages[4]["content"][1]["text"] == "reminder 1"
    assert out_messages[5]["content"][1]["text"] == "reminder 2"


def test_opens_with_tool_result_rejects_non_dict():
    config = AmazonConverseConfig()
    assert config._opens_with_tool_result("not-a-dict") is False
    assert config._opens_with_tool_result(None) is False
    assert config._opens_with_tool_result([{"role": "tool"}]) is False


def test_mid_conversation_system_without_tools_stays_in_place():
    config = AmazonConverseConfig()
    messages = [
        {"role": "system", "content": "You are helpful."},
        {"role": "user", "content": "hi"},
        {"role": "assistant", "content": "hello"},
        {"role": "system", "content": "reminder"},
        {"role": "user", "content": "thanks"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages)
    assert [b["text"] for b in system_blocks if "text" in b] == ["You are helpful."]
    assert [m["role"] for m in out_messages] == ["user", "assistant", "user", "user"]
    assert out_messages[2]["content"][1]["text"] == "reminder"
    assert out_messages[3]["content"] == "thanks"


def test_mid_conversation_system_str_with_cache_control():
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "hi"},
        {
            "role": "system",
            "content": "reminder",
            "cache_control": {"type": "ephemeral"},
        },
        {"role": "user", "content": "done"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages)
    assert system_blocks == []
    assert out_messages[1]["role"] == "user"
    assert out_messages[1]["content"][1] == {
        "type": "text",
        "text": "reminder",
        "cache_control": {"type": "ephemeral"},
    }


def test_mid_conversation_system_list_content_with_cache_control():
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "hi"},
        {
            "role": "system",
            "content": [
                {"type": "text", "text": "keep this", "cache_control": {"type": "ephemeral"}},
                {"type": "text", "text": "plain"},
                {"type": "text", "text": ""},
                {"type": "image", "source": "x"},
                "raw-string",
            ],
        },
        {"role": "user", "content": "done"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages)
    assert system_blocks == []
    blocks = out_messages[1]["content"]
    assert blocks[0]["text"] == CONVERTED_SYSTEM_NOTE
    assert blocks[1] == {
        "type": "text",
        "text": "keep this",
        "cache_control": {"type": "ephemeral"},
    }
    assert blocks[2] == {"type": "text", "text": "plain"}
    assert len(blocks) == 3


@pytest.mark.parametrize(
    "empty_content",
    ["", [], None, [{"type": "image", "source": "x"}, {"type": "text", "text": ""}]],
    ids=["empty-string", "empty-list", "none", "no-text-parts"],
)
def test_mid_conversation_system_entry_without_text_is_dropped(empty_content):
    config = AmazonConverseConfig()
    messages = [
        {"role": "user", "content": "hi"},
        {"role": "system", "content": empty_content},
        {"role": "user", "content": "done"},
    ]
    out_messages, system_blocks = config._transform_system_message(messages)
    assert system_blocks == []
    assert out_messages == [{"role": "user", "content": "hi"}, {"role": "user", "content": "done"}]


def test_system_entry_without_content_key_transforms_like_an_empty_one():
    config = AmazonConverseConfig()
    leading_without_key = [{"role": "system"}, {"role": "user", "content": "hi"}]
    leading_empty = [{"role": "system", "content": ""}, {"role": "user", "content": "hi"}]
    assert config._transform_system_message(leading_without_key) == config._transform_system_message(leading_empty)
    assert config._transform_system_message(leading_without_key) == ([{"role": "user", "content": "hi"}], [])
    mid_without_key = [{"role": "user", "content": "hi"}, {"role": "system"}, {"role": "user", "content": "done"}]
    mid_empty = [
        {"role": "user", "content": "hi"},
        {"role": "system", "content": ""},
        {"role": "user", "content": "done"},
    ]
    assert config._transform_system_message(mid_without_key) == config._transform_system_message(mid_empty)


def _thinking_reply(text: str) -> dict:
    return {
        "role": "assistant",
        "content": text,
        "thinking_blocks": [{"type": "thinking", "thinking": "Working it out.", "signature": f"sig-{text}"}],
    }


def _preserved_thinking_turns(reminder_after_user: bool) -> tuple[list[dict], list[dict], list[dict]]:
    turn_n = [{"role": "system", "content": "You are terse."}, {"role": "user", "content": "First question"}]
    reminder = {"role": "system", "content": "<system-reminder>Answer with exactly one word.</system-reminder>"}
    second_question = {"role": "user", "content": "Second question"}
    second_turn = [second_question, reminder] if reminder_after_user else [reminder, second_question]
    turn_n_plus_one = [*turn_n, _thinking_reply("First answer"), *second_turn]
    turn_n_plus_two = [
        *turn_n_plus_one,
        _thinking_reply("Second answer"),
        {"role": "user", "content": "Third question"},
    ]
    return turn_n, turn_n_plus_one, turn_n_plus_two


def _replayed_prefix(request: dict, message_count: int) -> str:
    replayed = {
        "system": request.get("system"),
        "toolConfig": request.get("toolConfig"),
        "messages": request["messages"][:message_count],
    }
    return json.dumps(replayed, sort_keys=True)


def _assert_prefix_stable(requests: list[dict]) -> None:
    for earlier, later in zip(requests, requests[1:]):
        count = len(earlier["messages"])
        assert _replayed_prefix(later, count) == _replayed_prefix(earlier, count)


@pytest.mark.parametrize("reminder_after_user", [True, False])
def test_flagged_model_replays_a_byte_identical_prefix_around_a_mid_conversation_reminder(
    local_model_cost_map, reminder_after_user
):
    """Converse rejects ``role: system`` inside ``messages``, so the reminder becomes a
    user turn in place; hoisting it into ``system`` would change the prefix every
    signed thinking block in the history is bound to."""
    requests = [
        AmazonConverseConfig()._transform_request(
            model="bedrock/us.anthropic.claude-fable-5-1",
            messages=copy.deepcopy(turn),
            optional_params={},
            litellm_params={},
            headers={},
        )
        for turn in _preserved_thinking_turns(reminder_after_user)
    ]

    _assert_prefix_stable(requests)
    assert requests[1]["system"] == [{"text": "You are terse."}]
    assert [m["role"] for m in requests[1]["messages"]] == ["user", "assistant", "user"]
    assert [m["role"] for m in requests[2]["messages"]] == ["user", "assistant", "user", "assistant", "user"]


@pytest.mark.parametrize("model", ("anthropic.claude-opus-4-7", "us.anthropic.claude-opus-4-7"))
def test_converse_accepts_anthropic_default_temperature(model: str) -> None:
    result: Final = litellm.utils.get_optional_params(
        model=model,
        custom_llm_provider="bedrock",
        temperature=1,
        drop_params=False,
    )

    assert result["temperature"] == 1


def test_get_supported_openai_params_drops_sampling_params_for_gpt5_models():
    config = AmazonConverseConfig()
    for model in [
        "bedrock/converse/global.openai.gpt-5.6-luna",
        "global.openai.gpt-5.6-luna",
        "global.openai.gpt-5.6-sol",
        "us.openai.gpt-5.6-terra",
        "eu.openai.gpt-5.6-luna",
        "openai.gpt-5.6-luna",
        "bedrock/openai.gpt-5.6-luna",
    ]:
        supported = config.get_supported_openai_params(model=model)
        assert "temperature" not in supported
        assert "top_p" not in supported

    supported_oss = config.get_supported_openai_params(model="openai.gpt-oss-120b-1:0")
    assert "temperature" in supported_oss
    assert "top_p" in supported_oss


def test_map_openai_params_drops_temperature_and_top_p_when_drop_params_true():
    config = AmazonConverseConfig()
    for model in [
        "bedrock/converse/global.openai.gpt-5.6-luna",
        "openai.gpt-5.6-luna",
        "eu.openai.gpt-5.6-luna",
    ]:
        result = config.map_openai_params(
            non_default_params={"temperature": 1.0, "top_p": 0.9, "max_tokens": 50},
            optional_params={},
            model=model,
            drop_params=True,
        )
        assert "temperature" not in result
        assert "topP" not in result
        assert result.get("maxTokens") == 50


def test_map_openai_params_raises_unsupported_params_when_drop_params_false(monkeypatch):
    monkeypatch.setattr(litellm, "drop_params", False)
    config = AmazonConverseConfig()
    for model in [
        "bedrock/converse/global.openai.gpt-5.6-luna",
        "openai.gpt-5.6-luna",
    ]:
        with pytest.raises(litellm.utils.UnsupportedParamsError) as exc_info:
            config.map_openai_params(
                non_default_params={"temperature": 1.0},
                optional_params={},
                model=model,
                drop_params=False,
            )
        assert "does not support temperature=1.0" in str(exc_info.value)


def test_map_openai_params_retains_sampling_params_for_supported_models():
    config = AmazonConverseConfig()
    result = config.map_openai_params(
        non_default_params={"temperature": 0.7, "top_p": 0.8},
        optional_params={},
        model="openai.gpt-oss-120b-1:0",
        drop_params=False,
    )
    assert result.get("temperature") == 0.7
    assert result.get("topP") == 0.8


def test_supports_sampling_params_prefixed_and_anthropic_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setitem(
        litellm.model_cost,
        "global.custom-test-reasoning-model",
        {"supports_sampling_params": False},
    )
    assert AmazonConverseConfig._supports_sampling_params("custom-test-reasoning-model") is False
    assert AmazonConverseConfig._supports_sampling_params("anthropic.claude-custom-unregistered") is True


@pytest.mark.usefixtures("fake_provider_credentials")
def test_bedrock_tools_pt_valid_names():
    """
    # related issue: https://github.com/BerriAI/litellm/issues/5007
    # Bedrock tool names must satisfy regular expression pattern: [a-zA-Z][a-zA-Z0-9_]* ensure this is true

    """
    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {"type": "string"},
                    },
                    "required": ["location"],
                },
            },
        },
        {
            "type": "function",
            "function": {
                "name": "search_restaurants",
                "description": "Search for restaurants",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "cuisine": {"type": "string"},
                    },
                    "required": ["cuisine"],
                },
            },
        },
    ]

    result = _bedrock_tools_pt(tools)

    assert len(result) == 2
    assert result[0]["toolSpec"]["name"] == "get_current_weather"
    assert result[1]["toolSpec"]["name"] == "search_restaurants"


@pytest.mark.usefixtures("fake_provider_credentials")
def test_bedrock_tools_pt_invalid_names():
    """
    # related issue: https://github.com/BerriAI/litellm/issues/5007
    # Bedrock tool names must satisfy regular expression pattern: [a-zA-Z][a-zA-Z0-9_]* ensure this is true

    """

    tools = [
        {
            "type": "function",
            "function": {
                "name": "123-invalid@name",
                "description": "Invalid name test",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "test": {"type": "string"},
                    },
                    "required": ["test"],
                },
            },
        },
        {
            "type": "function",
            "function": {
                "name": "another@invalid#name",
                "description": "Another invalid name test",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "test": {"type": "string"},
                    },
                    "required": ["test"],
                },
            },
        },
    ]

    result = _bedrock_tools_pt(tools)

    print("bedrock tools after prompt formatting=", result)

    assert len(result) == 2
    assert result[0]["toolSpec"]["name"] == "a123-invalid_name"
    assert result[1]["toolSpec"]["name"] == "another_invalid_name"


def test_bedrock_converse_tools_pt_converts_custom_schema_type_to_object():
    """
    Bedrock Converse ``toolSpec.inputSchema.json`` must use standard JSON Schema
    types. Anthropic / Claude Code use ``type: \"custom\"`` in ``input_schema`` (or
    OpenAI ``parameters``); ``_bedrock_tools_pt`` must convert ``custom`` → ``object``
    at the root and inside nested ``properties``.
    """
    tools = [
        {
            "name": "Agent",
            "description": "Subagent tool",
            "type": "custom",
            "input_schema": {
                "type": "custom",
                "additionalProperties": False,
                "properties": {
                    "prompt": {"type": "string"},
                    "nested": {
                        "type": "custom",
                        "properties": {"x": {"type": "string"}},
                        "required": ["x"],
                    },
                },
                "required": ["prompt"],
            },
        },
        {
            "type": "function",
            "function": {
                "name": "other",
                "description": "x",
                "parameters": {
                    "type": "custom",
                    "properties": {
                        "a": {"type": "integer"},
                        "nested_obj": {
                            "type": "custom",
                            "properties": {"b": {"type": "string"}},
                        },
                    },
                    "required": ["a"],
                },
            },
        },
        {
            "input_schema": {
                "type": "object",
                "properties": {"q": {"type": "string"}},
            },
        },
    ]

    result = _bedrock_tools_pt(tools)

    assert result[0]["toolSpec"]["name"] == "Agent"
    j0 = result[0]["toolSpec"]["inputSchema"]["json"]
    assert j0["type"] == "object"
    assert j0["properties"]["nested"]["type"] == "object"

    j1 = result[1]["toolSpec"]["inputSchema"]["json"]
    assert j1["type"] == "object"
    assert j1["properties"]["nested_obj"]["type"] == "object"

    assert result[2]["toolSpec"]["name"] == "litellm_unnamed_tool_2"


def test_bedrock_tools_transformation_valid_params():
    from litellm.types.llms.bedrock import ToolJsonSchemaBlock

    tools = [
        {
            "type": "function",
            "function": {
                "name": "123-invalid@name",
                "description": "Invalid name test",
                "parameters": {
                    "$id": "https://some/internal/name",
                    "type": "object",
                    "$schema": "https://json-schema.org/draft/2020-12/schema",
                    "properties": {
                        "test": {"type": "string"},
                    },
                    "required": ["test"],
                },
            },
        }
    ]

    result = _bedrock_tools_pt(tools)

    print("bedrock tools after prompt formatting=", result)
    toolJsonSchema = result[0]["toolSpec"]["inputSchema"]["json"]
    assert toolJsonSchema is not None
    print("transformed toolJsonSchema keys=", toolJsonSchema.keys())
    print("allowed ToolJsonSchemaBlock keys=", ToolJsonSchemaBlock.__annotations__.keys())
    assert set(toolJsonSchema.keys()).issubset(set(ToolJsonSchemaBlock.__annotations__.keys()))

    assert isinstance(result, list)
    assert len(result) == 1
    assert "toolSpec" in result[0]
    assert result[0]["toolSpec"]["name"] == "a123-invalid_name"
    assert result[0]["toolSpec"]["description"] == "Invalid name test"
    assert "inputSchema" in result[0]["toolSpec"]
    assert "json" in result[0]["toolSpec"]["inputSchema"]
    assert result[0]["toolSpec"]["inputSchema"]["json"]["properties"]["test"]["type"] == "string"
    assert "test" in result[0]["toolSpec"]["inputSchema"]["json"]["required"]


def test_not_found_error():
    with pytest.raises(litellm.NotFoundError):
        completion(
            model="bedrock/bad_model",
            messages=[
                {
                    "role": "user",
                    "content": "What is the meaning of life",
                }
            ],
        )


@pytest.mark.parametrize(
    "model, expected_base_model",
    [
        (
            "apac.anthropic.claude-haiku-4-5-20251001-v1:0",
            "anthropic.claude-haiku-4-5-20251001-v1:0",
        ),
    ],
)
def test_bedrock_get_base_model(model, expected_base_model):
    from litellm.llms.bedrock.common_utils import BedrockModelInfo

    assert BedrockModelInfo.get_base_model(model) == expected_base_model


@pytest.mark.usefixtures("fake_provider_credentials")
def test_bedrock_converse_translation_tool_message():

    litellm.set_verbose = True

    messages = [
        {
            "role": "user",
            "content": "What's the weather like in San Francisco, Tokyo, and Paris? - give me 3 responses",
        },
        {
            "tool_call_id": "tooluse_DnqEmD5qR6y2-aJ-Xd05xw",
            "role": "tool",
            "name": "get_current_weather",
            "content": [
                {
                    "text": '{"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"}',
                    "type": "text",
                }
            ],
        },
    ]

    translated_msg = _bedrock_converse_messages_pt(messages=messages, model="", llm_provider="")

    print(translated_msg)
    assert translated_msg == [
        {
            "role": "user",
            "content": [
                {"text": "What's the weather like in San Francisco, Tokyo, and Paris? - give me 3 responses"},
                {
                    "toolResult": {
                        "content": [
                            {"text": '{"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"}'}
                        ],
                        "toolUseId": "tooluse_DnqEmD5qR6y2-aJ-Xd05xw",
                    }
                },
            ],
        }
    ]


@pytest.mark.usefixtures("fake_provider_credentials")
def test_bedrock_completion_test_2():
    litellm.set_verbose = True
    data = {
        "model": "bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0",
        "messages": [
            {
                "role": "system",
                "content": "You are Claude Dev, a highly skilled software developer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.\n\n====\n \nCAPABILITIES\n\n- You can read and analyze code in various programming languages, and can write clean, efficient, and well-documented code.\n- You can debug complex issues and providing detailed explanations, offering architectural insights and design patterns.\n- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search, inspect websites, read and write files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.\n- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/Users/hongbo-miao/Clouds/Git/hongbomiao.com') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.\n- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.\n- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.\n\t- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the write_to_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.\n- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.\n- You can use the inspect_site tool to capture a screenshot and console logs of the initial state of a website (including html files and locally running development servers) when you feel it is necessary in accomplishing the user's task. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshot to ensure correct rendering or identify errors, and review console logs for runtime issues.\n\t- For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use inspect_site to verify there are no runtime errors on page load.\n\n====\n\nRULES\n\n- Your current working directory is: /Users/hongbo-miao/Clouds/Git/hongbomiao.com\n- You cannot `cd` into a different directory to complete a task. You are stuck operating from '/Users/hongbo-miao/Clouds/Git/hongbomiao.com', so be sure to pass in the correct 'path' parameter when using tools that require a path.\n- Do not use the ~ character or $HOME to refer to the home directory.\n- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/Users/hongbo-miao/Clouds/Git/hongbomiao.com', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/Users/hongbo-miao/Clouds/Git/hongbomiao.com'). For example, if you needed to run `npm install` in a project outside of '/Users/hongbo-miao/Clouds/Git/hongbomiao.com', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`.\n- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.\n- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.\n- You must try to use multiple tools in one request when possible. For example if you were to create a website, you would use the write_to_file tool to create the necessary files with their appropriate contents all at once. Or if you wanted to analyze a project, you could use the read_file tool multiple times to look at several key files. This will help you accomplish the user's task more efficiently.\n- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.\n- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.\n- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.\n- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.\n- When executing commands, if you don't see the expected output, assume the terminal executed the command successfully and proceed with the task. The user's terminal may be unable to stream the output back properly. If you absolutely need to see the actual terminal output, use the ask_followup_question tool to request the user to copy and paste it back to you.\n- Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.\n- NEVER end completion_attempt with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user. \n- NEVER start your responses with affirmations like \"Certainly\", \"Okay\", \"Sure\", \"Great\", etc. You should NOT be conversational in your responses, but rather direct and to the point.\n- Feel free to use markdown as much as you'd like in your responses. When using code blocks, always include a language specifier.\n- When presented with images, utilize your vision capabilities to thoroughly examine them and extract meaningful information. Incorporate these insights into your thought process as you accomplish the user's task.\n- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.\n- CRITICAL: When editing files with write_to_file, ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project.\n\n====\n\nOBJECTIVE\n\nYou accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.\n\n1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.\n2. Work through these goals sequentially, utilizing available tools as necessary. Each goal should correspond to a distinct step in your problem-solving process. It is okay for certain steps to take multiple iterations, i.e. if you need to create many files, it's okay to create a few files at a time as each subsequent iteration will keep you informed on the work completed and what's remaining. \n3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool call. BUT, if one of the values for a required parameter is missing, DO NOT invoke the function (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.\n4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. `open index.html` to show the website you've built.\n5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.\n\n====\n\nSYSTEM INFORMATION\n\nOperating System: macOS\nDefault Shell: /bin/zsh\nHome Directory: /Users/hongbo-miao\nCurrent Working Directory: /Users/hongbo-miao/Clouds/Git/hongbomiao.com\n",
            },
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "<task>\nHello\n</task>"},
                    {
                        "type": "text",
                        "text": "<environment_details>\n# VSCode Visible Files\ncomputer-vision/hm-open3d/src/main.py\n\n# VSCode Open Tabs\ncomputer-vision/hm-open3d/src/main.py\n../../../.vscode/extensions/continue.continue-0.8.52-darwin-arm64/continue_tutorial.py\n\n# Current Working Directory (/Users/hongbo-miao/Clouds/Git/hongbomiao.com) Files\n.ansible-lint\n.clang-format\n.cmakelintrc\n.dockerignore\n.editorconfig\n.gitignore\n.gitmodules\n.hadolint.yaml\n.isort.cfg\n.markdownlint-cli2.jsonc\n.mergify.yml\n.npmrc\n.nvmrc\n.prettierignore\n.rubocop.yml\n.ruby-version\n.ruff.toml\n.shellcheckrc\n.solhint.json\n.solhintignore\n.sqlfluff\n.sqlfluffignore\n.stylelintignore\n.yamllint.yaml\nCODE_OF_CONDUCT.md\ncommitlint.config.js\nGemfile\nGemfile.lock\nLICENSE\nlint-staged.config.js\nMakefile\nmiss_hit.cfg\nmypy.ini\npackage-lock.json\npackage.json\npoetry.lock\npoetry.toml\nprettier.config.js\npyproject.toml\nREADME.md\nrelease.config.js\nrenovate.json\nSECURITY.md\nstylelint.config.js\naerospace/\naerospace/air-defense-system/\naerospace/hm-aerosandbox/\naerospace/hm-openaerostruct/\naerospace/px4/\naerospace/quadcopter-pd-controller/\naerospace/simulate-satellite/\naerospace/simulated-and-actual-flights/\naerospace/toroidal-propeller/\nansible/\nansible/inventory.yaml\nansible/Makefile\nansible/requirements.yml\nansible/hm_macos_group/\nansible/hm_ubuntu_group/\nansible/hm_windows_group/\napi-go/\napi-go/buf.yaml\napi-go/go.mod\napi-go/go.sum\napi-go/Makefile\napi-go/api/\napi-go/build/\napi-go/cmd/\napi-go/config/\napi-go/internal/\napi-node/\napi-node/.env.development\napi-node/.env.development.local.example\napi-node/.env.development.local.example.docker\napi-node/.env.production\napi-node/.env.production.local.example\napi-node/.env.test\napi-node/.eslintignore\napi-node/.eslintrc.js\napi-node/.npmrc\napi-node/.nvmrc\napi-node/babel.config.js\napi-node/docker-compose.cypress.yaml\napi-node/docker-compose.development.yaml\napi-node/Dockerfile\napi-node/Dockerfile.development\napi-node/jest.config.js\napi-node/Makefile\napi-node/package-lock.json\napi-node/package.json\napi-node/Procfile\napi-node/stryker.conf.js\napi-node/tsconfig.json\napi-node/bin/\napi-node/postgres/\napi-node/scripts/\napi-node/src/\napi-python/\napi-python/.flaskenv\napi-python/docker-entrypoint.sh\napi-python/Dockerfile\napi-python/Makefile\napi-python/poetry.lock\napi-python/poetry.toml\napi-python/pyproject.toml\napi-python/flaskr/\nasterios/\nasterios/led-blinker/\nauthorization/\nauthorization/hm-opal-client/\nauthorization/ory-hydra/\nautomobile/\nautomobile/build-map-by-lidar-point-cloud/\nautomobile/detect-lane-by-lidar-point-cloud/\nbin/\nbin/clean.sh\nbin/count_code_lines.sh\nbin/lint_javascript_fix.sh\nbin/lint_javascript.sh\nbin/set_up.sh\nbiology/\nbiology/compare-nucleotide-sequences/\nbusybox/\nbusybox/Makefile\ncaddy/\ncaddy/Caddyfile\ncaddy/Makefile\ncaddy/bin/\ncloud-computing/\ncloud-computing/hm-ray/\ncloud-computing/hm-skypilot/\ncloud-cost/\ncloud-cost/komiser/\ncloud-infrastructure/\ncloud-infrastructure/hm-pulumi/\ncloud-infrastructure/karpenter/\ncloud-infrastructure/terraform/\ncloud-platform/\ncloud-platform/aws/\ncloud-platform/google-cloud/\ncloud-security/\ncloud-security/hm-prowler/\ncomputational-fluid-dynamics/\ncomputational-fluid-dynamics/matlab/\ncomputational-fluid-dynamics/openfoam/\ncomputer-vision/\ncomputer-vision/hm-open3d/\ncomputer-vision/hm-pyvista/\ndata-analytics/\ndata-analytics/hm-geopandas/\ndata-distribution-service/\ndata-distribution-service/dummy_test.py\ndata-distribution-service/hm_message.idl\ndata-distribution-service/hm_message.xml\ndata-distribution-service/Makefile\ndata-distribution-service/poetry.lock\ndata-distribution-service/poetry.toml\ndata-distribution-service/publish.py\ndata-ingestion/\ndata-orchestration/\ndata-processing/\ndata-storage/\ndata-transformation/\ndata-visualization/\ndesktop-qt/\nembedded/\nethereum/\ngit/\ngolang-migrate/\nhardware-in-the-loop/\nhasura-graphql-engine/\nhigh-performance-computing/\nhm-alpine/\nhm-kafka/\nhm-locust/\nhm-rust/\nhm-traefik/\nhm-xxhash/\nkubernetes/\nmachine-learning/\nmatlab/\nmobile/\nnetwork-programmability/\noperating-system/\nparallel-computing/\nphysics/\nquantum-computing/\nrclone/\nrestic/\nreverse-engineering/\nrobotics/\nsubmodules/\ntrino/\nvagrant/\nvalgrind/\nvhdl/\nvim/\nweb/\nweb-cypress/\nwireless-network/\n\n(File list truncated. Use list_files on specific subdirectories if you need to explore further.)\n</environment_details>",
                    },
                ],
            },
            {
                "role": "assistant",
                "content": '<thinking>\nThe user has simply said "Hello" without providing any specific task or request. There is not enough information to determine which tools would be relevant or necessary to respond.\n\nThe environment details show a list of files and directories in the current working directory, but without a clear task from the user, it\'s not apparent which of these, if any, are relevant.\n\nSince no specific request has been made, there are no required parameters to analyze for any of the available tools. Asking a follow-up question seems to be the most appropriate action to get clarification on what the user needs help with.\n</thinking>',
                "tool_calls": [
                    {
                        "id": "tooluse_OPznXwZaRzCfPaQF2dxRSA",
                        "type": "function",
                        "function": {
                            "name": "ask_followup_question",
                            "arguments": '{"question":"Hello! How can I assist you today? Do you have a specific task or request you need help with? I\'d be happy to help, but I\'ll need some more details on what you\'re looking to accomplish."}',
                        },
                    }
                ],
            },
            {
                "role": "tool",
                "tool_call_id": "tooluse_OPznXwZaRzCfPaQF2dxRSA",
                "content": "<answer>\nExplain this file\n</answer>",
            },
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "<environment_details>\n# VSCode Visible Files\ncomputer-vision/hm-open3d/src/main.py\n\n# VSCode Open Tabs\ncomputer-vision/hm-open3d/src/main.py\n../../../.vscode/extensions/continue.continue-0.8.52-darwin-arm64/continue_tutorial.py\n</environment_details>",
                    }
                ],
            },
        ],
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "execute_command",
                    "description": "Execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: /Users/hongbo-miao/Clouds/Git/hongbomiao.com",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "command": {
                                "type": "string",
                                "description": "The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.",
                            }
                        },
                        "required": ["command"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "read_file",
                    "description": "Read the contents of a file at the specified path. Use this when you need to examine the contents of an existing file, for example to analyze code, review text files, or extract information from configuration files. Automatically extracts raw text from PDF and DOCX files. May not be suitable for other types of binary files, as it returns the raw content as a string.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "The path of the file to read (relative to the current working directory /Users/hongbo-miao/Clouds/Git/hongbomiao.com)",
                            }
                        },
                        "required": ["path"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "write_to_file",
                    "description": "Write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. Always provide the full intended content of the file, without any truncation. This tool will automatically create any directories needed to write the file.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "The path of the file to write to (relative to the current working directory /Users/hongbo-miao/Clouds/Git/hongbomiao.com)",
                            },
                            "content": {
                                "type": "string",
                                "description": "The full content to write to the file.",
                            },
                        },
                        "required": ["path", "content"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "search_files",
                    "description": "Perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "The path of the directory to search in (relative to the current working directory /Users/hongbo-miao/Clouds/Git/hongbomiao.com). This directory will be recursively searched.",
                            },
                            "regex": {
                                "type": "string",
                                "description": "The regular expression pattern to search for. Uses Rust regex syntax.",
                            },
                            "filePattern": {
                                "type": "string",
                                "description": "Optional glob pattern to filter files (e.g., '*.ts' for TypeScript files). If not provided, it will search all files (*).",
                            },
                        },
                        "required": ["path", "regex"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "list_files",
                    "description": "List files and directories within the specified directory. If recursive is true, it will list all files and directories recursively. If recursive is false or not provided, it will only list the top-level contents.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "The path of the directory to list contents for (relative to the current working directory /Users/hongbo-miao/Clouds/Git/hongbomiao.com)",
                            },
                            "recursive": {
                                "type": "string",
                                "enum": ["true", "false"],
                                "description": "Whether to list files recursively. Use 'true' for recursive listing, 'false' or omit for top-level only.",
                            },
                        },
                        "required": ["path"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "list_code_definition_names",
                    "description": "Lists definition names (classes, functions, methods, etc.) used in source code files at the top level of the specified directory. This tool provides insights into the codebase structure and important constructs, encapsulating high-level concepts and relationships that are crucial for understanding the overall architecture.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "The path of the directory (relative to the current working directory /Users/hongbo-miao/Clouds/Git/hongbomiao.com) to list top level source code definitions for",
                            }
                        },
                        "required": ["path"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "inspect_site",
                    "description": "Captures a screenshot and console logs of the initial state of a website. This tool navigates to the specified URL, takes a screenshot of the entire page as it appears immediately after loading, and collects any console logs or errors that occur during page load. It does not interact with the page or capture any state changes after the initial load.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "url": {
                                "type": "string",
                                "description": "The URL of the site to inspect. This should be a valid URL including the protocol (e.g. http://localhost:3000/page, file:///path/to/file.html, etc.)",
                            }
                        },
                        "required": ["url"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "ask_followup_question",
                    "description": "Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "question": {
                                "type": "string",
                                "description": "The question to ask the user. This should be a clear, specific question that addresses the information you need.",
                            }
                        },
                        "required": ["question"],
                    },
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "attempt_completion",
                    "description": "Once you've completed the task, use this tool to present the result to the user. Optionally you may provide a CLI command to showcase the result of your work, but avoid using commands like 'echo' or 'cat' that merely print text. They may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "command": {
                                "type": "string",
                                "description": "A CLI command to execute to show a live demo of the result to the user. For example, use 'open index.html' to display a created website. This command should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.",
                            },
                            "result": {
                                "type": "string",
                                "description": "The result of the task. Formulate this result in a way that is final and does not require further input from the user. Don't end your result with questions or offers for further assistance.",
                            },
                        },
                        "required": ["result"],
                    },
                },
            },
        ],
    }

    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig

    request = AmazonConverseConfig()._transform_request(
        model=data["model"],
        messages=data["messages"],
        optional_params={"tools": data["tools"]},
        litellm_params={},
    )

    """
    Iterate through the messages

    ensure 'role' is always alternating b/w 'user' and 'assistant'
    """
    _messages = request["messages"]
    for i in range(len(_messages) - 1):
        assert _messages[i]["role"] != _messages[i + 1]["role"]


def test_bedrock_completion_test_3():
    """
    Check if content in tool result is formatted correctly
    """
    from litellm.litellm_core_utils.prompt_templates.factory import (
        _bedrock_converse_messages_pt,
    )
    from litellm.types.utils import ChatCompletionMessageToolCall, Function, Message

    messages = [
        {
            "role": "user",
            "content": "What's the weather like in San Francisco, Tokyo, and Paris? - give me 3 responses",
        },
        Message(
            content="Here are the current weather conditions for San Francisco, Tokyo, and Paris:",
            role="assistant",
            tool_calls=[
                ChatCompletionMessageToolCall(
                    index=1,
                    function=Function(
                        arguments='{"location": "San Francisco, CA", "unit": "fahrenheit"}',
                        name="get_current_weather",
                    ),
                    id="tooluse_EF8PwJ1dSMSh6tLGKu9VdA",
                    type="function",
                )
            ],
            function_call=None,
        ).model_dump(),
        {
            "tool_call_id": "tooluse_EF8PwJ1dSMSh6tLGKu9VdA",
            "role": "tool",
            "name": "get_current_weather",
            "content": '{"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"}',
        },
    ]

    transformed_messages = _bedrock_converse_messages_pt(messages=messages, model="", llm_provider="")
    print(transformed_messages)

    assert transformed_messages[-1]["role"] == "user"
    assert transformed_messages[-1]["content"] == [
        {
            "toolResult": {
                "content": [{"text": '{"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"}'}],
                "toolUseId": "tooluse_EF8PwJ1dSMSh6tLGKu9VdA",
            }
        }
    ]


def test_bedrock_context_window_error():
    with pytest.raises(litellm.ContextWindowExceededError) as e:
        litellm.completion(
            model="bedrock/claude-3-5-sonnet-20240620",
            messages=[{"role": "user", "content": "Hello, world!"}],
            mock_response=Exception("prompt is too long"),
        )


def test_bedrock_base_model_helper():
    from litellm.llms.bedrock.common_utils import BedrockModelInfo

    model = "us.amazon.nova-pro-v1:0"
    base_model = BedrockModelInfo.get_base_model(model)
    assert base_model == "amazon.nova-pro-v1:0"

    assert (
        BedrockModelInfo.get_base_model("invoke/anthropic.claude-haiku-4-5-20251001-v1:0")
        == "anthropic.claude-haiku-4-5-20251001-v1:0"
    )


@pytest.mark.parametrize(
    "model,expected_route",
    [
        ("invoke/anthropic.claude-3-sonnet-20240229-v1:0", "invoke"),
        ("converse/anthropic.claude-3-sonnet-20240229-v1:0", "converse"),
        ("converse_like/anthropic.claude-3-sonnet-20240229-v1:0", "converse_like"),
        ("anthropic.claude-3-5-haiku-20241022-v1:0", "converse"),
        ("anthropic.claude-v2", "converse"),
        ("meta.llama3-70b-instruct-v1:0", "converse"),
        ("mistral.mistral-large-2407-v1:0", "converse"),
        ("us.anthropic.claude-3-sonnet-20240229-v1:0", "converse"),
        ("us.meta.llama3-70b-instruct-v1:0", "converse"),
        ("amazon.titan-text-express-v1", "invoke"),
        ("cohere.command-text-v14", "invoke"),
        ("cohere.command-r-v1:0", "invoke"),
    ],
)
def test_bedrock_route_detection(model, expected_route):
    """Test all scenarios for BedrockModelInfo.get_bedrock_route"""
    from litellm.llms.bedrock.common_utils import BedrockModelInfo

    route = BedrockModelInfo.get_bedrock_route(model)
    assert route == expected_route, f"Expected route '{expected_route}' for model '{model}', but got '{route}'"


@pytest.mark.parametrize(
    "messages, expected_cache_control",
    [
        (
            [
                {
                    "role": "system",
                    "content": [
                        {
                            "type": "text",
                            "text": "You are an AI assistant tasked with analyzing legal documents.",
                        },
                        {
                            "type": "text",
                            "text": "Here is the full text of a complex legal agreement",
                            "cache_control": {"type": "ephemeral"},
                        },
                    ],
                },
                {
                    "role": "user",
                    "content": "what are the key terms and conditions in this agreement?",
                },
            ],
            True,
        ),
        (
            [
                {
                    "role": "user",
                    "content": "what are the key terms and conditions in this agreement?",
                    "cache_control": {"type": "ephemeral"},
                },
            ],
            True,
        ),
    ],
)
def test_bedrock_prompt_caching_message(messages, expected_cache_control):
    import json

    import litellm

    transformed_messages = litellm.AmazonConverseConfig()._transform_request(
        model="bedrock/anthropic.claude-3-5-haiku-20241022-v1:0",
        messages=messages,
        optional_params={},
        litellm_params={},
    )
    if expected_cache_control:
        assert "cachePoint" in json.dumps(transformed_messages)
    else:
        assert "cachePoint" not in json.dumps(transformed_messages)


@pytest.mark.parametrize(
    "model, expected_supports_tool_call",
    [
        ("bedrock/us.amazon.nova-pro-v1:0", True),
        ("bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0", True),
        ("bedrock/mistral.mistral-7b-instruct-v0.1:0", True),
        ("bedrock/meta.llama3-1-8b-instruct:0", True),
        ("bedrock/meta.llama3-2-70b-instruct:0", True),
        ("bedrock/meta.llama3-3-70b-instruct-v1:0", True),
        ("bedrock/amazon.titan-embed-text-v1:0", False),
    ],
)
def test_bedrock_supports_tool_call(model, expected_supports_tool_call):
    supported_openai_params = litellm.AmazonConverseConfig().get_supported_openai_params(model=model)
    if expected_supports_tool_call:
        assert "tools" in supported_openai_params
    else:
        assert "tools" not in supported_openai_params


@pytest.mark.usefixtures("fake_provider_credentials")
@pytest.mark.parametrize(
    "messages, continue_message_index",
    [
        (
            [
                {"role": "user", "content": [{"type": "text", "text": ""}]},
                {"role": "assistant", "content": [{"type": "text", "text": "Hello!"}]},
            ],
            0,
        ),
        (
            [
                {"role": "user", "content": [{"type": "text", "text": "Hello!"}]},
                {"role": "assistant", "content": [{"type": "text", "text": "   "}]},
            ],
            1,
        ),
    ],
)
def test_bedrock_empty_content_handling(messages, continue_message_index):
    """
    Test that empty content in messages is handled correctly with default messages
    """
    # Test with default behavior (modify_params=True)
    litellm.modify_params = True
    formatted_messages = _bedrock_converse_messages_pt(
        messages=messages,
        model="anthropic.claude-3-sonnet-20240229-v1:0",
        llm_provider="bedrock",
    )
    print(formatted_messages)
    # Verify assistant message with default text was inserted
    assert formatted_messages[0]["role"] == "user"
    assert formatted_messages[1]["role"] == "assistant"
    assert formatted_messages[continue_message_index]["content"][0]["text"] == "Please continue."


def test_bedrock_custom_continue_message():
    """
    Test that custom continue messages are used when provided
    """
    messages = [
        {"role": "user", "content": [{"type": "text", "text": "Hello!"}]},
        {"role": "assistant", "content": [{"type": "text", "text": "   "}]},
    ]

    custom_continue = {
        "role": "assistant",
        "content": [{"text": "Custom continue message", "type": "text"}],
    }

    formatted_messages = _bedrock_converse_messages_pt(
        messages=messages,
        model="anthropic.claude-3-sonnet-20240229-v1:0",
        llm_provider="bedrock",
        assistant_continue_message=custom_continue,
    )

    assert formatted_messages[1]["role"] == "assistant"
    assert formatted_messages[1]["content"][0]["text"] == "Custom continue message"


@pytest.mark.usefixtures("fake_provider_credentials")
def test_bedrock_no_default_message():
    """
    Test that empty content is replaced with placeholder when modify_params=False.
    AWS Bedrock doesn't allow empty or whitespace-only text content.
    """
    messages = [
        {"role": "user", "content": "Hello!"},
        {"role": "assistant", "content": ""},
        {"role": "user", "content": "Hi again"},
        {"role": "assistant", "content": "Valid response"},
    ]

    litellm.modify_params = False
    formatted_messages = _bedrock_converse_messages_pt(
        messages=messages,
        model="anthropic.claude-3-sonnet-20240229-v1:0",
        llm_provider="bedrock",
    )

    # Verify empty message is replaced with placeholder and valid message remains
    assistant_messages = [msg for msg in formatted_messages if msg["role"] == "assistant"]
    assert len(assistant_messages) == 1
    assert assistant_messages[0]["content"][0]["text"] == "Valid response"


def test_bedrock_process_empty_text_blocks():
    from litellm.litellm_core_utils.prompt_templates.factory import (
        process_empty_text_blocks,
    )

    message = {
        "message": {"role": "assistant", "content": [{"type": "text", "text": "   "}]},
        "assistant_continue_message": None,
    }
    modified_message = process_empty_text_blocks(**message)
    assert modified_message["content"][0]["text"] == "Please continue."


def test_bedrock_image_embedding_transformation():
    from litellm.llms.bedrock.embed.amazon_titan_multimodal_transformation import (
        AmazonTitanMultimodalEmbeddingG1Config,
    )

    args = {
        "input": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkBAMAAACCzIhnAAAAG1BMVEURAAD///+ln5/h39/Dv79qX18uHx+If39MPz9oMSdmAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABB0lEQVRYhe2SzWrEIBCAh2A0jxEs4j6GLDS9hqWmV5Flt0cJS+lRwv742DXpEjY1kOZW6HwHFZnPmVEBEARBEARB/jd0KYA/bcUYbPrRLh6amXHJ/K+ypMoyUaGthILzw0l+xI0jsO7ZcmCcm4ILd+QuVYgpHOmDmz6jBeJImdcUCmeBqQpuqRIbVmQsLCrAalrGpfoEqEogqbLTWuXCPCo+Ki1XGqgQ+jVVuhB8bOaHkvmYuzm/b0KYLWwoK58oFqi6XfxQ4Uz7d6WeKpna6ytUs5e8betMcqAv5YPC5EZB2Lm9FIn0/VP6R58+/GEY1X1egVoZ/3bt/EqF6malgSAIgiDIH+QL41409QMY0LMAAAAASUVORK5CYII=",
        "inference_params": {},
    }

    transformed_request = AmazonTitanMultimodalEmbeddingG1Config().transform_request(**args)
    assert (
        transformed_request["inputImage"]
        == "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkBAMAAACCzIhnAAAAG1BMVEURAAD///+ln5/h39/Dv79qX18uHx+If39MPz9oMSdmAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABB0lEQVRYhe2SzWrEIBCAh2A0jxEs4j6GLDS9hqWmV5Flt0cJS+lRwv742DXpEjY1kOZW6HwHFZnPmVEBEARBEARB/jd0KYA/bcUYbPrRLh6amXHJ/K+ypMoyUaGthILzw0l+xI0jsO7ZcmCcm4ILd+QuVYgpHOmDmz6jBeJImdcUCmeBqQpuqRIbVmQsLCrAalrGpfoEqEogqbLTWuXCPCo+Ki1XGqgQ+jVVuhB8bOaHkvmYuzm/b0KYLWwoK58oFqi6XfxQ4Uz7d6WeKpna6ytUs5e8betMcqAv5YPC5EZB2Lm9FIn0/VP6R58+/GEY1X1egVoZ/3bt/EqF6malgSAIgiDIH+QL41409QMY0LMAAAAASUVORK5CYII="
    )


@pytest.mark.parametrize(
    "exception_type, expected_status_code",
    [
        ("internalServerException", 500),
        ("serviceUnavailableException", 503),
        ("modelTimeoutException", 408),
        ("modelStreamErrorException", 424),
        ("validationException", 400),
    ],
)
def test_bedrock_error_handling_streaming(exception_type, expected_status_code):
    """Bedrock event-stream error events arrive with botocore's hard-coded
    status_code=400; the decoder must surface the modeled HTTP status instead
    (e.g. internalServerException -> 500). For 5xx this is what makes the error
    retryable downstream; for all types it replaces the misleading 400 with the
    true code. Regression for #24608."""
    from unittest.mock import Mock

    from litellm.llms.bedrock.chat.invoke_handler import (
        AWSEventStreamDecoder,
        BedrockError,
    )

    event = Mock()
    event.to_response_dict = Mock(
        return_value={
            "status_code": 400,
            "headers": {
                ":exception-type": exception_type,
                ":content-type": "application/json",
                ":message-type": "exception",
            },
            "body": b'{"message":"Bedrock is unable to process your request."}',
        }
    )

    decoder = AWSEventStreamDecoder(model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0")
    with pytest.raises(BedrockError) as e:
        decoder._parse_message_from_event(event)
    assert "Bedrock is unable to process your request." in e.value.message
    assert e.value.status_code == expected_status_code


@pytest.mark.parametrize(
    "model, expected_output",
    [
        ("bedrock/anthropic.claude-3-sonnet-20240229-v1:0", {"top_k": 3}),
        ("bedrock/converse/us.amazon.nova-pro-v1:0", {"inferenceConfig": {"topK": 3}}),
        ("bedrock/meta.llama3-70b-instruct-v1:0", {}),
    ],
)
def test_handle_top_k_value_helper(model, expected_output):
    assert litellm.AmazonConverseConfig()._handle_top_k_value(model, {"topK": 3}) == expected_output
    assert litellm.AmazonConverseConfig()._handle_top_k_value(model, {"top_k": 3}) == expected_output


@pytest.mark.usefixtures("fake_provider_credentials")
@pytest.mark.parametrize(
    "model, expected_params",
    [
        ("bedrock/anthropic.claude-3-sonnet-20240229-v1:0", {"top_k": 2}),
        ("bedrock/converse/us.amazon.nova-pro-v1:0", {"inferenceConfig": {"topK": 2}}),
        ("bedrock/meta.llama3-70b-instruct-v1:0", {}),
        ("bedrock/mistral.mistral-7b-instruct-v0:2", {}),
    ],
)
def test_bedrock_top_k_param(model, expected_params):
    import json

    client = HTTPHandler()

    with patch.object(client, "post") as mock_post:
        mock_response = Mock()

        if "mistral" in model:
            mock_response.text = json.dumps({"outputs": [{"text": "Here's a joke...", "stop_reason": "stop"}]})
        else:
            mock_response.text = json.dumps(
                {
                    "output": {
                        "message": {
                            "role": "assistant",
                            "content": [{"text": "Here's a joke..."}],
                        }
                    },
                    "usage": {"inputTokens": 12, "outputTokens": 6, "totalTokens": 18},
                    "stopReason": "stop",
                }
            )

        mock_response.status_code = 200
        # Add required response attributes
        mock_response.headers = {"Content-Type": "application/json"}
        mock_response.json = lambda: json.loads(mock_response.text)
        mock_post.return_value = mock_response

        litellm.completion(
            model=model,
            messages=[{"role": "user", "content": "Hello, world!"}],
            top_k=2,
            client=client,
        )
        data = json.loads(mock_post.call_args.kwargs["data"])
        if "mistral" in model:
            assert data["top_k"] == 2
        elif expected_params == {}:
            # Models that don't support top_k produce no additionalModelRequestFields;
            # the empty block is now omitted entirely rather than sent as `{}`.
            assert "additionalModelRequestFields" not in data
        else:
            assert data["additionalModelRequestFields"] == expected_params


def test_bedrock_invoke_provider():
    assert (
        litellm.AmazonInvokeConfig().get_bedrock_invoke_provider(
            "bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0"
        )
        == "anthropic"
    )
    assert (
        litellm.AmazonInvokeConfig().get_bedrock_invoke_provider("bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0")
        == "anthropic"
    )
    assert (
        litellm.AmazonInvokeConfig().get_bedrock_invoke_provider(
            "bedrock/llama/arn:aws:bedrock:us-east-1:086734376398:imported-model/r4c4kewx2s0n"
        )
        == "llama"
    )
    assert litellm.AmazonInvokeConfig().get_bedrock_invoke_provider("us.amazon.nova-pro-v1:0") == "nova"
    assert litellm.AmazonInvokeConfig().get_bedrock_invoke_provider("amazon.nova-pro-v1:0") == "nova"
    assert litellm.AmazonInvokeConfig().get_bedrock_invoke_provider("amazon.nova-lite-v1:0") == "nova"
    assert litellm.AmazonInvokeConfig().get_bedrock_invoke_provider("amazon.nova-micro-v1:0") == "nova"
    assert litellm.AmazonInvokeConfig().get_bedrock_invoke_provider("amazon.nova-premier-v1:0") == "nova"
    assert litellm.AmazonInvokeConfig().get_bedrock_invoke_provider("amazon.nova-2-lite-v1:0") == "nova"


@pytest.mark.usefixtures("fake_provider_credentials")
def test_bedrock_meta_llama_function_calling():
    """
    Tests that:
    - meta llama models support function calling
    """
    from litellm.types.utils import CallTypes
    from litellm.utils import return_raw_request

    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {
                            "type": "string",
                            "enum": ["celsius", "fahrenheit"],
                        },
                    },
                    "required": ["location"],
                },
            },
        }
    ]
    messages = [
        {
            "role": "user",
            "content": "What's the weather like in Boston today in fahrenheit?",
        }
    ]
    request_args = {
        "messages": messages,
        "tools": tools,
        "model": "bedrock/us.meta.llama4-scout-17b-instruct-v1:0",
    }

    response = return_raw_request(
        endpoint=CallTypes.completion,
        kwargs=request_args,
    )

    print(response)
    assert response["raw_request_body"]["toolConfig"]["tools"][0]["toolSpec"]["name"] == "get_current_weather"


def test_bedrock_nova_provider_detection():
    """
    Test that Nova models are correctly detected even when prefixed with "amazon."
    Regression test for issue #17910 where models like "amazon.nova-pro-v1:0"
    were incorrectly identified as "amazon" (Titan) instead of "nova".
    """

    nova_test_cases = [
        ("us.amazon.nova-pro-v1:0", "nova"),
        ("us.amazon.nova-lite-v1:0", "nova"),
        ("us.amazon.nova-micro-v1:0", "nova"),
        ("amazon.nova-pro-v1:0", "nova"),
        ("amazon.nova-lite-v1:0", "nova"),
        ("amazon.nova-micro-v1:0", "nova"),
        ("amazon.nova-premier-v1:0", "nova"),
        ("amazon.nova-2-lite-v1:0", "nova"),
        ("bedrock/amazon.nova-pro-v1:0", "nova"),
        ("bedrock/invoke/amazon.nova-pro-v1:0", "nova"),
        ("amazon.Nova-pro-v1:0", "nova"),
        ("amazon.NOVA-pro-v1:0", "nova"),
    ]

    for model, expected in nova_test_cases:
        provider = BaseAWSLLM.get_bedrock_invoke_provider(model)
        assert provider == expected, f"Failed for model: {model}, expected: {expected}, got: {provider}"

    titan_test_cases = [
        ("amazon.titan-text-express-v1", "amazon"),
        ("us.amazon.titan-text-lite-v1", "amazon"),
    ]

    for model, expected in titan_test_cases:
        provider = BaseAWSLLM.get_bedrock_invoke_provider(model)
        assert provider == expected, f"Failed for model: {model}, expected: {expected}, got: {provider}"


def test_bedrock_openai_provider_detection():
    """
    Test that the OpenAI provider is correctly detected from model strings.
    """

    test_cases = [
        "openai/arn:aws:bedrock:us-east-1:123456789012:imported-model/abc123",
        "bedrock/openai/arn:aws:bedrock:us-east-1:123456789012:imported-model/xyz789",
    ]

    for model in test_cases:
        provider = BaseAWSLLM.get_bedrock_invoke_provider(model)
        assert provider == "openai", f"Failed for model: {model}, got provider: {provider}"
        print(f"✓ Provider detection works for: {model}")


def test_bedrock_openai_model_id_extraction():
    """
    Test that the model ID (ARN) is correctly extracted and encoded for OpenAI models.
    """

    model = "openai/arn:aws:bedrock:us-east-1:123456789012:imported-model/test-model-123"
    provider = BaseAWSLLM.get_bedrock_invoke_provider(model)

    model_id = BaseAWSLLM.get_bedrock_model_id(model=model, provider=provider, optional_params={})

    assert "arn" in model_id
    assert "imported-model" in model_id
    print(f"✓ Model ID extracted and encoded: {model_id}")


def test_bedrock_openai_response_parsing():
    from litellm.llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import (
        AmazonBedrockOpenAIConfig,
    )

    openai_response = {
        "choices": [
            {
                "message": {
                    "content": "The capital of France is Paris.",
                    "role": "assistant",
                },
                "finish_reason": "stop",
                "index": 0,
            }
        ],
        "usage": {"prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18},
    }

    mock_response = Mock()
    mock_response.json.return_value = openai_response
    mock_response.text = json.dumps(openai_response)
    mock_response.status_code = 200
    mock_response.headers = {}

    result = AmazonBedrockOpenAIConfig().transform_response(
        model="openai/arn:aws:bedrock:us-east-1:123:imported-model/test",
        raw_response=mock_response,
        model_response=ModelResponse(),
        logging_obj=Mock(),
        request_data={},
        messages=[{"role": "user", "content": "What is the capital of France?"}],
        optional_params={},
        litellm_params={},
        encoding=None,
    )

    assert result.choices[0].message.content == "The capital of France is Paris."
    assert result.choices[0].finish_reason == "stop"
    assert result.usage.prompt_tokens == 10
    assert result.usage.completion_tokens == 8
    assert result.usage.total_tokens == 18


def test_bedrock_openai_request_transformation():
    """
    Test that the request is correctly transformed for OpenAI models.
    """
    from litellm.llms.bedrock.chat.invoke_transformations.base_invoke_transformation import (
        AmazonInvokeConfig,
    )

    config = AmazonInvokeConfig()

    model = "openai/arn:aws:bedrock:us-east-1:123:imported-model/test"
    messages = [
        {"role": "system", "content": "You are helpful"},
        {"role": "user", "content": "Hello"},
    ]

    optional_params = {
        "max_tokens": 100,
        "temperature": 0.7,
        "top_p": 0.9,
        "stream": False,
    }

    litellm_params = {}
    headers = {}

    with patch.object(config, "get_bedrock_invoke_provider", return_value="openai"):
        result = config.transform_request(
            model=model,
            messages=messages,
            optional_params=optional_params.copy(),
            litellm_params=litellm_params,
            headers=headers,
        )

    assert "messages" in result
    assert len(result["messages"]) == 2
    assert result["messages"][0]["role"] == "system"
    assert result["messages"][1]["role"] == "user"

    assert "max_tokens" in result
    assert "temperature" in result

    print("✓ Request transformation works correctly")


def test_bedrock_openai_parameter_filtering():
    """
    Test that only supported OpenAI parameters are included in the request.
    """
    from litellm.llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import (
        AmazonBedrockOpenAIConfig,
    )

    config = AmazonBedrockOpenAIConfig()
    model = "test-model"

    supported_params = config.get_supported_openai_params(model=model)

    assert "max_tokens" in supported_params
    assert "temperature" in supported_params
    assert "top_p" in supported_params
    assert "stream" in supported_params
    assert "stop" in supported_params

    print(f"✓ Parameter filtering supports: {len(supported_params)} parameters")
    print(f"  Supported params: {supported_params}")


def test_bedrock_openai_route_detection():
    """
    Test that the OpenAI route is correctly detected.
    """
    from litellm.llms.bedrock.common_utils import BedrockModelInfo

    test_cases = [
        ("openai/arn:aws:bedrock:us-east-1:123:imported-model/test", "openai"),
        ("bedrock/openai/arn:aws:bedrock:us-east-1:123:imported-model/test", "openai"),
    ]

    for model, expected_route in test_cases:
        route = BedrockModelInfo.get_bedrock_route(model)
        assert route == expected_route, f"Failed for model: {model}, got route: {route}"
        print(f"✓ Route detection works for: {model} -> {route}")


def test_bedrock_openai_explicit_route_check():
    """
    Test the explicit OpenAI route checker helper method.
    """
    from litellm.llms.bedrock.common_utils import BedrockModelInfo

    assert BedrockModelInfo._explicit_openai_route("openai/arn:aws:bedrock:us-east-1:123:imported-model/test") is True
    assert (
        BedrockModelInfo._explicit_openai_route("bedrock/openai/arn:aws:bedrock:us-east-1:123:imported-model/test")
        is True
    )

    assert BedrockModelInfo._explicit_openai_route("anthropic.claude-3-sonnet") is False
    assert BedrockModelInfo._explicit_openai_route("arn:aws:bedrock:us-east-1:123:imported-model/test") is False

    print("✓ Explicit route check works correctly")


def test_bedrock_openai_config_initialization():
    """
    Test that AmazonBedrockOpenAIConfig can be properly initialized.
    """
    from litellm.llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import (
        AmazonBedrockOpenAIConfig,
    )

    config = AmazonBedrockOpenAIConfig()

    assert hasattr(config, "get_supported_openai_params")
    assert hasattr(config, "transform_request")
    assert hasattr(config, "transform_response")
    assert hasattr(config, "map_openai_params")

    print("✓ AmazonBedrockOpenAIConfig initializes correctly")


def test_bedrock_openai_error_handling():
    from litellm.llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import (
        AmazonBedrockOpenAIConfig,
    )
    from litellm.llms.bedrock.common_utils import BedrockError

    error = AmazonBedrockOpenAIConfig().get_error_class(
        error_message="ValidationException: bad request",
        status_code=422,
        headers={},
    )

    assert isinstance(error, BedrockError)
    assert error.status_code == 422
    assert "ValidationException: bad request" in str(error)


def test_bedrock_nova_web_search_options_ignored_for_non_nova():
    """
    Test that web_search_options is ignored for non-Nova Bedrock models.

    Nova grounding is only supported on Nova models. For other models,
    the parameter should be silently ignored.
    """
    from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig

    config = AmazonConverseConfig()

    result = config._map_web_search_options({}, "anthropic.claude-3-sonnet-v1")
    assert result is None

    result = config._map_web_search_options({}, "amazon.titan-text-express-v1")
    assert result is None

    result = config._map_web_search_options({}, "amazon.nova-pro-v1:0")
    assert result is not None
    system_tool = result.get("systemTool")
    assert system_tool is not None
    assert system_tool["name"] == "nova_grounding"

    result2 = config._map_web_search_options({}, "us.amazon.nova-premier-v1:0")
    assert result2 is not None
    system_tool2 = result2.get("systemTool")
    assert system_tool2 is not None
    assert system_tool2["name"] == "nova_grounding"


@pytest.mark.parametrize(
    "model",
    [
        "bedrock/converse/us.amazon.nova-pro-v1:0",
        "bedrock/us.amazon.nova-pro-v1:0",
    ],
)
@pytest.mark.respx(assert_all_called=True)
def test_bedrock_nova_model_selects_converse_route(model: str, respx_mock: respx.Router) -> None:
    route: Final = respx_mock.post(
        re.compile(r"https://bedrock-runtime\.us-west-2\.amazonaws\.com/model/.+/converse")
    ).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "converse"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )
    response: Final = litellm.completion(
        model=model,
        messages=[{"role": "user", "content": "select Converse"}],
        aws_access_key_id="AKIANOVAROUTEKEY",
        aws_secret_access_key="nova-route-secret",
        aws_region_name="us-west-2",
        client=HTTPHandler(),
    )

    assert response.choices[0].message.content == "converse"
    assert route.calls[0].request.url.raw_path == b"/model/us.amazon.nova-pro-v1%3A0/converse"


def test_cross_region_bedrock_model_cost_falls_back_to_base_model(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
    model_cost_map: Final = litellm.get_model_cost_map(url="")
    litellm.get_model_info.cache_clear()
    region_model: Final = "us.anthropic.claude-haiku-4-5-20251001-v1:0"
    monkeypatch.setattr(
        litellm,
        "model_cost",
        {model_name: value for model_name, value in model_cost_map.items() if model_name != region_model},
    )
    model: Final = f"bedrock/{region_model}"
    info: Final = litellm.get_model_info(model=model)
    cost: Final = litellm.completion_cost(model=model, prompt="synthetic prompt", completion="synthetic completion")
    base_cost: Final = litellm.completion_cost(
        model="bedrock/anthropic.claude-haiku-4-5-20251001-v1:0",
        prompt="synthetic prompt",
        completion="synthetic completion",
    )
    base_info: Final = litellm.get_model_info(model="bedrock/anthropic.claude-haiku-4-5-20251001-v1:0")

    assert info["input_cost_per_token"] == base_info["input_cost_per_token"]
    assert cost == pytest.approx(base_cost)


def test_bedrock_nova_grounding_and_function_tool_share_request() -> None:
    config: Final = AmazonConverseConfig()
    model: Final = "amazon.nova-pro-v1:0"
    tools: Final = [_ARTIFACT_DATA_OPENAI_TOOL]
    mapped_params: Final = config.map_openai_params(
        non_default_params={"tools": tools, "web_search_options": {}},
        optional_params={},
        model=model,
        drop_params=False,
    )
    request: Final = config._transform_request(
        model=model,
        messages=[{"role": "user", "content": "Search and use the artifact tool"}],
        optional_params=mapped_params,
        litellm_params={},
        headers={},
    )

    assert request["toolConfig"]["tools"] == [
        {
            "toolSpec": {
                "name": "ArtifactData",
                "description": "Read a shared database",
                "inputSchema": {"json": _ARTIFACT_DATA_INPUT_SCHEMA},
            }
        },
        {"systemTool": {"name": "nova_grounding"}},
    ]


@pytest.mark.asyncio
@pytest.mark.parametrize("async_mode", (False, True))
async def test_bedrock_nova_grounding_request_transformation(async_mode: bool) -> None:
    requests: Final[list[httpx.Request]] = []

    def respond(request: httpx.Request) -> httpx.Response:
        requests.append(request)
        return httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "Found a result"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 2, "outputTokens": 3, "totalTokens": 5},
            },
            request=request,
        )

    request_args: Final = {
        "model": "bedrock/amazon.nova-pro-v1:0",
        "messages": [{"role": "user", "content": "Find current launch details"}],
        "web_search_options": {},
        "aws_access_key_id": "AKIAEXAMPLEKEY",
        "aws_secret_access_key": "example-secret-key",
        "aws_region_name": "us-west-2",
    }
    transport: Final = httpx.MockTransport(respond)
    response: Final = (
        await litellm.acompletion(**request_args, client=AsyncHTTPHandler(transport=transport))
        if async_mode
        else litellm.completion(**request_args, client=HTTPHandler(client=httpx.Client(transport=transport)))
    )
    request: Final = requests[0]
    request_body: Final = json.loads(request.content)

    assert request.url.path.endswith("/converse")
    assert response.choices[0].message.content == "Found a result"
    assert request_body["toolConfig"]["tools"] == [{"systemTool": {"name": "nova_grounding"}}]
    assert request_body["messages"][0]["content"] == [{"text": "Find current launch details"}]


@pytest.mark.respx(assert_all_called=True)
def test_bedrock_converse_drops_empty_stop_sequence(respx_mock: respx.Router) -> None:
    route: Final = respx_mock.post(re.compile(r"https://[^/]+/.*/converse(?:\?.*)?")).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
            },
        )
    )
    response: Final = litellm.completion(
        model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        messages=[{"role": "user", "content": "Continue"}],
        stop="",
        max_tokens=10,
        aws_access_key_id="AKIAEXAMPLEKEY",
        aws_secret_access_key="example-secret-key",
        aws_region_name="us-west-2",
        client=HTTPHandler(),
    )
    request_body: Final = json.loads(route.calls[0].request.content)

    assert response.choices[0].message.content == "ok"
    assert request_body["inferenceConfig"] == {"maxTokens": 10}


@pytest.mark.respx(assert_all_called=True)
def test_bedrock_image_url_sync_client_fetches_and_inlines_image(respx_mock: respx.Router) -> None:
    image_bytes: Final = b"synthetic-image-content"
    respx_mock.get("https://1.1.1.1/image.png").mock(
        return_value=httpx.Response(200, content=image_bytes, headers={"content-type": "image/png"})
    )
    bedrock_route: Final = respx_mock.post(re.compile(r"https://[^/]+/.*/converse(?:\?.*)?")).mock(
        return_value=httpx.Response(
            200,
            json={
                "output": {"message": {"role": "assistant", "content": [{"text": "a synthetic image"}]}},
                "stopReason": "end_turn",
                "usage": {"inputTokens": 1, "outputTokens": 2, "totalTokens": 3},
            },
        )
    )

    response: Final = litellm.completion(
        model="bedrock/amazon.nova-pro-v1:0",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this image"},
                    {"type": "image_url", "image_url": {"url": "https://1.1.1.1/image.png"}},
                ],
            }
        ],
        aws_access_key_id="AKIAIMAGEKEY",
        aws_secret_access_key="image-secret",
        aws_region_name="us-west-2",
        client=HTTPHandler(),
    )
    request_body: Final = json.loads(bedrock_route.calls[0].request.content)

    assert response.choices[0].message.content == "a synthetic image"
    assert request_body["messages"][0]["content"][1]["image"]["format"] == "png"
    assert (
        request_body["messages"][0]["content"][1]["image"]["source"]["bytes"] == base64.b64encode(image_bytes).decode()
    )


async def _transform_converse_request(sync_mode: bool, messages: list[AllMessageValues]) -> RequestObject:
    config: Final = AmazonConverseConfig()
    if sync_mode:
        return config._transform_request(
            model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
            messages=messages,
            optional_params={},
            litellm_params={},
            headers={},
        )
    return await config._async_transform_request(
        model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        messages=messages,
        optional_params={},
        litellm_params={},
        headers={},
    )


@pytest.mark.parametrize("sync_mode", [True, False])
@pytest.mark.asyncio
async def test_bedrock_thinking_in_assistant_message_keeps_reasoning_block(sync_mode: bool) -> None:
    request: Final = await _transform_converse_request(
        sync_mode,
        [
            {
                "role": "assistant",
                "content": [
                    {"type": "thinking", "thinking": "Plan the synthetic task", "signature": "synthetic-signature"},
                    {"type": "text", "text": "The answer is ready"},
                ],
            },
            {"role": "user", "content": "Continue"},
        ],
    )

    assert request["messages"][0]["role"] == "assistant"
    assert request["messages"][0]["content"][0]["reasoningContent"]["reasoningText"] == {
        "text": "Plan the synthetic task",
        "signature": "synthetic-signature",
    }
    assert request["messages"][0]["content"][1] == {"text": "The answer is ready"}


@pytest.mark.parametrize("sync_mode", [True, False])
@pytest.mark.asyncio
async def test_bedrock_user_file_element_becomes_document_block(sync_mode: bool) -> None:
    pdf_bytes: Final = b"%PDF-1.4 synthetic quarterly report"
    request: Final = await _transform_converse_request(
        sync_mode,
        [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Summarize this report"},
                    {
                        "type": "file",
                        "file": {
                            "filename": "report.pdf",
                            "file_data": f"data:application/pdf;base64,{base64.b64encode(pdf_bytes).decode()}",
                        },
                    },
                ],
            }
        ],
    )

    content: Final = request["messages"][0]["content"]
    assert [next(iter(block)) for block in content] == ["text", "document"]
    assert content[0] == {"text": "Summarize this report"}
    assert content[1]["document"]["source"] == {"bytes": base64.b64encode(pdf_bytes).decode()}
    assert content[1]["document"]["format"] == "pdf"


def _openai_tool_search_with_deferred_functions() -> list[dict[str, object]]:
    return [
        {"type": "tool_search", "execution": "server"},
        {
            "type": "function",
            "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {}}},
            "defer_loading": True,
        },
        {
            "type": "function",
            "function": {
                "name": "get_stock_price",
                "parameters": {"type": "object", "properties": {}},
                "defer_loading": True,
            },
        },
    ]


@pytest.mark.parametrize(
    ("model", "names_invoke_route"),
    [
        pytest.param("us.anthropic.claude-sonnet-5-5", True, id="claude-that-runs-tool-search-on-invoke"),
        pytest.param("anthropic.claude-3-haiku-20240307-v1:0", False, id="claude-without-tool-search"),
        pytest.param("us.amazon.nova-pro-v1:0", False, id="nova"),
    ],
)
def test_map_openai_params_answers_400_for_the_openai_tool_search_tool_without_drop_params(
    monkeypatch, model, names_invoke_route
):
    monkeypatch.setattr(litellm, "drop_params", False)
    with pytest.raises(litellm.utils.UnsupportedParamsError) as raised:
        AmazonConverseConfig().map_openai_params(
            non_default_params={"tools": _openai_tool_search_with_deferred_functions()},
            optional_params={},
            model=model,
            drop_params=False,
        )
    assert raised.value.status_code == 400
    assert "tool_search" in str(raised.value)
    assert "drop_params: true" in str(raised.value)
    assert ("bedrock/invoke/" in str(raised.value)) is names_invoke_route


def test_map_openai_params_drops_the_openai_tool_search_tool_and_every_deferral_under_drop_params(monkeypatch):
    monkeypatch.setattr(litellm, "drop_params", False)
    mapped: Final = AmazonConverseConfig().map_openai_params(
        non_default_params={"tools": _openai_tool_search_with_deferred_functions()},
        optional_params={},
        model="us.anthropic.claude-sonnet-5-5",
        drop_params=True,
    )
    assert [tool["function"]["name"] for tool in mapped["tools"]] == ["get_weather", "get_stock_price"]
    assert all("defer_loading" not in tool and "defer_loading" not in tool["function"] for tool in mapped["tools"])


def _converse_params(
    model: str, model_info: Mapping[str, object] | None, non_default_params: Mapping[str, object]
) -> Mapping[str, object]:
    return AmazonConverseConfig().map_openai_params(
        non_default_params=dict(non_default_params),
        optional_params={},
        model=model,
        drop_params=False,
        model_info=model_info,
    )


_OUTPUT_CONFIG_FORMAT: Final = {
    "output_config": {"format": {"type": "json_schema", "schema": CAPITAL_RESPONSE_FORMAT["json_schema"]["schema"]}}
}


@pytest.mark.parametrize(
    "request_params",
    [
        {"response_format": CAPITAL_RESPONSE_FORMAT, "thinking": ADAPTIVE_THINKING},
        {"response_format": CAPITAL_RESPONSE_FORMAT, "reasoning_effort": "low"},
        {"response_format": CAPITAL_RESPONSE_FORMAT, "thinking": {"type": "enabled", "budget_tokens": 2048}},
        _OUTPUT_CONFIG_FORMAT,
    ],
    ids=["adaptive", "reasoning_effort", "budget", "output_config_format"],
)
@pytest.mark.parametrize("model", ["us.anthropic.claude-opus-4-8", "global.anthropic.claude-sonnet-5"])
def test_uses_opt_in_native_output_when_the_opt_in_drove_native_output(local_model_cost_map, model, request_params):
    optional_params: Final = _converse_params(model, None, request_params)

    assert AmazonConverseConfig().uses_opt_in_native_output(model, optional_params, {"model_info": {"id": "d1"}})


@pytest.mark.parametrize(
    ("model", "model_info", "request_params"),
    [
        ("us.anthropic.claude-opus-4-8", None, {"response_format": CAPITAL_RESPONSE_FORMAT}),
        (
            "us.anthropic.claude-opus-4-8",
            {"supports_bedrock_native_structured_output": False},
            {"response_format": CAPITAL_RESPONSE_FORMAT, "thinking": ADAPTIVE_THINKING},
        ),
        (
            "us.anthropic.claude-sonnet-4-6",
            {"supports_bedrock_native_structured_output": True},
            {"response_format": CAPITAL_RESPONSE_FORMAT, "thinking": ADAPTIVE_THINKING},
        ),
    ],
    ids=["no_thinking", "deployment_opt_out", "native_model"],
)
def test_uses_opt_in_native_output_is_false_when_native_output_did_not_come_from_the_opt_in(
    local_model_cost_map, model, model_info, request_params
):
    optional_params: Final = _converse_params(model, model_info, request_params)

    assert not AmazonConverseConfig().uses_opt_in_native_output(model, optional_params, {"model_info": model_info})


def test_uses_opt_in_native_output_reads_the_base_model_of_an_application_inference_profile(local_model_cost_map):
    profile: Final = "arn:aws:bedrock:us-east-1:000000000000:application-inference-profile/profile-id"
    litellm_params: Final = {"base_model": "bedrock/us.anthropic.claude-opus-4-8"}
    optional_params: Final = _converse_params(
        "us.anthropic.claude-opus-4-8",
        None,
        {"response_format": CAPITAL_RESPONSE_FORMAT, "thinking": ADAPTIVE_THINKING},
    )

    assert AmazonConverseConfig().uses_opt_in_native_output(profile, optional_params, litellm_params)


_CALLER_OUTPUT_CONFIG_WITH_A_SCHEMA_OBJECT: Final = {
    "textFormat": {"type": "json_schema", "structure": {"jsonSchema": {"name": "capital", "schema": {"type": "object"}}}}
}
_BEDROCK_SCHEMA_TYPE_ERROR: Final = "outputConfig.textFormat.structure.jsonSchema.schema must be a string"


@pytest.mark.parametrize("model", [_OPUS, _LLAMA], ids=["opt_in", "not_opt_in"])
@pytest.mark.respx(assert_all_called=True)
def test_a_malformed_caller_output_config_gets_bedrocks_own_400(
    model: str, respx_mock: respx.Router, local_model_cost_map: None
) -> None:
    route: Final = respx_mock.post(url__regex=r"/converse$").mock(
        return_value=httpx.Response(400, json={"message": _BEDROCK_SCHEMA_TYPE_ERROR})
    )

    with pytest.raises(litellm.BadRequestError, match=re.escape(_BEDROCK_SCHEMA_TYPE_ERROR)):
        completion(
            model=f"bedrock/converse/{model}",
            messages=[{"role": "user", "content": "What is the capital of France?"}],
            response_format=CAPITAL_RESPONSE_FORMAT,
            outputConfig=_CALLER_OUTPUT_CONFIG_WITH_A_SCHEMA_OBJECT,
            num_retries=0,
            aws_access_key_id="fake",
            aws_secret_access_key="fake",
            aws_region_name="us-east-1",
            client=HTTPHandler(),
        )

    assert route.call_count == 1


_CALLER_OUTPUT_CONFIG: Final = {
    "textFormat": {
        "type": "json_schema",
        "structure": {
            "jsonSchema": {"name": "capital", "schema": json.dumps(CAPITAL_RESPONSE_FORMAT["json_schema"]["schema"])}
        },
    }
}
_BEDROCK_SCHEMA_REFUSAL: Final = "output_config.format.schema: pattern is too complex for structured output"


@pytest.mark.parametrize(
    ("caller_params", "expected_calls"),
    [
        ({"thinking": ADAPTIVE_THINKING}, 2),
        ({"outputConfig": _CALLER_OUTPUT_CONFIG}, 1),
        ({"outputConfig": _CALLER_OUTPUT_CONFIG, "thinking": ADAPTIVE_THINKING}, 1),
    ],
    ids=["litellm_native_output", "caller_output_config", "caller_output_config_thinking"],
)
@pytest.mark.respx(assert_all_called=True)
def test_a_refused_native_schema_is_sent_again_only_when_the_retry_drops_native_output(
    caller_params: dict, expected_calls: int, respx_mock: respx.Router, local_model_cost_map: None
) -> None:
    route: Final = respx_mock.post(url__regex=r"/converse$").mock(
        return_value=httpx.Response(400, json={"message": _BEDROCK_SCHEMA_REFUSAL})
    )

    with pytest.raises(litellm.BadRequestError, match=re.escape(_BEDROCK_SCHEMA_REFUSAL)):
        completion(
            model=f"bedrock/converse/{_OPUS}",
            messages=[{"role": "user", "content": "What is the capital of France?"}],
            response_format=CAPITAL_RESPONSE_FORMAT,
            num_retries=0,
            aws_access_key_id="fake",
            aws_secret_access_key="fake",
            aws_region_name="us-east-1",
            client=HTTPHandler(),
            **caller_params,
        )

    assert route.call_count == expected_calls
    assert all("outputConfig" in json.loads(call.request.content) for call in route.calls[:1])
    assert all("outputConfig" not in json.loads(call.request.content) for call in route.calls[1:])


CONTROL_PLANE_ENDPOINT: Final = "https://bedrock-fips.us-east-1.amazonaws.com"


def _bedrock_chat_answer(request: httpx.Request) -> httpx.Response:
    if request.url.path.endswith("/invoke"):
        return httpx.Response(
            200,
            json={
                "id": "msg_control_plane",
                "type": "message",
                "role": "assistant",
                "model": "claude-haiku-4-5",
                "content": [{"type": "text", "text": "ok"}],
                "stop_reason": "end_turn",
                "usage": {"input_tokens": 1, "output_tokens": 1},
            },
        )
    return httpx.Response(
        200,
        json={
            "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},
            "stopReason": "end_turn",
            "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},
        },
    )


@pytest.mark.parametrize("route_prefix", ["bedrock/", "bedrock/converse/", "bedrock/invoke/"])
@pytest.mark.respx(assert_all_called=True)
def test_a_deployment_with_a_batch_control_plane_endpoint_keeps_it_out_of_chat_requests(
    respx_mock: respx.Router, route_prefix: str
) -> None:
    route: Final = respx_mock.post(
        url__regex=r"^https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.+/(converse|invoke)$"
    ).mock(side_effect=_bedrock_chat_answer)

    response: Final = litellm.completion(
        model=f"{route_prefix}us.anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=[{"role": "user", "content": "hi"}],
        aws_access_key_id="AKIACONTROLPLANE",
        aws_secret_access_key="control-plane-secret",
        aws_region_name="us-east-1",
        aws_bedrock_control_plane_endpoint=CONTROL_PLANE_ENDPOINT,
        client=HTTPHandler(),
    )

    assert response.choices[0].message.content == "ok"
    assert "aws_bedrock_control_plane_endpoint" not in route.calls[0].request.content.decode()