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]

Merge branch 'litellm_internal_staging' into litellm_bedrock_batch_non_chat_records

mateo-berri7c2b7097276e
diff --cc litellm/litellm_core_utils/prompt_templates/common_utils.py
index 777ba398d5a,3f43fe38f5e..c596e821ce9
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@@ -6,14 -6,17 +6,17 @@@ import i
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 (
- TYPE_CHECKING,
- Any,
- Literal,
- cast,
+ from typing import TYPE_CHECKING, Any, Final, Literal, cast
+
+ from openai.types.chat.chat_completion_custom_tool_param import (
+ CustomFormatGrammar,
+ CustomFormatGrammarGrammar,
+ )
+ from openai.types.shared_params.custom_tool_input_format import (
+ Grammar as ResponsesGrammarFormat,
)
import litellm
@@@ -1742,23 -1775,3 +1775,24 @@@ def split_concatenated_json_objects(raw
idx = end_idx
return results
+
+
- def text_completion_prompt_to_messages(prompt: str | Sequence[str]) -> tuple[AllMessageValues, ...]:
++def text_completion_prompt_to_messages(prompt: object) -> 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.
+ """
++ prompt_type_name: Final = type(prompt).__name__
+ 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__}."
- )
++ entries: Final = cast("Sequence[object]", prompt) if isinstance(prompt, Sequence) else ()
++ string_entries: Final = tuple(entry for entry in entries if isinstance(entry, str) and entry)
++ if string_entries and len(string_entries) == len(entries):
++ return tuple(ChatCompletionUserMessage(role="user", content=entry) for entry in string_entries)
++ raise ValueError(f"`prompt` must be a non-empty string or a non-empty list of strings. Got: {prompt_type_name}.")
diff --cc litellm/llms/bedrock/files/transformation.py
index baa2630556a,399f11a94cf..90f9b47ad6a
--- a/litellm/llms/bedrock/files/transformation.py
+++ b/litellm/llms/bedrock/files/transformation.py
@@@ -2,13 -2,9 +2,11 @@@ import base6
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,
- )
+ from typing import Any, Final
from urllib.parse import unquote
import httpx
@@@ -62,29 -52,9 +60,29 @@@ from ..common_utils import BedrockErro
# `transform_file_content_request` to `validate_environment` (the only hook
# the shared file-content HTTP handler exposes for setting request headers).
# Same pattern as the `upload_url` handoff in `transform_create_file_request`.
- S3_SIGNED_GET_HEADERS_PARAM = "_s3_signed_get_headers"
+ S3_SIGNED_GET_HEADERS_PARAM: Final = "_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."""
@@@ -333,55 -303,41 +331,55 @@@ class BedrockFilesConfig(BaseAWSLLM, Ba
# 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: Final = openai_jsonl_record.get("url")
- if url == BedrockFilesConfig.OPENAI_EMBEDDINGS_URL:
- return True
- if url:
- return False
- body: Final = 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")
++ body: Final = 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
diff --cc litellm/types/llms/bedrock.py
index f7a4682cb03,1bf8ba513c2..5665aa3277a
--- a/litellm/types/llms/bedrock.py
+++ b/litellm/types/llms/bedrock.py
@@@ -1,8 -1,7 +1,8 @@@
import json
+from enum import Enum
- from typing import Any, Dict, List, Literal, Optional, Union
+ from typing import TYPE_CHECKING, Any, Final, Literal
- from typing_extensions import TYPE_CHECKING, Required, TypedDict, override
+ from typing_extensions import Required, TypedDict, override
from .openai import ChatCompletionToolCallChunk
diff --cc tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
index d10ccf77703,3728cc80323..b3956823dc1
--- 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
@@@ -723,44 -723,46 +723,89 @@@ class TestUnpackLegacyDefs
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)
++
++
+ class TestCustomToolFormatShapeConversion:
+ def test_flat_grammar_to_chat_shape(self):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ convert_custom_tool_format_to_chat_shape,
+ )
+
+ assert convert_custom_tool_format_to_chat_shape(
+ {"type": "grammar", "definition": "start: patch", "syntax": "lark"}
+ ) == {"type": "grammar", "grammar": {"definition": "start: patch", "syntax": "lark"}}
+
+ def test_nested_grammar_to_responses_shape(self):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ convert_custom_tool_format_to_responses_shape,
+ )
+
+ assert convert_custom_tool_format_to_responses_shape(
+ {"type": "grammar", "grammar": {"definition": "start: patch", "syntax": "regex"}}
+ ) == {"type": "grammar", "definition": "start: patch", "syntax": "regex"}
+
+ def test_both_directions_are_idempotent_and_pass_text_through(self):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ convert_custom_tool_format_to_chat_shape,
+ convert_custom_tool_format_to_responses_shape,
+ )
+
+ flat = {"type": "grammar", "definition": "d", "syntax": "lark"}
+ nested = {"type": "grammar", "grammar": {"definition": "d", "syntax": "lark"}}
+ text = {"type": "text"}
+ assert convert_custom_tool_format_to_chat_shape(nested) == nested
+ assert convert_custom_tool_format_to_responses_shape(flat) == flat
+ assert convert_custom_tool_format_to_chat_shape(text) == text
+ assert convert_custom_tool_format_to_responses_shape(text) == text
+ assert convert_custom_tool_format_to_chat_shape(convert_custom_tool_format_to_responses_shape(nested)) == nested
+
+ def test_unrecognized_formats_pass_through(self):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ convert_custom_tool_format_to_chat_shape,
+ convert_custom_tool_format_to_responses_shape,
+ )
+
+ for weird in ({}, {"type": "grammar"}, {"type": "future_format", "x": 1}):
+ assert convert_custom_tool_format_to_chat_shape(dict(weird)) in (weird, {"type": "grammar", "grammar": {}})
+ assert convert_custom_tool_format_to_responses_shape(dict(weird)) == weird