Skip to content
42 changes: 24 additions & 18 deletions litellm/litellm_core_utils/streaming_chunk_builder_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,13 @@ class _ToolCallDelta(TypedDict, total=False):


class _ToolCallChoice(TypedDict, total=False):
index: ReadOnly[int]
delta: ReadOnly[_ToolCallDelta]


_ToolCallKey: TypeAlias = tuple[int, int]


class _ToolCallChunk(TypedDict):
choices: ReadOnly[Sequence[_ToolCallChoice]]

Expand Down Expand Up @@ -417,40 +421,41 @@ def build_base_response(self, chunks: Sequence["_BaseChunk"]) -> ModelResponse:
@staticmethod
def _iter_tool_call_fragments(
tool_call_chunks: Sequence["_ToolCallChunk"],
) -> Iterator[tuple[int, str, str]]:
) -> Iterator[tuple[_ToolCallKey, str, str]]:
for chunk in tool_call_chunks:
for choice in chunk["choices"]:
delta = choice.get("delta")
if not delta:
continue
for tool_call in delta.get("tool_calls", ()):
choice_index = choice.get("index", 0)
for tool_call in delta.get("tool_calls") or ():
if not tool_call:
continue
if isinstance(tool_call, dict):
index = tool_call.get("index", 0)
key = (choice_index, tool_call.get("index", 0))
function = tool_call.get("function")
if isinstance(function, dict):
if fragment_arguments := function.get("arguments"):
yield index, "arguments", fragment_arguments
yield key, "arguments", fragment_arguments
elif function_arguments := getattr(function, "arguments", None):
yield index, "arguments", function_arguments
yield key, "arguments", function_arguments
custom = tool_call.get("custom")
if isinstance(custom, dict) and (custom_input := custom.get("input")):
yield index, "custom_input", custom_input
yield key, "custom_input", custom_input
else:
index = getattr(tool_call, "index", 0)
key = (choice_index, getattr(tool_call, "index", 0))
function = getattr(tool_call, "function", None)
if object_arguments := getattr(function, "arguments", None):
yield index, "arguments", object_arguments
yield key, "arguments", object_arguments
custom = getattr(tool_call, "custom", None)
if object_custom_input := getattr(custom, "input", None):
yield index, "custom_input", object_custom_input
yield key, "custom_input", object_custom_input

@staticmethod
def _join_fragments_by_index_and_field(
fragment_records: Iterator[tuple[int, str, str]],
) -> Mapping[tuple[int, str], str]:
def group_key(record: tuple[int, str, str]) -> tuple[int, str]:
def _join_fragments_by_key_and_field(
fragment_records: Iterator[tuple[_ToolCallKey, str, str]],
) -> Mapping[tuple[_ToolCallKey, str], str]:
def group_key(record: tuple[_ToolCallKey, str, str]) -> tuple[_ToolCallKey, str]:
return record[0], record[1]

return MappingProxyType(
Expand All @@ -468,13 +473,14 @@ def get_combined_tool_content(
tool_calls_list: list[
ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall
] = [] # mutable-ok: see return type
tool_call_map: Final[dict[int, dict[str, Any]]] = {} # Map to store tool calls by index
tool_call_map: Final[dict[_ToolCallKey, dict[str, Any]]] = {} # Map to store tool calls by choice and index
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

for chunk in tool_call_chunks:
choices = chunk["choices"]
for choice in choices:
delta = choice.get("delta", {})
tool_calls = delta.get("tool_calls", [])
tool_calls = delta.get("tool_calls") or ()
choice_index = choice.get("index", 0)

for tool_call in tool_calls:
# Handle both dict and object formats
Expand All @@ -496,9 +502,9 @@ def get_combined_tool_content(

# Get index (handle both dict and object)
if isinstance(tool_call, dict):
index = tool_call.get("index", 0)
index = (choice_index, tool_call.get("index", 0))
else:
index = getattr(tool_call, "index", 0)
index = (choice_index, getattr(tool_call, "index", 0))

if index not in tool_call_map:
tool_call_map[index] = {
Expand Down Expand Up @@ -573,7 +579,7 @@ def get_combined_tool_content(
if isinstance(provider_fields, dict):
merged_provider_fields.update(provider_fields)

joined_fragments: Final = self._join_fragments_by_index_and_field(
joined_fragments: Final = self._join_fragments_by_key_and_field(
self._iter_tool_call_fragments(tool_call_chunks)
)

Expand Down
10 changes: 8 additions & 2 deletions litellm/llms/anthropic/chat/guardrail_translation/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1457,7 +1457,9 @@ def is_text_delta(event: Mapping[str, object]) -> bool:
if not any(is_text_delta(event) for item in responses_so_far for event in cls._iter_sse_events(item)):
from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite

raise UndeliverableStreamRewrite(guardrail_name)
raise UndeliverableStreamRewrite(
guardrail_name, "the buffered stream carries no text_delta event to land the text rewrite on"
)
replacements: Final = chain((rewritten_text,), repeat(""))

def rewrite_text_delta(event: Mapping[str, object]) -> _SSEFieldRewrite | None:
Expand Down Expand Up @@ -1498,7 +1500,11 @@ def _write_ended_stream_tool_call_rewrites(
if len(block_indices) != len(post_guardrail_tool_calls):
from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite

raise UndeliverableStreamRewrite(guardrail_name)
raise UndeliverableStreamRewrite(
guardrail_name,
f"the guardrail returned {len(post_guardrail_tool_calls)} tool calls for a stream that carried "
f"{len(block_indices)} tool_use blocks",
)
rewrites_by_block: Final = MappingProxyType(
{
index: after
Expand Down
16 changes: 14 additions & 2 deletions litellm/llms/openai/chat/guardrail_translation/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1169,10 +1169,22 @@ def _write_ended_stream_tool_call_rewrites(
choice.index for response in responses_so_far for choice in response.choices
)
fragments_by_tool_call: Final = self._function_tool_call_fragments(responses_so_far)
if len(stream_choice_indices) != 1 or len(fragments_by_tool_call) != len(post_guardrail_tool_calls):
if len(stream_choice_indices) != 1:
from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite

raise UndeliverableStreamRewrite(guardrail_name)
raise UndeliverableStreamRewrite(
guardrail_name,
f"the stream carries {len(stream_choice_indices)} choices and tool-call rewrites are only written "
"back on single-choice streams",
)
if len(fragments_by_tool_call) != len(post_guardrail_tool_calls):
from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite

raise UndeliverableStreamRewrite(
guardrail_name,
f"the guardrail returned {len(post_guardrail_tool_calls)} tool calls for a stream that carried "
f"{len(fragments_by_tool_call)}",
)
for before, (name, arguments), fragments in zip(
pre_guardrail_tool_calls, post_guardrail_tool_calls, fragments_by_tool_call
):
Expand Down
52 changes: 43 additions & 9 deletions litellm/llms/openai/responses/guardrail_translation/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,34 @@ def _tool_call_rewrite(before: _ToolCallShape, after: _ToolCallShape) -> _ToolCa
return _ToolCallShape(name=after.name if after.name != before.name else None, arguments=after.arguments)


def _undeliverable_tool_call_rewrite_reason(
call_ids: Sequence[str],
tool_call_item_count: int,
post_guardrail_tool_call_count: int,
unresolved_argument_event: bool,
rewritten_call_ids: frozenset[str],
event_call_ids: frozenset[str],
) -> str | None:
if len(call_ids) != tool_call_item_count:
return (
f"{tool_call_item_count - len(call_ids)} of the stream's {tool_call_item_count} tool call items "
"carry no call_id"
)
if len(frozenset(call_ids)) != len(call_ids):
return "the stream's tool call items repeat a call_id"
if len(call_ids) != post_guardrail_tool_call_count:
return (
f"the guardrail returned {post_guardrail_tool_call_count} tool calls for the stream's "
f"{len(call_ids)} tool call items"
)
if unresolved_argument_event:
return "a tool call argument event names an item_id that no output_item event introduced"
missing_call_ids: Final = sorted(rewritten_call_ids - event_call_ids)
if missing_call_ids:
return f"no stream event carries the rewritten call_id {', '.join(missing_call_ids)}"
return None


class ResponseOutputEnvelope(TypedDict, total=False):
"""Dict form of a Responses API response, as far as guardrail write-back reads it."""

Expand Down Expand Up @@ -999,7 +1027,11 @@ def _spread_text_rewrite_over_stream_events(
):
from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite

raise UndeliverableStreamRewrite(guardrail_name)
raise UndeliverableStreamRewrite(
guardrail_name,
"the scanned text events are not all output_text deltas with an integer output_index and "
"content_index, so the text rewrite has nowhere to land",
)
self._sync_stream_events_with_rewrites(
stream_events=stream_events,
rewrites_by_position=MappingProxyType(dict(zip(placeable_positions, chain((rewritten_text,), repeat(""))))),
Expand Down Expand Up @@ -1106,16 +1138,18 @@ def _deliver_ended_stream_tool_call_rewrites(
call_id is None and stream_item_field(event, "type") in _TOOL_CALL_PAYLOAD_EVENT_TYPES
for event, call_id in zip(stream_events, event_call_ids)
)
if (
len(call_ids) != len(tool_call_items)
or len(frozenset(call_ids)) != len(call_ids)
or len(call_ids) != len(post_guardrail_tool_calls)
or unresolved_argument_event
or not rewrites_by_call_id.keys() <= frozenset(event_call_ids)
):
undeliverable_reason: Final = _undeliverable_tool_call_rewrite_reason(
call_ids=call_ids,
tool_call_item_count=len(tool_call_items),
post_guardrail_tool_call_count=len(post_guardrail_tool_calls),
unresolved_argument_event=unresolved_argument_event,
rewritten_call_ids=frozenset(rewrites_by_call_id),
event_call_ids=frozenset(call_id for call_id in event_call_ids if call_id is not None),
)
if undeliverable_reason is not None:
from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite

raise UndeliverableStreamRewrite(guardrail_name)
raise UndeliverableStreamRewrite(guardrail_name, undeliverable_reason)
for output_item, rewrite in (
(output_item, rewrites_by_call_id[call_id])
for output_item, call_id in zip(tool_call_items, call_ids)
Expand Down
66 changes: 40 additions & 26 deletions litellm/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8759,6 +8759,39 @@ def _stamp_streaming_usage_cost(usage: Usage, response: ModelResponse, logging_o
setattr(usage, "cost", computed_cost)


_NON_TEXT_DELTA_FIELDS: Final = (
"tool_calls",
"function_call",
"reasoning_content",
"thinking_blocks",
"annotations",
"audio",
"images",
"provider_specific_fields",
)


def _stream_choice_delta(choice: object) -> Mapping[str, object]:
delta: Final = choice.get("delta", {}) if isinstance(choice, dict) else getattr(choice, "delta", {})
if isinstance(delta, Mapping):
return delta
if isinstance(delta, BaseModel):
return delta.model_dump()
return {}


def _delta_carries_more_than_text(delta: Mapping[str, object]) -> bool:
return any(delta.get(field) is not None for field in _NON_TEXT_DELTA_FIELDS)


def _simple_text_part(choices: Sequence[object]) -> str | None:
deltas: Final = tuple(_stream_choice_delta(choice) for choice in choices)
if any(_delta_carries_more_than_text(delta) for delta in deltas):
return None
content: Final = deltas[0].get("content")
return content if isinstance(content, str) else ""


def stream_chunk_builder(
chunks: list,
messages: Sequence | None = None,
Expand Down Expand Up @@ -8803,31 +8836,11 @@ def stream_chunk_builder(
if not chunk.get("choices"):
continue

choice = chunk["choices"][0]
delta_obj = choice.get("delta", {}) if isinstance(choice, dict) else getattr(choice, "delta", {})
if isinstance(delta_obj, dict):
delta = delta_obj
elif hasattr(delta_obj, "model_dump"):
delta = cast(dict[str, Any], delta_obj.model_dump())
else:
delta = {}

if (
delta.get("tool_calls") is not None
or delta.get("function_call") is not None
or delta.get("reasoning_content") is not None
or delta.get("thinking_blocks") is not None
or delta.get("annotations") is not None
or delta.get("audio") is not None
or delta.get("images") is not None
or delta.get("provider_specific_fields") is not None
):
if (part := _simple_text_part(chunk["choices"])) is None:
is_simple_text_stream = False
break

content = delta.get("content")
if isinstance(content, str) and content:
simple_content_parts.append(content)
if part:
simple_content_parts.append(part)

if is_simple_text_stream:
if simple_content_parts:
Expand Down Expand Up @@ -8864,9 +8877,10 @@ def stream_chunk_builder(
tool_call_chunks: Final = [
chunk
for chunk in chunks
if chunk.get("choices")
and "tool_calls" in chunk["choices"][0]["delta"]
and chunk["choices"][0]["delta"]["tool_calls"] is not None
if any(
"tool_calls" in choice["delta"] and choice["delta"]["tool_calls"] is not None
for choice in chunk.get("choices") or ()
)
]

if len(tool_call_chunks) > 0:
Expand Down
2 changes: 1 addition & 1 deletion litellm/proxy/_lazy_openapi_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"a2a": {
"components": {
Expand Down Expand Up @@ -19632,7 +19632,7 @@
}
}
},
"description": "\n Unified rate-limit error.\n\n Every rate-limit condition surfaced by litellm \u2014 whether it originated from\n an upstream LLM provider, a vendor batch endpoint, or one of litellm's own\n proxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,\n max-iterations, etc.) \u2014 is raised as an instance of this class.\n\n The :attr:`category` attribute lets callers distinguish the source. See\n :class:`RateLimitErrorCategory` for the available values.\n "
"description": "\nUnified rate-limit error.\n\nEvery rate-limit condition surfaced by litellm \u2014 whether it originated from\nan upstream LLM provider, a vendor batch endpoint, or one of litellm's own\nproxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,\nmax-iterations, etc.) \u2014 is raised as an instance of this class.\n\nThe :attr:`category` attribute lets callers distinguish the source. See\n:class:`RateLimitErrorCategory` for the available values.\n"
},
"500": {
"content": {
Expand Down
Loading
Loading