Commit Graph
75 Commits
Author SHA1 Message Date
malagsandGitHub 68189d1c04 [Performance] Reduce complexity of InMemoryCache.evict_cache from O(n*log(n)) to O(log(n)) (#15000)
* Improved performance by reducing complexity

* Improved logic to prevent memory from increasing too much, added test

* Restore indent

* Restore indent

* Added type annotation

* Updated test to correctly initialize the expiration_heap
2025-09-30 16:49:35 -07:00
Krish DholakiaandGitHub 88f9cad886 Merge pull request #14796 from BerriAI/litellm_anthopic_token_count_issue
Add service_tier based pricing support for openai[ BOTH Service & Priority Support]
2025-09-22 22:38:59 -07:00
Sameerlite d2208023d2 Add service_tier based pricing support for openai 2025-09-23 10:48:27 +05:30
Ishaan JaffGitHubCopilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
b9ffa98c55 [Feat] Proxy CLI: Create a python method to login using litellm proxy (#14782)
* fix: cli auth with SSO okta

* fix: add LITTELM_CLI_SERVICE_ACCOUNT_NAME

* fix: get_litellm_cli_user_api_key_auth

* use existing_key CLI

* fix: use existing key

* test auth commands

* test_cli_sso_callback_regenerate_vs_create_flow

* feat: add CLI Token Utilities

* fix: get_stored_api_key

* move file

* fix: get_valid_models

* fix config.yaml

* TestCLITokenUtils

* TestGetValidModelsWithCLI

* fix: tie user id to keys created through CLI

* fix: add teams interface to CLI

* add /keys/update to the list client commands

* fix /sso/cli/poll to return the user_id

* fix: working TeamsManagementClient

* fix CLI Login command

* fixes for auth

* Potential fix for code scanning alert no. 3400: Clear-text logging of sensitive information

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* ruff fix

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2025-09-22 21:28:38 -07:00
Ishaan Jaffer 59d2f0f465 test_string_cost_values 2025-09-20 13:34:57 -07:00
Krish DholakiaandGitHub aa54994994 Merge pull request #14666 from michaeltansg/feat/add-bangkok-timezone
Added Indochina Time timezone support for budget resets
2025-09-18 23:41:27 -07:00
Krish DholakiaandGitHub 664c83cfb5 Merge branch 'litellm_contributor_prs_09_18_2025_p2' into litellm_dev_09_17_2025_p2_v2 2025-09-18 19:50:55 -07:00
Michael Tan 6721189b7c feat: add Asia/Bangkok timezone support for budget resets
- Add Asia/Bangkok (UTC+7) to timezone_map in duration_parser.py
- Update documentation to include Bangkok in common timezone values
- Add test case to verify Bangkok timezone functionality
2025-09-18 14:56:12 +07:00
Alexsander HamirandGitHub 8d96626044 fix: iscoroutine removed from hot path +50 RPS (#14649)
* fix: iscoroutine removed from hot path

* fix: replace all instances & separate concerns

1. Replaced all instances of iscoroutine with is_async_callable
2. Place the coroutine checker in its own file

* fix: PR comment changes

* fix: missing config setting declaration

* fix: revert non-performance related changes

* fix: revert to initial implementation

* fix: remove dead const
2025-09-17 19:01:43 -07:00
Krrish Dholakia 2f45c7ffd3 feat(anthropic/chat/transformation.py): account for 1h vs. 5m cache creation token cost difference
Closes LIT-907
2025-09-17 16:16:20 -07:00
Krish DholakiaandGitHub 895c41efa3 Merge pull request #14619 from BerriAI/litellm_dev_09_16_2025_p1
UI - allow team member to view service account keys they create + Anthropic - include cache creation tokens in prompt token total (separate out during cost tracking)
2025-09-17 15:43:04 -07:00
Krish DholakiaandGitHub bf0dd4a284 Merge pull request #14418 from iabhi4/deep-copy-issue
fix: avoid deepcopy crash with non-pickleables in Gemini/Vertex
2025-09-16 22:55:31 -07:00
Krish DholakiaandGitHub 2563c0ab2d Merge pull request #14534 from hula-la/fix/response-api-bugfixes
fix: improve response api handling and cold storage configuration
2025-09-16 22:46:03 -07:00
Krrish Dholakia e488312873 fix(utils.py): log cache_creation_tokens in prompt token details
Closes LIT-907
2025-09-16 18:24:10 -07:00
Krrish Dholakia 03f2be1e20 fix: fix race conditions 2025-09-14 09:41:04 -07:00
Ishaan Jaff 26dafdc493 test fix: note this does not play nice with circleCI, it passes on local 2025-09-13 11:37:19 -07:00
Ishaan Jaff 69e451458c test_logging_opentelemetry_context_propagation 2025-09-13 09:44:36 -07:00
soojin 488b373835 test: add unit tests for response api bug fixes 2025-09-13 23:10:15 +09:00
Din ee5a9d0aa0 propagate execution context into logging tasks 2025-09-11 15:54:40 +01:00
iabhi4 384ad7e99c fix: avoid deepcopy crash with non-pickleables in Gemini/Vertex 2025-09-10 12:59:03 -07:00
Krrish Dholakia 5a0328b1a9 test: update tests 2025-09-06 19:02:03 -07:00
Ishaan JaffandGitHub 58b713d19d [Bug fix] Misclassified 500 error on invalid image_url in /chat/completions request (#14149)
* add ImageFetchError

* docs ImageFetchError

* fix ImageFetchError

* test_completion_with_invalid_image_url
2025-09-01 15:26:27 -07:00
Krish DholakiaandGitHub fffccc0675 Merge pull request #14042 from WilsonSunBritten/10988-set-truncation-threshold
Allow configuration to set threshold before request entry in spend log gets truncated
2025-08-29 06:24:28 -07:00
WilsonSunBritten b3edff02e8 fix mock tests 2025-08-28 17:40:16 -06:00
lmwang 6760a6aaa1 Fix LoggingWorker graceful shutdown to prevent CancelledError warnings
- Change exception logging to debug level during shutdown cancellation
- Add clear_queue() call to process remaining coroutines during shutdown
- Prevents 'RuntimeWarning: coroutine was never awaited' messages
- Add comprehensive tests for graceful shutdown behavior

Fixes #13970
2025-08-28 14:15:17 -07:00
Ishaan JaffandGitHub 04dc1a5351 [Feat] Add support for returning images with gemini/gemini-2.5-flash-image-preview with /chat/completions (#13983)
* add gemini-2.5-flash-image-preview

* add gemini-2.5-flash-image-preview

* add image in ChatCompletionResponseMessage

* test_gemini_image_generation_async

* Revert "Merge pull request #13394 from Deviad/feature/enhance_logging_for_containers"

This reverts commit 539b94ad4e, reversing
changes made to 71af7bcf9c.

* include `image` in Delta

* fix _process_candidates should show the image response

* fix: _handle_special_delta_attributes

* test_gemini_image_generation_async_stream

* image_generation_chat

* UI - allow looking at generated images from /chat/completions

* _create_streaming_choice

* fix import StreamingChoices

* fix ChatCompletionResponseMessage

* test_gemini_image_generation

* add gemini img migration

* fix _extract_candidate_metadata

* ui fix

* fix batch endpoint test
2025-08-27 16:16:19 -07:00
Krish DholakiaandGitHub 71af7bcf9c Merge pull request #13374 from blahgeek/fix-count-special-token
Fix token_counter with special token input
2025-08-26 23:19:26 -07:00
Ishaan JaffandGitHub 433d1a4947 [Bug fix] - Fix /messages fallback from Anthropic API -> Bedrock API (#13946)
* use helper get_provider_specific_headers

* fix get_provider_specific_headers

* test_anthropic_messages_fallbacks

* bedrock/us.anthropic.claude-sonnet-4

* fix: get_provider_specific_headers

* TestProviderSpecificHeaderUtils

* test_anthropic_messages_fallbacks
2025-08-25 13:44:54 -07:00
Ishaan Jaff f1c710a608 test_e2e_generate_cold_storage_object_key_not_configured 2025-08-23 13:33:33 -07:00
Ishaan JaffandGitHub 56c16fc6f6 [Performance] Reduce Significant CPU overhead from litellm_logging.py (#13895)
* fix: litellm.configured_cold_storage_logger

* fix Session Management - Non-OpenAI Models docs

* ruff fix

* test fix
2025-08-22 16:17:57 -07:00
Jugal D. BhattandGitHub 1beba93cc8 Fix - add safe divide by 0 for most places to prevent crash (#13624) 2025-08-14 11:17:49 -07:00
Krish DholakiaandGitHub 6afaf5721a [Fix] Streaming - consistent 'finish_reason' chunk index (#13560)
* feat(model_response_utils.py): new function to check if modelresponsestream is empty

used for checking https://github.com/BerriAI/litellm/issues/13348

* fix(streaming_handler.py): skip chunk if empty

Fixes https://github.com/BerriAI/litellm/issues/13348

* fix(streaming_handler.py): add is_empty logic to async flow
2025-08-12 23:21:57 -07:00
Ishaan JaffandGitHub 3b65733af8 [Bug fix] - Error creating standard logging object - can't register atexit after shutdownLitellm fixes standard logging payload (#13436)
* fix: _generate_cold_storage_object_key

* _get_configured_cold_storage_custom_logger

* test_e2e_generate_cold_storage_object_key_runtime_error_handled
2025-08-08 12:38:26 -07:00
Ishaan Jaff e8c081b8ff test_stream_chunk_builder_litellm_usage_chunks 2025-08-07 15:22:52 -07:00
Ishaan JaffandGitHub 4d941c914e [Feat] Responses API Session Handling - Multi media support (#13347)
* rename ResponsesSessionHandler

* use ResponsesSessionHandler

* test session handler

* refactor ResponsesSessionHandler

* fix get_proxy_server_request_from_spend_log

* use constant for LITELLM_TRUNCATED_PAYLOAD_FIELD

* add _should_check_cold_storage_for_full_payload

* add get_class_type_for_custom_logger_name

* get_active_custom_logger_for_callback_name

* add get_proxy_server_request_from_cold_storage to CustomLogger

* add ColdStorageHandler

* start using cold storage integration

* add get_proxy_server_request_from_cold_storage

* fixes from manual testing

* s3 v2 fix getting region name

* ChatCompletionImageUrlObject

* use _get_configured_cold_storage_custom_logger

* fixes for _should_check_cold_storage_for_full_payload

* fix _download_object_from_s3

* test_s3_v2_with_cold_storage

* add cold_storage_object_key to StandardLoggingMetadata

* use get_proxy_server_request_from_cold_storage_with_object_key

* add cold_storage_object_key to SpendLogsMetadata

* add cold_storage_object_key

* get_proxy_server_request_from_cold_storage_with_object_key

* use get_proxy_server_request_from_cold_storage_with_object_key

* test responses API

* add get_proxy_server_request_from_cold_storage_with_object_key

* session handler fixes

* test session handler

* fix ruff checks

* _download_object_from_s3

* cleanup

* test

* lint fix

* test_e2e_cold_storage_successful_retrieval

* test_e2e_generate_cold_storage_object_key_successful

* test_async_gcs_pub_sub_v1

* test fix

* test fix

* test fix

* test_standard_logging_metadata_has_cold_storage_object_key_field

* test_sanitize_request_body_for_spend_logs_payload_basic

* test_transform_input_image_item_to_image_item_with_image_data
2025-08-07 10:59:53 -07:00
Yikai Zhao 4fdeff8e1a Fix token_counter with special token input 2025-08-07 22:58:07 +08:00
Ishaan JaffandGitHub 0ccc493455 [Bug]: Fix Mimetype Resolution Error in Bedrock Document Understanding (#13309)
* fix _validate_format for BedrockImageProcessor

* add test

* fix _validate_format for bedrock

* _get_document_format

* test_bedrock_get_document_format_fallback_mimes

* fix: add fallback method for mime type detection
2025-08-05 17:07:10 -07:00
Krish DholakiaandGitHub 416da066eb fix(main.py): handle tool being a pydantic object (#13274)
* fix(main.py): handle tool being a pydantic object

Fixes https://github.com/BerriAI/litellm/issues/13064

* fix(prompt_templates/common_utils.py): fix unpack defs deepcopy issue

Fixes https://github.com/BerriAI/litellm/issues/13151

* fix(utils.py): handle tools is none
2025-08-04 23:44:02 -07:00
Krrish Dholakia fe24c270de Prompt Management - add local dotprompt file support 2025-07-31 22:28:29 -07:00
Krish DholakiaandGitHub 78997c2e35 Anthropic - working mid-stream fallbacks (#13149)
* fix(router.py): add acompletion_streaming_iterator inside router

allows router to catch errors mid-stream for fallbacks

Work for https://github.com/BerriAI/litellm/issues/6532

* fix(router.py): working mid-stream fallbacks

* fix(router.py): more iterations

* fix(router.py): working mid-stream fallbacks with fallbacks set on router

* fix(router.py): pass prior content back in new request as assistant prefix message

* fix(router.py): add a system prompt to help guide non-prefix supporting models to use the continued text correctly

* fix(common_utils.py): support converting `prefix: true` for non-prefix supporting models

* fix: reduce LOC in function

* test(test_router.py): add unit tests for new function

* test: add basic unit test

* fix(router.py): ensure return type of fallback stream is compatible with CustomStreamWrapper

prevent client code from breaking

* fix: cleanup

* test: update test

* fix: fix linting error
2025-07-31 21:22:49 -07:00
Amit KumarandGitHub b6f15ed64d Fix token counter to ignore unsupported keys like prefix (#11791) (#11954) 2025-07-29 16:04:09 -07:00
Ishaan JaffandGitHub 078096247b [Bug Fix] The model gemini-2.5-flash with the merge_reasoning_content_in_choices parameter does not work (#13066)
* _optional_combine_thinking_block_in_choices

* test_optional_combine_thinking_block_with_none_content
2025-07-28 17:42:28 -07:00
Ishaan JaffandGitHub b41ce5c92f [Feat] - Track cost + add tags for health checks done by LiteLLM Proxy (#12880)
* refactor to use add_user_api_key_auth_to_request_metadata

* add get_litellm_internal_health_check_user_api_key_auth

* add get_litellm_internal_health_check_user_api_key_auth

* add _update_model_params_with_health_check_tracking_information

* add HealthCheckHelpers

* refactor to use clean helpers

* test_update_model_params_with_health_check_tracking_information

* test_get_litellm_internal_health_check_user_api_key_auth

* test_add_user_api_key_auth_to_request_metadata

* fix _update_model_params_with_health_check_tracking_information
2025-07-22 18:45:57 -07:00
Krish DholakiaandGitHub ab09d0621d Litellm gemini grounding metadata stream (#12673)
* fix(prompt_templates/factory.py): handle anthropic cache control on individual tool results

Fixes issue where cache control on individual tool result was being ignored

* test(test_vertex_And_google_ai_studio_gemini.py): initial unit test covering translation for grounding metadata on streaming chunk

* fix(vertex_and_google_ai_studio.py): ensure grounding metadata is preserved on streaming

Closes https://github.com/BerriAI/litellm/issues/10237

* fix(core_helpers.py): include usage in expected openai keys
2025-07-19 11:52:12 -07:00
Cole McIntoshandGitHub d4f5180212 fix(lowest_latency.py): Handle ZeroDivisionError with zero completion tokens (#12734)
* fix(lowest_latency.py): Handle ZeroDivisionError with zero completion tokens (#12641)

Fixes ZeroDivisionError when LLM responses have zero completion tokens, which can
occur with Gemini models on very long contexts that only use tool calls.

Changes:
- Add check for completion_tokens > 0 before division in log_success_event
- Handle both timedelta and float types for response times (supporting both time.time() and datetime)
- Apply fix to both occurrences of the division operation in the file
- Add comprehensive tests for zero completion token scenarios

This ensures the lowest latency routing continues to work properly even when
models return responses with no completion tokens.

* test: Move lowest_latency zero tokens test to test_litellm for CI execution

* refactor: Use safe_divide helper to eliminate code duplication

- Added safe_divide utility function to litellm_core_utils.core_helpers
- Handles both timedelta and float types for numerator
- Prevents ZeroDivisionError and negative denominator issues
- Replaced duplicated division logic in lowest_latency.py
- Added comprehensive unit tests for safe_divide function

This improves code quality by reducing duplication and centralizing the
division safety logic in a reusable helper function.

* refactor: Rename to safe_divide_seconds for clarity

- Renamed safe_divide to safe_divide_seconds to better indicate it handles time durations
- Simplified implementation with single-line ternary for seconds conversion
- Updated all references and tests accordingly

The function name now clearly indicates it's specifically for dividing
time durations (in seconds) by a denominator.

* refactor: Simplify safe_divide_seconds to only accept float arguments

- Changed safe_divide_seconds to accept only float parameters for consistency
- Callers now handle timedelta to seconds conversion explicitly
- Removed timedelta-specific test cases

* fix: Remove unused timedelta import

* fix: Remove Union[timedelta, float] type annotations

Since safe_divide_seconds now only accepts floats, we handle the
timedelta conversion explicitly in the code. The type annotations
are no longer needed and can be simplified.

* Revert "fix: Remove Union[timedelta, float] type annotations"

This reverts commit 19c6c62154fceb9c431fea3e448753495dec35d2.

* fix: Clean up implementation

- Remove unnecessary type annotations
- Use safe_divide_seconds utility for zero-division protection
- Handle both timedelta and float types explicitly
- Maintain compatibility with both datetime and time.time() usage
2025-07-18 15:19:47 -07:00
Krrish Dholakia 5a8762b6a1 test: update tests 2025-07-16 08:56:41 -07:00
Krrish Dholakia 85fe1d35e1 test: update test, remove old gemini models 2025-07-15 22:31:49 -07:00
Krish DholakiaandGitHub dcc8f04ca0 Remove stream options from streaming + fix guardrail start time on log duration (#12346)
* fix(streaming_handler.py): don't return stream options in clientside response

* test: add unit test

* fix(custom_guardrail.py): fix start time

don't start until function actually called

leading to incorrect high latency numbers

* fix(custom_guardrail.py): fix start time
2025-07-05 15:54:47 -07:00
Krish DholakiaandGitHub e7f1fa26ab UI - Azure Content Guardrails (#12341)
* build(model_prices_and_context_window.json): remove 'supports_tool_choice' for specific mistral models

Closes https://github.com/BerriAI/litellm/issues/11750

* feat: initial commit adding cleaner ui for azure text moderation guardrails

* feat(guardrail_endpoints.py): add discoverable guardrail configs and improve converting base model to dict with types

* fix(guardrail_provider_fields.tsx): render from api endpoint correctly

* fix(guardrail_provider_fields.tsx): cleanup

* refactor(guardrail_endpoints.py): refactor to handle dictionaries with literal - allows multiselect

* feat(ui/): render dictionary with known keys correctly

* feat(ui/): render optional params on separate page

* style(ui/): style improvements to rendering optional params on the UI

* feat(azure/prompt_shield.py): add azure prompt shield back on UI

* fix(add_guardrail_form.tsx): fix form to handle updated api

* fix(guardrail_optional_params.tsx): ensure values are nested correctly for writing to api

* fix: fix linting error

* feat(text_moderation.py): handle str to int conversion

* fix(guardrail_info.tsx): only render pii settings if guardrail is presidio

* fix(guardrail_info.tsx): add guardrail specific fields to update settings

allows updating guardrail fields (e.g. severity threshold) post-create

* fix(guardrail_endpoints.py): set guardrail_id in guardrail object

ensures duplicate objects not created on guardrail update

* fix(guardrail_endpoints.py): allow provider specific fields to be updated on patch update

* refactor(guardrail_endpoints.py): remove duplicate info endpoint

* fix(guardrail_endpoints.py): mask sensitive keys on returning via guardrail `/info`

Prevent leaking keys

* fix(guardrail_optional_params.tsx): return numerical input when numerical component used

fixes issue where output was a str

* fix(guardrail_optional_params.tsx): render dict keys correctly

* fix(text_moderation.py): fix severity by category check

* fix(proxy/utils.py): check if guardrail should run for post call streaming hook

Prevents invalid guardrails from running if not requested

* test: fix import

* fix: fix linting error

* test: update test

* fix: fix tests

* fix: fix code qa errors

* fix(guardrail_endpoints.py): set max depth for function

* test: update recursive_detector.py

* test: update list

* build: merge main

* fix: fix ruff check errors
2025-07-05 10:19:29 -07:00
c3e673b627 [Feat] Add github co-pilot as a new LLM API provider (#12325)
* Litellm dev 03 05 2025 contributor prs (#9079)

* feat: add support for copilot provider

* test: add tests for github copilot

* chore: clean up github copilot authenticator

* test: add test for github copilot authenticator

* test: add test for github copilot for sonnet 3.7 thought model

* Fix #7629 - Add tzdata package to Dockerfile (#8915)

* Add tzdata package to Dockerfile

* Move tzdata to python requirement.txt

* feat: add support for copilot provider (#8577)

* feat: add support for copilot provider

* test: add tests for github copilot

* chore: clean up github copilot authenticator

* test: add test for github copilot authenticator

* test: add test for github copilot for sonnet 3.7 thought model

---------

Co-authored-by: Krish Dholakia <krrishdholakia@gmail.com>

* feat: add model information for copilot models

* fix: fix linting errors

* test: remove integration test for github_copilot + fix misisng mock

* fix: use print to make sure the logger message shown

* test: remove debug print

* fix lint (#11112)

* Add init files to make test directories Python packages and update import paths in test_token_counter.py (#11119)

* Update litellm/model_prices_and_context_window_backup.json

Co-authored-by: மனோஜ்குமார் பழனிச்சாமி <smartmanoj42857@gmail.com>

---------

Co-authored-by: Son H. Nguyen <nhs.000.dev@gmail.com>
Co-authored-by: subnet.dev <50828879+subnet-dev@users.noreply.github.com>
Co-authored-by: Son H. Nguyen <33925625+nhs000@users.noreply.github.com>
Co-authored-by: மனோஜ்குமார் பழனிச்சாமி <smartmanoj42857@gmail.com>
Co-authored-by: Ishaan Jaff <ishaanjaffer0324@gmail.com>

* refactor github copilot

* test_github_copilot_transformation.py

* test_github_copilot_authenticator.py

* add GitHub Copilot

* fix order

* doc fix

---------

Co-authored-by: Krish Dholakia <krrishdholakia@gmail.com>
Co-authored-by: Son H. Nguyen <nhs.000.dev@gmail.com>
Co-authored-by: subnet.dev <50828879+subnet-dev@users.noreply.github.com>
Co-authored-by: Son H. Nguyen <33925625+nhs000@users.noreply.github.com>
Co-authored-by: மனோஜ்குமார் பழனிச்சாமி <smartmanoj42857@gmail.com>
2025-07-04 13:12:16 -07:00