Skip to content

perf: move Anthropic, Vertex Anthropic, Ollama and HF template fetches off the event loop - #40311

Merged
yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_lit_7028_async_remote_media
Sep 8, 2026
Merged

yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_lit_7028_async_remote_media

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Async chat requests still download images with blocking HTTP on the event loop's thread pool
  • Direct Anthropic http images, Vertex AI Anthropic forced base64, Ollama images, watsonx HF templates
  • A burst of slow image URLs stalls unrelated text requests on the same proxy

How it solves it:

  • Anthropic and Ollama configs gain async_transform_request built on async_inline_remote_media
  • Anthropic handler awaits the config's async transform before dispatch and in the Rust fallback
  • Vertex AI Anthropic inlines every remote image, direct Anthropic keeps http only
  • watsonx text opts into uses_async_transform_request, GPT-OSS always awaits ahf_chat_template

User Flow

Before: a team sends chat requests with image URLs through the proxy and every other request slows to a crawl

  1. Thirty clients each send POST https://litellm-domain/v1/chat/completions to an Anthropic, Vertex AI Anthropic or Ollama model with an image_url that takes 8 seconds to download
  2. Another client sends a small text-only POST https://litellm-domain/v1/chat/completions to the Anthropic model 1.5 seconds later
  3. The text-only request comes back 200 after about 15 seconds, and the thirty image requests finish in three waves (9s, 17s, 25s)

After: the same burst finishes in one wave and the text-only request stays fast

  1. Thirty clients each send POST https://litellm-domain/v1/chat/completions to an Anthropic, Vertex AI Anthropic or Ollama model with an image_url that takes 8 seconds to download
  2. Another client sends a small text-only POST https://litellm-domain/v1/chat/completions to the Anthropic model 1.5 seconds later
  3. The text-only request comes back 200 in about 0.6 seconds, and all thirty image requests finish together in the 8 to 9 second wave (Vertex adds its own upstream latency on top)

Relevant issues

Follow-up to #39839

Linear ticket

Resolves LIT-7028

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/test_litellm/<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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

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

Shared setup. One proxy process (--num_workers 1) on port 47028 with PYTHONPATH pointing at the checkout under test, the same config.yaml for both arms: anthropic-haiku is anthropic/claude-haiku-4-5 with a real key, vertex-claude is vertex_ai/claude-sonnet-4-6 in us-east5 with real credentials, ollama-llava is ollama/llava with api_base pointing at a local stand-in on 127.0.0.1:47029 (there is no Ollama server on this box, the stand-in logs the images array it receives and answers a fixed completion). The same local server also serves GET /slow.png?delay=8, a one pixel PNG returned after 8 seconds, and user_url_allowed_hosts lists it. Each leg fires 30 concurrent requests, then 1.5 seconds later one text-only anthropic-haiku request and one GET /health/liveliness. The image body is byte-identical across arms

IMG='http://127.0.0.1:47029/slow.png?delay=8'
for i in $(seq 1 30); do
  curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' http://127.0.0.1:47028/v1/chat/completions \
    -H 'Authorization: Bearer sk-lit7028' -H 'Content-Type: application/json' \
    -d '{"model":"anthropic-haiku","max_tokens":20,"messages":[{"role":"user","content":[{"type":"text","text":"One word: what color is this image?"},{"type":"image_url","image_url":{"url":"'"$IMG&n=$i"'"}}]}]}' &
done
sleep 1.5
curl -s -o /dev/null -w 'text-only during fan-out: %{http_code} %{time_total}s\n' http://127.0.0.1:47028/v1/chat/completions \
  -H 'Authorization: Bearer sk-lit7028' -H 'Content-Type: application/json' \
  -d '{"model":"anthropic-haiku","max_tokens":5,"messages":[{"role":"user","content":"say hi"}]}' &
curl -s -o /dev/null -w 'liveliness during fan-out: %{http_code} %{time_total}s\n' http://127.0.0.1:47028/health/liveliness &
wait

The same loop runs with "model":"vertex-claude" and "model":"ollama-llava". Timings below are %{time_total} per request, grouped as count status seconds

Before (35451ec)

anthropic-haiku, 30 concurrent http image requests

  1. Statuses: 12 200 9s; 12 200 17s; 6 200 25s (three waves 8s apart, 12 downloads at a time, matching the image server log below)
  2. Text-only anthropic-haiku during the fan-out: 200 15.104831s
  3. GET /health/liveliness during the fan-out: 200 0.001985s
  4. Responses 1 and 30: White. / White. (real Anthropic answer)

vertex-claude, 30 concurrent http image requests

  1. Statuses: 12 200 10s; 2 200 17s; 9 200 18s; 1 200 20s; 2 200 25s; 2 200 26s; 1 200 27s; 1 200 28s
  2. Text-only anthropic-haiku during the fan-out: 200 15.110801s
  3. GET /health/liveliness during the fan-out: 200 0.001804s
  4. Responses 1 and 30: **Green** / **Green** (real Vertex AI answer)

ollama-llava, 30 concurrent http image requests

  1. Statuses: 12 200 8s; 12 200 16s; 6 200 24s
  2. Text-only anthropic-haiku during the fan-out: 200 15.368942s
  3. GET /health/liveliness during the fan-out: 200 0.001764s
  4. Image server log, GET starts per second: 12 21:59:20; 12 21:59:28; 6 21:59:36 (downloads ran 12 at a time)
  5. Stand-in Ollama log: POST /ollama/api/generate model=llava ... images=['iVBORw0KGgoAAAANSUhEUgAA...'], response Green (sink saw 1 base64 image(s))

After (de87469)

anthropic-haiku, 30 concurrent http image requests

  1. Statuses: 30 200 9s (one wave)
  2. Text-only anthropic-haiku during the fan-out: 200 0.571313s
  3. GET /health/liveliness during the fan-out: 200 0.002038s
  4. Responses 1 and 30: White. / White (real Anthropic answer, image still delivered as base64 since Anthropic cannot fetch 127.0.0.1)

vertex-claude, 30 concurrent http image requests

  1. Statuses: 9 200 12s; 16 200 13s; 2 200 14s; 3 200 15s (8s download plus Vertex latency, no 17s to 28s tail)
  2. Text-only anthropic-haiku during the fan-out: 200 1.403497s
  3. GET /health/liveliness during the fan-out: 200 0.002189s
  4. Responses 1 and 30: **Green** / **Green** (real Vertex AI answer)

ollama-llava, 30 concurrent http image requests

  1. Statuses: 30 200 8s (one wave)
  2. Text-only anthropic-haiku during the fan-out: 200 0.547705s
  3. GET /health/liveliness during the fan-out: 200 0.001998s
  4. Image server log, GET starts per second: 30 22:25:49 (all 30 downloads began together)
  5. Stand-in Ollama log: POST /ollama/api/generate model=llava ... images=['iVBORw0KGgoAAAANSUhEUgAA...'], response Green (sink saw 1 base64 image(s))

Which branch each leg exercised: all three legs are acompletion=True, non-streaming. Anthropic and Vertex go through AnthropicChatCompletion.completion with the Rust core disabled by default, so they took the new acompletion_dispatch closure (Vertex with is_vertex_request=True, which is what flips the predicate to inline https as well). Ollama went through BaseLLMHTTPHandler, which only calls async_transform_request because OllamaConfig.uses_async_transform_request is now true. The sync litellm.completion path, streaming, and the Rust-enabled path are covered by the existing Anthropic handler and rust_bridge suites (570 tests in tests/test_litellm/llms/anthropic/chat, tests/test_litellm/rust_bridge plus the new ones pass locally) rather than by this live run. The watsonx GPT-OSS template path is covered by the new parameterized test only, since there are no watsonx credentials on this box

Type

🐛 Bug Fix

Caveats (if any)

Low

  • AnthropicConfig itself does not set uses_async_transform_request, on purpose: its subclasses routed through BaseLLMHTTPHandler (Azure AI Anthropic, Databricks, Bedrock Claude platform) keep their current sync transform; the Anthropic handler awaits async_transform_request unconditionally instead
  • Azure AI Anthropic has its own completion that still transforms synchronously; out of scope here
  • Ollama chat (ollama_chat/) never fetched remote images, only the Ollama completion path did, so only that one changed
  • Fetch timeouts, image size caps and download concurrency bounds are unchanged (out of scope per the ticket)

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

Link to Devin session: https://app.devin.ai/sessions/54d438b6c4af4cd7a4bd26c1f3fbcb30
Open in Devin Desktop: https://app.devin.ai/desktop/session/54d438b6c4af4cd7a4bd26c1f3fbcb30?variant=devin
Requested by: @yassin-berriai

…s off the event loop

Direct Anthropic http image inlining, Vertex AI Anthropic forced base64 conversion, Ollama completion image download and the watsonx GPT-OSS Hugging Face chat template lookup all ran synchronous HTTP inside the async request path. Each provider config now transforms through async_inline_remote_media on the async path, the Anthropic handler awaits the config's async_transform_request before dispatch and in the Rust fallback, and watsonx text exposes async_transform_request and always awaits ahf_chat_template

Resolves LIT-7028

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit_7028_async_remote_media (de87469) with litellm_internal_staging (5b2b542)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR moves remote-media and Hugging Face template retrieval off async request event-loop paths.

  • Adds asynchronous media inlining for direct Anthropic, Vertex AI Anthropic, and Ollama completion requests.
  • Routes Anthropic async dispatch and Rust fallback through asynchronous request transformation.
  • Makes watsonx text completion use asynchronous prompt-template retrieval.
  • Adds mocked regression tests covering each updated provider path.

Confidence Score: 5/5

The PR appears safe to merge, with no outstanding findings after the previous test-design concern was withdrawn.

The asynchronous transformations preserve provider-specific media behavior while moving blocking fetches off the event loop, and the relevant dispatch paths are covered by mocked regression tests. The only previous thread was manually resolved after Greptile accepted the author’s rationale and withdrew the finding.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/prompt_templates/image_handling.py Adds media-part classification so asynchronous transforms can selectively inline image URLs.
litellm/llms/anthropic/chat/handler.py Moves Anthropic async request transformation ahead of dispatch while preserving synchronous and Rust fallback behavior.
litellm/llms/anthropic/chat/transformation.py Adds asynchronous inlining of HTTP image URLs for direct Anthropic requests.
litellm/llms/ollama/completion/transformation.py Enables asynchronous transformation and remote-image inlining for Ollama completion requests.
litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py Configures Vertex AI Anthropic to inline all remote image URLs asynchronously.
litellm/llms/watsonx/chat/transformation.py Ensures GPT-OSS template application consistently uses the asynchronous Hugging Face path.
litellm/llms/watsonx/completion/transformation.py Opts watsonx text completion into the standard asynchronous request-transform interface.

Reviews (2): Last reviewed commit: "perf: move Anthropic, Vertex Anthropic, ..." | Re-trigger Greptile

@codecov

codecov Bot commented Sep 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/llms/anthropic/chat/handler.py 81.25% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai the only open finding was accepted in its thread above, please re-review de87469 with that resolved

@yassin-berriai
yassin-berriai merged commit 0f886d9 into litellm_internal_staging Sep 8, 2026
81 of 82 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_lit_7028_async_remote_media branch September 8, 2026 22:53
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