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]

[Test] Mock live Bedrock Moonshot tests in llm_translation

Yuneng Jiang35a186a133ef
diff --git a/tests/llm_translation/test_bedrock_moonshot.py b/tests/llm_translation/test_bedrock_moonshot.py
index c6066c7db42..a92e342a2c7 100644
--- a/tests/llm_translation/test_bedrock_moonshot.py
+++ b/tests/llm_translation/test_bedrock_moonshot.py
@@ -16,10 +16,12 @@ import pytest
import sys
import os
import json
+from unittest.mock import AsyncMock, Mock, patch
sys.path.insert(0, os.path.abspath("../.."))
import litellm
from litellm.llms.bedrock.common_utils import get_bedrock_chat_config
+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
class TestBedrockMoonshotInvoke(BaseLLMChatTest):
@@ -27,17 +29,121 @@ class TestBedrockMoonshotInvoke(BaseLLMChatTest):
Test suite for Bedrock Moonshot via invoke route.
Inherits all standard LLM tests from BaseLLMChatTest.
"""
-
+
def get_base_completion_call_args(self) -> dict:
litellm._turn_on_debug()
return {
"model": "bedrock/invoke/moonshot.kimi-k2-thinking",
}
-
+
def test_tool_call_no_arguments(self, tool_call_no_arguments):
"""Test that tool calls with no arguments is translated correctly."""
pass
+ # ---------------------------------------------------------------------
+ # The three overrides below replace inherited BaseLLMChatTest tests that
+ # would otherwise make live AWS Bedrock calls. The live versions were
+ # consistently crashing llm_translation xdist workers. Each override
+ # patches the HTTP client's post() so no network request is sent, and
+ # asserts on the outgoing request body (or a mocked response for cost)
+ # — which is what the translation lane is actually supposed to cover.
+ # ---------------------------------------------------------------------
+
+ def test_developer_role_translation(self):
+ """Verify LiteLLM maps the ``developer`` role to ``system`` on the
+ outgoing Bedrock invoke request, without hitting the network."""
+ client = HTTPHandler()
+ with patch.object(client, "post", new=Mock()) as mock_post:
+ try:
+ litellm.completion(
+ model="bedrock/invoke/moonshot.kimi-k2-thinking",
+ messages=[
+ {"role": "developer", "content": "Be a good bot!"},
+ {"role": "user", "content": "Hello, how are you?"},
+ ],
+ aws_access_key_id="fake",
+ aws_secret_access_key="fake",
+ aws_region_name="us-west-2",
+ client=client,
+ )
+ except Exception:
+ # The Mock() return value is not a parseable Bedrock response;
+ # we only care about the outgoing request body.
+ pass
+
+ mock_post.assert_called_once()
+ body = json.loads(mock_post.call_args.kwargs["data"])
+ assert body["messages"][0]["role"] == "system"
+ assert body["messages"][0]["content"] == "Be a good bot!"
+ assert body["messages"][1]["role"] == "user"
+
+ def test_message_with_name(self):
+ """Verify a user message carrying a ``name`` field is serialized into
+ the outgoing Bedrock invoke request without breaking the call."""
+ client = HTTPHandler()
+ with patch.object(client, "post", new=Mock()) as mock_post:
+ try:
+ litellm.completion(
+ model="bedrock/invoke/moonshot.kimi-k2-thinking",
+ messages=[
+ {"role": "user", "content": "Hello", "name": "test_name"},
+ ],
+ aws_access_key_id="fake",
+ aws_secret_access_key="fake",
+ aws_region_name="us-west-2",
+ client=client,
+ )
+ except Exception:
+ pass
+
+ mock_post.assert_called_once()
+ body = json.loads(mock_post.call_args.kwargs["data"])
+ assert body["messages"][0]["role"] == "user"
+ assert body["messages"][0]["content"] == "Hello"
+
+ async def test_completion_cost(self):
+ """Verify LiteLLM computes a positive cost from a mocked Bedrock
+ Moonshot response, using the local model cost map."""
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ response_body = {
+ "id": "chatcmpl-test",
+ "object": "chat.completion",
+ "created": 1234567890,
+ "model": "moonshot.kimi-k2-thinking",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "Hi!"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ },
+ }
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.headers = {"Content-Type": "application/json"}
+ mock_response.text = json.dumps(response_body)
+ mock_response.json = lambda: response_body
+
+ client = AsyncHTTPHandler()
+ with patch.object(client, "post", new=AsyncMock(return_value=mock_response)):
+ response = await litellm.acompletion(
+ model="bedrock/invoke/moonshot.kimi-k2-thinking",
+ messages=[{"role": "user", "content": "Hello, how are you?"}],
+ aws_access_key_id="fake",
+ aws_secret_access_key="fake",
+ aws_region_name="us-west-2",
+ client=client,
+ )
+
+ assert response._hidden_params["response_cost"] > 0
+
class TestBedrockMoonshotBasic:
"""Unit tests for Bedrock Moonshot configuration and transformations."""
@@ -47,7 +153,7 @@ class TestBedrockMoonshotBasic:
config = get_bedrock_chat_config("bedrock/invoke/moonshot.kimi-k2-thinking")
assert config is not None
assert config.__class__.__name__ == "AmazonMoonshotConfig"
-
+
def test_provider_detection_converse(self):
"""Test that Bedrock Moonshot converse models are correctly detected."""
config = get_bedrock_chat_config("bedrock/moonshot.kimi-k2-thinking")
@@ -62,8 +168,10 @@ class TestBedrockMoonshotBasic:
def test_supported_params(self):
"""Test that supported OpenAI params are correctly defined."""
config = get_bedrock_chat_config("invoke/moonshot.kimi-k2-thinking")
- supported_params = config.get_supported_openai_params("moonshot.kimi-k2-thinking")
-
+ supported_params = config.get_supported_openai_params(
+ "moonshot.kimi-k2-thinking"
+ )
+
# Should support these params
assert "temperature" in supported_params
assert "max_tokens" in supported_params
@@ -71,10 +179,10 @@ class TestBedrockMoonshotBasic:
assert "stream" in supported_params
assert "tools" in supported_params
assert "tool_choice" in supported_params
-
+
# Should NOT support stop sequences on Bedrock
assert "stop" not in supported_params
-
+
# Should NOT support functions (use tools instead)
assert "functions" not in supported_params
@@ -83,20 +191,20 @@ class TestBedrockMoonshotBasic:
from litellm.llms.bedrock.chat.invoke_transformations.amazon_moonshot_transformation import (
AmazonMoonshotConfig,
)
-
+
config = AmazonMoonshotConfig()
-
+
messages = [{"role": "user", "content": "Hello"}]
-
+
# Test that bedrock/invoke/ prefix is stripped
transformed = config.transform_request(
model="bedrock/invoke/moonshot.kimi-k2-thinking",
messages=messages,
optional_params={},
litellm_params={},
- headers={}
+ headers={},
)
-
+
# The model ID in the request body should be stripped
assert transformed["model"] == "moonshot.kimi-k2-thinking"
@@ -109,21 +217,27 @@ class TestBedrockMoonshotReasoningContent:
from litellm.llms.bedrock.chat.invoke_transformations.amazon_moonshot_transformation import (
AmazonMoonshotConfig,
)
-
+
config = AmazonMoonshotConfig()
-
+
# Test with reasoning tags
- content_with_reasoning = "<reasoning>This is my thought process</reasoning>This is the answer"
- reasoning, content = config._extract_reasoning_from_content(content_with_reasoning)
-
+ content_with_reasoning = (
+ "<reasoning>This is my thought process</reasoning>This is the answer"
+ )
+ reasoning, content = config._extract_reasoning_from_content(
+ content_with_reasoning
+ )
+
assert reasoning == "This is my thought process"
assert content == "This is the answer"
assert "<reasoning>" not in content
-
+
# Test without reasoning tags
content_without_reasoning = "This is just a regular answer"
- reasoning, content = config._extract_reasoning_from_content(content_without_reasoning)
-
+ reasoning, content = config._extract_reasoning_from_content(
+ content_without_reasoning
+ )
+
assert reasoning is None
assert content == "This is just a regular answer"
@@ -134,8 +248,10 @@ class TestBedrockMoonshotToolCalling:
def test_tool_calling_supported(self):
"""Test that tool calling is supported for Kimi K2 Thinking model."""
config = get_bedrock_chat_config("invoke/moonshot.kimi-k2-thinking")
- supported_params = config.get_supported_openai_params("moonshot.kimi-k2-thinking")
-
+ supported_params = config.get_supported_openai_params(
+ "moonshot.kimi-k2-thinking"
+ )
+
# Kimi K2 Thinking DOES support tool calls (unlike kimi-thinking-preview)
assert "tools" in supported_params
assert "tool_choice" in supported_params
@@ -145,13 +261,11 @@ class TestBedrockMoonshotToolCalling:
from litellm.llms.bedrock.chat.invoke_transformations.amazon_moonshot_transformation import (
AmazonMoonshotConfig,
)
-
+
config = AmazonMoonshotConfig()
-
- messages = [
- {"role": "user", "content": "What's the weather in San Francisco?"}
- ]
-
+
+ messages = [{"role": "user", "content": "What's the weather in San Francisco?"}]
+
optional_params = {
"tools": [
{
@@ -161,27 +275,25 @@ class TestBedrockMoonshotToolCalling:
"description": "Get the current weather",
"parameters": {
"type": "object",
- "properties": {
- "location": {"type": "string"}
- },
- "required": ["location"]
- }
- }
+ "properties": {"location": {"type": "string"}},
+ "required": ["location"],
+ },
+ },
}
]
}
-
+
transformed = config.transform_request(
model="bedrock/invoke/moonshot.kimi-k2-thinking",
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
-
+
# Verify model ID is stripped
assert transformed["model"] == "moonshot.kimi-k2-thinking"
-
+
# Verify tools are included
assert "tools" in transformed
assert len(transformed["tools"]) == 1
@@ -193,9 +305,9 @@ class TestBedrockMoonshotToolCalling:
tool_response_message = {
"role": "tool",
"tool_call_id": "call_123",
- "content": json.dumps({"temperature": 72, "condition": "sunny"})
+ "content": json.dumps({"temperature": 72, "condition": "sunny"}),
}
-
+
# Verify the message structure
assert tool_response_message["role"] == "tool"
assert "tool_call_id" in tool_response_message
@@ -208,8 +320,10 @@ class TestBedrockMoonshotParameterValidation:
def test_stop_sequences_not_supported(self):
"""Test that stop sequences are correctly excluded from supported params."""
config = get_bedrock_chat_config("invoke/moonshot.kimi-k2-thinking")
- supported_params = config.get_supported_openai_params("moonshot.kimi-k2-thinking")
-
+ supported_params = config.get_supported_openai_params(
+ "moonshot.kimi-k2-thinking"
+ )
+
# Bedrock Moonshot doesn't support stopSequences field
assert "stop" not in supported_params
@@ -218,10 +332,12 @@ class TestBedrockMoonshotParameterValidation:
# Moonshot models support temperature 0-1
# This is handled by the parent MoonshotChatConfig class
config = get_bedrock_chat_config("invoke/moonshot.kimi-k2-thinking")
-
+
# Verify config exists and can handle temperature
assert config is not None
- supported_params = config.get_supported_openai_params("moonshot.kimi-k2-thinking")
+ supported_params = config.get_supported_openai_params(
+ "moonshot.kimi-k2-thinking"
+ )
assert "temperature" in supported_params
@@ -233,34 +349,31 @@ class TestBedrockMoonshotTransformations:
from litellm.llms.bedrock.chat.invoke_transformations.amazon_moonshot_transformation import (
AmazonMoonshotConfig,
)
-
+
config = AmazonMoonshotConfig()
-
+
messages = [
{"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": "Hello!"}
+ {"role": "user", "content": "Hello!"},
]
-
- optional_params = {
- "temperature": 0.7,
- "max_tokens": 100
- }
-
+
+ optional_params = {"temperature": 0.7, "max_tokens": 100}
+
transformed = config.transform_request(
model="bedrock/invoke/moonshot.kimi-k2-thinking",
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
-
+
# Verify model ID is stripped
assert transformed["model"] == "moonshot.kimi-k2-thinking"
-
+
# Verify messages are included
assert "messages" in transformed
assert len(transformed["messages"]) >= 1
-
+
# Verify optional params are included
assert transformed["temperature"] == 0.7
assert transformed["max_tokens"] == 100
@@ -270,21 +383,21 @@ class TestBedrockMoonshotTransformations:
from litellm.llms.bedrock.chat.invoke_transformations.amazon_moonshot_transformation import (
AmazonMoonshotConfig,
)
-
+
config = AmazonMoonshotConfig()
-
+
messages = [
{"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": "Hello!"}
+ {"role": "user", "content": "Hello!"},
]
-
+
transformed = config.transform_request(
model="moonshot.kimi-k2-thinking",
messages=messages,
optional_params={},
litellm_params={},
- headers={}
+ headers={},
)
-
+
# System messages should be supported
assert "messages" in transformed