Commit graph

2892 commits

Author SHA1 Message Date
Yuneng Jiang
62e5bf48cc
chore: fixes 2026-04-04 23:32:57 -07: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
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
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
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
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
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
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
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
Harshit28j
132e2ed671 Merge branch 'main' of https://github.com/BerriAI/litellm into litellm_fix_CVE
# Please enter a commit message to explain why this merge is necessary,
# especially if it merges an updated upstream into a topic branch.
#
# Lines starting with '#' will be ignored, and an empty message aborts
# the commit.
2026-02-24 21:09:16 +05:30
Harshit28j
3e6c10a071 security: fix critical/high CVEs in OS-level libs and NPM transitive 2026-02-24 19:40:09 +05:30
Sameer Kankute
a37cd0fe7c
Merge pull request #22005 from BerriAI/litellm_mcp_server_ui_fix
Fix: Transport Type for OpenAPI Spec on UI
2026-02-24 19:38:34 +05:30
Sameer Kankute
c17caf4cc7
Merge pull request #21992 from BerriAI/litellm_fix_oauth_mcp
fix: Missing OAuth session state
2026-02-24 19:37:09 +05:30
Sameer Kankute
6531d01959
Merge pull request #21982 from BerriAI/litellm_fix_pat_token_mcp
Fix: skip health check for MCP integration with passthrough token auth
2026-02-24 19:36:08 +05:30
Sameer Kankute
816f9052ff Fix: Transport Type for OpenAPI Spec on UI 2026-02-24 19:27:12 +05:30
Sameer Kankute
12f37cea43 fix: Missing OAuth session state. Please retry 2026-02-24 14:22:38 +05:30
yuneng-jiang
c119adb6dc [Fix] UI - Virtual Keys: restrict Edit Settings button to key owners
Non-owner Internal Users could see and interact with the "Edit Settings"
button in the key Settings tab for keys they don't own. The button was
gated by `rolesWithWriteAccess.includes(userRole)` (role-only check)
instead of `canModifyKey` (ownership-aware), unlike the Regenerate and
Delete buttons which already used the correct check.

Replace the condition with `canModifyKey` so the Edit Settings button
follows the same proxy-admin / team-admin / key-owner logic as the
other action buttons. Add tests covering all permission paths.
2026-02-23 23:06:27 -08:00
Sameer Kankute
46ed7fc706 Add Additonal header field on UI for testing passthrough 2026-02-24 12:06:07 +05:30
yuneng-jiang
36f7722b0f fix: add QueryClientProvider, remove stale file, use should naming in tests
- Wrap onboarding page with QueryClientProvider to prevent runtime crash
  (mirrors the same pattern used in LoginPage)
- Stage deletion of stale litellm/ui/litellm-dashboard/src/app/onboarding/page.tsx
  committed at the wrong path
- Rename all 16 test names to start with "should" per AGENTS.md convention
2026-02-23 21:53:42 -08:00
yuneng-jiang
a3491490f9 refactor onboarding 2026-02-23 21:30:08 -08:00
yuneng-jiang
02a53989cf fix: narrow onSubmit values and use semantic loading assertion 2026-02-23 21:20:22 -08:00
yuneng-jiang
0873494270 feat: extract OnboardingFormBody component with tests
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 21:08:19 -08:00
yuneng-jiang
a347cf0a33 feat: extract OnboardingErrorView component with tests
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 21:06:17 -08:00
yuneng-jiang
a3d4a8752f feat: extract OnboardingLoadingView component with tests
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 21:04:48 -08:00
yuneng-jiang
10a3304e6a refactor: simplify onboarding page to use OnboardingForm component 2026-02-23 20:18:39 -08:00
yuneng-jiang
1f8d23ec5b fix: set cookie path and add error feedback on claim failure 2026-02-23 18:16:38 -08:00
yuneng-jiang
2bc6dc5cad fix: sync email field value into AntD Form after credentials load 2026-02-23 18:12:17 -08:00
yuneng-jiang
884904c6d1 feat: add OnboardingForm component with variant prop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 18:08:31 -08:00
yuneng-jiang
ba0ed492c4 fix: improve type safety and defensive guard in useOnboarding hook
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 18:05:23 -08:00
yuneng-jiang
f4303f5e22 feat: add useOnboarding hook with query and mutation
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 18:01:10 -08:00
yuneng-jiang
715e134a66 adding testing coverage + fixing flaky tests 2026-02-23 17:23:10 -08:00
yuneng-jiang
9f3fc492c2 adding tests 2026-02-23 16:02:36 -08:00
yuneng-jiang
09cc3b8bbc ui changes 2026-02-23 15:54:07 -08:00
yuneng-jiang
08f4a27e32 Merge remote-tracking branch 'origin' into litellm_blog_dropdown 2026-02-23 15:02:07 -08:00
yuneng-jiang
1ecfbad46e adjust blog posts to fetch from github first 2026-02-23 14:45:05 -08:00
Krish Dholakia
4dfec4661b
Guardrail Monitor - measure guardrail reliability in prod (#21944)
* fix: fix log viewer for guardrail monitoring

* feat(ui/): fix rendering logs per guardrail

* fix: fix viewing logs on overview tab of guardrail

* fix: log viewer

* fix: fix naming to align with metric
2026-02-23 10:23:14 -08:00
Sameer Kankute
9b5bbee906
Merge pull request #21786 from BerriAI/litellm_oss_staging_02_21_2026
Litellm oss staging 02 21 2026
2026-02-23 18:51:55 +05:30
Sameer Kankute
37d45139f2
Merge pull request #21917 from BerriAI/litellm_fix_model_cost_map_wildcard
Fix: Anthropic model wildcard access issue
2026-02-23 18:45:49 +05:30
Sameer Kankute
4934d89cc7
Merge pull request #21872 from BerriAI/litellm_dev_02_21_2026_p4
Litellm dev 02 19 2026 p2 (#21871)
2026-02-23 18:35:57 +05:30
Sameer Kankute
c7aafdf794
Merge pull request #21926 from BerriAI/main
merge main in oss 21 02
2026-02-23 18:17:30 +05:30
Sameer Kankute
262235f266 Add ability to see which model cost map is getting used 2026-02-23 17:15:06 +05:30
Krish Dholakia
76ccc9e844
Guardrail Policy Versioning (#21862)
* feat: initial commit, adding support for policy versioning on litellm

* fix(policy_registry): support policy versioning

* fix: multiple QA fixes for policy flow builder with guardrail versioning on litellm

* feat: ui improvements

* feat: add prisma migration

* fix: address greptile fixes
2026-02-21 20:14:31 -08:00
Krrish Dholakia
9828b9929f fix(guardrails/usage_endpoints.py): fix usage dashboard 2026-02-21 19:33:50 -08:00
Krish Dholakia
886f1a3472
Litellm dev 02 19 2026 p2 (#21871)
* feat(ui/): new guardrails monitor 'demo

mock representation of what guardrails monitor looks like

* fix: ui updates

* style(ui/): fix styling

* feat: enable running ai monitor on individual guardrails

* feat: add backend logic for guardrail monitoring
2026-02-21 19:14:04 -08:00
yuneng-jiang
a0965d5b4a feat: add BlogDropdown to navbar after Docs link 2026-02-21 17:34:08 -08:00
yuneng-jiang
929d592ef4 fix: add retry, stable post key, enabled guard in BlogDropdown
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-21 17:34:08 -08:00