Commit Graph

33547 Commits

Author SHA1 Message Date
yuneng-jiang ec7dc44e73 Merge pull request #22049 from BerriAI/litellm_spend_log_key_info
[Fix] Enrich Failure Spend Logs With Key/Team Metadata
2026-02-24 20:56:51 -08:00
shin-bot-litellm b2c0bec5c5 fix(test): Update status enum values to match Google Interactions OpenAPI spec (#22061)
Google's Interactions API spec changed the status enum:
- Values are now lowercase (was uppercase)
- 'UNSPECIFIED' value was removed

Updated test to match the current spec from:
https://ai.google.dev/static/api/interactions.openapi.json
2026-02-24 20:26:11 -08:00
yuneng-jiang aa48a7ec00 Allow DB fallback for failure metadata enrichment lookups
Accurate logging is more important than avoiding the rare DB lookup
on the async failure path. Remove check_cache_only=True so lookups
fall back to DB when the key/team is not in cache.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 19:43:55 -08:00
yuneng-jiang 7a8b3daff5 address greptile review feedback (greploop iteration 2)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 19:22:45 -08:00
yuneng-jiang bf77a114cc address greptile review feedback (greploop iteration 1)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 19:10:01 -08:00
yuneng-jiang 8f118fbbce Merge pull request #22053 from atapia27/healthcheck-typo-fix
removed extra comma typo
2026-02-24 19:06:53 -08:00
Ishaan Jaff 60bcb26dc8 feat(agents): assign virtual keys to agents (#22045)
* feat(agents): assign virtual keys to agents

- Add agent_id field to LiteLLM_VerificationToken (schema.prisma + _types.py)
- Pass agent_id through key generation endpoint so keys can be scoped to an agent
- Refactor Add Agent wizard to 3-step flow (Configure → Assign Key → Ready)
  - Configure: all agent fields, custom/other type with just name+description
  - Assign Key: create new key or reassign existing key to agent
  - URL is now optional for easy discovery
- Add "Agent" ownership option to Create Key modal on Virtual Keys page
  with agent selector dropdown
- Extract CreatedKeyDisplay into shared component, reused in both flows
- Add keyCreateForAgentCall networking helper
- Add test for agent_id key generation

* fix(agents): code quality fixes from self-review

- Fix test_generate_key_helper_fn_agent_id: remove bare except clause,
  use explicit assert mock_insert.called, use .kwargs for clean arg access
- Remove no-op conditional in handleNext (both branches were identical)
- Validate selectedExistingKey before calling keyUpdateCall
- Validate selectedAgentId before setting on formValues in create_key_button

* fix(ui): replace deprecated Tremor Button with Ant Design Button in CreatedKeyDisplay
2026-02-24 18:28:16 -08:00
Ishaan Jaff 4e84e4c607 fix(ui): show real tool names in logs for Anthropic format tools (#22048) 2026-02-24 18:16:04 -08:00
Alejandro Tapia b1423bc8bf removed extra comma typo 2026-02-24 17:37:00 -08:00
yuneng-jiang 3f1554c099 Merge pull request #21071 from atapia27/feat/healthcheck-model_id-fix
healthcheck-model_id-fix
2026-02-24 17:15:07 -08:00
yuneng-jiang f4e23c97fd [Fix] Enrich failure spend logs with key/team metadata
Failure spend logs were missing key metadata (key alias, user ID, team ID,
team alias) in two scenarios:

1. Auth errors (401 ProxyException): auth_exception_handler creates a
   minimal UserAPIKeyAuth with only api_key and request_route set — all
   other fields are null. The failure hook now looks up the full key object
   from cache/DB using the key hash to populate the missing fields.

2. Post-auth failures (provider errors, rate limits): key fields are
   present but team_alias is always null because LiteLLM_VerificationTokenView
   SQL view does not include team_alias. The failure hook now looks up the
   team object from cache to populate team_alias.

Both lookups are non-fatal and wrapped in try/except.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-24 17:14:37 -08:00
Alejandro Tapia 80c09295ad Merge upstream/main - resolve health check conflicts 2026-02-24 17:09:05 -08:00
yuneng-jiang 9837a1bd2a Merge pull request #22047 from BerriAI/litellm_key_info_page_email
[Feature] UI - Virtual Keys: Add KeyInfoHeader component
2026-02-24 17:04:17 -08:00
ryan-crabbe fa87291bd9 Merge pull request #20397 from ryan-crabbe/fix/openai-prompt-cache-params
fix: add prompt_cache_key and prompt_cache_retention support for OpenAI
2026-02-24 16:51:10 -08:00
yuneng-jiang 50ba6986ef [Feature] UI - Virtual Keys: Add KeyInfoHeader component with metadata display
Add a reusable KeyInfoHeader component to replace the inline header in KeyInfoView.
Extract LabeledField as a common component for labeled metadata display with copyable
support, default_user_id handling, and empty value placeholders.

- Migrate all icons from lucide-react/heroicons to @ant-design/icons
- Use antd native copyable with descriptive tooltips (Copy Key Alias, Copy Key ID, etc.)
- Show DefaultProxyAdminTag for default_user_id values
- Add canModifyKey, regenerateDisabled, regenerateTooltip props for permission gating
- Add tests for KeyInfoHeader (19 tests) and LabeledField (8 tests)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-02-24 16:46:26 -08:00
Ryan Crabbe adafac1117 fix: add prompt_cache_key and prompt_cache_retention support for OpenAI
These params were silently dropped for Chat Completions because they
were missing from the supported params whitelist. Also adds
prompt_cache_retention to the Responses API TypedDict and fixes
misleading cache_control comments in OpenAI prompt caching docs.
2026-02-24 16:42:54 -08:00
Ishaan Jaff 360643e213 [Feat] UI - Allow using AI to understand Usage patterns (#22042)
* Add Ask AI chat component to Usage page

- Create UsageAIChatModal component with streaming chat interface
- Integrate with existing model hub for model selection
- Pass usage data context (spend, models, providers, keys) to AI
- Add Ask AI button next to Export Data button in global view
- Add tests for the new component and integration

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Convert Ask AI from modal to right-side sliding panel

- Replace UsageAIChatModal with UsageAIChatPanel
- Panel slides in from right side, usage page stays visible
- Full-height panel with header, model selector, chat area, and input
- Smooth CSS transition for open/close animation
- Update tests for new panel component (34 tests passing)

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Remove build output directory from tracking

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Add backend AI usage chat endpoint with tool calling

Backend:
- New /usage/ai/chat SSE streaming endpoint
- AI agent has get_usage_data tool that queries /user/daily/activity/aggregated
- Follows same architecture as policy AI suggest (litellm.acompletion + tools)
- Non-admin users are restricted to their own data
- 12 backend unit tests

Frontend:
- Panel now calls /usage/ai/chat backend endpoint via SSE
- Removed direct OpenAI client calls from frontend
- Added usageAiChatStream networking function following enrichPolicyTemplateStream pattern

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Make model selection optional, default to gpt-4o-mini on backend

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Add team/tag tools, status indicators, and improved AI agent

- AI agent now has 3 tools: get_usage_data, get_team_usage_data, get_tag_usage_data
- Stream status events (Thinking... Fetching... Analyzing...) to UI
- Frontend shows spinner + status text during tool execution
- Better system prompt guiding tool selection
- Entity summariser for team/tag data with ranked breakdowns
- 13 backend tests, 34 frontend tests passing

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Fix: inject today's date into system prompt so AI resolves relative dates correctly

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Show tool calls as distinct steps + render markdown in responses

- Backend emits tool_call events with tool_name, label, args, and status
- Frontend shows each tool call as a step with ✓/spinner/✗ indicator
- Tool call steps show icon, label, date range, and filters
- AI responses rendered with ReactMarkdown (bold, lists, tables, code)
- Cursor-like UX: Thinking → tool calls → Analyzing → streamed answer

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Refactor backend for code quality: proper types, constants, all functions ≤50 LOC

- TypedDict for SSE events (SSEStatusEvent, SSEToolCallEvent, etc.) and ToolHandler
- Constants for table names, entity fields, temperature, page sizes, top-N limits
- Shared _query_activity() eliminates duplicated fetch logic
- _accumulate_breakdown() + _ranked_lines() replace inline aggregation loops
- Extracted _process_tool_call() and _stream_final_response() from main stream fn
- Black + Ruff clean, all 15 functions verified ≤50 LOC
- Replaced Tremor Button with Antd Button in panel (Tremor deprecated per AGENTS.md)

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Address greptile review: security fixes and input validation

- Restrict team/tag tools to admin-only users (non-admins only get get_usage_data)
- Constrain ChatMessage.role to Literal['user', 'assistant'] to prevent system prompt injection
- Add test for base tools restriction (non-admin gets 1 tool, admin gets 3)
- Issues 3 (unused imports) and 4 (inline datetime) were already fixed in prior commit

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Address greptile round 2: sanitize errors, defense-in-depth allowlist, revert tsconfig

- Sanitize error messages: generic 'An internal error occurred' sent to client,
  full exception logged server-side via verbose_proxy_logger
- Defense-in-depth: _process_tool_call validates fn_name against role-based
  allowlist before dispatch (even though LLM only receives allowed tools)
- Revert tsconfig.json jsx back to 'preserve' (Next.js recommended default)

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Role-scoped system prompt + additional test coverage

- System prompt is now role-aware: admin sees all 3 tool descriptions,
  non-admin only sees get_usage_data (consistent with tool filtering)
- Added tests: non-admin prompt excludes team/tag tools, date injection
- 15 backend tests, 34 frontend tests passing

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

* Fix LLM arg validation + cap conversation size at 20 messages

- _resolve_fetch_kwargs uses .get() with ValueError for missing dates
  (handles malformed LLM tool arguments gracefully)
- MAX_CHAT_MESSAGES = 20 constant; backend truncates to last 20
- Frontend also sends only last 20 messages per request
- Prevents excessive token usage and context-length errors

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>
2026-02-24 16:40:04 -08:00
ryan-crabbe 75113440ab Merge pull request #20509 from ryan-crabbe/docs/mcp-trailing-slash
docs: add trailing slash to /mcp endpoint URLs
2026-02-24 16:38:29 -08:00
ryan-crabbe d581c229ef Merge pull request #20376 from ryan-crabbe/fix/model-group-info-cache-invalidation
fix: add cache invalidation for _cached_get_model_group_info
2026-02-24 16:28:05 -08:00
Ishaan Jaff 6ee50ff73e feat(proxy): tool policies - auto-discover tools + policy enforcement guardrail (#22041)
* feat(proxy): tool policies - auto-discover tools, manage policies, guardrail enforcement

- New LiteLLM_ToolTable in schema.prisma to store discovered tools
- Auto-discovery: tools seen in LLM responses get upserted via ToolDiscoveryQueue
  (hooks into DBSpendUpdateWriter, same pipeline as spend tracking)
- Management endpoints: GET /v1/tool/list, GET /v1/tool/{name}, POST /v1/tool/policy
- ToolPolicyGuardrail: blocks tool_calls in responses based on policy setting
- UI: Tool Policies page under Guardrails section with policy selector,
  filters by policy/team/key, live tail, sortable table
- Unit tests for queue, writer, endpoints, guardrail

* feat(tool-policies): track call_count + discover tools from request body and /messages API

- Add call_count column to LiteLLM_ToolTable; incremented on every flush
- Extract tools from request body too (not just response tool_calls):
  - OpenAI /chat/completions: tools[].function.name
  - Anthropic /messages pass-through: request_body.tools[].name
- Show call_count column in UI table (sortable)
- UI: drop dual_llm option, keep only trusted/blocked

* fix: address greptile review feedback

- Remove redundant @@index([tool_name]) from schema.prisma (tool_name has @unique which already creates an index)
- Replace gen_random_uuid()::text with str(uuid.uuid4()) for portability
- Rewrite test_tool_registry_writer.py to mock execute_raw/query_raw (actual implementation) instead of Prisma model methods
- Fix test patches in test_tool_management_endpoints.py to target source modules since imports are inside function bodies
- Add "Tool Policies" page title to ToolPolicies.tsx

* fix: address greptile review round 2

- Replace NOW() with Python datetime parameter in tool_registry_writer (SQLite portability)
- Fix cache key collision in tool_policy_guardrail: use null-byte separator instead of colon
- Remove type==function filter from request-side tool extraction to match response-side behavior
- Clear seen_tool_names on flush so call_count increments per batch cycle not per pod lifetime

* fix: address greptile review round 3

- Fix test_seen_names_persist_across_flushes to match actual per-flush-cycle behavior
- Update module docstring in tool_discovery_queue.py to accurately describe flush behavior
- Add created_at/updated_at to raw SQL INSERT in batch_upsert_tools and update_tool_policy

* fix: cache tool policies per tool name not per combination

Previously the cache key was built from the full set of tool names in a
request, so each unique combination of tools got its own cold cache entry
and triggered a separate DB query. With N distinct tools across requests
this was effectively a DB hit on every request.

Now each tool name is cached individually. Cache hits are checked per
tool, only missing tools are fetched from DB in a single batch query,
and each result is cached separately. Once a tool's policy is warm,
any subsequent request using that tool benefits from the cache regardless
of what other tools are in the request.

* Update ui/litellm-dashboard/src/components/ToolPolicies.tsx

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-24 16:27:06 -08:00
Ryan Crabbe ba0f794591 Merge origin/main; keep both model_group_info and access_groups cache invalidation 2026-02-24 16:08:29 -08:00
yuneng-jiang 857816fe6d Merge pull request #22043 from BerriAI/litellm_router_settings_vitest
[Test] UI - Unit Testing Coverage: Router Settings
2026-02-24 16:02:30 -08:00
yuneng-jiang 26e5482abb address greptile review feedback (greploop iteration 2)
- Wait for strategy select (API data loaded) before clicking Save
- Assert specific payload content in setCallbacksCall
- Move NotificationsManager import to top of file
2026-02-24 15:52:15 -08:00
yuneng-jiang 784af16cb4 address greptile review feedback (greploop iteration 1)
- Replace document.querySelector/querySelectorAll with screen.getByRole
- Replace raw dispatchEvent with userEvent.selectOptions
2026-02-24 15:48:31 -08:00
yuneng-jiang b3bb744aa4 [Test] Add unit tests for router_settings components
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-24 15:26:06 -08:00
ryan-crabbe 8020276711 Merge pull request #21430 from BerriAI/litellm_perf_headers_caching
perf: use cached _safe_get_request_headers instead
2026-02-24 15:22:12 -08:00
Ryan Crabbe 9971b67587 fix: convert remaining dict(request.headers) to _safe_get_request_headers
Missed conversions in user_api_key_auth.py and litellm_pre_call_utils.py.
Both call sites are read-only so no .copy() needed.
2026-02-24 15:21:43 -08:00
Ryan Crabbe 53c10b0b64 Merge origin/main and address Greptile review feedback
- Resolve merge conflict in pass_through_endpoints.py
- Add .copy() to proxy_server_request headers to prevent cache corruption
- Add test for request.state unavailable fallback path
2026-02-24 15:13:19 -08:00
ryan-crabbe e9a45bf75b Merge pull request #20032 from ryan-crabbe/fix/mcp-server-unreachable-error-handling
fix: dead code cleanup in MCP server error handler
2026-02-24 15:03:01 -08:00
ryan-crabbe 56a507073b Merge pull request #21690 from BerriAI/litellm_perf_o_series_short_circuit
perf: optimize is_model_o_series_model with startswith
2026-02-24 14:59:53 -08:00
ryan-crabbe 253792a1d1 Merge pull request #21611 from BerriAI/litellm_perf_skip_throwaway_usage
perf: skip throwaway Usage() construction in ModelResponse.__init__
2026-02-24 14:53:17 -08:00
Ryan Crabbe 6a0dd0a45f Merge remote-tracking branch 'origin/main' into litellm_perf_skip_throwaway_usage
# Conflicts:
#	tests/llm_translation/test_llm_response_utils/test_convert_dict_to_chat_completion.py
2026-02-24 14:51:57 -08:00
yuneng-jiang 80ebe722d9 Merge pull request #22029 from BerriAI/litellm_spend_tracking_logging
[Infra] Add Spend Tracking Lifecycle Logging
2026-02-24 12:52:32 -08:00
yuneng-jiang 2cabbccf6f address greptile review feedback (greploop iteration 3)
- Add missing traceback to team member spend enqueue error log
2026-02-24 12:49:48 -08:00
yuneng-jiang 8b56e1d969 trigger review 2026-02-24 12:37:43 -08:00
Ishaan Jaff 33719e6b38 docs: update v1.81.12-stable release notes to point to v1.81.12-stable.1 (#22036) 2026-02-24 12:30:18 -08:00
yuneng-jiang 70ef4d0d69 address greptile review feedback (greploop iteration 2)
- Remove re-raise in _store_transactions_in_redis so one Redis
  push failure doesn't drop remaining transaction types
- Downgrade per-push success log from info to debug to reduce noise
- Fix misleading error message in update_database — entity spend
  updates run as independent tasks and are not affected by this catch
2026-02-24 12:10:19 -08:00
Sameer Kankute 5219b1d0c3 Merge pull request #22035 from BerriAI/litellm_openai_codex_day_0_codex_5.3
[Feat] OpenAI codex 5.3 day 0 support
2026-02-25 01:29:27 +05:30
yuneng-jiang 235d60eb88 address greptile review feedback (greploop iteration 1)
- Add traceback to cache update warning logs (user, end_user, team, tag)
- Remove duplicate info log in non-redis commit path
2026-02-24 11:58:59 -08:00
Ishaan Jaff c343bfffda fix(router): emit x-litellm-overhead-duration-ms header for streaming requests (#22027)
* fix(router): preserve _hidden_params in FallbackStreamWrapper so x-litellm-overhead-duration-ms is emitted for streaming requests

* test(router): add regression test for FallbackStreamWrapper _hidden_params preservation
2026-02-24 11:56:16 -08:00
Ishaan Jaff e44b9b6b35 feat(prometheus): add opt-in stream label to litellm_proxy_total_requests_metric (#22023)
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 11:51:42 -08:00
Sameer Kankute 5d291c739f Fix phase docs link 2026-02-25 01:21:38 +05:30
Sameer Kankute 74abf0c8e6 Fix phase docs link 2026-02-25 01:19:10 +05:30
Sameer Kankute aded14a55a Fix release version for gpt-5.3-codex 2026-02-25 01:04:12 +05:30
yuneng-jiang c43a8dc842 feat(proxy): add warning/error level logging throughout spend tracking lifecycle
Elevate silent debug-level and bare except:pass error paths to
warning/error so spend tracking failures are visible in production logs.

All new log messages are prefixed with "Spend tracking -" for easy
filtering. Changes cover the full request-to-DB lifecycle:
enqueue, in-memory flush, Redis buffer push/pop, DB commit,
cache updates, spend log writes, and pod lock management.

Also fixes a copy-paste bug in _update_team_cache that logged
"end user" instead of "team".
2026-02-24 10:17:35 -08:00
yuneng-jiang 4321bc9285 Merge pull request #21985 from BerriAI/litellm_ui_testing_coverage_00
[Fix] UI - Virtual Keys: restrict Edit Settings to key owners
2026-02-24 10:16:40 -08:00
Sameer Kankute 1c48d8fda7 Add gpt-5.3-codex in model cost map 2026-02-24 23:37:09 +05:30
Ishaan Jaff 5e9f24f74c fix(bedrock): pass timeout param to bedrock rerank http client (#22021)
* fix(bedrock): pass timeout to bedrock rerank http client

* refactor: extract large functions to fix PLR0915 ruff lint errors
2026-02-24 09:32:11 -08:00
Sean Marsh Glover 4652c73259 feat(proxy): limit concurrent health checks with health_check_concurrency (#20584)
* staged first pass

* black

* Update litellm/proxy/health_check.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* simpler

* restore cached logo

* fix tests for perform_health_check max_concurrency arg

* implement pr suggestion

* and the helm chart

* add configureable resources and probes to the deployment in the helm chart

* more helm chart unittests

* move some background healthcheck loggin to debug

---------

Co-authored-by: Sean Glover <sglover@athenahealth.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-24 08:16:59 -08:00
Harshit Jain 1fa0aad3f2 Merge pull request #22008 from BerriAI/litellm_fix_CVE
security: fix critical/high CVEs in OS-level libs and NPM transitive
2026-02-24 21:44:19 +05:30