mirror of
https://github.com/livekit/agents.git
synced 2026-12-06 04:18:36 +00:00
257 lines
10 KiB
Python
257 lines
10 KiB
Python
"""Hermetic unit tests for the AWS Bedrock LLM plugin (no AWS access needed)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pytest
|
|
from botocore.exceptions import ClientError
|
|
|
|
from livekit.agents import APIConnectOptions, APIError, APIStatusError
|
|
from livekit.agents.llm import ChatContext, ToolChoice, function_tool
|
|
from livekit.plugins.aws import LLM as BedrockLLM
|
|
from livekit.plugins.aws.llm import LLMStream
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
|
|
async def _inference_config(model: str, **kwargs: object) -> dict:
|
|
instance = BedrockLLM(model=model, **kwargs)
|
|
stream = instance.chat(chat_ctx=ChatContext())
|
|
opts = stream._opts["inferenceConfig"]
|
|
await stream.aclose()
|
|
return opts
|
|
|
|
|
|
async def test_temperature_sent_for_supporting_models() -> None:
|
|
config = await _inference_config("us.anthropic.claude-sonnet-4-6", temperature=0.5, top_p=0.9)
|
|
|
|
assert config["temperature"] == 0.5
|
|
assert config["topP"] == 0.9
|
|
|
|
|
|
async def test_temperature_omitted_for_opus_4_7(caplog: pytest.LogCaptureFixture) -> None:
|
|
# Claude Opus 4.7 rejects `temperature` with a ValidationException
|
|
# ("`temperature` is deprecated for this model").
|
|
config = await _inference_config("us.anthropic.claude-opus-4-7", temperature=0.5, top_p=0.9)
|
|
|
|
assert "temperature" not in config
|
|
assert "topP" not in config
|
|
|
|
|
|
async def test_sampling_params_warning_logged_once(caplog: pytest.LogCaptureFixture) -> None:
|
|
# chat() runs once per turn; the warning must not repeat every turn.
|
|
with caplog.at_level("WARNING"):
|
|
instance = BedrockLLM(model="us.anthropic.claude-opus-4-8", temperature=0.5)
|
|
for _ in range(3):
|
|
stream = instance.chat(chat_ctx=ChatContext())
|
|
await stream.aclose()
|
|
|
|
warnings = [r for r in caplog.records if "does not support" in r.message]
|
|
assert len(warnings) == 1
|
|
# the model ID may contain customer data (inference-profile ARNs) and must
|
|
# stay out of the message body
|
|
assert "claude-opus-4-8" not in warnings[0].getMessage()
|
|
assert warnings[0].__dict__.get("lk.pii.model") == "us.anthropic.claude-opus-4-8"
|
|
|
|
|
|
async def test_explicit_override_for_opaque_inference_profiles() -> None:
|
|
# An application inference-profile ARN can hide the underlying model name;
|
|
# auto-detection deliberately never guesses for those (the profile name may
|
|
# merely reference a model, or target an unrelated one), so sampling params
|
|
# are sent by default and supports_sampling_params=False forces them out.
|
|
arn = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/my-agent-llm"
|
|
config = await _inference_config(arn, temperature=0.5, top_p=0.9)
|
|
assert config["temperature"] == 0.5
|
|
|
|
config = await _inference_config(
|
|
arn, temperature=0.5, top_p=0.9, supports_sampling_params=False
|
|
)
|
|
assert "temperature" not in config
|
|
assert "topP" not in config
|
|
|
|
# an explicit True keeps them even for known-rejecting models
|
|
config = await _inference_config(
|
|
"us.anthropic.claude-opus-4-7",
|
|
temperature=0.5,
|
|
supports_sampling_params=True,
|
|
)
|
|
assert config["temperature"] == 0.5
|
|
|
|
|
|
async def test_application_profile_named_after_model_is_not_misclassified() -> None:
|
|
# A supporting-model application profile that merely references a rejecting
|
|
# model name must keep its explicitly configured sampling parameters.
|
|
arn = (
|
|
"arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/claude-opus-4-7-prod"
|
|
)
|
|
config = await _inference_config(arn, temperature=0.5)
|
|
assert config["temperature"] == 0.5
|
|
|
|
|
|
async def test_temperature_omitted_for_region_prefix_and_arn() -> None:
|
|
for model in (
|
|
"anthropic.claude-opus-4-8",
|
|
"eu.anthropic.claude-opus-4-7",
|
|
"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-sonnet-5",
|
|
):
|
|
config = await _inference_config(model, temperature=0.5)
|
|
assert "temperature" not in config
|
|
|
|
|
|
async def test_sampling_params_omitted_for_openai_gpt_5_6_and_6() -> None:
|
|
# OpenAI GPT-5.6/GPT-6 reject both fields on Converse with a ValidationException
|
|
# ("This model doesn't support the temperature field. Remove temperature and try again.").
|
|
for model in (
|
|
"us.openai.gpt-6-sol",
|
|
"us.openai.gpt-6-luna",
|
|
"global.openai.gpt-6-sol",
|
|
"us.openai.gpt-5.6-sol",
|
|
"arn:aws:bedrock:us-east-1:123456789012:inference-profile/global.openai.gpt-6-luna",
|
|
):
|
|
config = await _inference_config(model, temperature=0.5, top_p=0.9)
|
|
assert "temperature" not in config
|
|
assert "topP" not in config
|
|
|
|
|
|
async def test_sampling_params_kept_for_gpt_oss() -> None:
|
|
# gpt-oss accepts temperature/topP, so the GPT-5.6/GPT-6 entries must not match it.
|
|
config = await _inference_config("openai.gpt-oss-120b-1:0", temperature=0.5, top_p=0.9)
|
|
assert config == {"temperature": 0.5, "topP": 0.9}
|
|
|
|
|
|
def test_reasoning_deltas_skipped_without_warning(caplog: pytest.LogCaptureFixture) -> None:
|
|
# OpenAI GPT-6 streams reasoning as redactedContent bytes; gpt-oss and Claude thinking
|
|
# stream text (and signature). None is surfaced, so none should log "unknown chunk type".
|
|
for reasoning in ({"redactedContent": b"rsn_abc"}, {"text": "hmm"}, {"signature": "sig"}):
|
|
chunk = {"contentBlockDelta": {"delta": {"reasoningContent": reasoning}}}
|
|
with caplog.at_level("WARNING"):
|
|
assert LLMStream._parse_chunk(object.__new__(LLMStream), "req-1", chunk) is None
|
|
|
|
assert not [r for r in caplog.records if "unknown chunk type" in r.getMessage()]
|
|
|
|
|
|
@function_tool
|
|
async def get_weather(city: str) -> str:
|
|
"""Look up the weather."""
|
|
return city
|
|
|
|
|
|
async def _tool_choice(model: str, tool_choice: ToolChoice) -> dict:
|
|
instance = BedrockLLM(model=model)
|
|
stream = instance.chat(chat_ctx=ChatContext(), tools=[get_weather], tool_choice=tool_choice)
|
|
choice = stream._opts["toolConfig"]["toolChoice"]
|
|
await stream.aclose()
|
|
return choice
|
|
|
|
|
|
_NAMED: ToolChoice = {"type": "function", "function": {"name": "get_weather"}}
|
|
|
|
|
|
async def test_forced_tool_choice_sent_as_auto_for_opus_5_5() -> None:
|
|
# Claude Opus 5.5 and Fable 5.1 reject forced tool use with a ValidationException
|
|
# ('tool_choice: type "tool" and "any" are not supported for this model.').
|
|
for model in (
|
|
"us.anthropic.claude-opus-5-5",
|
|
"global.anthropic.claude-opus-5-5",
|
|
"anthropic.claude-opus-5-5",
|
|
"us.anthropic.claude-fable-5-1",
|
|
):
|
|
assert await _tool_choice(model, "required") == {"auto": {}}
|
|
assert await _tool_choice(model, _NAMED) == {"auto": {}}
|
|
|
|
|
|
async def test_forced_tool_choice_kept_for_other_models() -> None:
|
|
# Opus 5 and Fable 5 still accept any/tool; "claude-fable-5" must not match "-5-1".
|
|
for model in (
|
|
"us.anthropic.claude-opus-5",
|
|
"us.anthropic.claude-fable-5",
|
|
"us.anthropic.claude-sonnet-4-6",
|
|
):
|
|
assert await _tool_choice(model, "required") == {"any": {}}
|
|
assert await _tool_choice(model, _NAMED) == {"tool": {"name": "get_weather"}}
|
|
|
|
|
|
async def test_forced_tool_choice_warning_logged_once(caplog: pytest.LogCaptureFixture) -> None:
|
|
with caplog.at_level("WARNING"):
|
|
instance = BedrockLLM(model="us.anthropic.claude-opus-5-5")
|
|
for _ in range(3):
|
|
stream = instance.chat(
|
|
chat_ctx=ChatContext(), tools=[get_weather], tool_choice="required"
|
|
)
|
|
await stream.aclose()
|
|
|
|
warnings = [r for r in caplog.records if "forced tool_choice" in r.message]
|
|
assert len(warnings) == 1
|
|
assert "claude-opus-5-5" not in warnings[0].getMessage()
|
|
assert warnings[0].__dict__.get("lk.pii.model") == "us.anthropic.claude-opus-5-5"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("code", "status", "attempts"),
|
|
[
|
|
("ValidationException", 400, 1),
|
|
("ThrottlingException", 429, 4),
|
|
("InternalServerException", 500, 4),
|
|
],
|
|
)
|
|
async def test_bedrock_400_fails_fast_throttling_and_5xx_retried(
|
|
monkeypatch: pytest.MonkeyPatch, code: str, status: int, attempts: int
|
|
) -> None:
|
|
# A 400 fails the same way on every retry; throttling and 5xx are still retried.
|
|
calls = 0
|
|
|
|
class _Client:
|
|
async def __aenter__(self) -> _Client:
|
|
return self
|
|
|
|
async def __aexit__(self, *exc: object) -> None:
|
|
return None
|
|
|
|
async def converse_stream(self, **kwargs: object) -> dict:
|
|
nonlocal calls
|
|
calls += 1
|
|
raise ClientError(
|
|
{"Error": {"Code": code}, "ResponseMetadata": {"HTTPStatusCode": status}},
|
|
"ConverseStream",
|
|
)
|
|
|
|
instance = BedrockLLM(model="us.openai.gpt-6-sol")
|
|
monkeypatch.setattr(instance._session, "create_client", lambda *a, **kw: _Client())
|
|
chat_ctx = ChatContext()
|
|
chat_ctx.add_message(role="user", content="hi")
|
|
stream = instance.chat(chat_ctx=chat_ctx, conn_options=APIConnectOptions(retry_interval=0))
|
|
|
|
with pytest.raises(APIError) as exc_info:
|
|
await stream.collect()
|
|
|
|
assert calls == attempts
|
|
if attempts == 1:
|
|
assert isinstance(exc_info.value, APIStatusError)
|
|
assert exc_info.value.status_code == 400
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"usage, prompt, total",
|
|
[
|
|
({"cacheReadInputTokens": 2000}, 2100, 2150),
|
|
({"cacheWriteInputTokens": 1500}, 1600, 1650),
|
|
({"cacheReadInputTokens": 300, "cacheWriteInputTokens": 200}, 600, 650),
|
|
({"cacheReadInputTokens": None, "cacheWriteInputTokens": None}, 100, 150),
|
|
],
|
|
)
|
|
def test_bedrock_input_tokens_include_cached_tokens(
|
|
usage: dict[str, int | None], prompt: int, total: int
|
|
) -> None:
|
|
"""``TokenUsage.input_tokens`` includes cached tokens and ``total_tokens`` is input +
|
|
output. Bedrock's ``inputTokens`` is net of the cache (read or written, possibly sent as
|
|
null), and its own ``totalTokens`` is not trusted."""
|
|
chunk = {
|
|
"metadata": {
|
|
"usage": {"inputTokens": 100, "outputTokens": 50, "totalTokens": 999999, **usage}
|
|
}
|
|
}
|
|
result = LLMStream._parse_chunk(object.__new__(LLMStream), "req-1", chunk)
|
|
assert result is not None and result.usage is not None
|
|
assert (result.usage.input_tokens, result.usage.total_tokens) == (prompt, total)
|
|
assert result.usage.cache_read_tokens == usage.get("cacheReadInputTokens")
|
|
assert result.usage.cache_write_tokens == usage.get("cacheWriteInputTokens")
|