mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-25 22:20:43 +00:00
* test: migrate local_testing SDK and provider tests out of build_and_test * test: cover sagemaker region, hf template and nova paths end to end Region rows now go through litellm.completion on the sagemaker/ handler that the legacy tests exercised, the prompt template test mocks the Hugging Face tokenizer config instead of switching to custom_prompt_dict, streaming tests assert role, finish reason and body, and Nova single turn and streaming run through litellm.completion with a recorded request body * test: tighten migrated integration tests for local OpenAI routes, timeouts and air-gapped boot Split the catch-all providers migration file by behavior. The fake endpoint route tests now hit the owned upstream directly, as the legacy harness tests did. LM Studio asserts the outbound key, path and stripped model. The embedding timeout test asserts the proxy maps a deployment timeout to a 408 and forwards the read timeout to the provider client, instead of timing out the test client The Azure streaming tool-call test also asserts the second identical stream is served from the Redis cache with the same reassembled tool call The Docker network test always skipped in CI because the security job has no litellm/litellm image and no egress to pull one, and it tested a published image rather than the checkout. It now boots the checkout proxy with every outbound HTTP connection refused and asserts readiness, the bundled cost map fallback and that the cost map host is the only egress attempted * test: tighten the migrated e2e rows for local_testing SDK and provider tests Drop the duplicated Anthropic covers marker and the Anthropic cell wrongly claimed by the Bedrock and Vertex cache tests. Keep the file-wide Anthropic model as it is on main. Send the 2023-06-01 version header to Anthropic through the deployment's extra_headers so the header actually reaches the provider, and mark the creation-token case 1h then 5m like the legacy test did Reuse the Bedrock file's own registration for the pydantic response test, swap the hand-built PNGs for the shared cat.jpg fixture, assert the SageMaker Nova image answer names the cat and that top_logprobs=3 is honored, and register the SageMaker Nova opt-in markers the same way as the other opt-in markers * test: restore lost assertions in migrated test_main tests Restore the role alternation check in test_completion_anthropic_hanging, the embedding and streaming response-header checks, the logit_bias drop check and the gemini system and safety settings checks. Add an azure 429 retry-after test for test_exception_with_headers, trigger the router fallback with mock_timeout like the legacy test, and stop the mock timeout tests sleeping 3s * test: restore lost legacy assertions in migrated vertex ai unit tests * test: tighten migrated cost, streaming and embedding tests and scope the hosted mock guard * test: strengthen migrated anthropic, azure, bedrock and cohere provider tests Assert full request bodies and usage instead of presence checks, restore the dummy-tool and custom_llm_provider assertions the legacy tests made, add the async and per-model variants the legacy parametrization covered, split streamed tool arguments across deltas, and move the Azure chat streaming tests to the azure.py mirror file * test: tighten migrated llms provider tests and cover legacy intents lost in the move Strengthen the migrated fireworks, gemini, mistral, together, openai text completion, openrouter, perplexity and openai error tests so they assert what the legacy tests proved (cost, provider tag, usage-only-on-last-chunk, function_call rebuild, reasoning param, sync/async/stream error fields). Replace the huggingface and jina tests that doubled litellm code with respx end-to-end tests. Add the tests the pre-existing mapped tests never covered: cohere 400 mapping, token-array text completion, hosted_vllm/llamafile/lm_studio env api base embeddings, watsonx embedding auth, ollama ssl_verify client and ollama vision prompt * test: cover residual legacy paths for anthropic tool streams, watsonx async stream, ollama http images and caller async embedding clients * test: restore single request assertions in the deep_infra and azure_ai embedding tests * test: drop a no-op streaming cost flag from the openai streaming cost test * test: cover residual legacy-test lines in caching, main, utils, replicate, vertex and bedrock invoke * test: cover streamed audio assembly, choice membership, untranslated responses events and the stream log guard * test: pin cost rates in unit tests, use sdk for cohere e2e, drop vertex llama e2e * test: send the vertex maps e2e request through the openai sdk * test: drop the local_testing jobs that select no tests after the migrations * test: wait for the streamed cache entry and keep custom Mistral rates test-local * test: keep untouched Mistral test lines as they were --------- Co-authored-by: yuneng <yuneng@berri.ai>
327 lines
12 KiB
Python
327 lines
12 KiB
Python
import json
|
|
|
|
import pytest
|
|
import respx
|
|
import litellm
|
|
import httpx
|
|
from typing import Final
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def add_mistral_api_key_to_env(monkeypatch):
|
|
"""Add Mistral API key to environment for testing."""
|
|
monkeypatch.setenv("MISTRAL_API_KEY", "fake-mistral-api-key-12345")
|
|
|
|
|
|
@pytest.fixture
|
|
def mistral_api_response():
|
|
"""Mock response data for Mistral API calls."""
|
|
return {
|
|
"id": "chatcmpl-mistral-123",
|
|
"object": "chat.completion",
|
|
"created": 1677652288,
|
|
"model": "mistral-medium-latest",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": "Hello from Mistral! How can I help you today?",
|
|
},
|
|
"finish_reason": "stop",
|
|
}
|
|
],
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 15, "total_tokens": 25},
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def mistral_api_response_with_empty_content():
|
|
"""Mock response data for Mistral API calls with empty content that should be converted to None."""
|
|
return {
|
|
"id": "chatcmpl-mistral-123",
|
|
"object": "chat.completion",
|
|
"created": 1677652288,
|
|
"model": "mistral-medium-latest",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": "", # Empty string that should be converted to None
|
|
},
|
|
"finish_reason": "stop",
|
|
}
|
|
],
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 0, "total_tokens": 10},
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("sync_mode", [True, False])
|
|
@pytest.mark.asyncio
|
|
async def test_mistral_basic_completion(sync_mode, respx_mock, mistral_api_response):
|
|
"""Test basic Mistral completion functionality."""
|
|
litellm.disable_aiohttp_transport = True
|
|
|
|
model = "mistral/mistral-medium-latest"
|
|
messages = [{"role": "user", "content": "Hello, how are you?"}]
|
|
|
|
# Mock the Mistral API endpoint
|
|
respx_mock.post("https://api.mistral.ai/v1/chat/completions").respond(
|
|
json=mistral_api_response
|
|
)
|
|
|
|
if sync_mode:
|
|
response = litellm.completion(model=model, messages=messages)
|
|
else:
|
|
response = await litellm.acompletion(model=model, messages=messages)
|
|
|
|
# Verify response
|
|
assert (
|
|
response.choices[0].message.content
|
|
== "Hello from Mistral! How can I help you today?"
|
|
)
|
|
assert response.model == "mistral-medium-latest"
|
|
assert response.usage.total_tokens == 25
|
|
|
|
|
|
@pytest.mark.parametrize("sync_mode", [True, False])
|
|
@pytest.mark.asyncio
|
|
async def test_mistral_transform_response_empty_content_conversion(
|
|
sync_mode, respx_mock, mistral_api_response_with_empty_content
|
|
):
|
|
"""
|
|
Test that Mistral's transform_response method is being called by verifying
|
|
the specific behavior of converting empty string content to None.
|
|
|
|
This test verifies that the _handle_empty_content_response method in
|
|
MistralConfig.transform_response is being applied.
|
|
"""
|
|
litellm.disable_aiohttp_transport = True
|
|
|
|
model = "mistral/mistral-medium-latest"
|
|
messages = [{"role": "user", "content": "Generate an empty response"}]
|
|
|
|
# Mock the Mistral API endpoint with empty content
|
|
respx_mock.post("https://api.mistral.ai/v1/chat/completions").respond(
|
|
json=mistral_api_response_with_empty_content
|
|
)
|
|
|
|
if sync_mode:
|
|
response = litellm.completion(model=model, messages=messages)
|
|
else:
|
|
response = await litellm.acompletion(model=model, messages=messages)
|
|
|
|
# Verify that the transform_response method was called by checking that
|
|
# empty string content was converted to None (Mistral-specific behavior)
|
|
assert response.choices[0].message.content is None
|
|
assert response.model == "mistral-medium-latest"
|
|
assert response.usage.total_tokens == 10
|
|
|
|
|
|
@pytest.mark.parametrize("sync_mode", [True, False])
|
|
@pytest.mark.asyncio
|
|
async def test_mistral_transform_request_name_field_removal(
|
|
sync_mode, respx_mock, mistral_api_response
|
|
):
|
|
"""
|
|
Test that Mistral's transform_request method is being called by verifying
|
|
the specific behavior of removing the 'name' field from non-tool messages.
|
|
|
|
This test verifies that the _handle_name_in_message method in
|
|
MistralConfig._transform_messages is being applied.
|
|
"""
|
|
litellm.disable_aiohttp_transport = True
|
|
|
|
model = "mistral/mistral-medium-latest"
|
|
# Include a message with 'name' field that should be removed for non-tool messages
|
|
messages = [
|
|
{"role": "user", "content": "Hello", "name": "should_be_removed"},
|
|
{"role": "assistant", "content": "Hi there!"},
|
|
{"role": "user", "content": "How are you?"},
|
|
]
|
|
|
|
# Mock the Mistral API endpoint
|
|
respx_mock.post("https://api.mistral.ai/v1/chat/completions").respond(
|
|
json=mistral_api_response
|
|
)
|
|
|
|
if sync_mode:
|
|
response = litellm.completion(model=model, messages=messages)
|
|
else:
|
|
response = await litellm.acompletion(model=model, messages=messages)
|
|
|
|
# Verify the response works (if transform_request wasn't called, the API would reject the request)
|
|
assert (
|
|
response.choices[0].message.content
|
|
== "Hello from Mistral! How can I help you today?"
|
|
)
|
|
assert response.model == "mistral-medium-latest"
|
|
|
|
# Verify that the request was made (if transform_request failed, this would fail)
|
|
assert len(respx_mock.calls) == 1
|
|
|
|
# Get the actual request that was made
|
|
request = respx_mock.calls[0].request
|
|
import json
|
|
|
|
request_data = json.loads(request.content.decode("utf-8"))
|
|
|
|
# Verify that the 'name' field was removed from the user message
|
|
# (Mistral API only supports 'name' in tool messages)
|
|
user_message = request_data["messages"][0]
|
|
assert user_message["role"] == "user"
|
|
assert user_message["content"] == "Hello"
|
|
assert "name" not in user_message # The 'name' field should have been removed
|
|
|
|
|
|
def test_mistral_401_maps_to_authentication_error(respx_mock):
|
|
route = respx_mock.post("https://api.mistral.ai/v1/chat/completions").mock(
|
|
return_value=httpx.Response(401, json={"message": "invalid API key"})
|
|
)
|
|
|
|
with pytest.raises(litellm.AuthenticationError) as exc_info:
|
|
litellm.completion(
|
|
model="mistral/mistral-tiny",
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
api_key="bad-mistral-key",
|
|
max_retries=0,
|
|
)
|
|
|
|
assert exc_info.value.status_code == 401
|
|
assert "invalid API key" in str(exc_info.value)
|
|
assert route.calls.last.request.headers["Authorization"] == "Bearer bad-mistral-key"
|
|
|
|
|
|
def test_mistral_streaming_function_call_arguments_are_assembled(
|
|
respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
|
|
chunks: Final = (
|
|
{
|
|
"id": "chatcmpl-stream",
|
|
"object": "chat.completion.chunk",
|
|
"created": 1,
|
|
"model": "mistral-medium-latest",
|
|
"choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}],
|
|
},
|
|
{
|
|
"id": "chatcmpl-stream",
|
|
"object": "chat.completion.chunk",
|
|
"created": 1,
|
|
"model": "mistral-medium-latest",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"delta": {
|
|
"tool_calls": [
|
|
{
|
|
"index": 0,
|
|
"id": "call_weather",
|
|
"type": "function",
|
|
"function": {
|
|
"name": "get_current_weather",
|
|
"arguments": '{"location":"',
|
|
},
|
|
}
|
|
]
|
|
},
|
|
"finish_reason": None,
|
|
}
|
|
],
|
|
},
|
|
{
|
|
"id": "chatcmpl-stream",
|
|
"object": "chat.completion.chunk",
|
|
"created": 1,
|
|
"model": "mistral-medium-latest",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"delta": {
|
|
"tool_calls": [
|
|
{
|
|
"index": 0,
|
|
"function": {"arguments": 'Boston","unit":"fahrenheit"}'},
|
|
}
|
|
]
|
|
},
|
|
"finish_reason": None,
|
|
}
|
|
],
|
|
},
|
|
{
|
|
"id": "chatcmpl-stream",
|
|
"object": "chat.completion.chunk",
|
|
"created": 1,
|
|
"model": "mistral-medium-latest",
|
|
"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}],
|
|
},
|
|
)
|
|
body: Final = "".join(f"data: {json.dumps(chunk)}\n\n" for chunk in chunks) + "data: [DONE]\n\n"
|
|
respx_mock.post("https://api.mistral.ai/v1/chat/completions").respond(
|
|
200,
|
|
text=body,
|
|
headers={"content-type": "text/event-stream"},
|
|
)
|
|
messages: Final = [{"role": "user", "content": "What is the weather in Boston?"}]
|
|
stream: Final = litellm.completion(
|
|
model="mistral/mistral-medium-latest",
|
|
messages=messages,
|
|
tools=[
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "get_current_weather",
|
|
"description": "Get the current weather",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"location": {"type": "string"},
|
|
"unit": {"type": "string"},
|
|
},
|
|
"required": ["location", "unit"],
|
|
},
|
|
},
|
|
}
|
|
],
|
|
stream=True,
|
|
)
|
|
stream_chunks: Final = tuple(stream)
|
|
assert {chunk._hidden_params["custom_llm_provider"] for chunk in stream_chunks} == {"mistral"}
|
|
argument_fragments: Final = tuple(
|
|
chunk.choices[0].delta.tool_calls[0].function.arguments
|
|
for chunk in stream_chunks
|
|
if chunk.choices and chunk.choices[0].delta.tool_calls is not None
|
|
)
|
|
assert "".join(argument or "" for argument in argument_fragments) == (
|
|
'{"location":"Boston","unit":"fahrenheit"}'
|
|
)
|
|
assembled: Final = litellm.stream_chunk_builder(chunks=list(stream_chunks), messages=messages)
|
|
assert assembled is not None
|
|
assert assembled.choices[0].message.tool_calls[0].function.name == "get_current_weather"
|
|
assert json.loads(assembled.choices[0].message.tool_calls[0].function.arguments) == {
|
|
"location": "Boston",
|
|
"unit": "fahrenheit",
|
|
}
|
|
assert assembled.choices[0].finish_reason == "tool_calls"
|
|
|
|
|
|
def test_mistral_completion_cost_is_priced_from_the_returned_usage(
|
|
respx_mock, mistral_api_response, local_model_cost_map
|
|
):
|
|
route: Final = respx_mock.post("https://api.mistral.ai/v1/chat/completions").respond(json=mistral_api_response)
|
|
|
|
response: Final = litellm.completion(
|
|
model="mistral/mistral-medium-latest",
|
|
messages=[{"role": "user", "content": "Hey, how's it going?"}],
|
|
max_tokens=5,
|
|
seed=10,
|
|
input_cost_per_token=4e-07,
|
|
output_cost_per_token=2e-06,
|
|
)
|
|
|
|
body: Final = json.loads(route.calls.last.request.content)
|
|
assert (body["random_seed"], body["max_tokens"]) == (10, 5)
|
|
assert (response.usage.prompt_tokens, response.usage.completion_tokens) == (10, 15)
|
|
assert response._hidden_params["response_cost"] == pytest.approx(10 * 4e-07 + 15 * 2e-06)
|