Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
07f32a2
fix(transformation): merge consecutive system and developer messages …
sowmy86 Sep 2, 2026
12699bd
fix(base_utils): keep later cache_control and billing metadata bounda…
sowmy86 Sep 2, 2026
eecea12
perf(base_utils): fold consecutive system messages in a single linear…
sowmy86 Sep 3, 2026
25186b1
fix(base_utils): hoist later developer messages into the leading syst…
mateo-berri Sep 5, 2026
356fae0
fix(openai): hoist later developer messages into one leading system m…
mateo-berri Sep 5, 2026
9b859f0
refactor(base_utils): fold each run of system messages in one pass
mateo-berri Sep 5, 2026
f500578
fix(base_utils): keep a closing developer message in place and hoist …
mateo-berri Sep 5, 2026
9820d2f
fix(base_utils): keep a closing developer message in place only after…
mateo-berri Sep 5, 2026
1d26ee5
Merge remote-tracking branch 'origin/litellm_internal_staging' into l…
mateo-berri Sep 5, 2026
20b3f1e
refactor(openai): reuse is_openai_backed_api_base for the hosted endp…
mateo-berri Sep 5, 2026
69fd884
test(base_utils): cover an empty system message inside a block-conten…
sowmy86 Sep 5, 2026
ea840eb
fix(openai): hoist developer messages for litellm_proxy and harden th…
mateo-berri Sep 5, 2026
4e3ea74
fix(litellm_proxy): keep the AllMessageValues import the transform si…
mateo-berri Sep 5, 2026
d5d70da
Merge branch 'litellm_internal_staging' of https://github.com/BerriAI…
mateo-berri Sep 8, 2026
22da54b
fix(fireworks_ai): hoist developer items after the first turn on the …
mateo-berri Sep 8, 2026
8b49a64
Merge branch 'litellm_internal_staging' of https://github.com/BerriAI…
mateo-berri Sep 10, 2026
08c1a1c
fix(transformation): carry the developer-message hoist onto main 9633…
mateo-berri Oct 20, 2026
e91fda4
chore: merge the pre-merge branch history (8b49a6438c) into the rebui…
mateo-berri Oct 20, 2026
88923bc
fix(transformation): join a lone plain text block as text when hoisti…
mateo-berri Oct 20, 2026
5c9607d
fix(transformation): hoist later developer messages only for models t…
mateo-berri Oct 20, 2026
08eac7b
fix(responses): fold later developer items into instructions on hoste…
mateo-berri Oct 20, 2026
dbc4d11
fix(llms): place developer messages only for models declared system-f…
mateo-berri Oct 20, 2026
0b99586
Merge remote-tracking branch 'origin/main' into litellm_lit_7019_hois…
mateo-berri Oct 20, 2026
a6a9910
fix(proxy): keep a closing developer message's cache mark when it is …
mateo-berri Oct 20, 2026
7c4ef7c
Merge remote-tracking branch 'origin/main' into litellm_lit_7019_hois…
mateo-berri Oct 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions litellm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,9 @@
BEDROCK_MIN_THINKING_BUDGET_TOKENS: Final = int(os.getenv("BEDROCK_MIN_THINKING_BUDGET_TOKENS", 1024))
# Anthropic's Messages API rejects thinking.budget_tokens < 1024.
ANTHROPIC_MIN_THINKING_BUDGET_TOKENS: Final = 1024
# System content with this prefix is Claude Code billing metadata; Anthropic-family
# transformations match on it to strip the block for providers that reject it.
ANTHROPIC_BILLING_METADATA_PREFIX: Final = "x-anthropic-billing-header:"
REPLICATE_POLLING_DELAY_SECONDS: Final = float(os.getenv("REPLICATE_POLLING_DELAY_SECONDS", 0.5))
DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS: Final = int(os.getenv("DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS", 4096))
DEFAULT_OCI_CHAT_MAX_TOKENS: Final = 4096
Expand Down
120 changes: 107 additions & 13 deletions litellm/llms/base_llm/base_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
import copy
import json
from abc import ABC, abstractmethod
from typing import Any, Final
from typing import Any, Final, TypeAlias

from openai.lib import _parsing, _pydantic
from pydantic import BaseModel
from pydantic import BaseModel, TypeAdapter

from litellm._logging import verbose_logger
from litellm.types.llms.openai import AllMessageValues, ChatCompletionToolCallChunk
from litellm.constants import ANTHROPIC_BILLING_METADATA_PREFIX
from litellm.types.llms.openai import AllMessageValues, ChatCompletionSystemMessage, ChatCompletionToolCallChunk
from litellm.types.utils import Message, ProviderSpecificModelInfo, TokenCountResponse


Expand Down Expand Up @@ -204,19 +205,112 @@ def type_to_response_format_param(
}


SystemMessageContent: TypeAlias = str | list[object]


def _content_blocks(content: SystemMessageContent) -> list[object]: # mutable-ok: block lists are the wire format
if not isinstance(content, str):
return content
return [{"type": "text", "text": content}] if content else [] # mutable-ok: text block for str content


def merge_system_message_contents(first: SystemMessageContent, second: SystemMessageContent) -> SystemMessageContent:
"""
Merge the contents of two consecutive system messages: str pairs join with a
blank line, anything involving block lists concatenates as blocks.
"""
if isinstance(first, str) and isinstance(second, str):
return f"{first}\n\n{second}" if first and second else first or second
return _content_blocks(first) + _content_blocks(second)


_system_content_adapter: Final = TypeAdapter[SystemMessageContent](SystemMessageContent)


def _system_content(message: ChatCompletionSystemMessage) -> SystemMessageContent:
return _system_content_adapter.validate_python(message["content"])


def _as_system_message(message: AllMessageValues) -> AllMessageValues:
if message["role"] != "developer":
return message
verbose_logger.debug(
"Translating developer role to system role for non-OpenAI providers."
) # ensure user knows what's happening with their input.
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
translated: Final[ChatCompletionSystemMessage] = {**message, "role": "system"}
return translated


def _merged_system_messages(
first: ChatCompletionSystemMessage, second: ChatCompletionSystemMessage
) -> ChatCompletionSystemMessage:
# A cache_control breakpoint covers the prefix up to its block, so the later
# message's marker is the one that still means the same thing after the merge.
merged: Final[ChatCompletionSystemMessage] = {
**first,
**second,
"role": "system",
"content": merge_system_message_contents(_system_content(first), _system_content(second)),
}
return merged


def _is_billing_metadata(message: ChatCompletionSystemMessage) -> bool:
content: Final = _system_content(message)
return isinstance(content, str) and content.startswith(ANTHROPIC_BILLING_METADATA_PREFIX)


def _fold_into_previous_system(
previous: AllMessageValues, message: AllMessageValues
) -> ChatCompletionSystemMessage | None:
if previous["role"] != "system" or message["role"] != "system":
return None
if _is_billing_metadata(previous) or _is_billing_metadata(message):
# Anthropic-family transformations strip billing metadata by matching the
# block's prefix; merging would hide the marker or the neighbor behind it.
return None
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
return _merged_system_messages(previous, message)


def _leading_system_block_length(messages: list[AllMessageValues]) -> int:
return next(
(index for index, message in enumerate(messages) if message["role"] not in ("system", "developer")),
len(messages),
)


def _hoist_developer_messages(messages: list[AllMessageValues]) -> tuple[AllMessageValues, ...]:
leading_length: Final = _leading_system_block_length(messages)
later: Final = messages[leading_length:]
hoisted: Final = tuple(message for message in later if message["role"] == "developer")
if hoisted:
verbose_logger.debug(
"Hoisting %d developer message(s) into the leading system block for non-OpenAI providers.",
len(hoisted),
)
return (
*messages[:leading_length],
*hoisted,
*(message for message in later if message["role"] != "developer"),
)


def map_developer_role_to_system_role(
messages: list[AllMessageValues],
) -> list[AllMessageValues]:
"""
Translate `developer` role to `system` role for non-OpenAI providers.
Translate `developer` role to `system` role for non-OpenAI providers, hoisting
developer messages that arrive after the first user turn into the leading system
block and merging that block into one message for backends that allow only one.
"""
new_messages: Final[list[AllMessageValues]] = []
for m in messages:
if m["role"] == "developer":
verbose_logger.debug(
"Translating developer role to system role for non-OpenAI providers."
) # ensure user knows what's happening with their input.
new_messages.append({"role": "system", "content": m["content"]})
# A single linear pass that folds into the last element in place: an
# immutable accumulator would copy the prefix on every step, which is O(n^2)
# in the number of messages and request size is not bounded by default.
merged: Final[list[AllMessageValues]] = [] # mutable-ok: linear-time accumulator
for message in map(_as_system_message, _hoist_developer_messages(messages)):
folded = _fold_into_previous_system(merged[-1], message) if merged else None
if folded is None:
merged.append(message)
else:
new_messages.append(m)
return new_messages
merged[-1] = folded
return merged
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
get_supported_openai_params,
)
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.base_llm.base_utils import SystemMessageContent, merge_system_message_contents
from litellm.responses.litellm_completion_transformation.session_handler import (
ResponsesSessionHandler,
)
Expand Down Expand Up @@ -401,28 +402,38 @@ def transform_responses_api_input_to_messages(
guardrail scanning) leave it off, because they need every piece of text
in the request to stay readable as message ``content``.
"""
messages: list[
AllMessageValues
| GenericChatCompletionMessage
| ChatCompletionMessageToolCall
| ChatCompletionResponseMessage
| Message
] = []
if responses_api_request.get("instructions"):
messages.append(
LiteLLMCompletionResponsesConfig.transform_instructions_to_system_message(
responses_api_request.get("instructions")
)
)

messages.extend(
input_messages: Final = (
LiteLLMCompletionResponsesConfig._transform_response_input_param_to_chat_completion_message(
input=input,
replay_reasoning=replay_reasoning,
)
)
instructions: Final = cast( # cast-ok: instructions is a str per the Responses API
"str | None", responses_api_request.get("instructions")
)
if not instructions:
return list(input_messages) # mutable-ok: widened copy for the declared return union

return messages
first_message: Final = input_messages[0] if input_messages else None
if isinstance(first_message, dict):
leading: Final = cast( # cast-ok: every dict message form carries role and content
"GenericChatCompletionMessage", first_message
)
if leading["role"] in ("system", "developer"):
merged_content: Final = merge_system_message_contents(
instructions,
cast("SystemMessageContent", leading["content"]), # cast-ok: content field is typed as a bare list
)
merged_first: Final = cast( # cast-ok: source message shape is kept, only content changes
"GenericChatCompletionMessage",
{**leading, "content": merged_content}, # mutable-ok: chat messages travel as plain dicts
)
return [merged_first, *input_messages[1:]] # mutable-ok: declared return type is a list

return [ # mutable-ok: declared return type is a list
LiteLLMCompletionResponsesConfig.transform_instructions_to_system_message(instructions),
*input_messages,
]

@staticmethod
async def async_responses_api_session_handler(
Expand Down
Loading
Loading