Skip to content

fix(hosted_vllm,azure): leave the caller's messages untouched when building the chat request - #51841

Merged
mateo-berri merged 4 commits into
BerriAI:mainfrom
quietjules:litellm_copy_caller_messages_vllm_mistral_azure
Nov 24, 2026
Merged

mateo-berri merged 4 commits into
BerriAI:mainfrom
quietjules:litellm_copy_caller_messages_vllm_mistral_azure

Conversation

@quietjules

@quietjules quietjules commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

When a self-hosted vLLM model failed and the proxy fell back to Gemini, Gemini got the request vLLM had already rewritten, so it never saw the caller's video and made up an answer. vLLM and Azure now build their own copies instead of editing the caller's messages, so a fallback or an app that reuses its history sends exactly what the caller wrote. What each provider receives is unchanged

Details

TLDR

Problem this solves:

  • hosted vLLM rewrote the caller's video file part into video_url
  • A Gemini fallback then got video_url, dropped it, and invented an answer
  • Azure also rewrote the caller's image_url, file, and function_call parts

How it solves it:

  • Both transforms build new messages and parts instead of editing the caller's
  • The request body each provider gets is the same as before

User Flow

Before: a developer whose vision app falls back from a self-hosted vLLM model to Gemini gets an answer about a video Gemini never received

  1. The proxy admin sets the vLLM vision model vllm-video to fall back to gemini-video when vLLM fails
  2. The developer sends POST https://litellm-domain/v1/chat/completions to vllm-video with a text part and a file part for an mp4 URL with format: video/mp4
  3. vLLM fails, and the response comes back 200 with x-litellm-attempted-fallbacks: 1
  4. Gemini answers "NO VIDEO ATTACHED", or describes a scene that is not in the clip, because the video never reached it

After: the fallback answer describes the real clip, the same as a direct call to Gemini

  1. The proxy admin sets the vLLM vision model vllm-video to fall back to gemini-video when vLLM fails
  2. The developer sends POST https://litellm-domain/v1/chat/completions to vllm-video with a text part and a file part for an mp4 URL with format: video/mp4
  3. vLLM fails, and the response comes back 200 with x-litellm-attempted-fallbacks: 1
  4. The answer describes the clip's sunlit forest clearing and the burrow under a tree, the same as a direct gemini-video call

Relevant issues

Supersedes #44977

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Before is the merge base 05518975a5 and After is 2dea37b8a8. The tip f4cfe9973e adds two tests-only commits, which type the new tests and drop an async variant. The new tests fail on the merge base and pass at the tip.

Case Route Before After
Video by URL, vLLM to Gemini chat completions no video seen real clip
Video as base64, vLLM to Gemini chat completions made-up scene real clip
Thinking turn, vLLM to Claude chat completions matches control matches control
Image, vLLM to Gemini /v1/messages matches control matches control
Image by URL, Azure to Gemini chat completions matches control matches control
Video with format, Azure down to Gemini chat completions Gemini 400 real clip
Null function_call.arguments, Azure down to gpt-4.1-mini chat completions 200 500, OpenAI's 400 inside
Azure call that succeeds chat completions same body sent same body sent
SDK app reusing its messages, Azure SDK messages changed messages unchanged
SDK loop, vLLM then Gemini SDK no video seen real clip

On the proxy, the Azure change shows when a fallback reads format, which Azure used to strip

Setup (both legs)

Each leg runs a 2-worker proxy from its own tree with the same config, against real Gemini, Anthropic, and Azure. vLLM points at a dead port, so each vLLM call falls back. Each case also sends its body straight to the fallback model as a control

config.yaml
model_list:
  - model_name: vllm-video
    litellm_params:
      model: hosted_vllm/Qwen/Qwen2.5-VL-7B-Instruct
      api_base: http://127.0.0.1:20989/v1
  - model_name: gemini-video
    litellm_params:
      model: gemini/gemini-flash-latest
      api_key: os.environ/GEMINI_API_KEY
  - model_name: vllm-chat
    litellm_params:
      model: hosted_vllm/Qwen/Qwen3-8B
      api_base: http://127.0.0.1:20989/v1
  - model_name: claude-thinking
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
      thinking: {"type": "enabled", "budget_tokens": 1024}
      max_tokens: 2048
  - model_name: azure-image
    litellm_params:
      model: azure/gpt-4.1-2025-04-14
      api_base: os.environ/AZURE_AI_API_BASE
      api_key: os.environ/AZURE_AI_API_KEY
      api_version: "2025-04-01-preview"
  - model_name: gemini-image
    litellm_params:
      model: gemini/gemini-flash-latest
      api_key: os.environ/GEMINI_API_KEY

router_settings:
  num_retries: 0
  fallbacks:
    - vllm-video: ["gemini-video"]
    - vllm-chat: ["claude-thinking"]
    - azure-image: ["gemini-image"]

litellm_settings:
  user_url_allowed_hosts: ["127.0.0.1:22185"]
Steps and the curl loop

Env vars are GEMINI_API_KEY, ANTHROPIC_API_KEY, AZURE_AI_API_BASE, AZURE_AI_API_KEY, and LITELLM_MASTER_KEY

  1. Start the image server below, which serves a red PNG as application/octet-stream: python octet_server.py 22185
  2. Start each proxy: cd <tree> && PYTHONPATH=<tree> litellm --config config.yaml --port <port> --num_workers 2 --detailed_debug --timeout_worker_healthcheck 60
  3. Send each body with run_cases.sh below. The Azure cases ran the same curl and printed {model, content: .choices[0].message.content, prompt_tokens: .usage.prompt_tokens}, with the null function_call and error fields left out below
#!/bin/zsh
cd ${0:a:h}
K=$LITELLM_MASTER_KEY
typeset -A port=(before 29488 after 27066)
for leg in before after; do
  P=$port[$leg]
  for c in url data; do
    for m in vllm-video gemini-video; do
      out=${leg}_${c}_${m}
      code=$(curl -s -m 240 -D $out.hdr -o $out.json -w '%{http_code}' -H "Authorization: Bearer $K" -H 'Content-Type: application/json' http://127.0.0.1:$P/v1/chat/completions -d @body_${c}_${m}.json)
      print -r -- "== $leg $c $m $code"
      grep -i '^\(x-litellm-model-group\|x-litellm-attempted-fallbacks\)' $out.hdr | tr -d '\r'
      jq -c '{model, content: .choices[0].message.content, prompt_tokens_details: (.usage.prompt_tokens_details | {text_tokens, video_tokens})}' $out.json
    done
  done
  for m in vllm-chat claude-thinking; do
    out=${leg}_turn2_${m}
    code=$(curl -s -m 240 -D $out.hdr -o $out.json -w '%{http_code}' -H "Authorization: Bearer $K" -H 'Content-Type: application/json' http://127.0.0.1:$P/v1/chat/completions -d @turn2_${m}.json)
    print -r -- "== $leg turn2 $m $code"
    grep -i '^\(x-litellm-model-group\|x-litellm-attempted-fallbacks\)' $out.hdr | tr -d '\r'
    jq -c '{content: .choices[0].message.content, prompt_tokens: .usage.prompt_tokens}' $out.json
  done
  for m in vllm-video gemini-video; do
    out=${leg}_messages_${m}
    code=$(curl -s -m 240 -D $out.hdr -o $out.json -w '%{http_code}' -H "Authorization: Bearer $K" -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' http://127.0.0.1:$P/v1/messages -d @body_messages_${m}.json)
    print -r -- "== $leg messages $m $code"
    grep -i '^\(x-litellm-model-group\|x-litellm-attempted-fallbacks\)' $out.hdr | tr -d '\r'
    jq -c '{model, content: [.content[]? | select(.type=="text") | .text]}' $out.json
  done
done
Request bodies and the image server

Video by URL (body_url_vllm-video.json, and the control swaps in "model":"gemini-video")

{"model":"vllm-video","max_tokens":300,"messages":[{"role":"user","content":[{"type":"text","text":"Describe the attached video in one sentence. If no video is attached, reply exactly: NO VIDEO ATTACHED"},{"type":"file","file":{"file_id":"https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4","format":"video/mp4"}}]}]}

Video as base64 is the same request with the file part as {"file_data": "data:video/mp4;base64,<the same 1 MB clip>", "format": "video/mp4"}

Thinking turn (turn2_vllm-chat.json) is the second turn of a get_weather tool conversation. Turn 1 went straight to claude-thinking with the question "Pick a European capital whose name has as many letters as there are primes below 20, then get its weather. Tell me the weather and why you picked it." and a 16000 token thinking budget, since the config's 1024 budget maps to low effort and Claude skipped thinking. Turn 2 holds that question, the assistant turn with its content as a text part list, its signed thinking_blocks, reasoning_content, and the tool call, and the tool result 18C and sunny. vLLM's transform rewrites this assistant turn, so this case checks that the fallback still gets the full history

Image on /v1/messages

{"model": "vllm-video", "max_tokens": 100, "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "<64x64 red PNG>"}}, {"type": "text", "text": "What color is this image? Answer in one word."}]}]}

Image by URL to Azure. Azure cannot reach the local image server, so it fails and the router falls back to Gemini. The request sets format because the server answers with octet-stream. Both legs answer Red, so this case only checks that the fallback still works

{"model":"azure-image","max_tokens":50,"messages":[{"role":"user","content":[{"type":"text","text":"What color is this image? Answer in one word."},{"type":"image_url","image_url":{"url":"http://127.0.0.1:22185/red","format":"image/png"}}]}]}

Azure call that succeeds sends the same four messages as the SDK app below (body_azure_ok.json, with "model":"azure-image" and the get_current_city function)

octet_server.py

import http.server
import struct
import sys
import zlib


def red_png(size: int) -> bytes:
    row = b"\x00" + b"\xff\x00\x00" * size
    raw = row * size
    def chunk(tag: bytes, data: bytes) -> bytes:
        return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
    header = struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)
    return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")


BODY = red_png(64)


class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        self.send_response(200)
        self.send_header("Content-Type", "application/octet-stream")
        self.send_header("Content-Length", str(len(BODY)))
        self.end_headers()
        self.wfile.write(BODY)


http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()
SDK app (my_app.py), run as PYTHONPATH=<tree> python my_app.py azure and python my_app.py vllm
def azure():
    messages = [
        {"role": "user", "content": "What city am I in?"},
        {"role": "assistant", "content": None, "function_call": {"name": "get_current_city", "arguments": None}},
        {"role": "function", "name": "get_current_city", "content": "Copenhagen"},
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "In one line, name my city, the color of each image, and the title of the PDF."},
                {"type": "image_url", "image_url": data_uri("red.png", "image/png")},
                {"type": "image_url", "image_url": {"url": data_uri("blue.png", "image/png"), "format": "image/png"}},
                {"type": "file", "file": {"file_data": data_uri("report.pdf", "application/pdf"), "filename": "report.pdf", "format": "application/pdf"}},
            ],
        },
    ]
    snapshot = copy.deepcopy(messages)
    response = litellm.completion(
        model="azure/gpt-4.1-2025-04-14",
        api_base=os.environ["AZURE_AI_API_BASE"],
        api_key=os.environ["AZURE_AI_API_KEY"],
        api_version="2025-04-01-preview",
        messages=messages,
        functions=[{"name": "get_current_city", "parameters": {"type": "object", "properties": {}}}],
        max_tokens=100,
    )
    print("azure/gpt-4.1-2025-04-14 answered:", response.choices[0].message.content)
    report(messages, snapshot)


def vllm():
    messages = [{"role": "user", "content": [
        {"type": "text", "text": "Describe the attached video in one sentence. If no video is attached, reply exactly: NO VIDEO ATTACHED"},
        {"type": "file", "file": {"file_id": VIDEO, "format": "video/mp4"}},
    ]}]
    for model, extra in (
        ("hosted_vllm/Qwen/Qwen2.5-VL-7B-Instruct", {"api_base": "http://127.0.0.1:20989/v1"}),
        ("gemini/gemini-flash-latest", {}),
    ):
        try:
            response = litellm.completion(model=model, messages=messages, max_tokens=300, num_retries=0, **extra)
        except Exception as e:
            print(f"{model} failed:", type(e).__name__)
            print("  file part sent next:", json.dumps(short(messages[0]["content"][1])))
            continue
        print(f"{model} answered:", response.choices[0].message.content)

report prints messages == snapshot and each changed message, and short cuts strings over 40 characters. VIDEO is the same mp4 URL as above

Before (05518975a5)

Video by URL

== before url vllm-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":"NO VIDEO ATTACHED","prompt_tokens_details":{"text_tokens":24,"video_tokens":null}}
== before url gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":"In an animated forest clearing bathed in sunlight, gentle breezes sway the grass and leaves around a burrow nestled beneath the roots of a large tree.","prompt_tokens_details":{"text_tokens":24,"video_tokens":660}}

Video as base64

Fallback and control output
== before data vllm-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":"A live concert performance is captured from the audience, showing a band playing on a smoky, dramatically lit stage while concertgoers record the show on their smartphones.","prompt_tokens_details":{"text_tokens":24,"video_tokens":null}}
== before data gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":"A gentle breeze blows through the grass and leaves of a sunlit, animated forest clearing featuring a burrow under a tree.","prompt_tokens_details":{"text_tokens":24,"video_tokens":660}}
Thinking turn, image on /v1/messages, Azure to Gemini, Azure call that succeeds
== before turn2 vllm-chat 200
x-litellm-model-group: claude-thinking
x-litellm-attempted-fallbacks: 1
{"content":"The weather in Budapest is 18°C and sunny.\n\nI picked Budapest because there are 8 primes below 20 and \"Budapest\" has 8 letters (B-u-d-a-p-e-s-t). Other 8-letter capitals would also have worked, such as Brussels, Helsinki and Sarajevo. I chose Budapest from among them.","prompt_tokens":735}
== before turn2 claude-thinking 200
x-litellm-model-group: claude-thinking
x-litellm-attempted-fallbacks: 0
{"content":"Budapest is 18°C and sunny right now.\n\nI picked it because there are 8 primes below 20 and \"Budapest\" has 8 letters (B-u-d-a-p-e-s-t). Helsinki, Brussels and Sarajevo also have 8 letters. I chose Budapest from those.","prompt_tokens":735}
== before messages vllm-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":["Red"]}
== before messages gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":["Red"]}
== before azure-image 200
x-litellm-model-group: gemini-image
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":"Red","prompt_tokens":1101}
== before gemini-image 200
x-litellm-model-group: gemini-image
x-litellm-attempted-fallbacks: 0
{"model":"gemini-image","content":"Red","prompt_tokens":1101}
== before azure_ok 200
x-litellm-model-group: azure-image
x-litellm-attempted-fallbacks: 0
{"model":"azure-image","content":"Copenhagen, red, blue, Quarterly Weather Report.","prompt_tokens":612}

The request body this leg's --detailed_debug log shows going to Azure for azure_ok is 2042 bytes with sha256 863b7e02d2182e36…

SDK app

my_app.py azure and my_app.py vllm output
-- python my_app.py azure
azure/gpt-4.1-2025-04-14 answered: Copenhagen, red, blue, Quarterly Weather Report.
my messages unchanged after the call: False
  message 1 before the call: {"role": "assistant", "content": null, "function_call": {"name": "get_current_city", "arguments": null}}
  message 1 after the call:  {"role": "assistant", "content": null, "function_call": {"name": "get_current_city", "arguments": ""}}
  message 3 before the call: {"role": "user", "content": [{"type": "text", "text": "In one line, name my city, the color of ...(77 chars)"}, {"type": "image_url", "image_url": "data:image/png;base64,iVBORw0KGgoAAAANSU...(246 chars)"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgoAAAANSU...(246 chars)", "format": "image/png"}}, {"type": "file", "file": {"file_data": "data:application/pdf;base64,JVBERi0xLjQK...(828 chars)", "filename": "report.pdf", "format": "application/pdf"}}]}
  message 3 after the call:  {"role": "user", "content": [{"type": "text", "text": "In one line, name my city, the color of ...(77 chars)"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgoAAAANSU...(246 chars)"}}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgoAAAANSU...(246 chars)"}}, {"type": "file", "file": {"file_data": "data:application/pdf;base64,JVBERi0xLjQK...(828 chars)", "filename": "report.pdf"}}]}
-- python my_app.py vllm
hosted_vllm/Qwen/Qwen2.5-VL-7B-Instruct failed: InternalServerError
  file part sent next: {"type": "video_url", "video_url": {"url": "https://test-videos.co.uk/vids/bigbuckbu...(87 chars)"}}
gemini/gemini-flash-latest answered: NO VIDEO ATTACHED

After (2dea37b8a8)

Video by URL

== after url vllm-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":"A grassy mound featuring a rabbit burrow sits under a leafy tree in a sunlit, animated forest clearing as the wind gently sways the grass.","prompt_tokens_details":{"text_tokens":24,"video_tokens":660}}
== after url gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":"In an animated forest setting, gentle sunlight illuminates a grassy clearing with a tree and a small burrow beneath its roots as the breeze rustles the foliage and grass.","prompt_tokens_details":{"text_tokens":24,"video_tokens":660}}

Video as base64

Fallback and control output
== after data vllm-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":"An animated video captures a sunlit, peaceful forest clearing featuring a tree atop a mossy mound with a small burrow beneath its roots as the grass gently sways in the breeze.","prompt_tokens_details":{"text_tokens":24,"video_tokens":660}}
== after data gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":"An animated, sunlit forest clearing features gentle breezes rustling the grass and leaves around a burrow nestled beneath a large tree.","prompt_tokens_details":{"text_tokens":24,"video_tokens":660}}
Thinking turn, image on /v1/messages, Azure to Gemini, Azure call that succeeds
== after turn2 vllm-chat 200
x-litellm-model-group: claude-thinking
x-litellm-attempted-fallbacks: 1
{"content":"The weather in Budapest is 18°C and sunny.\n\nI picked Budapest because it has 8 letters (B-u-d-a-p-e-s-t), which matches the 8 primes below 20. Helsinki, Brussels and Sarajevo also have 8 letters. I chose Budapest from those.","prompt_tokens":735}
== after turn2 claude-thinking 200
x-litellm-model-group: claude-thinking
x-litellm-attempted-fallbacks: 0
{"content":"The weather in Budapest is 18°C and sunny.\n\nI picked Budapest because the primes below 20 are 2, 3, 5, 7, 11, 13, 17 and 19. That makes 8 primes, and \"Budapest\" has 8 letters (B-u-d-a-p-e-s-t). Other 8-letter capitals would also have worked, including Brussels, Helsinki and Valletta. I chose Budapest from among them.","prompt_tokens":735}
== after messages vllm-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":["Red"]}
== after messages gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":["Red"]}
== after azure-image 200
x-litellm-model-group: gemini-image
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":"Red","prompt_tokens":1101}
== after gemini-image 200
x-litellm-model-group: gemini-image
x-litellm-attempted-fallbacks: 0
{"model":"gemini-image","content":"Red","prompt_tokens":1101}
== after azure_ok 200
x-litellm-model-group: azure-image
x-litellm-attempted-fallbacks: 0
{"model":"azure-image","content":"Copenhagen, red, blue, Quarterly Weather Report.","prompt_tokens":612}

The request body this leg's --detailed_debug log shows going to Azure for azure_ok is 2042 bytes with sha256 863b7e02d2182e36…, the same bytes as Before

SDK app

my_app.py azure and my_app.py vllm output
-- python my_app.py azure
azure/gpt-4.1-2025-04-14 answered: Copenhagen, first image is red, second image is blue, and the PDF title is "Quarterly Weather Report."
my messages unchanged after the call: True
-- python my_app.py vllm
hosted_vllm/Qwen/Qwen2.5-VL-7B-Instruct failed: InternalServerError
  file part sent next: {"type": "file", "file": {"file_id": "https://test-videos.co.uk/vids/bigbuckbu...(87 chars)", "format": "video/mp4"}}
gemini/gemini-flash-latest answered: Sunlight gently filters through the leaves of a large tree rooted on a grassy knoll with a burrow at its base in an animated forest.

Azure-down legs (Before 05518975a5, After f4cfe9973e)

config.yaml, bodies, media server, and runner

Azure points at a closed port, so every Azure call fails and the router falls back. The media server answers the 1 MB clip as application/octet-stream at an extensionless URL, so only format says it is a video. The direct calls to each fallback model are the controls. gpt-5.4-mini rejects the legacy function role on both legs, so the null-arguments case also runs against gpt-4.1-mini

model_list:
  - model_name: azure-down-video
    litellm_params:
      model: azure/gpt-4.1-2025-04-14
      api_base: http://127.0.0.1:9
      api_key: unused
      api_version: "2025-04-01-preview"
  - model_name: azure-down-tools
    litellm_params:
      model: azure/gpt-4.1-2025-04-14
      api_base: http://127.0.0.1:9
      api_key: unused
      api_version: "2025-04-01-preview"
  - model_name: gemini-video
    litellm_params:
      model: gemini/gemini-flash-latest
      api_key: os.environ/GEMINI_API_KEY
  - model_name: azure-down-legacy
    litellm_params:
      model: azure/gpt-4.1-2025-04-14
      api_base: http://127.0.0.1:9
      api_key: unused
      api_version: "2025-04-01-preview"
  - model_name: openai-legacy
    litellm_params:
      model: openai/gpt-4.1-mini
      api_key: os.environ/OPENAI_API_KEY
  - model_name: openai-backup
    litellm_params:
      model: openai/gpt-5.4-mini
      api_key: os.environ/OPENAI_API_KEY

router_settings:
  num_retries: 0
  fallbacks:
    - azure-down-video: ["gemini-video"]
    - azure-down-tools: ["openai-backup"]
    - azure-down-legacy: ["openai-legacy"]

litellm_settings:
  user_url_allowed_hosts: ["127.0.0.1:23417"]

body_azure-down-video.json (the control swaps in "model":"gemini-video")

{"model":"azure-down-video","max_tokens":300,"messages":[{"role":"user","content":[{"type":"text","text":"Describe the attached video in one sentence. If no video is attached, reply exactly: NO VIDEO ATTACHED"},{"type":"file","file":{"file_id":"http://127.0.0.1:23417/clip","format":"video/mp4"}}]}]}

body_azure-down-legacy.json (azure-down-tools and the controls swap the model name)

{"model":"azure-down-legacy","max_tokens":300,"functions":[{"name":"get_current_city","parameters":{"type":"object","properties":{}}}],"messages":[{"role":"user","content":"What city am I in?"},{"role":"assistant","content":null,"function_call":{"name":"get_current_city","arguments":null}},{"role":"function","name":"get_current_city","content":"Copenhagen"}]}

media_server.py, run as python media_server.py 23417 clip.mp4

import http.server
import sys
from pathlib import Path

CLIP = Path(sys.argv[2]).read_bytes()


class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        self.send_response(200)
        self.send_header("Content-Type", "application/octet-stream")
        self.send_header("Content-Length", str(len(CLIP)))
        self.end_headers()
        self.wfile.write(CLIP)


http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()

run_cases.sh

#!/bin/zsh
cd ${0:A:h}
key=$(~/.claude/bin/dotenv-get LITELLM_MASTER_KEY --file /Users/mateo/Development/litellm-worktrees/work-65a9bbd4-head/.env)
for leg port in before 25803 after 26641; do
  for c in ${=CASES:-azure-down-video gemini-video azure-down-tools openai-backup azure-down-legacy openai-legacy}; do
    out=${leg}_$c
    code=$(curl -s -m 240 -D $out.hdr -o $out.json -w '%{http_code}' \
      -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \
      http://127.0.0.1:$port/v1/chat/completions -d @body_$c.json)
    print -r -- "== $leg $c $code"
    grep -i '^\(x-litellm-model-group\|x-litellm-attempted-fallbacks\)' $out.hdr | tr -d '\r'
    jq -c 'if .error then {error: (.error.message | .[0:300])} else {model, content: .choices[0].message.content, prompt_tokens: .usage.prompt_tokens} end' $out.json
  done
done
run_cases.sh output, both legs
== before azure-down-video 500
{"error":"litellm.APIConnectionError: AzureException APIConnectionError - Connection error.\n\nLiteLLM: model group 'azure-down-video' failed with the error above. Fallback to gemini-video also failed: litellm.BadRequestError: GeminiException BadRequestError - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Una"}
== before gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":"An animated, sunlit clearing features a burrow beneath the roots of a leafy tree set upon a grassy mound in a forest.","prompt_tokens":684}
== before azure-down-tools 500
{"error":"litellm.APIConnectionError: AzureException APIConnectionError - Connection error.\n\nLiteLLM: model group 'azure-down-tools' failed with the error above. Fallback to openai-backup also failed: litellm.BadRequestError: OpenAIException - Unsupported value: 'messages[2].role' does not support 'function' "}
== before openai-backup 400
{"error":"litellm.BadRequestError: OpenAIException - Invalid type for 'messages[1].function_call.arguments': expected a string, but got null instead.\n\nLiteLLM: model group 'openai-backup' failed with the error above and no fallback model group was found for it, so the request was not retried on another model."}
== before azure-down-legacy 200
x-litellm-model-group: openai-legacy
x-litellm-attempted-fallbacks: 1
{"model":"gpt-4.1-mini-2025-04-14","content":"You are in Copenhagen.","prompt_tokens":59}
== before openai-legacy 400
{"error":"litellm.BadRequestError: OpenAIException - Invalid type for 'messages[1].function_call.arguments': expected a string, but got null instead.\n\nLiteLLM: model group 'openai-legacy' failed with the error above and no fallback model group was found for it, so the request was not retried on another model."}
== after azure-down-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 1
{"model":"gemini-3.8-flash","content":"An animated scene depicts a sunny, grassy forest clearing featuring a burrow nestled beneath a leafy tree on a mossy mound.","prompt_tokens":684}
== after gemini-video 200
x-litellm-model-group: gemini-video
x-litellm-attempted-fallbacks: 0
{"model":"gemini-video","content":"An animated scene depicts a large tree with an underground burrow beneath its roots, set in a sunlit grassy forest clearing with gently swaying foliage.","prompt_tokens":684}
== after azure-down-tools 500
{"error":"litellm.APIConnectionError: AzureException APIConnectionError - Connection error.\n\nLiteLLM: model group 'azure-down-tools' failed with the error above. Fallback to openai-backup also failed: litellm.BadRequestError: OpenAIException - Invalid type for 'messages[1].function_call.arguments': expected a"}
== after openai-backup 400
{"error":"litellm.BadRequestError: OpenAIException - Invalid type for 'messages[1].function_call.arguments': expected a string, but got null instead.\n\nLiteLLM: model group 'openai-backup' failed with the error above and no fallback model group was found for it, so the request was not retried on another model."}
== after azure-down-legacy 500
{"error":"litellm.APIConnectionError: AzureException APIConnectionError - Connection error.\n\nLiteLLM: model group 'azure-down-legacy' failed with the error above. Fallback to openai-legacy also failed: litellm.BadRequestError: OpenAIException - Invalid type for 'messages[1].function_call.arguments': expected "}
== after openai-legacy 400
{"error":"litellm.BadRequestError: OpenAIException - Invalid type for 'messages[1].function_call.arguments': expected a string, but got null instead.\n\nLiteLLM: model group 'openai-legacy' failed with the error above and no fallback model group was found for it, so the request was not retried on another model."}

Blast radius at f4cfe9973e

What else reads the messages, base against head and merged with main

One answer changes beyond the fix. An Azure request with a null legacy function_call.arguments that falls back to a model taking the function role went from 200 to 500, and the error carries the fallback's own 400. Every other answer is the same or goes from a made-up video to the real clip. The requests litellm sends to vLLM and Azure are byte-identical on both sides. What hooks, guardrails, and the stored spend-log request receive is now the caller's messages

Breaking

  • Azure down, falling back to gpt-4.1-mini with a null legacy function_call.arguments, went from 200 to 500 with OpenAI's "expected a string, but got null" 400 inside, the same 400 a direct gpt-4.1-mini call gets
    • Base convert_to_azure_openai_messages wrote "" onto the caller's message and the router replayed that edited message to the fallback
    • Shipped as asked by Mateo in the ticket this PR resolves, "the fallback receives the caller's request unchanged", and recorded in Decision 7
  • A vLLM to openai/ fallback now gets the caller's video file part where it used to get video_url
    • Same edge and same approval as above, Decision 7. Not driven live, see Not verified

Backward incompatible

  • Logging callbacks, during_call guardrails, the post-call success hook, and the stored proxy_server_request in LiteLLM_SpendLogs now hold the caller's messages for hosted vLLM and Azure
    • Base gave them the rewritten ones, video_url for the caller's file, format dropped, a bare image_url string turned into {url}, and function_call.arguments "" for null. Base wrote that into the spend row even on Azure calls with no fallback
    • Base's during_call guardrail saw the caller's or the rewritten messages depending on timing. Head always gives it the caller's
    • Each is what every provider whose transform never edited in place already gives them. Shipped as asked by Mateo in the same ticket, Decision 6
  • A vLLM video fallback to Gemini now bills the video, 684 prompt tokens where base billed 24 for a request Gemini never saw the video in. That is the fix itself, same ticket
  • A repeat Azure media request now hits the response cache. Base looked up the caller's messages but wrote the entry under the rewritten ones, so it never hit. A vLLM fallback to Gemini now caches under the key a direct Gemini call uses. Same ticket, Decision 6
  • A streamed vLLM video call with no server usage logs an estimate instead of 0. Same ticket, Decision 6 and the Low caveat

Regression risk

  • Third-party logging and guardrail vendors now receive the caller's file and function_call shapes for these two providers. Only a custom logger and a custom guardrail were driven. Every vendor already receives those shapes from every other provider, so the risk is low
  • A second vLLM server configured as openai/ behind a hosted vLLM model. The OpenAI transform downloads the caller's video URL and sends it as file data, which vLLM may reject. It needs a real vLLM server to drive

Dependency graph

Dependent Entry Status
HostedVLLMChatConfig.transform_request hosted_vllm/ chat verified live
VLLMConfig subclass vllm/ unreachable
AzureOpenAIConfig azure/ chat verified live
AzureOpenAIGPT5Config azure/ GPT-5 wire verified
AzureOpenAIO1Config azure/ o-series not on path
Router fallback replay chat, /v1/messages verified live
/v1/messages adapter Anthropic route verified live
/v1/responses Responses route not on path
Logging callbacks litellm_settings.callbacks verified live
during_call guardrail guardrails verified live
Post-call success hook proxy verified live
Spend row Postgres verified live
Response cache cache: true verified live
Stream token estimate streaming not driven
Gemini, OpenAI transforms fallback targets verified live

VLLMConfig calls vllm_handler.completion and never reaches transform_request. The o-series transform does not call convert_to_azure_openai_messages. Mistral is not changed

Not verified

  • The Azure GPT-5 answer. gpt-5.4-nano answered 429 "exceeded token rate limit" on both sides twice. The recorded request body and headers are identical base and head
  • A vLLM to openai/ fallback against a real vLLM server. No vLLM server is available, so every vLLM call goes to a closed port
  • The streamed vLLM token estimate, which needs a vLLM server that streams without usage
  • The dashboard Logs page was not opened. Its request view renders the same proxy_server_request column read above

How it ran

Base 05518975a5, head f4cfe9973e, and head merged with main at ec48e2491c, each with its own Postgres, two workers, and its own Rust bridge build. Each proxy printed litellm.__file__ inside its own tree. A forwarding recorder sat in front of the vLLM base, which forwards to a closed port so every vLLM call fails over, and in front of the real Azure resource. rig_hooks.py loads a CustomLogger and a during_call guardrail through config that record the messages each hook gets

model_list:
  - model_name: vllm-video
    litellm_params: {model: hosted_vllm/Qwen/Qwen2.5-VL-7B-Instruct, api_base: os.environ/VLLM_REC}
  - model_name: vllm-chat
    litellm_params: {model: hosted_vllm/Qwen/Qwen3-8B, api_base: os.environ/VLLM_REC}
  - model_name: azure-41
    litellm_params: {model: azure/gpt-4.1-2025-04-14, api_base: os.environ/AZURE_REC, api_key: os.environ/AZURE_AI_API_KEY, api_version: "2025-04-01-preview"}
  - model_name: azure-gpt5
    litellm_params: {model: azure/gpt-5.4-nano, api_base: os.environ/AZURE_REC, api_key: os.environ/AZURE_AI_API_KEY, api_version: "2025-04-01-preview"}
  - model_name: gemini-video
    litellm_params: {model: gemini/gemini-flash-latest, api_key: os.environ/GEMINI_API_KEY}
  - model_name: claude-thinking
    litellm_params: {model: anthropic/claude-sonnet-5-5, api_key: os.environ/ANTHROPIC_API_KEY}
router_settings:
  num_retries: 0
  disable_cooldowns: true
  fallbacks: [{vllm-video: [gemini-video]}, {vllm-chat: [claude-thinking]}]
guardrails:
  - guardrail_name: rig-during
    litellm_params: {guardrail: rig_hooks.RigGuard, mode: during_call, default_on: true}
litellm_settings:
  callbacks: rig_hooks.rig_logger
general_settings:
  store_prompts_in_spend_logs: true
Cell Base Head Merged
c1 video URL, vLLM to Gemini "NO VIDEO ATTACHED" real clip real clip
c2 video base64, vLLM to Gemini "NO VIDEO ATTACHED" real clip real clip
c3 thinking turn, vLLM to Claude 200, 735 tokens 200, 735 tokens 200, 735 tokens
c4 video URL stream, vLLM to Gemini made-up piglet real clip real clip
c5 Azure tools and media 200, 612 tokens 200, 612 tokens 200, 612 tokens
c6 c5 streamed 200, 14 chunks 200, 14 chunks 200, 14 chunks
c7 Azure GPT-5 media 429 429 not run
c8 /v1/messages to Azure "Red" "Red" "Red"
c9 /v1/messages, vLLM to Gemini "Red" "Red" "Red"
vllm counts base=13 head=13 merge=13
vllm base=head identical
azure counts base=3 head=3 merge=3
azure base=head identical
head and merge bodies identical, accept-encoding differs (the merged venv was synced without brotli and zstandard, uv.lock unchanged)
hooks: head-db = merge, base-db differs on 34 lines

Response cache, cache: true with type: local, read from the cache keys each proxy logged since each worker has its own cache

Azure c5 sent twice  base lookup 120e87b7 write b896a24d, no hit, 2 Azure calls
Azure c5 sent twice  head lookup 120e87b7 write 120e87b7, hit, 1 Azure call
vLLM c1 fallback     base key 39d97560, from the rewritten messages
vLLM c1 fallback     head key fe0a68bb, the same key a direct gemini-video call logs on both sides

Stored proxy_server_request messages per spend row

base  c1  user[text video_url:{url}]
head  c1  user[text file:{file_id,format}]
base  c5  user / assistant(function_call.arguments='') / function / user[text image_url:{url} image_url:{url} file:{file_data,filename}]
head  c5  user / assistant(function_call.arguments=None) / function / user[text image_url:str image_url:{format,url} file:{file_data,filename,format}]
merge c1  same as head
merge c5  same as head

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A fallback that relied on Azure's or vLLM's rewrite now answers like a direct call to the fallback model
    • Azure down to gpt-4.1-mini with a null legacy function_call.arguments went from 200 to 500, see Decision 7
    • A vLLM video fallback to openai/ now downloads the caller's URL (an unreachable one gets a 400), and one to Anthropic gets Anthropic's 400

Low

  • Gemini still rewrites the caller's https image and file URLs in place
    • Pre-existing, tracked separately
  • On main fix(gemini): send video_url content parts to Gemini instead of dropping them #53406 fixed Gemini's video_url drop
    • Main's visible fix is the Azure cache hit
  • Streamed vLLM video calls with no server usage now log estimated prompt tokens instead of 0
    • The estimate counts a video as one image, tracked separately
Decisions
  1. Each transform builds new objects only where it changes something. The other option was a deep copy of the messages in the router before each fallback, which costs a full copy of every base64 video or image on every request and still leaves SDK callers who reuse their messages exposed
  2. hosted vLLM passes the OpenAI base transform new message dicts and content lists. The base itself stopped editing image_url and file items in fix(openai): stop stripping cache_control from the caller's own messages and tools #35602, which is in this PR's merge base, so this PR leaves that file alone
  3. Mistral is not changed. Its file part rewrite (fix(mistral): forward prompt_cache_key to the Mistral API #47432) and its name drop both build new dicts at the merge base
  4. _azure_tool_call_invoke_helper now returns the chunk type instead of an optional one, since it never returned None
  5. fix(hosted_vllm): stop rewriting the caller's video file part into video_url in place #44977 converted the video part into a new list but still assigned the result onto the message dict it was given, and it did not touch the assistant turns or Azure, so this PR replaces it instead of building on it. Thanks @sungbin1015 for the first take
  6. Logging callbacks, during_call guardrails, the post-call success hook, and the request stored in spend logs now see the messages the caller sent for hosted vLLM and Azure, where they used to see the rewritten ones. At the merge base a during_call guardrail saw one or the other depending on timing. That is what every provider whose transform never edited in place already logs. The body sent to the provider is still logged as raw_request when log_raw_request_response is on. Two more effects follow. A repeat of the same vLLM video or Azure media request now hits the response cache, because the merge base rewrote the messages between the cache lookup and the cache write. A streamed vLLM video call with no usage from the server now gets its prompt tokens estimated from the caller's file part, where the merge base logged 0 because the token counter raised on the rewritten video_url part
  7. A fallback now gets the caller's messages, so it answers what a direct call to the fallback model answers. That is the same trade fix(openai): stop stripping cache_control from the caller's own messages and tools #35602 made for the OpenAI base. A fallback that only worked because the primary's rewrite leaked into it now fails the way that direct call does. Azure turned a null legacy function_call.arguments into "", so an Azure to OpenAI fallback on a model that still takes the function role now gets OpenAI's 400 for the null. A vLLM to openai/ fallback, such as a second vLLM server, now gets the caller's file part, which the OpenAI transform downloads and sends as file data, so that server is better set up as hosted_vllm/. The other option was to turn null arguments into "" and video file parts into video_url in the OpenAI-compatible transforms. That changes direct calls for every one of them, so it belongs in its own change

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
Bugbot summary

[!NOTE]
Medium Risk
Behavior change on fallbacks and observability (logs/cache/guardrails) now see caller shapes instead of rewritten ones; one documented edge is Azure→OpenAI fallback with null legacy function_call.arguments now surfaces the fallback’s 400 instead of a masked 200.

Overview
Azure and hosted vLLM chat request transforms now return new message lists and content parts instead of rewriting the caller’s messages in place. Provider-specific shaping is unchanged (Azure still normalizes function_call.arguments, image_url, and file; vLLM still strips thinking fields, folds assistant tool_use into tool_calls, and maps video file parts to video_url).

That fixes router fallbacks and SDK apps that reuse conversation history: a failed vLLM or Azure call no longer leaves rewritten parts (e.g. video_url or stripped format) on the original objects, so the fallback model sees what the caller actually sent.

Unit tests assert the outbound request body still matches expectations while messages equals a pre-call deepcopy.

Reviewed by Cursor Bugbot for commit f4cfe99. Bugbot is set up for automated code reviews on this repo. Configure here.

…ilding the chat request

hosted_vllm and Azure rewrote the caller's nested message objects while building the request, so a Router fallback reused the rewritten parts. A video file part reached a Gemini fallback as video_url, which Gemini drops. Both now build new message dicts and content parts and send the same request body as before
@veria-ai

veria-ai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

…essages_vllm_mistral_azure

# Conflicts:
#	litellm/llms/hosted_vllm/chat/transformation.py
#	tests/unit/llms/azure/chat/test_azure_chat_gpt_transformation.py
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable issues found.

Summary

hosted vLLM and Azure now build changed messages and content parts without editing the caller’s history. Provider request shapes stay the same.

  • Hosted vLLM prepares its chat request without changing the caller’s messages.
  • Azure prepares its chat request without changing the caller’s messages.

Reviews (3) · Last reviewed commit: "test(hosted_vllm): drop the async varian..." · Reviewed by Greptile

@codspeed

codspeed Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing quietjules:litellm_copy_caller_messages_vllm_mistral_azure (f4cfe99) with main (ec48e24)

Open in CodSpeed

@codecov

codecov Bot commented Nov 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.82353% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/llms/hosted_vllm/chat/transformation.py 98.11% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

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.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit f4cfe99. Configure here.

@mateo-berri mateo-berri left a comment

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.

LGTM

@mateo-berri
mateo-berri merged commit c9fc315 into BerriAI:main Nov 24, 2026
153 of 155 checks passed
mateo-berri added a commit that referenced this pull request Nov 24, 2026
fix(hosted_vllm,azure): leave the caller's messages untouched when building the chat request on lts/1.108.x (#51841)
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.

2 participants