Commit graph

5908 commits

Author SHA1 Message Date
Ishaan Jaffer
ad40eeba2b fix: use async Redis write for cooldown on async call paths
litellm fires both failure_handler (sync) and async_failure_handler for
every call. deployment_callback_on_failure was doing a blocking Redis SET
via _set_cooldown_deployments() on every failure, including from async
request paths — stalling the event loop.

Changes:
- CooldownCache.async_add_deployment_to_cooldown(): new method using
  await self.cache.async_set_cache()
- async_set_cooldown_deployments(): async counterpart to
  _set_cooldown_deployments(), calls the new async cache method
- async_deployment_callback_on_failure(): now also handles cooldown
  writes via await async_set_cooldown_deployments()
- deployment_callback_on_failure(): skips the cooldown write for async
  callers (detected via CallTypes flags in litellm_params) to avoid the
  double Redis write; sync callers keep the existing sync path
- async_routing_strategy_pre_call_checks(): swapped to
  await async_set_cooldown_deployments()
2026-03-19 20:15:41 -07:00
Ishaan Jaffer
fd21f55160 refactor(proxy): move DDSpanTagger to its own file litellm/proxy/dd_span_tagger.py 2026-03-17 04:04:05 +05:30
Ishaan Jaffer
4bc8ca12db refactor(proxy): consolidate DD APM tag helpers into DDSpanTagger class 2026-03-17 04:04:05 +05:30
Ishaan Jaffer
916c773df7 feat(proxy): add key_alias, key_hash, requested_model tags to DD APM spans 2026-03-17 04:03:58 +05:30
Harshit28j
f6915872fa fix: ensure metadata isolation for silent model metrics 2026-03-17 01:29:23 +05:30
Harshit28j
777fc5a297 fix: test coverage 2026-03-17 01:29:23 +05:30
Harshit28j
8e852de117 fix: req changes by greptile on test coverage 2026-03-17 01:29:23 +05:30
Harshit28j
162796f532 fix: ensure metadata isolation in silent experiment to prevent metric collision 2026-03-17 01:29:23 +05:30
Harshit28j
70de83a6d8 fix: silent metrics race condition 2026-03-17 01:29:07 +05:30
Ishaan Jaffer
03500799be refactor: clean class with static methods, add tests, fix sentinel pattern 2026-02-27 18:04:05 -08:00
Ishaan Jaffer
1e936df2b4 _add_dd_apm_tags_for_litellm_call_id 2026-02-26 12:10:15 -08:00
Ishaan Jaff
bbf2c4fd0c [Feat] Add control for setting upperbound on chunk processing time (#22209)
* add LITELLM_MAX_STREAMING_DURATION_SECONDS

* add add LITELLM_MAX_STREAMING_DURATION_SECONDS

* fix: address Greptile review - rename constant, add sync check, add tests

- Rename MAX_STREAMING_CHUNK_DURATION_S → MAX_STREAMING_DURATION_S (misleading "CHUNK")
- Add _check_max_streaming_duration to SyncResponsesAPIStreamingIterator.__next__
- Add 8 unit tests covering both CustomStreamWrapper and ResponsesAPI paths
- Fix pre-existing pyright errors in streaming_handler.py

Made-with: Cursor

* add add LITELLM_MAX_STREAMING_DURATION_SECONDS

Made-with: Cursor
2026-02-26 11:49:42 -08:00
Ishaan Jaffer
699911dfc5 test(router): add regression test for FallbackStreamWrapper _hidden_params preservation 2026-02-24 12:04:55 -08:00
Ishaan Jaffer
de414859f2 fix(router): preserve _hidden_params in FallbackStreamWrapper so x-litellm-overhead-duration-ms is emitted for streaming requests 2026-02-24 12:04:39 -08:00
Ishaan Jaffer
9873ad62fa feat(prometheus): add opt-in stream label to litellm_proxy_total_requests_metric
Set prometheus_emit_stream_label: true in litellm_settings to emit a
stream label (True/False/None) on litellm_proxy_total_requests_metric.

Opt-in to avoid breaking cardinality on existing deployments.
2026-02-24 12:03:22 -08:00
Ishaan Jaffer
7a233d5f06 fix(proxy): remove per-chunk debug log in async_data_generator
Remove verbose_proxy_logger.debug that formatted every streaming chunk,
which triggered expensive Pydantic serialization on the hot path.
2026-02-24 12:00:02 -08:00
michelligabriele
20d3cbfdeb fix: revert httpx client caching that caused closed client errors
AsyncHTTPHandler.__del__ was closing httpx clients still in use by
AsyncOpenAI/AsyncAzureOpenAI due to independent cache lifecycles.
Restores standalone httpx client creation for OpenAI/Azure providers.
2026-02-04 18:45:08 -08:00
Ishaan Jaffer
b7e48f1d9e test fix 2026-01-31 19:08:07 -08:00
Ishaan Jaffer
466e6bdcf1 fix(test): make test_proxy_failure_metrics resilient to missing proxy-level metrics
- Check for both litellm_proxy_failed_requests_metric_total and the deprecated litellm_llm_api_failed_requests_metric_total
- The proxy-level failure hook may not always be called depending on where the exception occurs
- Simplify total_requests check to only verify key fields

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-01-31 18:46:27 -08:00
Ishaan Jaffer
92c8e00520 test_proxy_success_metrics 2026-01-31 18:36:22 -08:00
Ishaan Jaffer
faff9d1dc5 test_proxy_failure_metrics 2026-01-31 18:10:17 -08:00
Ishaan Jaffer
35e29c2bcd Revert "Merge pull request #18790 from BerriAI/litellm_key_team_routing_3"
This reverts commit ae26d8e68a, reversing
changes made to 864e8c6543.
2026-01-31 17:58:46 -08:00
shin-bot-litellm
0c006794f1
litellm_fix_mapped_tests_core: fix test isolation and mock injection issues (#20209)
* litellm_fix_mapped_tests_core: fix test isolation and mock injection issues

## Problem
Four tests in litellm_mapped_tests_core were failing:
1. test_register_model_with_scientific_notation - KeyError due to test isolation issues
2. test_search_uses_registry_credentials - Mock not being called due to incorrect patch path
3. test_send_email_missing_api_key - Real API calls despite mocking
4. test_stream_transformation_error_sync - Mock not effective, real API called

## Solution

### test_register_model_with_scientific_notation
- Use unique model name to avoid conflicts with other tests
- Clear LRU caches before test to prevent stale data
- Clean up model_cost entry after test

### test_search_uses_registry_credentials
- Use patch.object() on the actual base_llm_http_handler instance
- String-based patching for instance methods can fail; direct object patching is more reliable

### test_send_email_missing_api_key
- Directly inject mock HTTP client into logger instance
- This bypasses any caching issues that could cause the fixture mock to be ineffective

### test_stream_transformation_error_sync
- Patch litellm.completion directly instead of the handler module's litellm reference
- This ensures the mock is effective regardless of import order

## Regression
These tests were affected by LRU caching added in #19606 and HTTP client caching.

* fix(test): use patch.object for container API tests to fix mock injection

## Problem
test_retrieve_container_basic tests were failing because mocks weren't
being applied correctly. The tests used string-based patching:
  patch('litellm.containers.main.base_llm_http_handler')

But base_llm_http_handler is imported at module level, so the mock wasn't
intercepting the actual handler calls, resulting in real HTTP requests
to OpenAI API.

## Solution
Use patch.object() to directly mock methods on the imported handler
instance. Import base_llm_http_handler in the test file and patch like:
  patch.object(base_llm_http_handler, 'container_retrieve_handler', ...)

This ensures the mock is applied to the actual object being used,
regardless of import order or caching.

* fix(test): add missing Prometheus metric labels to test_proxy_failure_metrics

Add client_ip, user_agent, model_id labels to expected metric patterns.
These labels were added in PRs #19717 and #19678 but test wasn't updated.

* fix(test_resend_email): use direct mock injection for all email tests

Extend the mock injection pattern used in test_send_email_missing_api_key
to all other tests in the file:
- test_send_email_success
- test_send_email_multiple_recipients

Instead of relying on fixture-based patching and respx mocks which can
fail due to import order and caching issues, directly inject the mock
HTTP client into the logger instance. This ensures mocks are always used
regardless of test execution order.

* fix(test): use patch.object for image_edit and vector_store tests

- test_image_edit_merges_headers_and_extra_headers: import base_llm_http_handler
  and use patch.object instead of string path patching
- test_search_uses_registry_credentials: import module and patch via
  module.base_llm_http_handler to ensure we patch the right instance

---------

Co-authored-by: Ishaan Jaff <ishaanjaffer0324@gmail.com>
2026-01-31 17:53:54 -08:00
Ishaan Jaffer
bb3c2a92a0 fix(test): update test_prometheus with masked user_id and missing labels
- Update expected user_id from 'default_user_id' to '*******_user_id' (PII masking)
- Add missing client_ip, user_agent, model_id labels (from PRs #19717, #19678)
- Update label order to match Prometheus alphabetical sorting

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-01-31 17:51:27 -08:00
Ishaan Jaffer
3a3576dfb4 fix: update test_prometheus to expect masked user_id in metrics
The user_id field 'default_user_id' is being masked to '*******_user_id'
in prometheus metrics for privacy. Updated test expectations to match
the actual behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-01-31 17:26:37 -08:00
shin-bot-litellm
37a45a3295
litellm_fix_mapped_tests_core: clear client cache and fix isinstance checks (#20196)
## Problem
Tests using mocked HTTP clients were hitting real APIs because:
1. HTTP client cache was returning previously cached real clients
2. isinstance checks failed due to module identity issues from sys.path

### Tests affected:
- test_send_email_missing_api_key
- test_send_email_multiple_recipients (resend & sendgrid)
- test_search_uses_registry_credentials
- test_vector_store_create_with_simple_provider_name
- test_vector_store_create_with_provider_api_type
- test_vector_store_create_with_ragflow_provider
- test_image_edit_merges_headers_and_extra_headers
- test_retrieve_container_basic (container API tests)

## Solution
1. Add clear_client_cache fixture (autouse=True) to clear
   litellm.in_memory_llm_clients_cache before each test
2. Fix isinstance checks to use type name comparison
   (avoids module identity issues from sys.path.insert)

## Why not disable_aiohttp_transport
The default transport is aiohttp, so tests should work with it.
Clearing the cache ensures mocks are used instead of cached real clients.

## Regression
PR #19829 (commit f95572e3ed) added @respx.mock but cached clients
from earlier tests were being reused, bypassing the mocks.

Co-authored-by: shin-bot-litellm <shin-bot-litellm@users.noreply.github.com>
2026-01-31 15:42:17 -08:00
Ishaan Jaffer
671fd848da fix: bedrock-converse-claude-sonnet-4.5 2026-01-31 14:41:02 -08:00
shin-bot-litellm
e2475f4f9a
fix(test): correct prompt_tokens in test_string_cost_values (#20185)
The test had prompt_tokens=1000 but the sum of token details was 1150
(text=700 + audio=100 + cached=200 + cache_creation=150).

This triggered the double-counting detection logic which recalculated
text_tokens to 550, causing the assertion to fail.

Fixed by setting prompt_tokens=1150 to match the sum of details.
2026-01-31 14:23:10 -08:00
Ishaan Jaffer
a4acf81286 fix bedrock-nova-premier 2026-01-31 13:44:09 -08:00
Ishaan Jaffer
2e6659d9cb test_embedding fix 2026-01-31 13:43:53 -08:00
shin-bot-litellm
db120c524b
fix(test): accept both AuthenticationError and InternalServerError in batch_completion test (#20186)
The test uses an invalid API key to verify that batch_completion returns
exceptions rather than raising them. However, depending on network conditions,
the error may be:
- AuthenticationError: API properly rejected the invalid key
- InternalServerError: Connection error occurred before API could respond

Both are valid outcomes for this test case.

Co-authored-by: shin-bot-litellm <shin-bot-litellm@users.noreply.github.com>
2026-01-31 13:36:27 -08:00
shin-bot-litellm
dff7f83e7c fix(proxy): resolve 'multiple values for keyword argument' in batch cancel and file retrieve
- batch_endpoints.py: Pop batch_id from data before creating CancelBatchRequest
  to avoid duplicate batch_id when data already contains it from earlier cast

- files_endpoints.py: Pop file_id from data before calling afile_retrieve
  to avoid duplicate file_id when data was initialized with {"file_id": file_id}

- test_claude_agent_sdk.py: Disable bedrock-nova-premier test as it requires
  an inference profile for on-demand throughput (AWS limitation)

Fixes: e2e_openai_endpoints tests (test_batches_operations, test_file_operations)
Fixes: proxy_e2e_anthropic_messages_tests (nova-premier model skip)
2026-01-31 21:26:29 +00:00
Shin
586b041837 fix(test): update test_chat_completion to handle metadata in body
The proxy now adds metadata to the request body during processing.
Updated test to compare fields individually and strip metadata from
body comparison.

Fixes litellm_proxy_unit_testing_part2 CI failure.
2026-01-31 21:25:39 +00:00
shin-bot-litellm
5bd5df3ca6
fix(test): add router.acancel_batch coverage (#20183)
- Add test_router_acancel_batch.py with mock test for router.acancel_batch()
- Add _acancel_batch to ignored list (internal helper tested via public API)

Fixes CI failure in check_code_and_doc_quality job
2026-01-31 12:39:19 -08:00
Ishaan Jaffer
38f5ae8f05 test_budget_reset_and_expires_at_first_of_month 2026-01-31 12:36:53 -08:00
yuneng-jiang
b7c45991d8 Fix health endpoints 2026-01-31 12:25:04 -08:00
Ishaan Jaffer
66c7233f61 test_get_session_iterator_thread_safety 2026-01-31 12:05:09 -08:00
Ishaan Jaffer
f1b16d240e test_delete_vector_store_checks_access 2026-01-31 12:05:09 -08:00
Ishaan Jaffer
280e8a9cd7 test_get_image_non_root_uses_var_lib_assets_dir 2026-01-31 12:05:09 -08:00
yuneng-jiang
a81af9a875
Merge pull request #20177 from BerriAI/litellm_global_fallback_fix
[Fix] Model Name During Fallback
2026-01-31 11:59:54 -08:00
yuneng-jiang
c9261c9f37 fix model name during fallback 2026-01-31 11:46:58 -08:00
Ishaan Jaffer
8b575f4656 test_bedrock_nova_grounding_web_search_options_non_streaming 2026-01-31 11:23:48 -08:00
Ishaan Jaffer
3759ea2de8 test_increment_top_level_request_and_spend_metrics 2026-01-31 11:10:28 -08:00
shin-bot-litellm
fea40925cf
test: remove hosted_vllm from OpenAI client tests (#20163)
hosted_vllm no longer uses the OpenAI client, so these tests
that mock the OpenAI client are not applicable to hosted_vllm.

Removes hosted_vllm from:
- test_openai_compatible_custom_api_base
- test_openai_compatible_custom_api_video
2026-01-31 10:10:45 -08:00
shin-bot-litellm
2780e2f81e
litellm_fix(test): update Prometheus metric test assertions with new labels (#20162)
This fixes the failing litellm_mapped_enterprise_tests (metrics/logging) job.

Recent commits added new labels to several Prometheus metrics (model_id, client_ip, user_agent)
but the test assertions weren't fully updated to expect these new labels.

Tests fixed:
- test_async_post_call_failure_hook
- test_async_log_failure_event
- test_increment_token_metrics
- test_log_failure_fallback_event
- test_set_latency_metrics
- test_set_llm_deployment_success_metrics

Labels added to test assertions:
- model_id for token metrics (litellm_tokens_metric, litellm_input_tokens_metric, litellm_output_tokens_metric)
- model_id for latency metrics (litellm_llm_api_latency_metric)
- model_id for remaining requests/tokens metrics
- model_id for fallback metrics
- model_id for overhead latency metric
- client_ip and user_agent for deployment failure/total/success responses
- client_ip and user_agent for proxy failed/total requests metrics
2026-01-31 10:09:35 -08:00
yuneng-jiang
ae2cf7104d
Merge pull request #20086 from BerriAI/litellm_watsonx_inte_fix
[Fix] Add WATSONX_ZENAPIKEY to WatsonX credentials
2026-01-31 09:13:42 -08:00
yuneng-jiang
c4a2745983
Merge pull request #20031 from BerriAI/litellm_new_badge_dot
[Fix] UI - Vector Store: Allow Config Defined Models to Be Selected
2026-01-31 09:13:29 -08:00
shin-bot-litellm
e35e6504fc
litellm_fix(test): fix router silent experiment tests to properly mock async functions (#20140) 2026-01-31 07:39:05 -08:00
shin-bot-litellm
10194d96cf
litellm_fix: handle unknown models in Azure AI cost calculator (#20150) 2026-01-31 07:37:48 -08:00
shin-bot-litellm
395ad9bdc1
litellm_fix(test): add acancel_batch to Azure SDK client initialization test (#20143) 2026-01-31 07:34:54 -08:00