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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
chore: merge litellm_internal_staging into litellm_anthropic_fast_mode_speed_usage
Devin AIf0c3d8dcda0d
diff --cc litellm/litellm_core_utils/streaming_chunk_builder_utils.pyindex 5ceb64547a0,886ba6a3a18..5ab44d03520--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py@@@ -567,10 -728,8 +728,10 @@@ class ChunkProcessor# cache-creation count but drops the nested breakdown. prompt_tokens_details# is last-wins, so without preserving this separately the 1h breakdown is# lost and 1h cache writes get billed at the 5m rate.- cache_creation_token_details: Optional[CacheCreationTokenDetails] = None- cost: Optional[float] = None- inference_geo: Optional[str] = None- speed: Optional[str] = None+ cache_creation_token_details: CacheCreationTokenDetails | None = None+ cost: float | None = None++ inference_geo: str | None = None++ speed: str | None = Nonefor chunk in chunks:usage_chunk = self._extract_usage_chunk(chunk)@@@ -629,16 -785,7 +787,14 @@@if usage_chunk_dict["cost"] is not None:cost = usage_chunk_dict["cost"]+ chunk_inference_geo = getattr(usage_chunk, "inference_geo", None)+ if isinstance(chunk_inference_geo, str):+ inference_geo = chunk_inference_geo+ chunk_speed = getattr(usage_chunk, "speed", None)+ if isinstance(chunk_speed, str):+ speed = chunk_speed+- prompt_tokens_details = self._attach_cache_creation_token_details(- prompt_tokens_details, cache_creation_token_details- )+ prompt_tokens_details = attach_cache_creation_token_details(prompt_tokens_details, cache_creation_token_details)completion_tokens = self._reset_anthropic_cursor_completion_tokens(chunks=chunks,@@@ -656,41 -803,11 +812,13 @@@completion_tokens_details=completion_tokens_details,prompt_tokens_details=prompt_tokens_details,cost=cost,+ inference_geo=inference_geo,+ speed=speed,)- @staticmethod- def _capture_cache_creation_token_details(- prompt_tokens_details: Optional[PromptTokensDetailsWrapper],- current: Optional[CacheCreationTokenDetails],- ) -> Optional[CacheCreationTokenDetails]:- incoming = cast(- Optional[CacheCreationTokenDetails],- getattr(prompt_tokens_details, "cache_creation_token_details", None),- )- if incoming is not None:- return incoming- return current-- @staticmethod- def _attach_cache_creation_token_details(- prompt_tokens_details: Optional[PromptTokensDetailsWrapper],- cache_creation_token_details: Optional[CacheCreationTokenDetails],- ) -> Optional[PromptTokensDetailsWrapper]:- if prompt_tokens_details is None or cache_creation_token_details is None:- return prompt_tokens_details- existing = cast(- Optional[CacheCreationTokenDetails],- getattr(prompt_tokens_details, "cache_creation_token_details", None),- )- if existing is not None:- return prompt_tokens_details- return prompt_tokens_details.model_copy(update={"cache_creation_token_details": cache_creation_token_details})-@staticmethoddef _reset_anthropic_cursor_completion_tokens(- chunks: list[dict[str, Any] | ModelResponse],+ chunks: Sequence["_UsageBearingChunk | ModelResponse"],completion_tokens: int,completion_usage_updates: int,) -> int:diff --cc litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.pyindex 112780581de,9fb967e570f..b60edab0a66--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py@@@ -104,15 -103,6 +105,15 @@@ class AnthropicPassthroughLoggingHandle"kwargs": kwargs,}+ @staticmethod- def _cost_relevant_request_params(request_body: Optional[dict]) -> dict:++ def _cost_relevant_request_params(request_body: dict | None) -> dict:+ """+ Request params that change how the response is priced, and so must reach the+ usage-building paths. Anthropic's ``speed=fast`` multiplies non-cache token cost.+ """- speed = (request_body or {}).get("speed")++ speed: Final = (request_body or {}).get("speed")+ return {"speed": speed} if isinstance(speed, str) else {}+@staticmethoddef _get_user_from_metadata(passthrough_logging_payload: PassthroughStandardLoggingPayload,@@@ -326,7 -316,6 +327,7 @@@- Logs in litellm callbacks"""- speed = AnthropicPassthroughLoggingHandler._cost_relevant_request_params(request_body).get("speed")++ speed: Final = AnthropicPassthroughLoggingHandler._cost_relevant_request_params(request_body).get("speed")model = request_body.get("model", "")# Check if it's available in the logging objectif (@@@ -430,11 -417,10 +431,11 @@@@staticmethoddef _build_complete_streaming_response(- all_chunks: Sequence[Union[str, bytes]],+ all_chunks: Sequence[str | bytes],litellm_logging_obj: LiteLLMLoggingObj,model: str,- speed: Optional[str] = None,- ) -> Optional[Union[ModelResponse, TextCompletionResponse]]:++ speed: str | None = None,+ ) -> ModelResponse | TextCompletionResponse | None:"""Builds complete response from raw Anthropic chunks.@@@ -589,11 -573,10 +590,11 @@@@staticmethoddef _build_complete_streaming_response_legacy(- all_chunks: Sequence[Union[str, bytes]],+ all_chunks: Sequence[str | bytes],litellm_logging_obj: LiteLLMLoggingObj,model: str,- speed: Optional[str] = None,- ) -> Optional[Union[ModelResponse, TextCompletionResponse]]:++ speed: str | None = None,+ ) -> ModelResponse | TextCompletionResponse | None:"""Original reconstruction: convert every SSE event to a generic chunkand assemble via stream_chunk_builder. Kept verbatim as the fallback@@@ -605,12 -588,11 +606,12 @@@- Builds complete response from litellm chunks"""verbose_proxy_logger.debug("Building complete streaming response from %d chunks", len(all_chunks))- anthropic_model_response_iterator = AnthropicModelResponseIterator(+ anthropic_model_response_iterator: Final = AnthropicModelResponseIterator(streaming_response=None,sync_stream=False,+ speed=speed,)- all_openai_chunks = []+ all_openai_chunks: Final = []# Process each chunk - a chunk may contain multiple SSE eventsfor _chunk_str in all_chunks:@@@ -666,10 -648,9 +667,10 @@@@staticmethoddef _build_usage_only_response_from_chunks(- all_chunks: Sequence[Union[str, bytes]],+ all_chunks: Sequence[str | bytes],model: str,- speed: Optional[str] = None,- ) -> Optional[ModelResponse]:++ speed: str | None = None,+ ) -> ModelResponse | None:"""Build a usage-bearing ModelResponse from Anthropic SSE token-usage events, forcost tracking when stream_chunk_builder cannot reassemble the stream.@@@ -762,7 -743,7 +763,9 @@@usage_object["server_tool_use"] = _server_tool_useif inference_geo is not None:usage_object["inference_geo"] = inference_geo- usage_obj = AnthropicConfig().calculate_usage(usage_object=usage_object, reasoning_content=None, speed=speed)- usage_obj: Final = AnthropicConfig().calculate_usage(usage_object=usage_object, reasoning_content=None)++ usage_obj: Final = AnthropicConfig().calculate_usage(++ usage_object=usage_object, reasoning_content=None, speed=speed++ )return ModelResponse(model=resolved_model,choices=[diff --cc litellm/types/litellm_core_utils/streaming_chunk_builder_utils.pyindex 4ff47171e32,6846e4a91d4..893b0bdbb9f--- a/litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py+++ b/litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py@@@ -8,12 -6,10 +6,12 @@@ from ..utils import CompletionTokensDetclass UsagePerChunk(TypedDict):prompt_tokens: intcompletion_tokens: int- cache_creation_input_tokens: Optional[int]- cache_read_input_tokens: Optional[int]- server_tool_use: Optional[ServerToolUse]- web_search_requests: Optional[int]- completion_tokens_details: Optional[CompletionTokensDetails]- prompt_tokens_details: Optional[PromptTokensDetailsWrapper]- cost: Optional[float]- inference_geo: Optional[str]- speed: Optional[str]+ cache_creation_input_tokens: int | None+ cache_read_input_tokens: int | None+ server_tool_use: ServerToolUse | None+ web_search_requests: int | None+ completion_tokens_details: CompletionTokensDetails | None+ prompt_tokens_details: PromptTokensDetailsWrapper | None+ cost: float | None++ inference_geo: str | None++ speed: str | Nonediff --cc tests/test_litellm/litellm_core_utils/test_litellm_logging.pyindex 1cd4174c57c,9fa3116657b..6d50817341b--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py@@@ -4155,36 -4278,197 +4278,232 @@@ def test_pre_call_does_not_pin_request_assert litellm.error_logs == {}+def test_handle_anthropic_messages_response_logging_preserves_fast_mode_speed():+ """/v1/messages non-streaming rebuilds usage by re-transforming the raw Anthropic+ response. Anthropic's fast-mode multiplier is applied off ``usage.speed``, which the+ response body never carries, so the request's optional params have to be passed in or+ fast-mode spend is logged at the standard rate."""+ import httpx++ logging_obj = LitellmLogging(+ model="claude-opus-4-8",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="anthropic_messages",+ start_time=time.time(),+ litellm_call_id="lit-5115",+ function_id="lit-5115",+ )+ logging_obj.optional_params = {"speed": "fast"}+ logging_obj.model_call_details["httpx_response"] = httpx.Response(+ status_code=200,+ json={+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "model": "claude-opus-4-8",+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 1000, "cache_read_input_tokens": 200, "output_tokens": 100},+ },+ )++ result = logging_obj._handle_anthropic_messages_response_logging(result=None)+- assert result.usage.speed == "fast" # type: ignore[attr-defined]++ assert getattr(result.usage, "speed", None) == "fast"+++++ def test_logging_init_sets_trace_id():+ """Logging.__init__() must call set_trace_id with self.litellm_trace_id."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("")++ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-001",+ function_id="fn-001",+ kwargs={},+ )+ assert trace_id_var.get() == log_obj.litellm_trace_id+++ def test_logging_init_skips_stamping_when_correlation_logging_unsupported():+ """supports_correlation_logging=False (what wrapper(), the sync entry+ point, always passes) must leave trace_id_var/session_id_var completely+ untouched, even though self.litellm_trace_id/litellm_session_id (the+ plain attributes used by StandardLoggingPayload) are still populated as+ usual - only the ambient contextvar stamping is gated."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("")+ session_id_var.set("")++ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-sync-excluded",+ function_id="fn-sync-excluded",+ kwargs={"litellm_session_id": "should-not-be-stamped"},+ litellm_trace_id="should-not-be-stamped-either",+ supports_correlation_logging=False,+ )++ assert trace_id_var.get() == ""+ assert session_id_var.get() == ""+ # The plain attributes are unaffected - only the contextvar stamping is gated.+ assert log_obj.litellm_trace_id == "should-not-be-stamped-either"+ assert log_obj.litellm_session_id == "should-not-be-stamped"+++ def test_logging_init_sets_session_id_when_provided():+ """Logging.__init__() must call set_session_id when litellm_session_id is in kwargs."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ session_id_var.set("")++ Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-002",+ function_id="fn-002",+ kwargs={"litellm_session_id": "my-session-99"},+ )+ assert session_id_var.get() == "my-session-99"+++ def test_logging_init_resets_session_id_to_empty_when_absent():+ """When no session_id is in kwargs, Logging.__init__() must reset session_id_var to ""+ so a prior request's session_id does not leak into subsequent log records."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ session_id_var.set("preexisting-sid")++ Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-003",+ function_id="fn-003",+ kwargs={},+ )+ assert session_id_var.get() == ""+++ def test_restore_correlation_context_resets_to_pre_call_value():+ """_restore_correlation_context() must put trace_id_var/session_id_var back to+ whatever they were immediately before this Logging instance was constructed.+ This is the mechanism that prevents a nested call (e.g. a guardrail's own+ LLM-as-judge call sharing the same asyncio Task) from leaking its trace_id/+ session_id into the outer call's subsequent log lines."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("outer-trace")+ session_id_var.set("outer-session")+ try:+ inner = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="inner-call",+ function_id="fn-inner",+ kwargs={"litellm_session_id": "inner-session"},+ )+ assert trace_id_var.get() == inner.litellm_trace_id+ assert session_id_var.get() == "inner-session"++ inner._restore_correlation_context()++ assert trace_id_var.get() == "outer-trace"+ assert session_id_var.get() == "outer-session"+ finally:+ trace_id_var.set("")+ session_id_var.set("")+++ def test_restore_correlation_context_safe_to_call_repeatedly():+ """Calling _restore_correlation_context() more than once must not raise.++ It's deliberately NOT guarded against repeat calls: wrapper()'s finally+ block and a terminal handler (success_handler/failure_handler) can both+ end up calling it for the same instance, potentially from different+ asyncio Tasks - each call needs to take effect in its own Task's view of+ the contextvars, so repeat calls are expected, not just tolerated."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-idempotent",+ function_id="fn-idempotent",+ kwargs={},+ )+ log_obj._restore_correlation_context()+ log_obj._restore_correlation_context() # must not raise+++ @pytest.mark.asyncio+ async def test_restore_correlation_context_works_across_asyncio_task_boundary():+ """_restore_correlation_context() must succeed even when it's called from a+ different asyncio Task than the one Logging.__init__() ran in - exactly what+ happens on litellm's real async success path, where async_success_handler is+ dispatched via asyncio.create_task / the global logging worker rather than+ awaited directly in the request's own task.++ A contextvars.Token can only be reset in the exact Context it was created in+ and raises ValueError otherwise (verified separately against raw contextvars,+ not just this codebase). The fix uses a plain set() of the captured pre-call+ value instead, which works regardless of which Task calls it. This test+ fails with a token-based implementation - the child task's reset() would+ raise, get silently swallowed, and leave the child's view unrestored - and+ passes with the value-based one.+ """+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("outer-trace-cross-task")+ session_id_var.set("outer-session-cross-task")+ try:+ # __init__ runs in THIS (outer) task's context.+ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="acompletion",+ start_time=None,+ litellm_call_id="cross-task-call",+ function_id="fn-cross-task",+ kwargs={"litellm_session_id": "cross-task-session"},+ )+ assert trace_id_var.get() == log_obj.litellm_trace_id+ assert session_id_var.get() == "cross-task-session"++ async def restore_in_new_task():+ # Simulates async_success_handler running in a task spawned after+ # __init__ already ran elsewhere - a different Context object.+ log_obj._restore_correlation_context()+ return trace_id_var.get(), session_id_var.get()++ trace_in_child, session_in_child = await asyncio.create_task(restore_in_new_task())++ assert trace_in_child == "outer-trace-cross-task"+ assert session_in_child == "outer-session-cross-task"+ finally:+ trace_id_var.set("")+ session_id_var.set("")diff --cc tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.pyindex 72bbad7ae49,6edde02769b..10bd22689d0--- a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py@@@ -994,40 -994,232 +994,271 @@@ def test_cost_field_in_usage_chunks()assert usage.completion_tokens == 5+def test_anthropic_speed_and_geo_survive_stream_assembly():+ """Anthropic prices fast mode and non-global regions with a multiplier read off+ ``usage.speed`` / ``usage.inference_geo``. Dropping them while reassembling a stream+ bills streamed fast-mode calls at the standard rate."""+ from litellm.llms.anthropic.cost_calculation import cost_per_token++ def _usage(**extra):+ usage = Usage(completion_tokens=100, prompt_tokens=1000, total_tokens=1100)+ for key, value in extra.items():+ setattr(usage, key, value)+ return usage++ def _chunk(usage):+ return ModelResponseStream(+ id="chatcmpl-1",+ created=1745513206,+ model="claude-opus-4-8",+ choices=[StreamingChoices(finish_reason="stop", index=0, delta=Delta(content="Hi"))],+ usage=usage,+ )++ fast_chunk = _chunk(_usage(speed="fast", inference_geo="global"))+ fast_usage = ChunkProcessor(chunks=[fast_chunk]).calculate_usage(+ chunks=[fast_chunk], model="claude-opus-4-8", completion_output="Hi"+ )+ standard_chunk = _chunk(_usage(inference_geo="global"))+ standard_usage = ChunkProcessor(chunks=[standard_chunk]).calculate_usage(+ chunks=[standard_chunk], model="claude-opus-4-8", completion_output="Hi"+ )++ assert fast_usage.speed == "fast"+ assert fast_usage.inference_geo == "global"+ assert getattr(standard_usage, "speed", None) is None++ fast_cost = sum(cost_per_token(model="claude-opus-4-8", usage=fast_usage))+ standard_cost = sum(cost_per_token(model="claude-opus-4-8", usage=standard_usage))+ assert fast_cost == pytest.approx(standard_cost * 2.0)+++++ def test_prompt_tokens_details_survive_later_usage_chunk_without_details():+ """Regression for #34801: a trailing usage chunk that omits+ `prompt_tokens_details` must not wipe the OpenAI cache-read/cache-write split,+ otherwise those tokens get re-priced at the uncached input rate."""+ from litellm.types.utils import PromptTokensDetailsWrapper++ chunk_with_details = ModelResponseStream(+ id="chatcmpl-1",+ created=1745513206,+ model="openai/gpt-5.6-sol",+ choices=[+ StreamingChoices(finish_reason=None, index=0, delta=Delta(content="Hi"))+ ],+ usage=Usage(+ prompt_tokens=6017,+ completion_tokens=4,+ total_tokens=6021,+ prompt_tokens_details=PromptTokensDetailsWrapper(+ cached_tokens=6004, cache_write_tokens=10+ ),+ ),+ )+ chunk_without_details = ModelResponseStream(+ id="chatcmpl-1",+ created=1745513207,+ model="openai/gpt-5.6-sol",+ choices=[+ StreamingChoices(finish_reason="stop", index=0, delta=Delta(content=""))+ ],+ usage=Usage(prompt_tokens=6017, completion_tokens=4, total_tokens=6021),+ )++ chunks = [chunk_with_details, chunk_without_details]+ usage = ChunkProcessor(chunks=chunks).calculate_usage(+ chunks=chunks, model="openai/gpt-5.6-sol", completion_output="Hi"+ )++ assert usage.prompt_tokens == 6017+ assert usage.prompt_tokens_details is not None+ assert usage.prompt_tokens_details.cached_tokens == 6004+ assert usage.prompt_tokens_details.cache_write_tokens == 10+++ def test_get_combined_tool_content_custom_tool_call():+ from litellm.litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor+ from litellm.types.utils import ChatCompletionMessageCustomToolCall++ processor = ChunkProcessor.__new__(ChunkProcessor)+ tool_call_chunks = [+ {+ "choices": [+ {+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_TBs",+ "type": "custom",+ "custom": {"name": "ApplyPatch", "input": ""},+ }+ ]+ }+ }+ ]+ },+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** Begin Patch\n"}}]}}]},+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** End Patch\n"}}]}}]},+ ]+ combined = processor.get_combined_tool_content(tool_call_chunks)+ assert len(combined) == 1+ assert isinstance(combined[0], ChatCompletionMessageCustomToolCall)+ assert combined[0].model_dump() == {+ "id": "call_TBs",+ "type": "custom",+ "custom": {"name": "ApplyPatch", "input": "*** Begin Patch\n*** End Patch\n"},+ }+++ def test_get_combined_tool_content_custom_tool_call_without_type_field():+ """Delta coercion classifies a tool-call chunk as custom from its ``custom`` payload+ alone (``type`` may never arrive on any chunk). The assembler must use the same+ evidence; requiring ``type == "custom"`` dropped the whole tool call from the+ combined message (it matched neither the custom nor the function branch)."""+ from litellm.litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor+ from litellm.types.utils import ChatCompletionMessageCustomToolCall++ processor = ChunkProcessor.__new__(ChunkProcessor)+ tool_call_chunks = [+ {+ "choices": [+ {+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_TBs",+ "custom": {"name": "ApplyPatch", "input": "*** Begin"},+ }+ ]+ }+ }+ ]+ },+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": " Patch"}}]}}]},+ ]+ combined = processor.get_combined_tool_content(tool_call_chunks)+ assert len(combined) == 1+ assert isinstance(combined[0], ChatCompletionMessageCustomToolCall)+ assert combined[0].model_dump() == {+ "id": "call_TBs",+ "type": "custom",+ "custom": {"name": "ApplyPatch", "input": "*** Begin Patch"},+ }+++ def _tool_call_delta_chunk(tool_call: dict[str, object] | ChatCompletionDeltaToolCall) -> dict[str, object]:+ return {"choices": [{"delta": {"tool_calls": [tool_call]}}]}+++ def test_get_combined_tool_content_joins_many_dict_shaped_argument_fragments_in_order():+ processor = ChunkProcessor.__new__(ChunkProcessor)+ first_fragments = [f"a{i};" for i in range(300)]+ second_fragments = [f"b{i};" for i in range(300)]+ header_chunks = [+ _tool_call_delta_chunk({"index": 0, "id": "call_a", "type": "function", "function": {"name": "tool_a"}}),+ _tool_call_delta_chunk({"index": 1, "id": "call_b", "type": "function", "function": {"name": "tool_b"}}),+ _tool_call_delta_chunk({"index": 2, "id": "call_c", "type": "function", "function": {"name": "tool_c"}}),+ ]+ fragment_chunks = [+ _tool_call_delta_chunk({"index": index, "function": {"arguments": fragment}})+ for first, second in zip(first_fragments, second_fragments)+ for index, fragment in ((0, first), (1, second))+ ]++ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)++ assert [tool_call.id for tool_call in combined] == ["call_a", "call_b", "call_c"]+ assert combined[0].function.name == "tool_a"+ assert combined[0].function.arguments == "".join(first_fragments)+ assert combined[1].function.name == "tool_b"+ assert combined[1].function.arguments == "".join(second_fragments)+ assert combined[2].function.arguments == "{}"+++ def test_get_combined_tool_content_joins_fragments_across_many_parallel_tool_calls():+ processor = ChunkProcessor.__new__(ChunkProcessor)+ indexes = range(40)+ header_chunks = [+ _tool_call_delta_chunk(+ {"index": index, "id": f"call_{index}", "type": "function", "function": {"name": f"tool_{index}"}}+ )+ for index in indexes+ ]+ fragment_chunks = [+ _tool_call_delta_chunk({"index": index, "function": {"arguments": f"{index}.{position};"}})+ for position in range(5)+ for index in indexes+ ]++ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)++ assert [tool_call.id for tool_call in combined] == [f"call_{index}" for index in indexes]+ for index, tool_call in zip(indexes, combined):+ assert tool_call.function.arguments == "".join(f"{index}.{position};" for position in range(5))+++ def test_get_combined_tool_content_joins_many_object_shaped_argument_fragments_in_order():+ processor = ChunkProcessor.__new__(ChunkProcessor)+ first_fragments = [f"x{i}|" for i in range(300)]+ second_fragments = [f"y{i}|" for i in range(300)]+ header_chunks = [+ _tool_call_delta_chunk(+ ChatCompletionDeltaToolCall(+ id="call_x", type="function", index=0, function=Function(name="tool_x", arguments="")+ )+ ),+ _tool_call_delta_chunk(+ ChatCompletionDeltaToolCall(+ id="call_y", type="function", index=1, function=Function(name="tool_y", arguments="")+ )+ ),+ ]+ fragment_chunks = [+ _tool_call_delta_chunk(ChatCompletionDeltaToolCall(index=index, function=Function(arguments=fragment)))+ for first, second in zip(first_fragments, second_fragments)+ for index, fragment in ((0, first), (1, second))+ ]++ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)++ assert [tool_call.id for tool_call in combined] == ["call_x", "call_y"]+ assert combined[0].function.name == "tool_x"+ assert combined[0].function.arguments == "".join(first_fragments)+ assert combined[1].function.name == "tool_y"+ assert combined[1].function.arguments == "".join(second_fragments)+++ def test_get_combined_tool_content_joins_many_custom_tool_input_fragments_in_order():+ from types import SimpleNamespace++ from litellm.types.utils import ChatCompletionMessageCustomToolCall++ processor = ChunkProcessor.__new__(ChunkProcessor)+ dict_fragments = [f"d{i}," for i in range(200)]+ object_fragments = [f"o{i}," for i in range(200)]+ header_chunks = [+ _tool_call_delta_chunk({"index": 0, "id": "call_d", "type": "custom", "custom": {"name": "apply_patch"}}),+ _tool_call_delta_chunk(+ SimpleNamespace(index=1, id="call_o", type="custom", custom=SimpleNamespace(name="run_script", input=""))+ ),+ ]+ fragment_chunks = [+ _tool_call_delta_chunk(tool_call)+ for dict_fragment, object_fragment in zip(dict_fragments, object_fragments)+ for tool_call in (+ {"index": 0, "custom": {"input": dict_fragment}},+ SimpleNamespace(index=1, custom=SimpleNamespace(input=object_fragment)),+ )+ ]++ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)++ assert [tool_call.id for tool_call in combined] == ["call_d", "call_o"]+ assert isinstance(combined[0], ChatCompletionMessageCustomToolCall)+ assert combined[0].custom.name == "apply_patch"+ assert combined[0].custom.input == "".join(dict_fragments)+ assert isinstance(combined[1], ChatCompletionMessageCustomToolCall)+ assert combined[1].custom.name == "run_script"+ assert combined[1].custom.input == "".join(object_fragments)