Commit Graph

285 Commits

Author SHA1 Message Date
Sameer Kankute 3c0248edb9 Merge pull request #18663 from BerriAI/litellm_staging_01_05_2026
Staging 01/05/2026
2026-01-06 10:46:04 +05:30
YutaSaito ccdcb20048 Merge pull request #18279 from mangabits/fix-otel-provider
Use already configured opentelemetry providers
2026-01-06 12:49:48 +09:00
Shivam Rawat 8c21fcb957 added the option of adding langsmith tenant id in the env (#18623) 2026-01-06 01:19:27 +05:30
Chetan Choudhary 687adc6024 Add log_format parameter to GenericAPILogger (#18587)
Adds log_format parameter supporting json_array (default), ndjson, and single formats. NDJSON format enables webhook integrations like Sumo Logic to parse individual log records at ingest time. Defaults to json_array for backward compatibility.
2026-01-02 23:28:30 +05:30
Yuta Saito 3ae38c2a6d fix: test_langfuse_logging_completion_with_bedrock_llm_response 2026-01-02 15:55:02 +09:00
mangabits 78693bb9d0 Use already configured opentelemetry providers
Users that instrument using opentelemetry-instrument can now setup exporters as per their environment.
2026-01-01 19:06:55 -08:00
Yuta Saito b343d15157 fix: prevent LiteLLM from closing external OTEL spans 2026-01-01 08:28:48 +09:00
Alexsander Hamir 5534038e93 Fix CI: Revert security scan changes and add GitGuardian ignore rules (#18358) 2025-12-22 17:03:53 -08:00
Yuta Saito 41bbb3a6a5 feat: datadog log trace linking 2025-12-22 06:53:44 +09:00
Yuta Saito 01aa082d16 fix: call datadog_handler 2025-12-22 05:33:39 +09:00
Ishaan Jaffer 6112160a16 Revert "[Fix] Security - Remove example API keys with high entropy (#18255)"
This reverts commit 24edbccf5c.
2025-12-20 20:48:11 +05:30
Alexsander Hamir 24edbccf5c [Fix] Security - Remove example API keys with high entropy (#18255) 2025-12-19 10:09:50 -08:00
Alexsander Hamir 2e7b554747 3[Fix] CI/CD - logging_testing (#18204)
* fix: enforce team member budget check in common_checks

- Add missing team member budget validation in common_checks() function
  - Checks team membership budget when team key is used
  - Raises BudgetExceededError when team member spend exceeds max_budget_in_team
  - Follows same pattern as other budget checks (team, user, end_user)
  - Uses cached get_team_membership() for performance

- Fix AttributeError in lowest_tpm_rpm.py
  - Add null check for model_info before accessing .get() method
  - Prevents 'NoneType' object has no attribute 'get' error

- Add unit tests for team member budget enforcement
  - Test budget exceeded scenario
  - Test within budget scenario
  - Test edge cases (no budget, no membership, personal keys)
  - Tests run without requiring proxy server

Fixes failing test: test_users_in_team_budget

* fix: mock get_async_httpx_client in test_langsmith_key_based_logging

- Mock get_async_httpx_client to return a mock AsyncHTTPHandler instance
- Fixes test failure where mock_post was never called
- LangsmithLogger creates its own httpx client instance via get_async_httpx_client,
  so we need to mock the factory function rather than the class method
- Use MagicMock for response.raise_for_status (sync method) instead of AsyncMock

* fix: resolve linting errors (PLR0915, F401)

- Remove unused imports (datetime, ServiceLoggerPayload) from arize_phoenix.py
- Extract health ping setup logic from RedisCache.__init__ to reduce statement count
- Extract team member budget check from common_checks to reduce statement count

* fix: resolve type errors in ChatCompletionToolCallChunk construction

- Cast type field to Literal['function'] to satisfy TypedDict requirements
- Ensure arguments field is explicitly str type to match TypedDict signature
- Fixes pyright errors for incompatible types in transformation.py
2025-12-18 10:52:24 -08:00
yuneng-jiang c2f79681b6 Fixing test 2 2025-12-16 13:44:53 -08:00
Alexsander Hamir fab1b81b7f fix: add agent_id field to GCS PubSub spend_logs_payload.json test expectation (#17938)
- Add agent_id: null to expected JSON to match actual payload structure
- Fixes test_async_gcs_pub_sub_v1 test failure
- agent_id is an optional field in SpendLogsPayload that is always included (as null when not provided)
2025-12-13 13:35:20 -08:00
Cesar Garcia d693596e87 feat(langfuse): Add support for custom masking function (#17826)
* feat(langfuse): Add support for custom masking function

Allow users to pass a custom masking function via metadata to selectively
redact sensitive data (credit cards, emails, PII) before sending to Langfuse.

Usage:
```python
def mask_pii(data):
    if isinstance(data, str):
        data = re.sub(r'\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b', '[CARD]', data)
    return data

litellm.completion(
    model="gpt-4",
    messages=[...],
    metadata={"langfuse_masking_function": mask_pii}
)
```

* fix(langfuse): Isolate masking function from other logging integrations

Extract langfuse_masking_function from metadata early in the flow and store
it in a dedicated key (_langfuse_masking_function) that only the Langfuse
logger knows to look for. This prevents the callable from leaking to other
logging integrations (Datadog, S3, etc.) which would serialize it as
"<function at 0x...>".

Changes:
- scrub_sensitive_keys_in_metadata() now extracts and stores the function
- Langfuse logger looks in the dedicated key first, falls back to metadata
- Added tests to verify isolation works correctly
2025-12-11 15:36:54 -08:00
Ishaan Jaffer 2b069a343b test_init_custom_logger_compatible_class_as_callback 2025-12-06 16:21:50 -08:00
rioiart 1ac2655b17 Fix/organization max budget not enforced (#17334)
* test: add failing tests for organization budget enforcement bug

Add comprehensive tests exposing that organization-level budgets are
retrieved but never enforced during request authentication. Tests verify:

1. Basic org budget exceeded scenario (team under budget, org over)
2. Multiple teams collectively exceeding org budget
3. Organization budget fields exist but are never checked
4. Inconsistency between team budget enforcement (works) and org (doesn't)

Tests intentionally fail to document the bug. Will be fixed in next commit.

Related to organization_max_budget not being enforced in auth_checks.py

* fix: enforce organization budget in auth checks

Add organization budget enforcement to common_checks() in auth_checks.py.
Previously, organization_max_budget was retrieved from DB but never checked,
allowing teams to collectively exceed their organization's budget limit.

Changes:
- Add _organization_max_budget_check() function following team budget pattern
- Call org budget check after team budget check in common_checks()
- Add "organization_budget" to budget_alerts type literals
- Update tests to verify org budget is enforced

Budget hierarchy is now properly enforced:
  Organization Budget (hard ceiling)
    └─ Team Budget (sub-allocation)
        └─ Team Member Budget (per-user within team)
            └─ Key Budget (per-key)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: add organization_id to budget alerts, fix enum comparison and linting of newly added code

- Add organization_id field to CallInfo class for better alert context
- Include organization_id in budget alerts (token, soft, team, org)
- Fix event_group enum comparison (was comparing enum to string)
- Add OrganizationBudgetAlert class for organization budget alerting
- Add organization_budget to test parameterizations
- Apply Black formatting to slack_alerting.py

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-02 22:46:03 -08:00
Ishaan Jaff 427074ac6e Fix: Datadog callback regression when ddtrace is installed (#17393)
* fix DD agent host logging

* docs fix

* test_datadog_agent_configuration

* test_datadog_ignores_ddtrace_agent_host
2025-12-02 17:27:50 -08:00
Krish Dholakia 1cb5fcddba make generic api OSS + support multiple generic API's (#17152)
* feat(generic_api_callback.py): make generic api OSS + support multiple generic API's

Enables https://github.com/BerriAI/litellm/pull/17094#discussion_r2562832967

* feat(callback_utils.py): support custom generic api callbacks

* feat(generic_api_callback.py): support specifying which event types to run the generic api for

* fix(litellm_logging.py): log system prompt for anthropic messages

* feat(generic_api_callback.py): support generic api compatible api's - e.g. rubrik agent cloud

* docs(sidebars.js): document new OSS generic api

* docs(generic_api.md): document new OSS Generic API

* docs(custom_webhook_api.md): document custom webhook api integration tutorial

* docs(custom_webhook_api.md): cleanup

* docs(custom_webhook_api.md): document what get's logged to custom webhook api

* Refactor: Pass callback config to GenericAPILogger

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

* Fix: Handle empty messages list in logging payload

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

* Checkpoint before follow-up message

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

* feat: Cache GenericAPILogger instances to improve performance

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2025-11-26 18:38:38 -08:00
yuneng-jiang 1a9b2d2206 Merge pull request #16560 from BerriAI/litellm_org_usage
[Feature] Organization Usage
2025-11-26 13:55:58 -08:00
Ishaan Jaffer 529c56423c test_opentelemetry_integration 2025-11-26 12:28:47 -08:00
yuneng-jiang 24f90679f8 Changes for CI/CD Tests 2025-11-22 10:21:52 -08:00
Ishaan Jaffer 0699430206 test logging tests + mcp server QA checks 2025-11-15 08:58:46 -08:00
Ishaan Jaffer 11cf22e7b8 add "provider_specific_fields": null 2025-11-14 18:49:35 -08:00
Ishaan Jaffer 65468353d1 provider_specific_fields 2025-11-14 18:17:50 -08:00
yuneng-jiang 898f15c33c Add Langfuse OTEL and SQS to health check (#16514) 2025-11-12 18:25:30 -08:00
Ishaan Jaff abde56391b [Fix] - Bedrock Knowledge Bases - add support for filtering kb queries (#16543)
* test_e2e_bedrock_knowledgebase_retrieval_with_llm_api_call_with_tools_and_filters

* fix vs registry

* fix merging params

* test_bedrock_kb_request_body_has_transformed_filters

* fix typing / linting
2025-11-12 12:38:50 -08:00
Andrew Maguire bd15250960 fix: Add atexit handlers to flush callbacks for async completions (#16487)
Fixes #16486

## Problem
Callbacks configured via litellm.success_callback (e.g., PostHog, LangSmith)
were not being invoked for litellm.acompletion() in short-lived scripts.
The callbacks worked correctly for synchronous completions but async
completions would queue callbacks that were lost when the script exited
before GLOBAL_LOGGING_WORKER could process them.

Root cause: asyncio.run() closes the event loop immediately after the
async function completes, preventing the background worker from processing
queued callbacks.

## Solution
Implemented a two-level atexit handler approach:

1. GLOBAL_LOGGING_WORKER atexit handler (logging_worker.py):
   - Processes remaining callbacks from queue before exit
   - Creates new event loop to run pending coroutines synchronously
   - Applies time and iteration limits to prevent blocking shutdown

2. Integration-specific atexit handlers (posthog.py as example):
   - Flushes internal queue to external service
   - Uses synchronous HTTP client for reliable delivery
   - Each integration needs its own handler due to varying sync APIs

## Changes
- litellm/litellm_core_utils/logging_worker.py:
  - Added _flush_on_exit() method
  - Registered atexit handler in __init__
  - Processes up to MAX_ITERATIONS_TO_CLEAR_QUEUE events
  - Time-limited to MAX_TIME_TO_CLEAR_QUEUE seconds

- litellm/integrations/posthog.py:
  - Added _flush_on_exit() method
  - Registered atexit handler in __init__
  - Groups events by credentials for batch sending
  - Uses sync_client for reliable HTTP delivery

- tests/logging_callback_tests/test_posthog.py:
  - Added test_async_callback_atexit_handler_exists()
  - Added test_posthog_atexit_flushes_internal_queue()
  - Added test_sync_callback_not_affected_by_atexit()

## Testing
- All existing tests pass
- Manual end-to-end testing confirms fix:
  - Async events now arrive in PostHog
  - Sync events continue working (no regression)
- Unit tests verify atexit handlers registered and functional

## Impact
- Fixes async callback delivery for ALL integrations using GLOBAL_LOGGING_WORKER
- No breaking changes - only adds missing functionality
- Sync path unchanged - no performance impact
2025-11-11 19:12:53 -08:00
Ishaan Jaff e94186629d [Fix] Bedrock Knowledge bases - ensure users can access search_results for both stream + non stream response to /chat/completions (#16459)
* fix message with provider_specific_fields

* test_provider_specific_fields_in_proxy_http_response

* test_provider_specific_fields_in_proxy_http_response
2025-11-11 08:19:57 -08:00
Ishaan Jaffer a4c008c433 test_datadog_message_redaction 2025-11-08 14:02:24 -08:00
Ishaan Jaffer 993c75d10b test_redaction_responses_api 2025-11-08 13:43:22 -08:00
Ishaan Jaffer c43fcf2ded test_redaction_responses_api 2025-11-08 13:39:40 -08:00
Ishaan Jaffer eef8c01d4e test_redaction_responses_api 2025-11-08 12:29:38 -08:00
Ishaan Jaff 2bd85dc455 [Feat] Add DD Agent Host support for datadog callback (#16379)
* add DD_AGENT_HOST

* docs DD Agent

* test_datadog_agent_configuration

* DD_AGENT_HOST
2025-11-07 15:18:23 -08:00
Ishaan Jaff c98b125851 [Feat] OTEL - Log Cost Breakdown on OTEL Logger (#16334)
* add gen_ai cost metrics

* TestOpenTelemetryCostBreakdown

* fix QA check

* validate_redacted_message_span_attributes
2025-11-06 13:53:53 -08:00
Ishaan Jaffer a964e7f24c test_stream_token_counting_anthropic_with_include_usage 2025-10-31 20:24:58 -07:00
Ishaan Jaffer 6be9b97d15 test_stream_token_counting_anthropic_with_include_usage 2025-10-31 19:15:07 -07:00
Sameer Kankute 8f2becd1c4 Fix: Redact reasoning summaries in ResponsesAPI output when message logging is disabled (#15965)
* redact reasoning content as well

* fix mypy error
2025-10-28 16:42:41 -07:00
Ishaan Jaff ab8a3a5d9e [Fix] SQS Logger - Add Base64 handling (#16028)
* Enable base64 stripping from sqs (#15927)

* Add sqs logger

* Add sqs logger

* Add sqs strp base64

* Add sqs strp base64

* Add sqs strp base64

* strip base64

* Add sqs strp base64

* strip base64

* Add sqs strp base64

* Add max depth recursion

* Add max depth recursion

---------

Co-authored-by: deepanshu <deepanshu.lulla@hq.bill.com>

* refactor _strip_base64_from_messages

* test fixes SQS logger

* fix SQS linting

---------

Co-authored-by: Deepanshu Lulla <deepanshu.lulla@gmail.com>
Co-authored-by: deepanshu <deepanshu.lulla@hq.bill.com>
2025-10-28 16:41:32 -07:00
Sameer Kankute 59df75276c Fix: Respect LiteLLM-Disable-Message-Redaction header for Responses API (#15966)
* fix overide for logging unredacted messages

* Use _get_metadata_variable_name_from_kwargs

* fix test related to redaction
2025-10-27 13:46:21 -07:00
Ishaan Jaff 17f6238d2b [Feat] OTEL - Ensure error information is logged on OTEL (#15978)
* fix _record_exception_on_span

* _record_exception_on_span

* test_record_exception_on_span

* fix linting errors
2025-10-27 13:45:21 -07:00
Katsuhiro Muto d8b44f4dbf Enable OpenTelemetry context propagation by external tracers (#15940)
* Fix: Enable OpenTelemetry context propagation with external tracers

* Add test for handling external tracers

* change priority to get tracer

---------

Co-authored-by: eycjur <eycjur@example.com>
2025-10-26 10:09:54 -07:00
Ishaan Jaffer 0bedf1c0a7 fix tests 2025-10-25 10:19:24 -07:00
Krish Dholakia 302f55c7db Bedrock + MCP - working MCP calls to bedrock via Responses API + Log hidden params for OTEL calls (#15677)
* fix: minor fixes to mcp streaming with bedrock

* fix(bedrock/): working bedrock with mcp tools

handle empty description

* test: add unit test

* test: test fixes

* fix(vector_store_registry.py): load vector store with litellm params from config.yaml

fixes minor issue where litellm params weren't being loaded in from config.yaml

* docs(knowledgebase.md): document azure vector store current limitation

* fix(opentelemetry.py): add hidden params to otel logs

Fixes LIT-1274

* fix: fix test
2025-10-18 10:39:28 -07:00
Ishaan Jaffer fa8c123f0d test fix 2025-10-17 18:07:04 -07:00
Ishaan Jaff 3852fc96c1 [Oct Staging Branch] (#15460)
* Implement fix for thinking_blocks and converse API calls

This fixes Claude's models via the Converse API, which should also fix
Claude Code.

* Add thinking literal

* Fix mypy issues

* Type fix for redacted thinking

* Add voyage model integration in sagemaker

* Add config file logic

* Use already exiting voyage transformation

* refactor code as per comments

* fix merge error

* refactor code as per comments

* refactor code as per comments

* UI new build

* [Fix] router - regression when adding/removing models  (#15451)

* fix(router): update model_name_to_deployment_indices on deployment removal

When a deployment is deleted, the model_name_to_deployment_indices map
was not being updated, causing stale index references. This could lead
to incorrect routing behavior when deployments with the same model_name
were dynamically removed.

Changes:
- Update _update_deployment_indices_after_removal to maintain
  model_name_to_deployment_indices mapping
- Remove deleted indices and decrement indices greater than removed index
- Clean up empty entries when no deployments remain for a model name
- Update test to verify proper index shifting and cleanup behavior

* fix(router): remove redundant index building during initialization

Remove duplicate index building operations that were causing unnecessary
work during router initialization:

1. Removed redundant `_build_model_id_to_deployment_index_map` call in
   __init__ - `set_model_list` already builds all indices from scratch

2. Removed redundant `_build_model_name_index` call at end of
   `set_model_list` - the index is already built incrementally via
   `_create_deployment` -> `_add_model_to_list_and_index_map`

Both indices (model_id_to_deployment_index_map and
model_name_to_deployment_indices) are properly maintained as lookup
indexes through existing helper methods. This change eliminates O(N)
duplicate work during initialization without any behavioral changes.

The indices continue to be correctly synchronized with model_list on
all operations (add/remove/upsert).

* fix(prometheus): Fix Prometheus metric collection in a multi-workers environment (#14929)

Co-authored-by: sotazhang <sotazhang@tencent.com>

* Add tiered pricing and cost calculation for xai

* Use generic cost calculator

* Resolve conflicts in generated HTML files

* Remove penalty params as supported params for gemini preview model (#15503)

* fix conversion of thinking block

* add application level encryption in SQS (#15512)

* docs: fix doc

* docs(index.md): bump rc

* [Fix] GEMINI - CLI -  add google_routes to llm_api_routes (#15500)

* fix: add google_routes to llm_api_routes

* test: test_virtual_key_llm_api_routes_allows_google_routes

* build: bump version

* bump: version 1.78.0 → 1.78.1

* add application level encryption in SQS

* add application level encryption in SQS

---------

Co-authored-by: Krrish Dholakia <krrishdholakia@gmail.com>
Co-authored-by: Ishaan Jaff <ishaanjaffer0324@gmail.com>
Co-authored-by: deepanshu <deepanshu.lulla@hq.bill.com>

* [Feat] Bedrock Knowledgebase - return search_response when using /chat/completions API with LiteLLM (#15509)

* docs: fix doc

* docs(index.md): bump rc

* [Fix] GEMINI - CLI -  add google_routes to llm_api_routes (#15500)

* fix: add google_routes to llm_api_routes

* test: test_virtual_key_llm_api_routes_allows_google_routes

* add AnthropicCitation

* fix async_post_call_success_deployment_hook

* fix add vector_store_custom_logger to global callbacks

* test_e2e_bedrock_knowledgebase_retrieval_with_llm_api_call

* async_post_call_success_deployment_hook

* add async_post_call_streaming_deployment_hook

* async def test_e2e_bedrock_knowledgebase_retrieval_with_llm_api_call_streaming(setup_vector_store_registry):

* fix _call_post_streaming_deployment_hook

* fix async_post_call_streaming_deployment_hook

* test update

* docs: Accessing Search Results

* docs KB

* fix chatUI

* fix searchResults

* fix onSearchResults

* fix kb

---------

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

* [Feat] Add dynamic rate limits on LiteLLM Gateway  (#15518)

* docs: fix doc

* docs(index.md): bump rc

* [Fix] GEMINI - CLI -  add google_routes to llm_api_routes (#15500)

* fix: add google_routes to llm_api_routes

* test: test_virtual_key_llm_api_routes_allows_google_routes

* build: bump version

* bump: version 1.78.0 → 1.78.1

* fix: KeyRequestBase

* fix rpm_limit_type

* fix dynamic rate limits

* fix use dynamic limits here

* fix _should_enforce_rate_limit

* fix _should_enforce_rate_limit

* fix counter

* test_dynamic_rate_limiting_v3

* use _create_rate_limit_descriptors

---------

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

* Add google rerank endpoint

* Add docs

* fix mypy error

* fix mypy and lint errors

* Add haiku 4.5 integration

* Add haiku 4.5 integration for other regions as well

* Handle citation field correctly

* Fix filtering headers for signature calcs

* Add haiku 4.5 integration (#15650)

---------

Co-authored-by: Leslie Cheng <leslie.cheng5@gmail.com>
Co-authored-by: Sameer Kankute <sameer@berri.ai>
Co-authored-by: Alexsander Hamir <alexsanderhamirgomesbaptista@gmail.com>
Co-authored-by: Lucas <10226902+LoadingZhang@users.noreply.github.com>
Co-authored-by: sotazhang <sotazhang@tencent.com>
Co-authored-by: Deepanshu Lulla <deepanshu.lulla@gmail.com>
Co-authored-by: Krrish Dholakia <krrishdholakia@gmail.com>
Co-authored-by: deepanshu <deepanshu.lulla@hq.bill.com>
2025-10-17 17:52:25 -07:00
Carlos Marchal dd560f792e feat: posthog per request api key 2025-10-09 18:32:11 +02:00
Ishaan Jaffer ee36c30217 fix LF tests 2025-10-04 10:39:17 -07:00
Ishaan Jaffer 1655a9aea8 fix lf tests 2025-10-04 10:02:56 -07:00