Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion litellm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1897,7 +1897,7 @@ def set_global_gitlab_config(config: Dict[str, Any]) -> None:
supports_reasoning: Callable[..., bool]
acreate: Callable[..., Any]
get_max_tokens: Callable[..., int]
get_model_info: Callable[..., _ModelInfoType]
get_model_info: Callable[..., _ModelInfoType] # type: ignore[no-redef]
register_prompt_template: Callable[..., None]
validate_environment: Callable[..., dict]
check_valid_key: Callable[..., bool]
Expand Down
21 changes: 11 additions & 10 deletions litellm/litellm_core_utils/prompt_templates/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -2283,7 +2283,7 @@ def sanitize_messages_for_tool_calling(
for idx, msg in enumerate(sanitized_messages):
role = msg.get("role")
tcid = msg.get("tool_call_id") if role in ["tool", "function"] else None
if tcid:
if tcid and isinstance(tcid, str):
if tcid in seen_in_block:
# Mark the earlier occurrence for removal (keep latest)
duplicates_to_remove.add(seen_in_block[tcid])
Expand Down Expand Up @@ -2581,13 +2581,11 @@ def anthropic_messages_pt( # noqa: PLR0915

# Build the text block if content is a non-empty string
text_element = None
if (
isinstance(assistant_content_block.get("content"), str)
and assistant_content_block["content"]
):
_acb_content = assistant_content_block.get("content")
if isinstance(_acb_content, str) and _acb_content:
_anthropic_text_content_element = AnthropicMessagesTextParam(
type="text",
text=assistant_content_block["content"],
text=_acb_content,
)
_content_element = add_cache_control_to_content(
anthropic_content_element=_anthropic_text_content_element,
Expand Down Expand Up @@ -2682,9 +2680,10 @@ def anthropic_messages_pt( # noqa: PLR0915
_content_is_list = "content" in assistant_content_block and isinstance(
assistant_content_block["content"], list
)
_content_list = assistant_content_block.get("content") if _content_is_list else None
_list_has_thinking = False
if _content_is_list:
for _item in assistant_content_block["content"]:
if _content_is_list and _content_list is not None:
for _item in _content_list:
if isinstance(_item, dict) and _item.get("type") in (
"thinking",
"redacted_thinking",
Expand All @@ -2696,8 +2695,10 @@ def anthropic_messages_pt( # noqa: PLR0915
thinking_blocks is not None and not _list_has_thinking
): # IMPORTANT: ADD THIS FIRST, ELSE ANTHROPIC WILL RAISE AN ERROR
assistant_content.extend(thinking_blocks)
if _content_is_list:
for m in assistant_content_block["content"]:
if _content_is_list and _content_list is not None:
for m in _content_list:
if not isinstance(m, dict):
continue
# handle thinking blocks
thinking_block = cast(str, m.get("thinking", ""))
text_block = cast(str, m.get("text", ""))
Expand Down
4 changes: 2 additions & 2 deletions litellm/llms/anthropic/files/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import calendar
import time
from typing import Any, Dict, List, Optional, Union
from typing import Any, Dict, List, Optional, Union, cast

import httpx
from openai.types.file_deleted import FileDeleted
Expand Down Expand Up @@ -79,7 +79,7 @@ def get_error_class(
return AnthropicError(
status_code=status_code,
message=error_message,
headers=headers,
headers=cast(httpx.Headers, headers) if isinstance(headers, dict) else headers,
)

def validate_environment(
Expand Down
4 changes: 2 additions & 2 deletions litellm/llms/black_forest_labs/image_edit/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,8 @@ def _read_image_bytes(
def transform_image_edit_request(
self,
model: str,
prompt: str,
image: FileTypes,
prompt: Optional[str],
image: Optional[FileTypes],
image_edit_optional_request_params: Dict,
litellm_params: GenericLiteLLMParams,
headers: dict,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,12 @@ def transform_image_generation_response(
raw_response: httpx.Response,
model_response: ImageResponse,
logging_obj: LiteLLMLoggingObj,
**kwargs,
request_data: dict,
optional_params: dict,
litellm_params: dict,
encoding: Any,
api_key: Optional[str] = None,
json_mode: Optional[bool] = None,
) -> ImageResponse:
"""
Transform Black Forest Labs response to OpenAI-compatible ImageResponse.
Expand Down
2 changes: 1 addition & 1 deletion litellm/llms/brave/search/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from __future__ import annotations
from datetime import datetime, timezone
from dateutil import parser
from dateutil import parser # type: ignore[import-untyped]
from typing import Dict, List, Literal, Optional, TypedDict, Union
import httpx
import re
Expand Down
13 changes: 8 additions & 5 deletions litellm/llms/custom_httpx/llm_http_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3036,10 +3036,11 @@ def create_file(
elif isinstance(transformed_request, dict) and "file" in transformed_request:
# Handle multipart form-data uploads (e.g., Anthropic Files API)
# The dict contains tuples suitable for httpx's `files` parameter
file_request = cast(Dict[str, Any], transformed_request)
upload_response = sync_httpx_client.post(
url=api_base,
headers=headers,
files=transformed_request,
files=file_request,
timeout=timeout,
)
else:
Expand Down Expand Up @@ -4870,6 +4871,7 @@ async def async_realtime_client_secret_handler(
timeout=timeout,
)
except Exception as e:
assert provider_config is not None
raise self._handle_error(
e=e,
provider_config=provider_config,
Expand Down Expand Up @@ -4954,6 +4956,7 @@ async def async_realtime_calls_handler(
timeout=timeout,
)
except Exception as e:
assert provider_config is not None
raise self._handle_error(
e=e,
provider_config=provider_config,
Expand Down Expand Up @@ -8026,7 +8029,7 @@ async def async_vector_store_list_handler(

url = api_base

params = {}
params: Dict[str, Any] = {}
if after is not None:
params["after"] = after
if before is not None:
Expand Down Expand Up @@ -8108,7 +8111,7 @@ def vector_store_list_handler(

url = api_base

params = {}
params: Dict[str, Any] = {}
if after is not None:
params["after"] = after
if before is not None:
Expand Down Expand Up @@ -8170,7 +8173,7 @@ async def async_vector_store_update_handler(

url = f"{api_base}/{vector_store_id}"

request_body = dict(vector_store_update_optional_params)
request_body: Dict[str, Any] = dict(vector_store_update_optional_params)

# Clean metadata to only include string values (OpenAI requirement)
if "metadata" in request_body and request_body["metadata"] is not None:
Expand Down Expand Up @@ -8253,7 +8256,7 @@ def vector_store_update_handler(

url = f"{api_base}/{vector_store_id}"

request_body = dict(vector_store_update_optional_params)
request_body: Dict[str, Any] = dict(vector_store_update_optional_params)

# Clean metadata to only include string values (OpenAI requirement)
if "metadata" in request_body and request_body["metadata"] is not None:
Expand Down
11 changes: 7 additions & 4 deletions litellm/llms/perplexity/responses/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,19 @@ def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str

def _ensure_message_type(
self, input: Union[str, ResponseInputParam]
) -> Union[str, List[Dict[str, Any]]]:
) -> Union[str, ResponseInputParam]:
"""Ensure list input items have type='message' (required by Perplexity)."""
if isinstance(input, str):
return input
if isinstance(input, list):
result = []
result: List[Any] = []
for item in input:
if isinstance(item, dict) and "type" not in item:
item = {**item, "type": "message"}
result.append(item)
new_item = dict(item) # convert to plain dict to avoid TypedDict checking
new_item["type"] = "message"
result.append(new_item)
else:
result.append(item)
return result
return input

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ def batch_embeddings(

is_multimodal = _is_multimodal_input(input)
use_embed_content = is_multimodal or (custom_llm_provider == "vertex_ai")
mode: Literal["embedding", "batch_embedding"]
if use_embed_content:
mode = "embedding"
else:
Expand Down Expand Up @@ -200,6 +201,7 @@ def batch_embeddings(
)

### TRANSFORMATION (sync path) ###
request_data: Any
if use_embed_content:
resolved_files = {}
if api_key:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream:
],
)
# Modify current chunk to be the first chunk with role but no finish_reason
result.choices[0].finish_reason = None
result.choices[0].finish_reason = None # type: ignore[assignment]
delta.role = "assistant"
# Ensure content is empty string for first chunk, not None
if delta.content is None:
Expand Down
2 changes: 1 addition & 1 deletion litellm/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7700,7 +7700,7 @@ async def acount_tokens(
local_count = litellm.token_counter(
model=model,
messages=fallback_messages,
tools=tools,
tools=tools, # type: ignore[arg-type]
)

return TokenCountResponse(
Expand Down
6 changes: 3 additions & 3 deletions litellm/proxy/_experimental/mcp_server/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,9 @@ def decrypt_credentials(
"aws_session_token",
]
for field in secret_fields:
value = credentials.get(field)
if value is not None:
credentials[field] = decrypt_value_helper(
value = credentials.get(field) # type: ignore[literal-required]
if value is not None and isinstance(value, str):
credentials[field] = decrypt_value_helper( # type: ignore[literal-required]
value=value,
key=field,
exception_type="debug",
Expand Down
28 changes: 25 additions & 3 deletions litellm/proxy/common_request_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,8 @@ async def common_processing_pre_call_logic(
"aresponses",
"_arealtime",
"_aresponses_websocket",
"acreate_realtime_client_secret",
"arealtime_calls",
"aget_responses",
"adelete_responses",
"acancel_responses",
Expand All @@ -553,6 +555,10 @@ async def common_processing_pre_call_logic(
"allm_passthrough_route",
"avector_store_search",
"avector_store_create",
"avector_store_retrieve",
"avector_store_list",
"avector_store_update",
"avector_store_delete",
"avector_store_file_create",
"avector_store_file_list",
"avector_store_file_retrieve",
Expand Down Expand Up @@ -774,20 +780,36 @@ async def base_process_llm_request(
"aembedding",
"aresponses",
"_arealtime",
"_aresponses_websocket",
"acreate_realtime_client_secret",
"arealtime_calls",
"aget_responses",
"adelete_responses",
"acancel_responses",
"acompact_responses",
"acreate_batch",
"aretrieve_batch",
"alist_batches",
"acancel_batch",
"afile_content",
"afile_retrieve",
"afile_delete",
"atext_completion",
"aimage_edit",
"acreate_fine_tuning_job",
"acancel_fine_tuning_job",
"alist_fine_tuning_jobs",
"aretrieve_fine_tuning_job",
"alist_input_items",
"aimage_edit",
"agenerate_content",
"agenerate_content_stream",
"allm_passthrough_route",
"avector_store_search",
"avector_store_create",
"avector_store_retrieve",
"avector_store_list",
"avector_store_update",
"avector_store_delete",
"avector_store_file_create",
"avector_store_file_list",
"avector_store_file_retrieve",
Expand Down Expand Up @@ -815,8 +837,8 @@ async def base_process_llm_request(
"aget_interaction",
"adelete_interaction",
"acancel_interaction",
"acancel_batch",
"afile_delete",
"asend_message",
Comment on lines 837 to +840

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

acancel_batch / afile_delete silently removed from async-generator routes

The diff removes "acancel_batch" and "afile_delete" from the bottom of this list (replacing them with "asend_message" and "call_mcp_tool"), while adding them to an earlier block in the same function. However the parallel list in route_llm_request.py keeps "acancel_batch" and "afile_delete" at the bottom of its own list and only adds "asend_message"/"call_mcp_tool" before them. If the two files diverge on which position these route types occupy, any code that depends on list ordering (e.g. first-match logic, index-based dispatch) could behave differently for these two routes. Please double-check that the relocation is intentional and that the ordering semantics in both files remain consistent.

"call_mcp_tool",
"acreate_eval",
"alist_evals",
"aget_eval",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ async def _call_panw_api( # noqa: PLR0915
panw_metadata["litellm_trace_id"] = metadata["litellm_trace_id"]

# Build contents: tool_event takes priority, else prompt/response text
contents: List[Dict[str, Any]]
if tool_event is not None:
contents = [{"tool_event": tool_event}]
else:
Expand Down Expand Up @@ -1485,7 +1486,7 @@ async def async_post_call_streaming_iterator_hook(
detail = (
e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
)
error_obj = dict(detail.get("error", detail))
error_obj: Dict[str, Any] = dict(detail.get("error", detail)) # type: ignore[arg-type]
error_obj["code"] = e.status_code
yield f"data: {json.dumps({'error': error_obj})}\n\n"
except Exception as e:
Expand Down
14 changes: 7 additions & 7 deletions litellm/proxy/guardrails/guardrail_hooks/presidio.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@ def __init__(
if (self.output_parse_pii or self.apply_to_output) and not logging_only:
current_hook = self.event_hook
if isinstance(current_hook, str) and current_hook != "post_call":
self.event_hook = [current_hook, "post_call"]
self.event_hook = cast(List[GuardrailEventHooks], [current_hook, "post_call"])
elif isinstance(current_hook, list) and "post_call" not in current_hook:
self.event_hook = current_hook + ["post_call"]
self.event_hook = cast(List[GuardrailEventHooks], current_hook + ["post_call"])
self.pii_entities_config: Dict[Union[PiiEntityType, str], PiiAction] = (
pii_entities_config or {}
)
Expand Down Expand Up @@ -908,7 +908,7 @@ async def async_post_call_success_hook( # type: ignore
if self.apply_to_output is True:
if self._is_anthropic_message_response(response):
return await self._process_anthropic_response_for_pii(
response=response, request_data=data, mode="mask"
response=cast(dict, response), request_data=data, mode="mask"
)
return await self._mask_output_response(
response=response, request_data=data
Expand All @@ -927,7 +927,7 @@ async def async_post_call_success_hook( # type: ignore
)
elif self._is_anthropic_message_response(response):
await self._process_anthropic_response_for_pii(
response=response, request_data=data, mode="unmask"
response=cast(dict, response), request_data=data, mode="unmask"
)
return response

Expand Down Expand Up @@ -1234,15 +1234,15 @@ async def async_post_call_streaming_iterator_hook(
user_api_key_dict: UserAPIKeyAuth,
response: Any,
request_data: dict,
) -> AsyncGenerator[Union[ModelResponseStream, bytes], None]:
) -> AsyncGenerator[ModelResponseStream, None]:
"""
Process streaming response chunks to unmask PII tokens when needed.
"""
if self.apply_to_output:
async for chunk in self._stream_apply_output_masking(
response, request_data
):
yield chunk
yield cast(ModelResponseStream, chunk)
return

metadata = (request_data.get("metadata") or {}) if request_data else {}
Expand All @@ -1257,7 +1257,7 @@ async def async_post_call_streaming_iterator_hook(
return

async for chunk in self._stream_pii_unmasking(response, request_data):
yield chunk
yield cast(ModelResponseStream, chunk)

@staticmethod
def _preserve_usage_from_last_chunk(
Expand Down
1 change: 1 addition & 0 deletions litellm/proxy/hooks/mcp_semantic_filter/hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ async def async_post_call_response_headers_hook(
user_api_key_dict: "UserAPIKeyAuth",
response: Any,
request_headers: Optional[Dict[str, str]] = None,
litellm_call_info: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, str]]:
"""Add semantic filter stats and tool names to response headers."""
from litellm.constants import MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH
Expand Down
Loading
Loading