Skip to content

fix(gpt_transformation): avoid mutating input messages in remove_cache_control - #41776

Closed
vineethsaivs wants to merge 1 commit into
BerriAI:mainfrom
vineethsaivs:litellm_fix_cache_control_mutation
Closed

vineethsaivs wants to merge 1 commit into
BerriAI:mainfrom
vineethsaivs:litellm_fix_cache_control_mutation

Conversation

@vineethsaivs

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • remove_cache_control_flag_from_messages_and_tools mutates the caller's message dictionaries in place

How it solves it:

  • deepcopy the messages and tools before filtering cache_control

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem

Type

🐛 Bug Fix

@greptile-apps

greptile-apps Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

This PR is not safe to merge until the unavailable imports are resolved, cache-control preservation is explicitly capability-gated, and the unrelated behavior changes are separated.

Findings

  1. P1 Unavailable imports break loading ▶
  2. P1 Custom endpoints receive unsupported fields ▶
  3. P2 Unrelated behavior expands scope ▶

Summary

This PR deep-copies messages and tools before removing cache_control, but it also changes cache-control routing, tool-call parsing, streaming error handling, and typing throughout the OpenAI GPT transformation.

  • Prevents the cache-control filtering helper from mutating its direct inputs
  • Preserves cache-control fields for generic OpenAI routes using custom endpoints
  • Adds handling for error objects embedded in successful HTTP streams
  • Changes response tool-call conversion and adds regression tests for several behaviors

Reviews (1) · Last reviewed commit: "fix(gpt_transformation): avoid mutating ..."

Comment on lines +39 to +46
ChatCompletionMessageCustomToolCall,
ChatCompletionMessageToolCall,
Choices,
Function,
Message,
ModelResponse,
ModelResponseStream,
chat_completion_tool_call_from_dict,

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.

P1 Unavailable imports break loading

This module now imports ChatCompletionMessageCustomToolCall and chat_completion_tool_call_from_dict, but neither name exists or is imported in litellm.types.utils. Importing gpt_transformation therefore raises ImportError, preventing OpenAI chat support and its tests from loading.

Comment on lines +401 to +409
if custom_llm_provider != "openai":
return False
resolved_api_base = api_base or litellm.api_base or os.getenv("OPENAI_BASE_URL") or os.getenv("OPENAI_API_BASE")
if not resolved_api_base:
return False
hostname: Final = urlparse(resolved_api_base).hostname
if hostname is None:
return False
return hostname != "openai.com" and not hostname.endswith(".openai.com")

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.

P1 Custom endpoints receive unsupported fields

This check treats every non-OpenAI hostname using the generic openai provider as cache-control capable. If a custom OpenAI-compatible server does not support Anthropic cache_control, it will now receive those fields and may reject requests that previously succeeded after filtering. This violates the repository directive to avoid backward-incompatible behavior without a user-controlled flag.

Rule Used: What: avoid backwards-incompatible changes without user-controlled flags Why: This breaks current behaviour for users using existing functionality Example of BAD: this PR (#22164) introduced run_post_custom... (source)

Comment on lines +772 to +795
@staticmethod
def _extract_error_from_chunk(chunk: dict) -> tuple[str, int] | None:
"""OpenAI-compatible backends (vLLM, sglang) can return an HTTP 200
stream whose body carries an error payload, e.g.
``data: {"error": {"message": "...", "code": 400}}``."""
error: Final = chunk.get("error")
if not error:
return None
if not isinstance(error, dict):
return str(error), 500
message: Final = error.get("message")
code: Final = error.get("code")
status_code: Final = code if isinstance(code, int) and 400 <= code < 600 else 500
return (message if isinstance(message, str) else json.dumps(error)), status_code

def chunk_parser(self, chunk: dict) -> ModelResponseStream:
try:
error_details: Final = self._extract_error_from_chunk(chunk)
if error_details is not None:
error_message, error_status_code = error_details
raise OpenAIError(
status_code=error_status_code,
message=error_message,
)

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.

P2 Unrelated behavior expands scope

This mutation fix also introduces streaming error handling, endpoint capability policy, and custom tool-call conversion. The repository directive requires the minimum code needed for the stated problem and prohibits unrequested features. These unrelated behavioral changes must be separated before merging so they can be reviewed and released independently.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 14:33
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 14:33
@vineethsaivs

Copy link
Copy Markdown
Contributor Author

Closing as a duplicate of my #35602, which fixes the same cache_control mutation and is now rebased onto main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant