| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | from typing import * # noqa: F403 |
| 8 | |
| 9 | import boto3 |
| 10 | from botocore.client import BaseClient |
| 11 | from botocore.config import Config |
| 12 | |
| 13 | from llama_models.llama3.api.chat_format import ChatFormat |
| 14 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 15 | from llama_models.sku_list import resolve_model |
| 16 | |
| 17 | from llama_stack.apis.inference import * # noqa: F403 |
| 18 | from llama_stack.providers.adapters.inference.bedrock.config import BedrockConfig |
| 19 | |
| 20 | # mapping of Model SKUs to ollama models |
| 21 | BEDROCK_SUPPORTED_MODELS = { |
| 22 | "Meta-Llama3.1-8B-Instruct": "meta.llama3-1-8b-instruct-v1:0", |
| 23 | "Meta-Llama3.1-70B-Instruct": "meta.llama3-1-70b-instruct-v1:0", |
| 24 | "Meta-Llama3.1-405B-Instruct": "meta.llama3-1-405b-instruct-v1:0", |
| 25 | } |
| 26 | |
| 27 | |
| 28 | class BedrockInferenceAdapter(Inference): |
| 29 | |
| 30 | @staticmethod |
| 31 | def _create_bedrock_client(config: BedrockConfig) -> BaseClient: |
| 32 | retries_config = { |
| 33 | k: v |
| 34 | for k, v in dict( |
| 35 | total_max_attempts=config.total_max_attempts, |
| 36 | mode=config.retry_mode, |
| 37 | ).items() |
| 38 | if v is not None |
| 39 | } |
| 40 | |
| 41 | config_args = { |
| 42 | k: v |
| 43 | for k, v in dict( |
| 44 | region_name=config.region_name, |
| 45 | retries=retries_config if retries_config else None, |
| 46 | connect_timeout=config.connect_timeout, |
| 47 | read_timeout=config.read_timeout, |
| 48 | ).items() |
| 49 | if v is not None |
| 50 | } |
| 51 | |
| 52 | boto3_config = Config(**config_args) |
| 53 | |
| 54 | session_args = { |
| 55 | k: v |
| 56 | for k, v in dict( |
| 57 | aws_access_key_id=config.aws_access_key_id, |
| 58 | aws_secret_access_key=config.aws_secret_access_key, |
| 59 | aws_session_token=config.aws_session_token, |
| 60 | region_name=config.region_name, |
| 61 | profile_name=config.profile_name, |
| 62 | ).items() |
| 63 | if v is not None |
| 64 | } |
| 65 | |
| 66 | boto3_session = boto3.session.Session(**session_args) |
| 67 | |
| 68 | return boto3_session.client("bedrock-runtime", config=boto3_config) |
| 69 | |
| 70 | def __init__(self, config: BedrockConfig) -> None: |
| 71 | self._config = config |
| 72 | |
| 73 | self._client = BedrockInferenceAdapter._create_bedrock_client(config) |
| 74 | tokenizer = Tokenizer.get_instance() |
| 75 | self.formatter = ChatFormat(tokenizer) |
| 76 | |
| 77 | @property |
| 78 | def client(self) -> BaseClient: |
| 79 | return self._client |
| 80 | |
| 81 | async def initialize(self) -> None: |
| 82 | pass |
| 83 | |
| 84 | async def shutdown(self) -> None: |
| 85 | self.client.close() |
| 86 | |
| 87 | async def completion( |
| 88 | self, |
| 89 | model: str, |
| 90 | content: InterleavedTextMedia, |
| 91 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 92 | stream: Optional[bool] = False, |
| 93 | logprobs: Optional[LogProbConfig] = None, |
| 94 | ) -> Union[CompletionResponse, CompletionResponseStreamChunk]: |
| 95 | raise NotImplementedError() |
| 96 | |
| 97 | @staticmethod |
| 98 | def resolve_bedrock_model(model_name: str) -> str: |
| 99 | model = resolve_model(model_name) |
| 100 | assert ( |
| 101 | model is not None |
| 102 | and model.descriptor(shorten_default_variant=True) |
| 103 | in BEDROCK_SUPPORTED_MODELS |
| 104 | ), ( |
| 105 | f"Unsupported model: {model_name}, use one of the supported models: " |
| 106 | f"{','.join(BEDROCK_SUPPORTED_MODELS.keys())}" |
| 107 | ) |
| 108 | |
| 109 | return BEDROCK_SUPPORTED_MODELS.get( |
| 110 | model.descriptor(shorten_default_variant=True) |
| 111 | ) |
| 112 | |
| 113 | @staticmethod |
| 114 | def _bedrock_stop_reason_to_stop_reason(bedrock_stop_reason: str) -> StopReason: |
| 115 | if bedrock_stop_reason == "max_tokens": |
| 116 | return StopReason.out_of_tokens |
| 117 | return StopReason.end_of_turn |
| 118 | |
| 119 | @staticmethod |
| 120 | def _builtin_tool_name_to_enum(tool_name_str: str) -> Union[BuiltinTool, str]: |
| 121 | for builtin_tool in BuiltinTool: |
| 122 | if builtin_tool.value == tool_name_str: |
| 123 | return builtin_tool |
| 124 | else: |
| 125 | return tool_name_str |
| 126 | |
| 127 | @staticmethod |
| 128 | def _bedrock_message_to_message(converse_api_res: Dict) -> Message: |
| 129 | stop_reason = BedrockInferenceAdapter._bedrock_stop_reason_to_stop_reason( |
| 130 | converse_api_res["stopReason"] |
| 131 | ) |
| 132 | |
| 133 | bedrock_message = converse_api_res["output"]["message"] |
| 134 | |
| 135 | role = bedrock_message["role"] |
| 136 | contents = bedrock_message["content"] |
| 137 | |
| 138 | tool_calls = [] |
| 139 | text_content = [] |
| 140 | for content in contents: |
| 141 | if "toolUse" in content: |
| 142 | tool_use = content["toolUse"] |
| 143 | tool_calls.append( |
| 144 | ToolCall( |
| 145 | tool_name=BedrockInferenceAdapter._builtin_tool_name_to_enum( |
| 146 | tool_use["name"] |
| 147 | ), |
| 148 | arguments=tool_use["input"] if "input" in tool_use else None, |
| 149 | call_id=tool_use["toolUseId"], |
| 150 | ) |
| 151 | ) |
| 152 | elif "text" in content: |
| 153 | text_content.append(content["text"]) |
| 154 | |
| 155 | return CompletionMessage( |
| 156 | role=role, |
| 157 | content=text_content, |
| 158 | stop_reason=stop_reason, |
| 159 | tool_calls=tool_calls, |
| 160 | ) |
| 161 | |
| 162 | @staticmethod |
| 163 | def _messages_to_bedrock_messages( |
| 164 | messages: List[Message], |
| 165 | ) -> Tuple[List[Dict], Optional[List[Dict]]]: |
| 166 | bedrock_messages = [] |
| 167 | system_bedrock_messages = [] |
| 168 | |
| 169 | user_contents = [] |
| 170 | assistant_contents = None |
| 171 | for message in messages: |
| 172 | role = message.role |
| 173 | content_list = ( |
| 174 | message.content |
| 175 | if isinstance(message.content, list) |
| 176 | else [message.content] |
| 177 | ) |
| 178 | if role == "ipython" or role == "user": |
| 179 | if not user_contents: |
| 180 | user_contents = [] |
| 181 | |
| 182 | if role == "ipython": |
| 183 | user_contents.extend( |
| 184 | [ |
| 185 | { |
| 186 | "toolResult": { |
| 187 | "toolUseId": message.call_id, |
| 188 | "content": [ |
| 189 | {"text": content} for content in content_list |
| 190 | ], |
| 191 | } |
| 192 | } |
| 193 | ] |
| 194 | ) |
| 195 | else: |
| 196 | user_contents.extend( |
| 197 | [{"text": content} for content in content_list] |
| 198 | ) |
| 199 | |
| 200 | if assistant_contents: |
| 201 | bedrock_messages.append( |
| 202 | {"role": "assistant", "content": assistant_contents} |
| 203 | ) |
| 204 | assistant_contents = None |
| 205 | elif role == "system": |
| 206 | system_bedrock_messages.extend( |
| 207 | [{"text": content} for content in content_list] |
| 208 | ) |
| 209 | elif role == "assistant": |
| 210 | if not assistant_contents: |
| 211 | assistant_contents = [] |
| 212 | |
| 213 | assistant_contents.extend( |
| 214 | [ |
| 215 | { |
| 216 | "text": content, |
| 217 | } |
| 218 | for content in content_list |
| 219 | ] |
| 220 | + [ |
| 221 | { |
| 222 | "toolUse": { |
| 223 | "input": tool_call.arguments, |
| 224 | "name": ( |
| 225 | tool_call.tool_name |
| 226 | if isinstance(tool_call.tool_name, str) |
| 227 | else tool_call.tool_name.value |
| 228 | ), |
| 229 | "toolUseId": tool_call.call_id, |
| 230 | } |
| 231 | } |
| 232 | for tool_call in message.tool_calls |
| 233 | ] |
| 234 | ) |
| 235 | |
| 236 | if user_contents: |
| 237 | bedrock_messages.append({"role": "user", "content": user_contents}) |
| 238 | user_contents = None |
| 239 | else: |
| 240 | # Unknown role |
| 241 | pass |
| 242 | |
| 243 | if user_contents: |
| 244 | bedrock_messages.append({"role": "user", "content": user_contents}) |
| 245 | if assistant_contents: |
| 246 | bedrock_messages.append( |
| 247 | {"role": "assistant", "content": assistant_contents} |
| 248 | ) |
| 249 | |
| 250 | if system_bedrock_messages: |
| 251 | return bedrock_messages, system_bedrock_messages |
| 252 | |
| 253 | return bedrock_messages, None |
| 254 | |
| 255 | @staticmethod |
| 256 | def get_bedrock_inference_config(sampling_params: Optional[SamplingParams]) -> Dict: |
| 257 | inference_config = {} |
| 258 | if sampling_params: |
| 259 | param_mapping = { |
| 260 | "max_tokens": "maxTokens", |
| 261 | "temperature": "temperature", |
| 262 | "top_p": "topP", |
| 263 | } |
| 264 | |
| 265 | for k, v in param_mapping.items(): |
| 266 | if getattr(sampling_params, k): |
| 267 | inference_config[v] = getattr(sampling_params, k) |
| 268 | |
| 269 | return inference_config |
| 270 | |
| 271 | @staticmethod |
| 272 | def _tool_parameters_to_input_schema( |
| 273 | tool_parameters: Optional[Dict[str, ToolParamDefinition]] |
| 274 | ) -> Dict: |
| 275 | input_schema = {"type": "object"} |
| 276 | if not tool_parameters: |
| 277 | return input_schema |
| 278 | |
| 279 | json_properties = {} |
| 280 | required = [] |
| 281 | for name, param in tool_parameters.items(): |
| 282 | json_property = { |
| 283 | "type": param.param_type, |
| 284 | } |
| 285 | |
| 286 | if param.description: |
| 287 | json_property["description"] = param.description |
| 288 | if param.required: |
| 289 | required.append(name) |
| 290 | json_properties[name] = json_property |
| 291 | |
| 292 | input_schema["properties"] = json_properties |
| 293 | if required: |
| 294 | input_schema["required"] = required |
| 295 | return input_schema |
| 296 | |
| 297 | @staticmethod |
| 298 | def _tools_to_tool_config( |
| 299 | tools: Optional[List[ToolDefinition]], tool_choice: Optional[ToolChoice] |
| 300 | ) -> Optional[Dict]: |
| 301 | if not tools: |
| 302 | return None |
| 303 | |
| 304 | bedrock_tools = [] |
| 305 | for tool in tools: |
| 306 | tool_name = ( |
| 307 | tool.tool_name |
| 308 | if isinstance(tool.tool_name, str) |
| 309 | else tool.tool_name.value |
| 310 | ) |
| 311 | |
| 312 | tool_spec = { |
| 313 | "toolSpec": { |
| 314 | "name": tool_name, |
| 315 | "inputSchema": { |
| 316 | "json": BedrockInferenceAdapter._tool_parameters_to_input_schema( |
| 317 | tool.parameters |
| 318 | ), |
| 319 | }, |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | if tool.description: |
| 324 | tool_spec["toolSpec"]["description"] = tool.description |
| 325 | |
| 326 | bedrock_tools.append(tool_spec) |
| 327 | tool_config = { |
| 328 | "tools": bedrock_tools, |
| 329 | } |
| 330 | |
| 331 | if tool_choice: |
| 332 | tool_config["toolChoice"] = ( |
| 333 | {"any": {}} |
| 334 | if tool_choice.value == ToolChoice.required |
| 335 | else {"auto": {}} |
| 336 | ) |
| 337 | return tool_config |
| 338 | |
| 339 | async def chat_completion( |
| 340 | self, |
| 341 | model: str, |
| 342 | messages: List[Message], |
| 343 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 344 | # zero-shot tool definitions as input to the model |
| 345 | tools: Optional[List[ToolDefinition]] = None, |
| 346 | tool_choice: Optional[ToolChoice] = ToolChoice.auto, |
| 347 | tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json, |
| 348 | stream: Optional[bool] = False, |
| 349 | logprobs: Optional[LogProbConfig] = None, |
| 350 | ) -> ( |
| 351 | AsyncGenerator |
| 352 | ): # Union[ChatCompletionResponse, ChatCompletionResponseStreamChunk]: |
| 353 | bedrock_model = BedrockInferenceAdapter.resolve_bedrock_model(model) |
| 354 | inference_config = BedrockInferenceAdapter.get_bedrock_inference_config( |
| 355 | sampling_params |
| 356 | ) |
| 357 | |
| 358 | tool_config = BedrockInferenceAdapter._tools_to_tool_config(tools, tool_choice) |
| 359 | bedrock_messages, system_bedrock_messages = ( |
| 360 | BedrockInferenceAdapter._messages_to_bedrock_messages(messages) |
| 361 | ) |
| 362 | |
| 363 | converse_api_params = { |
| 364 | "modelId": bedrock_model, |
| 365 | "messages": bedrock_messages, |
| 366 | } |
| 367 | if inference_config: |
| 368 | converse_api_params["inferenceConfig"] = inference_config |
| 369 | |
| 370 | # Tool use is not supported in streaming mode |
| 371 | if tool_config and not stream: |
| 372 | converse_api_params["toolConfig"] = tool_config |
| 373 | if system_bedrock_messages: |
| 374 | converse_api_params["system"] = system_bedrock_messages |
| 375 | |
| 376 | if not stream: |
| 377 | converse_api_res = self.client.converse(**converse_api_params) |
| 378 | |
| 379 | output_message = BedrockInferenceAdapter._bedrock_message_to_message( |
| 380 | converse_api_res |
| 381 | ) |
| 382 | |
| 383 | yield ChatCompletionResponse( |
| 384 | completion_message=output_message, |
| 385 | logprobs=None, |
| 386 | ) |
| 387 | else: |
| 388 | converse_stream_api_res = self.client.converse_stream(**converse_api_params) |
| 389 | event_stream = converse_stream_api_res["stream"] |
| 390 | |
| 391 | for chunk in event_stream: |
| 392 | if "messageStart" in chunk: |
| 393 | yield ChatCompletionResponseStreamChunk( |
| 394 | event=ChatCompletionResponseEvent( |
| 395 | event_type=ChatCompletionResponseEventType.start, |
| 396 | delta="", |
| 397 | ) |
| 398 | ) |
| 399 | elif "contentBlockStart" in chunk: |
| 400 | yield ChatCompletionResponseStreamChunk( |
| 401 | event=ChatCompletionResponseEvent( |
| 402 | event_type=ChatCompletionResponseEventType.progress, |
| 403 | delta=ToolCallDelta( |
| 404 | content=ToolCall( |
| 405 | tool_name=chunk["contentBlockStart"]["toolUse"][ |
| 406 | "name" |
| 407 | ], |
| 408 | call_id=chunk["contentBlockStart"]["toolUse"][ |
| 409 | "toolUseId" |
| 410 | ], |
| 411 | ), |
| 412 | parse_status=ToolCallParseStatus.started, |
| 413 | ), |
| 414 | ) |
| 415 | ) |
| 416 | elif "contentBlockDelta" in chunk: |
| 417 | if "text" in chunk["contentBlockDelta"]["delta"]: |
| 418 | delta = chunk["contentBlockDelta"]["delta"]["text"] |
| 419 | else: |
| 420 | delta = ToolCallDelta( |
| 421 | content=ToolCall( |
| 422 | arguments=chunk["contentBlockDelta"]["delta"][ |
| 423 | "toolUse" |
| 424 | ]["input"] |
| 425 | ), |
| 426 | parse_status=ToolCallParseStatus.success, |
| 427 | ) |
| 428 | |
| 429 | yield ChatCompletionResponseStreamChunk( |
| 430 | event=ChatCompletionResponseEvent( |
| 431 | event_type=ChatCompletionResponseEventType.progress, |
| 432 | delta=delta, |
| 433 | ) |
| 434 | ) |
| 435 | elif "contentBlockStop" in chunk: |
| 436 | # Ignored |
| 437 | pass |
| 438 | elif "messageStop" in chunk: |
| 439 | stop_reason = ( |
| 440 | BedrockInferenceAdapter._bedrock_stop_reason_to_stop_reason( |
| 441 | chunk["messageStop"]["stopReason"] |
| 442 | ) |
| 443 | ) |
| 444 | |
| 445 | yield ChatCompletionResponseStreamChunk( |
| 446 | event=ChatCompletionResponseEvent( |
| 447 | event_type=ChatCompletionResponseEventType.complete, |
| 448 | delta="", |
| 449 | stop_reason=stop_reason, |
| 450 | ) |
| 451 | ) |
| 452 | elif "metadata" in chunk: |
| 453 | # Ignored |
| 454 | pass |
| 455 | else: |
| 456 | # Ignored |
| 457 | pass |