Commit Graph

753 Commits

Author SHA1 Message Date
John Greek 26a2c90818 [Fix] Anthropic models on Azure AI cache pricing (#19532) (#19614) 2026-01-22 20:00:40 -08:00
Sameer Kankute 842e5b3ad6 Merge pull request #19560 from BerriAI/litellm_bedrock_invoke_structured_output
[Feat] Add support for output formatfor bedrock invoke via v1/messages
2026-01-22 19:44:48 +05:30
Sameer Kankute c78c878822 Merge pull request #19558 from BerriAI/litellm_gemini_vertexai_mapping
Add custom vertex ai mapping to the output
2026-01-22 19:44:32 +05:30
Sameer Kankute 73715ab417 Merge pull request #19556 from BerriAI/litellm_fix_gemini_batch_jan22
Fix: generation config empty for batch
2026-01-22 19:44:26 +05:30
Sameer Kankute f312bf23d0 Fix:test_multiple_function_call 2026-01-22 19:34:54 +05:30
Sameer Kankute ad1edd38d5 Merge branch 'main' into litellm_staging_01_21_2026 2026-01-22 17:56:40 +05:30
Sameer Kankute 24faca9bcf Add support for output formatfor bedrock invoke via v1/messages 2026-01-22 16:36:03 +05:30
Sameer Kankute 18240662db Add custom vertex ai mapping to the output 2026-01-22 15:18:24 +05:30
jay prajapati 363b0cc132 fix(azure): preserve content_policy_violation details for images (#19328) (#19372)
Azure OpenAI Images (DALL·E 3) returns policy violations as a structured payload under body["error"], including inner_error.content_filter_results and revised_prompt.

LiteLLM previously:
- Failed to extract nested error messages (get_error_message only handled body["message"])
- Missed policy violation detection when error strings were generic
- Dropped inner_error details when raising ContentPolicyViolationError

This change:
- Extracts nested Azure error fields (code/type/message + inner_error)
- Detects policy violations via structured error codes
- Passes an OpenAI-style error body + provider_specific_fields to preserve details

Tests:
- python3 -m pytest tests/test_litellm/llms/azure/test_azure_exception_mapping.py
- python3 -m pytest tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py

Fixes #19328
2026-01-21 20:06:51 -08:00
John Greek aa4b0e0149 Fix duplicate test_handler.py filenames causing pytest collection errors (#19385) 2026-01-21 08:47:50 -08:00
Sameer Kankute b6691baf24 Merge pull request #19482 from BerriAI/litellm_anthropic_max_length
Filter out unsupported fields from JSON schema for Anthropic's output_format API.
2026-01-21 18:57:16 +05:30
Sameer Kankute a1aba2ed8d Merge pull request #19491 from BerriAI/main
merge main 20 1 25
2026-01-21 16:40:48 +05:30
Sameer Kankute c571a02f3b Filter out unsupported fields from JSON schema for Anthropic's output_format API. 2026-01-21 15:48:22 +05:30
Ryne Carbone 15013cec4b feat(gemini): add file content support in tool results (#19416)
Add support for 'file' and 'input_file' content types in
convert_to_gemini_tool_call_result(). File content in tool
results was previously silently dropped.

Supports base64 data URIs and HTTP URLs, matching the existing
image handling pattern. Enables PDF, audio, video, and other
file types as inline_data for Gemini.
2026-01-20 19:54:12 -08:00
Cesar Garcia b4ed387d24 fix(vertex_ai): handle reasoning_effort as dict from OpenAI Agents SDK (#19419)
The OpenAI Agents SDK (v0.6.9+) now passes reasoning_effort as a dict
when summary is specified: {"effort": "high", "summary": "auto"}

This change extracts the "effort" value from the dict for Vertex AI,
which only supports thinkingLevel (not summary).

Before: reasoning_effort={"effort": "high"} was silently ignored
After: reasoning_effort={"effort": "high"} correctly maps to thinkingLevel

Fixes #19411
2026-01-20 19:31:25 -08:00
Ishaan Jaff ddebdd47bc [Feat] Add Support for Claude Code Max/OAuth 2 on LiteLLM AI Gateway (#19453)
* fix count_tokens_with_anthropic_api

* remove outdated file

* fix ANTHROPIC_TOKEN_COUNTING_BETA_VERSION

* refactor: get_token_counter

* init test suite for token counter

* init token counters

* fix: fix pyrightI

* fix Code QA issues

* feat: add OAUTH handling ant

* feat: Oauth handling Ant

* test anthopic common utils

* fix code QA

* docs
2026-01-20 17:21:17 -08:00
Kris Xia 56bf6001e9 Supports setting media_resolution and fps parameters on each video file, when using Gemini video understanding. (#19273)
* feat: add gemini video metadata and detail support

Implement support for video_metadata and enhanced detail parameter
for Gemini 3.0+ models:

- Add video_metadata field to ChatCompletionFileObjectFile type
  - Supports fps, start_offset, and end_offset parameters
  - Properly converts snake_case to camelCase for Gemini API
- Extend detail parameter to support medium and ultra_high levels
  - Maps to MEDIA_RESOLUTION_MEDIUM and MEDIA_RESOLUTION_ULTRA_HIGH
- Update _process_gemini_image to handle video metadata transformation
- Add version gating to only apply features for Gemini 3+ models
- Add comprehensive test coverage (6 new test cases)
  - Test detail parameter with file objects
  - Test video_metadata fields (fps, start_offset, end_offset)
  - Test combined detail + video_metadata usage
  - Test new detail levels (medium, ultra_high)
  - Test version gating (Gemini 1.5 vs 3.0)

Note: video_metadata is only supported for video files but error
handling is delegated to Vertex AI for other media types.

* refactor: rename _process_gemini_image to _process_gemini_media

The function handles multiple media types (images, audio, video, PDF),
not just images. Renamed to better reflect its actual purpose.

- Update function name in transformation.py
- Update all function calls and references
- Update test names and imports to match
- Improve docstring to clarify it handles all media types

* docs: add video metadata and media resolution control documentation

Add comprehensive documentation for Gemini 3+ video processing features:
- Document media resolution control (detail parameter) for images and videos
- Add video_metadata field documentation (fps, start_offset, end_offset)
- Include usage examples with tabs for basic, combined, and proxy scenarios
- Update both Gemini and Vertex AI provider documentation
- Clarify snake_case to camelCase field conversion for Gemini API

Signed-off-by: Kris Xia <xiajiayi0506@gmail.com>

* refactor(gemini): extract metadata application into helper function

Extract duplicated Gemini 3+ media_resolution and video_metadata
application logic from _process_gemini_media into a dedicated
_apply_gemini_3_metadata helper function to improve code maintainability.

---------

Signed-off-by: Kris Xia <xiajiayi0506@gmail.com>
2026-01-20 11:36:55 -08:00
Sameer Kankute 9e1275b76c Merge branch 'main' into litellm_staging_01_19_2026 2026-01-20 19:19:36 +05:30
Sameer Kankute 2153db5e64 fix: test_convert_to_bedrock_format_post_call_streaming_hook 2026-01-20 18:27:36 +05:30
Sameer Kankute f0785d5a51 Fix:test_supported_params_limited_to_docs 2026-01-20 17:26:40 +05:30
Sameer Kankute deb9142117 Merge pull request #19400 from BerriAI/main
merge main iin 19/1 staging
2026-01-20 16:45:01 +05:30
Sameer Kankute 2ae308028d Merge pull request #18787 from aproorg/fix/bedrock-thinking-tool-call-2
fix(bedrock): handle thinking with tool calls for Claude 4 models
2026-01-20 09:43:07 +05:30
Ryan Malloy 58c8c2b7b1 fix: HTTP client memory leaks in Presidio, OpenAI, and Gemini (#19190)
* fix: prevent HTTP client memory leaks in Presidio and OpenAI wrappers

Fixes multiple memory leak issues reported in #14540 and related tickets:

**Presidio Guardrail Fix (#14540)**
- Problem: Every guardrail check created a new aiohttp.ClientSession
- Impact: High-traffic proxies accumulated thousands of unclosed sessions
- Solution: Share a single session across all guardrail checks
  - Added `self._http_session` instance variable
  - Lazy session creation via `_get_http_session()`
  - Proper cleanup via `_close_http_session()` and `__del__()`
- Files: litellm/proxy/guardrails/guardrail_hooks/presidio.py

**OpenAI HTTP Client Caching (#14540)**
- Problem: `_get_async_http_client()` created new httpx.AsyncClient on each call
- Impact: OpenAI/Azure completions bypassed client caching system
- Solution: Route through `get_async_httpx_client()` for TTL-based caching
  - Caches clients by provider and SSL config
  - Fallback to direct creation if caching fails
  - Applied to both async and sync client methods
- Files: litellm/llms/openai/common_utils.py

**Test Script**
- Added validation script to demonstrate fixes
- Counts file descriptors and unclosed session objects
- Files: test_oom_fixes.py

Related issues: #14384, #13251, #12443

* fix(oom): prevent memory leaks in Presidio guardrails and OpenAI client creation

Fixes two high-impact memory leaks:

1. Presidio Guardrail Session Leak (issue #14540)
   - Problem: Created new aiohttp.ClientSession on every guardrail check
   - Impact: Runs on EVERY proxy request when PII masking enabled
   - Fix: Shared session pattern with lifecycle management
   - Files: litellm/proxy/guardrails/guardrail_hooks/presidio.py

2. OpenAI HTTP Client Cache Bypass (issue #14540)
   - Problem: _get_async_http_client() created new httpx.AsyncClient, bypassing TTL cache
   - Impact: Every completion created new client with own connection pool
   - Fix: Route through get_async_httpx_client() for proper caching
   - Critical: Include SSL config in cache key for correctness
   - Files: litellm/llms/openai/common_utils.py

Validation:
- Presidio: 100 requests → 0 new sessions (was 100)
- OpenAI: 100 calls → 1 unique client (was 100)
- test_oom_fixes.py: Automated validation script

* fix(oom): resolve Gemini aiohttp session leak (issue #12443)

Fixes persistent "Unclosed client session" warnings when using Gemini models.

Root Causes:
1. Broken atexit cleanup - get_event_loop() fails at exit time
2. On-demand session creation without reliable cleanup

Changes:

1. Fixed atexit Cleanup (async_client_cleanup.py)
   - OLD: Used get_event_loop() which fails when loop is closed
   - NEW: Always create fresh event loop at exit time
   - Ensures cleanup runs successfully even when main loop is closed

2. Added __del__ Cleanup (aiohttp_handler.py)
   - Defense-in-depth: cleanup on garbage collection
   - Handles abnormal termination cases
   - Similar pattern to Presidio guardrail fix

3. Enhanced Cleanup Scope (async_client_cleanup.py)
   - Now closes global base_llm_aiohttp_handler instance
   - Previously only checked cache, missed module-level handler

Validation:
- Test 1: __del__ cleanup → 0 sessions leaked ✓
- Test 2: atexit cleanup → 0 sessions leaked ✓
- test_gemini_session_leak.py: Automated validation

Related: #14540 (broader OOM issue tracking)

* fix(types): use LlmProviders enum for get_async_httpx_client

MyPy was failing because llm_provider parameter expects Union[LlmProviders, httpxSpecialProvider], not a string.

Changed from string "openai" to LlmProviders.OPENAI enum value.

* test: move validation tests to proper CI directories

- Move test_oom_fixes.py to tests/test_litellm/llms/
- Move test_gemini_session_leak.py to tests/test_litellm/llms/custom_httpx/
- Fix pytest warning: use pytest.skip() instead of return True

This ensures CI actually runs our OOM fix validation tests.

* fix(oom): add asyncio.Lock to prevent race conditions in Presidio session creation

- Make _get_http_session() async with asyncio.Lock protection
- Prevents multiple concurrent requests from creating orphaned sessions
- Add concurrent load test (50 parallel requests) to validate fix
- Test confirms only 1 session created under concurrent load

Critical fix: Previous implementation had race condition where
concurrent guardrail checks could create multiple sessions,
defeating the shared session pattern and causing memory leaks.

* fix(presidio): eliminate race condition in session lock initialization

Move asyncio.Lock creation from lazy initialization in _get_http_session()
to __init__. The previous lazy init had a race condition where concurrent
coroutines could both see _session_lock as None, both create locks, and
end up with different lock instances - defeating the synchronization.

asyncio.Lock() can be safely created without an event loop; it only
requires one when awaited.
2026-01-19 19:02:55 -08:00
南辰燏炚 004bde2c45 feat (volcengine) : Support Volcengine responses api (#18508)
* Add Volcengine responses adapter

* fix llms/volcengine/responses/transformation.py:507:9: F841 Local variable `origin` is assigned to but never used

fix llms/volcengine/responses/transformation.py:95: error: Argument "headers" to "VolcEngineError" has incompatible type

add more supported optional params

removed redundant manual logging/utils fallbacks so litellm/__init__.py uses the registry only.
2026-01-19 19:02:29 -08:00
Cesar Garcia d30c25af21 feat(gemini): use responseJsonSchema for Gemini 2.0+ models (#19314)
* feat(gemini): add opt-in support for responseJsonSchema

Add support for Gemini's native responseJsonSchema parameter which uses
standard JSON Schema format instead of OpenAPI-style responseSchema.

Benefits of responseJsonSchema (Gemini 2.0+ only):
- Standard JSON Schema format (lowercase types)
- Supports additionalProperties for stricter validation
- Better compatibility with Pydantic's model_json_schema()
- No propertyOrdering required

Usage:
```python
response_format={
    "type": "json_schema",
    "json_schema": {"schema": {...}},
    "use_json_schema": True  # opt-in
}
```

This is backwards compatible - existing code continues to use
responseSchema by default.

Closes #16340

* docs: add documentation for use_json_schema parameter

Document the new use_json_schema option for Gemini 2.0+ models
in the JSON Mode documentation.

* refactor(gemini): use responseJsonSchema by default for Gemini 2.0+

Remove opt-in flag `use_json_schema` and automatically detect model version:
- Gemini 2.0+: uses responseJsonSchema (standard JSON Schema, supports additionalProperties)
- Gemini 1.5: uses responseSchema (OpenAPI format, legacy)

This follows LiteLLM's philosophy of abstracting provider differences -
users write the same code regardless of model version.

* test(vertex): update json_schema tests to accept both responseSchema formats

Gemini 2.x+ uses responseJsonSchema while Gemini 1.x uses responseSchema.
Update tests to accept both formats since litellm now auto-selects based
on model version.
2026-01-19 10:45:37 -08:00
Cesar Garcia 57b1d99b44 feat(azure): add support for Azure OpenAI v1 API (#19313)
* feat(azure): add support for Azure OpenAI v1 API

When api_version is 'v1', 'latest', or 'preview', use the standard
OpenAI client instead of AzureOpenAI client with base_url pointing
to /openai/v1/ endpoint.

This follows Microsoft's documentation for the new v1 API format:
https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#api-specs

Changes:
- Add OpenAI/AsyncOpenAI imports to common_utils.py and azure.py
- Modify get_azure_openai_client() to detect v1 API versions and
  create appropriate client type
- Update isinstance checks and type hints to accept both client types
- Add unit tests for v1 API client creation

* fix(azure): fix MyPy type errors for v1 API support

- Add type: ignore for AsyncOpenAI constructor
- Update type hints in files/handler.py and batches/handler.py
- Add OpenAI/AsyncOpenAI to Union types for client parameters
- Update isinstance checks to include OpenAI/AsyncOpenAI

* fix(azure): update type hints in files and batches handlers for v1 API

Update async method signatures to accept Union[AsyncAzureOpenAI, AsyncOpenAI]
to fix mypy errors when using v1 API client.
2026-01-19 10:44:38 -08:00
Cesar Garcia 4ad5de10cb fix(realtime): disable SSL for ws:// WebSocket connections (#19345)
When using http:// api_base (converted to ws://), the websockets library
throws "ssl argument is incompatible with a ws:// URI". Only pass SSL
context for secure wss:// connections.

Co-authored-by: Krish Dholakia <krrishdholakia@gmail.com>
2026-01-19 10:37:41 -08:00
Benedikt Óskarsson 406cdbe321 Merge branch 'litellm_staging_01_19_2026' into fix/bedrock-thinking-tool-call-2 2026-01-19 15:18:47 +00:00
Manuel Schweigert 29adf34313 Add ChatGPT subscription support and responses bridge (#19030)
* Add ChatGPT subscription support and responses bridge

* Fix typing import for responses bridge

* Guard device code timestamp parsing

* add /v1/messages endpoint to chatgpt model
2026-01-19 05:37:45 -08:00
Benedikt Óskarsson f09cae2107 Merge branch 'main' into fix/bedrock-thinking-tool-call-2 2026-01-19 13:08:17 +00:00
Sameer Kankute 480fa13b1d Merge pull request #19343 from BerriAI/litellm_anthropic_header_fix_19_jan
Fix: anthropic-beta is getting overriden and set to anthropic-beta
2026-01-19 18:24:46 +05:30
Sameer Kankute d7b103158a Fix: anthropic-beta is getting overriden and set to anthropic-beta': 'structured-outputs-2025-11-13', 2026-01-19 16:43:27 +05:30
Sameer Kankute 480cb9c0d8 Fix: upload pdfs for file endpoint 2026-01-19 11:58:32 +05:30
YutaSaito eec4ed640b Revert "Stabilise mock tests" 2026-01-17 06:26:18 +09:00
YutaSaito 66d67ae356 Revert "Add sanititzation for anthropic messages" 2026-01-17 06:01:12 +09:00
Anand Kamble 2c75194b49 fix(vertex_ai): Vertex AI 400 Error: Model used by GenerateContent request (models/gemini-3-*) and CachedContent (models/gemini-3-*) has to be the same (#19193)
* fix(vertex_ai): include model in context cache key generation

* test(vertex_ai): update context caching tests to verify model in cache key
2026-01-17 00:56:15 +05:30
Sameer Kankute fb3b4e6b33 Merge pull request #19196 from BerriAI/litellm_sanitise_anthropic_mesages
Add sanititzation for anthropic messages
2026-01-16 17:48:55 +05:30
Sameer Kankute 43893cb81a Merge pull request #19191 from BerriAI/litellm_fix_stream_timeout
Fix: [Bug]: stream_timeout:The function of this parameter has been changed
2026-01-16 17:43:43 +05:30
Sameer Kankute ca06bb4e3a Merge pull request #19201 from BerriAI/litellm_fix_vertex_ai_structured_output2
Fix: vertex ai doesn't support structured output
2026-01-16 17:09:03 +05:30
Sameer Kankute 101230e538 Merge pull request #19213 from BerriAI/main
merge main in sanitisation
2026-01-16 17:04:01 +05:30
Sameer Kankute f562186c75 Merge pull request #19212 from BerriAI/main
merge main in timeout PR
2026-01-16 17:02:22 +05:30
Sameer Kankute b0c6a1b308 Merge pull request #19203 from BerriAI/main
merge main
2026-01-16 15:16:29 +05:30
Sameer Kankute ac5a4df724 Fix: vertex ai doesn't support structured output 2026-01-16 14:54:31 +05:30
Sameer Kankute f1bde3c549 Add sanititzation for anthropic messages 2026-01-16 12:47:56 +05:30
Sameer Kankute c0e5637eae Fix: [Bug]: stream_timeout:The function of this parameter has been changed 2026-01-16 11:40:49 +05:30
Yuta Saito 1c38847b17 tests: skip Azure SDK init check for acreate_skill 2026-01-16 12:03:38 +09:00
Sameer Kankute 83e33944ef Fix: mock test tests 2026-01-15 22:02:42 +05:30
Sameer Kankute 4bdda9cc28 Fix: tests/test_litellm/proxy/test_proxy_server.py::test_embedding_input_array_of_tokens 2026-01-15 19:46:35 +05:30
Sameer Kankute f28d951202 Fix: tests/test_litellm/proxy/test_litellm_pre_call_utils.py::test_embedding_header_forwarding_with_model_group 2026-01-15 19:41:16 +05:30
Sameer Kankute 83cdfd886a Merge pull request #19059 from BerriAI/litellm_openrouter_image_gen
Add openrouter support for image/generation endpoints
2026-01-15 15:48:00 +05:30