mirror of
https://github.com/livekit/agents.git
synced 2026-12-06 05:08:31 +00:00
447 lines
20 KiB
Python
447 lines
20 KiB
Python
# Copyright 2023 LiveKit, Inc.
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from dataclasses import dataclass
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
from aiobotocore.config import AioConfig
|
|
from aiobotocore.session import AioSession
|
|
from botocore.exceptions import ClientError
|
|
|
|
from livekit.agents import APIConnectionError, APIStatusError, TokenUsage, llm
|
|
from livekit.agents.llm import ChatContext, FunctionToolCall, ToolChoice
|
|
from livekit.agents.types import (
|
|
DEFAULT_API_CONNECT_OPTIONS,
|
|
NOT_GIVEN,
|
|
APIConnectOptions,
|
|
NotGivenOr,
|
|
)
|
|
from livekit.agents.utils import is_given
|
|
|
|
from .log import logger
|
|
from .utils import resolve_session
|
|
|
|
if TYPE_CHECKING:
|
|
from types_aiobotocore_bedrock_runtime.type_defs import (
|
|
ConverseStreamOutputTypeDef,
|
|
SystemContentBlockTypeDef,
|
|
)
|
|
|
|
DEFAULT_TEXT_MODEL = "amazon.nova-2-lite-v1:0"
|
|
|
|
# Model IDs that reject ``temperature``/``topP`` in the Converse API's
|
|
# ``inferenceConfig`` with a ValidationException ("... is deprecated for this
|
|
# model"). Matched as case-insensitive substrings so region-prefixed IDs and
|
|
# inference profile ARNs containing the model name are covered too.
|
|
_MODELS_REJECTING_SAMPLING_PARAMS = (
|
|
"claude-opus-4-7",
|
|
"claude-opus-4-8",
|
|
"claude-opus-5",
|
|
"claude-sonnet-5",
|
|
"claude-fable-5",
|
|
# OpenAI GPT-5.6/GPT-6: "This model doesn't support the temperature field. Remove
|
|
# temperature and try again." gpt-oss still accepts both, so it stays off this list.
|
|
"gpt-5.6",
|
|
"gpt-6",
|
|
)
|
|
|
|
# Model IDs that reject a forced ``toolChoice`` (``any``/``tool``) with a
|
|
# ValidationException ('tool_choice: type "tool" and "any" are not supported for
|
|
# this model.'). Matched the same way as the list above.
|
|
_MODELS_REJECTING_FORCED_TOOL_CHOICE = (
|
|
"claude-opus-5-5",
|
|
"claude-fable-5-1",
|
|
)
|
|
|
|
|
|
def _model_matches(model_id: str, names: tuple[str, ...]) -> bool:
|
|
lowered = model_id.lower()
|
|
# Application inference profiles hide the underlying model behind a
|
|
# user-chosen name, so a substring match would both miss rejecting models
|
|
# and misclassify profiles merely named after one (e.g.
|
|
# ".../claude-opus-4-7-prod" targeting a supporting model). Never guess for
|
|
# those; callers can use the explicit supports_sampling_params override.
|
|
if "application-inference-profile" in lowered:
|
|
return False
|
|
return any(name in lowered for name in names)
|
|
|
|
|
|
def _model_rejects_sampling_params(model_id: str) -> bool:
|
|
return _model_matches(model_id, _MODELS_REJECTING_SAMPLING_PARAMS)
|
|
|
|
|
|
@dataclass
|
|
class _LLMOptions:
|
|
model: str
|
|
temperature: NotGivenOr[float]
|
|
tool_choice: NotGivenOr[ToolChoice]
|
|
max_output_tokens: NotGivenOr[int]
|
|
top_p: NotGivenOr[float]
|
|
additional_request_fields: NotGivenOr[dict[str, Any]]
|
|
cache_system: bool
|
|
cache_tools: bool
|
|
|
|
|
|
class LLM(llm.LLM):
|
|
def __init__(
|
|
self,
|
|
*,
|
|
model: NotGivenOr[str] = DEFAULT_TEXT_MODEL,
|
|
api_key: NotGivenOr[str] = NOT_GIVEN,
|
|
api_secret: NotGivenOr[str] = NOT_GIVEN,
|
|
region: NotGivenOr[str] = "us-east-1",
|
|
temperature: NotGivenOr[float] = NOT_GIVEN,
|
|
max_output_tokens: NotGivenOr[int] = NOT_GIVEN,
|
|
top_p: NotGivenOr[float] = NOT_GIVEN,
|
|
tool_choice: NotGivenOr[ToolChoice] = NOT_GIVEN,
|
|
additional_request_fields: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
|
|
cache_system: bool = False,
|
|
cache_tools: bool = False,
|
|
supports_sampling_params: NotGivenOr[bool] = NOT_GIVEN,
|
|
session: AioSession | None = None,
|
|
) -> None:
|
|
"""
|
|
Create a new instance of AWS Bedrock LLM.
|
|
|
|
``api_key`` and ``api_secret`` must be set to your AWS Access key id and secret access key, either using the argument or by setting the
|
|
``AWS_ACCESS_KEY_ID`` and ``AWS_SECRET_ACCESS_KEY`` environmental variables.
|
|
|
|
See https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse_stream.html for more details on the AWS Bedrock Runtime API.
|
|
|
|
Args:
|
|
model (str, optional): model or inference profile arn to use(https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-use.html).
|
|
Defaults to 'amazon.nova-2-lite-v1:0'.
|
|
api_key(str, optional): AWS access key id.
|
|
api_secret(str, optional): AWS secret access key
|
|
region (str, optional): The region to use for AWS API requests. Defaults value is "us-east-1".
|
|
temperature (float, optional): Sampling temperature for response generation. Defaults to 0.8.
|
|
Ignored (with a warning) for models that reject sampling parameters, e.g. Claude
|
|
Opus 4.7/4.8, Opus 5, Sonnet 5, Fable 5 and OpenAI GPT-5.6/GPT-6.
|
|
max_output_tokens (int, optional): Maximum number of tokens to generate in the output. Defaults to None.
|
|
top_p (float, optional): The nucleus sampling probability for response generation. Defaults to None.
|
|
tool_choice (ToolChoice, optional): Specifies whether to use tools during response generation. Defaults to "auto".
|
|
Forced choices ("required" or a named tool) are sent as "auto" (with a warning) for
|
|
models that reject them, e.g. Claude Opus 5.5 and Fable 5.1.
|
|
additional_request_fields (dict[str, Any], optional): Additional request fields to send to the AWS Bedrock Converse API. Defaults to None.
|
|
cache_system (bool, optional): Caches system messages to reduce token usage. Defaults to False.
|
|
cache_tools (bool, optional): Caches tool definitions to reduce token usage. Defaults to False.
|
|
supports_sampling_params (bool, optional): Explicit override for whether the model accepts
|
|
'temperature'/'top_p'. By default the plugin detects known-rejecting models from the
|
|
model ID, which cannot cover application inference-profile ARNs that hide the
|
|
underlying model name — set False for those profiles to have sampling parameters
|
|
dropped instead of triggering a ValidationException. Defaults to NOT_GIVEN (auto-detect).
|
|
session (AioSession, optional): Optional aiobotocore session to use.
|
|
""" # noqa: E501
|
|
super().__init__()
|
|
|
|
self._sampling_params_warned = False
|
|
self._forced_tool_choice_warned = False
|
|
self._session = resolve_session(session)
|
|
if session is None:
|
|
if is_given(api_key) and api_key and is_given(api_secret) and api_secret:
|
|
self._session.set_credentials(api_key, api_secret)
|
|
if is_given(region) and region:
|
|
self._session.set_config_variable("region", region)
|
|
|
|
bedrock_model = (
|
|
model if is_given(model) else os.environ.get("BEDROCK_INFERENCE_PROFILE_ARN")
|
|
)
|
|
if not bedrock_model:
|
|
raise ValueError(
|
|
"model or inference profile arn must be set using the argument or by setting the BEDROCK_INFERENCE_PROFILE_ARN environment variable." # noqa: E501
|
|
)
|
|
self._opts = _LLMOptions(
|
|
model=bedrock_model,
|
|
temperature=temperature,
|
|
tool_choice=tool_choice,
|
|
max_output_tokens=max_output_tokens,
|
|
top_p=top_p,
|
|
additional_request_fields=additional_request_fields,
|
|
cache_system=cache_system,
|
|
cache_tools=cache_tools,
|
|
)
|
|
self._supports_sampling_params = (
|
|
supports_sampling_params
|
|
if is_given(supports_sampling_params)
|
|
else not _model_rejects_sampling_params(bedrock_model)
|
|
)
|
|
|
|
@property
|
|
def model(self) -> str:
|
|
return self._opts.model
|
|
|
|
@property
|
|
def provider(self) -> str:
|
|
return "AWS Bedrock"
|
|
|
|
def chat(
|
|
self,
|
|
*,
|
|
chat_ctx: ChatContext,
|
|
tools: list[llm.Tool] | None = None,
|
|
parallel_tool_calls: NotGivenOr[bool] = NOT_GIVEN,
|
|
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
|
|
tool_choice: NotGivenOr[ToolChoice] = NOT_GIVEN,
|
|
temperature: NotGivenOr[float] = NOT_GIVEN,
|
|
extra_kwargs: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
|
|
) -> LLMStream:
|
|
chat_ctx = chat_ctx.copy()
|
|
opts: dict[str, Any] = {}
|
|
extra_kwargs = extra_kwargs if is_given(extra_kwargs) else {}
|
|
|
|
if is_given(self._opts.model):
|
|
opts["modelId"] = self._opts.model
|
|
|
|
effective_tool_choice = tool_choice if is_given(tool_choice) else self._opts.tool_choice
|
|
|
|
def _get_tool_config() -> dict[str, Any] | None:
|
|
if not tools:
|
|
return None
|
|
|
|
# Bedrock's toolChoice only accepts auto/any/tool — no "none" equivalent.
|
|
# When the caller wants no tools for this turn, drop toolConfig entirely;
|
|
# orphan toolUse/toolResult blocks in history are stripped below so
|
|
# Bedrock doesn't reject the request.
|
|
if isinstance(effective_tool_choice, str) and effective_tool_choice == "none":
|
|
return None
|
|
|
|
tools_list = llm.ToolContext(tools).parse_function_tools("aws")
|
|
if self._opts.cache_tools:
|
|
tools_list.append({"cachePoint": {"type": "default"}})
|
|
|
|
tool_config: dict[str, Any] = {"tools": tools_list}
|
|
if isinstance(effective_tool_choice, dict):
|
|
tool_config["toolChoice"] = {
|
|
"tool": {"name": effective_tool_choice["function"]["name"]}
|
|
}
|
|
elif effective_tool_choice == "required":
|
|
tool_config["toolChoice"] = {"any": {}}
|
|
elif effective_tool_choice == "auto":
|
|
tool_config["toolChoice"] = {"auto": {}}
|
|
|
|
forced = tool_config.get("toolChoice", {}).keys() & {"any", "tool"}
|
|
if forced and _model_matches(self._opts.model, _MODELS_REJECTING_FORCED_TOOL_CHOICE):
|
|
# "auto" is the only toolChoice these models accept; warn once per
|
|
# instance, like the sampling params below.
|
|
if not self._forced_tool_choice_warned:
|
|
logger.warning(
|
|
"aws bedrock llm: this model does not support a forced "
|
|
"tool_choice; sending 'auto' to avoid a ValidationException",
|
|
extra={"lk.pii.model": self._opts.model},
|
|
)
|
|
self._forced_tool_choice_warned = True
|
|
tool_config["toolChoice"] = {"auto": {}}
|
|
|
|
return tool_config
|
|
|
|
tool_config = _get_tool_config()
|
|
if tool_config:
|
|
opts["toolConfig"] = tool_config
|
|
else:
|
|
chat_ctx = chat_ctx.copy(exclude_function_call=True)
|
|
inference_config: dict[str, Any] = {}
|
|
if is_given(self._opts.max_output_tokens):
|
|
inference_config["maxTokens"] = self._opts.max_output_tokens
|
|
temperature = temperature if is_given(temperature) else self._opts.temperature
|
|
if not self._supports_sampling_params:
|
|
if is_given(temperature) or is_given(self._opts.top_p):
|
|
# chat() runs once per turn: warn only the first time to avoid
|
|
# flooding the logs over a long conversation. The model ID can
|
|
# contain customer data (e.g. an application inference-profile
|
|
# ARN), so it goes into a structured attribute, not the message.
|
|
if not self._sampling_params_warned:
|
|
logger.warning(
|
|
"aws bedrock llm: this model does not support "
|
|
"'temperature'/'top_p'; ignoring them to avoid a "
|
|
"ValidationException",
|
|
extra={"lk.pii.model": self._opts.model},
|
|
)
|
|
self._sampling_params_warned = True
|
|
else:
|
|
if is_given(temperature):
|
|
inference_config["temperature"] = temperature
|
|
if is_given(self._opts.top_p):
|
|
inference_config["topP"] = self._opts.top_p
|
|
|
|
opts["inferenceConfig"] = inference_config
|
|
if is_given(self._opts.additional_request_fields):
|
|
opts["additionalModelRequestFields"] = self._opts.additional_request_fields
|
|
|
|
return LLMStream(
|
|
self,
|
|
chat_ctx=chat_ctx,
|
|
tools=tools or [],
|
|
session=self._session,
|
|
conn_options=conn_options,
|
|
extra_kwargs=opts,
|
|
cache_system=self._opts.cache_system,
|
|
)
|
|
|
|
|
|
class LLMStream(llm.LLMStream):
|
|
def __init__(
|
|
self,
|
|
llm: LLM,
|
|
*,
|
|
chat_ctx: ChatContext,
|
|
session: AioSession,
|
|
conn_options: APIConnectOptions,
|
|
tools: list[llm.Tool],
|
|
extra_kwargs: dict[str, Any],
|
|
cache_system: bool,
|
|
) -> None:
|
|
super().__init__(llm, chat_ctx=chat_ctx, tools=tools, conn_options=conn_options)
|
|
self._llm: LLM = llm
|
|
self._opts = extra_kwargs
|
|
self._cache_system = cache_system
|
|
self._session = session
|
|
self._tool_call_id: str | None = None
|
|
self._fnc_name: str | None = None
|
|
self._fnc_raw_arguments: str | None = None
|
|
self._text: str = ""
|
|
|
|
async def _run(self) -> None:
|
|
retryable = True
|
|
try:
|
|
messages, extra_data = await self._chat_ctx.to_provider_format(format="aws")
|
|
self._opts["messages"] = messages
|
|
if extra_data.system_messages:
|
|
system_messages: list[SystemContentBlockTypeDef] = [
|
|
{"text": content} for content in extra_data.system_messages
|
|
]
|
|
if self._cache_system:
|
|
system_messages.append({"cachePoint": {"type": "default"}})
|
|
self._opts["system"] = system_messages
|
|
|
|
config = AioConfig(
|
|
user_agent_extra="x-client-framework:livekit-plugins-aws",
|
|
connect_timeout=self._conn_options.connect_timeout,
|
|
read_timeout=self._conn_options.read_timeout,
|
|
retries={"mode": "standard", "total_max_attempts": 1},
|
|
)
|
|
# Other services in this SDK overload set have no generated return stub.
|
|
async with self._session.create_client("bedrock-runtime", config=config) as client: # pyright: ignore[reportUnknownMemberType]
|
|
try:
|
|
response = await client.converse_stream(**self._opts)
|
|
except ClientError as e:
|
|
# Bedrock rejected the request itself, e.g. a ValidationException
|
|
# ("This model doesn't support the temperature field."). Keep the HTTP
|
|
# status so a 4xx is not retried; throttling and 5xx still are.
|
|
meta = e.response.get("ResponseMetadata", {})
|
|
raise APIStatusError(
|
|
f"aws bedrock llm: error generating content: {e}",
|
|
status_code=meta.get("HTTPStatusCode", -1),
|
|
request_id=meta.get("RequestId"),
|
|
) from e
|
|
request_id = response["ResponseMetadata"]["RequestId"]
|
|
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
|
|
raise APIStatusError(
|
|
f"aws bedrock llm: error generating content: {response}",
|
|
status_code=response["ResponseMetadata"]["HTTPStatusCode"],
|
|
# Not sure there is a single error field: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse_stream.html#
|
|
# body=response,
|
|
retryable=False,
|
|
request_id=request_id,
|
|
)
|
|
|
|
async for chunk in response["stream"]:
|
|
chat_chunk = self._parse_chunk(request_id, chunk)
|
|
if chat_chunk is not None:
|
|
retryable = False
|
|
self.send(chat_chunk)
|
|
|
|
except APIStatusError:
|
|
raise
|
|
except Exception as e:
|
|
raise APIConnectionError(
|
|
f"aws bedrock llm: error generating content: {e}",
|
|
retryable=retryable,
|
|
) from e
|
|
|
|
def _parse_chunk(
|
|
self, request_id: str, chunk: ConverseStreamOutputTypeDef
|
|
) -> llm.ChatChunk | None:
|
|
if "contentBlockStart" in chunk:
|
|
start = chunk["contentBlockStart"]["start"]
|
|
if "toolUse" in start:
|
|
tool_use = start["toolUse"]
|
|
self._tool_call_id = tool_use["toolUseId"]
|
|
self._fnc_name = tool_use["name"]
|
|
self._fnc_raw_arguments = ""
|
|
|
|
elif "contentBlockDelta" in chunk:
|
|
delta = chunk["contentBlockDelta"]["delta"]
|
|
if "toolUse" in delta:
|
|
if self._fnc_raw_arguments is None:
|
|
raise APIConnectionError("Bedrock sent tool arguments before a tool start")
|
|
self._fnc_raw_arguments += delta["toolUse"]["input"]
|
|
elif "text" in delta:
|
|
return llm.ChatChunk(
|
|
id=request_id,
|
|
delta=llm.ChoiceDelta(content=delta["text"], role="assistant"),
|
|
)
|
|
elif "reasoningContent" in delta:
|
|
# Reasoning deltas (text/signature, or the redactedContent OpenAI GPT-6
|
|
# streams) are not surfaced; skip them quietly, as the anthropic plugin
|
|
# does for thinking deltas.
|
|
pass
|
|
else:
|
|
logger.warning("aws bedrock llm: unknown chunk type", extra={"lk.pii.chunk": chunk})
|
|
|
|
elif "metadata" in chunk:
|
|
usage = chunk["metadata"]["usage"]
|
|
# Bedrock reports inputTokens net of the cache and puts the cached tokens in
|
|
# their own fields; our input total includes them. This mirrors what the
|
|
# anthropic plugin does for the same models served directly.
|
|
cache_read_tokens = usage.get("cacheReadInputTokens")
|
|
cache_write_tokens = usage.get("cacheWriteInputTokens")
|
|
return llm.ChatChunk(
|
|
id=request_id,
|
|
usage=TokenUsage(
|
|
input_tokens=usage["inputTokens"]
|
|
+ (cache_read_tokens or 0)
|
|
+ (cache_write_tokens or 0),
|
|
output_tokens=usage["outputTokens"],
|
|
cache_read_tokens=cache_read_tokens,
|
|
cache_write_tokens=cache_write_tokens,
|
|
),
|
|
)
|
|
elif "contentBlockStop" in chunk:
|
|
if self._tool_call_id:
|
|
if self._fnc_name is None:
|
|
logger.warning("aws bedrock llm: no function name in the response")
|
|
return None
|
|
if self._fnc_raw_arguments is None:
|
|
logger.warning("aws bedrock llm: no function arguments in the response")
|
|
return None
|
|
chat_chunk = llm.ChatChunk(
|
|
id=request_id,
|
|
delta=llm.ChoiceDelta(
|
|
role="assistant",
|
|
tool_calls=[
|
|
FunctionToolCall(
|
|
arguments=self._fnc_raw_arguments,
|
|
name=self._fnc_name,
|
|
call_id=self._tool_call_id,
|
|
),
|
|
],
|
|
),
|
|
)
|
|
self._tool_call_id = self._fnc_name = self._fnc_raw_arguments = None
|
|
return chat_chunk
|
|
return None
|