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]

fix(bedrock): normalize /v1/completions and /v1/responses batch records

milana7250f4eeab5
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index 639c93dfb80..777ba398d5a 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -6,7 +6,7 @@ import io
import json
import mimetypes
import re
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from os import PathLike
from pathlib import Path
from typing import (
@@ -1742,3 +1742,23 @@ def split_concatenated_json_objects(raw: str) -> list[dict[str, Any]]:
idx = end_idx
return results
+
+
+def text_completion_prompt_to_messages(prompt: str | Sequence[str]) -> tuple[AllMessageValues, ...]:
+ """
+ Wrap an OpenAI ``/v1/completions`` ``prompt`` into Chat Completion messages.
+
+ Mirrors what ``litellm.text_completion`` does on the real-time path: a
+ string becomes a single user message, and a list of strings becomes one
+ user message per element. Pre-tokenized prompts (``list[int]`` /
+ ``list[list[int]]``) are only meaningful for the OpenAI-family text
+ endpoints, so they are rejected here rather than silently forwarded, as is
+ an empty prompt, which every chat-shaped provider rejects downstream.
+ """
+ if isinstance(prompt, str) and prompt:
+ return (ChatCompletionUserMessage(role="user", content=prompt),)
+ if isinstance(prompt, Sequence) and prompt and all(isinstance(entry, str) and entry for entry in prompt):
+ return tuple(ChatCompletionUserMessage(role="user", content=entry) for entry in prompt)
+ raise ValueError(
+ f"`prompt` must be a non-empty string or a non-empty list of strings. Got: {type(prompt).__name__}."
+ )
diff --git a/litellm/llms/bedrock/files/transformation.py b/litellm/llms/bedrock/files/transformation.py
index 3656088cb9d..0aa832780e5 100644
--- a/litellm/llms/bedrock/files/transformation.py
+++ b/litellm/llms/bedrock/files/transformation.py
@@ -2,7 +2,9 @@ import base64
import json
import os
import time
-from collections.abc import Mapping, MutableMapping
+from collections.abc import Iterable, Mapping, MutableMapping
+from functools import cache
+from itertools import chain
from types import MappingProxyType
from typing import (
Any,
@@ -12,7 +14,7 @@ from urllib.parse import unquote
import httpx
from httpx import Headers, Response
from openai.types.file_deleted import FileDeleted
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, TypeAdapter
from litellm._logging import verbose_logger
from litellm._uuid import uuid
@@ -28,12 +30,16 @@ from litellm.litellm_core_utils.cloud_storage_security import (
split_configured_cloud_bucket_name,
validate_managed_cloud_file_id,
)
-from litellm.litellm_core_utils.prompt_templates.common_utils import extract_file_data
+from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ extract_file_data,
+ text_completion_prompt_to_messages,
+)
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.base_llm.files.transformation import (
BaseFilesConfig,
LiteLLMLoggingObj,
)
+from litellm.types.llms.bedrock import BedrockBatchRecordKind
from litellm.types.llms.openai import (
AllMessageValues,
CreateFileRequest,
@@ -43,6 +49,8 @@ from litellm.types.llms.openai import (
OpenAICreateFileRequestOptionalParams,
OpenAIFileObject,
PathLike,
+ ResponseInputParam,
+ ResponsesAPIOptionalRequestParams,
)
from litellm.types.utils import ExtractedFileData, LlmProviders, SpecialEnums
from litellm.utils import get_llm_provider
@@ -57,6 +65,26 @@ from ..common_utils import BedrockError
S3_SIGNED_GET_HEADERS_PARAM = "_s3_signed_get_headers"
+def _frozen_mapping(items: Iterable[tuple[str, Any]]) -> Mapping[str, Any]:
+ return MappingProxyType(dict(items))
+
+
+# JSONL batch records are untyped json, so the `/v1/responses` fields are
+# validated into their concrete Responses API types before being handed to the
+# Responses-to-Chat bridge. Both adapters drop keys the Responses API doesn't
+# define, which is what the bridge would ignore anyway. Built on first use
+# rather than at import: `ResponseInputParam` is a deep union and only batch
+# files carrying `/v1/responses` records need it.
+@cache
+def _responses_input_adapter() -> TypeAdapter[str | ResponseInputParam]:
+ return TypeAdapter(str | ResponseInputParam)
+
+
+@cache
+def _responses_request_adapter() -> TypeAdapter[ResponsesAPIOptionalRequestParams]:
+ return TypeAdapter(ResponsesAPIOptionalRequestParams)
+
+
class _BedrockS3RequestParams(BaseModel):
"""Typed view of the credential/region params the S3 GetObject path reads."""
@@ -305,41 +333,55 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig):
# example; add others here as they adopt the same schema.
CONVERSE_INVOKE_PROVIDERS = ("nova",)
- # OpenAI batch URL that signals an embedding request. Per OpenAI Batch API
- # spec, every JSONL record carries a `url` field; we use it as the
- # authoritative signal to route the line to the embedding code path
- # instead of inferring from the presence of `input` vs `messages`.
+ # OpenAI batch URLs that select which request shape a JSONL line carries.
+ # Per the OpenAI Batch API spec every record carries a `url`, so we use it
+ # as the authoritative routing signal instead of inferring from the
+ # presence of `input` vs `prompt` vs `messages`.
OPENAI_EMBEDDINGS_URL = "/v1/embeddings"
+ OPENAI_TEXT_COMPLETIONS_URL = "/v1/completions"
+ OPENAI_RESPONSES_URL = "/v1/responses"
@staticmethod
- def _is_embedding_record(openai_jsonl_record: dict[str, Any]) -> bool:
+ def _classify_batch_record(openai_jsonl_record: Mapping[str, Any]) -> BedrockBatchRecordKind:
"""
- Decide whether an OpenAI batch JSONL line is an embedding request.
-
- Precedence (strict - any explicit `url` short-circuits):
- 1. `url == "/v1/embeddings"` -> embedding. Authoritative per the
- OpenAI Batch API spec.
- 2. Any other non-empty `url` (e.g. `/v1/chat/completions`) -> NOT
- embedding. We trust the caller's explicit signal even if the
- body would otherwise suggest embedding; misrouting a chat
- record into the embedding transformer would corrupt the
- modelInput, while a chat-shaped body sent to the chat path
- either succeeds or fails cleanly inside that transformer.
- 3. `url` missing/empty -> fall back to body shape. Requires
- `input` present AND `messages` absent so a malformed record
- carrying both keys routes to the chat path (safer default:
- Anthropic transforms ignore unknown top-level keys, whereas
- the embedding transformer would silently drop the messages).
+ Decide which OpenAI endpoint shape an OpenAI batch JSONL line carries.
+
+ Precedence (strict - any recognized `url` short-circuits):
+ 1. A `url` matching a supported endpoint wins. Authoritative per the
+ OpenAI Batch API spec, which requires it on every record.
+ 2. Any other non-empty `url` -> chat. We trust the caller's explicit
+ signal rather than re-deriving it from the body, and an
+ unexpectedly-shaped body fails cleanly inside the chat
+ transformer instead of being silently misrouted.
+ 3. `url` missing/empty -> fall back to body shape. `messages` wins
+ over the other keys so a malformed record carrying several of
+ them keeps its conversation instead of having it dropped, and a
+ bare `input` stays an embedding for backwards compatibility
+ (that ambiguity with `/v1/responses` is only resolvable from
+ `url`).
"""
- url = openai_jsonl_record.get("url")
- if url == BedrockFilesConfig.OPENAI_EMBEDDINGS_URL:
- return True
- if url:
- return False
- body = openai_jsonl_record.get("body", {})
- if not isinstance(body, dict):
- return False
- return "input" in body and "messages" not in body
+ match openai_jsonl_record.get("url"):
+ case BedrockFilesConfig.OPENAI_EMBEDDINGS_URL:
+ return BedrockBatchRecordKind.EMBEDDING
+ case BedrockFilesConfig.OPENAI_TEXT_COMPLETIONS_URL:
+ return BedrockBatchRecordKind.TEXT_COMPLETION
+ case BedrockFilesConfig.OPENAI_RESPONSES_URL:
+ return BedrockBatchRecordKind.RESPONSES
+ case None | "":
+ pass
+ case _:
+ return BedrockBatchRecordKind.CHAT
+
+ body = openai_jsonl_record.get("body")
+ if not isinstance(body, Mapping):
+ return BedrockBatchRecordKind.CHAT
+ if "messages" in body:
+ return BedrockBatchRecordKind.CHAT
+ if "prompt" in body:
+ return BedrockBatchRecordKind.TEXT_COMPLETION
+ if "input" in body:
+ return BedrockBatchRecordKind.EMBEDDING
+ return BedrockBatchRecordKind.CHAT
# Identifier for the Bedrock Titan v2 InvokeModel body schema as stored
# in `model_prices_and_context_window.json`. Centralized so future
@@ -546,9 +588,83 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig):
)
return dict(titan_config._transform_request(input=input_text, inference_params=inference_params))
+ @staticmethod
+ def _transform_text_completion_body_to_chat_body(openai_request_body: Mapping[str, Any]) -> Mapping[str, Any]:
+ """
+ Rewrite an OpenAI `/v1/completions` batch body as a Chat Completions body.
+
+ Bedrock batch `modelInput` is the model's InvokeModel/Converse body, and
+ no Bedrock batch model takes a bare `prompt`, so the wrapping that
+ `litellm.text_completion` does in real time has to happen here too.
+ """
+ prompt = openai_request_body.get("prompt")
+ if prompt is None:
+ raise ValueError(
+ "Batch record for /v1/completions is missing required `prompt` field: "
+ f"model={openai_request_body.get('model', '')}"
+ )
+ return _frozen_mapping(
+ chain(
+ ((key, value) for key, value in openai_request_body.items() if key != "prompt"),
+ (("messages", text_completion_prompt_to_messages(prompt)),),
+ )
+ )
+
+ @staticmethod
+ def _transform_responses_body_to_chat_body(openai_request_body: Mapping[str, Any]) -> Mapping[str, Any]:
+ """
+ Rewrite an OpenAI `/v1/responses` batch body as a Chat Completions body.
+
+ Delegates to the same Responses-to-Chat bridge the real-time path uses
+ for providers without a native Responses API (which is every Bedrock
+ model), so `input`, `instructions`, `max_output_tokens` and the tool
+ params translate identically in batch and real time. The bridge always
+ emits a `tools` key; an empty one is dropped rather than shipped as an
+ empty array inside `modelInput`.
+ """
+ from litellm.responses.litellm_completion_transformation.transformation import (
+ LiteLLMCompletionResponsesConfig,
+ )
+
+ responses_input = openai_request_body.get("input")
+ if responses_input is None:
+ raise ValueError(
+ "Batch record for /v1/responses is missing required `input` field: "
+ f"model={openai_request_body.get('model', '')}"
+ )
+ chat_body = LiteLLMCompletionResponsesConfig.transform_responses_api_request_to_chat_completion_request(
+ model=openai_request_body.get("model", ""),
+ input=_responses_input_adapter().validate_python(responses_input),
+ responses_api_request=_responses_request_adapter().validate_python(
+ _frozen_mapping(
+ (key, value) for key, value in openai_request_body.items() if key not in ("model", "input")
+ )
+ ),
+ )
+ return _frozen_mapping((key, value) for key, value in chat_body.items() if key != "tools" or value)
+
+ @staticmethod
+ def _transform_batch_body_to_chat_body(
+ openai_request_body: Mapping[str, Any],
+ record_kind: BedrockBatchRecordKind,
+ ) -> Mapping[str, Any]:
+ """
+ Normalize a non-embedding batch body to the Chat Completions shape the
+ per-provider Bedrock transformations expect.
+ """
+ match record_kind:
+ case BedrockBatchRecordKind.TEXT_COMPLETION:
+ return BedrockFilesConfig._transform_text_completion_body_to_chat_body(openai_request_body)
+ case BedrockBatchRecordKind.RESPONSES:
+ return BedrockFilesConfig._transform_responses_body_to_chat_body(openai_request_body)
+ case BedrockBatchRecordKind.CHAT:
+ return openai_request_body
+ case BedrockBatchRecordKind.EMBEDDING:
+ raise ValueError("Embedding batch records do not have a chat-completion equivalent")
+
def _map_openai_to_bedrock_params(
self,
- openai_request_body: dict[str, Any],
+ openai_request_body: Mapping[str, Any],
provider: str | None = None,
) -> dict[str, Any]:
"""
@@ -659,14 +775,18 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig):
provider = self.get_bedrock_invoke_provider(model)
# Route to the embedding transformer when the OpenAI batch line
- # targets /v1/embeddings; otherwise fall back to the existing
- # chat-completion path. We branch here (rather than inside
+ # targets /v1/embeddings; every other endpoint shape is normalized
+ # to chat completions first. We branch here (rather than inside
# `_map_openai_to_bedrock_params`) so the chat helper keeps its
# narrow contract and the embedding helper can evolve independently.
- if self._is_embedding_record(_openai_jsonl_content):
+ record_kind = self._classify_batch_record(_openai_jsonl_content)
+ if record_kind is BedrockBatchRecordKind.EMBEDDING:
model_input = self._map_openai_embedding_to_bedrock_params(openai_request_body=openai_body)
else:
- model_input = self._map_openai_to_bedrock_params(openai_request_body=openai_body, provider=provider)
+ model_input = self._map_openai_to_bedrock_params(
+ openai_request_body=self._transform_batch_body_to_chat_body(openai_body, record_kind),
+ provider=provider,
+ )
# Create Bedrock batch record
record_id = _openai_jsonl_content.get("custom_id", f"CALL{str(idx).zfill(7)}")
diff --git a/litellm/types/llms/bedrock.py b/litellm/types/llms/bedrock.py
index d9f8229dbed..f7a4682cb03 100644
--- a/litellm/types/llms/bedrock.py
+++ b/litellm/types/llms/bedrock.py
@@ -1,4 +1,5 @@
import json
+from enum import Enum
from typing import Any, Dict, List, Literal, Optional, Union
from typing_extensions import TYPE_CHECKING, Required, TypedDict, override
@@ -1100,3 +1101,17 @@ class BedrockInvokeAnthropicMessagesRequest(TypedDict, total=False):
# supported subset and strips the field entirely when nothing remains, so
# other edit types (e.g. `clear_thinking_20251015`) never reach Bedrock.
context_management: dict
+
+
+class BedrockBatchRecordKind(Enum):
+ """
+ Which OpenAI endpoint shape a line of a Bedrock managed-batch JSONL file
+ carries. Bedrock batch `modelInput` is always the model's InvokeModel /
+ Converse body, so every non-embedding shape is normalized to Chat
+ Completions before being handed to the per-provider transformation.
+ """
+
+ CHAT = "chat"
+ TEXT_COMPLETION = "text_completion"
+ RESPONSES = "responses"
+ EMBEDDING = "embedding"
diff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
index 1b1db634ed2..d10ccf77703 100644
--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
@@ -721,3 +721,46 @@ class TestUnpackLegacyDefs:
out = unpack_legacy_defs(schema)
assert "components" not in out
assert out["properties"]["r0"]["properties"]["p0"] == {"type": "string"}
+
+
+class TestTextCompletionPromptToMessages:
+ """`/v1/completions` prompt wrapping, shared by the real-time and batch paths."""
+
+ def test_string_prompt_becomes_single_user_message(self):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ text_completion_prompt_to_messages,
+ )
+
+ assert text_completion_prompt_to_messages("summarize this") == (
+ {"role": "user", "content": "summarize this"},
+ )
+
+ def test_list_of_strings_becomes_one_message_each(self):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ text_completion_prompt_to_messages,
+ )
+
+ assert text_completion_prompt_to_messages(["first", "second"]) == (
+ {"role": "user", "content": "first"},
+ {"role": "user", "content": "second"},
+ )
+
+ @pytest.mark.parametrize(
+ "prompt",
+ [
+ [1, 2, 3],
+ [[1, 2], [3, 4]],
+ ["ok", 7],
+ [],
+ "",
+ None,
+ {"role": "user"},
+ ],
+ )
+ def test_unsupported_prompt_shapes_raise(self, prompt):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ text_completion_prompt_to_messages,
+ )
+
+ with pytest.raises(ValueError, match="non-empty string or a non-empty list of strings"):
+ text_completion_prompt_to_messages(prompt)
diff --git a/tests/test_litellm/llms/bedrock/files/test_bedrock_files_transformation.py b/tests/test_litellm/llms/bedrock/files/test_bedrock_files_transformation.py
index c548fe53e15..87b03b02e1a 100644
--- a/tests/test_litellm/llms/bedrock/files/test_bedrock_files_transformation.py
+++ b/tests/test_litellm/llms/bedrock/files/test_bedrock_files_transformation.py
@@ -1072,21 +1072,34 @@ class TestBedrockFilesEmbeddingTransformation:
is None
)
- def test_is_embedding_record_helper(self):
- """Helper detects embeddings via `url` first, then by body shape."""
+ def test_classify_batch_record_helper(self):
+ """Helper classifies by `url` first, then by body shape."""
from litellm.llms.bedrock.files.transformation import BedrockFilesConfig
+ from litellm.types.llms.bedrock import BedrockBatchRecordKind
- assert BedrockFilesConfig._is_embedding_record(
- {"url": "/v1/embeddings", "body": {"input": "x"}}
+ assert (
+ BedrockFilesConfig._classify_batch_record(
+ {"url": "/v1/embeddings", "body": {"input": "x"}}
+ )
+ is BedrockBatchRecordKind.EMBEDDING
)
# body-only fallback
- assert BedrockFilesConfig._is_embedding_record({"body": {"input": "x"}})
+ assert (
+ BedrockFilesConfig._classify_batch_record({"body": {"input": "x"}})
+ is BedrockBatchRecordKind.EMBEDDING
+ )
# chat shape
- assert not BedrockFilesConfig._is_embedding_record(
- {"url": "/v1/chat/completions", "body": {"messages": []}}
+ assert (
+ BedrockFilesConfig._classify_batch_record(
+ {"url": "/v1/chat/completions", "body": {"messages": []}}
+ )
+ is BedrockBatchRecordKind.CHAT
+ )
+ # ambiguous body without any recognized key is treated as chat
+ assert (
+ BedrockFilesConfig._classify_batch_record({"body": {}})
+ is BedrockBatchRecordKind.CHAT
)
- # ambiguous body without `input` is treated as not-embedding
- assert not BedrockFilesConfig._is_embedding_record({"body": {}})
def test_explicit_chat_url_with_input_body_short_circuits_to_chat(self):
"""Explicit url=/v1/chat/completions wins even if body looks like embedding.
@@ -1097,15 +1110,20 @@ class TestBedrockFilesEmbeddingTransformation:
"""
from litellm.llms.bedrock.files.transformation import BedrockFilesConfig
+ from litellm.types.llms.bedrock import BedrockBatchRecordKind
+
# Direct helper assertion
- assert not BedrockFilesConfig._is_embedding_record(
- {
- "url": "/v1/chat/completions",
- "body": {
- "model": "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
- "input": "this would mis-route under the old precedence",
- },
- }
+ assert (
+ BedrockFilesConfig._classify_batch_record(
+ {
+ "url": "/v1/chat/completions",
+ "body": {
+ "model": "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
+ "input": "this would mis-route under the old precedence",
+ },
+ }
+ )
+ is BedrockBatchRecordKind.CHAT
)
# End-to-end: a record like this routes through the chat path. We
@@ -1164,19 +1182,300 @@ class TestBedrockFilesEmbeddingTransformation:
with pytest.raises(ValueError, match="must be a string"):
BedrockFilesConfig._coerce_embedding_input_to_string({"unsupported": True})
- def test_other_non_embedding_urls_route_to_chat(self):
- """Any non-/v1/embeddings url short-circuits to chat path."""
+ def test_other_non_embedding_urls_do_not_route_to_embeddings(self):
+ """An `input` body only means "embedding" when the url says so."""
from litellm.llms.bedrock.files.transformation import BedrockFilesConfig
+ from litellm.types.llms.bedrock import BedrockBatchRecordKind
# /v1/completions (legacy completions endpoint)
- assert not BedrockFilesConfig._is_embedding_record(
- {"url": "/v1/completions", "body": {"input": "x"}}
+ assert (
+ BedrockFilesConfig._classify_batch_record(
+ {"url": "/v1/completions", "body": {"input": "x"}}
+ )
+ is BedrockBatchRecordKind.TEXT_COMPLETION
+ )
+ assert (
+ BedrockFilesConfig._classify_batch_record(
+ {"url": "/v1/responses", "body": {"input": "x"}}
+ )
+ is BedrockBatchRecordKind.RESPONSES
)
# Arbitrary unknown url - caller's explicit signal still wins
- assert not BedrockFilesConfig._is_embedding_record(
- {"url": "/v1/responses", "body": {"input": "x"}}
+ assert (
+ BedrockFilesConfig._classify_batch_record(
+ {"url": "/v1/moderations", "body": {"input": "x"}}
+ )
+ is BedrockBatchRecordKind.CHAT
+ )
+
+
+class TestBedrockBatchNonChatEndpointRecords:
+ """`/v1/completions` and `/v1/responses` JSONL records (issue #35639).
+
+ Bedrock batch `modelInput` is always the model's InvokeModel/Converse body,
+ so a record shaped for another OpenAI endpoint has to be normalized to chat
+ completions first. Before this normalization every record below either
+ raised `BadRequestError` at `POST /v1/files` (Anthropic, Nova) or silently
+ shipped an empty `messages` list to AWS (passthrough providers).
+ """
+
+ ANTHROPIC_MODEL = "bedrock/us.anthropic.claude-sonnet-4-6"
+ NOVA_MODEL = "bedrock/us.amazon.nova-pro-v1:0"
+ PASSTHROUGH_MODEL = "bedrock/openai.gpt-oss-120b-1:0"
+
+ def _transform(self, record: dict) -> dict:
+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig
+
+ result = BedrockFilesConfig()._transform_openai_jsonl_content_to_bedrock_jsonl_content([record])
+ assert len(result) == 1
+ assert result[0]["recordId"] == record["custom_id"]
+ return result[0]["modelInput"]
+
+ def test_anthropic_text_completion_record_wraps_prompt(self):
+ model_input = self._transform(
+ {
+ "custom_id": "1",
+ "method": "POST",
+ "url": "/v1/completions",
+ "body": {
+ "model": self.ANTHROPIC_MODEL,
+ "prompt": "Summarize the following call transcript",
+ "max_tokens": 64,
+ },
+ }
+ )
+
+ assert model_input == {
+ "messages": [
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "Summarize the following call transcript"}],
+ }
+ ],
+ "max_tokens": 64,
+ "anthropic_version": "bedrock-2023-05-31",
+ }
+
+ def test_anthropic_text_completion_record_keeps_every_prompt_in_a_list(self):
+ model_input = self._transform(
+ {
+ "custom_id": "2",
+ "method": "POST",
+ "url": "/v1/completions",
+ "body": {
+ "model": self.ANTHROPIC_MODEL,
+ "prompt": ["first prompt", "second prompt"],
+ "max_tokens": 8,
+ },
+ }
)
+ # Consecutive user messages are merged by the Anthropic transform, the
+ # same way they are on the real-time path.
+ assert model_input["messages"] == [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "first prompt"},
+ {"type": "text", "text": "second prompt"},
+ ],
+ }
+ ]
+ assert "prompt" not in model_input
+
+ def test_anthropic_responses_record_wraps_string_input(self):
+ model_input = self._transform(
+ {
+ "custom_id": "3",
+ "method": "POST",
+ "url": "/v1/responses",
+ "body": {
+ "model": self.ANTHROPIC_MODEL,
+ "input": "hi",
+ "max_output_tokens": 16,
+ },
+ }
+ )
+
+ assert model_input == {
+ "messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}],
+ "max_tokens": 16,
+ "anthropic_version": "bedrock-2023-05-31",
+ }
+ assert "tools" not in model_input, "an empty tools array must not be shipped to Bedrock"
+
+ def test_anthropic_responses_record_maps_instructions_and_input_items(self):
+ """The Responses-specific params go through the same bridge as real time."""
+ model_input = self._transform(
+ {
+ "custom_id": "4",
+ "method": "POST",
+ "url": "/v1/responses",
+ "body": {
+ "model": self.ANTHROPIC_MODEL,
+ "instructions": "be terse",
+ "input": [
+ {"role": "user", "content": "what is 2+2?"},
+ {"role": "assistant", "content": "4"},
+ {"role": "user", "content": "and 3+3?"},
+ ],
+ "max_output_tokens": 32,
+ "temperature": 0.2,
+ },
+ }
+ )
+
+ assert model_input["system"] == [{"type": "text", "text": "be terse"}]
+ assert model_input["max_tokens"] == 32
+ assert model_input["temperature"] == 0.2
+ assert [message["role"] for message in model_input["messages"]] == [
+ "user",
+ "assistant",
+ "user",
+ ]
+ assert model_input["messages"][-1]["content"] == [{"type": "text", "text": "and 3+3?"}]
+ assert "input" not in model_input
+ assert "max_output_tokens" not in model_input
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ {"prompt": "hi"},
+ {"input": "hi"},
+ ],
+ ids=["prompt", "input"],
+ )
+ def test_nova_converse_record_wraps_prompt_and_input(self, body):
+ url = "/v1/completions" if "prompt" in body else "/v1/responses"
+ model_input = self._transform(
+ {
+ "custom_id": "5",
+ "method": "POST",
+ "url": url,
+ "body": {"model": self.NOVA_MODEL, **body},
+ }
+ )
+
+ assert model_input["messages"] == [{"role": "user", "content": [{"text": "hi"}]}]
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ {"prompt": "hi"},
+ {"input": "hi"},
+ ],
+ ids=["prompt", "input"],
+ )
+ def test_passthrough_provider_record_no_longer_emits_empty_messages(self, body):
+ """The passthrough branch used to emit `{"messages": [], "prompt": ...}`.
+
+ That shape is accepted by `POST /v1/files`, so the whole batch job was
+ submitted to AWS and only failed there.
+ """
+ url = "/v1/completions" if "prompt" in body else "/v1/responses"
+ model_input = self._transform(
+ {
+ "custom_id": "6",
+ "method": "POST",
+ "url": url,
+ "body": {"model": self.PASSTHROUGH_MODEL, **body},
+ }
+ )
+
+ # Asserted on the serialized form, since the passthrough branch hands
+ # `messages` straight to S3 without a per-provider transform.
+ assert json.loads(json.dumps(model_input)) == {"messages": [{"role": "user", "content": "hi"}]}
+
+ def test_mixed_endpoints_in_one_file_keep_their_own_shapes(self):
+ from litellm.llms.bedrock.files.transformation import BedrockFilesConfig
+
+ result = BedrockFilesConfig()._transform_openai_jsonl_content_to_bedrock_jsonl_content(
+ [
+ {
+ "custom_id": "chat",
+ "url": "/v1/chat/completions",
+ "body": {
+ "model": self.ANTHROPIC_MODEL,
+ "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 4,
+ },
+ },
+ {
+ "custom_id": "text",
+ "url": "/v1/completions",
+ "body": {"model": self.ANTHROPIC_MODEL, "prompt": "hi", "max_tokens": 4},
+ },
+ {
+ "custom_id": "responses",
+ "url": "/v1/responses",
+ "body": {"model": self.ANTHROPIC_MODEL, "input": "hi", "max_output_tokens": 4},
+ },
+ {
+ "custom_id": "embedding",
+ "url": "/v1/embeddings",
+ "body": {"model": "bedrock/amazon.titan-embed-text-v2:0", "input": "hi"},
+ },
+ ]
+ )
+
+ assert [record["recordId"] for record in result] == [
+ "chat",
+ "text",
+ "responses",
+ "embedding",
+ ]
+ for record in result[:3]:
+ assert record["modelInput"]["messages"] == [
+ {"role": "user", "content": [{"type": "text", "text": "hi"}]}
+ ]
+ assert result[3]["modelInput"] == {"inputText": "hi"}
+
+ @pytest.mark.parametrize(
+ ("url", "expected_message"),
+ [
+ ("/v1/completions", "missing required `prompt` field"),
+ ("/v1/responses", "missing required `input` field"),
+ ],
+ )
+ def test_missing_required_field_raises_actionable_error(self, url, expected_message):
+ with pytest.raises(ValueError, match=expected_message):
+ self._transform(
+ {
+ "custom_id": "7",
+ "method": "POST",
+ "url": url,
+ "body": {"model": self.ANTHROPIC_MODEL, "max_tokens": 4},
+ }
+ )
+
+ def test_prompt_body_without_url_is_still_wrapped(self):
+ """A record can omit `url`; the body shape then decides."""
+ model_input = self._transform(
+ {
+ "custom_id": "8",
+ "body": {"model": self.ANTHROPIC_MODEL, "prompt": "hi", "max_tokens": 4},
+ }
+ )
+
+ assert model_input["messages"] == [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]
+
+ def test_messages_win_over_prompt_when_url_is_absent(self):
+ model_input = self._transform(
+ {
+ "custom_id": "9",
+ "body": {
+ "model": self.ANTHROPIC_MODEL,
+ "messages": [{"role": "user", "content": "from messages"}],
+ "prompt": "from prompt",
+ "max_tokens": 4,
+ },
+ }
+ )
+
+ assert model_input["messages"] == [
+ {"role": "user", "content": [{"type": "text", "text": "from messages"}]}
+ ]
+
class TestBedrockFileContentTransformation:
"""SigV4-signed S3 GetObject retrieval of Bedrock batch output files."""