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: surface Anthropic code execution results as code_interpreter_call in Responses API

Andrzej Pomirski92b89353ae60
diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py
index 5eebebc2e23..51b9c9835a7 100644
--- a/litellm/llms/anthropic/chat/handler.py
+++ b/litellm/llms/anthropic/chat/handler.py
@@ -48,6 +48,10 @@ from litellm.types.llms.openai import (
ChatCompletionToolCallChunk,
ChatCompletionToolCallFunctionChunk,
)
+from litellm.types.responses.main import (
+ OutputCodeInterpreterCall,
+ OutputCodeInterpreterCallLog,
+)
from litellm.types.utils import (
Delta,
GenericStreamingChunk,
@@ -538,6 +542,11 @@ class ModelResponseIterator:
# Accumulate compaction blocks for multi-turn reconstruction
self.compaction_blocks: List[Dict[str, Any]] = []
+ # Track server tool use inputs and results for code_interpreter_results
+ self._server_tool_inputs: Dict[str, Any] = {}
+ self.tool_results: List[Dict[str, Any]] = []
+ self._last_code_interpreter_results_count: int = 0
+
def check_empty_tool_call_args(self) -> bool:
"""
Check if the tool call block so far has been an empty string
@@ -568,9 +577,7 @@ class ModelResponseIterator:
speed=self.speed,
)
- def _content_block_delta_helper(
- self, chunk: dict
- ) -> Tuple[
+ def _content_block_delta_helper(self, chunk: dict) -> Tuple[
str,
Optional[ChatCompletionToolCallChunk],
List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]],
@@ -682,6 +689,44 @@ class ModelResponseIterator:
return content_block_start
+ def _build_code_interpreter_results(self) -> list:
+ """Convert accumulated tool_results to OutputCodeInterpreterCall objects.
+
+ Called during streaming to produce provider-neutral code_interpreter_results
+ alongside the raw tool_results, so the Responses API layer doesn't need
+ Anthropic-specific knowledge.
+ """
+ # Only convert tool_results added since the last call to avoid
+ # duplicates when _merge_provider_specific_fields extends the list.
+ new_results = self.tool_results[self._last_code_interpreter_results_count :]
+ self._last_code_interpreter_results_count = len(self.tool_results)
+ results = []
+ for tr in new_results:
+ call_id = tr.get("tool_use_id", "")
+ content = tr.get("content", {})
+ if isinstance(content, dict):
+ parts = []
+ if content.get("stdout"):
+ parts.append(content["stdout"])
+ if content.get("stderr"):
+ parts.append(f"STDERR: {content['stderr']}")
+ logs = "".join(parts) if parts else str(content)
+ else:
+ logs = str(content)
+ tool_input = self._server_tool_inputs.get(call_id, {})
+ code = tool_input.get("command", "") if isinstance(tool_input, dict) else ""
+ results.append(
+ OutputCodeInterpreterCall(
+ type="code_interpreter_call",
+ id=call_id,
+ code=code,
+ container_id=None,
+ status="completed",
+ outputs=[OutputCodeInterpreterCallLog(type="logs", logs=logs)],
+ )
+ )
+ return results
+
def chunk_parser(self, chunk: dict) -> ModelResponseStream: # noqa: PLR0915
try:
type_chunk = chunk.get("type", "") or ""
@@ -748,6 +793,17 @@ class ModelResponseIterator:
),
index=self.tool_index,
)
+ # Track server tool use inputs for code_interpreter_results
+ if (
+ content_block_start["content_block"]["type"]
+ == "server_tool_use"
+ ):
+ tool_input = content_block_start["content_block"].get(
+ "input", {}
+ )
+ self._server_tool_inputs[
+ content_block_start["content_block"]["id"]
+ ] = tool_input
# Include caller information if present (for programmatic tool calling)
if "caller" in content_block_start["content_block"]:
caller_data = content_block_start["content_block"]["caller"]
@@ -768,9 +824,9 @@ class ModelResponseIterator:
# Handle compaction blocks
# The full content comes in content_block_start
self.compaction_blocks.append(content_block_start["content_block"])
- provider_specific_fields[
- "compaction_blocks"
- ] = self.compaction_blocks
+ provider_specific_fields["compaction_blocks"] = (
+ self.compaction_blocks
+ )
provider_specific_fields["compaction_start"] = {
"type": "compaction",
"content": content_block_start["content_block"].get(
@@ -792,9 +848,9 @@ class ModelResponseIterator:
self.web_search_results.append(
content_block_start["content_block"]
)
- provider_specific_fields[
- "web_search_results"
- ] = self.web_search_results
+ provider_specific_fields["web_search_results"] = (
+ self.web_search_results
+ )
elif content_type == "web_fetch_tool_result":
# Capture web_fetch_tool_result for multi-turn reconstruction
# The full content comes in content_block_start, not in deltas
@@ -802,16 +858,18 @@ class ModelResponseIterator:
self.web_search_results.append(
content_block_start["content_block"]
)
- provider_specific_fields[
- "web_search_results"
- ] = self.web_search_results
+ provider_specific_fields["web_search_results"] = (
+ self.web_search_results
+ )
elif content_type != "tool_search_tool_result":
# Handle other tool results (code execution, etc.)
# Skip tool_search_tool_result as it's internal metadata
- if not hasattr(self, "tool_results"):
- self.tool_results = []
self.tool_results.append(content_block_start["content_block"])
provider_specific_fields["tool_results"] = self.tool_results
+ # Convert to provider-neutral code_interpreter_results
+ provider_specific_fields["code_interpreter_results"] = (
+ self._build_code_interpreter_results()
+ )
elif type_chunk == "content_block_stop":
ContentBlockStop(**chunk) # type: ignore
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py
index 47cdd8287e0..033afea2ffa 100644
--- a/litellm/llms/anthropic/chat/transformation.py
+++ b/litellm/llms/anthropic/chat/transformation.py
@@ -59,6 +59,10 @@ from litellm.types.utils import (
PromptTokensDetailsWrapper,
ServerToolUse,
)
+from litellm.types.responses.main import (
+ OutputCodeInterpreterCall,
+ OutputCodeInterpreterCallLog,
+)
from litellm.utils import (
ModelResponse,
Usage,
@@ -960,11 +964,11 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
if mcp_servers:
optional_params["mcp_servers"] = mcp_servers
elif param == "tool_choice" or param == "parallel_tool_calls":
- _tool_choice: Optional[
- AnthropicMessagesToolChoice
- ] = self._map_tool_choice(
- tool_choice=non_default_params.get("tool_choice"),
- parallel_tool_use=non_default_params.get("parallel_tool_calls"),
+ _tool_choice: Optional[AnthropicMessagesToolChoice] = (
+ self._map_tool_choice(
+ tool_choice=non_default_params.get("tool_choice"),
+ parallel_tool_use=non_default_params.get("parallel_tool_calls"),
+ )
)
if _tool_choice is not None:
@@ -1062,9 +1066,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
self.map_openai_context_management_to_anthropic(value)
)
if anthropic_context_management is not None:
- optional_params[
- "context_management"
- ] = anthropic_context_management
+ optional_params["context_management"] = (
+ anthropic_context_management
+ )
elif param == "speed" and isinstance(value, str):
# Pass through Anthropic-specific speed parameter for fast mode
optional_params["speed"] = value
@@ -1138,9 +1142,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
text=system_message_block["content"],
)
if "cache_control" in system_message_block:
- anthropic_system_message_content[
- "cache_control"
- ] = system_message_block["cache_control"]
+ anthropic_system_message_content["cache_control"] = (
+ system_message_block["cache_control"]
+ )
anthropic_system_message_list.append(
anthropic_system_message_content
)
@@ -1164,9 +1168,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
)
)
if "cache_control" in _content:
- anthropic_system_message_content[
- "cache_control"
- ] = _content["cache_control"]
+ anthropic_system_message_content["cache_control"] = (
+ _content["cache_control"]
+ )
anthropic_system_message_list.append(
anthropic_system_message_content
@@ -1463,9 +1467,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
)
return _message
- def extract_response_content(
- self, completion_response: dict
- ) -> Tuple[
+ def extract_response_content(self, completion_response: dict) -> Tuple[
str,
Optional[List[Any]],
Optional[
@@ -1749,6 +1751,48 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
provider_specific_fields["web_search_results"] = web_search_results
if tool_results is not None:
provider_specific_fields["tool_results"] = tool_results
+ # Convert to provider-neutral OutputCodeInterpreterCall objects
+ # so the Responses API layer can use them without Anthropic-specific knowledge.
+ container_id = (
+ completion_response.get("container", {}).get("id")
+ if isinstance(completion_response.get("container"), dict)
+ else None
+ )
+ code_by_id: Dict[str, str] = {}
+ for tc in tool_calls:
+ try:
+ args = json.loads(tc.get("function", {}).get("arguments", "{}"))
+ code_by_id[tc.get("id", "")] = args.get("command", "")
+ except Exception:
+ pass
+ code_interpreter_results = []
+ for tr in tool_results:
+ call_id = tr.get("tool_use_id", "")
+ content = tr.get("content", {})
+ if isinstance(content, dict):
+ parts = []
+ if content.get("stdout"):
+ parts.append(content["stdout"])
+ if content.get("stderr"):
+ parts.append(f"STDERR: {content['stderr']}")
+ logs = "".join(parts) if parts else str(content)
+ else:
+ logs = str(content)
+ code_interpreter_results.append(
+ OutputCodeInterpreterCall(
+ type="code_interpreter_call",
+ id=call_id,
+ code=code_by_id.get(call_id, ""),
+ container_id=container_id,
+ status="completed",
+ outputs=[
+ OutputCodeInterpreterCallLog(type="logs", logs=logs)
+ ],
+ )
+ )
+ provider_specific_fields["code_interpreter_results"] = (
+ code_interpreter_results
+ )
if container is not None:
provider_specific_fields["container"] = container
if compaction_blocks is not None:
@@ -1794,6 +1838,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
model_response.created = int(time.time())
model_response.model = completion_response["model"]
+ _hidden_params["provider_specific_fields"] = provider_specific_fields
model_response._hidden_params = _hidden_params
return model_response
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
index ce037850b86..0b7d6e8a7a4 100644
--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py
+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
@@ -107,6 +107,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self._reasoning_done_emitted = False
self._reasoning_item_id: Optional[str] = None
self._accumulated_reasoning_content_parts: List[str] = []
+ self._accumulated_provider_specific_fields: Dict[str, Any] = {}
def _get_or_assign_tool_output_index(self, call_id: str) -> int:
existing = self._tool_output_index_by_call_id.get(call_id)
@@ -479,16 +480,37 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
event.__dict__["sequence_number"] = self._sequence_number
return event
- def create_litellm_model_response(
- self,
- ) -> Optional[ModelResponse]:
- return cast(
+ def _merge_provider_specific_fields(self, src: dict) -> None:
+ """Merge provider_specific_fields, extending list values instead of replacing."""
+ for key, val in src.items():
+ existing = self._accumulated_provider_specific_fields.get(key)
+ if (
+ existing is not None
+ and isinstance(val, list)
+ and isinstance(existing, list)
+ ):
+ existing.extend(val)
+ else:
+ self._accumulated_provider_specific_fields[key] = val
+
+ def create_litellm_model_response(self) -> Optional[ModelResponse]:
+ response = cast(
Optional[ModelResponse],
stream_chunk_builder(
chunks=self.collected_chat_completion_chunks,
logging_obj=self.litellm_logging_obj,
),
)
+ if response is not None and self._accumulated_provider_specific_fields:
+ if (
+ not hasattr(response, "_hidden_params")
+ or response._hidden_params is None
+ ):
+ response._hidden_params = {}
+ response._hidden_params.setdefault("provider_specific_fields", {}).update(
+ self._accumulated_provider_specific_fields
+ )
+ return response
@staticmethod
def _snapshot_chunk_for_stream_chunk_builder(
@@ -853,6 +875,17 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
if chunk is not None:
chunk = cast(ModelResponseStream, chunk)
self._ensure_output_item_for_chunk(chunk)
+ # Accumulate provider_specific_fields from chunk and delta
+ for src in (
+ getattr(chunk, "provider_specific_fields", None),
+ getattr(
+ chunk.choices[0].delta if chunk.choices else None,
+ "provider_specific_fields",
+ None,
+ ),
+ ):
+ if src and isinstance(src, dict):
+ self._merge_provider_specific_fields(src)
# Proceed to transformation
self.collected_chat_completion_chunks.append(
self._snapshot_chunk_for_stream_chunk_builder(chunk)
@@ -964,6 +997,17 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
try:
chunk = self.litellm_custom_stream_wrapper.__next__()
self._ensure_output_item_for_chunk(chunk)
+ # Accumulate provider_specific_fields from chunk and delta
+ for src in (
+ getattr(chunk, "provider_specific_fields", None),
+ getattr(
+ chunk.choices[0].delta if chunk.choices else None,
+ "provider_specific_fields",
+ None,
+ ),
+ ):
+ if src and isinstance(src, dict):
+ self._merge_provider_specific_fields(src)
# Emit any just-queued output_item event
if self._pending_response_events:
return self._pending_response_events.pop(0)
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
index 71fa88fb751..b54d5930efc 100644
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -42,6 +42,7 @@ from litellm.types.llms.openai import (
from litellm.types.responses.main import (
GenericResponseOutputItem,
GenericResponseOutputItemContentAnnotation,
+ OutputCodeInterpreterCall,
OutputFunctionToolCall,
OutputImageGenerationCall,
OutputText,
@@ -1696,6 +1697,7 @@ class LiteLLMCompletionResponsesConfig:
) -> List[
Union[
GenericResponseOutputItem,
+ OutputCodeInterpreterCall,
OutputFunctionToolCall,
OutputImageGenerationCall,
ResponseFunctionToolCall,
@@ -1704,6 +1706,7 @@ class LiteLLMCompletionResponsesConfig:
responses_output: List[
Union[
GenericResponseOutputItem,
+ OutputCodeInterpreterCall,
OutputFunctionToolCall,
OutputImageGenerationCall,
ResponseFunctionToolCall,
@@ -1725,8 +1728,56 @@ class LiteLLMCompletionResponsesConfig:
chat_completion_response=chat_completion_response
)
)
+
+ # Convert server-side tool results (e.g. Anthropic code execution)
+ # into code_interpreter_call output items, replacing the corresponding
+ # function_call items so the output matches OpenAI's native shape.
+ tool_result_items = (
+ LiteLLMCompletionResponsesConfig._extract_tool_result_output_items(
+ chat_completion_response
+ )
+ )
+ if tool_result_items:
+ result_by_id = {item.id: item for item in tool_result_items}
+ replaced_ids = set(result_by_id.keys())
+ responses_output = [
+ (
+ result_by_id[getattr(item, "call_id", None)]
+ if (
+ getattr(item, "type", None) == "function_call"
+ and getattr(item, "call_id", None) in replaced_ids
+ )
+ else item
+ )
+ for item in responses_output
+ ]
+
return responses_output
+ @staticmethod
+ def _extract_tool_result_output_items(
+ chat_completion_response: ModelResponse,
+ ) -> list:
+ """Extract pre-built code_interpreter_call output items from provider_specific_fields.
+
+ Provider transformers (e.g. Anthropic) convert their native tool results
+ into OutputCodeInterpreterCall objects and store them in
+ provider_specific_fields["code_interpreter_results"]. This method
+ simply retrieves them — no provider-specific parsing here.
+ """
+ output_items: list = []
+ for choice in chat_completion_response.choices or []:
+ message = getattr(choice, "message", None)
+ if not message:
+ continue
+ psf = getattr(message, "provider_specific_fields", None)
+ if not psf or not isinstance(psf, dict):
+ continue
+ results = psf.get("code_interpreter_results")
+ if results and isinstance(results, list):
+ output_items.extend(results)
+ return output_items
+
@staticmethod
def _extract_reasoning_output_items(
chat_completion_response: ModelResponse,
@@ -2055,9 +2106,9 @@ class LiteLLMCompletionResponsesConfig:
hasattr(completion_details, "reasoning_tokens")
and completion_details.reasoning_tokens is not None
):
- output_details_dict[
- "reasoning_tokens"
- ] = completion_details.reasoning_tokens
+ output_details_dict["reasoning_tokens"] = (
+ completion_details.reasoning_tokens
+ )
else:
output_details_dict["reasoning_tokens"] = 0
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
index a2df3f2e0d6..a265198e6b8 100644
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -84,6 +84,7 @@ from typing_extensions import Annotated, Dict, Required, TypedDict, override
from litellm.types.llms.base import BaseLiteLLMOpenAIResponseObject
from litellm.types.responses.main import (
GenericResponseOutputItem,
+ OutputCodeInterpreterCall,
OutputFunctionToolCall,
OutputImageGenerationCall,
)
@@ -969,12 +970,12 @@ class OpenAIChatCompletionChunk(ChatCompletionChunk):
class Hyperparameters(BaseModel):
batch_size: Optional[Union[str, int]] = None # "Number of examples in each batch."
- learning_rate_multiplier: Optional[
- Union[str, float]
- ] = None # Scaling factor for the learning rate
- n_epochs: Optional[
- Union[str, int]
- ] = None # "The number of epochs to train the model for"
+ learning_rate_multiplier: Optional[Union[str, float]] = (
+ None # Scaling factor for the learning rate
+ )
+ n_epochs: Optional[Union[str, int]] = (
+ None # "The number of epochs to train the model for"
+ )
model_config = {"extra": "allow"}
@@ -1003,18 +1004,18 @@ class FineTuningJobCreate(BaseModel):
model: str # "The name of the model to fine-tune."
training_file: str # "The ID of an uploaded file that contains training data."
- hyperparameters: Optional[
- Hyperparameters
- ] = None # "The hyperparameters used for the fine-tuning job."
- suffix: Optional[
- str
- ] = None # "A string of up to 18 characters that will be added to your fine-tuned model name."
- validation_file: Optional[
- str
- ] = None # "The ID of an uploaded file that contains validation data."
- integrations: Optional[
- List[str]
- ] = None # "A list of integrations to enable for your fine-tuning job."
+ hyperparameters: Optional[Hyperparameters] = (
+ None # "The hyperparameters used for the fine-tuning job."
+ )
+ suffix: Optional[str] = (
+ None # "A string of up to 18 characters that will be added to your fine-tuned model name."
+ )
+ validation_file: Optional[str] = (
+ None # "The ID of an uploaded file that contains validation data."
+ )
+ integrations: Optional[List[str]] = (
+ None # "A list of integrations to enable for your fine-tuning job."
+ )
seed: Optional[int] = None # "The seed controls the reproducibility of the job."
@@ -1242,6 +1243,7 @@ class ResponsesAPIResponse(BaseLiteLLMOpenAIResponseObject):
List[
Union[
GenericResponseOutputItem,
+ OutputCodeInterpreterCall,
OutputFunctionToolCall,
OutputImageGenerationCall,
ResponseFunctionToolCall,
@@ -1308,13 +1310,16 @@ class ResponsesAPIResponse(BaseLiteLLMOpenAIResponseObject):
if not isinstance(serialized, list):
return serialized
return [
- {
- k: v
- for k, v in item.items()
- if v is not None or k not in ("status", "content", "encrypted_content")
- }
- if isinstance(item, dict) and item.get("type") == "reasoning"
- else item
+ (
+ {
+ k: v
+ for k, v in item.items()
+ if v is not None
+ or k not in ("status", "content", "encrypted_content")
+ }
+ if isinstance(item, dict) and item.get("type") == "reasoning"
+ else item
+ )
for item in serialized
]
diff --git a/litellm/types/responses/main.py b/litellm/types/responses/main.py
index 7a666d5e65f..e46857565c7 100644
--- a/litellm/types/responses/main.py
+++ b/litellm/types/responses/main.py
@@ -49,6 +49,24 @@ class OutputImageGenerationCall(BaseLiteLLMOpenAIResponseObject):
result: Optional[str] # Base64 encoded image data (without data:image prefix)
+class OutputCodeInterpreterCallLog(BaseLiteLLMOpenAIResponseObject):
+ """Log output from a code interpreter call"""
+
+ type: Literal["logs"]
+ logs: str
+
+
+class OutputCodeInterpreterCall(BaseLiteLLMOpenAIResponseObject):
+ """A code interpreter / code execution call output"""
+
+ type: Literal["code_interpreter_call"]
+ id: str
+ code: Optional[str]
+ container_id: Optional[str]
+ status: Literal["in_progress", "completed", "incomplete", "failed"]
+ outputs: Optional[List[OutputCodeInterpreterCallLog]]
+
+
class GenericResponseOutputItem(BaseLiteLLMOpenAIResponseObject):
"""
Generic response API output item
diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py
index d9f513d8d1d..35c7a62027b 100644
--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py
+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py
@@ -6,6 +6,7 @@ from litellm.types.llms.openai import (
ChatCompletionToolCallChunk,
ChatCompletionToolCallFunctionChunk,
)
+from litellm.types.responses.main import OutputCodeInterpreterCall
def test_redacted_thinking_content_block_delta():
@@ -479,14 +480,22 @@ def test_partial_json_chunk_accumulation():
# First partial chunk should return None (still accumulating)
result1 = iterator._parse_sse_data(f"data:{partial_chunk_1}")
assert result1 is None, "First partial chunk should return None while accumulating"
- assert iterator.chunk_type == "accumulated_json", "Should switch to accumulated_json mode"
- assert iterator.accumulated_json == partial_chunk_1, "Should have accumulated first part"
+ assert (
+ iterator.chunk_type == "accumulated_json"
+ ), "Should switch to accumulated_json mode"
+ assert (
+ iterator.accumulated_json == partial_chunk_1
+ ), "Should have accumulated first part"
# Second partial chunk should complete the JSON and return a parsed result
result2 = iterator._parse_sse_data(f"data:{partial_chunk_2}")
assert result2 is not None, "Second chunk should return parsed result"
- assert iterator.accumulated_json == "", "Buffer should be cleared after successful parse"
- assert result2.choices[0].delta.content == "Hello", f"Expected 'Hello', got '{result2.choices[0].delta.content}'"
+ assert (
+ iterator.accumulated_json == ""
+ ), "Buffer should be cleared after successful parse"
+ assert (
+ result2.choices[0].delta.content == "Hello"
+ ), f"Expected 'Hello', got '{result2.choices[0].delta.content}'"
def test_complete_json_chunk_no_accumulation():
@@ -503,7 +512,9 @@ def test_complete_json_chunk_no_accumulation():
assert result is not None, "Complete chunk should return parsed result immediately"
assert iterator.chunk_type == "valid_json", "Should remain in valid_json mode"
assert iterator.accumulated_json == "", "Buffer should remain empty"
- assert result.choices[0].delta.content == "Hello", f"Expected 'Hello', got '{result.choices[0].delta.content}'"
+ assert (
+ result.choices[0].delta.content == "Hello"
+ ), f"Expected 'Hello', got '{result.choices[0].delta.content}'"
def test_multiple_partial_chunks_accumulation():
@@ -620,7 +631,9 @@ def test_web_search_tool_result_no_extra_tool_calls():
# Should have exactly 2 tool calls:
# 1. From content_block_start (server_tool_use) with id and name
# 2. From content_block_delta with the actual query
- assert len(tool_calls_emitted) == 2, f"Expected 2 tool calls, got {len(tool_calls_emitted)}"
+ assert (
+ len(tool_calls_emitted) == 2
+ ), f"Expected 2 tool calls, got {len(tool_calls_emitted)}"
# First tool call should have the id and name
assert tool_calls_emitted[0]["id"] == "srvtoolu_01ABC123"
@@ -722,7 +735,10 @@ def test_web_search_tool_result_captured_in_provider_specific_fields():
{
"type": "content_block_delta",
"index": 0,
- "delta": {"type": "input_json_delta", "partial_json": '{"query": "otter facts"}'},
+ "delta": {
+ "type": "input_json_delta",
+ "partial_json": '{"query": "otter facts"}',
+ },
},
# 4. content_block_stop for server_tool_use
{"type": "content_block_stop", "index": 0},
@@ -822,7 +838,10 @@ def test_web_fetch_tool_result_captured_in_provider_specific_fields():
{
"type": "content_block_delta",
"index": 0,
- "delta": {"type": "input_json_delta", "partial_json": '{"url": "https://example.com"}'},
+ "delta": {
+ "type": "input_json_delta",
+ "partial_json": '{"url": "https://example.com"}',
+ },
},
# 4. content_block_stop for server_tool_use
{"type": "content_block_stop", "index": 0},
@@ -946,7 +965,7 @@ def test_web_fetch_tool_result_no_extra_tool_calls():
def test_container_in_provider_specific_fields_streaming():
"""
Test that container is captured in provider_specific_fields for streaming responses.
-
+
When container with skills is used, the container field should be present in
the provider_specific_fields of the message_delta chunk.
"""
@@ -1025,7 +1044,9 @@ def test_container_in_provider_specific_fields_streaming():
]
# Verify container was captured
- assert container_field is not None, "container should be captured in provider_specific_fields"
+ assert (
+ container_field is not None
+ ), "container should be captured in provider_specific_fields"
assert (
container_field["id"] == "container_011CW9hA9zpZ8xD3bjjShy4p"
), "container id should match"
@@ -1033,18 +1054,14 @@ def test_container_in_provider_specific_fields_streaming():
container_field["expires_at"] == "2025-12-16T04:57:16.913181Z"
), "expires_at should match"
assert len(container_field["skills"]) == 1, "Should have 1 skill"
- assert (
- container_field["skills"][0]["skill_id"] == "pptx"
- ), "skill_id should be pptx"
- assert (
- container_field["skills"][0]["version"] == "20251013"
- ), "version should match"
+ assert container_field["skills"][0]["skill_id"] == "pptx", "skill_id should be pptx"
+ assert container_field["skills"][0]["version"] == "20251013", "version should match"
def test_container_in_provider_specific_fields_non_streaming():
"""
Test that container is captured in provider_specific_fields for non-streaming responses.
-
+
When container with skills is used in non-streaming, the container field should be
present in the provider_specific_fields of the response.
"""
@@ -1106,7 +1123,7 @@ def test_container_in_provider_specific_fields_non_streaming():
def test_container_absent_when_not_provided():
"""
Test that container is not added to provider_specific_fields when not provided.
-
+
This ensures we don't add empty or None container fields.
"""
iterator = ModelResponseIterator(
@@ -1133,3 +1150,197 @@ def test_container_absent_when_not_provided():
assert (
"container" not in model_response.choices[0].delta.provider_specific_fields
), "container should not be present when not provided in delta"
+
+
+def test_streaming_code_execution_produces_code_interpreter_results():
+ """
+ Test that bash_code_execution_tool_result content blocks in streaming
+ produce code_interpreter_results in provider_specific_fields, so the
+ Responses API layer can use them without Anthropic-specific knowledge.
+ """
+
+ chunks = [
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_01XYZ",
+ "type": "message",
+ "role": "assistant",
+ "content": [],
+ "usage": {"input_tokens": 100, "output_tokens": 1},
+ },
+ },
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {
+ "type": "text",
+ "text": "",
+ },
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "text_delta", "text": "Running code..."},
+ },
+ {"type": "content_block_stop", "index": 0},
+ {
+ "type": "content_block_start",
+ "index": 1,
+ "content_block": {
+ "type": "server_tool_use",
+ "id": "srvtoolu_01ABC",
+ "name": "bash_code_execution",
+ "input": {"command": "echo hello"},
+ },
+ },
+ {"type": "content_block_stop", "index": 1},
+ {
+ "type": "content_block_start",
+ "index": 2,
+ "content_block": {
+ "type": "bash_code_execution_tool_result",
+ "tool_use_id": "srvtoolu_01ABC",
+ "content": {
+ "type": "bash_code_execution_result",
+ "stdout": "hello\n",
+ "stderr": "",
+ "return_code": 0,
+ },
+ },
+ },
+ {"type": "content_block_stop", "index": 2},
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn"},
+ "usage": {"output_tokens": 50},
+ },
+ ]
+
+ iterator = ModelResponseIterator(None, sync_stream=True)
+
+ found_code_interpreter_results = False
+ for chunk in chunks:
+ parsed = iterator.chunk_parser(chunk)
+ psf = None
+ if parsed.choices and parsed.choices[0].delta:
+ psf = getattr(parsed.choices[0].delta, "provider_specific_fields", None)
+ if psf and "code_interpreter_results" in psf:
+ found_code_interpreter_results = True
+ results = psf["code_interpreter_results"]
+ assert len(results) == 1
+ assert isinstance(results[0], OutputCodeInterpreterCall)
+ assert results[0].type == "code_interpreter_call"
+ assert results[0].id == "srvtoolu_01ABC"
+ assert results[0].code == "echo hello"
+ assert results[0].outputs is not None
+ assert len(results[0].outputs) == 1
+ assert results[0].outputs[0].logs == "hello\n"
+
+ assert found_code_interpreter_results, (
+ "code_interpreter_results should appear in provider_specific_fields "
+ "when bash_code_execution_tool_result is streamed"
+ )
+
+
+def test_streaming_multiple_code_executions_no_duplicates():
+ """
+ Test that multiple code executions in a single streaming response produce
+ exactly one code_interpreter_result per execution — no duplicates from
+ _build_code_interpreter_results rebuilding the full list.
+ """
+ chunks = [
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_01XYZ",
+ "type": "message",
+ "role": "assistant",
+ "content": [],
+ "usage": {"input_tokens": 100, "output_tokens": 1},
+ },
+ },
+ # First code execution
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {
+ "type": "server_tool_use",
+ "id": "srvtoolu_01AAA",
+ "name": "bash_code_execution",
+ "input": {"command": "echo first"},
+ },
+ },
+ {"type": "content_block_stop", "index": 0},
+ {
+ "type": "content_block_start",
+ "index": 1,
+ "content_block": {
+ "type": "bash_code_execution_tool_result",
+ "tool_use_id": "srvtoolu_01AAA",
+ "content": {
+ "type": "bash_code_execution_result",
+ "stdout": "first\n",
+ "stderr": "",
+ "return_code": 0,
+ },
+ },
+ },
+ {"type": "content_block_stop", "index": 1},
+ # Second code execution
+ {
+ "type": "content_block_start",
+ "index": 2,
+ "content_block": {
+ "type": "server_tool_use",
+ "id": "srvtoolu_01BBB",
+ "name": "bash_code_execution",
+ "input": {"command": "echo second"},
+ },
+ },
+ {"type": "content_block_stop", "index": 2},
+ {
+ "type": "content_block_start",
+ "index": 3,
+ "content_block": {
+ "type": "bash_code_execution_tool_result",
+ "tool_use_id": "srvtoolu_01BBB",
+ "content": {
+ "type": "bash_code_execution_result",
+ "stdout": "second\n",
+ "stderr": "",
+ "return_code": 0,
+ },
+ },
+ },
+ {"type": "content_block_stop", "index": 3},
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn"},
+ "usage": {"output_tokens": 50},
+ },
+ ]
+
+ iterator = ModelResponseIterator(None, sync_stream=True)
+
+ # Collect ALL code_interpreter_results emitted across all chunks
+ all_results = []
+ for chunk in chunks:
+ parsed = iterator.chunk_parser(chunk)
+ psf = None
+ if parsed.choices and parsed.choices[0].delta:
+ psf = getattr(parsed.choices[0].delta, "provider_specific_fields", None)
+ if psf and "code_interpreter_results" in psf:
+ all_results.extend(psf["code_interpreter_results"])
+
+ # Should have exactly 2 results, one per execution — no duplicates
+ assert len(all_results) == 2, (
+ f"Expected 2 code_interpreter_results, got {len(all_results)}. "
+ f"IDs: {[r.id for r in all_results]}"
+ )
+ assert all_results[0].id == "srvtoolu_01AAA"
+ assert all_results[0].code == "echo first"
+ assert all_results[0].outputs[0].logs == "first\n"
+ assert all_results[1].id == "srvtoolu_01BBB"
+ assert all_results[1].code == "echo second"
+ assert all_results[1].outputs[0].logs == "second\n"
diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
index a95b9413b9d..a3469964862 100644
--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
@@ -183,7 +183,9 @@ def test_extract_response_content_with_citations():
},
}
- _, citations, _, _, _, _, _, _ = config.extract_response_content(completion_response)
+ _, citations, _, _, _, _, _, _ = config.extract_response_content(
+ completion_response
+ )
assert citations == [
[
{
@@ -305,7 +307,7 @@ def test_web_search_tool_result_extraction():
"type": "server_tool_use",
"id": "srvtoolu_01ABC123",
"name": "web_search",
- "input": {"query": "average weight african elephant kg"}
+ "input": {"query": "average weight african elephant kg"},
},
{
"type": "web_search_tool_result",
@@ -317,32 +319,39 @@ def test_web_search_tool_result_extraction():
"title": "African Elephant Facts",
"encrypted_content": "encrypted_data_here",
"page_age": "2024-01-15",
- "snippet": "Adult African elephants weigh between 4,000-6,000 kg..."
+ "snippet": "Adult African elephants weigh between 4,000-6,000 kg...",
}
- ]
+ ],
},
{
"type": "text",
- "text": "Based on my search, African elephants weigh around 5,000 kg."
+ "text": "Based on my search, African elephants weigh around 5,000 kg.",
},
{
"type": "tool_use",
"id": "toolu_01XYZ789",
"name": "add_numbers",
- "input": {"a": 5000, "b": 100}
- }
+ "input": {"a": 5000, "b": 100},
+ },
],
"stop_reason": "tool_use",
"usage": {
"input_tokens": 100,
"output_tokens": 50,
- "server_tool_use": {"web_search_requests": 1}
- }
+ "server_tool_use": {"web_search_requests": 1},
+ },
}
- text, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(
- completion_response
- )
+ (
+ text,
+ citations,
+ thinking_blocks,
+ reasoning_content,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
# Verify text extraction
assert "Based on my search" in text
@@ -388,7 +397,7 @@ def test_web_search_tool_result_in_provider_specific_fields():
"type": "server_tool_use",
"id": "srvtoolu_provider_test",
"name": "web_search",
- "input": {"query": "test query"}
+ "input": {"query": "test query"},
},
{
"type": "web_search_tool_result",
@@ -398,21 +407,18 @@ def test_web_search_tool_result_in_provider_specific_fields():
"type": "web_search_result",
"url": "https://example.com/test",
"title": "Test Result",
- "snippet": "Test snippet content"
+ "snippet": "Test snippet content",
}
- ]
+ ],
},
- {
- "type": "text",
- "text": "Here is the result."
- }
+ {"type": "text", "text": "Here is the result."},
],
"stop_reason": "end_turn",
"usage": {
"input_tokens": 50,
"output_tokens": 25,
- "server_tool_use": {"web_search_requests": 1}
- }
+ "server_tool_use": {"web_search_requests": 1},
+ },
}
raw_response = httpx.Response(status_code=200, headers={})
@@ -432,7 +438,10 @@ def test_web_search_tool_result_in_provider_specific_fields():
assert "web_search_results" in provider_fields
assert len(provider_fields["web_search_results"]) == 1
assert provider_fields["web_search_results"][0]["type"] == "web_search_tool_result"
- assert provider_fields["web_search_results"][0]["tool_use_id"] == "srvtoolu_provider_test"
+ assert (
+ provider_fields["web_search_results"][0]["tool_use_id"]
+ == "srvtoolu_provider_test"
+ )
def test_multiple_web_search_tool_results():
@@ -447,34 +456,52 @@ def test_multiple_web_search_tool_results():
"type": "server_tool_use",
"id": "srvtoolu_search1",
"name": "web_search",
- "input": {"query": "african elephant weight"}
+ "input": {"query": "african elephant weight"},
},
{
"type": "web_search_tool_result",
"tool_use_id": "srvtoolu_search1",
- "content": [{"type": "web_search_result", "url": "https://example1.com", "title": "Result 1", "snippet": "First result"}]
+ "content": [
+ {
+ "type": "web_search_result",
+ "url": "https://example1.com",
+ "title": "Result 1",
+ "snippet": "First result",
+ }
+ ],
},
{
"type": "server_tool_use",
"id": "srvtoolu_search2",
"name": "web_search",
- "input": {"query": "asian elephant weight"}
+ "input": {"query": "asian elephant weight"},
},
{
"type": "web_search_tool_result",
"tool_use_id": "srvtoolu_search2",
- "content": [{"type": "web_search_result", "url": "https://example2.com", "title": "Result 2", "snippet": "Second result"}]
+ "content": [
+ {
+ "type": "web_search_result",
+ "url": "https://example2.com",
+ "title": "Result 2",
+ "snippet": "Second result",
+ }
+ ],
},
- {
- "type": "text",
- "text": "Found information about both elephants."
- }
+ {"type": "text", "text": "Found information about both elephants."},
]
}
- text, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(
- completion_response
- )
+ (
+ text,
+ citations,
+ thinking_blocks,
+ reasoning_content,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
# Verify both web_search_tool_results are extracted
assert web_search_results is not None
@@ -751,7 +778,7 @@ def test_anthropic_beta_header_merging_with_output_format():
optional_params = {
"output_format": {
"type": "json_schema",
- "schema": {"type": "object", "properties": {}}
+ "schema": {"type": "object", "properties": {}},
}
}
@@ -761,10 +788,12 @@ def test_anthropic_beta_header_merging_with_output_format():
# Both beta headers should be present
beta_value = result_headers["anthropic-beta"]
- assert "context-1m-2025-08-07" in beta_value, \
- f"User's context-1m beta header missing from: {beta_value}"
- assert "structured-outputs-2025-11-13" in beta_value, \
- f"Structured output beta header missing from: {beta_value}"
+ assert (
+ "context-1m-2025-08-07" in beta_value
+ ), f"User's context-1m beta header missing from: {beta_value}"
+ assert (
+ "structured-outputs-2025-11-13" in beta_value
+ ), f"Structured output beta header missing from: {beta_value}"
def test_anthropic_beta_header_merging_with_multiple_features():
@@ -780,10 +809,10 @@ def test_anthropic_beta_header_merging_with_multiple_features():
optional_params = {
"output_format": {
"type": "json_schema",
- "schema": {"type": "object", "properties": {}}
+ "schema": {"type": "object", "properties": {}},
},
"context_management": _sample_context_management_payload(),
- "tools": [{"type": "web_fetch_20250910", "name": "web_fetch"}]
+ "tools": [{"type": "web_fetch_20250910", "name": "web_fetch"}],
}
result_headers = config.update_headers_with_optional_anthropic_beta(
@@ -950,20 +979,12 @@ def test_tool_search_regex_detection():
# Test with tool search regex tool
tools = [
- {
- "type": "tool_search_tool_regex_20251119",
- "name": "tool_search_tool_regex"
- }
+ {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}
]
assert config.is_tool_search_used(tools) is True
# Test without tool search
- tools = [
- {
- "type": "function",
- "function": {"name": "get_weather"}
- }
- ]
+ tools = [{"type": "function", "function": {"name": "get_weather"}}]
assert config.is_tool_search_used(tools) is False
@@ -975,10 +996,7 @@ def test_tool_search_bm25_detection():
# Test with tool search BM25 tool
tools = [
- {
- "type": "tool_search_tool_bm25_20251119",
- "name": "tool_search_tool_bm25"
- }
+ {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"}
]
assert config.is_tool_search_used(tools) is True
@@ -1002,10 +1020,7 @@ def test_tool_search_regex_mapping():
"""Test that tool search regex tools are properly mapped"""
config = AnthropicConfig()
- tool = {
- "type": "tool_search_tool_regex_20251119",
- "name": "tool_search_tool_regex"
- }
+ tool = {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}
mapped_tool, mcp_server = config._map_tool_helper(tool)
@@ -1019,10 +1034,7 @@ def test_tool_search_bm25_mapping():
"""Test that tool search BM25 tools are properly mapped"""
config = AnthropicConfig()
- tool = {
- "type": "tool_search_tool_bm25_20251119",
- "name": "tool_search_tool_bm25"
- }
+ tool = {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"}
mapped_tool, mcp_server = config._map_tool_helper(tool)
@@ -1037,20 +1049,17 @@ def test_deferred_tools_separation():
config = AnthropicConfig()
tools = [
- {
- "type": "tool_search_tool_regex_20251119",
- "name": "tool_search_tool_regex"
- },
+ {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"},
{
"type": "function",
"function": {"name": "get_weather"},
- "defer_loading": True
+ "defer_loading": True,
},
{
"type": "function",
"function": {"name": "search_files"},
- "defer_loading": False
- }
+ "defer_loading": False,
+ },
]
non_deferred, deferred = config._separate_deferred_tools(tools)
@@ -1069,14 +1078,21 @@ def test_server_tool_use_in_response():
"type": "server_tool_use",
"id": "srvtoolu_01ABC123",
"name": "tool_search_tool_regex",
- "input": {"query": "weather"}
+ "input": {"query": "weather"},
}
]
}
- text, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(
- completion_response
- )
+ (
+ text,
+ citations,
+ thinking_blocks,
+ reasoning_content,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
assert len(tool_calls) == 1
assert tool_calls[0]["id"] == "srvtoolu_01ABC123"
@@ -1091,9 +1107,7 @@ def test_tool_search_usage_tracking():
usage_object = {
"input_tokens": 100,
"output_tokens": 50,
- "server_tool_use": {
- "tool_search_requests": 2
- }
+ "server_tool_use": {"tool_search_requests": 2},
}
usage = config.calculate_usage(usage_object=usage_object, reasoning_content=None)
@@ -1109,16 +1123,13 @@ def test_tool_reference_expansion():
deferred_tools = [
{
"type": "function",
- "function": {
- "name": "get_weather",
- "description": "Get weather"
- }
+ "function": {"name": "get_weather", "description": "Get weather"},
}
]
content = [
{"type": "text", "text": "I'll search for tools"},
- {"type": "tool_reference", "tool_name": "get_weather"}
+ {"type": "tool_reference", "tool_name": "get_weather"},
]
expanded = config._expand_tool_references(content, deferred_tools)
@@ -1140,13 +1151,11 @@ def test_defer_loading_preserved_in_transformation():
"description": "Get weather information",
"parameters": {
"type": "object",
- "properties": {
- "location": {"type": "string"}
- },
- "required": ["location"]
- }
+ "properties": {"location": {"type": "string"}},
+ "required": ["location"],
+ },
},
- "defer_loading": True
+ "defer_loading": True,
}
mapped_tool, mcp_server = config._map_tool_helper(tool)
@@ -1166,45 +1175,51 @@ def test_tool_search_complete_response_parsing():
"content": [
{
"type": "text",
- "text": "I'll search for weather-related tools that can help you."
+ "text": "I'll search for weather-related tools that can help you.",
},
{
"type": "server_tool_use",
"id": "srvtoolu_015i6aVA2niwzv4RG4DtnxDJ",
"name": "tool_search_tool_regex",
"input": {"pattern": "weather", "limit": 5},
- "caller": {"type": "direct"}
+ "caller": {"type": "direct"},
},
{
"type": "tool_search_tool_result",
"tool_use_id": "srvtoolu_015i6aVA2niwzv4RG4DtnxDJ",
"content": {
"type": "tool_search_tool_search_result",
- "tool_references": [{"type": "tool_reference", "tool_name": "get_weather"}]
- }
- },
- {
- "type": "text",
- "text": "Great! I found a weather tool."
+ "tool_references": [
+ {"type": "tool_reference", "tool_name": "get_weather"}
+ ],
+ },
},
+ {"type": "text", "text": "Great! I found a weather tool."},
{
"type": "tool_use",
"id": "toolu_01CrCNx4ntSaeeV9iArT4JfQ",
"name": "get_weather",
- "input": {"location": "San Francisco"}
- }
+ "input": {"location": "San Francisco"},
+ },
],
"usage": {
"input_tokens": 1639,
"output_tokens": 170,
- "server_tool_use": {"web_search_requests": 0}
- }
+ "server_tool_use": {"web_search_requests": 0},
+ },
}
# Extract content
- text, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(
- completion_response
- )
+ (
+ text,
+ citations,
+ thinking_blocks,
+ reasoning_content,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
# Verify text extraction (should concatenate both text blocks)
assert "I'll search for weather-related tools" in text
@@ -1222,12 +1237,14 @@ def test_tool_search_complete_response_parsing():
usage = config.calculate_usage(
usage_object=completion_response["usage"],
reasoning_content=None,
- completion_response=completion_response
+ completion_response=completion_response,
)
assert usage.server_tool_use is not None
assert usage.server_tool_use.web_search_requests == 0
- assert usage.server_tool_use.tool_search_requests == 1 # Counted from server_tool_use blocks
+ assert (
+ usage.server_tool_use.tool_search_requests == 1
+ ) # Counted from server_tool_use blocks
def test_allowed_callers_field_preservation():
@@ -1242,13 +1259,11 @@ def test_allowed_callers_field_preservation():
"description": "Execute a SQL query",
"parameters": {
"type": "object",
- "properties": {
- "sql": {"type": "string"}
- },
- "required": ["sql"]
- }
+ "properties": {"sql": {"type": "string"}},
+ "required": ["sql"],
+ },
},
- "allowed_callers": ["code_execution_20250825"]
+ "allowed_callers": ["code_execution_20250825"],
}
transformed_tool, _ = config._map_tool_helper(tool_with_allowed_callers)
@@ -1265,19 +1280,16 @@ def test_programmatic_tool_calling_beta_header():
# Test detection with allowed_callers
tools = [
- {
- "type": "code_execution_20250825",
- "name": "code_execution"
- },
+ {"type": "code_execution_20250825", "name": "code_execution"},
{
"type": "function",
"function": {
"name": "query_database",
"description": "Execute a SQL query",
- "parameters": {"type": "object", "properties": {}}
+ "parameters": {"type": "object", "properties": {}},
},
- "allowed_callers": ["code_execution_20250825"]
- }
+ "allowed_callers": ["code_execution_20250825"],
+ },
]
is_programmatic = model_info.is_programmatic_tool_calling_used(tools)
@@ -1285,8 +1297,7 @@ def test_programmatic_tool_calling_beta_header():
# Test header generation
headers = model_info.get_anthropic_headers(
- api_key="test-key",
- programmatic_tool_calling_used=True
+ api_key="test-key", programmatic_tool_calling_used=True
)
assert "anthropic-beta" in headers
@@ -1303,10 +1314,7 @@ def test_caller_field_in_response():
"type": "message",
"role": "assistant",
"content": [
- {
- "type": "text",
- "text": "I'll query the database."
- },
+ {"type": "text", "text": "I'll query the database."},
{
"type": "tool_use",
"id": "toolu_123",
@@ -1314,15 +1322,24 @@ def test_caller_field_in_response():
"input": {"sql": "SELECT * FROM users"},
"caller": {
"type": "code_execution_20250825",
- "tool_id": "srvtoolu_abc"
- }
- }
+ "tool_id": "srvtoolu_abc",
+ },
+ },
],
"stop_reason": "tool_use",
- "usage": {"input_tokens": 100, "output_tokens": 50}
+ "usage": {"input_tokens": 100, "output_tokens": 50},
}
- text, citations, thinking, reasoning, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(completion_response)
+ (
+ text,
+ citations,
+ thinking,
+ reasoning,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
assert len(tool_calls) == 1
assert tool_calls[0]["id"] == "toolu_123"
@@ -1337,10 +1354,7 @@ def test_code_execution_20250825_tool_type():
"""Test that code_execution_20250825 tool type is handled correctly."""
config = AnthropicConfig()
- tool = {
- "type": "code_execution_20250825",
- "name": "code_execution"
- }
+ tool = {"type": "code_execution_20250825", "name": "code_execution"}
transformed_tool, _ = config._map_tool_helper(tool)
assert transformed_tool is not None
@@ -1360,13 +1374,11 @@ def test_allowed_callers_in_function_field():
"description": "Execute a SQL query",
"parameters": {
"type": "object",
- "properties": {
- "sql": {"type": "string"}
- },
- "required": ["sql"]
+ "properties": {"sql": {"type": "string"}},
+ "required": ["sql"],
},
- "allowed_callers": ["code_execution_20250825"]
- }
+ "allowed_callers": ["code_execution_20250825"],
+ },
}
transformed_tool, _ = config._map_tool_helper(tool)
@@ -1389,15 +1401,15 @@ def test_input_examples_field_preservation():
"type": "object",
"properties": {
"location": {"type": "string"},
- "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
+ "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
- "required": ["location"]
- }
+ "required": ["location"],
+ },
},
"input_examples": [
{"location": "San Francisco, CA", "unit": "fahrenheit"},
- {"location": "Tokyo, Japan", "unit": "celsius"}
- ]
+ {"location": "Tokyo, Japan", "unit": "celsius"},
+ ],
}
transformed_tool, _ = config._map_tool_helper(tool_with_examples)
@@ -1420,11 +1432,9 @@ def test_input_examples_beta_header():
"function": {
"name": "get_weather",
"description": "Get weather information",
- "parameters": {"type": "object", "properties": {}}
+ "parameters": {"type": "object", "properties": {}},
},
- "input_examples": [
- {"location": "San Francisco, CA"}
- ]
+ "input_examples": [{"location": "San Francisco, CA"}],
}
]
@@ -1433,8 +1443,7 @@ def test_input_examples_beta_header():
# Test header generation
headers = model_info.get_anthropic_headers(
- api_key="test-key",
- input_examples_used=True
+ api_key="test-key", input_examples_used=True
)
assert "anthropic-beta" in headers
@@ -1453,16 +1462,14 @@ def test_input_examples_in_function_field():
"description": "Get weather information",
"parameters": {
"type": "object",
- "properties": {
- "location": {"type": "string"}
- },
- "required": ["location"]
+ "properties": {"location": {"type": "string"}},
+ "required": ["location"],
},
"input_examples": [
{"location": "Paris, France"},
- {"location": "London, UK"}
- ]
- }
+ {"location": "London, UK"},
+ ],
+ },
}
transformed_tool, _ = config._map_tool_helper(tool)
@@ -1483,17 +1490,13 @@ def test_input_examples_with_other_features():
"description": "Execute a SQL query",
"parameters": {
"type": "object",
- "properties": {
- "sql": {"type": "string"}
- },
- "required": ["sql"]
- }
+ "properties": {"sql": {"type": "string"}},
+ "required": ["sql"],
+ },
},
- "input_examples": [
- {"sql": "SELECT * FROM users WHERE id = 1"}
- ],
+ "input_examples": [{"sql": "SELECT * FROM users WHERE id = 1"}],
"defer_loading": True,
- "allowed_callers": ["code_execution_20250825"]
+ "allowed_callers": ["code_execution_20250825"],
}
transformed_tool, _ = config._map_tool_helper(tool)
@@ -1517,19 +1520,20 @@ def test_input_examples_empty_list_not_added():
"description": "Get weather information",
"parameters": {
"type": "object",
- "properties": {
- "location": {"type": "string"}
- },
- "required": ["location"]
- }
+ "properties": {"location": {"type": "string"}},
+ "required": ["location"],
+ },
},
- "input_examples": []
+ "input_examples": [],
}
transformed_tool, _ = config._map_tool_helper(tool)
assert transformed_tool is not None
# Empty list should not be added
- assert "input_examples" not in transformed_tool or len(transformed_tool.get("input_examples", [])) == 0
+ assert (
+ "input_examples" not in transformed_tool
+ or len(transformed_tool.get("input_examples", [])) == 0
+ )
# ============ Effort Parameter Tests ============
@@ -1540,18 +1544,14 @@ def test_effort_output_config_preservation():
config = AnthropicConfig()
messages = [{"role": "user", "content": "Analyze this code"}]
- optional_params = {
- "output_config": {
- "effort": "medium"
- }
- }
+ optional_params = {"output_config": {"effort": "medium"}}
result = config.transform_request(
model="claude-opus-4-5-20251101",
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
assert "output_config" in result
@@ -1565,18 +1565,13 @@ def test_effort_beta_header_injection():
model_info = AnthropicModelInfo()
# Test with effort parameter
- optional_params = {
- "output_config": {
- "effort": "low"
- }
- }
+ optional_params = {"output_config": {"effort": "low"}}
effort_used = model_info.is_effort_used(optional_params=optional_params)
assert effort_used is True
headers = model_info.get_anthropic_headers(
- api_key="test-key",
- effort_used=effort_used
+ api_key="test-key", effort_used=effort_used
)
assert "anthropic-beta" in headers
@@ -1597,7 +1592,7 @@ def test_effort_validation():
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
assert result["output_config"]["effort"] == effort
@@ -1609,7 +1604,7 @@ def test_effort_validation():
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
@@ -1618,18 +1613,14 @@ def test_effort_with_claude_opus_45():
config = AnthropicConfig()
messages = [{"role": "user", "content": "Complex analysis task"}]
- optional_params = {
- "output_config": {
- "effort": "high"
- }
- }
+ optional_params = {"output_config": {"effort": "high"}}
result = config.transform_request(
model="claude-opus-4-5-20251101",
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
assert "output_config" in result
@@ -1650,7 +1641,7 @@ def test_effort_validation_with_opus_46():
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
assert result["output_config"]["effort"] == effort
@@ -1661,14 +1652,16 @@ def test_max_effort_rejected_for_opus_45():
messages = [{"role": "user", "content": "Test"}]
- with pytest.raises(ValueError, match="effort='max' is only supported by Claude Opus 4.6"):
+ with pytest.raises(
+ ValueError, match="effort='max' is only supported by Claude Opus 4.6"
+ ):
optional_params = {"output_config": {"effort": "max"}}
config.transform_request(
model="claude-opus-4-5-20251101",
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
@@ -1685,23 +1678,16 @@ def test_effort_with_other_features():
"description": "Get data",
"parameters": {
"type": "object",
- "properties": {
- "query": {"type": "string"}
- },
- "required": ["query"]
- }
- }
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ },
+ },
}
]
optional_params = {
- "output_config": {
- "effort": "low"
- },
+ "output_config": {"effort": "low"},
"tools": tools,
- "thinking": {
- "type": "enabled",
- "budget_tokens": 1000
- }
+ "thinking": {"type": "enabled", "budget_tokens": 1000},
}
result = config.transform_request(
@@ -1709,7 +1695,7 @@ def test_effort_with_other_features():
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
# Verify all features are present
@@ -1752,11 +1738,14 @@ def test_translate_system_message_skips_empty_list_content():
# Test list content with empty text block
messages = [
- {"role": "system", "content": [
- {"type": "text", "text": ""},
- {"type": "text", "text": "Valid content"},
- {"type": "text", "text": ""},
- ]},
+ {
+ "role": "system",
+ "content": [
+ {"type": "text", "text": ""},
+ {"type": "text", "text": "Valid content"},
+ {"type": "text", "text": ""},
+ ],
+ },
{"role": "user", "content": "Hello"},
]
@@ -1794,9 +1783,16 @@ def test_translate_system_message_preserves_cache_control():
# Test list content with cache_control
messages = [
- {"role": "system", "content": [
- {"type": "text", "text": "Cached content", "cache_control": {"type": "ephemeral"}},
- ]},
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "Cached content",
+ "cache_control": {"type": "ephemeral"},
+ },
+ ],
+ },
{"role": "user", "content": "Hello"},
]
@@ -1938,7 +1934,7 @@ def test_transform_request_uses_dynamic_max_tokens():
messages=messages,
optional_params={}, # No max_tokens provided
litellm_params={},
- headers={}
+ headers={},
)
assert result["max_tokens"] == 64000
@@ -1959,7 +1955,7 @@ def test_transform_request_respects_user_max_tokens():
messages=messages,
optional_params={"max_tokens": 1000},
litellm_params={},
- headers={}
+ headers={},
)
assert result["max_tokens"] == 1000
@@ -2006,11 +2002,12 @@ def test_calculate_usage_completion_tokens_details_with_reasoning():
"output_tokens": 500,
}
# Simulating reasoning content that would count as ~50 tokens
- reasoning_content = "Let me think about this step by step. " * 10 # Roughly 50 tokens
+ reasoning_content = (
+ "Let me think about this step by step. " * 10
+ ) # Roughly 50 tokens
usage = config.calculate_usage(
- usage_object=usage_object,
- reasoning_content=reasoning_content
+ usage_object=usage_object, reasoning_content=reasoning_content
)
# completion_tokens_details should be populated with both reasoning and text tokens
@@ -2051,7 +2048,7 @@ def test_reasoning_effort_maps_to_adaptive_thinking_for_claude_4_6_models():
non_default_params=non_default_params,
optional_params=optional_params,
model=model,
- drop_params=False
+ drop_params=False,
)
# Should map to adaptive thinking type
@@ -2062,7 +2059,9 @@ def test_reasoning_effort_maps_to_adaptive_thinking_for_claude_4_6_models():
# reasoning_effort should not be in the result (it's transformed to thinking)
assert "reasoning_effort" not in result
# Should set output_config with the mapped effort value
- assert "output_config" in result, f"output_config missing for {model} with effort={effort}"
+ assert (
+ "output_config" in result
+ ), f"output_config missing for {model} with effort={effort}"
assert result["output_config"]["effort"] == effort_map[effort]
@@ -2123,10 +2122,10 @@ def test_reasoning_effort_maps_to_budget_thinking_for_non_opus_4_6():
# Test with Claude Sonnet 4.5 (non-Opus 4.6 model)
test_cases = [
- ("low", 1024), # DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET
- ("medium", 2048), # DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET
- ("high", 4096), # DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET
- ("minimal", 128), # DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET
+ ("low", 1024), # DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET
+ ("medium", 2048), # DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET
+ ("high", 4096), # DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET
+ ("minimal", 128), # DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET
]
for effort, expected_budget in test_cases:
@@ -2137,7 +2136,7 @@ def test_reasoning_effort_maps_to_budget_thinking_for_non_opus_4_6():
non_default_params=non_default_params,
optional_params=optional_params,
model="claude-sonnet-4-5-20250929",
- drop_params=False
+ drop_params=False,
)
# Should map to enabled thinking type with budget_tokens
@@ -2166,9 +2165,9 @@ def test_reasoning_effort_sets_output_config_for_46_models():
drop_params=False,
)
- assert "output_config" in result, (
- f"output_config missing for {model} with effort={effort}"
- )
+ assert (
+ "output_config" in result
+ ), f"output_config missing for {model} with effort={effort}"
assert result["output_config"]["effort"] == effort
@@ -2207,9 +2206,9 @@ def test_reasoning_effort_does_not_set_output_config_for_older_models():
drop_params=False,
)
- assert "output_config" not in result, (
- f"output_config should not be set for {model}"
- )
+ assert (
+ "output_config" not in result
+ ), f"output_config should not be set for {model}"
def test_max_effort_rejected_for_sonnet_46():
@@ -2217,7 +2216,9 @@ def test_max_effort_rejected_for_sonnet_46():
config = AnthropicConfig()
messages = [{"role": "user", "content": "Test"}]
- with pytest.raises(ValueError, match="effort='max' is only supported by Claude Opus 4.6"):
+ with pytest.raises(
+ ValueError, match="effort='max' is only supported by Claude Opus 4.6"
+ ):
config.transform_request(
model="claude-sonnet-4-6-20260219",
messages=messages,
@@ -2260,9 +2261,7 @@ def test_effort_beta_header_not_injected_for_46_models():
optional_params={"output_config": {"effort": "high"}},
model=model,
)
- assert result is False, (
- f"is_effort_used should return False for {model}"
- )
+ assert result is False, f"is_effort_used should return False for {model}"
def test_effort_beta_header_still_injected_for_older_models():
@@ -2302,17 +2301,12 @@ def test_code_execution_tool_results_extraction():
"role": "assistant",
"model": "claude-sonnet-4-5-20250929",
"content": [
- {
- "type": "text",
- "text": "I'll calculate that for you."
- },
+ {"type": "text", "text": "I'll calculate that for you."},
{
"type": "server_tool_use",
"id": "srvtoolu_01ABC",
"name": "bash_code_execution",
- "input": {
- "command": "python3 << 'EOF'\nprint(2 + 2)\nEOF\n"
- }
+ "input": {"command": "python3 << 'EOF'\nprint(2 + 2)\nEOF\n"},
},
{
"type": "bash_code_execution_tool_result",
@@ -2321,8 +2315,8 @@ def test_code_execution_tool_results_extraction():
"type": "bash_code_execution_result",
"stdout": "4\n",
"stderr": "",
- "return_code": 0
- }
+ "return_code": 0,
+ },
},
{
"type": "server_tool_use",
@@ -2331,28 +2325,22 @@ def test_code_execution_tool_results_extraction():
"input": {
"command": "create",
"path": "test.txt",
- "file_text": "Hello"
- }
+ "file_text": "Hello",
+ },
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01DEF",
"content": {
"type": "text_editor_code_execution_result",
- "is_file_update": False
- }
+ "is_file_update": False,
+ },
},
- {
- "type": "text",
- "text": "Done!"
- }
+ {"type": "text", "text": "Done!"},
],
"stop_reason": "stop",
"stop_sequence": None,
- "usage": {
- "input_tokens": 100,
- "output_tokens": 50
- }
+ "usage": {"input_tokens": 100, "output_tokens": 50},
}
# Create mock HTTP response
@@ -2377,11 +2365,17 @@ def test_code_execution_tool_results_extraction():
# Verify first tool call
assert transformed_response.choices[0].message.tool_calls[0].id == "srvtoolu_01ABC"
- assert transformed_response.choices[0].message.tool_calls[0].function.name == "bash_code_execution"
+ assert (
+ transformed_response.choices[0].message.tool_calls[0].function.name
+ == "bash_code_execution"
+ )
# Verify second tool call
assert transformed_response.choices[0].message.tool_calls[1].id == "srvtoolu_01DEF"
- assert transformed_response.choices[0].message.tool_calls[1].function.name == "text_editor_code_execution"
+ assert (
+ transformed_response.choices[0].message.tool_calls[1].function.name
+ == "text_editor_code_execution"
+ )
# Verify tool results are in provider_specific_fields
provider_fields = transformed_response.choices[0].message.provider_specific_fields
@@ -2404,14 +2398,21 @@ def test_code_execution_tool_results_extraction():
assert editor_result["content"]["is_file_update"] is False
# Verify text content is properly concatenated
- assert "I'll calculate that for you." in transformed_response.choices[0].message.content
+ assert (
+ "I'll calculate that for you."
+ in transformed_response.choices[0].message.content
+ )
assert "Done!" in transformed_response.choices[0].message.content
-def test_tool_search_tool_result_not_in_tool_results():
+def test_code_execution_tool_results_in_hidden_params():
"""
- Test that tool_search_tool_result is NOT included in tool_results
- since it's internal metadata, not actual tool execution results.
+ Test that tool_results reaches _hidden_params so the Responses API adapter
+ can surface them via provider_specific_fields.
+
+ The Responses API adapter reads _hidden_params.get("provider_specific_fields")
+ to set provider_specific_fields on the response. Without this, server-side
+ code execution results (stdout/stderr) are lost when using responses.create().
"""
import httpx
@@ -2425,21 +2426,78 @@ def test_tool_search_tool_result_not_in_tool_results():
"role": "assistant",
"model": "claude-sonnet-4-5-20250929",
"content": [
+ {"type": "text", "text": "Here's the result."},
{
- "type": "text",
- "text": "Found tools."
+ "type": "server_tool_use",
+ "id": "srvtoolu_01ABC",
+ "name": "bash_code_execution",
+ "input": {"command": "echo hello"},
},
{
- "type": "tool_search_tool_result",
- "tool_references": ["tool1", "tool2"]
- }
+ "type": "bash_code_execution_tool_result",
+ "tool_use_id": "srvtoolu_01ABC",
+ "content": {
+ "type": "bash_code_execution_result",
+ "stdout": "hello\n",
+ "stderr": "",
+ "return_code": 0,
+ },
+ },
],
"stop_reason": "stop",
"stop_sequence": None,
- "usage": {
- "input_tokens": 100,
- "output_tokens": 50
- }
+ "usage": {"input_tokens": 100, "output_tokens": 50},
+ }
+
+ mock_raw_response = MagicMock(spec=httpx.Response)
+ mock_raw_response.json.return_value = mock_anthropic_response
+ mock_raw_response.status_code = 200
+ mock_raw_response.headers = {}
+
+ model_response = ModelResponse()
+
+ transformed_response = config.transform_parsed_response(
+ completion_response=mock_anthropic_response,
+ raw_response=mock_raw_response,
+ model_response=model_response,
+ json_mode=False,
+ prefix_prompt=None,
+ )
+
+ # Verify tool_results is in _hidden_params for the Responses API adapter
+ hidden = transformed_response._hidden_params
+ assert "provider_specific_fields" in hidden
+ assert "tool_results" in hidden["provider_specific_fields"]
+ assert len(hidden["provider_specific_fields"]["tool_results"]) == 1
+ assert (
+ hidden["provider_specific_fields"]["tool_results"][0]["content"]["stdout"]
+ == "hello\n"
+ )
+
+
+def test_tool_search_tool_result_not_in_tool_results():
+ """
+ Test that tool_search_tool_result is NOT included in tool_results
+ since it's internal metadata, not actual tool execution results.
+ """
+ import httpx
+
+ from litellm.types.utils import ModelResponse
+
+ config = AnthropicConfig()
+
+ mock_anthropic_response = {
+ "id": "msg_01XYZ",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5-20250929",
+ "content": [
+ {"type": "text", "text": "Found tools."},
+ {"type": "tool_search_tool_result", "tool_references": ["tool1", "tool2"]},
+ ],
+ "stop_reason": "stop",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 100, "output_tokens": 50},
}
mock_raw_response = MagicMock(spec=httpx.Response)
@@ -2479,22 +2537,16 @@ def test_web_search_tool_result_backwards_compatibility():
"role": "assistant",
"model": "claude-sonnet-4-5-20250929",
"content": [
- {
- "type": "text",
- "text": "Here are the results."
- },
+ {"type": "text", "text": "Here are the results."},
{
"type": "web_search_tool_result",
"search_query": "test query",
- "results": [{"title": "Result 1", "url": "https://example.com"}]
- }
+ "results": [{"title": "Result 1", "url": "https://example.com"}],
+ },
],
"stop_reason": "stop",
"stop_sequence": None,
- "usage": {
- "input_tokens": 100,
- "output_tokens": 50
- }
+ "usage": {"input_tokens": 100, "output_tokens": 50},
}
mock_raw_response = MagicMock(spec=httpx.Response)
@@ -2540,24 +2592,28 @@ def test_compaction_block_extraction():
"content": [
{
"type": "compaction",
- "content": "Summary of the conversation: The user requested help building a web scraper..."
+ "content": "Summary of the conversation: The user requested help building a web scraper...",
},
{
"type": "text",
- "text": "I don't have access to real-time data, so I can't provide the current weather in San Francisco."
- }
+ "text": "I don't have access to real-time data, so I can't provide the current weather in San Francisco.",
+ },
],
"stop_reason": "max_tokens",
"stop_sequence": None,
- "usage": {
- "input_tokens": 86,
- "output_tokens": 100
- }
+ "usage": {"input_tokens": 86, "output_tokens": 100},
}
- text, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(
- completion_response
- )
+ (
+ text,
+ citations,
+ thinking_blocks,
+ reasoning_content,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
# Verify compaction blocks are extracted
assert compaction_blocks is not None
@@ -2587,18 +2643,12 @@ def test_compaction_block_in_provider_specific_fields():
"content": [
{
"type": "compaction",
- "content": "Summary of the conversation: The user requested help building a web scraper..."
+ "content": "Summary of the conversation: The user requested help building a web scraper...",
},
- {
- "type": "text",
- "text": "Here is the response."
- }
+ {"type": "text", "text": "Here is the response."},
],
"stop_reason": "end_turn",
- "usage": {
- "input_tokens": 50,
- "output_tokens": 25
- }
+ "usage": {"input_tokens": 50, "output_tokens": 25},
}
raw_response = httpx.Response(status_code=200, headers={})
@@ -2618,7 +2668,10 @@ def test_compaction_block_in_provider_specific_fields():
assert "compaction_blocks" in provider_fields
assert len(provider_fields["compaction_blocks"]) == 1
assert provider_fields["compaction_blocks"][0]["type"] == "compaction"
- assert "Summary of the conversation" in provider_fields["compaction_blocks"][0]["content"]
+ assert (
+ "Summary of the conversation"
+ in provider_fields["compaction_blocks"][0]["content"]
+ )
def test_multiple_compaction_blocks():
@@ -2629,24 +2682,22 @@ def test_multiple_compaction_blocks():
completion_response = {
"content": [
- {
- "type": "compaction",
- "content": "First summary..."
- },
- {
- "type": "text",
- "text": "Some text."
- },
- {
- "type": "compaction",
- "content": "Second summary..."
- }
+ {"type": "compaction", "content": "First summary..."},
+ {"type": "text", "text": "Some text."},
+ {"type": "compaction", "content": "Second summary..."},
]
}
- text, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(
- completion_response
- )
+ (
+ text,
+ citations,
+ thinking_blocks,
+ reasoning_content,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
# Verify both compaction blocks are extracted
assert compaction_blocks is not None
@@ -2665,37 +2716,26 @@ def test_compaction_block_request_transformation():
)
messages = [
- {
- "role": "user",
- "content": "What is the weather in San Francisco?"
- },
+ {"role": "user", "content": "What is the weather in San Francisco?"},
{
"role": "assistant",
"content": [
- {
- "type": "text",
- "text": "I don't have access to real-time data."
- }
+ {"type": "text", "text": "I don't have access to real-time data."}
],
"provider_specific_fields": {
"compaction_blocks": [
{
"type": "compaction",
- "content": "Summary of the conversation: The user requested help building a web scraper..."
+ "content": "Summary of the conversation: The user requested help building a web scraper...",
}
]
- }
+ },
},
- {
- "role": "user",
- "content": "What about New York?"
- }
+ {"role": "user", "content": "What about New York?"},
]
result = anthropic_messages_pt(
- messages=messages,
- model="claude-opus-4-6",
- llm_provider="anthropic"
+ messages=messages, model="claude-opus-4-6", llm_provider="anthropic"
)
# Find the assistant message
@@ -2727,14 +2767,8 @@ def test_compaction_with_context_management():
messages = [{"role": "user", "content": "Hello"}]
optional_params = {
- "context_management": {
- "edits": [
- {
- "type": "compact_20260112"
- }
- ]
- },
- "max_tokens": 100
+ "context_management": {"edits": [{"type": "compact_20260112"}]},
+ "max_tokens": 100,
}
result = config.transform_request(
@@ -2742,7 +2776,7 @@ def test_compaction_with_context_management():
messages=messages,
optional_params=optional_params,
litellm_params={},
- headers={}
+ headers={},
)
# Verify context_management is included
@@ -2758,30 +2792,28 @@ def test_compaction_block_with_other_content_types():
completion_response = {
"content": [
- {
- "type": "compaction",
- "content": "Summary of previous conversation..."
- },
- {
- "type": "thinking",
- "thinking": "Let me think about this..."
- },
- {
- "type": "text",
- "text": "Based on my analysis..."
- },
+ {"type": "compaction", "content": "Summary of previous conversation..."},
+ {"type": "thinking", "thinking": "Let me think about this..."},
+ {"type": "text", "text": "Based on my analysis..."},
{
"type": "tool_use",
"id": "toolu_123",
"name": "get_weather",
- "input": {"location": "San Francisco"}
- }
+ "input": {"location": "San Francisco"},
+ },
]
}
- text, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks = config.extract_response_content(
- completion_response
- )
+ (
+ text,
+ citations,
+ thinking_blocks,
+ reasoning_content,
+ tool_calls,
+ web_search_results,
+ tool_results,
+ compaction_blocks,
+ ) = config.extract_response_content(completion_response)
# Verify all content types are extracted
assert compaction_blocks is not None
@@ -2798,11 +2830,11 @@ def test_map_openai_context_management_to_anthropic():
Test mapping OpenAI Responses API context_management format to Anthropic format.
"""
config = AnthropicConfig()
-
+
# Test OpenAI list format with compaction
openai_format = [{"type": "compaction", "compact_threshold": 200000}]
result = config.map_openai_context_management_to_anthropic(openai_format)
-
+
assert result is not None
assert "edits" in result
assert len(result["edits"]) == 1
@@ -2811,26 +2843,32 @@ def test_map_openai_context_management_to_anthropic():
assert result["edits"][0]["trigger"]["value"] == 200000
# Test OpenAI format with instructions
- openai_format_with_instructions = [{
- "type": "compaction",
- "compact_threshold": 150000,
- "instructions": "Focus on preserving code snippets"
- }]
- result = config.map_openai_context_management_to_anthropic(openai_format_with_instructions)
-
+ openai_format_with_instructions = [
+ {
+ "type": "compaction",
+ "compact_threshold": 150000,
+ "instructions": "Focus on preserving code snippets",
+ }
+ ]
+ result = config.map_openai_context_management_to_anthropic(
+ openai_format_with_instructions
+ )
+
assert result is not None
assert result["edits"][0]["trigger"]["value"] == 150000
assert result["edits"][0]["instructions"] == "Focus on preserving code snippets"
-
+
# Test Anthropic format (should pass through)
anthropic_format = {
- "edits": [{
- "type": "compact_20260112",
- "trigger": {"type": "input_tokens", "value": 150000}
- }]
+ "edits": [
+ {
+ "type": "compact_20260112",
+ "trigger": {"type": "input_tokens", "value": 150000},
+ }
+ ]
}
result = config.map_openai_context_management_to_anthropic(anthropic_format)
-
+
assert result == anthropic_format
@@ -2839,46 +2877,51 @@ def test_map_openai_params_with_context_management():
Test that map_openai_params correctly transforms context_management from OpenAI to Anthropic format.
"""
config = AnthropicConfig()
-
+
# Test with OpenAI list format
non_default_params = {
"context_management": [{"type": "compaction", "compact_threshold": 200000}]
}
optional_params = {}
-
+
result = config.map_openai_params(
non_default_params=non_default_params,
optional_params=optional_params,
model="claude-opus-4-6",
- drop_params=False
+ drop_params=False,
)
-
+
assert "context_management" in result
assert "edits" in result["context_management"]
assert result["context_management"]["edits"][0]["type"] == "compact_20260112"
assert result["context_management"]["edits"][0]["trigger"]["value"] == 200000
-
+
# Test with Anthropic dict format (should pass through)
non_default_params_anthropic = {
"context_management": {
- "edits": [{
- "type": "compact_20260112",
- "trigger": {"type": "input_tokens", "value": 150000},
- "instructions": "Focus on preserving code"
- }]
+ "edits": [
+ {
+ "type": "compact_20260112",
+ "trigger": {"type": "input_tokens", "value": 150000},
+ "instructions": "Focus on preserving code",
+ }
+ ]
}
}
optional_params = {}
-
+
result = config.map_openai_params(
non_default_params=non_default_params_anthropic,
optional_params=optional_params,
model="claude-opus-4-6",
- drop_params=False
+ drop_params=False,
)
-
+
assert "context_management" in result
- assert result["context_management"] == non_default_params_anthropic["context_management"]
+ assert (
+ result["context_management"]
+ == non_default_params_anthropic["context_management"]
+ )
def test_cache_control_in_supported_params():
@@ -2897,9 +2940,7 @@ def test_map_openai_params_with_cache_control():
"""
config = AnthropicConfig()
- non_default_params = {
- "cache_control": {"type": "ephemeral"}
- }
+ non_default_params = {"cache_control": {"type": "ephemeral"}}
optional_params = {}
result = config.map_openai_params(
@@ -2919,9 +2960,7 @@ def test_map_openai_params_cache_control_ignored_when_not_dict():
"""
config = AnthropicConfig()
- non_default_params = {
- "cache_control": "ephemeral"
- }
+ non_default_params = {"cache_control": "ephemeral"}
optional_params = {}
result = config.map_openai_params(
@@ -2974,17 +3013,9 @@ def test_compaction_block_empty_list_not_added():
"type": "message",
"role": "assistant",
"model": "claude-opus-4-6",
- "content": [
- {
- "type": "text",
- "text": "Just a regular response."
- }
- ],
+ "content": [{"type": "text", "text": "Just a regular response."}],
"stop_reason": "end_turn",
- "usage": {
- "input_tokens": 10,
- "output_tokens": 5
- }
+ "usage": {"input_tokens": 10, "output_tokens": 5},
}
raw_response = httpx.Response(status_code=200, headers={})
@@ -3001,7 +3032,10 @@ def test_compaction_block_empty_list_not_added():
# Verify compaction_blocks is not in provider_specific_fields when there are none
provider_fields = result.choices[0].message.provider_specific_fields
if provider_fields:
- assert "compaction_blocks" not in provider_fields or provider_fields.get("compaction_blocks") is None
+ assert (
+ "compaction_blocks" not in provider_fields
+ or provider_fields.get("compaction_blocks") is None
+ )
def test_fast_mode_beta_header():
@@ -3014,8 +3048,7 @@ def test_fast_mode_beta_header():
optional_params = {"speed": "fast"}
result_headers = config.update_headers_with_optional_anthropic_beta(
- headers=headers,
- optional_params=optional_params
+ headers=headers, optional_params=optional_params
)
assert "anthropic-beta" in result_headers
@@ -3029,14 +3062,10 @@ def test_fast_mode_with_other_beta_headers():
config = AnthropicConfig()
headers = {}
- optional_params = {
- "speed": "fast",
- "output_format": {"type": "json_object"}
- }
+ optional_params = {"speed": "fast", "output_format": {"type": "json_object"}}
result_headers = config.update_headers_with_optional_anthropic_beta(
- headers=headers,
- optional_params=optional_params
+ headers=headers, optional_params=optional_params
)
assert "anthropic-beta" in result_headers
@@ -3056,9 +3085,7 @@ def test_fast_mode_usage_calculation():
}
usage = config.calculate_usage(
- usage_object=usage_object,
- reasoning_content=None,
- speed="fast"
+ usage_object=usage_object, reasoning_content=None, speed="fast"
)
assert usage.prompt_tokens == 1000
@@ -3171,7 +3198,7 @@ def test_fast_mode_parameter_mapping():
non_default_params=non_default_params,
optional_params=optional_params,
model="claude-opus-4-6",
- drop_params=False
+ drop_params=False,
)
assert "speed" in result
@@ -3236,9 +3263,9 @@ def test_map_tool_helper_enforces_object_type_when_missing():
assert "properties" in result["input_schema"]
assert "query" in result["input_schema"]["properties"]
# Original parameters dict must not be modified in place
- assert tool["function"]["parameters"] == original_params, (
- "parameters dict was mutated; _map_tool_helper should not modify caller data"
- )
+ assert (
+ tool["function"]["parameters"] == original_params
+ ), "parameters dict was mutated; _map_tool_helper should not modify caller data"
def test_map_tool_helper_enforces_object_type_when_wrong_type():
@@ -3264,13 +3291,13 @@ def test_map_tool_helper_enforces_object_type_when_wrong_type():
result, _ = config._map_tool_helper(tool)
assert result is not None
assert result["input_schema"]["type"] == "object"
- assert result["input_schema"].get("properties") == {}, (
- "properties should be injected as {} when schema has non-object type and no properties key"
- )
+ assert (
+ result["input_schema"].get("properties") == {}
+ ), "properties should be injected as {} when schema has non-object type and no properties key"
# Original parameters dict must not be modified in place
- assert tool["function"]["parameters"] == original_params, (
- "parameters dict was mutated; _map_tool_helper should not modify caller data"
- )
+ assert (
+ tool["function"]["parameters"] == original_params
+ ), "parameters dict was mutated; _map_tool_helper should not modify caller data"
def test_map_tool_helper_preserves_valid_object_schema():