diff --git a/.circleci/config.yml b/.circleci/config.yml index 6ee5634f54f..dbeb412506f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -111,6 +111,28 @@ commands: - wait_for_service: url: tcp://localhost:6379 timeout: "60" + start_openai_record_replay_proxy: + description: "Start the record/replay proxy (tests/_openai_record_replay_proxy.py) on host port 8090 and wait until healthy. Models whose api_base points here replay recorded provider responses, so the E2E run neither pays for nor depends on the live provider. The default upstream is OpenAI; a non-OpenAI model must point its api_base at /__recorder_upstream// so the recorder forwards there instead of defaulting to OpenAI. Run after uv deps are synced." + steps: + - run: + name: Start record/replay proxy + background: true + command: | + CASSETTE_REDIS_URL="$CASSETTE_REDIS_URL" \ + RECORDER_UPSTREAM_BASE_URL="https://api.openai.com" \ + uv run --no-sync python tests/_openai_record_replay_proxy.py --host 0.0.0.0 --port 8090 + - run: + name: Wait for record/replay proxy + command: | + for i in $(seq 1 30); do + if curl -sf http://localhost:8090/__recorder_health >/dev/null 2>&1; then + echo "record/replay proxy is up" + exit 0 + fi + sleep 1 + done + echo "record/replay proxy did not become ready" >&2 + exit 1 setup_litellm_enterprise_pip: steps: - run: @@ -452,6 +474,120 @@ jobs: - auth_ui_unit_tests_coverage.xml - auth_ui_unit_tests_coverage + proxy_behavior_tests: + docker: + - *python312_image + - image: cimg/postgres:16.0@sha256:b125148bc76e8e8eee5eb3ad6020a3a14110a14e8192f1c645128afebe2e2f84 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: litellm_test + working_directory: ~/project + environment: + DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/litellm_test" + steps: + - checkout + - setup_google_dns + - install_uv + - run: + name: Install Dependencies + command: | + uv sync --frozen --all-groups --all-extras --python 3.12 + - wait_for_service: + url: tcp://localhost:5432 + timeout: "60" + - run: + name: Seed DB schema via prisma db push + command: | + uv run --no-sync prisma db push --schema litellm/proxy/schema.prisma --accept-data-loss + - run: + name: Generate Prisma Client + command: uv run --no-sync python -m prisma generate + - run: + name: Run proxy management behavior tests + command: | + mkdir -p test-results + uv run --no-sync python -m pytest tests/proxy_behavior \ + -v --junitxml=test-results/junit.xml --durations=10 + no_output_timeout: 15m + - store_test_results: + path: test-results + + proxy_security_tests: + docker: + - *python312_image + - image: cimg/postgres:16.0@sha256:b125148bc76e8e8eee5eb3ad6020a3a14110a14e8192f1c645128afebe2e2f84 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: litellm_test + working_directory: ~/project + environment: + DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/litellm_test" + steps: + - checkout + - setup_google_dns + - install_uv + - run: + name: Install Dependencies + command: | + uv sync --frozen --all-groups --all-extras --python 3.12 + - wait_for_service: + url: tcp://localhost:5432 + timeout: "60" + - run: + name: Seed DB schema via prisma db push + command: | + uv run --no-sync prisma db push --schema litellm/proxy/schema.prisma --accept-data-loss + - run: + name: Generate Prisma Client + command: uv run --no-sync python -m prisma generate + - run: + name: Run proxy security tests + command: | + mkdir -p test-results + uv run --no-sync python -m pytest tests/proxy_security_tests \ + -v --junitxml=test-results/junit.xml --durations=10 + no_output_timeout: 15m + - store_test_results: + path: test-results + + schema_migration_check: + docker: + - *python312_image + - image: cimg/postgres:16.0@sha256:b125148bc76e8e8eee5eb3ad6020a3a14110a14e8192f1c645128afebe2e2f84 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: litellm_test + working_directory: ~/project + environment: + # An empty database; the test applies every committed migration itself. + DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/litellm_test" + steps: + - checkout + - setup_google_dns + - install_uv + - run: + name: Install Dependencies + command: | + uv sync --frozen --all-groups --all-extras --python 3.12 + - wait_for_service: + url: tcp://localhost:5432 + timeout: "60" + - run: + name: Generate Prisma Client + command: uv run --no-sync python -m prisma generate + - run: + name: Check schema.prisma is in sync with committed migrations + command: | + mkdir -p test-results + uv run --no-sync python -m pytest tests/proxy_migration_tests \ + -v --junitxml=test-results/junit.xml --durations=10 + no_output_timeout: 15m + - store_test_results: + path: test-results + litellm_router_testing: # Runs all tests with the "router" keyword docker: - *python312_image @@ -1511,6 +1647,7 @@ jobs: command: | zstd -d litellm-docker-database.tar.zst --stdout | docker load docker tag litellm-docker-database:ci my-app:latest + - start_openai_record_replay_proxy - run: name: Run Docker container command: | @@ -1541,6 +1678,7 @@ jobs: -e LANGFUSE_PROJECT2_PUBLIC=$LANGFUSE_PROJECT2_PUBLIC \ -e LANGFUSE_PROJECT1_SECRET=$LANGFUSE_PROJECT1_SECRET \ -e LANGFUSE_PROJECT2_SECRET=$LANGFUSE_PROJECT2_SECRET \ + -e RECORDER_OPENAI_BASE_URL=http://host.docker.internal:8090/v1 \ --add-host host.docker.internal:host-gateway \ --name my-app \ -v $(pwd)/proxy_server_config.yaml:/app/config.yaml \ @@ -1678,6 +1816,7 @@ jobs: command: | zstd -d litellm-docker-database.tar.zst --stdout | docker load docker images | grep litellm-docker-database + - start_openai_record_replay_proxy - run: name: Run Docker container # intentionally give bad redis credentials here @@ -1701,6 +1840,7 @@ jobs: -e DD_SITE=$DD_SITE \ -e AWS_REGION_NAME=$AWS_REGION_NAME \ -e COHERE_API_KEY=$COHERE_API_KEY \ + -e RECORDER_COHERE_BASE_URL=http://host.docker.internal:8090/__recorder_upstream/api.cohere.com \ -e GCS_FLUSH_INTERVAL="1" \ --add-host host.docker.internal:host-gateway \ --name my-app \ @@ -2266,6 +2406,7 @@ jobs: command: | zstd -d litellm-docker-database.tar.zst --stdout | docker load docker images | grep litellm-docker-database + - start_openai_record_replay_proxy - run: name: Run Docker container with test config command: | @@ -2274,6 +2415,7 @@ jobs: -e DATABASE_URL=postgresql://postgres:postgres@host.docker.internal:5432/circle_test \ -e LITELLM_MASTER_KEY="sk-1234" \ -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \ + -e RECORDER_ANTHROPIC_BASE_URL=http://host.docker.internal:8090/__recorder_upstream/api.anthropic.com \ -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \ -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \ -e AWS_REGION_NAME="us-east-1" \ @@ -2548,6 +2690,122 @@ jobs: path: ui/litellm-dashboard/playwright-report destination: e2e-playwright-report + e2e_ui_testing_server_root_path: + docker: + - image: cimg/python:3.12-browsers@sha256:b432899af01c9a311bf74f4f22e9ada2e5306d4b1b4383f8d29e1228a5844ef2 + auth: + username: ${DOCKERHUB_USERNAME} + password: ${DOCKERHUB_PASSWORD} + - image: cimg/postgres:16.0@sha256:b125148bc76e8e8eee5eb3ad6020a3a14110a14e8192f1c645128afebe2e2f84 + environment: + POSTGRES_USER: e2euser + POSTGRES_PASSWORD: e2epassword + POSTGRES_DB: litellm_e2e + resource_class: large + working_directory: ~/project + environment: + DATABASE_URL: "postgresql://e2euser:e2epassword@localhost:5432/litellm_e2e" + CI: "true" + # The whole job exercises the proxy mounted under a prefix. SERVER_ROOT_PATH + # is read both by the proxy at boot (to rewrite the built UI bundle in place) + # and by migration.serverRootPath.config.ts, which refuses to run without it. + SERVER_ROOT_PATH: "/litellm" + steps: + - checkout + - setup_google_dns + - install_uv + - restore_cache: + keys: + - v1-uv-cache-{{ checksum "uv.lock" }} + - run: + name: Install Python dependencies + command: | + uv sync --frozen --all-groups --all-extras --python 3.12 + uv run --no-sync python -m prisma generate --schema litellm/proxy/schema.prisma + - save_cache: + key: v1-uv-cache-{{ checksum "uv.lock" }} + paths: + - ~/.cache/uv + - restore_cache: + keys: + - ui-e2e-node-deps-v2-{{ checksum "ui/litellm-dashboard/package-lock.json" }} + - run: + name: Install Node dependencies and Playwright + command: | + cd ui/litellm-dashboard + npm ci + npx playwright install chromium + - save_cache: + key: ui-e2e-node-deps-v2-{{ checksum "ui/litellm-dashboard/package-lock.json" }} + paths: + - ui/litellm-dashboard/node_modules + - ~/.cache/ms-playwright + - run: + name: Build UI from source + command: | + cd ui/litellm-dashboard + npm run build + rm -rf ../../litellm/proxy/_experimental/out + mv out ../../litellm/proxy/_experimental/out + find ../../litellm/proxy/_experimental/out -name '*.html' ! -name 'index.html' | while read -r f; do + d="${f%.html}"; mkdir -p "$d"; mv "$f" "$d/index.html" + done + - wait_for_service: + url: tcp://localhost:5432 + timeout: "30" + - run: + name: Push Prisma schema + command: uv run --no-sync python -m prisma db push --schema litellm/proxy/schema.prisma --accept-data-loss + - run: + name: Seed database + command: | + PGPASSWORD=e2epassword psql -h localhost -p 5432 -U e2euser -d litellm_e2e \ + -f ui/litellm-dashboard/e2e_tests/fixtures/seed.sql + - run: + name: Start mock LLM server + command: uv run --no-sync python ui/litellm-dashboard/e2e_tests/fixtures/mock_llm_server/server.py + background: true + - run: + name: Start LiteLLM proxy under a server root path + environment: + LITELLM_MASTER_KEY: "sk-1234" + MOCK_LLM_URL: "http://127.0.0.1:8090/v1" + DISABLE_SCHEMA_UPDATE: "true" + # Output flows to this step's own log, so a boot crash is visible here + # rather than swallowed by a downstream readiness probe. + command: | + LITELLM_LICENSE="$LITELLM_LICENSE" \ + uv run --no-sync python -m litellm.proxy.proxy_cli \ + --config ui/litellm-dashboard/e2e_tests/fixtures/config.yml \ + --port 4000 + background: true + - run: + name: Wait for prefixed proxy to be ready + command: | + for i in $(seq 1 60); do + HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 -H "Authorization: Bearer sk-1234" http://127.0.0.1:4000/litellm/health 2>/dev/null || true) + if [ "$HTTP_CODE" = "200" ]; then + echo "Prefixed proxy is ready" + exit 0 + fi + sleep 2 + done + echo "Prefixed proxy failed to start; see the 'Start LiteLLM proxy under a server root path' step for the boot log" + exit 1 + - run: + name: Run migration smoke under SERVER_ROOT_PATH + command: | + cd ui/litellm-dashboard + LITELLM_LICENSE="$LITELLM_LICENSE" \ + npx playwright test --config e2e_tests/migration.serverRootPath.config.ts + no_output_timeout: 10m + - store_artifacts: + path: ui/litellm-dashboard/test-results + destination: e2e-server-root-path-test-results + - store_artifacts: + path: ui/litellm-dashboard/playwright-report + destination: e2e-server-root-path-playwright-report + build_docker_database_image: machine: image: ubuntu-2204:2024.04.1 @@ -2643,10 +2901,18 @@ workflows: filters: *main_branches - auth_ui_unit_tests: filters: *main_branches + - proxy_behavior_tests: + filters: *main_branches + - proxy_security_tests: + filters: *main_branches + - schema_migration_check: + filters: *main_branches - build_docker_database_image: filters: *main_branches - e2e_ui_testing: filters: *main_branches + - e2e_ui_testing_server_root_path: + filters: *main_branches - build_and_test: requires: - build_docker_database_image diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index f0ced6bedb8..23b520e2ad5 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -8,3 +8,6 @@ # Update pydantic code to fix warnings (GH-3600) 876840e9957bc7e9f7d6a2b58c4d7c53dad16481 + +# style(ui): run prettier --write across the dashboard (#29622) +7edf3a9cb55548b143df1692f4ed7c4681d7fcf7 diff --git a/.gitattributes b/.gitattributes index 9030923a781..5c9061f52ac 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ -*.ipynb linguist-vendored \ No newline at end of file +*.ipynb linguist-vendored +ui/litellm-dashboard/src/lib/http/schema.d.ts linguist-generated \ No newline at end of file diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 00000000000..b64e38a2286 --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# +# commit-msg — enforce Conventional Commits 1.0.0 +# https://www.conventionalcommits.org/en/v1.0.0/ +# +# Subject format: ()!: +# - must be one of the angular types (feat, fix, ...) +# - () is optional +# - ! is optional and marks a breaking change +# - is mandatory and must be non-empty +# +# Bypass: commit with --no-verify. +# Merge, revert, fixup!, squash!, and amend! messages are passed through. + +set -eu + +COMMIT_MSG_FILE="${1:-}" +if [ -z "$COMMIT_MSG_FILE" ] || [ ! -f "$COMMIT_MSG_FILE" ]; then + echo "commit-msg: missing commit message file" >&2 + exit 1 +fi + +# First non-comment, non-empty line is the subject. +subject="" +while IFS= read -r line || [ -n "$line" ]; do + case "$line" in + ''|'#'*) continue ;; + esac + subject="$line" + break +done < "$COMMIT_MSG_FILE" + +if [ -z "$subject" ]; then + echo "commit-msg: empty commit message" >&2 + exit 1 +fi + +# Pass-through commits generated by git itself. +case "$subject" in + "Merge "*|"Revert \""*|"fixup! "*|"squash! "*|"amend! "*) + exit 0 + ;; +esac + +ALLOWED_TYPES="feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert" +# Description must not start with an uppercase letter — kept in sync with the +# subjectPattern in .github/workflows/conventional-commits.yml so the local +# hook is the strictly tighter of the two gates. (Without this guard, a commit +# like "feat: Add thing" passes locally but fails the PR-title CI check.) +PATTERN="^(${ALLOWED_TYPES})(\([^)]+\))?!?: [^A-Z].*" + +if printf '%s' "$subject" | grep -Eq "$PATTERN"; then + exit 0 +fi + +cat >&2 <()!: + (description must start with a lowercase letter) + + Allowed types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert + Examples: + feat(router): add weighted round-robin strategy + fix(bedrock): decouple STS region from aws_region_name + chore(deps): bump black to 26.3.1 + refactor!: drop Python 3.8 support + +See https://www.conventionalcommits.org/en/v1.0.0/ + +To bypass (use sparingly): git commit --no-verify +EOF +exit 1 diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 00000000000..c2267c8501c --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# +# pre-push — enforce Conventional Branches +# https://conventional-branch.github.io/ +# +# Branch format: / +# must be one of: feature, bugfix, hotfix, release, chore +# +# Protected branches (always allowed): +# - main +# - litellm_internal_staging +# - dependabot/* +# - gh-readonly-queue/* +# +# Tag pushes and branch deletions are skipped. +# Bypass: git push --no-verify. + +set -eu + +ZERO_OID="0000000000000000000000000000000000000000" +ZERO_OID_SHA256="0000000000000000000000000000000000000000000000000000000000000000" +ALLOWED_TYPES="feature|bugfix|hotfix|release|chore" +BRANCH_PATTERN="^(${ALLOWED_TYPES})/.+" + +PROTECTED_NAMES="main litellm_internal_staging" +PROTECTED_PREFIXES="dependabot/ gh-readonly-queue/" + +is_protected() { + branch="$1" + for name in $PROTECTED_NAMES; do + if [ "$branch" = "$name" ]; then + return 0 + fi + done + for prefix in $PROTECTED_PREFIXES; do + case "$branch" in "$prefix"*) return 0 ;; esac + done + return 1 +} + +invalid="" + +while read -r local_ref local_oid remote_ref remote_oid; do + # Branch deletion (no local commit being pushed). + if [ "$local_oid" = "$ZERO_OID" ] || [ "$local_oid" = "$ZERO_OID_SHA256" ]; then + continue + fi + + # Only validate branch pushes; ignore tags and other ref namespaces. + case "$remote_ref" in + refs/heads/*) ;; + *) continue ;; + esac + + branch="${remote_ref#refs/heads/}" + + if is_protected "$branch"; then + continue + fi + + if ! printf '%s' "$branch" | grep -Eq "$BRANCH_PATTERN"; then + invalid="$invalid $branch" + fi +done + +if [ -n "$invalid" ]; then + cat >&2 </ + + Allowed types: feature, bugfix, hotfix, release, chore + Examples: + feature/weighted-round-robin + bugfix/streaming-empty-chunks + chore/bump-deps + hotfix/auth-bypass + + Protected (always allowed): main, litellm_internal_staging, + dependabot/*, gh-readonly-queue/*. + +See https://conventional-branch.github.io/ + +Rename with: git branch -m +To bypass (use sparingly): git push --no-verify +EOF + exit 1 +fi + +exit 0 diff --git a/.github/workflows/_test-unit-base.yml b/.github/workflows/_test-unit-base.yml index 7e91341ac77..a42b2f8f9df 100644 --- a/.github/workflows/_test-unit-base.yml +++ b/.github/workflows/_test-unit-base.yml @@ -27,6 +27,11 @@ on: required: false type: number default: 10 + dist: + description: "pytest-xdist distribution mode (loadscope|load|worksteal|loadfile|no)" + required: false + type: string + default: "loadscope" artifact-name: description: "Unique name for the coverage artifact (must be unique per run)" required: true @@ -82,18 +87,31 @@ jobs: MAX_FAILURES: ${{ inputs.max-failures }} WORKERS: ${{ inputs.workers }} RERUNS: ${{ inputs.reruns }} + DIST: ${{ inputs.dist }} run: | - uv run --no-sync pytest ${TEST_PATH:?} \ - --tb=short -vv \ - --maxfail="${MAX_FAILURES}" \ - -n "${WORKERS}" \ - --reruns "${RERUNS}" \ - --reruns-delay 1 \ - --dist=loadscope \ - --durations=20 \ - --cov=./litellm \ - --cov-report=xml:coverage.xml \ - --cov-config=pyproject.toml + if [ "${WORKERS}" = "0" ]; then + uv run --no-sync pytest ${TEST_PATH:?} \ + --tb=short -vv \ + --maxfail="${MAX_FAILURES}" \ + --reruns "${RERUNS}" \ + --reruns-delay 1 \ + --durations=20 \ + --cov=./litellm \ + --cov-report=xml:coverage.xml \ + --cov-config=pyproject.toml + else + uv run --no-sync pytest ${TEST_PATH:?} \ + --tb=short -vv \ + --maxfail="${MAX_FAILURES}" \ + -n "${WORKERS}" \ + --reruns "${RERUNS}" \ + --reruns-delay 1 \ + --dist="${DIST}" \ + --durations=20 \ + --cov=./litellm \ + --cov-report=xml:coverage.xml \ + --cov-config=pyproject.toml + fi - name: Save coverage report if: always() diff --git a/.github/workflows/_test-unit-services-base.yml b/.github/workflows/_test-unit-services-base.yml deleted file mode 100644 index 7f973d8cafa..00000000000 --- a/.github/workflows/_test-unit-services-base.yml +++ /dev/null @@ -1,190 +0,0 @@ -name: _Unit Test Services Base (Reusable) - -on: - workflow_call: - inputs: - test-path: - description: "Pytest path(s) to run" - required: true - type: string - workers: - description: "Number of pytest-xdist workers (0 = no parallelism)" - required: false - type: number - default: 2 - reruns: - description: "Number of reruns for flaky tests" - required: false - type: number - default: 2 - timeout-minutes: - description: "Job timeout in minutes" - required: false - type: number - default: 20 - max-failures: - description: "Stop after this many failures" - required: false - type: number - default: 10 - enable-postgres: - description: "Start a local Postgres service container and run Prisma migrations" - required: false - type: boolean - default: false - dist: - description: "pytest-xdist distribution mode (loadscope|load|worksteal|loadfile|no)" - required: false - type: string - default: "loadscope" - artifact-name: - description: "Unique name for the coverage artifact (must be unique per run)" - required: false - type: string - default: "run" - -permissions: - contents: read - -# The postgres service container below is spawned per-job on localhost and -# destroyed with the job. Nothing outside the runner can reach it. The -# user/password/database here are not secrets — they're bootstrap values -# for a throwaway container — so we hardcode them instead of attaching -# every matrix shard to a GHA environment just to read three "secrets" -# (which also produces a "temporarily deployed to …" notification on the -# PR timeline per shard per push). -jobs: - run: - name: Run tests - runs-on: ubuntu-latest - timeout-minutes: ${{ inputs.timeout-minutes }} - - services: - postgres: - image: postgres@sha256:705a5d5b5836f3fcba0d02c4d281e6a7dd9ed2dd4078640f08a1e1e9896e097d # postgres:14 - env: - POSTGRES_USER: litellm - POSTGRES_PASSWORD: litellm - POSTGRES_DB: litellm_test - ports: - - 5432:5432 - options: >- - --health-cmd "pg_isready" - --health-interval 10s - --health-timeout 5s - --health-retries 5 - - steps: - - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 - with: - persist-credentials: false - - - name: Set up Python - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 - with: - python-version: "3.12" - - - name: Set up uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 - with: - version: "0.10.9" - - - name: Cache uv dependencies - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: | - ~/.cache/uv - .venv - key: ${{ runner.os }}-uv-services-${{ hashFiles('uv.lock') }} - restore-keys: | - ${{ runner.os }}-uv-services- - - - name: Install dependencies - run: | - uv sync --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router - - - name: Generate Prisma client - env: - PRISMA_BINARY_CACHE_DIR: ${{ runner.temp }}/prisma-cache - run: | - uv run --no-sync prisma generate --schema litellm/proxy/schema.prisma - - - name: Run Prisma migrations - if: ${{ inputs.enable-postgres }} - env: - DATABASE_URL: "postgresql://litellm:litellm@localhost:5432/litellm_test" - run: | - uv run --no-sync prisma db push --schema litellm/proxy/schema.prisma --accept-data-loss - - - name: Run tests - env: - TEST_PATH: ${{ inputs.test-path }} - MAX_FAILURES: ${{ inputs.max-failures }} - WORKERS: ${{ inputs.workers }} - RERUNS: ${{ inputs.reruns }} - DIST: ${{ inputs.dist }} - DATABASE_URL: ${{ inputs.enable-postgres && 'postgresql://litellm:litellm@localhost:5432/litellm_test' || '' }} - run: | - if [ "${WORKERS}" = "0" ]; then - uv run --no-sync pytest ${TEST_PATH:?} \ - --tb=short -vv \ - --maxfail="${MAX_FAILURES}" \ - --reruns "${RERUNS}" \ - --reruns-delay 1 \ - --durations=20 \ - --cov=./litellm \ - --cov-report=xml:coverage.xml \ - --cov-config=pyproject.toml - else - uv run --no-sync pytest ${TEST_PATH:?} \ - --tb=short -vv \ - --maxfail="${MAX_FAILURES}" \ - -n "${WORKERS}" \ - --reruns "${RERUNS}" \ - --reruns-delay 1 \ - --dist="${DIST}" \ - --durations=20 \ - --cov=./litellm \ - --cov-report=xml:coverage.xml \ - --cov-config=pyproject.toml - fi - - - name: Save coverage report - if: always() - uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 - with: - name: coverage-${{ inputs.artifact-name }}-${{ github.run_id }}-${{ github.run_attempt }} - path: coverage.xml - retention-days: 1 - - upload-coverage: - name: Upload coverage to Codecov - needs: run - if: always() - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - pull-requests: write - - steps: - - name: Checkout code - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 - with: - persist-credentials: false - - - name: Download coverage report - uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1 - with: - pattern: coverage-${{ inputs.artifact-name }}-${{ github.run_id }}-${{ github.run_attempt }} - path: coverage-reports - merge-multiple: true - - - name: Upload to Codecov - uses: codecov/codecov-action@75cd11691c0faa626561e295848008c8a7dddffe # v5.5.4 - with: - use_oidc: true - directory: coverage-reports - root_dir: ${{ github.workspace }} - flags: ${{ inputs.artifact-name }} - fail_ci_if_error: false diff --git a/.github/workflows/check-ui-api-types.yml b/.github/workflows/check-ui-api-types.yml new file mode 100644 index 00000000000..eeb5545b15e --- /dev/null +++ b/.github/workflows/check-ui-api-types.yml @@ -0,0 +1,84 @@ +name: Check UI API Types Sync + +on: + pull_request: + paths: + - "litellm/proxy/**" + - "litellm/types/**" + - "ui/litellm-dashboard/src/lib/http/schema.d.ts" + - "ui/litellm-dashboard/scripts/gen-api-types.mjs" + - "ui/litellm-dashboard/package.json" + - "ui/litellm-dashboard/package-lock.json" + - ".github/workflows/check-ui-api-types.yml" + +permissions: + contents: read + +jobs: + check-sync: + name: Verify schema.d.ts matches the proxy OpenAPI spec + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout repository + uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + + - name: Set up uv + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + version: "0.10.9" + + - name: Cache uv dependencies + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: | + ~/.cache/uv + .venv + key: ${{ runner.os }}-uv-${{ hashFiles('uv.lock') }} + restore-keys: | + ${{ runner.os }}-uv- + + - name: Install backend dependencies + run: uv sync --frozen --group ci --group proxy-dev --extra google --extra proxy --extra semantic-router + + - name: Generate Prisma client + env: + PRISMA_BINARY_CACHE_DIR: ${{ runner.temp }}/prisma-cache + run: uv run --no-sync prisma generate --schema litellm/proxy/schema.prisma + + - name: Set up Node.js + uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0 + with: + node-version: "20" + cache: "npm" + cache-dependency-path: ui/litellm-dashboard/package-lock.json + + - name: Install dashboard dependencies + working-directory: ui/litellm-dashboard + run: npm ci + + - name: Regenerate types from the live spec + working-directory: ui/litellm-dashboard + env: + LITELLM_PYTHON: "uv run --no-sync python" + run: npm run gen:api + + - name: Fail if types are stale + run: | + if ! git diff --exit-code -- ui/litellm-dashboard/src/lib/http/schema.d.ts; then + echo "::error file=ui/litellm-dashboard/src/lib/http/schema.d.ts::Generated API types are out of sync with the proxy OpenAPI spec." + echo "" + echo "A backend route or model changed without regenerating the dashboard types." + echo "To fix, run from ui/litellm-dashboard:" + echo " npm run gen:api" + echo "then commit the updated src/lib/http/schema.d.ts." + exit 1 + fi + echo "schema.d.ts is in sync with the proxy OpenAPI spec." diff --git a/.github/workflows/conventional-commits.yml b/.github/workflows/conventional-commits.yml new file mode 100644 index 00000000000..69ade24d028 --- /dev/null +++ b/.github/workflows/conventional-commits.yml @@ -0,0 +1,46 @@ +name: Conventional PR Title + +# Squash-merge replaces the merge commit subject with the PR title, so +# enforcing Conventional Commits at the PR-title level is what actually gates +# the commits that land on the default branch. The local commit-msg hook +# (.githooks/commit-msg) is a best-effort assist; this workflow is the gate. +# +# See https://www.conventionalcommits.org/en/v1.0.0/ + +on: + pull_request: + types: [opened, edited, reopened, synchronize, labeled, unlabeled] + +permissions: + pull-requests: read + +jobs: + lint-pr-title: + name: Validate PR title + runs-on: ubuntu-latest + steps: + - name: Check title against Conventional Commits + uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6.1.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + # Must mirror the type list in .githooks/commit-msg. + types: | + feat + fix + docs + style + refactor + perf + test + build + ci + chore + revert + requireScope: false + subjectPattern: ^(?![A-Z]).+$ + subjectPatternError: | + The subject "{subject}" must start with a lowercase character. + # Allow merges/reverts that GitHub generates automatically. + ignoreLabels: | + ignore-semantic-pull-request diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index a726a921a2b..4834775e329 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -52,6 +52,22 @@ jobs: // are stable maintenance releases, not pre-releases. const isPrerelease = /(?:rc|nightly|alpha|beta|[-.]dev)/i.test(tag); + // A stable release should only claim the repo "latest" badge when its + // version is >= the current latest. Otherwise a backport (e.g. 1.84.6) + // would steal "latest" from a newer line (e.g. 1.88.1). + const versionKey = (rawTag) => { + const m = String(rawTag).match(/^v?(\d+)\.(\d+)\.(\d+)/); + if (!m) return null; + const maintenance = String(rawTag).match(/(?:\.post|\.patch\.)(\d+)/i); + return [Number(m[1]), Number(m[2]), Number(m[3]), maintenance ? Number(maintenance[1]) : 0]; + }; + const isAtLeast = (a, b) => { + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return a[i] > b[i]; + } + return true; + }; + const cosignSection = [ `## Verify Docker Image Signature`, ``, @@ -90,6 +106,22 @@ jobs: ].join('\n'); try { + let makeLatest = "false"; + const newVersion = versionKey(tag); + if (!isPrerelease && newVersion) { + let latestVersion = null; + try { + const latest = await github.rest.repos.getLatestRelease({ + owner: context.repo.owner, + repo: context.repo.repo, + }); + latestVersion = versionKey(latest.data.tag_name); + } catch (error) { + if (error.status !== 404) throw error; + } + makeLatest = (!latestVersion || isAtLeast(newVersion, latestVersion)) ? "true" : "false"; + } + const response = await github.rest.repos.createRelease({ draft: true, generate_release_notes: true, @@ -108,6 +140,7 @@ jobs: release_id: response.data.id, body: updatedBody, draft: false, + make_latest: makeLatest, }); } catch (error) { diff --git a/.github/workflows/test-unit-misc.yml b/.github/workflows/test-unit-misc.yml index 9add77ff424..a7363ac3b43 100644 --- a/.github/workflows/test-unit-misc.yml +++ b/.github/workflows/test-unit-misc.yml @@ -28,6 +28,8 @@ jobs: tests/test_litellm/completion_extras tests/test_litellm/containers tests/test_litellm/experimental_mcp_client + tests/test_litellm/models + tests/test_litellm/repositories tests/test_litellm/images tests/test_litellm/interactions tests/test_litellm/passthrough diff --git a/.github/workflows/test-unit-proxy-db.yml b/.github/workflows/test-unit-proxy-db.yml index 2d4e85630dc..2ac9a3b7c1c 100644 --- a/.github/workflows/test-unit-proxy-db.yml +++ b/.github/workflows/test-unit-proxy-db.yml @@ -1,9 +1,10 @@ name: "Unit Tests: Proxy DB Operations" -# Uses DATABASE_URL secret — only runs on trusted branches, not PRs. on: - push: - branches: [main, "litellm_**"] + pull_request: + branches: + - main + - litellm_internal_staging permissions: contents: read @@ -30,9 +31,6 @@ concurrency: # xdist balances its 188 parametrized cases across workers instead of # pinning the whole file to one worker (the default --dist=loadscope # behavior for single-file targets). -# * test_db_schema_migration.py is isolated because one test in it -# (test_aaaasschema_migration_check) takes ~170s — by itself it -# determines the shard's wall-clock floor. jobs: # Fast guard — fails the workflow if a test_*.py file under # tests/proxy_unit_tests/ is not referenced by any matrix entry below. @@ -166,18 +164,6 @@ jobs: dist: loadscope timeout: 15 - # ---- db-and-spend: isolate the 170s schema-migration test ---- - # test_db_schema_migration.py has exactly one test, and that test - # is mostly waiting on `prisma migrate deploy` / `prisma migrate - # diff` subprocesses (~170s). It does no CPU-bound Python work - # inside the test. Running with workers=0 (serial, no xdist) - # skips the 4-worker cold-start cost we'd otherwise pay for a - # single test, saving ~4 minutes of wall-clock. - - test-group: schema-migration - test-path: "tests/proxy_unit_tests/test_db_schema_migration.py" - workers: 0 - dist: loadscope - timeout: 15 - test-group: db-and-spend test-path: >- tests/proxy_unit_tests/test_prisma_client_backoff_retry.py @@ -232,12 +218,11 @@ jobs: workers: 4 dist: loadscope timeout: 15 - uses: ./.github/workflows/_test-unit-services-base.yml + uses: ./.github/workflows/_test-unit-base.yml with: test-path: ${{ matrix.test-path }} workers: ${{ matrix.workers }} reruns: 2 timeout-minutes: ${{ matrix.timeout }} - enable-postgres: true dist: ${{ matrix.dist }} artifact-name: proxy-db-${{ matrix.test-group }} diff --git a/.github/workflows/test-unit-proxy-mgmt-behavior.yml b/.github/workflows/test-unit-proxy-mgmt-behavior.yml deleted file mode 100644 index e73997323a4..00000000000 --- a/.github/workflows/test-unit-proxy-mgmt-behavior.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: "Unit Tests: Proxy Management-Endpoint Behavior Pinning" - -on: - pull_request: - branches: - - main - - litellm_internal_staging - - litellm_oss_branch - - "litellm_**" - -permissions: - contents: read - id-token: write - pull-requests: write - -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -jobs: - proxy-mgmt-behavior: - uses: ./.github/workflows/_test-unit-services-base.yml - with: - test-path: tests/proxy_behavior - # workers=0 (no xdist): the world seed is a single shared Postgres - # state — two xdist workers both call seed_world() and race on the - # ``behavior-pin-budget`` row, producing UniqueViolation + cascading - # missing-membership FK failures. The whole suite is ~7s sequentially, - # so the cost of disabling parallelism here is negligible. - workers: 0 - reruns: 0 - enable-postgres: true - artifact-name: proxy-mgmt-behavior - timeout-minutes: 15 diff --git a/.github/workflows/test-unit-security.yml b/.github/workflows/test-unit-security.yml deleted file mode 100644 index 4ee89897024..00000000000 --- a/.github/workflows/test-unit-security.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: "Unit Tests: Security" - -# Kept push-only (was previously required by DATABASE_URL secret scoping; -# now the postgres credentials are ephemeral localhost values but the -# push-trigger stays to match the proxy-db workflow cadence). -on: - push: - branches: [main, "litellm_**"] - -permissions: - contents: read - id-token: write - pull-requests: write - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - security: - uses: ./.github/workflows/_test-unit-services-base.yml - with: - test-path: "tests/proxy_security_tests/" - workers: 1 - reruns: 2 - timeout-minutes: 20 - enable-postgres: true - artifact-name: security diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c114a838d6d..3d2fa3e51c8 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -240,6 +240,24 @@ graph LR 7. `DBSpendUpdateWriter.update_database()` queues spend increments to Redis 8. Background job `update_spend` flushes queued spend to PostgreSQL every 60s +### Data Access Layer (Models & Repositories) + +Database entities and the operations on them live in two packages at the root of `litellm/` so both the gateway (`proxy/`) and the SDK can use them without importing proxy internals: + +- `litellm/models/` holds the canonical Pydantic definitions for every persisted entity (`LiteLLM_VerificationToken`, `LiteLLM_TeamTable`, `LiteLLM_UserTable`, etc.). `proxy/_types.py` re-exports these for backwards compatibility, so existing imports keep working. +- `litellm/repositories/` holds the data-access layer. `BaseRepository[T]` provides the generic CRUD (`find_by_id`, `find_many`, `create`, `update`, `delete`, `count`, `exists`); entity repositories such as `VerificationTokenRepository`, `TeamRepository`, and `UserRepository` add domain-specific queries and writes on top of it. + +Conventions to follow when touching this layer: + +| Concern | How it's handled | +|---------|------------------| +| JSON columns | Prisma `Json` columns are stored as JSON strings. Repositories `json.dumps()` on write and `json.loads()` on read (see `_to_model` and the `_build_*_data` helpers). | +| Archive-then-delete | `delete_team` / `delete_token` copy the row into the `LiteLLM_Deleted*` table and delete the original inside a single `prisma_client.db.tx()` transaction. Archive payloads are built explicitly so only columns that exist on the archive table are written. | +| Column vs. field names | Where a model field differs from its DB column (for example `org_id` maps to the `organization_id` column), the repository translates in both directions rather than relying on Pydantic to guess. | +| Array mutations | Adds use Prisma's atomic `push` (`add_member`, `add_admin`, `add_models`) to avoid read-modify-write races. Removals fall back to read-modify-write because Prisma has no atomic array remove. | + +To add a new entity, define the model under `litellm/models/`, re-export it from `proxy/_types.py` if existing code imports it from there, and add a repository under `litellm/repositories/` (subclass `BaseRepository` for plain CRUD, or add bespoke methods when the entity needs encryption, archiving, or atomic array updates). Mirror the tests in `tests/test_litellm/repositories/`. + --- ## 2. SDK Request Flow diff --git a/CLAUDE.md b/CLAUDE.md index d2d8601a9c9..758eac7e266 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,7 @@ When you must use real LLM models to, for example, write e2e tests, write a QA r If you're an internal contributor, when creating a new PR, the typical flow is to branch off litellm_internal_staging and create a branch prefixed with litellm_. Do not create a branch prefixed with claude/ and generally do not have / in your branch names -Do not add `Co-Authored-By: Claude` or any Claude attribution to commit messages. Never use a `claude/` prefix or put a `/` in a branch name. Do not add "Generated with Claude Code" (or any similar attribution) to PR descriptions. Do not create a new PR/branch off the existing PR to fix/add something that is related and could've just been committed directly to the existing PR's branch +Do not add `Co-Authored-By: Claude` or any Claude attribution to commit messages. Never use a `claude/` prefix or put a `/` in a branch name. Do not add "Generated with Claude Code" (or any similar attribution) to PR descriptions or comments. Do not create a new PR/branch off the existing PR to fix/add something that is related and could've just been committed directly to the existing PR's branch When working on a PR, keep the PR description in sync with new commits being made @@ -52,6 +52,19 @@ Do not put names of customers or customer company names in code, PRs, and issues CI supply-chain safety: Never pipe a remote script into a shell (`curl ... | bash`, `wget ... | sh`); download the artifact to a file, verify its SHA-256 checksum, then install. Pin every external tool to a specific version with a full URL (not `latest` or `stable`). Verify checksums for all downloaded binaries, using the provider's official `.sha256` / `.sha256sum` sidecar when available. These rules apply to every download in CI +Follow these coding conventions for new/updated code (a three-line fix in a legacy file shouldn't trigger huge drive-by refactors): + +- Composition over inheritance +- Never-nester: early returns over deep nesting +- Don't throw; model failures as values (One function (e.g., raise_public) maps error union to existing public exception contracts via exhaustive match + assert_never) +- No mutation; instead of mutable lists and dicts, prefer tuples, NamedTuples, frozen dataclasses, etc. +- Use dependency injection +- Fully typed; no `Any` or coarse types like dict[str, Any]. Every function parameter must be strongly typed +- Use tagged unions + match +- No monster files or god objects + +Follow conventional commits for commit names and PR titles + ## Think Before Coding **Don't assume. Don't hide confusion. Surface tradeoffs** diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8ac83341f64..2177c764806 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,18 +38,25 @@ Before contributing code to LiteLLM, you must sign our [Contributor License Agre git clone https://github.com/YOUR_USERNAME/litellm.git cd litellm -# Create a new branch for your feature -git checkout -b your-feature-branch +# Create a new branch for your feature (see "Commit and Branch Conventions" below) +git checkout -b feature/your-feature # Install development dependencies make install-dev +# Install git hooks that enforce commit + branch conventions (one-time, opt-in) +make install-hooks + # Verify your setup works make help ``` That's it! Your local development environment is ready. +## Commit and Branch Conventions + +Commits follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) and branches follow [Conventional Branches](https://conventional-branch.github.io/). Run `make install-hooks` once per clone to enable the local git hooks that enforce these — see the [contributor docs](https://docs.litellm.ai/docs/extras/contributing_code#commit-and-branch-conventions) for the full type list, examples, the protected-branch bypass list, and how to opt out. + ### 2. Development Workflow Here's the recommended workflow for making changes: @@ -67,12 +74,12 @@ make lint # Run unit tests to ensure nothing is broken make test-unit -# Commit your changes +# Commit your changes (must follow Conventional Commits — see above) git add . -git commit -m "Your descriptive commit message" +git commit -m "feat(scope): your descriptive commit message" -# Push and create a PR -git push origin your-feature-branch +# Push and create a PR (branch must follow Conventional Branches — see above) +git push origin feature/your-feature ``` ## Adding Testing diff --git a/Dockerfile b/Dockerfile index 9ad9ab31b65..4d55148ff89 100644 --- a/Dockerfile +++ b/Dockerfile @@ -68,22 +68,24 @@ FROM $LITELLM_RUNTIME_IMAGE AS runtime USER root -RUN apk add --no-cache bash openssl tzdata nodejs npm python3 libsndfile && \ - npm install -g npm@11.14.0 tar@7.5.11 glob@13.0.6 @isaacs/brace-expansion@5.0.1 brace-expansion@5.0.5 minimatch@10.2.4 diff@8.0.3 picomatch@4.0.4 && \ - GLOBAL="$(npm root -g)" && \ - for pkg in tar glob @isaacs/brace-expansion brace-expansion minimatch diff picomatch; do \ - name="${pkg##*/}"; \ - find "$GLOBAL/npm" -type d -name "$name" -path "*/node_modules/$pkg" | while read d; do \ - rm -rf "$d" && cp -rL "$GLOBAL/$pkg" "$d"; \ - done; \ - done && \ - npm cache clean --force && \ - { apk del --no-cache npm 2>/dev/null || true; } +# node (without npm) is required by the prisma CLI at runtime +RUN apk add --no-cache bash openssl tzdata nodejs python3 libsndfile WORKDIR /app ENV PATH="/app/.venv/bin:${PATH}" -COPY --from=builder /app /app +# Copy only what runtime needs. The application is installed inside the venv; +# the rest of the builder's /app is source and build metadata that must not +# ship (manifest-scanning tools attribute everything in it to this image). +# entrypoint.sh invokes litellm/proxy/prisma_migration.py by source path. +COPY --from=builder /app/.venv /app/.venv +COPY --from=builder /app/docker /app/docker +COPY --from=builder /app/schema.prisma /app/schema.prisma +COPY --from=builder /app/litellm/proxy/prisma_migration.py /app/litellm/proxy/prisma_migration.py +# enterprise/ is imported by source path at runtime (proxy_cli puts the +# working directory on sys.path; litellm/proxy/hooks resolves +# enterprise.enterprise_hooks from it) +COPY --from=builder /app/enterprise /app/enterprise # Prisma binaries live in $HOME/.cache (default prisma-python location), # which is /root/.cache here. Copy only the Prisma subdirs — copying the # whole /root/.cache drags in the uv build cache (~660 MB, includes a diff --git a/Makefile b/Makefile index a00a90da601..3d7b51bc745 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ test-unit-integrations test-unit-core-utils test-unit-other test-unit-root \ test-proxy-unit-a test-proxy-unit-b test-integration test-unit-helm \ info lint lint-dev format \ - install-dev install-proxy-dev install-test-deps \ + install-dev install-proxy-dev install-test-deps install-hooks \ install-helm-unittest check-circular-imports check-import-safety # Default target @@ -17,6 +17,7 @@ help: @echo " make install-proxy-dev-ci - Install proxy dev dependencies (CI-compatible)" @echo " make install-test-deps - Install the full local test environment" @echo " make install-helm-unittest - Install helm unittest plugin" + @echo " make install-hooks - Install git hooks (Conventional Commits + Branches)" @echo " make format - Apply Black code formatting" @echo " make format-check - Check Black code formatting (matches CI)" @echo " make lint - Run all linting (Ruff, MyPy, Black check, circular imports, import safety)" @@ -68,6 +69,11 @@ install-test-deps: install-proxy-dev install-helm-unittest: helm plugin install https://github.com/helm-unittest/helm-unittest --version v0.4.4 || echo "ignore error if plugin exists" +# Install git hooks that enforce Conventional Commits and Conventional Branches. +# Opt-in: not chained into install-dev. +install-hooks: + ./scripts/install_git_hooks.sh + # Formatting format: install-dev cd litellm && $(UV_RUN) black . && cd .. diff --git a/README.md b/README.md index 9924aeb5829..d600f3952c6 100644 --- a/README.md +++ b/README.md @@ -407,7 +407,7 @@ Support for more providers. Missing a provider or LLM Platform, raise a [feature ### Run in Developer Mode #### Services 1. Setup .env file in root -2. Run dependant services `docker-compose up db prometheus` +2. Run dependent services `docker-compose up db prometheus` #### Backend 1. (In root) create virtual environment `python -m venv .venv` diff --git a/db_scripts/partition_spend_logs.sql b/db_scripts/partition_spend_logs.sql new file mode 100644 index 00000000000..08fcbddb6f8 --- /dev/null +++ b/db_scripts/partition_spend_logs.sql @@ -0,0 +1,99 @@ +-- Converts an existing LiteLLM_SpendLogs table into a native Postgres +-- range-partitioned table keyed on "startTime". +-- +-- Why: at high request volume, retention via DELETE leaves dead tuples that +-- autovacuum cannot reclaim quickly enough, so the table keeps growing on disk +-- (seen at 450GB+ after ~1 month). With partitioning, retention drops whole +-- partitions, which is instant and returns disk to the OS immediately. +-- +-- This is an opt-in, manual operation. The default LiteLLM schema is NOT +-- partitioned, so existing installs are unaffected until you run this. +-- +-- IMPORTANT +-- * Test on a staging copy first and take a backup. +-- * Postgres cannot convert a populated table to partitioned in place, so this +-- renames the old table aside and creates a fresh partitioned table. +-- * The partition key ("startTime") must be part of the primary key, so the +-- PK becomes composite ("request_id", "startTime"). LiteLLM's write path uses +-- INSERT ... ON CONFLICT DO NOTHING, which is compatible with this. +-- * Choose a partition granularity ("day" is the recommended default for +-- high-volume tables) and keep it consistent with SPEND_LOG_PARTITION_INTERVAL. +-- +-- After running this, enable the feature and set a retention period in +-- proxy_config.yaml: +-- general_settings: +-- use_spend_logs_partitioning: true +-- maximum_spend_logs_retention_period: "30d" +-- The spend-log cleanup job then verifies the table is partitioned and reclaims +-- disk by dropping expired partitions instead of deleting rows. It also +-- pre-creates upcoming partitions on each run. To roll back, see +-- db_scripts/unpartition_spend_logs.sql. + +BEGIN; + +ALTER TABLE "LiteLLM_SpendLogs" RENAME TO "LiteLLM_SpendLogs_legacy"; + +-- Renaming a table does NOT rename its indexes, and index names are unique per +-- schema. Move the legacy table's indexes aside so the CREATE INDEX statements +-- below actually create indexes on the new partitioned table instead of being +-- silently skipped by IF NOT EXISTS, and so the new PK keeps the canonical +-- name instead of getting a "_pkey1" suffix. +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_pkey" + RENAME TO "LiteLLM_SpendLogs_legacy_pkey"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_startTime_idx" + RENAME TO "LiteLLM_SpendLogs_legacy_startTime_idx"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_startTime_request_id_idx" + RENAME TO "LiteLLM_SpendLogs_legacy_startTime_request_id_idx"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_end_user_idx" + RENAME TO "LiteLLM_SpendLogs_legacy_end_user_idx"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_session_id_idx" + RENAME TO "LiteLLM_SpendLogs_legacy_session_id_idx"; + +CREATE TABLE "LiteLLM_SpendLogs" ( + LIKE "LiteLLM_SpendLogs_legacy" INCLUDING DEFAULTS INCLUDING GENERATED +) PARTITION BY RANGE ("startTime"); + +ALTER TABLE "LiteLLM_SpendLogs" + ADD PRIMARY KEY ("request_id", "startTime"); + +-- Recreate every index Prisma defines on the table. LIKE ... INCLUDING DEFAULTS +-- INCLUDING GENERATED copies columns and defaults but NOT indexes, so without +-- these the admin-UI cost-reporting queries that filter by end_user/session_id +-- fall back to sequential scans. On a partitioned parent these propagate to +-- every current and future partition automatically. +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_startTime_idx" + ON "LiteLLM_SpendLogs" ("startTime"); + +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_startTime_request_id_idx" + ON "LiteLLM_SpendLogs" ("startTime", "request_id"); + +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_end_user_idx" + ON "LiteLLM_SpendLogs" ("end_user"); + +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_session_id_idx" + ON "LiteLLM_SpendLogs" ("session_id"); + +-- Safety net: any row whose startTime has no explicit partition lands here so +-- writes never fail. The cleanup job never drops the DEFAULT partition. +CREATE TABLE IF NOT EXISTS "LiteLLM_SpendLogs_pdefault" + PARTITION OF "LiteLLM_SpendLogs" DEFAULT; + +COMMIT; + +-- Backfill (optional). Rows route to the correct partition automatically. +-- For large legacy tables, copy in time-bounded batches during a low-traffic +-- window instead of one statement, or simply keep "LiteLLM_SpendLogs_legacy" +-- read-only until its data ages past your retention, then DROP it. +-- +-- Backfilled rows land in the DEFAULT partition until explicit partitions +-- cover their dates. Postgres refuses to create a partition whose range +-- overlaps rows already in DEFAULT, so the cleanup job may log a warning when +-- pre-creating today's partition right after a backfill; it recovers on its +-- own once those dates age out, and future partitions are unaffected because +-- they are always created ahead of writes. +-- +-- INSERT INTO "LiteLLM_SpendLogs" +-- SELECT * FROM "LiteLLM_SpendLogs_legacy" +-- WHERE "startTime" >= now() - interval '30 days'; +-- +-- DROP TABLE "LiteLLM_SpendLogs_legacy"; diff --git a/db_scripts/unpartition_spend_logs.sql b/db_scripts/unpartition_spend_logs.sql new file mode 100644 index 00000000000..0bd82513e4a --- /dev/null +++ b/db_scripts/unpartition_spend_logs.sql @@ -0,0 +1,69 @@ +-- Rolls back db_scripts/partition_spend_logs.sql: converts the native +-- range-partitioned "LiteLLM_SpendLogs" table back into a plain, +-- non-partitioned table matching the default LiteLLM schema. +-- +-- When/why: run this if you want to stop using partition-based retention and +-- return to DELETE-based cleanup, or to restore the original single-column +-- primary key ("request_id") that the partitioned layout had to widen to a +-- composite ("request_id", "startTime"). +-- +-- IMPORTANT +-- * Test on a staging copy first and take a backup. +-- * Postgres cannot convert a partitioned table back in place, so this +-- renames the partitioned table aside and creates a fresh plain table. +-- * The composite PK could in principle hold the same "request_id" in more +-- than one partition, so rows are copied with ON CONFLICT DO NOTHING to +-- restore the single-column PK without failing on such duplicates. +-- * For large tables the INSERT ... SELECT copies every surviving row and may +-- run long; do it during a low-traffic window. +-- * Also remove use_spend_logs_partitioning from proxy_config.yaml (or set it +-- to false) so the cleanup job returns to DELETE-based retention. + +BEGIN; + +ALTER TABLE "LiteLLM_SpendLogs" RENAME TO "LiteLLM_SpendLogs_partitioned"; + +-- Renaming a table does NOT rename its indexes, and index names are unique per +-- schema. Move the partitioned table's indexes aside so the CREATE INDEX +-- statements below actually create indexes on the new plain table instead of +-- being silently skipped by IF NOT EXISTS, and so the new PK keeps the +-- canonical name. +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_pkey" + RENAME TO "LiteLLM_SpendLogs_partitioned_pkey"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_pkey1" + RENAME TO "LiteLLM_SpendLogs_partitioned_pkey1"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_startTime_idx" + RENAME TO "LiteLLM_SpendLogs_partitioned_startTime_idx"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_startTime_request_id_idx" + RENAME TO "LiteLLM_SpendLogs_partitioned_startTime_request_id_idx"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_end_user_idx" + RENAME TO "LiteLLM_SpendLogs_partitioned_end_user_idx"; +ALTER INDEX IF EXISTS "LiteLLM_SpendLogs_session_id_idx" + RENAME TO "LiteLLM_SpendLogs_partitioned_session_id_idx"; + +CREATE TABLE "LiteLLM_SpendLogs" ( + LIKE "LiteLLM_SpendLogs_partitioned" INCLUDING DEFAULTS INCLUDING GENERATED +); + +ALTER TABLE "LiteLLM_SpendLogs" + ADD PRIMARY KEY ("request_id"); + +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_startTime_idx" + ON "LiteLLM_SpendLogs" ("startTime"); + +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_startTime_request_id_idx" + ON "LiteLLM_SpendLogs" ("startTime", "request_id"); + +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_end_user_idx" + ON "LiteLLM_SpendLogs" ("end_user"); + +CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_session_id_idx" + ON "LiteLLM_SpendLogs" ("session_id"); + +INSERT INTO "LiteLLM_SpendLogs" +SELECT * FROM "LiteLLM_SpendLogs_partitioned" +ON CONFLICT ("request_id") DO NOTHING; + +DROP TABLE "LiteLLM_SpendLogs_partitioned"; + +COMMIT; diff --git a/docker/Dockerfile.database b/docker/Dockerfile.database index c84003a065f..e591a4a2adb 100644 --- a/docker/Dockerfile.database +++ b/docker/Dockerfile.database @@ -66,36 +66,31 @@ FROM $LITELLM_RUNTIME_IMAGE AS runtime USER root -RUN apk add --no-cache bash openssl tzdata nodejs npm python3 libsndfile && \ - npm install -g npm@11.12.1 tar@7.5.11 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 && \ - GLOBAL="$(npm root -g)" && \ - find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \ - rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \ - done && \ - find "$GLOBAL/npm" -type d -name "glob" -path "*/node_modules/glob" | while read d; do \ - rm -rf "$d" && cp -rL "$GLOBAL/glob" "$d"; \ - done && \ - find "$GLOBAL/npm" -type d -name "brace-expansion" -path "*/node_modules/@isaacs/brace-expansion" | while read d; do \ - rm -rf "$d" && cp -rL "$GLOBAL/@isaacs/brace-expansion" "$d"; \ - done && \ - find "$GLOBAL/npm" -type d -name "minimatch" -path "*/node_modules/minimatch" | while read d; do \ - rm -rf "$d" && cp -rL "$GLOBAL/minimatch" "$d"; \ - done && \ - find "$GLOBAL/npm" -type d -name "diff" -path "*/node_modules/diff" | while read d; do \ - rm -rf "$d" && cp -rL "$GLOBAL/diff" "$d"; \ - done && \ - npm cache clean --force && \ - { apk del --no-cache npm 2>/dev/null || true; } +# node (without npm) is required by the prisma CLI at runtime +RUN apk add --no-cache bash openssl tzdata nodejs python3 libsndfile WORKDIR /app ENV PATH="/app/.venv/bin:${PATH}" -COPY --from=builder /app /app +# Copy only what runtime needs. The application is installed inside the venv; +# the rest of the builder's /app is source and build metadata that must not +# ship (manifest-scanning tools attribute everything in it to this image). +# entrypoint.sh invokes litellm/proxy/prisma_migration.py by source path. +COPY --from=builder /app/.venv /app/.venv +COPY --from=builder /app/docker /app/docker +COPY --from=builder /app/schema.prisma /app/schema.prisma +COPY --from=builder /app/litellm/proxy/prisma_migration.py /app/litellm/proxy/prisma_migration.py +# enterprise/ is imported by source path at runtime (proxy_cli puts the +# working directory on sys.path; litellm/proxy/hooks resolves +# enterprise.enterprise_hooks from it) +COPY --from=builder /app/enterprise /app/enterprise # Prisma binaries live in $HOME/.cache (default prisma-python location), # which is /root/.cache here. Copy them from the builder so they survive # deployments that volume-mount /app/.cache (e.g. readOnlyRootFilesystem # + emptyDir) — otherwise the mount would shadow the baked-in query engine. -COPY --from=builder /root/.cache /root/.cache +# Only the Prisma subdirs: the whole /root/.cache drags in the uv build cache. +COPY --from=builder /root/.cache/prisma /root/.cache/prisma +COPY --from=builder /root/.cache/prisma-python /root/.cache/prisma-python RUN find /app/.venv -type f -path "*/tornado/test/*" -delete && \ find /app/.venv -type d -path "*/tornado/test" -delete diff --git a/docker/Dockerfile.non_root b/docker/Dockerfile.non_root index 8717e5b3fcd..eafbd23fd90 100644 --- a/docker/Dockerfile.non_root +++ b/docker/Dockerfile.non_root @@ -95,7 +95,21 @@ RUN for i in 1 2 3; do \ apk add --no-cache python3 bash openssl tzdata libsndfile nodejs && break || sleep 5; \ done -COPY --from=builder /app /app +# Copy only what runtime needs. The application is installed inside the venv; +# the rest of the builder's /app is source and build metadata that must not +# ship (manifest-scanning tools attribute everything in it to this image). +# entrypoint.sh invokes litellm/proxy/prisma_migration.py by source path. +# Prisma caches live under /app/.cache here (XDG_CACHE_HOME / +# PRISMA_BINARY_CACHE_DIR) so the runtime prisma generate finds them. +COPY --from=builder /app/.venv /app/.venv +COPY --from=builder /app/docker /app/docker +COPY --from=builder /app/schema.prisma /app/schema.prisma +COPY --from=builder /app/litellm/proxy/prisma_migration.py /app/litellm/proxy/prisma_migration.py +# enterprise/ is imported by source path at runtime (proxy_cli puts the +# working directory on sys.path; litellm/proxy/hooks resolves +# enterprise.enterprise_hooks from it) +COPY --from=builder /app/enterprise /app/enterprise +COPY --from=builder /app/.cache /app/.cache COPY --from=builder /var/lib/litellm/ui /var/lib/litellm/ui COPY --from=builder /var/lib/litellm/assets /var/lib/litellm/assets diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py index ae5905f9cdf..a1f63f388b4 100644 --- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py +++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py @@ -504,7 +504,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints): if retrieve_file_id else False ) - if potential_file_id: + if potential_file_id and "llm_output_file_id," in potential_file_id: model_id = self.get_model_id_from_unified_file_id(potential_file_id) if model_id: data["model"] = model_id @@ -1058,7 +1058,12 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints): return file_id.split("llm_output_file_model_id,")[1].split(";")[0] def get_output_file_id_from_unified_file_id(self, file_id: str) -> str: - return file_id.split("llm_output_file_id,")[1].split(";")[0] + marker = "llm_output_file_id," + if marker not in file_id: + raise ValueError( + f"Unified id does not contain {marker!r}: {file_id[:80]!r}" + ) + return file_id.split(marker, 1)[1].split(";")[0] async def async_post_call_success_hook( self, data: Dict, user_api_key_dict: UserAPIKeyAuth, response: LLMResponseTypes @@ -1099,13 +1104,33 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints): for file_attr in ["output_file_id", "error_file_id"]: file_id_value = getattr(response, file_attr, None) if file_id_value and model_id: - original_file_id = file_id_value - unified_file_id = self.get_unified_output_file_id( - output_file_id=original_file_id, - model_id=model_id, - model_name=resolved_model_name, + decoded_output_file_id = _is_base64_encoded_unified_file_id( + file_id_value ) - setattr(response, file_attr, unified_file_id) + if ( + decoded_output_file_id + and "llm_output_file_id," in decoded_output_file_id + ): + provider_file_id = ( + self.get_output_file_id_from_unified_file_id( + decoded_output_file_id + ) + ) + unified_file_id = file_id_value + elif decoded_output_file_id: + verbose_logger.warning( + f"Skipping {file_attr}={file_id_value!r}: " + "unified id is not a managed file output id" + ) + continue + else: + provider_file_id = file_id_value + unified_file_id = self.get_unified_output_file_id( + output_file_id=provider_file_id, + model_id=model_id, + model_name=resolved_model_name, + ) + setattr(response, file_attr, unified_file_id) # Use llm_router credentials when available. Without credentials, # Azure and other auth-required providers return 500/401. @@ -1125,27 +1150,27 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints): or {} ) file_object = await litellm.afile_retrieve( - file_id=original_file_id, + file_id=provider_file_id, **_creds, ) else: file_object = await litellm.afile_retrieve( custom_llm_provider=model_name.split("/")[0] if model_name and "/" in model_name else "openai", # type: ignore[arg-type] - file_id=original_file_id, + file_id=provider_file_id, ) verbose_logger.debug( - f"Successfully retrieved file object for {file_attr}={original_file_id}" + f"Successfully retrieved file object for {file_attr}={provider_file_id}" ) except Exception as e: verbose_logger.warning( - f"Failed to retrieve file object for {file_attr}={original_file_id}: {str(e)}. Storing with None and will fetch on-demand." + f"Failed to retrieve file object for {file_attr}={provider_file_id}: {str(e)}. Storing with None and will fetch on-demand." ) await self.store_unified_file_id( file_id=unified_file_id, file_object=file_object, litellm_parent_otel_span=user_api_key_dict.parent_otel_span, - model_mappings={model_id: original_file_id}, + model_mappings={model_id: provider_file_id}, user_api_key_dict=user_api_key_dict, ) await self.store_unified_object_id( diff --git a/helm/litellm/templates/backend/deployment.yaml b/helm/litellm/templates/backend/deployment.yaml index 3b59c58c8bf..b355db43540 100644 --- a/helm/litellm/templates/backend/deployment.yaml +++ b/helm/litellm/templates/backend/deployment.yaml @@ -12,9 +12,14 @@ spec: {{- include "litellm.backend.selectorLabels" . | nindent 6 }} template: metadata: - {{- with .Values.backend.podAnnotations }} + {{- if or .Values.gateway.config.create .Values.backend.podAnnotations }} annotations: + {{- if .Values.gateway.config.create }} + checksum/config: {{ include (print $.Template.BasePath "/gateway/configmap.yaml") . | sha256sum }} + {{- end }} + {{- with .Values.backend.podAnnotations }} {{- toYaml . | nindent 8 }} + {{- end }} {{- end }} labels: {{- include "litellm.backend.selectorLabels" . | nindent 8 }} @@ -35,7 +40,17 @@ spec: protocol: TCP env: {{- include "litellm.serverEnv" (dict "root" $ "component" .Values.backend) | nindent 12 }} + {{- if .Values.gateway.config.create }} + - name: CONFIG_FILE_PATH + value: /app/config/config.yaml + {{- end }} {{- include "litellm.envFrom" .Values.backend | nindent 10 }} + {{- if .Values.gateway.config.create }} + volumeMounts: + - name: gateway-config + mountPath: /app/config/config.yaml + subPath: config.yaml + {{- end }} {{- with .Values.backend.livenessProbe }} livenessProbe: {{- toYaml . | nindent 12 }} @@ -46,6 +61,12 @@ spec: {{- end }} resources: {{- toYaml .Values.backend.resources | nindent 12 }} + {{- if .Values.gateway.config.create }} + volumes: + - name: gateway-config + configMap: + name: {{ include "litellm.gateway.fullname" . }}-config + {{- end }} {{- with .Values.backend.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260520120000_add_mcp_env_vars/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260520120000_add_mcp_env_vars/migration.sql new file mode 100644 index 00000000000..08d35cd74a3 --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260520120000_add_mcp_env_vars/migration.sql @@ -0,0 +1,23 @@ +-- AlterTable: add admin-configured env_vars to MCP server table +ALTER TABLE "LiteLLM_MCPServerTable" ADD COLUMN IF NOT EXISTS "env_vars" JSONB DEFAULT '[]'; + +-- CreateTable: per-user env var values for MCP servers +CREATE TABLE IF NOT EXISTS "LiteLLM_MCPUserEnvVars" ( + "id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, + "server_id" TEXT NOT NULL, + "values_b64" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "LiteLLM_MCPUserEnvVars_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "LiteLLM_MCPUserEnvVars_user_id_server_id_key" ON "LiteLLM_MCPUserEnvVars"("user_id", "server_id"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "LiteLLM_MCPUserEnvVars_user_id_idx" ON "LiteLLM_MCPUserEnvVars"("user_id"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "LiteLLM_MCPUserEnvVars_server_id_idx" ON "LiteLLM_MCPUserEnvVars"("server_id"); diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260604120000_add_oauth2_flow_to_mcp_servers/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260604120000_add_oauth2_flow_to_mcp_servers/migration.sql new file mode 100644 index 00000000000..fee6926d963 --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260604120000_add_oauth2_flow_to_mcp_servers/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "LiteLLM_MCPServerTable" ADD COLUMN IF NOT EXISTS "oauth2_flow" TEXT; diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260605182307_add_timeout_to_mcp_server_table/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260605182307_add_timeout_to_mcp_server_table/migration.sql new file mode 100644 index 00000000000..845ad017cbf --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260605182307_add_timeout_to_mcp_server_table/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "LiteLLM_MCPServerTable" ADD COLUMN "timeout" DOUBLE PRECISION; + diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma index c4754ef6117..e21c0016491 100644 --- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma +++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma @@ -311,6 +311,11 @@ model LiteLLM_MCPServerTable { tool_name_to_description Json? @default("{}") extra_headers String[] @default([]) static_headers Json? @default("{}") + // Admin-configured environment variables interpolated into static_headers + // via ${NAME} syntax. Stored as an array of + // {name, value, scope, description}. scope is "global" (value used as-is) + // or "user" (value supplied per-user via LiteLLM_MCPUserEnvVars). + env_vars Json? @default("[]") // Health check status status String? @default("unknown") last_health_check DateTime? @@ -322,6 +327,7 @@ model LiteLLM_MCPServerTable { authorization_url String? token_url String? registration_url String? + oauth2_flow String? allow_all_keys Boolean @default(false) available_on_public_internet Boolean @default(true) delegate_auth_to_upstream Boolean @default(false) @@ -330,6 +336,7 @@ model LiteLLM_MCPServerTable { byok_description String[] @default([]) byok_api_key_help_url String? source_url String? + timeout Float? // BYOM submission lifecycle approval_status String? @default("active") submitted_by String? @@ -364,6 +371,21 @@ model LiteLLM_MCPUserCredentials { @@unique([user_id, server_id]) } +// Per-user environment variable values for MCP servers. +// values_b64 is an encrypted JSON object: {VAR_NAME: "value", ...}. +model LiteLLM_MCPUserEnvVars { + id String @id @default(uuid()) + user_id String + server_id String + values_b64 String + created_at DateTime @default(now()) + updated_at DateTime @default(now()) @updatedAt + + @@unique([user_id, server_id]) + @@index([user_id]) + @@index([server_id]) +} + // Generate Tokens for Proxy model LiteLLM_VerificationToken { token String @id diff --git a/litellm-proxy-extras/pyproject.toml b/litellm-proxy-extras/pyproject.toml index 0654f17ec68..e2a86205fc5 100644 --- a/litellm-proxy-extras/pyproject.toml +++ b/litellm-proxy-extras/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "litellm-proxy-extras" -version = "0.4.73" +version = "0.4.74" description = "Additional files for the LiteLLM Proxy. Reduces the size of the main litellm package." readme = "README.md" requires-python = ">=3.9" @@ -26,7 +26,7 @@ required-version = ">=0.10.9" module-root = "" [tool.commitizen] -version = "0.4.73" +version = "0.4.74" version_files = [ "pyproject.toml:^version", "../pyproject.toml:litellm-proxy-extras==", diff --git a/litellm/__init__.py b/litellm/__init__.py index 98c9dcb5ddf..e5bc785ed3b 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -16,8 +16,17 @@ import os # Load .env before any other litellm imports so env vars (e.g. LITELLM_UI_SESSION_DURATION) are available import dotenv as _dotenv + +def _dev_env_hot_reload_enabled() -> bool: + """The proxy exports this flag when started with ``--reload``. A reloaded + worker is a fresh process that inherits the reloader's environment, so an + edited ``.env`` value stays masked by the stale inherited one unless we + let the file win; overriding makes the edit take effect on reload.""" + return os.getenv("LITELLM_DEV_ENV_HOT_RELOAD") == "True" + + if os.getenv("LITELLM_MODE", "DEV") == "DEV": - _dotenv.load_dotenv() + _dotenv.load_dotenv(override=_dev_env_hot_reload_enabled()) from typing import ( Callable, @@ -34,6 +43,7 @@ from typing import ( Type, ) from litellm.types.integrations.datadog import DatadogInitParams +from litellm.types.integrations.newrelic import NewRelicInitParams from litellm._logging import ( set_verbose, _turn_on_debug, @@ -145,10 +155,12 @@ _custom_logger_compatible_callbacks_literal = Literal[ "gitlab", "cloudzero", "focus", + "mavvrik", "vantage", "posthog", "levo", "compression_interception", + "newrelic", ] cold_storage_custom_logger: Optional[_custom_logger_compatible_callbacks_literal] = None logged_real_time_event_types: Optional[Union[List[str], Literal["*"]]] = None @@ -350,6 +362,9 @@ enable_gemini_default_thinking_level_low: bool = ( #################### logging: bool = True enable_loadbalancing_on_batch_endpoints: Optional[bool] = None +require_managed_files: bool = ( + False # proxy only - require target_model_names on POST /v1/files +) enable_caching_on_provider_specific_optional_params: bool = ( False # feature-flag for caching on optional params - e.g. 'top_k' ) @@ -403,6 +418,7 @@ s3_callback_params: Optional[Dict] = None s3_audit_callback_params: Optional[Dict] = None datadog_llm_observability_params: Optional[Union[DatadogLLMObsInitParams, Dict]] = None datadog_params: Optional[Union[DatadogInitParams, Dict]] = None +newrelic_params: Optional[Union[NewRelicInitParams, Dict]] = None aws_sqs_callback_params: Optional[Dict] = None generic_logger_headers: Optional[Dict] = None default_key_generate_params: Optional[Dict] = None @@ -433,6 +449,13 @@ custom_prometheus_metadata_labels: List[str] = [] custom_prometheus_tags: List[str] = [] prometheus_metrics_config: Optional[List] = None prometheus_emit_stream_label: bool = False +# Opt-in: emit `rate_limit_category` and `rate_limit_type` labels on +# `litellm_proxy_failed_requests_metric`. Off by default to preserve the +# pre-unification label set so existing dashboards / recording rules keyed on +# that metric keep matching after upgrade. Enable when downstream consumers +# are ready to split 429s by source (vendor vs. litellm) and dimension +# (RPM/TPM/concurrent/budget). +prometheus_emit_rate_limit_labels: bool = False prometheus_user_budget_label_include_email_alias: bool = False prometheus_end_user_metrics_max_series_per_metric: Optional[int] = 10000 prometheus_end_user_metrics_ttl_seconds: Optional[float] = 3600.0 @@ -612,6 +635,7 @@ cerebras_models: Set = set() galadriel_models: Set = set() nvidia_nim_models: Set = set() nvidia_riva_models: Set = set() +soniox_models: Set = set() sambanova_models: Set = set() sambanova_embedding_models: Set = set() novita_models: Set = set() @@ -844,6 +868,8 @@ def add_known_models(model_cost_map: Optional[Dict] = None): nvidia_nim_models.add(key) elif value.get("litellm_provider") == "nvidia_riva": nvidia_riva_models.add(key) + elif value.get("litellm_provider") == "soniox": + soniox_models.add(key) elif value.get("litellm_provider") == "sambanova": sambanova_models.add(key) elif value.get("litellm_provider") == "sambanova-embedding-models": @@ -1009,6 +1035,7 @@ model_list = list( | galadriel_models | nvidia_nim_models | nvidia_riva_models + | soniox_models | sambanova_models | azure_text_models | novita_models @@ -1109,6 +1136,7 @@ models_by_provider: dict = { "galadriel": galadriel_models, "nvidia_nim": nvidia_nim_models, "nvidia_riva": nvidia_riva_models, + "soniox": soniox_models, "sambanova": sambanova_models | sambanova_embedding_models, "novita": novita_models, "nebius": nebius_models | nebius_embedding_models, @@ -1289,6 +1317,8 @@ from .exceptions import ( NotFoundError, PermissionDeniedError, RateLimitError, + RateLimitErrorCategory, + RateLimitType, ServiceUnavailableError, BadGatewayError, OpenAIError, @@ -1350,6 +1380,7 @@ from .search.main import * from .realtime_api.main import ( _arealtime, acreate_realtime_client_secret, + acreate_realtime_transcription_session, arealtime_calls, ) from .responses.main import _aresponses_websocket @@ -1740,6 +1771,9 @@ if TYPE_CHECKING: from .llms.openrouter.responses.transformation import ( OpenRouterResponsesAPIConfig as OpenRouterResponsesAPIConfig, ) + from .llms.bedrock_mantle.responses.transformation import ( + BedrockMantleResponsesAPIConfig as BedrockMantleResponsesAPIConfig, + ) from .llms.gemini.interactions.transformation import ( GoogleAIStudioInteractionsConfig as GoogleAIStudioInteractionsConfig, ) diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py index bdc3289b87c..bace54ffad1 100644 --- a/litellm/_lazy_imports_registry.py +++ b/litellm/_lazy_imports_registry.py @@ -237,6 +237,7 @@ LLM_CONFIG_NAMES = ( "PerplexityResponsesConfig", "DatabricksResponsesAPIConfig", "OpenRouterResponsesAPIConfig", + "BedrockMantleResponsesAPIConfig", "GoogleAIStudioInteractionsConfig", "OpenAIOSeriesConfig", "AnthropicSkillsConfig", @@ -320,6 +321,7 @@ LLM_CONFIG_NAMES = ( "LemonadeChatConfig", "SnowflakeEmbeddingConfig", "AmazonNovaChatConfig", + "SonioxAudioTranscriptionConfig", ) # Types that support lazy loading via _lazy_import_types @@ -958,6 +960,10 @@ _LLM_CONFIGS_IMPORT_MAP = { ".llms.openrouter.responses.transformation", "OpenRouterResponsesAPIConfig", ), + "BedrockMantleResponsesAPIConfig": ( + ".llms.bedrock_mantle.responses.transformation", + "BedrockMantleResponsesAPIConfig", + ), "GoogleAIStudioInteractionsConfig": ( ".llms.gemini.interactions.transformation", "GoogleAIStudioInteractionsConfig", @@ -1190,6 +1196,10 @@ _LLM_CONFIGS_IMPORT_MAP = { ".llms.amazon_nova.chat.transformation", "AmazonNovaChatConfig", ), + "SonioxAudioTranscriptionConfig": ( + ".llms.soniox.audio_transcription.transformation", + "SonioxAudioTranscriptionConfig", + ), } # Import map for utils module lazy imports diff --git a/litellm/a2a_protocol/litellm_completion_bridge/handler.py b/litellm/a2a_protocol/litellm_completion_bridge/handler.py index 52e471ff702..a3502f21f95 100644 --- a/litellm/a2a_protocol/litellm_completion_bridge/handler.py +++ b/litellm/a2a_protocol/litellm_completion_bridge/handler.py @@ -19,6 +19,7 @@ from litellm.a2a_protocol.litellm_completion_bridge.transformation import ( A2AStreamingContext, ) from litellm.a2a_protocol.providers.config_manager import A2AProviderConfigManager +from litellm.interactions.agents.utils import merge_agent_headers # litellm_params key carrying the authenticated principal (hashed virtual key) so # A2A provider configs can scope provider-side state (e.g. LangFlow session memory) @@ -48,6 +49,7 @@ class A2ACompletionBridgeHandler: params: Dict[str, Any], litellm_params: Dict[str, Any], api_base: Optional[str] = None, + agent_extra_headers: Optional[Dict[str, str]] = None, *, _skip_a2a_provider_routing: bool = False, ) -> Dict[str, Any]: @@ -59,6 +61,8 @@ class A2ACompletionBridgeHandler: params: A2A MessageSendParams containing the message litellm_params: Agent's litellm_params (custom_llm_provider, model, etc.) api_base: API base URL from agent_card_params + agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and + admin extra_headers) to forward on the upstream HTTP call. Returns: A2A SendMessageResponse dict @@ -80,6 +84,7 @@ class A2ACompletionBridgeHandler: params=params, api_base=api_base, litellm_params=litellm_params, + agent_extra_headers=agent_extra_headers, ) # Extract message from params @@ -106,7 +111,7 @@ class A2ACompletionBridgeHandler: ) # Build completion params dict - completion_params = { + completion_params: Dict[str, Any] = { "model": full_model, "messages": openai_messages, "api_base": api_base, @@ -128,6 +133,12 @@ class A2ACompletionBridgeHandler: params=params, ) + if agent_extra_headers: + completion_params["extra_headers"] = merge_agent_headers( + dynamic_headers=agent_extra_headers, + static_headers=completion_params.get("extra_headers"), + ) + # Call litellm.acompletion response = await litellm.acompletion(**completion_params) @@ -149,6 +160,7 @@ class A2ACompletionBridgeHandler: params: Dict[str, Any], litellm_params: Dict[str, Any], api_base: Optional[str] = None, + agent_extra_headers: Optional[Dict[str, str]] = None, *, _skip_a2a_provider_routing: bool = False, ) -> AsyncIterator[Dict[str, Any]]: @@ -166,6 +178,8 @@ class A2ACompletionBridgeHandler: params: A2A MessageSendParams containing the message litellm_params: Agent's litellm_params (custom_llm_provider, model, etc.) api_base: API base URL from agent_card_params + agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and + admin extra_headers) to forward on the upstream HTTP call. Yields: A2A streaming response events @@ -187,6 +201,7 @@ class A2ACompletionBridgeHandler: params=params, api_base=api_base, litellm_params=litellm_params, + agent_extra_headers=agent_extra_headers, ): yield chunk @@ -222,7 +237,7 @@ class A2ACompletionBridgeHandler: ) # Build completion params dict - completion_params = { + completion_params: Dict[str, Any] = { "model": full_model, "messages": openai_messages, "api_base": api_base, @@ -244,6 +259,12 @@ class A2ACompletionBridgeHandler: params=params, ) + if agent_extra_headers: + completion_params["extra_headers"] = merge_agent_headers( + dynamic_headers=agent_extra_headers, + static_headers=completion_params.get("extra_headers"), + ) + # 1. Emit initial task event (kind: "task", status: "submitted") task_event = A2ACompletionBridgeTransformation.create_task_event(ctx) yield task_event @@ -305,6 +326,7 @@ async def handle_a2a_completion( params: Dict[str, Any], litellm_params: Dict[str, Any], api_base: Optional[str] = None, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """Convenience function for non-streaming A2A completion.""" return await A2ACompletionBridgeHandler.handle_non_streaming( @@ -312,6 +334,7 @@ async def handle_a2a_completion( params=params, litellm_params=litellm_params, api_base=api_base, + agent_extra_headers=agent_extra_headers, ) @@ -320,6 +343,7 @@ async def handle_a2a_completion_streaming( params: Dict[str, Any], litellm_params: Dict[str, Any], api_base: Optional[str] = None, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> AsyncIterator[Dict[str, Any]]: """Convenience function for streaming A2A completion.""" async for chunk in A2ACompletionBridgeHandler.handle_streaming( @@ -327,5 +351,6 @@ async def handle_a2a_completion_streaming( params=params, litellm_params=litellm_params, api_base=api_base, + agent_extra_headers=agent_extra_headers, ): yield chunk diff --git a/litellm/a2a_protocol/main.py b/litellm/a2a_protocol/main.py index 6979e1ac659..dcb5cb74ec4 100644 --- a/litellm/a2a_protocol/main.py +++ b/litellm/a2a_protocol/main.py @@ -132,6 +132,7 @@ async def _send_message_via_completion_bridge( custom_llm_provider: str, api_base: Optional[str], litellm_params: Dict[str, Any], + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> LiteLLMSendMessageResponse: """ Route a send_message through the LiteLLM completion bridge (e.g. LangGraph, Bedrock AgentCore). @@ -157,6 +158,7 @@ async def _send_message_via_completion_bridge( params=params, litellm_params=litellm_params, api_base=api_base, + agent_extra_headers=agent_extra_headers, ) return LiteLLMSendMessageResponse.from_dict( @@ -283,6 +285,7 @@ async def asend_message( custom_llm_provider=custom_llm_provider, api_base=api_base, litellm_params=litellm_params, + agent_extra_headers=agent_extra_headers, ) # Standard A2A client flow @@ -509,6 +512,7 @@ async def asend_message_streaming( # noqa: PLR0915 params=params, litellm_params=litellm_params, api_base=api_base, + agent_extra_headers=agent_extra_headers, ): yield chunk return diff --git a/litellm/a2a_protocol/providers/bedrock_agentcore/config.py b/litellm/a2a_protocol/providers/bedrock_agentcore/config.py index 679e19c23cd..e7f38c6488c 100644 --- a/litellm/a2a_protocol/providers/bedrock_agentcore/config.py +++ b/litellm/a2a_protocol/providers/bedrock_agentcore/config.py @@ -37,6 +37,7 @@ class BedrockAgentCoreA2AConfig(BaseA2AProviderConfig): request_id=request_id, params=params, litellm_params=litellm_params, + agent_extra_headers=kwargs.get("agent_extra_headers"), ) async def handle_streaming( @@ -57,5 +58,6 @@ class BedrockAgentCoreA2AConfig(BaseA2AProviderConfig): request_id=request_id, params=params, litellm_params=litellm_params, + agent_extra_headers=kwargs.get("agent_extra_headers"), ): yield chunk diff --git a/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py b/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py index 11676aaa895..2f93895099b 100644 --- a/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py +++ b/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py @@ -6,7 +6,7 @@ completion bridge that would otherwise strip the envelope. """ import json -from typing import Any, AsyncIterator, Dict, cast +from typing import Any, AsyncIterator, Dict, Optional, cast from litellm._logging import verbose_logger from litellm.a2a_protocol.providers.bedrock_agentcore.transformation import ( @@ -29,6 +29,7 @@ class BedrockAgentCoreA2AHandler: request_id: str, params: Dict[str, Any], litellm_params: Dict[str, Any], + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """ Handle non-streaming A2A request to AgentCore. @@ -37,6 +38,8 @@ class BedrockAgentCoreA2AHandler: request_id: A2A JSON-RPC request ID params: A2A MessageSendParams containing the message litellm_params: Agent's litellm_params (model, api_key, etc.) + agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and + admin extra_headers) to forward on the upstream HTTP call. Returns: A2A JSON-RPC response dict from the AgentCore agent @@ -47,6 +50,7 @@ class BedrockAgentCoreA2AHandler: params=params, litellm_params=litellm_params, method="message/send", + agent_extra_headers=agent_extra_headers, ) ) @@ -77,6 +81,7 @@ class BedrockAgentCoreA2AHandler: request_id: str, params: Dict[str, Any], litellm_params: Dict[str, Any], + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> AsyncIterator[Dict[str, Any]]: """ Handle streaming A2A request to AgentCore. @@ -85,6 +90,8 @@ class BedrockAgentCoreA2AHandler: request_id: A2A JSON-RPC request ID params: A2A MessageSendParams containing the message litellm_params: Agent's litellm_params (model, api_key, etc.) + agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and + admin extra_headers) to forward on the upstream HTTP call. Yields: A2A streaming response events from the AgentCore agent @@ -96,6 +103,7 @@ class BedrockAgentCoreA2AHandler: litellm_params=litellm_params, method="message/send", stream=True, + agent_extra_headers=agent_extra_headers, ) ) diff --git a/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py b/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py index 44dc10fe2b7..f868845bb58 100644 --- a/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py +++ b/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py @@ -6,11 +6,66 @@ and signs requests via AmazonAgentCoreConfig (SigV4 or JWT). """ import json -from typing import Any, AsyncIterator, Dict, Tuple +from typing import Any, AsyncIterator, Dict, Mapping, Optional, Tuple from litellm._logging import verbose_logger from litellm.llms.bedrock.chat.agentcore.transformation import AmazonAgentCoreConfig +# Reserved outbound header names that must never be sourced from per-request +# ``agent_extra_headers`` for AgentCore requests. ``agent_extra_headers`` carries +# values rewritten from the client-controlled ``x-a2a-{agent}-*`` convention, so +# allowing these would let any caller with access to the agent spoof the AWS +# request identity / SigV4 metadata by overwriting headers the proxy sets from +# trusted server-side config. +# +# The runtime headers (session / user id) are derived server-side from +# ``runtimeSessionId`` / ``runtimeUserId`` in the agent's ``litellm_params``; +# ``authorization`` is set by the AgentCore signer (JWT or SigV4); ``host`` and +# the ``x-amz-*`` family are owned by SigV4 itself. +_RESERVED_EXACT_HEADERS = frozenset( + { + "authorization", + "host", + } +) +_RESERVED_PREFIX_HEADERS: Tuple[str, ...] = ( + "x-amzn-bedrock-agentcore-runtime-", + "x-amz-", +) + + +def _filter_reserved_headers( + agent_extra_headers: Optional[Mapping[str, str]], +) -> Optional[Dict[str, str]]: + """ + Strip reserved AWS / AgentCore headers from caller-supplied + ``agent_extra_headers`` before they are merged into the signed request. + + Returns ``None`` if the result is empty. + """ + if not agent_extra_headers: + return None + + filtered: Dict[str, str] = {} + dropped: list = [] + for k, v in agent_extra_headers.items(): + k_lower = k.lower() + if k_lower in _RESERVED_EXACT_HEADERS or any( + k_lower.startswith(prefix) for prefix in _RESERVED_PREFIX_HEADERS + ): + dropped.append(k) + continue + filtered[k] = v + + if dropped: + verbose_logger.warning( + "BedrockAgentCore A2A: dropping reserved header(s) from " + "agent_extra_headers (not forwarded to AgentCore): %s", + sorted(dropped), + ) + + return filtered or None + class BedrockAgentCoreA2ATransformation: """ @@ -27,6 +82,7 @@ class BedrockAgentCoreA2ATransformation: litellm_params: Dict[str, Any], method: str = "message/send", stream: bool = False, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Tuple[str, dict, bytes]: """ Build the AgentCore URL, construct a JSON-RPC envelope, and sign the request. @@ -37,6 +93,15 @@ class BedrockAgentCoreA2ATransformation: litellm_params: Agent's litellm_params (model, api_key, etc.) method: JSON-RPC method name (default: "message/send") stream: Whether this is a streaming request + agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and + admin extra_headers) to forward on the upstream HTTP call. Merged into + the headers dict before signing so SigV4 includes them in the signature. + Reserved AWS / AgentCore identity headers (``authorization``, ``host``, + ``x-amzn-bedrock-agentcore-runtime-*``, ``x-amz-*``) are filtered out + here to prevent a caller-controlled ``x-a2a-{agent}-*`` header from + spoofing the AgentCore runtime user id or other SigV4 metadata. Use + ``api_key`` / ``runtimeUserId`` / ``runtimeSessionId`` in litellm_params + (not ``agent_extra_headers``) to override those values. Returns: Tuple of (url, signed_headers, signed_body_bytes) @@ -85,6 +150,13 @@ class BedrockAgentCoreA2ATransformation: if runtime_user_id: headers["X-Amzn-Bedrock-AgentCore-Runtime-User-Id"] = runtime_user_id + # Merge per-request agent headers before signing so SigV4 covers them. + # Reserved headers are stripped first to prevent client-controlled values + # from spoofing the AgentCore runtime identity / SigV4 metadata. + safe_extra_headers = _filter_reserved_headers(agent_extra_headers) + if safe_extra_headers: + headers.update(safe_extra_headers) + # Sign the request (SigV4 or JWT depending on api_key presence) signed_headers, signed_body = agentcore_config.sign_request( headers=headers, diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py index 2f16779cc9f..6f067aecd2b 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py @@ -31,6 +31,7 @@ class PydanticAIProviderConfig(BaseA2AProviderConfig): params=params, api_base=api_base, timeout=kwargs.get("timeout", 60.0), + agent_extra_headers=kwargs.get("agent_extra_headers"), ) async def handle_streaming( @@ -50,5 +51,6 @@ class PydanticAIProviderConfig(BaseA2AProviderConfig): timeout=kwargs.get("timeout", 60.0), chunk_size=kwargs.get("chunk_size", 50), delay_ms=kwargs.get("delay_ms", 10), + agent_extra_headers=kwargs.get("agent_extra_headers"), ): yield chunk diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py index 5b8d6b94ff2..b5d3f262a63 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py @@ -28,6 +28,7 @@ class PydanticAIHandler: params: Dict[str, Any], api_base: Optional[str] = None, timeout: float = 60.0, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """ Handle non-streaming request to Pydantic AI agent. @@ -37,6 +38,8 @@ class PydanticAIHandler: params: A2A MessageSendParams containing the message api_base: Base URL of the Pydantic AI agent timeout: Request timeout in seconds + agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and + admin extra_headers) to forward on the upstream HTTP call. Returns: A2A SendMessageResponse dict @@ -51,6 +54,7 @@ class PydanticAIHandler: request_id=request_id, params=params, timeout=timeout, + agent_extra_headers=agent_extra_headers, ) return response_data @@ -63,6 +67,7 @@ class PydanticAIHandler: timeout: float = 60.0, chunk_size: int = 50, delay_ms: int = 10, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> AsyncIterator[Dict[str, Any]]: """ Handle streaming request to Pydantic AI agent with fake streaming. @@ -78,6 +83,8 @@ class PydanticAIHandler: timeout: Request timeout in seconds chunk_size: Number of characters per chunk delay_ms: Delay between chunks in milliseconds + agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and + admin extra_headers) to forward on the upstream HTTP call. Yields: A2A streaming response events @@ -94,6 +101,7 @@ class PydanticAIHandler: request_id=request_id, params=params, timeout=timeout, + agent_extra_headers=agent_extra_headers, ) # Convert raw task response to fake streaming chunks diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py index bf68a01d98c..8fac43e7ae1 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py @@ -6,7 +6,7 @@ This module provides fake streaming by converting non-streaming responses into s """ import asyncio -from typing import Any, AsyncIterator, Dict, cast +from typing import Any, AsyncIterator, Dict, Optional, cast from uuid import uuid4 from litellm._logging import verbose_logger @@ -86,6 +86,7 @@ class PydanticAITransformation: request_id: str, max_attempts: int = 30, poll_interval: float = 0.5, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """ Poll for task completion using tasks/get method. @@ -112,7 +113,10 @@ class PydanticAITransformation: response = await client.post( endpoint, json=poll_request, - headers={"Content-Type": "application/json"}, + headers={ + **(agent_extra_headers or {}), + "Content-Type": "application/json", + }, ) response.raise_for_status() poll_data = response.json() @@ -142,6 +146,7 @@ class PydanticAITransformation: request_id: str, params: Any, timeout: float = 60.0, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """ Send a request to Pydantic AI agent and return the raw task response. @@ -189,7 +194,10 @@ class PydanticAITransformation: response = await client.post( endpoint, json=a2a_request, - headers={"Content-Type": "application/json"}, + headers={ + **(agent_extra_headers or {}), + "Content-Type": "application/json", + }, ) response.raise_for_status() response_data = response.json() @@ -211,6 +219,7 @@ class PydanticAITransformation: endpoint=endpoint, task_id=task_id, request_id=request_id, + agent_extra_headers=agent_extra_headers, ) verbose_logger.info( @@ -225,6 +234,7 @@ class PydanticAITransformation: request_id: str, params: Any, timeout: float = 60.0, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """ Send a non-streaming A2A request to Pydantic AI agent and wait for completion. @@ -234,6 +244,7 @@ class PydanticAITransformation: request_id: A2A JSON-RPC request ID params: A2A MessageSendParams containing the message (dict or Pydantic model) timeout: Request timeout in seconds + agent_extra_headers: Per-request headers to forward on the upstream HTTP call. Returns: Standard A2A non-streaming response format with message @@ -244,6 +255,7 @@ class PydanticAITransformation: request_id=request_id, params=params, timeout=timeout, + agent_extra_headers=agent_extra_headers, ) # Transform to standard A2A non-streaming format @@ -258,6 +270,7 @@ class PydanticAITransformation: request_id: str, params: Any, timeout: float = 60.0, + agent_extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """ Send a request to Pydantic AI agent and return the raw task response. @@ -269,6 +282,7 @@ class PydanticAITransformation: request_id: A2A JSON-RPC request ID params: A2A MessageSendParams containing the message timeout: Request timeout in seconds + agent_extra_headers: Per-request headers to forward on the upstream HTTP call. Returns: Raw Pydantic AI task response (with history/artifacts) @@ -278,6 +292,7 @@ class PydanticAITransformation: request_id=request_id, params=params, timeout=timeout, + agent_extra_headers=agent_extra_headers, ) @staticmethod diff --git a/litellm/anthropic_beta_headers_config.json b/litellm/anthropic_beta_headers_config.json index d02afe37569..a0d63f5043c 100644 --- a/litellm/anthropic_beta_headers_config.json +++ b/litellm/anthropic_beta_headers_config.json @@ -129,7 +129,7 @@ "bash_20241022": null, "bash_20250124": null, "code-execution-2025-08-25": null, - "compact-2026-01-12": null, + "compact-2026-01-12": "compact-2026-01-12", "computer-use-2025-01-24": "computer-use-2025-01-24", "computer-use-2025-11-24": "computer-use-2025-11-24", "context-1m-2025-08-07": "context-1m-2025-08-07", diff --git a/litellm/caching/caching.py b/litellm/caching/caching.py index 11733ce4cee..b6cfc8e7907 100644 --- a/litellm/caching/caching.py +++ b/litellm/caching/caching.py @@ -309,9 +309,13 @@ class Cache: param_value = kwargs[param] cache_key += f"{str(param)}: {str(param_value)}" - verbose_logger.debug("\nCreated cache key: %s", cache_key) hashed_cache_key = Cache._get_hashed_cache_key(cache_key) hashed_cache_key = self._add_namespace_to_cache_key(hashed_cache_key, **kwargs) + verbose_logger.debug( + "\nCreated cache key: %s (source material length: %d)", + hashed_cache_key, + len(cache_key), + ) # Remove preset_cache_key from kwargs to avoid "got multiple values" TypeError # when kwargs already contains preset_cache_key from upstream callers kwargs_for_preset = {k: v for k, v in kwargs.items() if k != "preset_cache_key"} @@ -497,6 +501,34 @@ class Cache: return cached_response return cached_result + @staticmethod + def _get_safe_cache_lookup_kwargs(kwargs: Dict[str, Any]) -> Dict[str, Any]: + cache_lookup_kwargs: Dict[str, Any] = {} + for prompt_kwarg in ("messages", "input"): + if prompt_kwarg in kwargs: + cache_lookup_kwargs[prompt_kwarg] = kwargs[prompt_kwarg] + + if isinstance(kwargs.get("metadata"), dict): + cache_lookup_kwargs["metadata"] = {} + + return cache_lookup_kwargs + + @staticmethod + def _update_metadata_from_cache_lookup_kwargs( + original_kwargs: Dict[str, Any], cache_lookup_kwargs: Dict[str, Any] + ) -> None: + original_metadata = original_kwargs.get("metadata") + cache_lookup_metadata = cache_lookup_kwargs.get("metadata") + if not isinstance(original_metadata, dict) or not isinstance( + cache_lookup_metadata, dict + ): + return + + if "semantic-similarity" in cache_lookup_metadata: + original_metadata["semantic-similarity"] = cache_lookup_metadata[ + "semantic-similarity" + ] + def get_cache(self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs): """ Retrieves the cached result for the given arguments. @@ -511,7 +543,6 @@ class Cache: try: # never block execution if self.should_use_cache(**kwargs) is not True: return - messages = kwargs.get("messages", []) if "cache_key" in kwargs: cache_key = kwargs["cache_key"] else: @@ -523,12 +554,19 @@ class Cache: or cache_control_args.get("s-max-age") or float("inf") ) + cache_lookup_kwargs = self._get_safe_cache_lookup_kwargs(kwargs) if dynamic_cache_object is not None: cached_result = dynamic_cache_object.get_cache( - cache_key, messages=messages + cache_key, **cache_lookup_kwargs ) else: - cached_result = self.cache.get_cache(cache_key, messages=messages) + cached_result = self.cache.get_cache( + cache_key, **cache_lookup_kwargs + ) + self._update_metadata_from_cache_lookup_kwargs( + original_kwargs=kwargs, + cache_lookup_kwargs=cache_lookup_kwargs, + ) return self._get_cache_logic( cached_result=cached_result, max_age=max_age ) @@ -549,7 +587,6 @@ class Cache: if self.should_use_cache(**kwargs) is not True: return - kwargs.get("messages", []) if "cache_key" in kwargs: cache_key = kwargs["cache_key"] else: @@ -654,6 +691,7 @@ class Cache: self, embedding_response: Any, model: Optional[str], + prompt_tokens: Optional[int] = None, prompt_tokens_details: Optional[dict] = None, ) -> CachedEmbedding: """ @@ -666,6 +704,7 @@ class Cache: "index": embedding_response.get("index"), "object": embedding_response.get("object"), "model": model, + "prompt_tokens": prompt_tokens, "prompt_tokens_details": prompt_tokens_details, } elif hasattr(embedding_response, "model_dump"): @@ -675,6 +714,7 @@ class Cache: "index": data.get("index"), "object": data.get("object"), "model": model, + "prompt_tokens": prompt_tokens, "prompt_tokens_details": prompt_tokens_details, } else: @@ -684,6 +724,7 @@ class Cache: "index": data.get("index"), "object": data.get("object"), "model": model, + "prompt_tokens": prompt_tokens, "prompt_tokens_details": prompt_tokens_details, } except KeyError as e: @@ -732,6 +773,29 @@ class Cache: per_item[key] = value return per_item if per_item else None + def _get_per_item_prompt_tokens( + self, + result: EmbeddingResponse, + idx_in_result_data: int, + ) -> Optional[int]: + """ + Extract the per-item prompt_tokens from a response for caching. + + Single-item responses store the full usage.prompt_tokens. Multi-item + responses distribute it evenly (with remainder) so that summing all + per-item values on retrieval reconstructs the original total. + """ + if result.usage is None or result.usage.prompt_tokens is None: + return None + + total = result.usage.prompt_tokens + num_items = len(result.data) + if num_items <= 1: + return total + + quotient, remainder = divmod(total, num_items) + return quotient + (1 if idx_in_result_data < remainder else 0) + def add_embedding_response_to_cache( self, result: EmbeddingResponse, @@ -743,7 +807,11 @@ class Cache: kwargs["cache_key"] = preset_cache_key embedding_response = result.data[idx_in_result_data] - # Extract per-item prompt_tokens_details from response usage + # Extract per-item prompt_tokens + details from response usage + prompt_tokens = self._get_per_item_prompt_tokens( + result=result, + idx_in_result_data=idx_in_result_data, + ) prompt_tokens_details = self._get_per_item_prompt_tokens_details( result=result, idx_in_result_data=idx_in_result_data, @@ -754,6 +822,7 @@ class Cache: embedding_dict: CachedEmbedding = self._convert_to_cached_embedding( embedding_response, model_name, + prompt_tokens=prompt_tokens, prompt_tokens_details=prompt_tokens_details, ) diff --git a/litellm/caching/caching_handler.py b/litellm/caching/caching_handler.py index 3f4e54382c9..48691335b40 100644 --- a/litellm/caching/caching_handler.py +++ b/litellm/caching/caching_handler.py @@ -394,7 +394,7 @@ class LLMCachingHandler: return cr["model"] return None - def _process_async_embedding_cached_response( + def _process_async_embedding_cached_response( # noqa: PLR0915 self, final_embedding_cached_response: Optional[EmbeddingResponse], cached_result: List[Optional[CachedEmbedding]], @@ -456,7 +456,10 @@ class LLMCachingHandler: index=idx, object="embedding", ) - if isinstance(kwargs_input_as_list[idx], str): + cached_prompt_tokens = cr.get("prompt_tokens") + if cached_prompt_tokens is not None: + prompt_tokens += cached_prompt_tokens + elif isinstance(kwargs_input_as_list[idx], str): from litellm.utils import token_counter prompt_tokens += token_counter( diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py index cb9ce475d30..7239bea7853 100644 --- a/litellm/caching/redis_cache.py +++ b/litellm/caching/redis_cache.py @@ -22,6 +22,7 @@ import litellm from litellm._logging import print_verbose, verbose_logger from litellm.constants import ( DEFAULT_REDIS_MAJOR_VERSION, + REDIS_CIRCUIT_BREAKER_ENABLED, REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD, REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT, ) @@ -114,15 +115,23 @@ class RedisCircuitBreaker: OPEN = "open" HALF_OPEN = "half_open" - def __init__(self, failure_threshold: int, recovery_timeout: int) -> None: + def __init__( + self, + failure_threshold: int, + recovery_timeout: int, + enabled: bool = True, + ) -> None: self.failure_threshold = failure_threshold self.recovery_timeout = recovery_timeout + self.enabled = enabled self._failure_count = 0 self._opened_at: Optional[float] = None self._state = self.CLOSED def is_open(self) -> bool: """Returns True if Redis calls should be skipped.""" + if not self.enabled: + return False if self._state == self.HALF_OPEN: # Probe already in flight — fast-fail all concurrent requests. # Only the one call that caused the OPEN→HALF_OPEN transition @@ -136,6 +145,8 @@ class RedisCircuitBreaker: return False def record_failure(self) -> None: + if not self.enabled: + return self._failure_count += 1 self._opened_at = time.time() if self._failure_count >= self.failure_threshold: @@ -149,6 +160,8 @@ class RedisCircuitBreaker: self._state = self.OPEN def record_success(self) -> None: + if not self.enabled: + return if self._state == self.HALF_OPEN: verbose_logger.info("Redis circuit breaker CLOSED — Redis recovered") self._failure_count = 0 @@ -243,6 +256,7 @@ class RedisCache(BaseCache): self._circuit_breaker = RedisCircuitBreaker( failure_threshold=REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD, recovery_timeout=REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT, + enabled=REDIS_CIRCUIT_BREAKER_ENABLED, ) self._setup_health_pings() diff --git a/litellm/caching/redis_semantic_cache.py b/litellm/caching/redis_semantic_cache.py index da9e7b1e587..cce4b75795f 100644 --- a/litellm/caching/redis_semantic_cache.py +++ b/litellm/caching/redis_semantic_cache.py @@ -213,6 +213,78 @@ class RedisSemanticCache(BaseCache): ttl = int(ttl) return ttl + @classmethod + def _get_prompt_from_kwargs(cls, **kwargs) -> Optional[str]: + """ + Extract a semantic-cache prompt from chat or Responses API request kwargs. + """ + messages = kwargs.get("messages") + if messages: + return get_str_from_messages(messages) + + if "input" not in kwargs: + return None + + prompt_parts: List[str] = [] + cls._collect_responses_input_text(kwargs.get("input"), prompt_parts) + prompt = "\n".join(prompt_parts).strip() + return prompt or None + + @classmethod + def _collect_responses_input_text(cls, value: Any, prompt_parts: List[str]) -> None: + value = cls._coerce_response_input_value(value) + if value is None: + return + + if isinstance(value, str): + stripped_value = value.strip() + if stripped_value: + prompt_parts.append(stripped_value) + return + + if isinstance(value, (list, tuple)): + for item in value: + cls._collect_responses_input_text(item, prompt_parts) + return + + if isinstance(value, dict): + content = value.get("content") + if content is not None: + cls._collect_responses_input_text(content, prompt_parts) + return + + for text_key in ("text", "output", "input_text", "output_text"): + text_value = value.get(text_key) + if isinstance(text_value, str): + stripped_text = text_value.strip() + if stripped_text: + prompt_parts.append(stripped_text) + return + return + + content = getattr(value, "content", None) + if content is not None: + cls._collect_responses_input_text(content, prompt_parts) + return + + for text_key in ("text", "output", "input_text", "output_text"): + text_value = getattr(value, text_key, None) + if isinstance(text_value, str): + stripped_text = text_value.strip() + if stripped_text: + prompt_parts.append(stripped_text) + return + + @staticmethod + def _coerce_response_input_value(value: Any) -> Any: + model_dump = getattr(value, "model_dump", None) + if callable(model_dump): + return model_dump() + dict_method = getattr(value, "dict", None) + if callable(dict_method): + return dict_method() + return value + def _get_embedding(self, prompt: str) -> List[float]: """ Generate an embedding vector for the given prompt using the configured embedding model. @@ -278,13 +350,11 @@ class RedisSemanticCache(BaseCache): value_str: Optional[str] = None try: - # Extract the prompt from messages - messages = kwargs.get("messages", []) - if not messages: - print_verbose("No messages provided for semantic caching") + prompt = self._get_prompt_from_kwargs(**kwargs) + if prompt is None: + print_verbose("No prompt provided for semantic caching") return - prompt = get_str_from_messages(messages) value_str = str(value) store_kwargs: Dict[str, Any] = { @@ -315,14 +385,12 @@ class RedisSemanticCache(BaseCache): print_verbose(f"Redis semantic-cache get_cache, kwargs: {kwargs}") try: - # Extract the prompt from messages - messages = kwargs.get("messages", []) - if not messages: - print_verbose("No messages provided for semantic cache lookup") + prompt = self._get_prompt_from_kwargs(**kwargs) + if prompt is None: + print_verbose("No prompt provided for semantic cache lookup") kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 return None - prompt = get_str_from_messages(messages) # Check the cache for semantically similar prompts in this exact # LiteLLM cache-key scope. check_kwargs: Dict[str, Any] = { @@ -428,13 +496,11 @@ class RedisSemanticCache(BaseCache): print_verbose(f"Async Redis semantic-cache set_cache, kwargs: {kwargs}") try: - # Extract the prompt from messages - messages = kwargs.get("messages", []) - if not messages: - print_verbose("No messages provided for semantic caching") + prompt = self._get_prompt_from_kwargs(**kwargs) + if prompt is None: + print_verbose("No prompt provided for semantic caching") return - prompt = get_str_from_messages(messages) value_str = str(value) # Generate embedding for the value (response) to cache @@ -471,15 +537,12 @@ class RedisSemanticCache(BaseCache): print_verbose(f"Async Redis semantic-cache get_cache, kwargs: {kwargs}") try: - # Extract the prompt from messages - messages = kwargs.get("messages", []) - if not messages: - print_verbose("No messages provided for semantic cache lookup") + prompt = self._get_prompt_from_kwargs(**kwargs) + if prompt is None: + print_verbose("No prompt provided for semantic cache lookup") kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 return None - prompt = get_str_from_messages(messages) - # Generate embedding for the prompt prompt_embedding = await self._get_async_embedding(prompt, **kwargs) diff --git a/litellm/completion_extras/litellm_responses_transformation/handler.py b/litellm/completion_extras/litellm_responses_transformation/handler.py index 87c26b776e8..d27cfefda73 100644 --- a/litellm/completion_extras/litellm_responses_transformation/handler.py +++ b/litellm/completion_extras/litellm_responses_transformation/handler.py @@ -171,6 +171,8 @@ class ResponsesToCompletionBridgeHandler: model_response = validated_kwargs["model_response"] logging_obj = validated_kwargs["logging_obj"] custom_llm_provider = validated_kwargs["custom_llm_provider"] + if kwargs.get("stream") is True and "stream" not in optional_params: + optional_params = {**optional_params, "stream": True} request_data = self.transformation_handler.transform_request( model=model, @@ -263,6 +265,8 @@ class ResponsesToCompletionBridgeHandler: model_response = validated_kwargs["model_response"] logging_obj = validated_kwargs["logging_obj"] custom_llm_provider = validated_kwargs["custom_llm_provider"] + if kwargs.get("stream") is True and "stream" not in optional_params: + optional_params = {**optional_params, "stream": True} try: request_data = self.transformation_handler.transform_request( diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py index 51abbbf729b..6d8b5cf8a57 100644 --- a/litellm/completion_extras/litellm_responses_transformation/transformation.py +++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py @@ -402,6 +402,20 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): instructions, ) = self.convert_chat_completion_messages_to_responses_api(messages) + # OpenAI's Responses API rejects an empty input. For a system-only + # request, carry the system message as a system-role input item instead + # of instructions, mirroring how non-string system content is already + # handled in convert_chat_completion_messages_to_responses_api. + if not input_items and instructions is not None: + input_items = [ + { + "type": "message", + "role": "system", + "content": [{"type": "input_text", "text": instructions}], + } + ] + instructions = None + optional_params = self._extract_extra_body_params(optional_params) # Build responses API request using the reverse transformation logic diff --git a/litellm/constants.py b/litellm/constants.py index 36e578bd323..663afb87fb5 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -398,6 +398,9 @@ REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD = int( REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT = int( os.getenv("REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT", 60) ) +REDIS_CIRCUIT_BREAKER_ENABLED = ( + os.getenv("REDIS_CIRCUIT_BREAKER_ENABLED", "true").lower() == "true" +) # Default Redis major version to assume when version cannot be determined # Using 7 as it's the modern version that supports LPOP with count parameter DEFAULT_REDIS_MAJOR_VERSION = int(os.getenv("DEFAULT_REDIS_MAJOR_VERSION", 7)) @@ -418,6 +421,7 @@ REPLICATE_POLLING_DELAY_SECONDS = float( DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS = int( os.getenv("DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS", 4096) ) +DEFAULT_OCI_CHAT_MAX_TOKENS = 4096 TOGETHER_AI_4_B = int(os.getenv("TOGETHER_AI_4_B", 4)) TOGETHER_AI_8_B = int(os.getenv("TOGETHER_AI_8_B", 8)) TOGETHER_AI_21_B = int(os.getenv("TOGETHER_AI_21_B", 21)) @@ -831,6 +835,7 @@ openai_compatible_providers: List = [ "nano-gpt", # Nano-GPT - JSON-configured provider "poe", # Poe - JSON-configured provider "chutes", # Chutes - JSON-configured provider + "parasail", # Parasail - JSON-configured provider "featherless_ai", "nscale", "nebius", @@ -1157,6 +1162,7 @@ BEDROCK_CONVERSE_MODELS = [ "openai.gpt-oss-120b-1:0", "anthropic.claude-haiku-4-5-20251001-v1:0", "anthropic.claude-sonnet-4-5-20250929-v1:0", + "anthropic.claude-fable-5", "anthropic.claude-opus-4-8", "anthropic.claude-opus-4-7", "anthropic.claude-opus-4-6-v1:0", @@ -1478,6 +1484,7 @@ DB_SPEND_UPDATE_JOB_NAME = "db_spend_update_job" DB_DAILY_TAG_SPEND_UPDATE_JOB_NAME = "db_daily_tag_spend_update_job" PROMETHEUS_EMIT_BUDGET_METRICS_JOB_NAME = "prometheus_emit_budget_metrics" CLOUDZERO_EXPORT_USAGE_DATA_JOB_NAME = "cloudzero_export_usage_data" +MAVVRIK_FOCUS_EXPORT_JOB_NAME = "mavvrik_focus_export_usage_data" CLOUDZERO_MAX_FETCHED_DATA_RECORDS = int( os.getenv("CLOUDZERO_MAX_FETCHED_DATA_RECORDS", 50000) ) @@ -1492,6 +1499,10 @@ SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES = int( SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS = float( os.getenv("SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.5) ) +SPEND_LOG_PARTITION_INTERVAL = os.getenv("SPEND_LOG_PARTITION_INTERVAL", "day") +SPEND_LOG_PARTITION_PRECREATE_AHEAD = int( + os.getenv("SPEND_LOG_PARTITION_PRECREATE_AHEAD", 7) +) SPEND_LOG_QUEUE_SIZE_THRESHOLD = int(os.getenv("SPEND_LOG_QUEUE_SIZE_THRESHOLD", 100)) SPEND_LOG_QUEUE_POLL_INTERVAL = float(os.getenv("SPEND_LOG_QUEUE_POLL_INTERVAL", 2.0)) SPEND_COUNTER_RESEED_LOCKS_MAX_SIZE = int( diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py index 9a4b158b622..e934c6a6f83 100644 --- a/litellm/cost_calculator.py +++ b/litellm/cost_calculator.py @@ -2425,12 +2425,11 @@ class BaseTokenUsageProcessor: if not attr.startswith("_") and not callable( getattr(usage.completion_tokens_details, attr) ): - current_val = getattr( - combined.completion_tokens_details, attr, 0 + current_val = ( + getattr(combined.completion_tokens_details, attr, 0) or 0 ) - new_val = getattr(usage.completion_tokens_details, attr, 0) - - if new_val is not None and current_val is not None: + new_val = getattr(usage.completion_tokens_details, attr, 0) or 0 + if isinstance(new_val, (int, float)): setattr( combined.completion_tokens_details, attr, @@ -2489,6 +2488,11 @@ class RealtimeAPITokenUsageProcessor(BaseTokenUsageProcessor): ) +_TRANSCRIPTION_COMPLETED_EVENT_TYPE = ( + "conversation.item.input_audio_transcription.completed" +) + + def handle_realtime_stream_cost_calculation( results: OpenAIRealtimeStreamList, combined_usage_object: Usage, @@ -2534,4 +2538,99 @@ def handle_realtime_stream_cost_calculation( break # exit if we find a valid model total_cost = input_cost_per_token + output_cost_per_token + if any(r.get("type") == _TRANSCRIPTION_COMPLETED_EVENT_TYPE for r in results): + total_cost += handle_realtime_transcription_cost_calculation( + results=results, + custom_llm_provider=custom_llm_provider, + litellm_model_name=litellm_model_name, + ) + return total_cost + + +def handle_realtime_transcription_cost_calculation( + results: OpenAIRealtimeStreamList, + custom_llm_provider: str, + litellm_model_name: str, +) -> float: + """ + Cost for realtime transcription sessions (e.g. gpt-realtime-whisper). + + Transcription sessions emit no `response.done` events; instead each + `conversation.item.input_audio_transcription.completed` event carries a + `usage` object billed by the ASR model. The usage is one of: + - {"type": "duration", "seconds": } → priced via input_cost_per_second + - {"type": "tokens", "input_tokens": ...} → priced via input/audio token cost + """ + completed_events = [ + cast(dict, result) + for result in results + if result.get("type") == _TRANSCRIPTION_COMPLETED_EVENT_TYPE + ] + if not completed_events: + return 0.0 + + model_name = ( + _get_transcription_model_name_from_results(results) or litellm_model_name + ) + try: + model_info = litellm.get_model_info( + model=model_name, custom_llm_provider=custom_llm_provider + ) + except Exception: + model_info = None + + total_cost = 0.0 + for event in completed_events: + usage = event.get("usage") or {} + total_cost += _transcription_usage_cost(usage, model_info) + return total_cost + + +def _get_transcription_model_name_from_results( + results: OpenAIRealtimeStreamList, +) -> Optional[str]: + """Resolve the ASR model from a transcription_session.* / session.* event.""" + for result in results: + if result.get("type") in ( + "transcription_session.created", + "transcription_session.updated", + "session.created", + "session.updated", + ): + session = cast(dict, result).get("session", {}) or {} + transcription = ( + (session.get("audio", {}) or {}).get("input", {}) or {} + ).get("transcription", {}) or session.get("input_audio_transcription", {}) + model = (transcription or {}).get("model") or session.get("model") + if model: + return model + return None + + +def _transcription_usage_cost(usage: dict, model_info: Optional[ModelInfo]) -> float: + if model_info is None: + return 0.0 + usage_type = usage.get("type") + if usage_type == "duration": + seconds = usage.get("seconds") or 0.0 + per_second = model_info.get("input_cost_per_second") or 0.0 + return float(seconds) * float(per_second) + if usage_type == "tokens": + input_token_details = usage.get("input_token_details") or {} + audio_tokens = input_token_details.get("audio_tokens") or 0 + text_tokens = input_token_details.get("text_tokens") or 0 + output_tokens = usage.get("output_tokens") or 0 + audio_cost = float(audio_tokens) * float( + model_info.get("input_cost_per_audio_token") + or model_info.get("input_cost_per_token") + or 0.0 + ) + text_cost = float(text_tokens) * float( + model_info.get("input_cost_per_token") or 0.0 + ) + output_cost = float(output_tokens) * float( + model_info.get("output_cost_per_token") or 0.0 + ) + return audio_cost + text_cost + output_cost + return 0.0 diff --git a/litellm/exceptions.py b/litellm/exceptions.py index 17f5b43c273..1cbef6b0b49 100644 --- a/litellm/exceptions.py +++ b/litellm/exceptions.py @@ -9,13 +9,109 @@ ## LiteLLM versions of the OpenAI Exception Types -from typing import Any, Dict, Optional +import enum +from typing import Any, Dict, Optional, Union import httpx import openai from litellm.types.utils import LiteLLMCommonStrings + +class RateLimitErrorCategory(str, enum.Enum): + """ + Category of a rate limit error, allowing callers to distinguish where the rate + limit originated. Exposed on every :class:`RateLimitError` instance via the + ``category`` attribute. + + Use these values to switch on the rate limit source, e.g.:: + + try: + ... + except litellm.RateLimitError as e: + if e.category == RateLimitErrorCategory.LITELLM_RATE_LIMIT: + ... # litellm's own limiter (key/team/user/model RPM/TPM/budget) + elif e.category == RateLimitErrorCategory.VENDOR_RATE_LIMIT: + ... # the upstream LLM provider returned 429 + """ + + VENDOR_RATE_LIMIT = "vendor_rate_limit" + """The upstream LLM provider returned a rate-limit response (e.g. OpenAI 429).""" + + VENDOR_BATCH_RATE_LIMIT = "vendor_batch_rate_limit" + """The upstream LLM provider returned a rate-limit response on a batch endpoint.""" + + LITELLM_RATE_LIMIT = "litellm_rate_limit" + """LiteLLM's own rate limiter (key/team/user/model RPM/TPM, budget, parallel-requests, etc.) blocked the request.""" + + LITELLM_BATCH_RATE_LIMIT = "litellm_batch_rate_limit" + """LiteLLM's own batch rate limiter (token/request budget across a batch input file) blocked the request.""" + + +class RateLimitType(str, enum.Enum): + """ + The dimension that was exceeded when a rate-limit error fired. + + This is orthogonal to :class:`RateLimitErrorCategory` — *category* tells + callers **who** rate-limited the request (the upstream vendor vs. one of + litellm's own limiters), while *type* tells them **which limit dimension** + was exceeded (an RPM ceiling, a TPM ceiling, a max-parallel-requests + ceiling, a budget cap, or a max-iterations cap). + + Surfaced both on every :class:`RateLimitError` instance via the + ``rate_limit_type`` attribute and on the structured + ``StandardLoggingPayload.error_information.error_rate_limit_type`` field + so custom callbacks / metrics consumers can split rate-limit failures by + cause without parsing free-text error messages. + """ + + REQUESTS = "requests" + """Requests-per-minute (RPM) or requests-per-window ceiling exceeded.""" + + TOKENS = "tokens" + """Tokens-per-minute (TPM) or tokens-per-window ceiling exceeded.""" + + CONCURRENT_REQUESTS = "concurrent_requests" + """``max_parallel_requests`` — too many in-flight requests at once.""" + + BUDGET = "budget" + """Spend budget cap reached (key, team, user, or per-session).""" + + MAX_ITERATIONS = "max_iterations" + """Per-session max-iterations cap reached (agent-style flows).""" + + +_RATE_LIMIT_CATEGORY_VALUES = frozenset(c.value for c in RateLimitErrorCategory) +_RATE_LIMIT_TYPE_VALUES = frozenset(t.value for t in RateLimitType) + + +def validate_rate_limit_category(value: Any) -> Optional[str]: + """Return ``value`` only if it matches a known :class:`RateLimitErrorCategory`. + + Used at duck-typed read sites (StandardLoggingPayload extraction, Prometheus + labels) to reject `.category` strings set by unrelated third-party exceptions + — otherwise those would leak into custom-callback payloads and Prometheus + label cardinality. + """ + if isinstance(value, RateLimitErrorCategory): + return value.value + if isinstance(value, str) and value in _RATE_LIMIT_CATEGORY_VALUES: + return value + return None + + +def validate_rate_limit_type(value: Any) -> Optional[str]: + """Return ``value`` only if it matches a known :class:`RateLimitType`. + + See :func:`validate_rate_limit_category` for the rationale. + """ + if isinstance(value, RateLimitType): + return value.value + if isinstance(value, str) and value in _RATE_LIMIT_TYPE_VALUES: + return value + return None + + _MINIMAL_ERROR_RESPONSE: Optional[httpx.Response] = None @@ -321,6 +417,18 @@ class PermissionDeniedError(openai.PermissionDeniedError): # type: ignore class RateLimitError(openai.RateLimitError): # type: ignore + """ + Unified rate-limit error. + + Every rate-limit condition surfaced by litellm — whether it originated from + an upstream LLM provider, a vendor batch endpoint, or one of litellm's own + proxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget, + max-iterations, etc.) — is raised as an instance of this class. + + The :attr:`category` attribute lets callers distinguish the source. See + :class:`RateLimitErrorCategory` for the available values. + """ + def __init__( self, message, @@ -330,6 +438,12 @@ class RateLimitError(openai.RateLimitError): # type: ignore litellm_debug_info: Optional[str] = None, max_retries: Optional[int] = None, num_retries: Optional[int] = None, + category: Union[str, RateLimitErrorCategory] = ( + RateLimitErrorCategory.VENDOR_RATE_LIMIT + ), + rate_limit_type: Optional[Union[str, RateLimitType]] = None, + headers: Optional[Dict[str, str]] = None, + detail: Any = None, ): self.status_code = 429 self.message = "litellm.RateLimitError: {}".format(message) @@ -338,9 +452,39 @@ class RateLimitError(openai.RateLimitError): # type: ignore self.litellm_debug_info = litellm_debug_info self.max_retries = max_retries self.num_retries = num_retries + self.category = ( + category.value if isinstance(category, RateLimitErrorCategory) else category + ) + # Which dimension was exceeded — request count, token count, parallel + # requests, budget, max iterations. None when the source didn't + # classify the failure (e.g. legacy vendor 429 with no header hints). + self.rate_limit_type: Optional[str] = ( + rate_limit_type.value + if isinstance(rate_limit_type, RateLimitType) + else rate_limit_type + ) + # Headers explicitly attached to the error (e.g. retry-after, + # rate_limit_type, reset_at). Preserved across the proxy boundary so + # clients can react appropriately. + # + # IMPORTANT: we deliberately do NOT auto-populate self.headers from + # response.headers when only `response` is provided. A vendor 429 can + # set arbitrary response headers (Set-Cookie, CORS overrides, …); if + # those leaked into e.headers and a downstream proxy serializer + # forwarded them to the client, a malicious upstream could inject + # browser-interpreted headers for the proxy origin. Vendor response + # headers stay reachable on `e.response.headers` for callers that + # explicitly want them; only the proxy-supplied `headers=` kwarg + # makes it onto `self.headers`. _response_headers = ( getattr(response, "headers", None) if response is not None else None ) + self.headers: Optional[Dict[str, str]] = ( + {k: str(v) for k, v in headers.items()} if headers else None + ) + # Mirrors FastAPI HTTPException.detail so the same instance can be + # serialized through both the ProxyException and HTTPException paths. + self.detail = detail if detail is not None else self.message self.response = httpx.Response( status_code=429, headers=_response_headers, @@ -843,11 +987,24 @@ LITELLM_EXCEPTION_TYPES = [ class BudgetExceededError(Exception): def __init__( - self, current_cost: float, max_budget: float, message: Optional[str] = None + self, + current_cost: float, + max_budget: float, + message: Optional[str] = None, + llm_provider: Optional[str] = None, ): self.current_cost = current_cost self.max_budget = max_budget self.status_code = 429 + self.llm_provider = llm_provider or "" + # Surface unified rate-limit fields without joining the RateLimitError + # hierarchy so existing `except BudgetExceededError:` handlers keep + # working; custom callbacks reading StandardLoggingPayload pick these + # up via the same `category` / `rate_limit_type` attributes the rest + # of the unified rate-limit error path uses. Stored as plain strings + # to match the normalization RateLimitError.__init__ performs. + self.category: str = RateLimitErrorCategory.LITELLM_RATE_LIMIT.value + self.rate_limit_type: str = RateLimitType.BUDGET.value message = ( message or f"Budget has been exceeded! Current cost: {current_cost}, Max budget: {max_budget}" @@ -1062,3 +1219,37 @@ class GuardrailInterventionNormalStringError( def __repr__(self): return self.__str__() + + +class SensitiveDataRouteException(Exception): + """ + Exception raised when a guardrail detects sensitive data and wants to reroute the request. + + Instead of blocking the request, this exception signals that the request should be + routed to a different model (typically an on-premise model for data privacy). + + The proxy catches this exception and: + 1. Reroutes the current request to the specified model + 2. When sticky_session_routing is True, stores the routing decision in session + cache so all subsequent requests in the same session are routed to the same model + """ + + def __init__( + self, + route_to_model: str, + session_id: str, + guardrail_name: Optional[str] = None, + detection_info: Optional[Dict[str, Any]] = None, + message: Optional[str] = None, + sticky_session_routing: bool = True, + ): + self.route_to_model = route_to_model + self.session_id = session_id + self.guardrail_name = guardrail_name + self.detection_info = detection_info or {} + self.sticky_session_routing = sticky_session_routing + self.message = ( + message + or f"Sensitive data detected by {guardrail_name}. Routing to model: {route_to_model}" + ) + super().__init__(self.message) diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py index 7559fe142c4..c6d427e7f09 100644 --- a/litellm/experimental_mcp_client/client.py +++ b/litellm/experimental_mcp_client/client.py @@ -4,6 +4,7 @@ LiteLLM Proxy uses this MCP Client to connnect to other MCP servers. import asyncio import base64 +import os from typing import ( Any, Awaitable, @@ -16,7 +17,6 @@ from typing import ( TypeVar, Union, ) - import httpx from mcp import ClientSession, ReadResourceResult, Resource, StdioServerParameters from mcp.client.sse import sse_client @@ -42,9 +42,8 @@ from mcp.types import ( ) from mcp.types import Tool as MCPTool from pydantic import AnyUrl - from litellm._logging import verbose_logger -from litellm.constants import MCP_CLIENT_TIMEOUT +from litellm.constants import MCP_CLIENT_TIMEOUT, MCP_NPM_CACHE_DIR from litellm.llms.custom_httpx.http_handler import get_ssl_configuration from litellm.types.llms.custom_http import VerifyTypes from litellm.types.mcp import ( @@ -61,13 +60,33 @@ def to_basic_auth(auth_value: str) -> str: return base64.b64encode(auth_value.encode("utf-8")).decode() +def _strip_header_whitespace(headers: Dict[str, str]) -> Dict[str, str]: + return { + (key.strip() if isinstance(key, str) else key): ( + value.strip() if isinstance(value, str) else value + ) + for key, value in headers.items() + } + + +def _first_non_cancelled_cause(exc: BaseException) -> Optional[BaseException]: + queue: List[BaseException] = [exc] + while queue: + current = queue.pop(0) + nested = getattr(current, "exceptions", None) + if nested: + queue.extend(nested) + elif not isinstance(current, asyncio.CancelledError): + return current + return None + + TSessionResult = TypeVar("TSessionResult") class MCPSigV4Auth(httpx.Auth): """ httpx Auth class that signs each request with AWS SigV4. - This is used for MCP servers that require AWS SigV4 authentication, such as AWS Bedrock AgentCore MCP servers. httpx calls auth_flow() for every outgoing request, enabling per-request signature computation. @@ -92,10 +111,8 @@ class MCPSigV4Auth(httpx.Auth): "Missing botocore to use AWS SigV4 authentication. " "Run 'pip install boto3'." ) - self.service_name = aws_service_name or "bedrock-agentcore" self.region_name = aws_region_name or "us-east-1" - # Note: os.environ/ prefixed values are already resolved by # ProxyConfig._check_for_os_environ_vars() at config load time. # Values arrive here as plain strings. @@ -143,20 +160,17 @@ class MCPSigV4Auth(httpx.Auth): session_name = ( aws_session_name or f"litellm-mcp-{int(__import__('time').time())}" ) - sts_kwargs: dict = {"region_name": aws_region_name} if aws_access_key_id and aws_secret_access_key: sts_kwargs["aws_access_key_id"] = aws_access_key_id sts_kwargs["aws_secret_access_key"] = aws_secret_access_key if aws_session_token: sts_kwargs["aws_session_token"] = aws_session_token - sts_client = boto3.client("sts", **sts_kwargs) sts_response = sts_client.assume_role( RoleArn=aws_role_name, RoleSessionName=session_name, ) - sts_creds = sts_response["Credentials"] return Credentials( access_key=sts_creds["AccessKeyId"], @@ -178,17 +192,14 @@ class MCPSigV4Auth(httpx.Auth): data=request.content, headers=dict(request.headers), ) - # Sign the request — SigV4Auth.add_auth() adds Authorization, # X-Amz-Date, and X-Amz-Security-Token (if session token present). # Host header is derived automatically from the URL. sigv4 = SigV4Auth(self.credentials, self.service_name, self.region_name) sigv4.add_auth(aws_request) - # Copy SigV4 headers back to the httpx request for header_name, header_value in aws_request.headers.items(): request.headers[header_name] = header_value - yield request @@ -198,6 +209,8 @@ class MCPClient: SSE and HTTP transports Authentication via Bearer token, Basic Auth, or API Key Tool calling with error handling and result parsing + Sampling callbacks for upstream server LLM requests + Elicitation callbacks for upstream server user-input requests """ def __init__( @@ -211,6 +224,9 @@ class MCPClient: extra_headers: Optional[Dict[str, str]] = None, ssl_verify: Optional[VerifyTypes] = None, aws_auth: Optional[httpx.Auth] = None, + sampling_callback: Optional[Callable] = None, + elicitation_callback: Optional[Callable] = None, + logging_callback: Optional[Callable] = None, ): self.server_url: str = server_url self.transport_type: MCPTransport = transport_type @@ -222,6 +238,9 @@ class MCPClient: self.ssl_verify: Optional[VerifyTypes] = ssl_verify self._aws_auth: Optional[httpx.Auth] = aws_auth self._last_initialize_instructions: Optional[str] = None + self._sampling_callback: Optional[Callable] = sampling_callback + self._elicitation_callback: Optional[Callable] = elicitation_callback + self._logging_callback: Optional[Callable] = logging_callback # handle the basic auth value if provided if auth_value: self.update_auth_value(auth_value) @@ -231,23 +250,20 @@ class MCPClient: ) -> Tuple[Any, Optional[httpx.AsyncClient]]: """ Create the appropriate transport context based on transport type. - Returns: Tuple of (transport_context, http_client). http_client is only set for HTTP transport and needs cleanup. """ http_client: Optional[httpx.AsyncClient] = None - if self.transport_type == MCPTransport.stdio: if not self.stdio_config: raise ValueError("stdio_config is required for stdio transport") server_params = StdioServerParameters( command=self.stdio_config.get("command", ""), args=self.stdio_config.get("args", []), - env=self.stdio_config.get("env", {}), + env=self._get_safe_stdio_env(self.stdio_config.get("env")), ) return stdio_client(server_params), None - if self.transport_type == MCPTransport.sse: headers = self._get_auth_headers() httpx_client_factory = self._create_httpx_client_factory() @@ -260,14 +276,12 @@ class MCPClient: ), None, ) - # HTTP transport (default) if streamable_http_client is None: raise ImportError( "streamable_http_client is not available. " "Please install mcp with HTTP support." ) - headers = self._get_auth_headers() httpx_client_factory = self._create_httpx_client_factory() verbose_logger.debug("litellm headers for streamable_http_client: %s", headers) @@ -281,6 +295,54 @@ class MCPClient: ) return transport_ctx, http_client + def _get_safe_stdio_env( + self, provided_env: Optional[Dict[str, str]] + ) -> Optional[Dict[str, str]]: + """ + Return a safe environment for the stdio subprocess. + + If provided_env is set, we use it as-is. + If provided_env is None, we return a minimal allowlist from the parent environment + to avoid leaking sensitive LiteLLM keys (OPENAI_API_KEY, etc.) to sub-processes. + """ + if provided_env is not None: + return provided_env + + # Minimal allowlist of safe/standard environment variables + safe_keys = { + "PATH", + "HOME", + "USER", + "LOGNAME", + "TMPDIR", + "TMP", + "TEMP", + "SHELL", + "LANG", + "LC_ALL", + # Node/Package manager caches + "NPM_CONFIG_CACHE", + "PNPM_HOME", + "XDG_CACHE_HOME", + "XDG_CONFIG_HOME", + "XDG_DATA_HOME", + # System info + "SYSTEMROOT", + "COMSPEC", + "PATHEXT", + "WINDIR", + } + + safe_env = {} + for key in safe_keys: + if key in os.environ: + safe_env[key] = os.environ[key] + + if "NPM_CONFIG_CACHE" not in safe_env: + safe_env["NPM_CONFIG_CACHE"] = MCP_NPM_CACHE_DIR + + return safe_env + async def _execute_session_operation( self, transport_ctx: Any, @@ -288,13 +350,24 @@ class MCPClient: ) -> TSessionResult: """ Execute an operation within a transport and session context. - Handles entering/exiting contexts and running the operation. + Passes sampling/elicitation/logging callbacks to the ClientSession + so that upstream MCP servers can request LLM inference (sampling), + user input (elicitation), or send log messages. """ transport = await transport_ctx.__aenter__() + in_flight_error: Optional[BaseException] = None try: read_stream, write_stream = transport[0], transport[1] - session_ctx = ClientSession(read_stream, write_stream) + # Build session kwargs with optional callbacks + session_kwargs: Dict[str, Any] = {} + if self._sampling_callback is not None: + session_kwargs["sampling_callback"] = self._sampling_callback + if self._elicitation_callback is not None: + session_kwargs["elicitation_callback"] = self._elicitation_callback + if self._logging_callback is not None: + session_kwargs["logging_callback"] = self._logging_callback + session_ctx = ClientSession(read_stream, write_stream, **session_kwargs) session = await session_ctx.__aenter__() try: init_result = await session.initialize() @@ -309,11 +382,21 @@ class MCPClient: await session_ctx.__aexit__(None, None, None) except BaseException as e: verbose_logger.debug(f"Error during session context exit: {e}") + except BaseException as e: + in_flight_error = e + raise finally: try: await transport_ctx.__aexit__(None, None, None) - except BaseException as e: - verbose_logger.debug(f"Error during transport context exit: {e}") + except BaseException as exit_error: + verbose_logger.debug( + f"Error during transport context exit: {exit_error}" + ) + root_cause = _first_non_cancelled_cause(exit_error) + if root_cause is not None and isinstance( + in_flight_error, asyncio.CancelledError + ): + raise root_cause from in_flight_error async def run_with_session( self, operation: Callable[[ClientSession], Awaitable[TSessionResult]] @@ -351,7 +434,6 @@ class MCPClient: def _get_auth_headers(self) -> dict: """Generate authentication headers based on auth type.""" headers = {} - if self._mcp_auth_value: if isinstance(self._mcp_auth_value, str): if self.auth_type == MCPAuth.bearer_token: @@ -373,17 +455,14 @@ class MCPClient: # Note: aws_sigv4 auth is not handled here — SigV4 requires per-request # signing (including the body hash), so it uses httpx.Auth flow instead # of static headers. See MCPSigV4Auth and _create_httpx_client_factory(). - # update the headers with the extra headers if self.extra_headers: headers.update(self.extra_headers) - - return headers + return _strip_header_whitespace(headers) def _create_httpx_client_factory(self) -> Callable[..., httpx.AsyncClient]: """ Create a custom httpx client factory that uses LiteLLM's SSL configuration. - This factory follows the same CA bundle path logic as http_handler.py: 1. Check ssl_verify parameter (can be SSLContext, bool, or path to CA bundle) 2. Check SSL_VERIFY environment variable @@ -400,17 +479,14 @@ class MCPClient: """Create an httpx.AsyncClient with LiteLLM's SSL configuration.""" # Get unified SSL configuration using the same logic as http_handler.py ssl_config = get_ssl_configuration(self.ssl_verify) - verbose_logger.debug( f"MCP client using SSL configuration: {type(ssl_config).__name__}" ) - # Use SigV4 auth if configured and no explicit auth provided. # The MCP SDK's sse_client and streamable_http_client call this # factory without passing auth=, so self._aws_auth is used. # For non-SigV4 clients, self._aws_auth is None — no behavior change. effective_auth = auth if auth is not None else self._aws_auth - return httpx.AsyncClient( headers=headers, timeout=timeout, @@ -458,7 +534,6 @@ class MCPClient: f"Server: {self.server_url or 'stdio'}, " f"Transport: {self.transport_type}" ) - # Check if it's a stream/connection error if "BrokenResourceError" in error_type or "Broken" in error_type: verbose_logger.error( @@ -491,7 +566,6 @@ class MCPClient: f"MCP Tool '{call_tool_request_params.name}' progress: " f"{progress}/{total} ({percentage:.0f}%) - {message or ''}" ) - # Forward to Host if callback provided if host_progress_callback: try: @@ -514,14 +588,15 @@ class MCPClient: ) return tool_result except asyncio.CancelledError: - verbose_logger.warning("MCP client tool call was cancelled") + verbose_logger.warning( + f"MCP client tool call timed out after {self.timeout}s for {self.server_url}" + ) raise except Exception as e: import traceback error_trace = traceback.format_exc() verbose_logger.debug(f"MCP client tool call traceback:\n{error_trace}") - # Log detailed error information error_type = type(e).__name__ verbose_logger.error( @@ -532,14 +607,12 @@ class MCPClient: f"Server: {self.server_url or 'stdio'}, " f"Transport: {self.transport_type}" ) - # Check if it's a stream/connection error if "BrokenResourceError" in error_type or "Broken" in error_type: verbose_logger.error( "MCP client detected broken connection/stream - " "the MCP server may have crashed, disconnected, or timed out." ) - # Return a default error result instead of raising return MCPCallToolResult( content=[ @@ -577,14 +650,12 @@ class MCPClient: f"Server: {self.server_url or 'stdio'}, " f"Transport: {self.transport_type}" ) - # Check if it's a stream/connection error if "BrokenResourceError" in error_type or "Broken" in error_type: verbose_logger.error( "MCP client detected broken connection/stream during list_tools - " "the MCP server may have crashed, disconnected, or timed out" ) - # Return empty list instead of raising to allow graceful degradation return [] @@ -617,7 +688,6 @@ class MCPClient: error_trace = traceback.format_exc() verbose_logger.debug(f"MCP client get_prompt traceback:\n{error_trace}") - # Log detailed error information error_type = type(e).__name__ verbose_logger.error( @@ -628,14 +698,12 @@ class MCPClient: f"Server: {self.server_url or 'stdio'}, " f"Transport: {self.transport_type}" ) - # Check if it's a stream/connection error if "BrokenResourceError" in error_type or "Broken" in error_type: verbose_logger.error( "MCP client detected broken connection/stream during get_prompt - " "the MCP server may have crashed, disconnected, or timed out." ) - raise async def list_resources(self) -> list[Resource]: @@ -667,14 +735,12 @@ class MCPClient: f"Server: {self.server_url or 'stdio'}, " f"Transport: {self.transport_type}" ) - # Check if it's a stream/connection error if "BrokenResourceError" in error_type or "Broken" in error_type: verbose_logger.error( "MCP client detected broken connection/stream during list_resources - " "the MCP server may have crashed, disconnected, or timed out" ) - # Return empty list instead of raising to allow graceful degradation return [] @@ -709,14 +775,12 @@ class MCPClient: f"Server: {self.server_url or 'stdio'}, " f"Transport: {self.transport_type}" ) - # Check if it's a stream/connection error if "BrokenResourceError" in error_type or "Broken" in error_type: verbose_logger.error( "MCP client detected broken connection/stream during list_resource_templates - " "the MCP server may have crashed, disconnected, or timed out" ) - # Return empty list instead of raising to allow graceful degradation return [] @@ -742,7 +806,6 @@ class MCPClient: error_trace = traceback.format_exc() verbose_logger.debug(f"MCP client read_resource traceback:\n{error_trace}") - # Log detailed error information error_type = type(e).__name__ verbose_logger.error( @@ -753,12 +816,10 @@ class MCPClient: f"Server: {self.server_url or 'stdio'}, " f"Transport: {self.transport_type}" ) - # Check if it's a stream/connection error if "BrokenResourceError" in error_type or "Broken" in error_type: verbose_logger.error( "MCP client detected broken connection/stream during read_resource - " "the MCP server may have crashed, disconnected, or timed out." ) - raise diff --git a/litellm/google_genai/streaming_iterator.py b/litellm/google_genai/streaming_iterator.py index 3e97b480779..a8d0e5976f0 100644 --- a/litellm/google_genai/streaming_iterator.py +++ b/litellm/google_genai/streaming_iterator.py @@ -18,6 +18,42 @@ else: GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ = PassThroughEndpointLogging() +def _encode_google_genai_sse_event(event_lines: List[str]) -> bytes: + return ("\n".join(event_lines) + "\n\n").encode("utf-8") + + +def _next_google_genai_sse_chunk(line_iter) -> bytes: + event_lines: List[str] = [] + while True: + try: + line = next(line_iter) + except StopIteration: + if event_lines: + return _encode_google_genai_sse_event(event_lines) + raise + if line == "": + if event_lines: + return _encode_google_genai_sse_event(event_lines) + continue + event_lines.append(line) + + +async def _anext_google_genai_sse_chunk(line_iter) -> bytes: + event_lines: List[str] = [] + while True: + try: + line = await line_iter.__anext__() + except StopAsyncIteration: + if event_lines: + return _encode_google_genai_sse_event(event_lines) + raise + if line == "": + if event_lines: + return _encode_google_genai_sse_event(event_lines) + continue + event_lines.append(line) + + class BaseGoogleGenAIGenerateContentStreamingIterator: """ Base class for Google GenAI Generate Content streaming iterators that provides common logic @@ -91,18 +127,17 @@ class GoogleGenAIGenerateContentStreamingIterator( self.generate_content_provider_config = generate_content_provider_config self.litellm_metadata = litellm_metadata self.custom_llm_provider = custom_llm_provider - # Store the iterator once to avoid multiple stream consumption - self.stream_iterator = response.iter_bytes() + # Gemini streamGenerateContent uses SSE line framing; iter_lines keeps + # large inlineData payloads (e.g. image/jpeg) intact within one event. + self.stream_iterator = response.iter_lines() def __iter__(self): return self def __next__(self): try: - # Get the next chunk from the stored iterator - chunk = next(self.stream_iterator) + chunk = _next_google_genai_sse_chunk(self.stream_iterator) self.collected_chunks.append(chunk) - # Just yield raw bytes return chunk except StopIteration: raise StopIteration @@ -147,18 +182,17 @@ class AsyncGoogleGenAIGenerateContentStreamingIterator( self.generate_content_provider_config = generate_content_provider_config self.litellm_metadata = litellm_metadata self.custom_llm_provider = custom_llm_provider - # Store the async iterator once to avoid multiple stream consumption - self.stream_iterator = response.aiter_bytes() + # Gemini streamGenerateContent uses SSE line framing; aiter_lines keeps + # large inlineData payloads (e.g. image/jpeg) intact within one event. + self.stream_iterator = response.aiter_lines() def __aiter__(self): return self async def __anext__(self): try: - # Get the next chunk from the stored async iterator - chunk = await self.stream_iterator.__anext__() + chunk = await _anext_google_genai_sse_chunk(self.stream_iterator) self.collected_chunks.append(chunk) - # Just yield raw bytes return chunk except StopAsyncIteration: await self._handle_async_streaming_logging() diff --git a/litellm/integrations/SlackAlerting/budget_alert_types.py b/litellm/integrations/SlackAlerting/budget_alert_types.py index ea80b258540..2a19ec0b7fa 100644 --- a/litellm/integrations/SlackAlerting/budget_alert_types.py +++ b/litellm/integrations/SlackAlerting/budget_alert_types.py @@ -1,7 +1,7 @@ from abc import ABC, abstractmethod from typing import Literal -from litellm.proxy._types import CallInfo +from litellm.proxy._types import CallInfo, Litellm_EntityType class BaseBudgetAlertType(ABC): @@ -31,6 +31,8 @@ class SoftBudgetAlert(BaseBudgetAlertType): return "Soft Budget Crossed: " def get_id(self, user_info: CallInfo) -> str: + if user_info.event_group == Litellm_EntityType.TEAM: + return user_info.team_id or "default_id" return user_info.token or "default_id" diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.py index 0ec17bbea5d..390af2cb6e6 100644 --- a/litellm/integrations/SlackAlerting/slack_alerting.py +++ b/litellm/integrations/SlackAlerting/slack_alerting.py @@ -37,6 +37,8 @@ from litellm.proxy._types import ( VirtualKeyEvent, WebhookEvent, ) +from litellm.repositories.team_repository import TeamRepository +from litellm.repositories.user_repository import UserRepository from litellm.types.integrations.slack_alerting import * from ..email_templates.templates import * @@ -1231,7 +1233,7 @@ Model Info: and recipient_user_id is not None and prisma_client is not None ): - user_row = await prisma_client.db.litellm_usertable.find_unique( + user_row = await UserRepository(prisma_client).table.find_unique( where={"user_id": recipient_user_id} ) @@ -1263,7 +1265,7 @@ Model Info: team_id = webhook_event.team_id team_name = "Default Team" if team_id is not None and prisma_client is not None: - team_row = await prisma_client.db.litellm_teamtable.find_unique( + team_row = await TeamRepository(prisma_client).table.find_unique( where={"team_id": team_id} ) if team_row is not None: diff --git a/litellm/integrations/callback_configs.json b/litellm/integrations/callback_configs.json index c2b0c4ddce9..590c848767a 100644 --- a/litellm/integrations/callback_configs.json +++ b/litellm/integrations/callback_configs.json @@ -104,6 +104,51 @@ }, "description": "Datadog Custom Metrics Integration" }, + { + "id": "galileo", + "displayName": "Galileo", + "logo": "galileo.ico", + "supports_key_team_logging": false, + "dynamic_params": { + "GALILEO_API_KEY": { + "type": "password", + "ui_name": "API Key", + "description": "Galileo Cloud API key (app.galileo.ai). Omit for enterprise username/password auth.", + "required": false + }, + "GALILEO_PROJECT_ID": { + "type": "text", + "ui_name": "Project ID", + "description": "Galileo project ID to log traces to", + "required": true + }, + "GALILEO_LOG_STREAM_ID": { + "type": "text", + "ui_name": "Log Stream ID", + "description": "Galileo log stream ID for v2 spans logging (optional)", + "required": false + }, + "GALILEO_BASE_URL": { + "type": "text", + "ui_name": "Base URL", + "description": "Galileo API base URL (e.g. https://api.galileo.ai for Cloud, or your enterprise API URL)", + "required": false + }, + "GALILEO_USERNAME": { + "type": "text", + "ui_name": "Username", + "description": "Galileo enterprise username (legacy Observe auth; use instead of API key)", + "required": false + }, + "GALILEO_PASSWORD": { + "type": "password", + "ui_name": "Password", + "description": "Galileo enterprise password (legacy Observe auth)", + "required": false + } + }, + "description": "Galileo AI Observability Integration" + }, { "id": "datadog_cost_management", "displayName": "Datadog Cost Management", @@ -245,6 +290,21 @@ }, "description": "Langsmith Logging Integration" }, + { + "id": "newrelic", + "displayName": "New Relic", + "logo": "newrelic.png", + "supports_key_team_logging": false, + "dynamic_params": { + "NEW_RELIC_AI_MONITORING_RECORD_CONTENT_ENABLED": { + "type": "text", + "ui_name": "Record AI Content (default: true)", + "description": "Whether to record AI message content. Set to false to disable.", + "required": false + } + }, + "description": "New Relic AI Monitoring Integration" + }, { "id": "openmeter", "displayName": "OpenMeter", diff --git a/litellm/integrations/compression_interception/handler.py b/litellm/integrations/compression_interception/handler.py index c6ae7d9e82b..8899089500d 100644 --- a/litellm/integrations/compression_interception/handler.py +++ b/litellm/integrations/compression_interception/handler.py @@ -72,8 +72,13 @@ class CompressionInterceptionLogger(CustomLogger): compression_params: CompressionInterceptionConfig = {} if "compression_interception_params" in litellm_settings: compression_params = litellm_settings["compression_interception_params"] - elif "compression_interception" in callback_specific_params: - compression_params = callback_specific_params["compression_interception"] + elif "compression_interception" in callback_specific_params and isinstance( + callback_specific_params["compression_interception"], dict + ): + compression_params = cast( + CompressionInterceptionConfig, + callback_specific_params["compression_interception"], + ) return CompressionInterceptionLogger.from_config_yaml(compression_params) async def async_pre_call_deployment_hook( diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py index 6d0d73e033d..fc5f0429b63 100644 --- a/litellm/integrations/custom_guardrail.py +++ b/litellm/integrations/custom_guardrail.py @@ -47,9 +47,29 @@ from litellm.exceptions import ( BlockedPiiEntityError, GuardrailRaisedException, ModifyResponseException, + SensitiveDataRouteException, ) +def get_session_id_from_request_data(request_data: Dict[str, Any]) -> Optional[str]: + """Extract session_id from request data (litellm_session_id or metadata).""" + session_id = request_data.get("litellm_session_id") + if session_id: + return str(session_id) + + metadata = request_data.get("metadata") or {} + session_id = metadata.get("session_id") + if session_id: + return str(session_id) + + litellm_metadata = request_data.get("litellm_metadata") or {} + session_id = litellm_metadata.get("session_id") + if session_id: + return str(session_id) + + return None + + class CustomGuardrail(CustomLogger): # If True, during_call runs async_moderation_hook instead of the unified apply_guardrail path. use_native_during_call_hook: ClassVar[bool] = False @@ -68,6 +88,9 @@ class CustomGuardrail(CustomLogger): end_session_after_n_fails: Optional[int] = None, on_violation: Optional[str] = None, realtime_violation_message: Optional[str] = None, + on_sensitive_data: Optional[str] = None, + sensitive_data_route_to_model: Optional[str] = None, + sticky_session_routing: bool = True, **kwargs, ): """ @@ -83,6 +106,9 @@ class CustomGuardrail(CustomLogger): end_session_after_n_fails: For /v1/realtime sessions, end the session after this many violations on_violation: For /v1/realtime sessions, 'warn' or 'end_session' realtime_violation_message: Message the bot speaks aloud when a /v1/realtime guardrail fires + on_sensitive_data: Action when sensitive data is detected. 'block' (default) or 'route' + sensitive_data_route_to_model: Model to route to when on_sensitive_data='route' + sticky_session_routing: When True, all subsequent requests in the session use the same model """ self.guardrail_name = guardrail_name self.supported_event_hooks = supported_event_hooks @@ -96,6 +122,11 @@ class CustomGuardrail(CustomLogger): self.end_session_after_n_fails: Optional[int] = end_session_after_n_fails self.on_violation: Optional[str] = on_violation self.realtime_violation_message: Optional[str] = realtime_violation_message + self.on_sensitive_data: Optional[str] = on_sensitive_data + self.sensitive_data_route_to_model: Optional[str] = ( + sensitive_data_route_to_model + ) + self.sticky_session_routing: bool = sticky_session_routing if supported_event_hooks: ## validate event_hook is in supported_event_hooks @@ -167,6 +198,108 @@ class CustomGuardrail(CustomLogger): detection_info=detection_info, ) + def raise_sensitive_data_route_exception( + self, + route_to_model: str, + request_data: Dict[str, Any], + detection_info: Optional[Dict[str, Any]] = None, + ) -> None: + """ + Raise an exception to reroute the request to a different model. + + Use this when sensitive data is detected and the guardrail is configured + to route to an on-premise model instead of blocking. + + The exception will reroute this request to the specified model. When + sticky_session_routing is enabled (the default), it also stores the + routing decision so subsequent requests in this session reuse the model. + + Args: + route_to_model: The model to route this request (and session) to + request_data: The original request data dictionary + detection_info: Optional non-sensitive detection metadata (e.g. matched + entity types, rule ids, scores). This is surfaced in request metadata + and logs, so it must not contain the raw detected sensitive values. + + Raises: + SensitiveDataRouteException: Always raises to trigger rerouting + """ + session_id = self._get_session_id_from_request_data(request_data) + if not session_id: + raise ValueError( + "Cannot route sensitive data without a session_id. " + "Ensure the request includes a session_id in metadata or headers." + ) + + raise SensitiveDataRouteException( + route_to_model=route_to_model, + session_id=session_id, + guardrail_name=self.guardrail_name, + detection_info=detection_info, + sticky_session_routing=self.sticky_session_routing, + ) + + def _get_session_id_from_request_data( + self, request_data: Dict[str, Any] + ) -> Optional[str]: + """Extract session_id from request data.""" + return get_session_id_from_request_data(request_data) + + def should_route_on_sensitive_data(self) -> bool: + """ + Returns True if this guardrail is configured to route requests + to a different model when sensitive data is detected. + """ + return ( + self.on_sensitive_data == "route" + and self.sensitive_data_route_to_model is not None + ) + + def handle_sensitive_data_detection( + self, + request_data: Dict[str, Any], + detection_info: Optional[Dict[str, Any]] = None, + ) -> None: + """ + Handle sensitive data detection based on guardrail configuration. + + If on_sensitive_data='route', raises SensitiveDataRouteException to reroute. + Otherwise, raises GuardrailRaisedException to block. When routing is + configured but the request carries no session_id, routing is not possible + so the request falls back to a graceful block. + + Args: + request_data: The request data dictionary + detection_info: Optional non-sensitive detection metadata. When routing, + this is surfaced in request metadata and logs, so it must not contain + the raw detected sensitive values. + + Raises: + SensitiveDataRouteException: When configured to route and a session_id is present + GuardrailRaisedException: When configured to block, or when routing is + configured but no session_id is available + """ + if self.should_route_on_sensitive_data(): + try: + self.raise_sensitive_data_route_exception( + route_to_model=self.sensitive_data_route_to_model, # type: ignore + request_data=request_data, + detection_info=detection_info, + ) + except ValueError: + raise GuardrailRaisedException( + message=( + f"Sensitive data detected by {self.guardrail_name} " + "(routing skipped: request has no session_id)" + ), + guardrail_name=self.guardrail_name, + ) + else: + raise GuardrailRaisedException( + message=f"Sensitive data detected by {self.guardrail_name}", + guardrail_name=self.guardrail_name, + ) + @staticmethod def get_config_model() -> Optional[Type["GuardrailConfigModel"]]: """ @@ -753,12 +886,20 @@ class CustomGuardrail(CustomLogger): Guardrails signal intentional blocks by raising: - GuardrailRaisedException (generic guardrail API, tool permission) - BlockedPiiEntityError (Presidio PII detection) + - SensitiveDataRouteException (sensitive-data reroute to on-premise model) - HTTPException with status 400 (content policy violation) - ModifyResponseException (passthrough mode violation) """ if isinstance(e, ModifyResponseException): return True - if isinstance(e, (GuardrailRaisedException, BlockedPiiEntityError)): + if isinstance( + e, + ( + GuardrailRaisedException, + BlockedPiiEntityError, + SensitiveDataRouteException, + ), + ): return True if ( HTTPException is not None diff --git a/litellm/integrations/email_alerting.py b/litellm/integrations/email_alerting.py index b45b9aa7f5c..b721dc50464 100644 --- a/litellm/integrations/email_alerting.py +++ b/litellm/integrations/email_alerting.py @@ -7,6 +7,7 @@ from typing import List, Optional from litellm._logging import verbose_logger, verbose_proxy_logger from litellm.proxy._types import WebhookEvent +from litellm.repositories.team_repository import TeamRepository # we use this for the email header, please send a test email if you change this. verify it looks good on email LITELLM_LOGO_URL = "https://litellm-listing.s3.amazonaws.com/litellm_logo.png" @@ -24,7 +25,7 @@ async def get_all_team_member_emails(team_id: Optional[str] = None) -> list: if prisma_client is None: raise Exception("Not connected to DB!") - team_row = await prisma_client.db.litellm_teamtable.find_unique( + team_row = await TeamRepository(prisma_client).table.find_unique( where={ "team_id": team_id, } diff --git a/litellm/integrations/focus/database.py b/litellm/integrations/focus/database.py index 298254670eb..3ae3f6b53ac 100644 --- a/litellm/integrations/focus/database.py +++ b/litellm/integrations/focus/database.py @@ -80,11 +80,15 @@ class FocusLiteLLMDatabase: vt.team_id, vt.key_alias as api_key_alias, tt.team_alias, - ut.user_email as user_email + ut.user_email as user_email, + COALESCE(vt.organization_id, tt.organization_id) as organization_id, + ot.organization_alias as organization_alias FROM "LiteLLM_DailyUserSpend" dus LEFT JOIN "LiteLLM_VerificationToken" vt ON dus.api_key = vt.token LEFT JOIN "LiteLLM_TeamTable" tt ON vt.team_id = tt.team_id LEFT JOIN "LiteLLM_UserTable" ut ON dus.user_id = ut.user_id + LEFT JOIN "LiteLLM_OrganizationTable" ot + ON ot.organization_id = COALESCE(vt.organization_id, tt.organization_id) {where_clause} ORDER BY dus.date DESC, dus.created_at DESC {limit_clause} diff --git a/litellm/integrations/focus/destinations/__init__.py b/litellm/integrations/focus/destinations/__init__.py index 775d3a259d2..21945c9b457 100644 --- a/litellm/integrations/focus/destinations/__init__.py +++ b/litellm/integrations/focus/destinations/__init__.py @@ -2,13 +2,17 @@ from .base import FocusDestination, FocusTimeWindow from .factory import FocusDestinationFactory +from .gcs_destination import FocusGCSDestination from .s3_destination import FocusS3Destination +from .mavvrik_destination import FocusMavvrikDestination from .vantage_destination import FocusVantageDestination __all__ = [ "FocusDestination", "FocusDestinationFactory", + "FocusGCSDestination", "FocusTimeWindow", "FocusS3Destination", + "FocusMavvrikDestination", "FocusVantageDestination", ] diff --git a/litellm/integrations/focus/destinations/factory.py b/litellm/integrations/focus/destinations/factory.py index 706e10624ce..cd25a87729f 100644 --- a/litellm/integrations/focus/destinations/factory.py +++ b/litellm/integrations/focus/destinations/factory.py @@ -6,7 +6,9 @@ import os from typing import Any, Dict, Optional from .base import FocusDestination +from .gcs_destination import FocusGCSDestination from .s3_destination import FocusS3Destination +from .mavvrik_destination import FocusMavvrikDestination from .vantage_destination import FocusVantageDestination @@ -29,6 +31,10 @@ class FocusDestinationFactory: return FocusS3Destination(prefix=prefix, config=normalized_config) if provider_lower == "vantage": return FocusVantageDestination(prefix=prefix, config=normalized_config) + if provider_lower == "gcs": + return FocusGCSDestination(prefix=prefix, config=normalized_config) + if provider_lower == "mavvrik": + return FocusMavvrikDestination(prefix=prefix, config=normalized_config) raise NotImplementedError( f"Provider '{provider}' not supported for Focus export" ) @@ -72,6 +78,27 @@ class FocusDestinationFactory: "VANTAGE_INTEGRATION_TOKEN must be provided for Vantage exports" ) return {k: v for k, v in resolved.items() if v is not None} + if provider == "gcs": + resolved = { + "bucket_name": overrides.get("bucket_name") + or os.getenv("FOCUS_GCS_BUCKET_NAME"), + "service_account_json": overrides.get("service_account_json") + or os.getenv("FOCUS_GCS_PATH_SERVICE_ACCOUNT"), + } + if not resolved.get("bucket_name"): + raise ValueError( + "FOCUS_GCS_BUCKET_NAME must be provided for GCS exports" + ) + return {k: v for k, v in resolved.items() if v is not None} + if provider == "mavvrik": + resolved = { + "api_key": overrides.get("api_key") or os.getenv("MAVVRIK_API_KEY"), + "api_endpoint": overrides.get("api_endpoint") + or os.getenv("MAVVRIK_API_ENDPOINT"), + "connection_id": overrides.get("connection_id") + or os.getenv("MAVVRIK_CONNECTION_ID"), + } + return {k: v for k, v in resolved.items() if v is not None} raise NotImplementedError( f"Provider '{provider}' not supported for Focus export configuration" ) diff --git a/litellm/integrations/focus/destinations/gcs_destination.py b/litellm/integrations/focus/destinations/gcs_destination.py new file mode 100644 index 00000000000..b04c16c9d32 --- /dev/null +++ b/litellm/integrations/focus/destinations/gcs_destination.py @@ -0,0 +1,74 @@ +"""GCS destination for Focus export — reuses GCSBucketBase auth and httpx client.""" + +from __future__ import annotations + +from datetime import timezone +from typing import Any, Optional + +from litellm._logging import verbose_logger +from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase +from litellm.litellm_core_utils.cloud_storage_security import ( + encode_gcs_object_name_for_url, +) + +from .base import FocusDestination, FocusTimeWindow + + +class FocusGCSDestination(GCSBucketBase, FocusDestination): + """Upload serialized Focus exports to GCS using the GCS JSON API.""" + + def __init__( + self, + *, + prefix: str, + config: Optional[dict[str, Any]] = None, + ) -> None: + config = config or {} + bucket_name = config.get("bucket_name") + if not bucket_name: + raise ValueError("bucket_name must be provided for GCS destination") + super().__init__(bucket_name=bucket_name) + service_account_json = config.get("service_account_json") + if service_account_json is not None: + self.path_service_account_json = service_account_json + self.prefix = prefix.rstrip("/") + + async def deliver( + self, + *, + content: bytes, + time_window: FocusTimeWindow, + filename: str, + ) -> None: + object_name = self._build_object_key(time_window=time_window, filename=filename) + headers = await self.construct_request_headers( + service_account_json=self.path_service_account_json + ) + headers["Content-Type"] = "application/octet-stream" + encoded_name = encode_gcs_object_name_for_url(object_name) + url = ( + f"https://storage.googleapis.com/upload/storage/v1/b/" + f"{self.BUCKET_NAME}/o?uploadType=media&name={encoded_name}" + ) + response = await self.async_httpx_client.post( + url=url, headers=headers, data=content + ) + if response.status_code != 200: + raise RuntimeError( + f"GCS upload failed: status={response.status_code} body={response.text}" + ) + verbose_logger.debug( + "Focus GCS: uploaded %d bytes to gs://%s/%s", + len(content), + self.BUCKET_NAME, + object_name, + ) + + def _build_object_key(self, *, time_window: FocusTimeWindow, filename: str) -> str: + start_utc = time_window.start_time.astimezone(timezone.utc) + date_component = f"date={start_utc.strftime('%Y-%m-%d')}" + parts = [self.prefix, date_component] + if time_window.frequency == "hourly": + parts.append(f"hour={start_utc.strftime('%H')}") + key_prefix = "/".join(filter(None, parts)) + return f"{key_prefix}/{filename}" if key_prefix else filename diff --git a/litellm/integrations/focus/destinations/mavvrik_destination.py b/litellm/integrations/focus/destinations/mavvrik_destination.py new file mode 100644 index 00000000000..1e3c98b9a70 --- /dev/null +++ b/litellm/integrations/focus/destinations/mavvrik_destination.py @@ -0,0 +1,345 @@ +"""Mavvrik GCS destination for FOCUS export. + +Flow: + 1. GET /metrics/agent/ai/{connection_id}/upload-url → GCS signed URL + 2. PUT with CSV content +""" + +from __future__ import annotations + +import gzip +from typing import Any, Optional +from urllib.parse import urlparse + +from litellm._logging import verbose_logger +from litellm.llms.custom_httpx.http_handler import ( + AsyncHTTPHandler, + get_async_httpx_client, + httpxSpecialProvider, +) + +from .base import FocusDestination, FocusTimeWindow + +_MAVVRIK_ALLOWED_SUFFIXES = (".mavvrik.dev", ".mavvrik.ai", ".mavvrik.app") + +# GCS requires intermediate chunks to be a multiple of 256 KB. +# 8 MB gives a good balance between round-trips and memory pressure. +_GCS_CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB + + +def _validate_api_endpoint(api_endpoint: str) -> None: + if not api_endpoint.startswith("https://"): + raise ValueError("MAVVRIK_API_ENDPOINT must be an HTTPS URL") + hostname = (urlparse(api_endpoint).hostname or "").lower() + if not any(hostname.endswith(suffix) for suffix in _MAVVRIK_ALLOWED_SUFFIXES): + raise ValueError( + "MAVVRIK_API_ENDPOINT host must be a Mavvrik domain " + "(e.g. https://api.mavvrik.dev/)" + ) + + +def _validate_gcs_url(url: str, label: str) -> None: + parsed = urlparse(url) + if parsed.scheme != "https": + raise ValueError( + f"Mavvrik FOCUS destination: {label} must be HTTPS, got scheme '{parsed.scheme}'" + ) + hostname = (parsed.hostname or "").lower() + if not ( + hostname == "storage.googleapis.com" + or hostname.endswith(".storage.googleapis.com") + ): + raise ValueError( + f"Mavvrik FOCUS destination: {label} must be a GCS endpoint " + f"(storage.googleapis.com), got '{hostname}'" + ) + + +class FocusMavvrikDestination(FocusDestination): + """Upload FOCUS CSV exports to Mavvrik via GCS signed URL.""" + + def __init__( + self, + *, + prefix: str, + config: Optional[dict[str, Any]] = None, + ) -> None: + config = config or {} + api_key = config.get("api_key") + api_endpoint = config.get("api_endpoint") + connection_id = config.get("connection_id") + + if not api_key: + raise ValueError( + "MAVVRIK_API_KEY must be provided for Mavvrik FOCUS destination " + "(set MAVVRIK_API_KEY env var or pass in destination_config)" + ) + if not api_endpoint: + raise ValueError( + "MAVVRIK_API_ENDPOINT must be provided for Mavvrik FOCUS destination " + "(set MAVVRIK_API_ENDPOINT env var or pass in destination_config)" + ) + if not connection_id: + raise ValueError( + "MAVVRIK_CONNECTION_ID must be provided for Mavvrik FOCUS destination " + "(set MAVVRIK_CONNECTION_ID env var or pass in destination_config)" + ) + + _validate_api_endpoint(api_endpoint) + + self.api_key = api_key + self.api_endpoint = api_endpoint.rstrip("/") + self.connection_id = connection_id + self.prefix = prefix + self._http: AsyncHTTPHandler = get_async_httpx_client( + llm_provider=httpxSpecialProvider.LoggingCallback + ) + self._registered = False + + @property + def _agent_url(self) -> str: + return f"{self.api_endpoint}/metrics/agent/ai/{self.connection_id}" + + @property + def _upload_url_endpoint(self) -> str: + return f"{self.api_endpoint}/metrics/agent/ai/{self.connection_id}/upload-url" + + @property + def _auth_headers(self) -> dict[str, str]: + return {"Content-Type": "application/json", "x-api-key": self.api_key} + + async def _ensure_registered(self) -> Optional[int]: + """POST agent endpoint to register/initialize the connector (once per instance). + + Returns metricsMarker from the Mavvrik response — the last date index + Mavvrik has successfully processed. Used by the logger to catch up any + dates that were missed due to previous export failures. + + Returns None if the connector was already registered (cached). + """ + if self._registered: + return None + resp = await self._http.client.request( + method="POST", + url=self._agent_url, + headers=self._auth_headers, + json={"name": self.connection_id}, + timeout=30.0, + ) + if resp.status_code == 410: + # Connector has been disconnected in Mavvrik — reset flag so next + # delivery attempt re-registers after it becomes active again. + self._registered = False + raise RuntimeError( + "Mavvrik FOCUS destination: connector is disconnected (410). " + "Re-enable the connection in the Mavvrik dashboard." + ) + if resp.status_code >= 400: + raise RuntimeError( + f"Mavvrik FOCUS destination: register failed " + f"({resp.status_code}): {resp.text[:200]}" + ) + self._registered = True + metrics_marker = resp.json().get("metricsMarker", 0) + verbose_logger.debug( + "Mavvrik FOCUS destination: connector registered (metricsMarker=%s)", + metrics_marker, + ) + return metrics_marker + + async def _get_signed_url(self, date_str: str) -> str: + """GET upload-url endpoint → GCS signed URL for the given date.""" + params = {"name": date_str, "type": "metrics", "datetime": date_str} + resp = await self._http.client.request( + method="GET", + url=self._upload_url_endpoint, + headers=self._auth_headers, + params=params, + timeout=30.0, + ) + if resp.status_code >= 400: + raise RuntimeError( + f"Mavvrik FOCUS destination: failed to get signed URL " + f"({resp.status_code}): {resp.text[:200]}" + ) + signed_url = resp.json().get("url") + if not signed_url: + raise RuntimeError( + f"Mavvrik FOCUS destination: response missing 'url' field: {resp.json()}" + ) + _validate_gcs_url(signed_url, "signed URL") + verbose_logger.debug( + "Mavvrik FOCUS destination: got signed URL for date %s", date_str + ) + return signed_url + + async def _upload_to_gcs(self, signed_url: str, content: bytes) -> None: + """Upload gzip-compressed CSV to GCS via chunked resumable upload. + + The full CSV is gzip-compressed first, then uploaded in _GCS_CHUNK_SIZE + chunks using the GCS resumable upload protocol. GCS assembles the chunks + server-side into a single complete object — the bucket receives one file + regardless of how many chunks were sent. + + Intermediate chunks: Content-Range: bytes X-Y/* → expect 308 + Final chunk: Content-Range: bytes X-Y/T → expect 200/201 + + This handles exports larger than available memory for a single PUT while + keeping the destination code self-contained (no changes to the FOCUS + pipeline upstream). + """ + gzip_bytes = gzip.compress(content) + total = len(gzip_bytes) + + # Step 1: initiate resumable upload session + metadata = b'{"contentEncoding":"gzip","contentDisposition":"attachment"}' + init_resp = await self._http.client.request( + method="POST", + url=signed_url, + headers={ + "Content-Type": "application/gzip", + "x-goog-resumable": "start", + }, + content=metadata, + timeout=30.0, + ) + if init_resp.status_code not in (200, 201): + raise RuntimeError( + f"Mavvrik FOCUS destination: GCS session init failed " + f"({init_resp.status_code}): {init_resp.text[:400]}" + ) + + session_uri = init_resp.headers.get("Location") + if not session_uri: + raise RuntimeError( + "Mavvrik FOCUS destination: GCS session init missing Location header" + ) + _validate_gcs_url(session_uri, "session URI") + + verbose_logger.debug( + "Mavvrik FOCUS destination: GCS session started, uploading %d gzip bytes " + "in %d chunk(s)", + total, + max(1, -(-total // _GCS_CHUNK_SIZE)), # ceiling division + ) + + # Step 2: upload in chunks; cancel session on any failure to avoid + # lingering GCS sessions (they stay open for ~1 week otherwise). + offset = 0 + try: + while offset < total: + chunk = gzip_bytes[offset : offset + _GCS_CHUNK_SIZE] + chunk_end = offset + len(chunk) - 1 + is_final = (offset + len(chunk)) >= total + content_range = ( + f"bytes {offset}-{chunk_end}/{total}" + if is_final + else f"bytes {offset}-{chunk_end}/*" + ) + expected_statuses = {200, 201} if is_final else {308} + + resp = await self._http.client.request( + method="PUT", + url=session_uri, + headers={ + "Content-Type": "application/gzip", + "Content-Range": content_range, + }, + content=chunk, + timeout=120.0, + ) + if resp.status_code not in expected_statuses: + raise RuntimeError( + f"Mavvrik FOCUS destination: GCS chunk upload failed " + f"(chunk offset={offset}, expected={expected_statuses}, " + f"got={resp.status_code}): {resp.text[:400]}" + ) + offset += len(chunk) + verbose_logger.debug( + "Mavvrik FOCUS destination: uploaded chunk offset=%d/%d", + offset, + total, + ) + except Exception: + # Cancel the open GCS session so it doesn't linger for up to 1 week. + try: + await self._http.client.request( + method="DELETE", url=session_uri, timeout=10.0 + ) + verbose_logger.debug( + "Mavvrik FOCUS destination: cancelled GCS session after error" + ) + except Exception: + pass + raise + + async def get_metrics_marker(self) -> Optional[int]: + """Register with Mavvrik and return the current metricsMarker. + + The metricsMarker is a Unix timestamp (seconds) representing the last + date Mavvrik has successfully ingested. Called on every scheduled run + so the logger can detect and catch up any dates missed due to previous + export failures. + + Always calls the Mavvrik register API — unlike deliver() which skips + registration once _registered is True, catch-up requires a fresh + marker value on every run. + """ + resp = await self._http.client.request( + method="POST", + url=self._agent_url, + headers=self._auth_headers, + json={"name": self.connection_id}, + timeout=30.0, + ) + if resp.status_code == 410: + self._registered = False + raise RuntimeError( + "Mavvrik FOCUS destination: connector is disconnected (410). " + "Re-enable the connection in the Mavvrik dashboard." + ) + if resp.status_code >= 400: + raise RuntimeError( + f"Mavvrik FOCUS destination: register failed " + f"({resp.status_code}): {resp.text[:200]}" + ) + self._registered = True + metrics_marker = resp.json().get("metricsMarker", 0) + verbose_logger.debug( + "Mavvrik FOCUS destination: got metricsMarker=%s", metrics_marker + ) + return metrics_marker + + async def deliver( + self, + *, + content: bytes, + time_window: FocusTimeWindow, + filename: str, + ) -> None: + """Upload FOCUS CSV to Mavvrik via GCS signed URL. + + Uses the start date of the time window as the object date key. + """ + if not content: + verbose_logger.debug( + "Mavvrik FOCUS destination: empty content, skipping upload" + ) + return + + date_str = time_window.start_time.strftime("%Y-%m-%d") + + verbose_logger.debug( + "Mavvrik FOCUS destination: uploading %d bytes for date=%s (%s)", + len(content), + date_str, + filename, + ) + + await self._ensure_registered() + signed_url = await self._get_signed_url(date_str) + await self._upload_to_gcs(signed_url, content) + + verbose_logger.debug( + "Mavvrik FOCUS destination: upload complete for date=%s", date_str + ) diff --git a/litellm/integrations/focus/transformer.py b/litellm/integrations/focus/transformer.py index 8496b7ec159..a17df29b912 100644 --- a/litellm/integrations/focus/transformer.py +++ b/litellm/integrations/focus/transformer.py @@ -12,6 +12,8 @@ from .schema import FOCUS_NORMALIZED_SCHEMA _TAG_KEYS = ( "team_id", "team_alias", + "organization_id", + "organization_alias", "user_id", "user_email", "api_key_alias", diff --git a/litellm/integrations/galileo.py b/litellm/integrations/galileo.py index a598124f612..f9ff7e8c7a1 100644 --- a/litellm/integrations/galileo.py +++ b/litellm/integrations/galileo.py @@ -1,8 +1,13 @@ +from __future__ import annotations + import json import os import re -from typing import Any, Dict, List, Optional, Tuple, cast +import uuid +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional, Tuple, Union, cast +import httpx from pydantic import BaseModel, Field import litellm @@ -12,11 +17,16 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import ( convert_content_list_to_str, get_content_from_model_response, ) +from litellm.types.llms.openai import ( + AllMessageValues, + HttpxBinaryResponseContent, + ResponsesAPIResponse, +) from litellm.llms.custom_httpx.http_handler import ( get_async_httpx_client, httpxSpecialProvider, ) -from litellm.types.llms.openai import AllMessageValues +from litellm.types.integrations.base_health_check import IntegrationHealthCheckStatus GALILEO_CLOUD_API_BASE_URL = "https://api.galileo.ai" # Cap the in-memory buffer so persistent flush failures (e.g. Galileo @@ -33,6 +43,11 @@ class LLMResponse(BaseModel): model: str num_input_tokens: int num_output_tokens: int + num_total_tokens: int + cost: Optional[float] = Field( + default=None, + description="Total cost of the LLM call in USD as computed by LiteLLM.", + ) output_logprobs: Optional[Dict[str, Any]] = Field( default=None, description="Optional. When available, logprobs are used to compute Uncertainty.", @@ -75,6 +90,52 @@ class GalileoObserve(CustomLogger): return bool(self.api_key) return bool(self.username and self.password) + async def async_health_check(self) -> IntegrationHealthCheckStatus: + try: + if not self.project_id: + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message="GALILEO_PROJECT_ID environment variable not set", + ) + + if not self.base_url: + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message="GALILEO_BASE_URL environment variable not set", + ) + + if not self.use_v2_api and (not self.username or not self.password): + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message=( + "GALILEO_API_KEY or GALILEO_USERNAME and GALILEO_PASSWORD " + "environment variables must be set" + ), + ) + + if not await self._ensure_headers(): + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message="Galileo authentication failed", + ) + + response = await self.async_httpx_handler.get( + url=f"{self.base_url}/current_user", + headers=self.headers, + ) + if response.status_code >= 400: + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message=(f"Galileo API returned HTTP {response.status_code}"), + ) + + return IntegrationHealthCheckStatus(status="healthy", error_message=None) + except Exception as e: + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message=f"Galileo health check failed: {str(e)}", + ) + async def async_set_galileo_headers(self) -> None: galileo_login_response = await self.async_httpx_handler.post( url=f"{self.base_url}/login", @@ -121,10 +182,14 @@ class GalileoObserve(CustomLogger): @staticmethod def _galileo_input_messages( - messages: Optional[List[Any]], input_text: str + messages: Optional[Any], input_text: str ) -> List[Dict[str, str]]: + if isinstance(messages, dict): + messages = messages.get("messages") if not messages: return [{"role": "user", "content": input_text}] + if not isinstance(messages, list): + return [{"role": "user", "content": input_text}] galileo_messages: List[Dict[str, str]] = [] for message in messages: @@ -147,13 +212,59 @@ class GalileoObserve(CustomLogger): return [{"role": "user", "content": input_text}] @staticmethod - def _record_to_v2_span(record: Dict[str, Any]) -> Dict[str, Any]: - created_at = record.get("created_at", "") + def _local_timezone(): + return datetime.now().astimezone().tzinfo or timezone.utc + + @staticmethod + def _format_created_at(dt: Union[datetime, Any]) -> str: + """Serialize timestamps as UTC ISO-8601 for Galileo.""" + if not isinstance(dt, datetime): + return str(dt) + + if dt.tzinfo is None: + # LiteLLM often passes naive datetimes in local time; convert to UTC + # instead of appending Z to local time (which shifts Traces tab sorting). + dt = dt.replace(tzinfo=GalileoObserve._local_timezone()) + + return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + @staticmethod + def _normalize_created_at(created_at: str) -> str: if created_at and not re.search(r"(Z|[+-]\d{2}:?\d{2})$", created_at): - created_at = f"{created_at}Z" + return f"{created_at}Z" + return created_at + + @staticmethod + def _token_metrics_from_record(record: Dict[str, Any]) -> Dict[str, Any]: + num_input_tokens = int(record.get("num_input_tokens") or 0) + num_output_tokens = int(record.get("num_output_tokens") or 0) + num_total_tokens = int(record.get("num_total_tokens") or 0) + if num_total_tokens == 0 and (num_input_tokens or num_output_tokens): + num_total_tokens = num_input_tokens + num_output_tokens + metrics: Dict[str, Any] = { + "num_input_tokens": num_input_tokens, + "num_output_tokens": num_output_tokens, + "num_total_tokens": num_total_tokens, + } + cost = record.get("cost") + if cost is not None: + metrics["cost"] = float(cost) + return metrics + + @staticmethod + def _record_to_v2_span( + record: Dict[str, Any], + *, + trace_id: str, + span_id: str, + ) -> Dict[str, Any]: + created_at = GalileoObserve._normalize_created_at(record.get("created_at", "")) span: Dict[str, Any] = { "type": "llm", + "id": span_id, + "trace_id": trace_id, + "parent_id": trace_id, "name": record.get("node_type", "litellm"), "created_at": created_at, "input": GalileoObserve._galileo_input_messages( @@ -167,14 +278,49 @@ class GalileoObserve(CustomLogger): "model": record.get("model"), "metrics": { "duration_ns": int(record.get("latency_ms", 0)) * 1_000_000, - "num_input_tokens": record.get("num_input_tokens"), - "num_output_tokens": record.get("num_output_tokens"), + **GalileoObserve._token_metrics_from_record(record), }, } if record.get("tags"): span["tags"] = record["tags"] return span + @staticmethod + def _record_to_v2_trace(record: Dict[str, Any]) -> Dict[str, Any]: + trace_id = str(uuid.uuid4()) + span_id = str(uuid.uuid4()) + created_at = GalileoObserve._normalize_created_at(record.get("created_at", "")) + + return { + "type": "trace", + "id": trace_id, + "name": record.get("node_type", "litellm"), + "created_at": created_at, + "input": record.get("input_text", ""), + "output": record.get("output_text", ""), + "status_code": record.get("status_code", 200), + "metrics": { + "duration_ns": int(record.get("latency_ms", 0)) * 1_000_000, + **GalileoObserve._token_metrics_from_record(record), + }, + "spans": [ + GalileoObserve._record_to_v2_span( + record, trace_id=trace_id, span_id=span_id + ) + ], + } + + def _build_traces_payload(self, records: List[dict]) -> Dict[str, Any]: + payload: Dict[str, Any] = { + "traces": [self._record_to_v2_trace(record) for record in records], + "logging_method": "api_direct", + "reliable": False, + "is_complete": True, + } + if self.log_stream_id: + payload["log_stream_id"] = self.log_stream_id + return payload + def _get_ingest_request(self) -> Optional[Tuple[str, Dict[str, Any]]]: if not self.base_url or not self.project_id: return None @@ -184,105 +330,453 @@ class GalileoObserve(CustomLogger): # flush_in_memory_records) aren't silently dropped when we later clear # the in-memory buffer. records = list(self.in_memory_records) + payload = self._build_traces_payload(records) if self.use_v2_api: - payload: Dict[str, Any] = { - "spans": [self._record_to_v2_span(record) for record in records], - "reliable": False, - } - if self.log_stream_id: - payload["log_stream_id"] = self.log_stream_id return ( - f"{self.base_url}/v2/projects/{self.project_id}/spans", + f"{self.base_url}/ingest/traces/{self.project_id}", payload, ) + # Username/password auth logs in for a JWT and uses the standard v2 traces API. return ( - f"{self.base_url}/projects/{self.project_id}/observe/ingest", - {"records": records}, + f"{self.base_url}/v2/projects/{self.project_id}/traces", + payload, ) + @staticmethod + def _redact_headers(headers: Optional[Dict[str, str]]) -> Dict[str, str]: + if not headers: + return {} + redacted: Dict[str, str] = {} + for key, value in headers.items(): + if key.lower() in {"authorization", "galileo-api-key"} and value: + redacted[key] = ( + f"{value[:8]}...{value[-4:]}" if len(value) > 12 else "***" + ) + else: + redacted[key] = value + return redacted + + def _log_flush_config(self) -> None: + verbose_logger.debug( + "Galileo Logger flush config: use_v2_api=%s base_url=%s project_id=%s " + "log_stream_id=%s api_key_set=%s username_set=%s record_count=%s", + self.use_v2_api, + self.base_url, + self.project_id, + self.log_stream_id, + bool(self.api_key), + bool(self.username), + len(self.in_memory_records), + ) + + @staticmethod + def _log_v2_payload_validation(payload: Dict[str, Any]) -> None: + missing_fields: List[str] = [] + traces = payload.get("traces", []) + if not traces: + missing_fields.append("traces") + + for trace_index, trace in enumerate(traces): + if not isinstance(trace, dict): + continue + for field in ("id", "type", "spans"): + if field not in trace: + missing_fields.append(f"traces[{trace_index}].{field}") + + trace_id = trace.get("id") + for span_index, span in enumerate(trace.get("spans", [])): + if not isinstance(span, dict): + continue + for field in ("id", "trace_id", "parent_id"): + if field not in span: + missing_fields.append( + f"traces[{trace_index}].spans[{span_index}].{field}" + ) + if trace_id and span.get("trace_id") != trace_id: + missing_fields.append( + f"traces[{trace_index}].spans[{span_index}].trace_id mismatch" + ) + + if missing_fields: + verbose_logger.debug( + "Galileo Logger: ingest /traces payload validation issues: %s", + missing_fields, + ) + + def _log_flush_payload(self, url: str, payload: Dict[str, Any]) -> None: + traces = payload.get("traces", []) + verbose_logger.debug( + "Galileo Logger flush URL: %s trace_count=%s", + url, + len(traces) if isinstance(traces, list) else 0, + ) + if self.use_v2_api and "/ingest/traces/" in url: + self._log_v2_payload_validation(payload) + + @staticmethod + def _log_http_status_error(error: httpx.HTTPStatusError, url: str) -> None: + response = error.response + verbose_logger.debug( + "Galileo Logger HTTP error: status=%s url=%s", + response.status_code, + url, + ) + verbose_logger.debug( + "Galileo Logger HTTP error response body: %s", + response.text, + ) + try: + verbose_logger.debug( + "Galileo Logger HTTP error response json: %s", + response.json(), + ) + except Exception: + pass + + @staticmethod + def _build_prompt(kwargs: Dict[str, Any]) -> Dict[str, Any]: + optional_params = kwargs.get("optional_params", {}) or {} + prompt: Dict[str, Any] = {"messages": kwargs.get("messages")} + if optional_params.get("functions") is not None: + prompt["functions"] = optional_params["functions"] + if optional_params.get("tools") is not None: + prompt["tools"] = optional_params["tools"] + return prompt + + @staticmethod + def _serialize_galileo_output(value: Any) -> str: + if value is None: + return "" + if isinstance(value, str): + return value + + def _json_default(obj: Any) -> Any: + if hasattr(obj, "model_dump"): + return obj.model_dump() + return str(obj) + + return json.dumps(value, default=_json_default) + + @staticmethod + def _prompt_to_input_text(prompt: Dict[str, Any]) -> str: + messages = prompt.get("messages") + if messages is not None: + text = GalileoObserve._input_text_from_messages(messages) + if text: + return text + return json.dumps(prompt, default=str) + + @staticmethod + def _get_chat_content_for_galileo(response_obj: litellm.ModelResponse) -> Any: + if response_obj.choices and len(response_obj.choices) > 0: + message = response_obj["choices"][0]["message"] + if hasattr(message, "json"): + message_json = message.json() + if isinstance(message_json, str): + return json.loads(message_json) + return message_json + return message + return None + + @staticmethod + def _get_text_completion_content_for_galileo( + response_obj: litellm.TextCompletionResponse, + ) -> Optional[str]: + if response_obj.choices and len(response_obj.choices) > 0: + return response_obj.choices[0].text + return None + + @staticmethod + def _get_responses_api_content_for_galileo( + response_obj: ResponsesAPIResponse, + ) -> Any: + if hasattr(response_obj, "output") and response_obj.output: + return response_obj.output + return None + + @staticmethod + def _langfuse_style_rerank_prompt(kwargs: Dict[str, Any]) -> Dict[str, Any]: + """Match Langfuse rerank input: prompt = {"messages": kwargs.get("messages")}.""" + return {"messages": kwargs.get("messages")} + + def _get_galileo_input_output_content( + self, + kwargs: Dict[str, Any], + response_obj: Any, + level: str = "DEFAULT", + status_message: Optional[str] = None, + ) -> Tuple[str, str, Any]: + """ + Mirror Langfuse _get_langfuse_input_output_content for Galileo ingest. + + Returns (input_text, output_text, messages_for_span). + """ + call_type = kwargs.get("call_type") + prompt = self._build_prompt(kwargs) + + if ( + level == "ERROR" + and status_message is not None + and isinstance(status_message, str) + ): + return self._prompt_to_input_text(prompt), status_message, prompt + + if response_obj is not None and ( + call_type in ("embedding", "aembedding") + or isinstance(response_obj, litellm.EmbeddingResponse) + ): + # Match Langfuse OTEL: log embeddings without serializing vectors. + return self._prompt_to_input_text(prompt), "embedding-output", prompt + + if response_obj is not None and isinstance(response_obj, litellm.ModelResponse): + output = self._get_chat_content_for_galileo(response_obj) + return ( + self._prompt_to_input_text(prompt), + self._serialize_galileo_output(output), + kwargs.get("messages") or [], + ) + + if response_obj is not None and isinstance( + response_obj, HttpxBinaryResponseContent + ): + return self._prompt_to_input_text(prompt), "speech-output", prompt + + if response_obj is not None and isinstance( + response_obj, litellm.TextCompletionResponse + ): + output = self._get_text_completion_content_for_galileo(response_obj) + return ( + self._prompt_to_input_text(prompt), + self._serialize_galileo_output(output), + kwargs.get("messages") or [], + ) + + if response_obj is not None and isinstance(response_obj, litellm.ImageResponse): + output = response_obj.get("data", None) + return ( + self._prompt_to_input_text(prompt), + self._serialize_galileo_output(output), + prompt, + ) + + if response_obj is not None and isinstance( + response_obj, litellm.TranscriptionResponse + ): + output = response_obj.get("text", None) + return ( + self._prompt_to_input_text(prompt), + self._serialize_galileo_output(output), + prompt, + ) + + if response_obj is not None and isinstance( + response_obj, litellm.RerankResponse + ): + output = response_obj.results + rerank_prompt = self._langfuse_style_rerank_prompt(kwargs) + return ( + json.dumps(rerank_prompt, default=str), + self._serialize_galileo_output(output), + rerank_prompt, + ) + + if response_obj is not None and isinstance(response_obj, ResponsesAPIResponse): + output = self._get_responses_api_content_for_galileo(response_obj) + return ( + self._prompt_to_input_text(prompt), + self._serialize_galileo_output(output), + kwargs.get("messages") or [], + ) + + if ( + call_type == "_arealtime" + and response_obj is not None + and isinstance(response_obj, list) + ): + input_val = kwargs.get("input") + return ( + self._serialize_galileo_output(input_val), + self._serialize_galileo_output(response_obj), + input_val, + ) + + if ( + call_type == "pass_through_endpoint" + and response_obj is not None + and isinstance(response_obj, dict) + ): + output = response_obj.get("response", "") + return ( + self._prompt_to_input_text(prompt), + self._serialize_galileo_output(output), + prompt, + ) + + if response_obj is not None and isinstance(response_obj, dict): + output = get_content_from_model_response(response_obj) + return ( + self._prompt_to_input_text(prompt), + self._serialize_galileo_output(output), + kwargs.get("messages") or [], + ) + + return self._prompt_to_input_text(prompt), "", kwargs.get("messages") or [] + def get_output_str_from_response( self, response_obj: Any, kwargs: Dict[str, Any] - ) -> Optional[str]: - if response_obj is None: - return None - if kwargs.get("call_type", None) == "embedding" or isinstance( - response_obj, litellm.EmbeddingResponse - ): - return None - if isinstance(response_obj, litellm.TextCompletionResponse): - return response_obj.choices[0].text - if isinstance(response_obj, litellm.ImageResponse): - return json.dumps(response_obj["data"], default=str) - if isinstance(response_obj, (litellm.ModelResponse, dict)): - return get_content_from_model_response(response_obj) - return None + ) -> str: + _, output_text, _ = self._get_galileo_input_output_content( + kwargs=kwargs, response_obj=response_obj + ) + return output_text + + @staticmethod + def _input_text_from_messages(messages: Any) -> str: + """Return a plain-string summary of the input suitable for the trace-level input field.""" + if isinstance(messages, str): + return messages + if not isinstance(messages, list): + return "" + # Use the last user/human message so the trace table shows the actual prompt + for msg in reversed(messages): + if not isinstance(msg, dict): + continue + if str(msg.get("role", "")).lower() in ("user", "human"): + content = msg.get("content") or "" + if isinstance(content, list): + content = " ".join( + b.get("text", "") if isinstance(b, dict) else str(b) + for b in content + ) + if content: + return str(content) + # Fallback: first non-empty content of any role + for msg in messages: + if isinstance(msg, dict): + content = msg.get("content") or "" + if isinstance(content, list): + content = " ".join( + b.get("text", "") if isinstance(b, dict) else str(b) + for b in content + ) + if content: + return str(content) + return "" async def async_log_success_event( self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any ): verbose_logger.debug("On Async Success") + try: + await self._async_log_success_event_impl( + kwargs=kwargs, + response_obj=response_obj, + start_time=start_time, + end_time=end_time, + ) + except Exception: + verbose_logger.exception( + "Galileo Logger: unexpected error in async_log_success_event" + ) + async def _async_log_success_event_impl( + self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any + ): if not self._is_configured(): verbose_logger.debug( - "Galileo Logger: skipping flush — set GALILEO_PROJECT_ID and " - "either GALILEO_API_KEY (hosted) or GALILEO_USERNAME/GALILEO_PASSWORD " - "(enterprise Observe)." + "Galileo Logger: skipping — GALILEO_PROJECT_ID=%s GALILEO_API_KEY=%s GALILEO_BASE_URL=%s", + bool(self.project_id), + bool(self.api_key), + bool(self.base_url), ) return - _latency_ms = int((end_time - start_time).total_seconds() * 1000) - _call_type = kwargs.get("call_type", "litellm") - input_text = litellm.utils.get_formatted_prompt( - data=kwargs, call_type=_call_type + slo: Optional[Dict[str, Any]] = kwargs.get("standard_logging_object") + if slo is None: + verbose_logger.debug( + "Galileo Logger: no standard_logging_object in kwargs, skipping" + ) + return + + _call_type: str = str( + slo.get("call_type") or kwargs.get("call_type") or "litellm" ) - _usage = response_obj.get("usage", {}) or {} - num_input_tokens = _usage.get("prompt_tokens", 0) - num_output_tokens = _usage.get("completion_tokens", 0) - - output_text = self.get_output_str_from_response( - response_obj=response_obj, kwargs=kwargs + input_text, output_text, messages = self._get_galileo_input_output_content( + kwargs=kwargs, response_obj=response_obj ) - if output_text is not None: - request_record = LLMResponse( - latency_ms=_latency_ms, - status_code=200, - input_text=input_text, - output_text=output_text, - node_type=_call_type, - model=kwargs.get("model", "-"), - num_input_tokens=num_input_tokens, - num_output_tokens=num_output_tokens, - created_at=start_time.strftime( - "%Y-%m-%dT%H:%M:%S" - ), # timestamp str constructed in "%Y-%m-%dT%H:%M:%S" format + raw_start = slo.get("startTime") + raw_end = slo.get("endTime") + if raw_start is None or raw_end is None: + verbose_logger.debug( + "Galileo Logger: standard_logging_object missing startTime/endTime, " + "falling back to start_time/end_time params" + ) + if not isinstance(start_time, datetime) or not isinstance( + end_time, datetime + ): + return + start_ts = start_time + end_ts = end_time + if start_ts.tzinfo is None: + start_ts = start_ts.replace(tzinfo=GalileoObserve._local_timezone()) + if end_ts.tzinfo is None: + end_ts = end_ts.replace(tzinfo=GalileoObserve._local_timezone()) + start_ts = start_ts.astimezone(timezone.utc) + end_ts = end_ts.astimezone(timezone.utc) + else: + start_ts = datetime.fromtimestamp(float(raw_start), tz=timezone.utc) + end_ts = datetime.fromtimestamp(float(raw_end), tz=timezone.utc) + _latency_ms = max(0, int((end_ts - start_ts).total_seconds() * 1000)) + num_input_tokens = int(slo.get("prompt_tokens") or 0) + num_output_tokens = int(slo.get("completion_tokens") or 0) + num_total_tokens = int(slo.get("total_tokens") or 0) + if num_total_tokens == 0 and (num_input_tokens or num_output_tokens): + num_total_tokens = num_input_tokens + num_output_tokens + + request_record = LLMResponse( + latency_ms=_latency_ms, + status_code=200, + input_text=input_text, + output_text=output_text, + node_type=_call_type, + model=str(slo.get("model") or kwargs.get("model") or "-"), + num_input_tokens=num_input_tokens, + num_output_tokens=num_output_tokens, + num_total_tokens=num_total_tokens, + cost=slo.get("response_cost"), + created_at=GalileoObserve._format_created_at(start_ts), + ) + + request_dict = request_record.model_dump() + if isinstance(messages, dict): + messages = messages.get("messages") + if isinstance(messages, list) and messages: + request_dict["messages"] = messages + self.in_memory_records.append(request_dict) + verbose_logger.debug( + "Galileo Logger: queued record, in_memory=%d", len(self.in_memory_records) + ) + + # Bound the buffer so persistent flush failures cannot grow it + # without limit. Drop the oldest records once we exceed the cap. + if len(self.in_memory_records) > GALILEO_MAX_IN_MEMORY_RECORDS: + dropped = len(self.in_memory_records) - GALILEO_MAX_IN_MEMORY_RECORDS + self.in_memory_records = self.in_memory_records[ + -GALILEO_MAX_IN_MEMORY_RECORDS: + ] + verbose_logger.warning( + "Galileo Logger: in-memory buffer exceeded %s records; " + "dropped %s oldest record(s). Check Galileo connectivity/credentials.", + GALILEO_MAX_IN_MEMORY_RECORDS, + dropped, ) - request_dict = request_record.model_dump() - messages = kwargs.get("messages") - if messages: - request_dict["messages"] = messages - self.in_memory_records.append(request_dict) - - # Bound the buffer so persistent flush failures cannot grow it - # without limit. Drop the oldest records once we exceed the cap. - if len(self.in_memory_records) > GALILEO_MAX_IN_MEMORY_RECORDS: - dropped = len(self.in_memory_records) - GALILEO_MAX_IN_MEMORY_RECORDS - self.in_memory_records = self.in_memory_records[ - -GALILEO_MAX_IN_MEMORY_RECORDS: - ] - verbose_logger.warning( - "Galileo Logger: in-memory buffer exceeded %s records; " - "dropped %s oldest record(s). Check Galileo connectivity/credentials.", - GALILEO_MAX_IN_MEMORY_RECORDS, - dropped, - ) - - if len(self.in_memory_records) >= self.batch_size: - await self.flush_in_memory_records() + if len(self.in_memory_records) >= self.batch_size: + await self.flush_in_memory_records() async def flush_in_memory_records(self): if not self.in_memory_records: @@ -296,15 +790,23 @@ class GalileoObserve(CustomLogger): ingest_request = self._get_ingest_request() if ingest_request is None: verbose_logger.debug( - "Galileo Logger: missing GALILEO_BASE_URL or GALILEO_PROJECT_ID" + "Galileo Logger: missing GALILEO_BASE_URL or GALILEO_PROJECT_ID — skipping flush" ) return if not await self._ensure_headers(): - verbose_logger.debug("Galileo Logger: could not set request headers") + verbose_logger.debug( + "Galileo Logger: could not set request headers — skipping flush" + ) return url, payload = ingest_request + self._log_flush_config() + self._log_flush_payload(url=url, payload=payload) + verbose_logger.debug( + "Galileo Logger flush headers: %s", + self._redact_headers(self.headers), + ) verbose_logger.debug("flushing in memory records to %s", url) try: @@ -313,6 +815,12 @@ class GalileoObserve(CustomLogger): headers=self.headers, json=payload, ) + except httpx.HTTPStatusError as e: + self._log_http_status_error(error=e, url=url) + verbose_logger.debug( + "Galileo Logger: failed to flush in memory records: %s", e + ) + return except Exception as e: verbose_logger.debug( "Galileo Logger: failed to flush in memory records: %s", e @@ -323,6 +831,11 @@ class GalileoObserve(CustomLogger): verbose_logger.debug( "Galileo Logger: successfully flushed in memory records" ) + verbose_logger.debug( + "Galileo Logger flush response: status=%s body=%s", + response.status_code, + response.text, + ) del self.in_memory_records[:records_in_payload] else: verbose_logger.debug("Galileo Logger: failed to flush in memory records") diff --git a/litellm/integrations/langfuse/langfuse_prompt_management.py b/litellm/integrations/langfuse/langfuse_prompt_management.py index b7a565512c6..cae59295634 100644 --- a/litellm/integrations/langfuse/langfuse_prompt_management.py +++ b/litellm/integrations/langfuse/langfuse_prompt_management.py @@ -102,6 +102,18 @@ def langfuse_client_init( if Version(langfuse.version.__version__) >= Version("2.6.0"): parameters["sdk_integration"] = "litellm" + if Version(langfuse.version.__version__) >= Version("2.7.3"): + import httpx + + import litellm + + from ...llms.custom_httpx.http_handler import get_ssl_configuration + + parameters["httpx_client"] = httpx.Client( + verify=get_ssl_configuration(), + cert=os.getenv("SSL_CERTIFICATE", litellm.ssl_certificate), + ) + client = Langfuse(**parameters) return client diff --git a/litellm/integrations/mavvrik_focus/__init__.py b/litellm/integrations/mavvrik_focus/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/litellm/integrations/mavvrik_focus/mavvrik_focus_logger.py b/litellm/integrations/mavvrik_focus/mavvrik_focus_logger.py new file mode 100644 index 00000000000..47d3e1da7bc --- /dev/null +++ b/litellm/integrations/mavvrik_focus/mavvrik_focus_logger.py @@ -0,0 +1,272 @@ +"""MavvrikFocusLogger — FOCUS-based Mavvrik export logger. + +Usage in config.yaml: + litellm_settings: + callbacks: ["mavvrik"] + +Required env vars: + MAVVRIK_API_KEY + MAVVRIK_API_ENDPOINT + MAVVRIK_CONNECTION_ID + +Optional env vars: + MAVVRIK_FOCUS_MAX_ROWS — row cap per export window (default: 500000) + +Only daily frequency is supported. The Mavvrik ingestion protocol stores one +file per calendar date (metrics/YYYY-MM-DD). Hourly or interval exports would +overwrite each other within the same day, producing incomplete data. +""" + +from __future__ import annotations + +import os +from datetime import datetime, timedelta, timezone +from typing import TYPE_CHECKING, Any, List, Optional + +import litellm +from litellm._logging import verbose_proxy_logger +from litellm.constants import MAVVRIK_FOCUS_EXPORT_JOB_NAME +from litellm.integrations.focus.destinations.base import FocusTimeWindow +from litellm.integrations.focus.focus_logger import FocusLogger + +if TYPE_CHECKING: + from apscheduler.schedulers.asyncio import AsyncIOScheduler +else: + AsyncIOScheduler = Any + + +def _parse_metrics_marker( + marker: Optional[object], +) -> Optional[datetime]: + """Parse metricsMarker from Mavvrik register response into a UTC datetime. + + Handles both formats Mavvrik may return: + - Unix timestamp (int/float): e.g. 1749340800 + - ISO date string: e.g. "2026-06-09" or "2026-06-09T00:00:00Z" + + Returns None for falsy values (0, None, empty string) which indicate + no data has been ingested yet. + """ + if not marker: + return None + try: + if isinstance(marker, (int, float)): + return datetime.fromtimestamp(float(marker), tz=timezone.utc).replace( + hour=0, minute=0, second=0, microsecond=0 + ) + if isinstance(marker, str): + marker = marker.strip() + if not marker: + return None + # Try ISO date first (YYYY-MM-DD), then full ISO datetime + for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S"): + try: + return datetime.strptime(marker, fmt).replace(tzinfo=timezone.utc) + except ValueError: + continue + except Exception: + pass + verbose_proxy_logger.warning( + "Mavvrik FOCUS: could not parse metricsMarker %r — skipping catch-up", marker + ) + return None + + +class MavvrikFocusLogger(FocusLogger): + """FOCUS-based export logger that routes to the Mavvrik destination.""" + + def __init__(self, **kwargs: Any) -> None: + frequency = os.getenv("MAVVRIK_FOCUS_FREQUENCY", "daily").lower() + if frequency != "daily": + raise ValueError( + f"MAVVRIK_FOCUS_FREQUENCY='{frequency}' is not supported. " + "Only 'daily' is allowed -- the Mavvrik ingestion protocol stores one " + "file per calendar date (metrics/YYYY-MM-DD). Hourly or interval " + "exports would overwrite each other within the same day." + ) + super().__init__( + provider="mavvrik", + export_format="csv", + frequency="daily", + prefix="mavvrik_focus_exports", + destination_config={ + "api_key": os.getenv("MAVVRIK_API_KEY"), + "api_endpoint": os.getenv("MAVVRIK_API_ENDPOINT"), + "connection_id": os.getenv("MAVVRIK_CONNECTION_ID"), + }, + **kwargs, + ) + raw = os.getenv("MAVVRIK_FOCUS_MAX_ROWS") + self._max_rows: Optional[int] = int(raw) if raw else 500_000 + + async def _export_window( + self, + *, + window: FocusTimeWindow, + limit: Optional[int], + ) -> None: + """Export with Mavvrik row cap applied when no explicit limit is passed.""" + effective_limit = limit if limit is not None else self._max_rows + engine = self._ensure_engine() + data = await engine._database.get_usage_data( + limit=effective_limit, + start_time_utc=window.start_time, + end_time_utc=window.end_time, + ) + if effective_limit is not None and len(data) >= effective_limit: + verbose_proxy_logger.warning( + "Mavvrik FOCUS export: row cap reached (%d rows). " + "Some data for window %s→%s may be excluded. " + "Increase MAVVRIK_FOCUS_MAX_ROWS to export all rows.", + effective_limit, + window.start_time.date(), + window.end_time.date(), + ) + if data.is_empty(): + verbose_proxy_logger.debug( + "Mavvrik FOCUS export: no usage data for window %s", window + ) + return + normalized = engine._transformer.transform(data) + if normalized.is_empty(): + return + payload = engine._serializer.serialize(normalized) + if not payload: + return + await engine._destination.deliver( + content=payload, + time_window=window, + filename=engine._build_filename(window), + ) + + # Maximum number of days to catch up in a single run. Prevents runaway + # loops if the connector was disabled for a long time, and avoids querying + # data that has likely been cleaned up from LiteLLM_DailyUserSpend. + _MAX_CATCHUP_DAYS = 7 + + async def _run_scheduled_export(self) -> None: + """Export today's window, catching up any dates Mavvrik has not yet received. + + On each run: + 1. Register with Mavvrik → get metricsMarker (last successfully ingested date) + 2. If metricsMarker is behind yesterday, catch up missed dates (capped at + _MAX_CATCHUP_DAYS to avoid runaway loops on long outages) + 3. Export yesterday (today's daily window) + + This ensures a failed export on day N is automatically retried on day N+1 + without any manual intervention. + """ + engine = self._ensure_engine() + from litellm.integrations.focus.destinations.mavvrik_destination import ( # noqa: PLC0415 + FocusMavvrikDestination, + ) + + destination = engine._destination + if not isinstance(destination, FocusMavvrikDestination): + await super()._run_scheduled_export() + return + + # Register and get the last date Mavvrik has processed. + # metricsMarker may be a Unix timestamp (int/float) or an ISO date string. + marker = await destination.get_metrics_marker() + + now = datetime.now(timezone.utc) + yesterday = now.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta( + days=1 + ) + + last_ingested = _parse_metrics_marker(marker) + + # Catch up missed dates, capped at _MAX_CATCHUP_DAYS + if last_ingested and last_ingested < yesterday: + # Never go further back than _MAX_CATCHUP_DAYS from yesterday + earliest_catchup = yesterday - timedelta(days=self._MAX_CATCHUP_DAYS - 1) + catch_up_date = max(last_ingested + timedelta(days=1), earliest_catchup) + + if last_ingested + timedelta(days=1) < earliest_catchup: + verbose_proxy_logger.warning( + "Mavvrik FOCUS export: metricsMarker is more than %d days behind " + "(%s). Catching up from %s only; earlier data will not be re-exported.", + self._MAX_CATCHUP_DAYS, + last_ingested.date(), + catch_up_date.date(), + ) + + while catch_up_date < yesterday: + verbose_proxy_logger.info( + "Mavvrik FOCUS export: catching up missed date %s", + catch_up_date.date(), + ) + window = FocusTimeWindow( + start_time=catch_up_date, + end_time=catch_up_date + timedelta(days=1), + frequency="daily", + ) + await self._export_window(window=window, limit=None) + catch_up_date += timedelta(days=1) + + # Export yesterday's window (the normal daily run) + window = FocusTimeWindow( + start_time=yesterday, + end_time=yesterday + timedelta(days=1), + frequency="daily", + ) + await self._export_window(window=window, limit=None) + + async def initialize_mavvrik_focus_export_job(self) -> None: + """Scheduler entry point — uses Mavvrik-specific pod-lock key.""" + from litellm.proxy.proxy_server import proxy_logging_obj # noqa: PLC0415 + + pod_lock_manager = None + if proxy_logging_obj is not None: + writer = getattr(proxy_logging_obj, "db_spend_update_writer", None) + if writer is not None: + pod_lock_manager = getattr(writer, "pod_lock_manager", None) + + if pod_lock_manager and pod_lock_manager.redis_cache: + acquired = await pod_lock_manager.acquire_lock( + cronjob_id=MAVVRIK_FOCUS_EXPORT_JOB_NAME + ) + if not acquired: + verbose_proxy_logger.debug( + "Mavvrik FOCUS export: unable to acquire pod lock" + ) + return + try: + await self._run_scheduled_export() + finally: + await pod_lock_manager.release_lock( + cronjob_id=MAVVRIK_FOCUS_EXPORT_JOB_NAME + ) + else: + await self._run_scheduled_export() + + @staticmethod + async def init_mavvrik_focus_background_job( + scheduler: AsyncIOScheduler, + ) -> None: + """Register the Mavvrik FOCUS export job on the provided scheduler.""" + loggers: List[MavvrikFocusLogger] = [ + cb + for cb in litellm.logging_callback_manager.get_custom_loggers_for_type( + callback_type=MavvrikFocusLogger + ) + if type(cb) is MavvrikFocusLogger + ] + if not loggers: + verbose_proxy_logger.debug( + "No MavvrikFocusLogger registered; skipping scheduler" + ) + return + + logger = loggers[0] + trigger_kwargs = logger._build_scheduler_trigger() + scheduler.add_job( # type: ignore[attr-defined] + logger.initialize_mavvrik_focus_export_job, + id=MAVVRIK_FOCUS_EXPORT_JOB_NAME, + replace_existing=True, + **trigger_kwargs, + ) + verbose_proxy_logger.info( + "mavvrik_focus: background export job scheduled (%s)", trigger_kwargs + ) diff --git a/litellm/integrations/newrelic/__init__.py b/litellm/integrations/newrelic/__init__.py new file mode 100644 index 00000000000..5b0f5b9cb24 --- /dev/null +++ b/litellm/integrations/newrelic/__init__.py @@ -0,0 +1,10 @@ +""" +New Relic AI Monitoring Integration for LiteLLM + +This module provides integration with New Relic's AI Monitoring feature to track +LLM requests, responses, and usage metrics. +""" + +from litellm.integrations.newrelic.newrelic import NewRelicLogger + +__all__ = ["NewRelicLogger"] diff --git a/litellm/integrations/newrelic/newrelic.py b/litellm/integrations/newrelic/newrelic.py new file mode 100644 index 00000000000..753b8520337 --- /dev/null +++ b/litellm/integrations/newrelic/newrelic.py @@ -0,0 +1,926 @@ +""" +New Relic AI Monitoring Integration for LiteLLM + +This module provides integration with New Relic's AI Monitoring feature to track +LLM requests, responses, and usage metrics. + +Environment Variables (consumed by the New Relic agent at process bootstrap - +set via container env, or before invoking `newrelic-admin run-program`): + NEW_RELIC_LICENSE_KEY: Your New Relic license key (required) + NEW_RELIC_APP_NAME: Your application name (required) + +UI- and runtime-toggleable: + NEW_RELIC_AI_MONITORING_RECORD_CONTENT_ENABLED: Whether to record message + content (optional, default: true) + +Configuration: + Message logging can be controlled via (both must agree to record): + 1. turn_off_message_logging parameter - pass via callback initialization or config YAML + 2. NEW_RELIC_AI_MONITORING_RECORD_CONTENT_ENABLED env var + + Default behavior: Messages ARE recorded unless explicitly disabled by either method + Either method can disable recording - both must enable for recording to occur + +Usage - Python SDK: + import litellm + litellm.callbacks = ["newrelic"] + + # Or with explicit configuration: + from litellm.integrations.newrelic import NewRelicLogger + litellm.callbacks = [NewRelicLogger(turn_off_message_logging=True)] + +Usage - Proxy Server (config.yaml): + litellm_settings: + callbacks: ["newrelic"] + newrelic_params: + turn_off_message_logging: true # Disable message content recording + + # Or disable via environment variable: + # export NEW_RELIC_AI_MONITORING_RECORD_CONTENT_ENABLED=false + + # Ensure New Relic agent is initialized (use newrelic-admin or initialize manually) + # newrelic-admin run-program python your_app.py +""" + +import json +import os +import threading +import time +import uuid +from typing import Any, Dict, List, Optional, Tuple, Union + +import litellm +from litellm._logging import verbose_logger +from litellm.integrations.custom_logger import CustomLogger +from litellm.litellm_core_utils.redact_messages import should_redact_message_logging +from litellm.types.integrations.newrelic import NewRelicInitParams +from litellm.types.integrations.base_health_check import IntegrationHealthCheckStatus +from litellm.types.utils import ModelResponse, Message, StandardLoggingPayload + +try: + import newrelic.agent as _newrelic_agent +except ImportError: + _newrelic_agent = None # type: ignore + + +class NewRelicLogger(CustomLogger): + """ + New Relic logger for LiteLLM to send AI monitoring events. + + This logger creates two types of New Relic custom events: + 1. LlmChatCompletionSummary - One per completion request + 2. LlmChatCompletionMessage - One per message (request and response) + """ + + # Class-level state for supportability metric emission, shared across all instances. + # Protected by _metric_lock to ensure thread-safe access. + _last_metric_emission_time: float = 0.0 + _metric_lock = threading.Lock() + + def __init__(self, **kwargs): + ######################################################### + # Handle newrelic_params set as litellm.newrelic_params + ######################################################### + dict_newrelic_params = self._get_newrelic_params() + + # Use setdefault so constructor kwargs take priority over global params. + # model_dump() always returns all fields (including defaults), so update() + # would silently overwrite explicit constructor args like turn_off_message_logging=True. + for k, v in dict_newrelic_params.items(): + kwargs.setdefault(k, v) + + # CustomLogger.__init__ will set self.turn_off_message_logging from kwargs + super().__init__(**kwargs) + + # Check for required environment variables + self.license_key = os.getenv("NEW_RELIC_LICENSE_KEY") + self.app_name = os.getenv("NEW_RELIC_APP_NAME") + + # Validate configuration + if not self.license_key or not self.app_name: + verbose_logger.warning( + "New Relic integration requires NEW_RELIC_LICENSE_KEY and " + "NEW_RELIC_APP_NAME environment variables. Integration will be disabled." + ) + self.enabled = False + elif _newrelic_agent is None: + verbose_logger.error( + "New Relic Python agent not installed. Review the New Relic integration documentation at https://docs.litellm.ai/docs/observability/newrelic." + ) + self.enabled = False + else: + try: + # timeout=0 forces non-blocking startup: the agent connects in a + # background thread regardless of newrelic.ini / NEW_RELIC_STARTUP_TIMEOUT. + _newrelic_agent.register_application(timeout=0) + + self.enabled = True + verbose_logger.info( + f"New Relic AI Monitoring initialized for app: {self.app_name}, " + f"content recording: {self.record_content}" + ) + except Exception as e: + verbose_logger.error( + f"Failed to initialize New Relic agent: {e}. " + "Integration will be disabled." + ) + self.enabled = False + + def _get_newrelic_params(self) -> Dict: + """ + Get the newrelic_params from litellm.newrelic_params + + These are params specific to initializing the NewRelicLogger e.g. turn_off_message_logging + """ + dict_newrelic_params: Dict = {} + if litellm.newrelic_params is not None: + if isinstance(litellm.newrelic_params, NewRelicInitParams): + dict_newrelic_params = litellm.newrelic_params.model_dump() + elif isinstance(litellm.newrelic_params, Dict): + # only allow params that are of NewRelicInitParams + dict_newrelic_params = NewRelicInitParams( + **litellm.newrelic_params + ).model_dump() + return dict_newrelic_params + + @property + def record_content(self) -> bool: + """Whether to record message content in New Relic. + + Both turn_off_message_logging param AND NEW_RELIC_AI_MONITORING_RECORD_CONTENT_ENABLED + env var must agree to record content. If either disables recording, content will not + be recorded. Read at call time so UI config changes take effect without a restart. + Default: True (record content) unless explicitly disabled by either method. + """ + return (not self.turn_off_message_logging) and self._parse_bool_env( + "NEW_RELIC_AI_MONITORING_RECORD_CONTENT_ENABLED", True + ) + + def _parse_bool_env(self, var_name: str, default: bool = False) -> bool: + """Parse a boolean environment variable. + + Accepts true/false, 1/0, yes/no, on/off (case-insensitive, + whitespace-tolerant) — matching the convention used in + ``litellm/__init__.py`` and the standard library's + ``configparser.BOOLEAN_STATES``. Unrecognised values log a + warning and fall back to ``default`` rather than silently + flipping user intent. + """ + raw = os.getenv(var_name) + if not raw: + return default + value = raw.strip().lower() + if value in ("1", "true", "yes", "on"): + return True + if value in ("0", "false", "no", "off"): + return False + verbose_logger.warning( + f"{var_name}={raw!r} is not a recognised boolean " + f"(accepts true/false, 1/0, yes/no, on/off). " + f"Falling back to default ({default})." + ) + return default + + def _get_litellm_version(self) -> str: + """ + Get litellm version for supportability metrics. + + Returns: + Version string (e.g., "1.80.0") or "unknown" if unable to determine + """ + try: + from importlib.metadata import version + + return version("litellm") + except Exception as e: + verbose_logger.warning(f"Unable to determine litellm version: {e}") + return "unknown" + + def _emit_supportability_metric(self): + """ + Emit New Relic supportability metric for LiteLLM usage. + + Per spec, this metric should be emitted at least once every 27 hours + to indicate the library is in use. Format: + Supportability/Python/ML/LiteLLM/{version} + + This method updates _last_metric_emission_time and should + be called within a lock when checking periodic emission. + """ + try: + litellm_version = self._get_litellm_version() + metric_name = f"Supportability/Python/ML/LiteLLM/{litellm_version}" + + # Record metric with value of 1 (will be aggregated by New Relic) + app = _newrelic_agent.application() + + # Always update the timestamp so the 27-hour back-off applies + # regardless of whether the app is ready, preventing lock contention + # on every request when the agent is slow to register or never starts. + NewRelicLogger._last_metric_emission_time = time.time() + + if app and app.enabled: + app.record_custom_metric(metric_name, 1) + verbose_logger.info( + f"Emitted New Relic supportability metric: {metric_name}" + ) + else: + verbose_logger.info( + "New Relic application is not enabled; skipping metric recording." + ) + + except Exception as e: + verbose_logger.warning(f"Failed to emit supportability metric: {e}") + + def _check_and_emit_periodic_metric(self): + """ + Check if 27 hours have passed since last metric emission and re-emit if needed. + + Uses a mutex to ensure only one thread emits the metric even if multiple + requests are being processed concurrently. + """ + # Quick check without lock to avoid unnecessary locking + current_time = time.time() + time_since_last_emission = ( + current_time - NewRelicLogger._last_metric_emission_time + ) + + if time_since_last_emission >= 97200: # 27 hours = 97200 seconds + # Acquire lock to ensure only one thread emits + with NewRelicLogger._metric_lock: + # Double-check inside lock in case another thread just emitted + current_time = time.time() + time_since_last_emission = ( + current_time - NewRelicLogger._last_metric_emission_time + ) + + if time_since_last_emission >= 97200: + self._emit_supportability_metric() + + def _get_trace_context( + self, + kwargs: Dict, + standard_logging_object: Optional[StandardLoggingPayload] = None, + ) -> str: + """ + Get the New Relic trace ID for AI monitoring events. + + This integration runs in LiteLLM's async logging worker, outside the + New Relic agent's current transaction. Because we can't call + `newrelic.agent.current_trace_id()` to let the agent populate the + trace_id on AIM custom events, we manually simulate what the agent + would do. An AIM event without a trace_id is malformed per the NR + schema, so this method always returns a valid string. + + Resolution order: + 1. W3C traceparent header (litellm_params.metadata.headers.traceparent) - + what the agent would link to if we were in-transaction. + 2. StandardLoggingPayload.trace_id - LiteLLM's internal trace for + retry/fallback grouping. + 3. Generated UUID - synthetic grouping key when upstream context is + absent or parsing it fails. + + Span IDs are intentionally not emitted: any span ID recoverable from + the inbound traceparent is the caller's parent span, not ours. + + Returns: + trace_id: always a non-empty string. + """ + trace_id: Optional[str] = None + try: + litellm_params = kwargs.get("litellm_params") or {} + metadata = litellm_params.get("metadata") or {} + headers = metadata.get("headers") or {} + # Normalize header key lookup to be case-insensitive per W3C spec + traceparent = next( + (v for k, v in headers.items() if k.lower() == "traceparent"), None + ) + + if traceparent: + # Extract trace_id from traceparent header if available + # traceparent format: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00" + parts = traceparent.split("-") + if len(parts) == 4: + trace_id = parts[1] + + if not trace_id and standard_logging_object: + slo_trace_id = standard_logging_object.get("trace_id") + if slo_trace_id: + trace_id = slo_trace_id + + except Exception as e: + verbose_logger.warning( + f"Unable to parse New Relic trace context from upstream sources: {e}" + ) + + if not trace_id: + trace_id = uuid.uuid4().hex + verbose_logger.debug( + f"New Relic trace_id not available from distributed tracing headers or " + f"StandardLoggingPayload. Generated trace_id={trace_id} for AI monitoring " + f"event grouping." + ) + + return trace_id + + def _extract_completion_id(self, kwargs: Dict, response_obj: ModelResponse) -> str: + """ + Extract completion ID from kwargs or response_obj, or generate one. + """ + completion_id = None + + if response_obj: + completion_id = response_obj.get("id") + + if not completion_id: + completion_id = kwargs.get("litellm_call_id") + + # If still not found, generate UUID and log warning per spec + if not completion_id: + completion_id = str(uuid.uuid4()) + + return completion_id + + def _get_vendor( + self, + kwargs: Dict, + standard_logging_object: Optional[StandardLoggingPayload] = None, + ) -> str: + """Extract vendor/provider, preferring StandardLoggingPayload.""" + if standard_logging_object: + vendor = standard_logging_object.get("custom_llm_provider") + if vendor: + return vendor + litellm_params = kwargs.get("litellm_params", {}) or {} + return litellm_params.get("custom_llm_provider") or "litellm" + + def _get_model_names( + self, + kwargs: Dict, + response_obj: ModelResponse, + standard_logging_object: Optional[StandardLoggingPayload] = None, + ) -> Tuple[str, str]: + """ + Extract request and response model names, preferring StandardLoggingPayload + for the request model. + + Returns: + Tuple of (request_model, response_model) + """ + request_model = None + if standard_logging_object: + slo_model = standard_logging_object.get("model") + if slo_model: + request_model = str(slo_model) + if not request_model: + request_model = str(kwargs.get("model") or "unknown") + response_model: str = str(response_obj.get("model") or request_model) + return request_model, response_model + + def _extract_usage( + self, + response_obj: ModelResponse, + standard_logging_object: Optional[StandardLoggingPayload] = None, + ) -> Dict[str, int]: + """Extract usage statistics, preferring StandardLoggingPayload.""" + if standard_logging_object: + prompt = standard_logging_object.get("prompt_tokens") + completion = standard_logging_object.get("completion_tokens") + total = standard_logging_object.get("total_tokens") + if any(x is not None for x in [prompt, completion, total]): + return { + "prompt_tokens": prompt or 0, + "completion_tokens": completion or 0, + "total_tokens": total or 0, + } + + usage = response_obj.get("usage", None) + if not usage: + return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0} + + return { + "prompt_tokens": usage.get("prompt_tokens") or 0, + "completion_tokens": usage.get("completion_tokens") or 0, + "total_tokens": usage.get("total_tokens") or 0, + } + + def _get_finish_reason(self, response_obj: ModelResponse) -> str: + """ + Extract finish reason from first choice in the response. + + Returns "unknown" if choices are not present or finish_reason is not found. + """ + choices = response_obj.get("choices") or [] + if choices and len(choices) > 0: + return choices[0].get("finish_reason") or "unknown" + return "unknown" + + def _to_epoch_ms(self, t: Any) -> float: + """Convert a datetime or float timestamp to epoch milliseconds.""" + if hasattr(t, "timestamp"): + return t.timestamp() * 1000.0 + return float(t) * 1000.0 + + def _get_duration( + self, + kwargs: Dict, + start_time: Any, + end_time: Any, + standard_logging_object: Optional[StandardLoggingPayload] = None, + ) -> Optional[float]: + """ + Extract duration in milliseconds. + + Resolution order: + 1. StandardLoggingPayload.response_time (already computed by LiteLLM) + 2. llm_api_duration_ms from kwargs + 3. Calculated from start_time and end_time + """ + if standard_logging_object: + response_time = standard_logging_object.get("response_time") + if response_time is not None: + return ( + float(response_time) * 1000.0 + ) # SLO stores seconds; convert to ms + + duration_ms = kwargs.get("llm_api_duration_ms") + if duration_ms is not None: + return float(duration_ms) + + if start_time is not None and end_time is not None: + return self._to_epoch_ms(end_time) - self._to_epoch_ms(start_time) + + return None + + def _get_request_params( + self, + kwargs: Dict, + standard_logging_object: Optional[StandardLoggingPayload] = None, + ) -> Dict[str, Any]: + """ + Extract request parameters like temperature and max_tokens, preferring + StandardLoggingPayload.model_parameters. + + Returns dict with available parameters, omitting those not present. + """ + if standard_logging_object: + source_params = standard_logging_object.get("model_parameters") or {} + else: + source_params = kwargs.get("optional_params") or {} + + params = {} + + temperature = source_params.get("temperature") + if temperature is not None: + params["temperature"] = temperature + + max_tokens = source_params.get("max_tokens") + if max_tokens is not None: + params["max_tokens"] = max_tokens + + return params + + def _extract_message_content(self, message: Union[Message, Dict]) -> str: + """ + Extract content from a message, handling various formats. + + Handles tool calls, multimodal content (as JSON), and standard text content. + Returns empty string if content is None or missing. + """ + content = message.get("content") + + # Handle tool calls + if message.get("tool_calls"): + try: + return json.dumps(message["tool_calls"]) + except Exception: + return str(message["tool_calls"]) + + # Handle None or missing content + if content is None: + return "" + + # Handle list content (multimodal) + if isinstance(content, list): + try: + return json.dumps(content) + except Exception: + return str(content) + + # Handle non-string content + if not isinstance(content, str): + return str(content) + + return content + + def _extract_all_messages( + self, + kwargs: Dict, + response_obj: ModelResponse, + response_model: str, + vendor: str, + standard_logging_object: Optional[StandardLoggingPayload] = None, + ) -> List[Dict[str, Any]]: + """ + Extract all messages (request + response) with sequence numbers and timestamps. + + Processes request messages from StandardLoggingPayload.messages (preferred) or + kwargs["messages"] (fallback), and response messages from response_obj["choices"]. + Assigns sequential numbers starting at 0. + Adds timestamps from StandardLoggingPayload (preferred) or kwargs if available + (converted to epoch milliseconds). + """ + messages = [] + sequence = 0 + + # Extract timestamps, preferring StandardLoggingPayload + start_time = None + if standard_logging_object: + start_time = standard_logging_object.get("startTime") + if not start_time: + start_time = kwargs.get("start_time") + + end_time = None + if standard_logging_object: + end_time = standard_logging_object.get("endTime") + if not end_time: + end_time = kwargs.get("end_time") + + # Content is recorded only when the NR-specific switches allow it AND + # LiteLLM's wider redaction decision (turn_off_message_logging, dynamic + # params, headers) does not require redaction. Async streaming hands the + # callback an unredacted async_complete_streaming_response, so without + # this gate generated content would still reach NR even when the user + # has globally disabled message logging. + record_content = self.record_content and not should_redact_message_logging( + kwargs + ) + + # Extract request messages, preferring StandardLoggingPayload. + # SLO messages can be a string (serialized/redacted), so only use it when it's a list. + slo_messages = ( + standard_logging_object.get("messages") if standard_logging_object else None + ) + if isinstance(slo_messages, list): + request_messages = slo_messages + else: + request_messages = kwargs.get("messages") or [] + for msg in request_messages: + message_data = { + "role": msg.get("role") or "user", + "sequence": sequence, + "response.model": response_model, + "vendor": vendor, + } + + # Add timestamp for request message if available (convert to milliseconds) + if start_time is not None: + message_data["timestamp"] = int(self._to_epoch_ms(start_time)) + + if record_content: + message_data["content"] = self._extract_message_content(msg) + + messages.append(message_data) + sequence += 1 + + # Extract response messages from choices + choices = response_obj.get("choices") or [] + if choices and len(choices) > 0: + for choice in choices: + # Prefer "message" (non-streaming); fall back to "delta" (streaming-assembled) + message = choice.get("message", None) or choice.get("delta", None) + if message: + message_data = { + "role": message.get("role") or "assistant", + "sequence": sequence, + "response.model": response_model, + "vendor": vendor, + "is_response": True, + } + + # Add timestamp for response message if available (convert to milliseconds) + if end_time is not None: + message_data["timestamp"] = int(self._to_epoch_ms(end_time)) + + if record_content: + message_data["content"] = self._extract_message_content(message) + + messages.append(message_data) + sequence += 1 + + return messages + + def _record_summary_event( + self, + request_id: str, + trace_id: Optional[str], + request_model: str, + response_model: str, + vendor: str, + finish_reason: str, + num_messages: int, + usage: Dict[str, int], + duration: Optional[float] = None, + request_params: Optional[Dict[str, Any]] = None, + ): + """Record LlmChatCompletionSummary event to New Relic.""" + try: + event_data = { + "id": request_id, + "request_id": request_id, + "request.model": request_model, + "response.model": response_model, + "response.choices.finish_reason": finish_reason, + "response.number_of_messages": num_messages, + "vendor": vendor, + "ingest_source": "litellm", + "response.usage.prompt_tokens": usage["prompt_tokens"], + "response.usage.completion_tokens": usage["completion_tokens"], + "response.usage.total_tokens": usage["total_tokens"], + } + + # Add optional attributes if present + if trace_id: + event_data["trace_id"] = trace_id + + if duration is not None: + event_data["duration"] = duration + + # Add request parameters if present + if request_params: + if "temperature" in request_params: + event_data["request.temperature"] = request_params["temperature"] + if "max_tokens" in request_params: + event_data["request.max_tokens"] = request_params["max_tokens"] + + app = _newrelic_agent.application() + + if app and app.enabled: + app.record_custom_event("LlmChatCompletionSummary", event_data) + else: + verbose_logger.warning( + "New Relic application is not enabled; skipping summary event recording." + ) + + except Exception as e: + verbose_logger.warning(f"Failed to record New Relic summary event: {e}") + self.handle_callback_failure("newrelic") + + def _record_message_events( + self, + request_id: str, + llm_response_id: str, + trace_id: Optional[str], + messages: List[Dict[str, Any]], + ): + """Record LlmChatCompletionMessage events to New Relic. + + Args: + request_id: Agent-generated UUID that links to Summary event's id + llm_response_id: LLM's response ID (e.g., "chatcmpl-...") for message id format + trace_id: Trace ID for distributed tracing (None if not available) + messages: List of message dicts to record + """ + try: + app = _newrelic_agent.application() + + if not (app and app.enabled): + verbose_logger.warning( + "New Relic application is not enabled; skipping message event recording." + ) + return + + for message in messages: + sequence = message["sequence"] + event_data = { + "id": f"{llm_response_id}-{sequence}", + "request_id": request_id, + "completion_id": request_id, + "role": message["role"], + "sequence": sequence, + "response.model": message["response.model"], + "vendor": message["vendor"], + "ingest_source": "litellm", + "token_count": 0, # Per-message token counts are not available from LiteLLM + } + + # Add trace context if available + if trace_id: + event_data["trace_id"] = trace_id + + # Add content only if it was included in the message data + if "content" in message: + event_data["content"] = message["content"] + + # Add is_response only if True (per spec, omit for request messages) + if message.get("is_response"): + event_data["is_response"] = True + + # Forward actual request/response timestamp (ms) so NR uses the + # real LLM call window rather than the async-logger fire time. + # Requires newrelic>=11.2.0 which reads params["timestamp"] as + # the intrinsic event timestamp. + if "timestamp" in message: + event_data["timestamp"] = message["timestamp"] + + app.record_custom_event("LlmChatCompletionMessage", event_data) + + except Exception as e: + verbose_logger.warning(f"Failed to record New Relic message events: {e}") + self.handle_callback_failure("newrelic") + + def _record_error_metric(self): + """Record error metric to New Relic.""" + try: + if not self.enabled: + return + + self._check_and_emit_periodic_metric() + + app = _newrelic_agent.application() + if app and app.enabled: + app.record_custom_metric("LLM/LiteLLM/Error", 1) + except Exception as e: + verbose_logger.warning(f"Failed to record New Relic error metric: {e}") + self.handle_callback_failure("newrelic") + + def _process_success( + self, + kwargs: Dict, + response_obj: ModelResponse, + start_time: Optional[float] = None, + end_time: Optional[float] = None, + ): + """ + Core logic for processing successful LLM calls. + Used by both sync and async success event handlers. + """ + # Early exit if not enabled + if not self.enabled: + return + + # Check and emit periodic supportability metric if 27 hours have passed + self._check_and_emit_periodic_metric() + + # Use StandardLoggingPayload where available for normalized, pre-computed values + standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get( + "standard_logging_object" + ) + + # Get trace context + trace_id = self._get_trace_context(kwargs, standard_logging_object) + + # Generate unique request ID for this request (used as Summary event id) + request_id = str(uuid.uuid4()) + + # Extract data from response + llm_response_id = self._extract_completion_id(kwargs, response_obj) + vendor = self._get_vendor(kwargs, standard_logging_object) + request_model, response_model = self._get_model_names( + kwargs, response_obj, standard_logging_object + ) + usage = self._extract_usage(response_obj, standard_logging_object) + finish_reason = self._get_finish_reason(response_obj) + + # Extract additional summary event fields + duration = self._get_duration( + kwargs, start_time, end_time, standard_logging_object + ) + request_params = self._get_request_params(kwargs, standard_logging_object) + + # Extract all messages + messages = self._extract_all_messages( + kwargs, response_obj, response_model, vendor, standard_logging_object + ) + + # Record summary event + self._record_summary_event( + request_id=request_id, + trace_id=trace_id, + request_model=request_model, + response_model=response_model, + vendor=vendor, + finish_reason=finish_reason, + num_messages=len(messages), + usage=usage, + duration=duration, + request_params=request_params, + ) + + # Record message events + self._record_message_events( + request_id=request_id, + llm_response_id=llm_response_id, + trace_id=trace_id, + messages=messages, + ) + + async def async_health_check(self) -> IntegrationHealthCheckStatus: + """ + Check if the New Relic integration is healthy. + + Verifies that the integration is enabled and the New Relic agent + has an active, connected application, then records a small + `LiteLLMConnectionTest` custom event so the user can confirm the + end-to-end pipeline in the New Relic UI via NRQL: + `SELECT * FROM LiteLLMConnectionTest SINCE 1 hour ago`. + + The `LiteLLMConnectionTest` event type is intentionally outside the + `Llm*` family that AI Monitoring queries, so test events do not + appear in AI Monitoring dashboards. + """ + if not self.enabled: + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message="New Relic integration is disabled. Check that " + "NEW_RELIC_LICENSE_KEY and NEW_RELIC_APP_NAME are set and the " + "newrelic package is installed.", + ) + + try: + app = _newrelic_agent.application() + if not (app and app.enabled): + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message=( + "New Relic Python agent not installed. Review the New Relic integration documentation at https://docs.litellm.ai/docs/observability/newrelic." + ), + ) + + app.record_custom_event( + "LiteLLMConnectionTest", + { + "is_test_event": True, + "app_name": self.app_name, + "source": "litellm-proxy", + "timestamp": time.time(), + }, + ) + return IntegrationHealthCheckStatus(status="healthy", error_message=None) + except Exception as e: + return IntegrationHealthCheckStatus( + status="unhealthy", + error_message=str(e), + ) + + # CustomLogger interface implementation + + def log_pre_api_call(self, model, messages, kwargs): + """Unused per spec.""" + pass + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + """Unused per spec.""" + pass + + def log_success_event(self, kwargs, response_obj, start_time, end_time): + """ + Main success path for non-streaming requests. + + Note: New Relic's record_custom_event is synchronous but non-blocking + (in-memory operation), so it's safe to call from sync context. + """ + try: + self._process_success(kwargs, response_obj, start_time, end_time) + except Exception as e: + verbose_logger.warning(f"Error in New Relic log_success_event: {e}") + self.handle_callback_failure("newrelic") + + async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): + """ + Main success path for async/streaming requests. + + Note: New Relic's SDK is thread-safe and record_custom_event is fast, + so we can call it directly without asyncio.to_thread(). + """ + try: + self._process_success(kwargs, response_obj, start_time, end_time) + except Exception as e: + verbose_logger.warning(f"Error in New Relic async_log_success_event: {e}") + self.handle_callback_failure("newrelic") + + def log_failure_event(self, kwargs, response_obj, start_time, end_time): + """ + Log error metric for failed LLM calls (sync). + + Per spec: Do not send AI events on failure, only record error metric. + """ + try: + self._record_error_metric() + + except Exception as e: + verbose_logger.warning(f"Error in New Relic log_failure_event: {e}") + self.handle_callback_failure("newrelic") + + async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): + """ + Log error metric for failed LLM calls (async). + + Per spec: Do not send AI events on failure, only record error metric. + """ + try: + self._record_error_metric() + + except Exception as e: + verbose_logger.warning(f"Error in New Relic async_log_failure_event: {e}") + self.handle_callback_failure("newrelic") diff --git a/litellm/integrations/openmeter.py b/litellm/integrations/openmeter.py index 5a8ab4bcc9f..b234ab11ddb 100644 --- a/litellm/integrations/openmeter.py +++ b/litellm/integrations/openmeter.py @@ -65,7 +65,15 @@ class OpenMeterLogger(CustomLogger): "total_tokens": response_obj["usage"].get("total_tokens"), } - user_param = kwargs.get("user", None) # end-user passed in via 'user' param + # OPENMETER_TRUST_REQUEST_USER (default "true"): when set to "false", + # the request-supplied `user` field is ignored and the subject is + # resolved solely from the key-bound user_api_key_user_id. Proxies + # serving multi-tenant traffic enable this to prevent clients from + # forging attribution by setting `user` in the request body. + trust_request_user = ( + os.getenv("OPENMETER_TRUST_REQUEST_USER", "true").lower() != "false" + ) + user_param = kwargs.get("user", None) if trust_request_user else None # If no user provided directly, try to get it from token user_id if user_param is None: diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.py index 57738c356f7..5e683ce7b99 100644 --- a/litellm/integrations/otel/logger.py +++ b/litellm/integrations/otel/logger.py @@ -15,6 +15,7 @@ from litellm.integrations.otel.model.baggage import promoted_baggage from litellm.integrations.otel.model.config import OpenTelemetryV2Config from litellm.integrations.otel.plumbing.context import ( is_recordable_span, + request_root_span, resolve_parent_context, resolve_request_span_context, set_request_baggage, @@ -435,8 +436,12 @@ class OpenTelemetryV2(CustomLogger): attach(set_request_baggage(bag, context=get_current())) # The server span was started by the instrumentor before this ran, # so the Baggage processor (which only fires at span start) won't - # backfill it — stamp identity on it directly. - server_span = get_current_span() + # backfill it — stamp identity on it directly. Prefer the anchored + # root span over the ambient one so identity still lands on the + # server span when seeding from inside the live ``auth`` phase span + # (the auth-failure path), where ``get_current_span`` is the phase + # span, not the request's root. + server_span = request_root_span() or get_current_span() if is_recordable_span(server_span): # Re-capture the anchor here too: this runs post-auth with the # server span active and covers entrypoints that bypass diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py index 9fc09807369..2119527a8e5 100644 --- a/litellm/integrations/prometheus.py +++ b/litellm/integrations/prometheus.py @@ -24,14 +24,18 @@ from typing import ( import litellm from litellm._logging import print_verbose, verbose_logger -from litellm.integrations.custom_logger import CustomLogger -from litellm.integrations.prometheus_helpers.bounded_prometheus_series_tracker import ( - BoundedPrometheusSeriesTracker, +from litellm.exceptions import ( + validate_rate_limit_category, + validate_rate_limit_type, ) +from litellm.integrations.custom_logger import CustomLogger from litellm.integrations.prometheus_helpers import ( PrometheusLabelFactoryContext, _get_cached_end_user_id_for_cost_tracking, ) +from litellm.integrations.prometheus_helpers.bounded_prometheus_series_tracker import ( + BoundedPrometheusSeriesTracker, +) from litellm.litellm_core_utils.core_helpers import ( get_litellm_metadata_from_kwargs, get_metadata_variable_name_from_kwargs, @@ -42,6 +46,9 @@ from litellm.proxy._types import ( LiteLLM_UserTable, UserAPIKeyAuth, ) +from litellm.repositories.organization_repository import OrganizationRepository +from litellm.repositories.team_repository import TeamRepository +from litellm.repositories.user_repository import UserRepository from litellm.types.integrations.prometheus import * from litellm.types.integrations.prometheus import ( _sanitize_prometheus_label_name, @@ -78,6 +85,20 @@ class PrometheusLogger(CustomLogger): # Always initialize label_filters, even for non-premium users self.label_filters = self._parse_prometheus_config() + # Cache resolved label sets per metric. Several entries in + # ``PrometheusMetricLabels.get_labels`` read module-level toggles + # (e.g. ``litellm.prometheus_emit_stream_label``, + # ``litellm.prometheus_emit_rate_limit_labels``) that can be + # changed at runtime. Prometheus counters/gauges/histograms are + # created with a *fixed* ``labelnames`` set; if a runtime call + # to ``get_labels_for_metric`` returned a different set, the + # subsequent ``counter.labels(**_labels)`` would raise a + # ``ValueError`` from the prometheus client. Snapshotting at + # logger init time pins the label set for the lifetime of the + # logger so toggling these flags only takes effect after a + # restart, keeping init-time and runtime label sets in sync. + self._cached_metric_labels: Dict[str, List[str]] = {} + _custom_buckets = litellm.prometheus_latency_buckets self.latency_buckets = ( tuple(_custom_buckets) @@ -1033,13 +1054,27 @@ class PrometheusLogger(CustomLogger): self, metric_name: DEFINED_PROMETHEUS_METRICS ) -> List[str]: """ - Get the labels for a metric, filtered if configured + Get the labels for a metric, filtered if configured. + + The result is cached on the instance so the label set used to + construct each Prometheus metric at ``__init__`` time stays in lock + step with the label set passed to ``counter.labels(...)`` at + runtime, even if the underlying module-level toggles consulted by + :meth:`PrometheusMetricLabels.get_labels` (e.g. + ``litellm.prometheus_emit_rate_limit_labels``, + ``litellm.prometheus_emit_stream_label``) are flipped after the + logger has been created. """ + cached = self._cached_metric_labels.get(metric_name) + if cached is not None: + return cached + # Get default labels for this metric from PrometheusMetricLabels default_labels = PrometheusMetricLabels.get_labels(metric_name) # If no label filtering is configured for this metric, use default labels if metric_name not in self.label_filters: + self._cached_metric_labels[metric_name] = default_labels return default_labels # Get configured labels for this metric @@ -1050,6 +1085,7 @@ class PrometheusLogger(CustomLogger): label for label in default_labels if label in configured_labels ] + self._cached_metric_labels[metric_name] = filtered_labels return filtered_labels def _track_end_user_metric_series( @@ -2029,14 +2065,8 @@ class PrometheusLogger(CustomLogger): Proxy level tracking - failed client side requests - labelnames=[ - "end_user", - "hashed_api_key", - "api_key_alias", - REQUESTED_MODEL, - "team", - "team_alias", - ] + EXCEPTION_LABELS, + See :attr:`PrometheusMetricLabels.litellm_proxy_failed_requests_metric` + for the authoritative list of labels emitted on this metric. """ from litellm.litellm_core_utils.litellm_logging import ( StandardLoggingPayloadSetup, @@ -2059,6 +2089,9 @@ class PrometheusLogger(CustomLogger): model_id = _metadata.get("model_info", {}).get("id") or request_data.get( "model_info", {} ).get("id") + rate_limit_category, rate_limit_type = self._extract_rate_limit_labels( + original_exception + ) enum_values = UserAPIKeyLabelValues( end_user=user_api_key_dict.end_user_id, user=user_api_key_dict.user_id, @@ -2073,6 +2106,8 @@ class PrometheusLogger(CustomLogger): status_code=str(status_code), exception_status=str(status_code), exception_class=self._get_exception_class_name(original_exception), + rate_limit_category=rate_limit_category, + rate_limit_type=rate_limit_type, tags=_tags, route=user_api_key_dict.request_route, client_ip=_metadata.get("requester_ip_address"), @@ -2690,7 +2725,7 @@ class PrometheusLogger(CustomLogger): Args: guardrail_name: Name of the guardrail latency_seconds: Execution latency in seconds - status: "success" or "error" + status: "success", "error", or "intervened" error_type: Type of error if any, None otherwise hook_type: "pre_call", "during_call", or "post_call" """ @@ -2843,6 +2878,33 @@ class PrometheusLogger(CustomLogger): @staticmethod def _get_exception_class_name(exception: Exception) -> str: + # Some exception types pin the ``exception_class`` label to a legacy + # value for back-compat with existing dashboards (e.g. proxy-side 429s + # keep reporting as "HTTPException"). Honor that opt-in marker before + # deriving the label from the runtime class name. Reading it via + # ``getattr`` keeps this core integrations module free of a transitive + # ``fastapi`` dependency. + legacy_class_name = getattr(exception, "prometheus_exception_class_name", None) + if isinstance(legacy_class_name, str) and legacy_class_name: + return legacy_class_name + + # Same back-compat reasoning for ``BudgetExceededError``: the unified + # rate-limit error work attached ``.llm_provider`` to budget errors + # too (so callbacks reading ``StandardLoggingPayload`` get provider + # attribution). Without this short-circuit, the provider prefix below + # would silently flip the label from "BudgetExceededError" to e.g. + # "Openai.BudgetExceededError" and break dashboards keyed on the + # original value. + try: + from litellm.exceptions import BudgetExceededError + except ImportError: + BudgetExceededError = None # type: ignore[assignment,misc] + + if BudgetExceededError is not None and isinstance( + exception, BudgetExceededError + ): + return "BudgetExceededError" + exception_class_name = "" if hasattr(exception, "llm_provider"): exception_class_name = getattr(exception, "llm_provider") or "" @@ -2857,6 +2919,27 @@ class PrometheusLogger(CustomLogger): exception_class_name += exception.__class__.__name__ return exception_class_name + @staticmethod + def _extract_rate_limit_labels( + exception: Optional[Exception], + ) -> Tuple[Optional[str], Optional[str]]: + """ + Pull the unified ``category`` / ``rate_limit_type`` fields off any + exception that declares them (``litellm.RateLimitError`` and bare- + Exception subclasses like ``BudgetExceededError``). + + Values are validated against the :class:`RateLimitErrorCategory` / + :class:`RateLimitType` enums so unrelated third-party exceptions that + happen to declare ``.category`` / ``.rate_limit_type`` string attributes + can't leak garbage into Prometheus label cardinality. + """ + if exception is None: + return None, None + return ( + validate_rate_limit_category(getattr(exception, "category", None)), + validate_rate_limit_type(getattr(exception, "rate_limit_type", None)), + ) + async def log_success_fallback_event( self, original_model_group: str, kwargs: dict, original_exception: Exception ): @@ -3198,12 +3281,12 @@ class PrometheusLogger(CustomLogger): page_size: int, page: int ) -> Tuple[List[LiteLLM_UserTable], Optional[int]]: skip = (page - 1) * page_size - users = await prisma_client.db.litellm_usertable.find_many( + users = await UserRepository(prisma_client).table.find_many( skip=skip, take=page_size, order={"created_at": "desc"}, ) - total_count = await prisma_client.db.litellm_usertable.count() + total_count = await UserRepository(prisma_client).table.count() return users, total_count await self._initialize_budget_metrics( @@ -3226,13 +3309,13 @@ class PrometheusLogger(CustomLogger): async def fetch_orgs(page_size: int, page: int) -> Tuple[list, Optional[int]]: skip = (page - 1) * page_size - orgs = await prisma_client.db.litellm_organizationtable.find_many( + orgs = await OrganizationRepository(prisma_client).table.find_many( skip=skip, take=page_size, order={"created_at": "desc"}, include={"litellm_budget_table": True}, ) - total_count = await prisma_client.db.litellm_organizationtable.count() + total_count = await OrganizationRepository(prisma_client).table.count() return orgs, total_count await self._initialize_budget_metrics( @@ -3300,14 +3383,14 @@ class PrometheusLogger(CustomLogger): try: # Get total user count - total_users = await prisma_client.db.litellm_usertable.count() + total_users = await UserRepository(prisma_client).table.count() self.litellm_total_users_metric.set(total_users) verbose_logger.debug( f"Prometheus: set litellm_total_users to {total_users}" ) # Get total team count - total_teams = await prisma_client.db.litellm_teamtable.count() + total_teams = await TeamRepository(prisma_client).table.count() self.litellm_teams_count_metric.set(total_teams) verbose_logger.debug( f"Prometheus: set litellm_teams_count to {total_teams}" diff --git a/litellm/integrations/websearch_interception/ARCHITECTURE.md b/litellm/integrations/websearch_interception/ARCHITECTURE.md index 3aa0a1558d7..ce7f01c5a2a 100644 --- a/litellm/integrations/websearch_interception/ARCHITECTURE.md +++ b/litellm/integrations/websearch_interception/ARCHITECTURE.md @@ -244,6 +244,9 @@ search_tools: - search_tool_name: "my-tavily-tool" litellm_params: search_provider: "tavily" + - search_tool_name: "my-you-com-tool" + litellm_params: + search_provider: "you_com" ``` --- diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index 37528e7dcd5..79f9b16bba0 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -1339,8 +1339,13 @@ class WebSearchInterceptionLogger(CustomLogger): websearch_params: WebSearchInterceptionConfig = {} if "websearch_interception_params" in litellm_settings: websearch_params = litellm_settings["websearch_interception_params"] - elif "websearch_interception" in callback_specific_params: - websearch_params = callback_specific_params["websearch_interception"] + elif "websearch_interception" in callback_specific_params and isinstance( + callback_specific_params["websearch_interception"], dict + ): + websearch_params = cast( + WebSearchInterceptionConfig, + callback_specific_params["websearch_interception"], + ) # Use classmethod to initialize from config return WebSearchInterceptionLogger.from_config_yaml(websearch_params) diff --git a/litellm/interactions/agents/utils.py b/litellm/interactions/agents/utils.py index d16a9597f53..e9405928a3d 100644 --- a/litellm/interactions/agents/utils.py +++ b/litellm/interactions/agents/utils.py @@ -2,11 +2,40 @@ Utility functions for the Agents API SDK. """ -from typing import Optional +from typing import Dict, Mapping, Optional from litellm.llms.base_llm.agents.transformation import BaseAgentsAPIConfig +def merge_agent_headers( + *, + dynamic_headers: Optional[Mapping[str, str]] = None, + static_headers: Optional[Mapping[str, str]] = None, +) -> Optional[Dict[str, str]]: + """Merge outbound HTTP headers for A2A agent calls. + + Merge rules: + - Start with ``dynamic_headers`` (values extracted from the incoming client request). + - Overlay ``static_headers`` (admin-configured per agent). + - Comparison is case-insensitive (HTTP headers are case-insensitive), so a + static ``Authorization`` strips any dynamic ``authorization`` before the + static value is written. The static side's casing is preserved. + + If both contain the same header (case-insensitively), ``static_headers`` wins. + """ + merged: Dict[str, str] = {} + + if dynamic_headers: + merged.update({str(k): str(v) for k, v in dynamic_headers.items()}) + + if static_headers: + static_lower = {str(k).lower() for k in static_headers} + merged = {k: v for k, v in merged.items() if k.lower() not in static_lower} + merged.update({str(k): str(v) for k, v in static_headers.items()}) + + return merged or None + + def get_provider_agents_api_config( custom_llm_provider: Optional[str], ) -> Optional[BaseAgentsAPIConfig]: diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.py index 3776d276912..eb01359cdc0 100644 --- a/litellm/litellm_core_utils/cli_token_utils.py +++ b/litellm/litellm_core_utils/cli_token_utils.py @@ -37,7 +37,7 @@ def get_litellm_gateway_api_key( """ Get the stored CLI API key for use with LiteLLM SDK. - This function reads the token file created by `litellm-proxy login` + This function reads the token file created by `lite login` and returns the API key for use in Python scripts. Args: diff --git a/litellm/litellm_core_utils/custom_logger_registry.py b/litellm/litellm_core_utils/custom_logger_registry.py index fd402b90d88..a7fae104c92 100644 --- a/litellm/litellm_core_utils/custom_logger_registry.py +++ b/litellm/litellm_core_utils/custom_logger_registry.py @@ -25,6 +25,7 @@ from litellm.integrations.datadog.datadog_metrics import DatadogMetricsLogger from litellm.integrations.deepeval import DeepEvalLogger from litellm.integrations.dotprompt import DotpromptManager from litellm.integrations.focus.focus_logger import FocusLogger +from litellm.integrations.mavvrik_focus.mavvrik_focus_logger import MavvrikFocusLogger from litellm.integrations.vantage.vantage_logger import VantageLogger from litellm.integrations.galileo import GalileoObserve from litellm.integrations.gcs_bucket.gcs_bucket import GCSBucketLogger @@ -39,6 +40,7 @@ from litellm.integrations.langsmith import LangsmithLogger from litellm.integrations.litellm_agent import LiteLLMAgentModelResolver from litellm.integrations.literal_ai import LiteralAILogger from litellm.integrations.mlflow import MlflowLogger +from litellm.integrations.newrelic import NewRelicLogger from litellm.integrations.openmeter import OpenMeterLogger from litellm.integrations.opentelemetry import OpenTelemetry from litellm.integrations.opik.opik import OpikLogger @@ -102,8 +104,10 @@ class CustomLoggerRegistry: "gitlab": GitLabPromptManager, "cloudzero": CloudZeroLogger, "focus": FocusLogger, + "mavvrik": MavvrikFocusLogger, "vantage": VantageLogger, "posthog": PostHogLogger, + "newrelic": NewRelicLogger, } try: diff --git a/litellm/litellm_core_utils/duration_parser.py b/litellm/litellm_core_utils/duration_parser.py index 6d2b4226ff4..036d691c686 100644 --- a/litellm/litellm_core_utils/duration_parser.py +++ b/litellm/litellm_core_utils/duration_parser.py @@ -131,6 +131,8 @@ def get_next_standardized_reset_time( # Handle different time units if unit == "d": return _handle_day_reset(current_time, base_midnight, value, tz) + elif unit == "w": + return _handle_day_reset(current_time, base_midnight, value * 7, tz) elif unit == "h": return _handle_hour_reset(current_time, base_midnight, value) elif unit == "m": diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py index 95658d08767..ffaa5140916 100644 --- a/litellm/litellm_core_utils/exception_mapping_utils.py +++ b/litellm/litellm_core_utils/exception_mapping_utils.py @@ -655,7 +655,11 @@ def exception_type( # type: ignore # noqa: PLR0915 custom_llm_provider == "anthropic" or custom_llm_provider == "anthropic_text" ): # one of the anthropics - if "prompt is too long" in error_str or "prompt: length" in error_str: + if ( + "prompt is too long" in error_str + or "prompt: length" in error_str + or ExceptionCheckers.is_error_str_context_window_exceeded(error_str) + ): exception_mapping_worked = True raise ContextWindowExceededError( message="AnthropicError - {}".format(error_str), diff --git a/litellm/litellm_core_utils/get_litellm_params.py b/litellm/litellm_core_utils/get_litellm_params.py index 16875816037..4f4c046ec59 100644 --- a/litellm/litellm_core_utils/get_litellm_params.py +++ b/litellm/litellm_core_utils/get_litellm_params.py @@ -4,7 +4,7 @@ from litellm.llms.openai.data_residency import infer_openai_data_residency # Pre-define optional kwargs keys as frozenset for O(1) lookups # These are extracted from kwargs only if present, avoiding unnecessary .get() calls -_OPTIONAL_KWARGS_KEYS = frozenset( +OPTIONAL_KWARGS_KEYS = frozenset( { "azure_ad_token", "tenant_id", @@ -32,14 +32,19 @@ _OPTIONAL_KWARGS_KEYS = frozenset( "aws_sts_endpoint", "aws_external_id", "aws_bedrock_runtime_endpoint", + "aws_bedrock_project_id", "gigachat_scope", "gigachat_auth_url", "gigachat_access_token", "tpm", "rpm", + "use_xai_oauth", } ) +# Backward-compatible alias for existing imports/tests. +_OPTIONAL_KWARGS_KEYS = OPTIONAL_KWARGS_KEYS + def _get_base_model_from_litellm_call_metadata( metadata: Optional[dict], @@ -167,7 +172,7 @@ def get_litellm_params( # Sparse extraction: only add kwargs keys that are actually present if kwargs: - for key in _OPTIONAL_KWARGS_KEYS: + for key in OPTIONAL_KWARGS_KEYS: if key in kwargs: litellm_params[key] = kwargs[key] diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py index 6bdb83d9f9b..dd817f309da 100644 --- a/litellm/litellm_core_utils/get_llm_provider_logic.py +++ b/litellm/litellm_core_utils/get_llm_provider_logic.py @@ -1,5 +1,5 @@ import re -from typing import Optional, Tuple +from typing import Optional, Tuple, cast from urllib.parse import urlparse import litellm @@ -7,7 +7,7 @@ from litellm.constants import REPLICATE_MODEL_NAME_WITH_ID_LENGTH from litellm.llms.openai_like.json_loader import JSONProviderRegistry from litellm.secret_managers.main import get_secret, get_secret_str -from ..types.router import LiteLLM_Params +from ..types.router import GenericLiteLLMParams, LiteLLM_Params def _endpoint_matches_api_base(endpoint: str, api_base: str) -> bool: @@ -159,7 +159,7 @@ def get_llm_provider( # noqa: PLR0915 custom_llm_provider: Optional[str] = None, api_base: Optional[str] = None, api_key: Optional[str] = None, - litellm_params: Optional[LiteLLM_Params] = None, + litellm_params: Optional[GenericLiteLLMParams] = None, ) -> Tuple[str, str, Optional[str], Optional[str]]: """ Returns the provider for a given model name - e.g. 'azure/chatgpt-v-2' -> 'azure' @@ -178,7 +178,7 @@ def get_llm_provider( # noqa: PLR0915 ) if litellm.LiteLLMProxyChatConfig._should_use_litellm_proxy_by_default( - litellm_params=litellm_params + litellm_params=cast(Optional[LiteLLM_Params], litellm_params) ): return litellm.LiteLLMProxyChatConfig.litellm_proxy_get_custom_llm_provider_info( model=model, api_base=api_base, api_key=api_key @@ -186,12 +186,10 @@ def get_llm_provider( # noqa: PLR0915 ## IF LITELLM PARAMS GIVEN ## if litellm_params: - assert ( - custom_llm_provider is None and api_base is None and api_key is None - ), "Either pass in litellm_params or the custom_llm_provider/api_base/api_key. Otherwise, these values will be overriden." - custom_llm_provider = litellm_params.custom_llm_provider - api_base = litellm_params.api_base - api_key = litellm_params.api_key + if custom_llm_provider is None and api_base is None and api_key is None: + custom_llm_provider = litellm_params.custom_llm_provider + api_base = litellm_params.api_base + api_key = litellm_params.api_key dynamic_api_key = None # check if llm provider provided @@ -235,6 +233,7 @@ def get_llm_provider( # noqa: PLR0915 api_base=api_base, api_key=api_key, dynamic_api_key=dynamic_api_key, + litellm_params=litellm_params, ) # check if llm provider part of model name @@ -250,6 +249,7 @@ def get_llm_provider( # noqa: PLR0915 api_base=api_base, api_key=api_key, dynamic_api_key=dynamic_api_key, + litellm_params=litellm_params, ) elif model.split("/", 1)[0] in litellm.provider_list: custom_llm_provider = model.split("/", 1)[0] @@ -575,6 +575,7 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 api_base: Optional[str], api_key: Optional[str], dynamic_api_key: Optional[str], + litellm_params: Optional[GenericLiteLLMParams] = None, ) -> Tuple[str, str, Optional[str], Optional[str]]: """ Returns: @@ -642,7 +643,7 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 api_base, dynamic_api_key, ) = litellm.BedrockMantleChatConfig()._get_openai_compatible_provider_info( - api_base, api_key + api_base, api_key, litellm_params=litellm_params ) elif custom_llm_provider == "nvidia_nim": # nvidia_nim is openai compatible, we just need to set this to custom_openai and have the api_base be https://api.endpoints.anyscale.com/v1 @@ -664,6 +665,11 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 or get_secret_str("NVIDIA_RIVA_API_KEY") or get_secret_str("NVIDIA_NIM_API_KEY") ) + elif custom_llm_provider == "soniox": + api_base = ( + api_base or get_secret_str("SONIOX_API_BASE") or "https://api.soniox.com" + ) + dynamic_api_key = api_key or get_secret_str("SONIOX_API_KEY") elif custom_llm_provider == "cerebras": api_base = ( api_base or get_secret("CEREBRAS_API_BASE") or "https://api.cerebras.ai/v1" diff --git a/litellm/litellm_core_utils/get_supported_openai_params.py b/litellm/litellm_core_utils/get_supported_openai_params.py index b8cdc8210fc..23b51faafc7 100644 --- a/litellm/litellm_core_utils/get_supported_openai_params.py +++ b/litellm/litellm_core_utils/get_supported_openai_params.py @@ -22,9 +22,11 @@ def get_supported_openai_params( # noqa: PLR0915 ``` Args: - base_model: For Azure, the true underlying model (e.g. ``"azure/gpt-5.2"``) - when the deployment name differs. Used for model-type detection so that - non-standard deployment names route to the correct config. + base_model: An optional capability hint for deployments whose ``model`` + label isn't recognized on its own (e.g. an Azure deployment name, or a + friendly Bedrock alias). It is additive: the result is the union of the + params supported by ``model`` and by ``base_model``, so a hint can only + add capabilities, never strip ones the real model already supports. Returns: - List if custom_llm_provider is mapped @@ -52,7 +54,15 @@ def get_supported_openai_params( # noqa: PLR0915 provider_config = None if provider_config and request_type == "chat_completion": - return provider_config.get_supported_openai_params(model=base_model or model) + supported_params = provider_config.get_supported_openai_params(model=model) + if base_model and base_model != model: + base_model_params = provider_config.get_supported_openai_params( + model=base_model + ) + supported_params = list( + dict.fromkeys([*supported_params, *base_model_params]) + ) + return supported_params if custom_llm_provider == "bedrock": return litellm.AmazonConverseConfig().get_supported_openai_params(model=model) @@ -331,6 +341,11 @@ def get_supported_openai_params( # noqa: PLR0915 return ElevenLabsAudioTranscriptionConfig().get_supported_openai_params( model=model ) + elif custom_llm_provider == "soniox": + if request_type == "transcription": + return litellm.SonioxAudioTranscriptionConfig().get_supported_openai_params( + model=model + ) elif custom_llm_provider in litellm._custom_providers: if request_type == "chat_completion": provider_config = litellm.ProviderConfigManager.get_provider_chat_config( diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 11e5fee7602..1447b078387 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -37,6 +37,10 @@ from litellm import ( turn_off_message_logging, ) from litellm._logging import _is_debugging_on, _redact_string, verbose_logger +from litellm.exceptions import ( + validate_rate_limit_category, + validate_rate_limit_type, +) from litellm._uuid import uuid from litellm.batches.batch_utils import _handle_completed_batch from litellm.caching.caching import DualCache, InMemoryCache @@ -154,6 +158,7 @@ from ..integrations.litellm_agent import LiteLLMAgentModelResolver from ..integrations.literal_ai import LiteralAILogger from ..integrations.logfire_logger import LogfireLevel, LogfireLogger from ..integrations.lunary import LunaryLogger +from ..integrations.newrelic import NewRelicLogger from ..integrations.openmeter import OpenMeterLogger from ..integrations.opik.opik import OpikLogger from ..integrations.posthog import PostHogLogger @@ -3528,6 +3533,14 @@ class Logging(LiteLLMLoggingBaseClass): elif isinstance(result, ModelResponse): return result + if isinstance( + result, + (ResponseCompletedEvent, ResponseIncompleteEvent, ResponseFailedEvent), + ): + result = result.response + if isinstance(result, ResponsesAPIResponse): + return self._translate_responses_api_response_to_model_response(result) + httpx_response = self.model_call_details.get("httpx_response", None) if httpx_response and isinstance(httpx_response, httpx.Response): result = litellm.AnthropicConfig().transform_response( @@ -3560,6 +3573,55 @@ class Logging(LiteLLMLoggingBaseClass): ) return result + def _translate_responses_api_response_to_model_response( + self, result: ResponsesAPIResponse + ) -> ModelResponse: + """ + Convert a Responses API response into a ModelResponse for spend_logs. + + The proxy UI parses spend_log rows expecting chat-completion shape + (response.choices[0].message); a raw ResponsesAPIResponse dump (output[...]) + would render as empty in the Logs tab. Translation also yields full + choices/message detail downstream consumers can rely on. + """ + from litellm.completion_extras.litellm_responses_transformation.transformation import ( + LiteLLMResponsesTransformationHandler, + ) + + try: + return LiteLLMResponsesTransformationHandler().transform_response( + model=self.model, + raw_response=result, + model_response=litellm.ModelResponse(), + logging_obj=self, + request_data={}, + messages=[], + optional_params={}, + litellm_params={}, + encoding=litellm.encoding, + ) + except Exception as e: + verbose_logger.debug( + "Responses API -> ModelResponse translation failed for " + "anthropic_messages logging (%s); falling back to minimal " + "usage-only ModelResponse to keep the spend_logs row.", + str(e), + ) + model_response = litellm.ModelResponse() + model_response.model = self.model + usage = getattr(result, "usage", None) + if usage is not None and ResponseAPILoggingUtils._is_response_api_usage( + usage + ): + setattr( + model_response, + "usage", + ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( + usage + ), + ) + return model_response + def _handle_non_streaming_google_genai_generate_content_response_logging( self, result: Any ) -> ModelResponse: @@ -4114,6 +4176,17 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 focus_logger = FocusLogger() _in_memory_loggers.append(focus_logger) return focus_logger # type: ignore + elif logging_integration == "mavvrik": + from litellm.integrations.mavvrik_focus.mavvrik_focus_logger import ( + MavvrikFocusLogger, + ) + + for callback in _in_memory_loggers: + if type(callback) is MavvrikFocusLogger: + return callback # type: ignore + mavvrik_focus_logger = MavvrikFocusLogger() + _in_memory_loggers.append(mavvrik_focus_logger) + return mavvrik_focus_logger # type: ignore elif logging_integration == "vantage": from litellm.integrations.vantage.vantage_logger import VantageLogger @@ -4409,6 +4482,13 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 gitlab_logger = GitLabPromptManager(gitlab_config=gitlab_config) _in_memory_loggers.append(gitlab_logger) return gitlab_logger # type: ignore + elif logging_integration == "newrelic": + for callback in _in_memory_loggers: + if isinstance(callback, NewRelicLogger): + return callback # type: ignore + newrelic_logger = NewRelicLogger() + _in_memory_loggers.append(newrelic_logger) + return newrelic_logger # type: ignore return None except Exception as e: verbose_logger.exception( @@ -4710,6 +4790,10 @@ def get_custom_logger_compatible_class( # noqa: PLR0915 for callback in _in_memory_loggers: if isinstance(callback, SMTPEmailLogger): return callback + elif logging_integration == "newrelic": + for callback in _in_memory_loggers: + if isinstance(callback, NewRelicLogger): + return callback return None except Exception as e: @@ -5312,12 +5396,27 @@ class StandardLoggingPayloadSetup: else str(original_exception) ) + # Duck-typed read so bare-Exception subclasses like + # `litellm.BudgetExceededError` can participate without joining the + # RateLimitError hierarchy (which would break `except BudgetExceededError`). + # Validated against the enum value sets so a third-party exception that + # happens to declare a `.category` or `.rate_limit_type` string attribute + # can't leak garbage into the payload or Prometheus label cardinality. + rate_limit_category = validate_rate_limit_category( + getattr(original_exception, "category", None) + ) + rate_limit_type = validate_rate_limit_type( + getattr(original_exception, "rate_limit_type", None) + ) + return StandardLoggingPayloadErrorInformation( error_code=error_status, error_class=error_class, llm_provider=_llm_provider_in_exception, traceback=traceback_info, error_message=error_message if original_exception else "", + error_rate_limit_category=rate_limit_category, + error_rate_limit_type=rate_limit_type, ) @staticmethod diff --git a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py index 8da66d4600d..413ddb71bf8 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py +++ b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py @@ -6,6 +6,7 @@ from typing import Any, Dict, List, Literal, Optional, Tuple import litellm from litellm.constants import OPENAI_FILE_SEARCH_COST_PER_1K_CALLS +from litellm.litellm_core_utils.llm_cost_calc.utils import _get_web_search_requests from litellm.types.llms.openai import ( FileSearchTool, ResponsesAPIResponse, @@ -339,8 +340,7 @@ class StandardBuiltInToolCostTracking: # and _handle_web_search_cost() is never called. if ( hasattr(usage, "server_tool_use") - and usage.server_tool_use is not None - and usage.server_tool_use.web_search_requests is not None + and _get_web_search_requests(usage.server_tool_use) is not None ): return True return False @@ -352,8 +352,7 @@ class StandardBuiltInToolCostTracking: elif usage is not None: if ( hasattr(usage, "server_tool_use") - and usage.server_tool_use is not None - and usage.server_tool_use.web_search_requests is not None + and _get_web_search_requests(usage.server_tool_use) is not None ): return True elif ( diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py index f39c942f90f..d75850984a9 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/utils.py +++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py @@ -1,7 +1,7 @@ # What is this? ## Helper utilities for cost_per_token() -from typing import Literal, Optional, Tuple, TypedDict, cast +from typing import Any, Literal, Optional, Tuple, TypedDict, cast import litellm from litellm._logging import verbose_logger @@ -42,6 +42,26 @@ def _get_token_detail_value(details: object, key: str) -> Optional[int]: return value if isinstance(value, int) else None +def _get_web_search_requests(server_tool_use: Any) -> Optional[int]: + """ + Tolerantly read ``web_search_requests`` from a ``server_tool_use`` value + that may be ``None``, a ``dict``, a ``ServerToolUse`` pydantic instance, + or any other object supporting attribute access. + + Returns ``None`` when the value cannot be resolved — callers can + distinguish "absent" from "zero" using ``is None``. + + See https://github.com/BerriAI/litellm/issues/26153 — ``stream_chunk_builder`` + historically left this as a plain ``dict``, which broke direct attribute + access in cost calculation. + """ + if server_tool_use is None: + return None + if isinstance(server_tool_use, dict): + return server_tool_use.get("web_search_requests") + return getattr(server_tool_use, "web_search_requests", None) + + def _is_above_128k(tokens: float) -> bool: if tokens > 128000: return True @@ -929,6 +949,43 @@ def calculate_image_response_cost_from_usage( return prompt_cost + completion_cost +def calculate_image_response_web_search_cost( + image_response: ImageResponse, + custom_llm_provider: str, + model_info: ModelInfo, +) -> float: + """ + Cost of Google Search grounding performed during image generation. + + The grounding request count is carried on the image usage object by the + provider transformers; it is billed with the same per-request accounting + used for chat completions. + """ + usage = image_response.usage + if usage is None: + return 0.0 + + web_search_requests = getattr(usage, "web_search_requests", None) + if not web_search_requests: + return 0.0 + + from litellm.llms import get_cost_for_web_search_request + + synthetic_usage = Usage( + prompt_tokens_details=PromptTokensDetailsWrapper( + web_search_requests=web_search_requests + ) + ) + return ( + get_cost_for_web_search_request( + custom_llm_provider=custom_llm_provider, + usage=synthetic_usage, + model_info=model_info, + ) + or 0.0 + ) + + class CostCalculatorUtils: @staticmethod def _call_type_has_image_response(call_type: str) -> bool: diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py index 2547fd4d8c6..4e5b53a13d7 100644 --- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py +++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py @@ -633,11 +633,6 @@ def convert_to_model_response_object( # noqa: PLR0915 thinking_blocks = choice["message"]["thinking_blocks"] provider_specific_fields["thinking_blocks"] = thinking_blocks - if reasoning_content: - provider_specific_fields["reasoning_content"] = ( - reasoning_content - ) - message = Message( content=content, role=choice["message"]["role"] or "assistant", diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index 1460dbaf0a9..5059e612f2f 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -3653,17 +3653,13 @@ from litellm.types.llms.bedrock import ContentBlock as BedrockContentBlock from litellm.types.llms.bedrock import DocumentBlock as BedrockDocumentBlock from litellm.types.llms.bedrock import ImageBlock as BedrockImageBlock from litellm.types.llms.bedrock import SourceBlock as BedrockSourceBlock +from litellm.types.llms.bedrock import BedrockToolSpec from litellm.types.llms.bedrock import ToolBlock as BedrockToolBlock -from litellm.types.llms.bedrock import ( - ToolInputSchemaBlock as BedrockToolInputSchemaBlock, -) -from litellm.types.llms.bedrock import ToolJsonSchemaBlock as BedrockToolJsonSchemaBlock from litellm.types.llms.bedrock import SearchResultBlock from litellm.types.llms.bedrock import ToolResultBlock as BedrockToolResultBlock from litellm.types.llms.bedrock import ( ToolResultContentBlock as BedrockToolResultContentBlock, ) -from litellm.types.llms.bedrock import ToolSpecBlock as BedrockToolSpecBlock from litellm.types.llms.bedrock import ToolUseBlock as BedrockToolUseBlock from litellm.types.llms.bedrock import VideoBlock as BedrockVideoBlock @@ -4294,6 +4290,49 @@ def _deduplicate_bedrock_tool_content( return _deduplicate_bedrock_content_blocks(tool_content, "toolResult") +def _rename_duplicate_bedrock_document_names( + contents: List[BedrockMessageBlock], +) -> List[BedrockMessageBlock]: + """ + Rename duplicate document names across all messages in a Bedrock request. + + Document names are derived from a content hash, so the same file appearing + in multiple conversation turns produces identical names and Bedrock rejects + the request with "Messages can not contain duplicate document names". The + first occurrence keeps its original name so prompt-cache prefixes stay + stable; later occurrences get a deterministic positional suffix + (``_2``, ``_3``, ...), bumped further if the suffixed name already + belongs to another document (e.g. an organic name ending in ``_2``). + """ + used_names: Set[str] = set() + for message in contents: + for block in message.get("content") or []: + document = block.get("document") + if isinstance(document, dict) and document.get("name"): + used_names.add(document["name"]) + + name_counts: Dict[str, int] = {} + for message in contents: + for block in message.get("content") or []: + document = block.get("document") + if not isinstance(document, dict): + continue + name = document.get("name") + if not name: + continue + count = name_counts.get(name, 0) + 1 + name_counts[name] = count + if count > 1: + suffix = count + new_name = f"{name}_{suffix}" + while new_name in used_names: + suffix += 1 + new_name = f"{name}_{suffix}" + used_names.add(new_name) + document["name"] = new_name + return contents + + def _sort_bedrock_assistant_content_blocks( blocks: List[BedrockContentBlock], ) -> List[BedrockContentBlock]: @@ -4702,6 +4741,12 @@ class BedrockConverseMessagesProcessor: guardContent={"text": {"text": element["text"]}} ) _parts.append(_part) + elif element["type"] in ("grounding_source", "query"): + # Contextual grounding tags are guardrail metadata; the + # model only needs the underlying text, so render them + # as plain text on the generate path. + _part = BedrockContentBlock(text=element["text"]) + _parts.append(_part) elif element["type"] == "image_url": format: Optional[str] = None if isinstance(element["image_url"], dict): @@ -4942,7 +4987,7 @@ class BedrockConverseMessagesProcessor: llm_provider=llm_provider, ) - return contents + return _rename_duplicate_bedrock_document_names(contents) @staticmethod def translate_thinking_blocks_to_reasoning_content_blocks( @@ -5134,6 +5179,12 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 guardContent={"text": {"text": element["text"]}} ) _parts.append(_part) + elif element["type"] in ("grounding_source", "query"): + # Contextual grounding tags are guardrail metadata; the + # model only needs the underlying text, so render them as + # plain text on the generate path. + _part = BedrockContentBlock(text=element["text"]) + _parts.append(_part) elif element["type"] == "image_url": format: Optional[str] = None if isinstance(element["image_url"], dict): @@ -5364,7 +5415,7 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 llm_provider=llm_provider, ) - return contents + return _rename_duplicate_bedrock_document_names(contents) def make_valid_bedrock_tool_name(input_tool_name: str) -> str: @@ -5496,6 +5547,7 @@ def _bedrock_tools_pt( ] """ from litellm.llms.bedrock.common_utils import ( + get_bedrock_base_model, normalize_json_schema_custom_types_to_object, ) from litellm.litellm_core_utils.prompt_templates.common_utils import unpack_defs @@ -5503,6 +5555,11 @@ def _bedrock_tools_pt( _valid_json_schema_root_types = frozenset( ("array", "boolean", "integer", "null", "number", "object", "string") ) + # Only Claude on Bedrock honours strict tool schemas; other families + # (Nova, Llama, GPT-OSS) reject the strict field outright. + supports_strict_tools = bool( + model and get_bedrock_base_model(model).startswith("anthropic") + ) tool_block_list: List[BedrockToolBlock] = [] for tool_idx, tool in enumerate(tools): # Check if tool is already a BedrockToolBlock (e.g., systemTool for Nova grounding) @@ -5548,17 +5605,16 @@ def _bedrock_tools_pt( normalize_json_schema_custom_types_to_object(parameters) if parameters.get("type") not in _valid_json_schema_root_types: parameters["type"] = "object" - tool_input_schema = BedrockToolInputSchemaBlock( - json=BedrockToolJsonSchemaBlock( - type=parameters["type"], - properties=parameters.get("properties", {}), - required=parameters.get("required", []), - ) + tool_block = cast( + BedrockToolBlock, + BedrockToolSpec( + name=name, + description=description, + parameters=parameters, + strict=tool.get("function", {}).get("strict", None), + supports_strict_tools=supports_strict_tools, + ), ) - tool_spec = BedrockToolSpecBlock( - inputSchema=tool_input_schema, name=name, description=description - ) - tool_block = BedrockToolBlock(toolSpec=tool_spec) tool_block_list.append(tool_block) ## ADD CACHE POINT TOOL BLOCK ## diff --git a/litellm/litellm_core_utils/realtime_streaming.py b/litellm/litellm_core_utils/realtime_streaming.py index 772f058d9bb..c8f87d96e2f 100644 --- a/litellm/litellm_core_utils/realtime_streaming.py +++ b/litellm/litellm_core_utils/realtime_streaming.py @@ -47,6 +47,7 @@ class RealTimeStreaming: user_api_key_dict: Optional[Any] = None, request_data: Optional[Dict] = None, backend_uses_beta_protocol: Optional[bool] = None, + force_transcription_model: Optional[str] = None, ): self.websocket = websocket self.backend_ws = backend_ws @@ -100,6 +101,11 @@ class RealTimeStreaming: self._flushing_pending_messages_until_setup: bool = False self._pending_messages_until_setup: List[str] = [] self._pending_messages_byte_total: int = 0 + # Whether this is a transcription-only session (session.type == "transcription", + # e.g. gpt-realtime-whisper). Such sessions must not be sent response.create and + # their input_audio_transcription.completed usage drives duration-based cost. + self._force_transcription_model = force_transcription_model + self._is_transcription_session: bool = force_transcription_model is not None # Per-connection caps for pre-setup audio frames (message count + total bytes). _MAX_BUFFERED_MESSAGES: int = 200 @@ -111,8 +117,12 @@ class RealTimeStreaming: "input_audio_buffer.append", "input_audio_buffer.commit", "input_audio_buffer.clear", + "input_audio_buffer.end", ] ) + _CLIENT_AUDIO_BUFFER_COMMIT_TYPES = frozenset( + ["input_audio_buffer.commit", "input_audio_buffer.end"] + ) _AUDIO_FORMAT_MAP: Dict[str, Dict[str, Any]] = { "pcm16": {"type": "audio/pcm", "rate": 24000}, "g711_ulaw": {"type": "audio/G711-ulaw", "rate": 8000}, @@ -144,7 +154,7 @@ class RealTimeStreaming: return True return False - def store_message(self, message: Union[str, bytes, OpenAIRealtimeEvents]): + def store_message(self, message: Union[str, bytes, dict, OpenAIRealtimeEvents]): """Store message in list""" if isinstance(message, bytes): message = message.decode("utf-8") @@ -154,22 +164,20 @@ class RealTimeStreaming: else: message_obj = cast(Dict[str, Any], json.loads(cast(str, message))) self._collect_tool_calls_from_response_done(cast(dict, message_obj)) + if not self._should_store_message(message_obj): + return try: event_type = message_obj.get("type", "") if event_type in self._SESSION_EVENT_TYPES: - typed_obj = OpenAIRealtimeStreamSessionEvents(**message_obj) # type: ignore + typed_obj: OpenAIRealtimeEvents = OpenAIRealtimeStreamSessionEvents(**message_obj) # type: ignore else: - # Use the base object as a safe catch-all for all other event types - # (both beta and GA), so unknown/new event names never raise here. + # Catch-all base object so unknown/new event names never raise. typed_obj = OpenAIRealtimeStreamResponseBaseObject(**message_obj) # type: ignore except Exception as e: verbose_logger.debug(f"Error parsing message for logging: {e}") - # Don't re-raise — a parse failure must not drop or delay the message - if self._should_store_message(message_obj): - self.messages.append(message_obj) # type: ignore[arg-type] + self.messages.append(message_obj) # type: ignore[arg-type] return - if self._should_store_message(typed_obj): - self.messages.append(typed_obj) + self.messages.append(typed_obj) def _collect_user_input_from_client_event(self, message: Union[str, dict]) -> None: """Extract user text content from client WebSocket events for spend logging.""" @@ -209,6 +217,8 @@ class RealTimeStreaming: self.session_tools = tools # GA: session.type is required; log it for traceability but no action needed verbose_logger.debug(f"Realtime session.type: {session.get('type')}") + if session.get("type") == "transcription": + self._is_transcription_session = True except (json.JSONDecodeError, AttributeError, TypeError): pass @@ -225,6 +235,55 @@ class RealTimeStreaming: except (AttributeError, TypeError): pass + def _detect_transcription_session_from_backend( + self, event_obj: Union[dict, OpenAIRealtimeEvents] + ) -> None: + """Flag transcription-only sessions from backend session events.""" + try: + event_type = event_obj.get("type", "") + if event_type in ( + "transcription_session.created", + "transcription_session.updated", + ): + self._is_transcription_session = True + elif event_type in ("session.created", "session.updated"): + session = cast(dict, event_obj).get("session", {}) or {} + if session.get("type") == "transcription": + self._is_transcription_session = True + except (AttributeError, TypeError): + pass + + def _capture_transcription_usage( + self, event_obj: Union[dict, OpenAIRealtimeEvents] + ) -> None: + """ + Append a usage-only transcription completed event to the logged results so + the cost calculator can bill it by audio duration. The default logged event + types exclude this event, so it is captured here directly for transcription + sessions rather than widening logging for every realtime session. Only the + type and usage are kept — the transcript is already captured separately in + input_messages, so it is not duplicated into the response log here. + """ + try: + usage = event_obj.get("usage") + if usage is None: + return + # If this event type is already captured by store_message (e.g. the user + # logs all realtime events), don't append a second copy. + if self._should_store_message(event_obj): + return + self.messages.append( + cast( + OpenAIRealtimeEvents, + { + "type": "conversation.item.input_audio_transcription.completed", + "usage": usage, + }, + ) + ) + except (AttributeError, TypeError): + pass + def _collect_tool_calls_from_response_done( self, event_obj: Union[dict, OpenAIRealtimeEvents] ) -> None: @@ -285,6 +344,7 @@ class RealTimeStreaming: backend, False if the provider transformation produced no output and the message was effectively dropped. """ + message = self._enforce_transcription_session_model(message) if self.provider_config: transformed = self.provider_config.transform_realtime_request( message, self.model, self.session_configuration_request @@ -304,12 +364,128 @@ class RealTimeStreaming: await self.backend_ws.send(message) # type: ignore[union-attr, attr-defined] return True + def _enforce_transcription_session_model(self, message: str) -> str: + """Force client transcription session updates to the authorized model. + + `/v1/realtime?intent=transcription` may intentionally omit `model` from + the upstream URL for Azure compatibility, but the proxy still authorizes + a resolved LiteLLM model before opening the backend websocket. If a + client later sends a transcription `session.update`, any model embedded + in that update must be rewritten to the same authorized model instead of + allowing a post-auth model/deployment switch. + + Normal realtime sessions keep their independent nested transcription + model behavior because `_force_transcription_model` is only set for + transcription-intent websocket routes. + """ + if self._force_transcription_model is None: + return message + + try: + message_obj = json.loads(message) + except (json.JSONDecodeError, TypeError): + return message + + if message_obj.get("type") not in ( + "session.update", + "transcription_session.update", + ): + return message + + session = message_obj.get("session") + if not isinstance(session, dict): + return message + + if session.get("type") == "transcription": + self._is_transcription_session = True + + authorized_model = self._force_transcription_model + changed = False + + transcription = session.get("input_audio_transcription") + if ( + isinstance(transcription, dict) + and transcription.get("model") != authorized_model + ): + session["input_audio_transcription"] = { + **transcription, + "model": authorized_model, + } + changed = True + + audio = session.get("audio") + if isinstance(audio, dict): + audio_input = audio.get("input") + if isinstance(audio_input, dict): + nested_transcription = audio_input.get("transcription") + if ( + isinstance(nested_transcription, dict) + and nested_transcription.get("model") != authorized_model + ): + session["audio"] = { + **audio, + "input": { + **audio_input, + "transcription": { + **nested_transcription, + "model": authorized_model, + }, + }, + } + changed = True + + if not changed: + return message + return json.dumps(message_obj) + def _uses_deferred_backend_setup(self) -> bool: """True when setup is deferred until the client's first session.update.""" if self.provider_config is None: return False return not self.provider_config.requires_session_configuration() + @staticmethod + def _collapse_buffered_audio_messages(messages: List[str]) -> List[str]: + """Apply ``input_audio_buffer.clear`` semantics before replaying buffered frames. + + During deferred Gemini Live setup, ``clear`` is buffered alongside appends. + On flush each append becomes a provider ``realtimeInput``; ``clear`` must + drop preceding uncommitted appends instead of being forwarded as a no-op. + """ + collapsed: List[str] = [] + pending_appends: List[str] = [] + + for message in messages: + try: + msg_type = json.loads(message).get("type") + except (json.JSONDecodeError, TypeError): + collapsed.extend(pending_appends) + pending_appends = [] + collapsed.append(message) + continue + + if msg_type == "input_audio_buffer.append": + pending_appends.append(message) + elif msg_type == "input_audio_buffer.clear": + pending_appends = [] + elif msg_type in RealTimeStreaming._CLIENT_AUDIO_BUFFER_COMMIT_TYPES: + collapsed.extend(pending_appends) + pending_appends = [] + collapsed.append(message) + else: + collapsed.extend(pending_appends) + pending_appends = [] + collapsed.append(message) + + collapsed.extend(pending_appends) + return collapsed + + def _sync_pending_messages_byte_total(self) -> None: + self._pending_messages_byte_total = sum( + len(message.encode("utf-8")) + for message in self._pending_messages_until_setup + ) + def _should_buffer_client_message_until_setup(self, message: str) -> bool: if not self._uses_deferred_backend_setup(): return False @@ -325,6 +501,18 @@ class RealTimeStreaming: return msg_obj.get("type") in RealTimeStreaming._CLIENT_AUDIO_BUFFER_TYPES def _buffer_pending_message_until_setup(self, message: str) -> None: + try: + msg_type = json.loads(message).get("type") + except (json.JSONDecodeError, TypeError): + msg_type = None + + if msg_type == "input_audio_buffer.clear": + self._pending_messages_until_setup = self._collapse_buffered_audio_messages( + self._pending_messages_until_setup + [message] + ) + self._sync_pending_messages_byte_total() + return + msg_bytes = len(message.encode("utf-8")) if ( len(self._pending_messages_until_setup) @@ -342,7 +530,9 @@ class RealTimeStreaming: ) async def _flush_pending_messages_until_setup(self) -> bool: - pending = self._pending_messages_until_setup + pending = self._collapse_buffered_audio_messages( + self._pending_messages_until_setup + ) self._pending_messages_until_setup = [] self._pending_messages_byte_total = 0 for idx, message in enumerate(pending): @@ -358,8 +548,7 @@ class RealTimeStreaming: for msg in self._pending_messages_until_setup ) verbose_logger.debug( - "Failed to flush buffered client message after setup: %s " - "(%d buffered message(s) retained)", + "Failed to flush buffered client message after setup: %s (%d buffered message(s) retained)", e, len(unsent), ) @@ -376,8 +565,7 @@ class RealTimeStreaming: return True except Exception as e: verbose_logger.warning( - "Failed to translate %s to beta protocol, forwarding " - "untranslated event to client: %s", + "Failed to translate %s to beta protocol, forwarding untranslated event to client: %s", event.get("type"), e, ) @@ -429,16 +617,13 @@ class RealTimeStreaming: if sent: self._guardrail_turn_detection_update_sent = True - def _has_realtime_guardrails(self) -> bool: - """Return True if any callback is registered for realtime guardrail event types.""" + def _has_realtime_guardrails_for_event_hooks( + self, + event_hooks: List[Any], + ) -> bool: + """Return True if any callback would run for one of ``event_hooks``.""" from litellm.integrations.custom_guardrail import CustomGuardrail - from litellm.types.guardrails import GuardrailEventHooks - _realtime_event_types = [ - GuardrailEventHooks.realtime_input_transcription, - GuardrailEventHooks.pre_call, - GuardrailEventHooks.post_call, - ] return any( isinstance(cb, CustomGuardrail) and any( @@ -446,31 +631,45 @@ class RealTimeStreaming: data=self.request_data, event_type=et, ) - for et in _realtime_event_types + for et in event_hooks ) for cb in litellm.callbacks ) + def _has_realtime_guardrails(self) -> bool: + """Return True if any callback is registered for realtime guardrail event types.""" + from litellm.types.guardrails import GuardrailEventHooks + + return self._has_realtime_guardrails_for_event_hooks( + [ + GuardrailEventHooks.realtime_input_transcription, + GuardrailEventHooks.pre_call, + GuardrailEventHooks.post_call, + ] + ) + def _has_audio_transcription_guardrails(self) -> bool: - """Return True if any callback needs to run on audio transcriptions (VAD path). + """Return True when a guardrail is configured for the audio/VAD transcript path. - When this returns True, we inject a session.update to disable the LLM's - auto-response so the guardrail can gate it first. - - Must match the same hook criteria as run_realtime_guardrails() so that - any guardrail that would actually check the transcript also disables - auto-response before the transcript arrives. + Only ``realtime_input_transcription`` hooks disable ``server_vad`` auto-response. + ``pre_call`` / ``post_call`` guardrails (e.g. Model Armor on chat completions) + must not override ``turn_detection.create_response`` on realtime sessions. """ - return self._has_realtime_guardrails() + from litellm.types.guardrails import GuardrailEventHooks + + return self._has_realtime_guardrails_for_event_hooks( + [GuardrailEventHooks.realtime_input_transcription] + ) async def run_realtime_guardrails( self, transcript: str, item_id: Optional[str] = None, pre_block_backend_message: Optional[str] = None, + event_hooks: Optional[List[Any]] = None, ) -> bool: """ - Run registered guardrails on a completed speech transcription. + Run registered guardrails on realtime text (transcript, user message, tool output). Returns True if blocked (synthetic warning already sent to client). Returns False if clean (caller should send response.create to the backend). @@ -481,15 +680,17 @@ class RealTimeStreaming: specific message to be sent first — e.g. Gemini Live requires a matching ``toolResponse`` immediately after a ``toolCall`` before any other client messages can be accepted. + + ``event_hooks`` selects which guardrail modes to evaluate. Audio/VAD + transcript completion uses ``realtime_input_transcription`` only; + typed user messages and tool outputs use ``pre_call``. """ from litellm.integrations.custom_guardrail import CustomGuardrail from litellm.types.guardrails import GuardrailEventHooks - _realtime_event_types = [ - GuardrailEventHooks.realtime_input_transcription, - GuardrailEventHooks.pre_call, - GuardrailEventHooks.post_call, - ] + if event_hooks is None: + event_hooks = [GuardrailEventHooks.realtime_input_transcription] + _realtime_event_types = event_hooks _check_data = {**self.request_data, "transcript": transcript} _already_run: set = set() @@ -705,48 +906,58 @@ class RealTimeStreaming: self.store_message(event_str) await self._send_event_to_client(event, event_str) - async def _handle_raw_backend_message(self, raw_response) -> bool: + @staticmethod + def _parse_backend_event(raw_response: str) -> Optional[dict]: + """Parse a backend frame once. Returns None for non-JSON or non-object frames.""" + try: + event = json.loads(raw_response) + except (json.JSONDecodeError, TypeError): + return None + return event if isinstance(event, dict) else None + + async def _handle_raw_backend_message( + self, event_obj: dict, raw_response: str + ) -> bool: """Process a backend message without provider_config (raw path). Returns True if the caller should skip the default store+forward (i.e. continue the loop). """ - try: - event_obj = json.loads(raw_response) + event_type = event_obj.get("type") - # For audio/VAD guardrail path: once the session is ready, tell the backend - # not to auto-respond after VAD detects end-of-speech. We send the - # session.created to the client FIRST so the client is always in sync, then - # inject the session.update so a potential error from the backend doesn't - # arrive before the client sees session.created. - if ( - event_obj.get("type") == "session.created" - and self._has_audio_transcription_guardrails() - ): - self.store_message(raw_response) - await self.websocket.send_text(raw_response) - await self._send_to_backend(self._make_disable_auto_response_message()) + self._detect_transcription_session_from_backend(event_obj) + + # Send session.created to the client FIRST so it stays in sync, then inject + # the disable-auto-response session.update; otherwise a backend error could + # reach the client before it sees session.created. + if ( + event_type == "session.created" + and self._has_audio_transcription_guardrails() + ): + self.store_message(event_obj) + await self.websocket.send_text(raw_response) + await self._send_to_backend(self._make_disable_auto_response_message()) + return True + + if event_type == "conversation.item.input_audio_transcription.completed": + transcript = event_obj.get("transcript", "") + self._collect_user_input_from_backend_event(event_obj) + self.store_message(event_obj) + await self.websocket.send_text(raw_response) + + # Transcription-only sessions (e.g. gpt-realtime-whisper) have no + # assistant turn: capture audio-duration usage for cost and never + # trigger response.create. + if self._is_transcription_session: + self._capture_transcription_usage(event_obj) return True - if ( - event_obj.get("type") - == "conversation.item.input_audio_transcription.completed" - ): - transcript = event_obj.get("transcript", "") - self._collect_user_input_from_backend_event(event_obj) - ## LOGGING — must happen before continue below - self.store_message(raw_response) - # Forward transcript to client so user sees what they said - await self.websocket.send_text(raw_response) - blocked = await self.run_realtime_guardrails( - transcript, - item_id=event_obj.get("item_id"), - ) - if not blocked: - # Clean — trigger LLM response - await self._send_to_backend(json.dumps({"type": "response.create"})) - return True - except (json.JSONDecodeError, AttributeError): - pass + blocked = await self.run_realtime_guardrails( + transcript, + item_id=event_obj.get("item_id"), + ) + if not blocked: + await self._send_to_backend(json.dumps({"type": "response.create"})) + return True return False async def backend_to_client_send_messages(self): @@ -779,25 +990,25 @@ class RealTimeStreaming: ) continue else: - handled = await self._handle_raw_backend_message(raw_response) - if handled: - continue - ## LOGGING - self.store_message(raw_response) - - # If the client opted into beta protocol, translate GA event - # names/shapes back to the beta equivalents before forwarding. - if self._client_wants_beta: - try: - event_dict = json.loads(raw_response) - translated = self._translate_event_to_beta(event_dict) - if translated is None: - continue # drop GA-only events (e.g. conversation.item.done) - await self.websocket.send_text(json.dumps(translated)) - except Exception: - await self.websocket.send_text(raw_response) - else: + event = self._parse_backend_event(raw_response) + if event is None: await self.websocket.send_text(raw_response) + continue + + if await self._handle_raw_backend_message(event, raw_response): + continue + self.store_message(event) + + if not self._client_wants_beta: + await self.websocket.send_text(raw_response) + continue + + translated = self._translate_event_to_beta(event) + if translated is None: + continue + await self.websocket.send_text( + raw_response if translated is event else json.dumps(translated) + ) except websockets.exceptions.ConnectionClosed as e: # type: ignore verbose_logger.exception( @@ -927,41 +1138,43 @@ class RealTimeStreaming: def _translate_event_to_beta(event: dict) -> Optional[dict]: """Translate a single GA event dict to its beta equivalent. - Returns None if the event should be dropped entirely (e.g. the GA-only - conversation.item.done has no beta counterpart). - Returns the (possibly mutated copy of the) event otherwise. + Returns None when the event must be dropped (the GA-only + conversation.item.done has no beta counterpart). Returns the original + event object unchanged when no translation applies, so the caller can + forward the raw frame without re-serializing; otherwise returns a + translated copy. """ event_type = event.get("type", "") - # conversation.item.done has no beta equivalent — the client already - # received conversation.item.created (translated from .added). if event_type == "conversation.item.done": return None - # Shallow-copy so we don't mutate the stored message + renamed_type = RealTimeStreaming._GA_TO_BETA_EVENT_TYPES.get(event_type) + has_item = isinstance(event.get("item"), dict) + response = event.get("response") + has_response_output = isinstance(response, dict) and isinstance( + response.get("output"), list + ) + if renamed_type is None and not has_item and not has_response_output: + return event + translated = dict(event) - - # Rename the type field - if event_type in RealTimeStreaming._GA_TO_BETA_EVENT_TYPES: - translated["type"] = RealTimeStreaming._GA_TO_BETA_EVENT_TYPES[event_type] - - # Fix content block types inside items (response.done output list, - # conversation.item.created item content, etc.) - if "item" in translated and isinstance(translated["item"], dict): + if renamed_type is not None: + translated["type"] = renamed_type + if has_item: translated["item"] = RealTimeStreaming._translate_item_content_types( dict(translated["item"]) ) - if "response" in translated and isinstance(translated["response"], dict): + if has_response_output: resp = dict(translated["response"]) - if "output" in resp and isinstance(resp["output"], list): - resp["output"] = [ - ( - RealTimeStreaming._translate_item_content_types(dict(o)) - if isinstance(o, dict) - else o - ) - for o in resp["output"] - ] + resp["output"] = [ + ( + RealTimeStreaming._translate_item_content_types(dict(o)) + if isinstance(o, dict) + else o + ) + for o in resp["output"] + ] translated["response"] = resp return translated @@ -994,6 +1207,8 @@ class RealTimeStreaming: guardrail_turn_detection_injected = False msg_type: Optional[str] = None try: + from litellm.types.guardrails import GuardrailEventHooks + msg_obj = json.loads(message) msg_type = msg_obj.get("type") @@ -1046,6 +1261,7 @@ class RealTimeStreaming: blocked = await self.run_realtime_guardrails( output_text, pre_block_backend_message=sanitized_msg, + event_hooks=[GuardrailEventHooks.pre_call], ) if blocked: # ``_pending_guardrail_message`` is @@ -1071,7 +1287,8 @@ class RealTimeStreaming: combined_text = " ".join(texts) if combined_text: blocked = await self.run_realtime_guardrails( - combined_text + combined_text, + event_hooks=[GuardrailEventHooks.pre_call], ) if blocked: # Store the guardrail reason so the next response.create diff --git a/litellm/litellm_core_utils/redact_messages.py b/litellm/litellm_core_utils/redact_messages.py index dbc9cabdc7a..763596336a0 100644 --- a/litellm/litellm_core_utils/redact_messages.py +++ b/litellm/litellm_core_utils/redact_messages.py @@ -17,6 +17,10 @@ from litellm.integrations.custom_logger import CustomLogger from litellm.litellm_core_utils.core_helpers import ( get_metadata_variable_name_from_kwargs, ) +from litellm.llms.vertex_ai.common_utils import ( + redact_vertex_ai_metadata_from_litellm_params, + redact_vertex_ai_metadata_from_logged_object, +) from litellm.secret_managers.main import str_to_bool from litellm.types.utils import StandardCallbackDynamicParams @@ -119,10 +123,12 @@ def _redact_standard_logging_object(model_call_details: dict): # ResponsesAPIResponse format - redact content in output items if isinstance(response.get("output"), list): _redact_responses_api_output_dict(response["output"], redacted_str) + redact_vertex_ai_metadata_from_logged_object(response) elif isinstance(response, dict) and "choices" in response: # ModelResponse dict format - redact content in choices if isinstance(response.get("choices"), list): _redact_model_response_dict_choices(response["choices"], redacted_str) + redact_vertex_ai_metadata_from_logged_object(response) elif isinstance(response, str): standard_logging_object["response"] = redacted_str else: @@ -164,6 +170,7 @@ def perform_redaction(model_call_details: dict, result): model_call_details["prompt"] = "" model_call_details["input"] = "" _redact_standard_logging_object(model_call_details) + redact_vertex_ai_metadata_from_litellm_params(model_call_details) # Redact streaming response if ( @@ -174,6 +181,7 @@ def perform_redaction(model_call_details: dict, result): if hasattr(_streaming_response, "choices"): for choice in _streaming_response.choices: _redact_choice_content(choice) + redact_vertex_ai_metadata_from_logged_object(_streaming_response) elif hasattr(_streaming_response, "output"): _redact_responses_api_output(_streaming_response.output) # Redact reasoning field in ResponsesAPIResponse @@ -200,12 +208,14 @@ def perform_redaction(model_call_details: dict, result): if hasattr(_result, "choices") and _result.choices is not None: for choice in _result.choices: _redact_choice_content(choice) + redact_vertex_ai_metadata_from_logged_object(_result) elif isinstance(_result, dict) and "choices" in _result: # Handle dict representation of ModelResponse (e.g., from model_dump()) if _result.get("choices") is not None: _redact_model_response_dict_choices( _result["choices"], "redacted-by-litellm" ) + redact_vertex_ai_metadata_from_logged_object(_result) elif isinstance(_result, dict) and "output" in _result: if isinstance(_result.get("output"), list): _redact_responses_api_output_dict( diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py index fe7c62c3842..b495b183ec0 100644 --- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py +++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py @@ -20,6 +20,7 @@ from litellm.types.utils import ( ServerToolUse, Usage, ) +from litellm._logging import verbose_logger from litellm.utils import print_verbose, token_counter if TYPE_CHECKING: @@ -79,6 +80,54 @@ class ChunkProcessor: model_response._hidden_params = chunk.get("_hidden_params", {}) return model_response + @staticmethod + def apply_provider_assembled_streaming_metadata( + response: ModelResponse, + chunks: List[Any], + logging_obj: Optional[Any] = None, + ) -> None: + if not chunks: + return + + model = getattr(response, "model", None) + if not model: + return + + custom_llm_provider = None + if logging_obj is not None: + custom_llm_provider = logging_obj.model_call_details.get( + "custom_llm_provider" + ) + + try: + from litellm.litellm_core_utils.get_llm_provider_logic import ( + get_llm_provider, + ) + from litellm.types.utils import LlmProviders + from litellm.utils import ProviderConfigManager + + if custom_llm_provider: + provider = LlmProviders(custom_llm_provider) + else: + _, provider_str, _, _ = get_llm_provider(model) + provider = LlmProviders(provider_str) + + provider_config = ProviderConfigManager.get_provider_chat_config( + model=model, + provider=provider, + ) + if provider_config is not None: + provider_config.apply_assembled_streaming_response_metadata( + response=response, + chunks=chunks, + ) + except Exception as e: + verbose_logger.debug( + "apply_provider_assembled_streaming_metadata failed for model=%s: %s", + model, + e, + ) + @staticmethod def _get_chunk_id(chunks: List[Dict[str, Any]]) -> str: """ @@ -588,7 +637,18 @@ class ChunkProcessor: hasattr(usage_chunk, "server_tool_use") and usage_chunk.server_tool_use is not None ): - server_tool_use = usage_chunk.server_tool_use + # Coerce dict to ServerToolUse so downstream cost-calc code + # (which accesses .web_search_requests as an attribute) + # doesn't raise AttributeError. Some providers / streaming + # paths leave server_tool_use as a plain dict on the chunk. + if isinstance(usage_chunk.server_tool_use, dict): + server_tool_use = ServerToolUse(**usage_chunk.server_tool_use) + elif isinstance(usage_chunk.server_tool_use, ServerToolUse): + server_tool_use = usage_chunk.server_tool_use + else: + server_tool_use = ServerToolUse.model_validate( + usage_chunk.server_tool_use + ) if ( usage_chunk_dict["prompt_tokens_details"] is not None and getattr( diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py index 55042a733ed..f3274151e5a 100644 --- a/litellm/litellm_core_utils/streaming_handler.py +++ b/litellm/litellm_core_utils/streaming_handler.py @@ -1149,6 +1149,32 @@ class CustomStreamWrapper: completion_obj: Dict[str, Any] = {"content": ""} from litellm.types.utils import GenericStreamingChunk as GChunk + if ( + isinstance(chunk, ModelResponseStream) + and self.custom_llm_provider is not None + and self.custom_llm_provider in litellm._custom_providers + ): + _has_content = bool( + chunk.choices + and chunk.choices[0].delta is not None + and ( + chunk.choices[0].delta.content + or chunk.choices[0].delta.tool_calls + ) + ) + if self.received_finish_reason is not None: + if not _has_content: + raise StopIteration + if chunk.choices and chunk.choices[0].finish_reason: + self.received_finish_reason = chunk.choices[0].finish_reason + if not _has_content: + return None + # Strip finish_reason from the content chunk so it appears + # only on the trailing empty-delta chunk (OpenAI spec). + # finish_reason_handler() will emit the proper terminal chunk. + chunk.choices[0].finish_reason = None # type: ignore[assignment] + return chunk + if ( isinstance(chunk, dict) and generic_chunk_has_all_required_fields( diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py index 4f15d1b3cef..9ecd0df0cb8 100644 --- a/litellm/llms/anthropic/chat/transformation.py +++ b/litellm/llms/anthropic/chat/transformation.py @@ -81,7 +81,6 @@ from litellm.types.utils import ( from litellm.utils import ( ModelResponse, Usage, - _supports_factory, add_dummy_tool, any_assistant_message_has_thinking_blocks, get_max_tokens, @@ -337,50 +336,6 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): v in model_lower for v in ("opus-4-7", "opus_4_7", "opus-4.7", "opus_4.7") ) - @staticmethod - def _supports_model_capability(model: str, key: str) -> bool: - """Check a boolean capability ``key`` in the model map. - - Strips bedrock/vertex prefixes so a provider-routed Claude still - resolves to the Anthropic model-map entry. - """ - try: - if _supports_factory( - model=model, - custom_llm_provider="anthropic", - key=key, - ): - return True - except Exception: - pass - candidates = [model] - for prefix in ( - "bedrock/converse/", - "bedrock/invoke/", - "bedrock/", - "vertex_ai/", - ): - if model.startswith(prefix): - candidates.append(model[len(prefix) :]) - try: - from litellm.llms.bedrock.common_utils import BedrockModelInfo - - base = BedrockModelInfo.get_base_model(model) - if base: - candidates.append(base) - candidates.append(f"bedrock/{base}") - except Exception: - pass - try: - for cand in candidates: - if cand in litellm.model_cost and ( - litellm.model_cost[cand].get(key) is True - ): - return True - except Exception: - pass - return False - @staticmethod def _supports_effort_level(model: str, level: str) -> bool: """Check ``supports_{level}_reasoning_effort`` in the model map.""" @@ -918,7 +873,39 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): anthropic_tools = [] mcp_servers = [] for tool in tools: - if "input_schema" in tool: # assume in anthropic format + if tool.get("type") == "namespace": + # Namespace is a grouping container (e.g. codex's multi_agent_v1). + # Extract its nested tools and map them individually. + for nested in tool.get("tools") or []: + if "input_schema" in nested: + # Already in Anthropic format. + anthropic_tools.append(nested) + elif "function" not in nested and "name" in nested: + # Flat format: {type, name, description, parameters, ...}. + # Normalize to OpenAI-wrapped format before mapping. + wrapped = cast( + ChatCompletionToolParam, + { + "type": nested.get("type", "function"), + "function": { + k: v for k, v in nested.items() if k != "type" + }, + }, + ) + nested_tool, nested_mcp = self._map_tool_helper(wrapped) + if nested_tool is not None: + anthropic_tools.append(nested_tool) + if nested_mcp is not None: + mcp_servers.append(nested_mcp) + elif "function" in nested: + nested_tool, nested_mcp = self._map_tool_helper( + cast(ChatCompletionToolParam, nested) + ) + if nested_tool is not None: + anthropic_tools.append(nested_tool) + if nested_mcp is not None: + mcp_servers.append(nested_mcp) + elif "input_schema" in tool: # assume in anthropic format anthropic_tools.append(tool) else: # assume openai tool call new_tool, mcp_server_tool = self._map_tool_helper(tool) @@ -1468,10 +1455,15 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): _value = self._map_stop_sequences(value) if _value is not None: optional_params["stop_sequences"] = _value - elif param == "temperature": - optional_params["temperature"] = value - elif param == "top_p": - optional_params["top_p"] = value + elif param == "temperature" or param == "top_p": + AnthropicConfig._apply_sampling_param( + optional_params=optional_params, + model=model, + param=param, + value=value, + drop_params=drop_params, + output_key=param, + ) elif param == "response_format" and isinstance(value, dict): if any( substring in model @@ -1620,6 +1612,15 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): ) return _tool + def should_strip_billing_metadata(self) -> bool: + """ + Whether to drop x-anthropic-billing-header system blocks before sending upstream. + + The first-party Anthropic API uses these blocks for Claude Code attribution, so the + base config keeps them. Providers that reject them (e.g. Bedrock) override this to True. + """ + return False + def translate_system_message( self, messages: List[AllMessageValues] ) -> List[AnthropicSystemMessageContent]: @@ -1627,7 +1628,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): Translate system message to anthropic format. Removes system message from the original list and returns a new list of anthropic system message content. - Filters out system messages containing x-anthropic-billing-header metadata. + When should_strip_billing_metadata() is True, x-anthropic-billing-header system blocks are dropped. """ system_prompt_indices = [] anthropic_system_message_list: List[AnthropicSystemMessageContent] = [] @@ -1639,10 +1640,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): # Skip empty text blocks - Anthropic API raises errors for empty text if not system_message_block["content"]: continue - # Skip system messages containing x-anthropic-billing-header metadata - if system_message_block["content"].startswith( - "x-anthropic-billing-header:" - ): + if self.should_strip_billing_metadata() and system_message_block[ + "content" + ].startswith("x-anthropic-billing-header:"): continue anthropic_system_message_content = AnthropicSystemMessageContent( type="text", @@ -1661,9 +1661,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): text_value = _content.get("text") if _content.get("type") == "text" and not text_value: continue - # Skip system messages containing x-anthropic-billing-header metadata if ( - _content.get("type") == "text" + self.should_strip_billing_metadata() + and _content.get("type") == "text" and text_value and text_value.startswith("x-anthropic-billing-header:") ): @@ -1978,6 +1978,21 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): # Remove internal LiteLLM parameters that should not be sent to Anthropic API optional_params.pop("is_vertex_request", None) + optional_params.pop("client_metadata", None) + + # ``top_k`` is a provider-specific kwarg that bypasses + # ``map_openai_params``; gate it here, the single boundary shared by + # the direct Anthropic, Bedrock invoke, Vertex, and Azure paths. + top_k = optional_params.pop("top_k", None) + if top_k is not None: + AnthropicConfig._apply_sampling_param( + optional_params=optional_params, + model=model, + param="top_k", + value=top_k, + drop_params=litellm_params.get("drop_params") is True, + output_key="top_k", + ) data = { "model": model, diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py index 31131d722ab..5741513903c 100644 --- a/litellm/llms/anthropic/common_utils.py +++ b/litellm/llms/anthropic/common_utils.py @@ -272,19 +272,133 @@ class AnthropicModelInfo(BaseLLMModelInfo): ) @staticmethod - def _is_adaptive_thinking_model(model: str) -> bool: - """Claude 4.6+ models use adaptive thinking with ``output_config.effort``.""" + def _supports_sampling_params(model: str) -> bool: + """Claude 4.7+ (Opus 4.7/4.8, Fable 5) removed sampling params: the API + rejects ``top_p``, ``top_k``, and any ``temperature`` other than 1 with + a 400 ("`temperature` is deprecated for this model"). + + Driven by the ``supports_sampling_params`` flag in the model map; the + name check remains only as a fallback for provider-routed ids whose + map entries predate the flag.""" + flag = AnthropicModelInfo._get_model_capability( + model, "supports_sampling_params" + ) + if flag is not None: + return flag + model_lower = model.lower() + return not any( + v in model_lower + for v in ( + "fable", + "opus-4-7", + "opus_4_7", + "opus-4.7", + "opus_4.7", + "opus-4-8", + "opus_4_8", + "opus-4.8", + "opus_4.8", + ) + ) + + @staticmethod + def _apply_sampling_param( + optional_params: dict, + model: str, + param: str, + value: Any, + drop_params: bool, + output_key: str, + ) -> None: + """Forward ``temperature``/``top_p``/``top_k`` to + ``optional_params[output_key]`` unless the model removed sampling + params, in which case drop the param (with drop_params) or raise a + clean client-side 400.""" + if AnthropicModelInfo._supports_sampling_params(model) or ( + param == "temperature" and value == 1 + ): + optional_params[output_key] = value + elif not (litellm.drop_params or drop_params): + supported_hint = ( + "Only temperature=1 is supported. " if param == "temperature" else "" + ) + raise litellm.utils.UnsupportedParamsError( + message=( + f"{model} does not support {param}={value}. {supported_hint}" + "To drop unsupported params, set `litellm.drop_params = True`." + ), + status_code=400, + ) + + @staticmethod + def _model_map_lookup_candidates(model: str) -> List[str]: + """Model-map keys to try for ``model``, stripping bedrock/vertex + prefixes so a provider-routed Claude still resolves to its entry.""" + candidates = [model] + for prefix in ( + "bedrock/converse/", + "bedrock/invoke/", + "bedrock/", + "vertex_ai/", + ): + if model.startswith(prefix): + candidates.append(model[len(prefix) :]) + try: + from litellm.llms.bedrock.common_utils import BedrockModelInfo + + base = BedrockModelInfo.get_base_model(model) + if base: + candidates.append(base) + candidates.append(f"bedrock/{base}") + except Exception: + pass + return candidates + + @staticmethod + def _get_model_capability(model: str, key: str) -> Optional[bool]: + """Read boolean capability ``key`` from the model map, or None when + no entry declares it.""" + try: + for cand in AnthropicModelInfo._model_map_lookup_candidates(model): + value = litellm.model_cost.get(cand, {}).get(key) + if isinstance(value, bool): + return value + except Exception: + pass + return None + + @staticmethod + def _supports_model_capability(model: str, key: str) -> bool: + """Check a boolean capability ``key`` in the model map. + + Strips bedrock/vertex prefixes so a provider-routed Claude still + resolves to the Anthropic model-map entry. + """ from litellm.utils import _supports_factory try: if _supports_factory( model=model, - custom_llm_provider=None, - key="supports_adaptive_thinking", + custom_llm_provider="anthropic", + key=key, ): return True except Exception: pass + return AnthropicModelInfo._get_model_capability(model, key) is True + + @staticmethod + def _is_adaptive_thinking_model(model: str) -> bool: + """Claude 4.6+ models use adaptive thinking with ``output_config.effort``. + + Driven by the ``supports_adaptive_thinking`` flag in the model map; the + 4.6/4.7 name checks remain only as a fallback for provider-routed ids + whose map entries predate the flag. + """ + if AnthropicModelInfo._supports_model_capability( + model, "supports_adaptive_thinking" + ): + return True return AnthropicModelInfo._is_claude_4_6_model( model ) or AnthropicModelInfo._is_claude_4_7_model(model) diff --git a/litellm/llms/anthropic/cost_calculation.py b/litellm/llms/anthropic/cost_calculation.py index 3882d8f978c..6a031498dae 100644 --- a/litellm/llms/anthropic/cost_calculation.py +++ b/litellm/llms/anthropic/cost_calculation.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Optional, Tuple from litellm.litellm_core_utils.llm_cost_calc.utils import ( _get_token_base_cost, + _get_web_search_requests, _parse_prompt_tokens_details, calculate_cache_writing_cost, generic_cost_per_token, @@ -110,11 +111,12 @@ def get_cost_for_anthropic_web_search( if model_info is None: return 0.0 - if ( - usage is None - or usage.server_tool_use is None - or usage.server_tool_use.web_search_requests is None - ): + if usage is None: + return 0.0 + web_search_requests = _get_web_search_requests( + getattr(usage, "server_tool_use", None) + ) + if web_search_requests is None: return 0.0 ## Get the cost per web search request @@ -128,5 +130,5 @@ def get_cost_for_anthropic_web_search( return 0.0 ## Calculate the total cost - total_cost = cost_per_web_search_request * usage.server_tool_use.web_search_requests + total_cost = cost_per_web_search_request * web_search_requests return total_cost diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py index bacb9f8ddf6..f049abcf47f 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py @@ -1,5 +1,6 @@ # What is this? ## Translates OpenAI call to Anthropic `/v1/messages` format +import copy import json import traceback from collections import deque @@ -29,6 +30,98 @@ if TYPE_CHECKING: from litellm.types.utils import ModelResponseStream +class _CombinedChunkSplitter: + """ + Splits a streaming chunk that carries BOTH response content and a + ``finish_reason`` into two chunks: a content-only chunk followed by a + finish-only chunk. + + ``AnthropicStreamWrapper`` (via ``translate_streaming_openai_response_to_anthropic``) + assumes content and ``finish_reason`` never arrive in the same chunk — true for + real provider streams, but false for fake-streamed providers (e.g. Vertex AI + Gemma ``:predict``) where ``MockResponseIterator`` collapses the entire response + into a single chunk. Without this split the assumption causes all content to be + silently dropped (only the ``message_delta`` stop event is emitted). + + Supports both sync and async iteration, since ``AnthropicStreamWrapper`` exposes + both ``__next__`` and ``__anext__``. An instance is single-mode: callers must + iterate it either synchronously or asynchronously, never both — the two modes + hold independent iterator references on the upstream stream and mixing them + would advance them out of sync. + """ + + def __init__(self, completion_stream: Any): + self._stream = completion_stream + self._sync_iter: Optional[Iterator[Any]] = None + self._async_iter: Optional[AsyncIterator[Any]] = None + self._buffer: deque = deque() + + @staticmethod + def _is_combined(chunk: Any) -> bool: + """True if ``chunk`` carries response content AND a finish_reason.""" + choices = getattr(chunk, "choices", None) + if not choices: + return False + choice = choices[0] + if getattr(choice, "finish_reason", None) is None: + return False + delta = getattr(choice, "delta", None) + if delta is None: + return False + return bool( + getattr(delta, "content", None) + or getattr(delta, "tool_calls", None) + or getattr(delta, "reasoning_content", None) + or getattr(delta, "thinking_blocks", None) + ) + + @staticmethod + def _split(chunk: Any) -> List[Any]: + """Return ``[chunk]``, or ``[content_chunk, finish_chunk]`` if combined.""" + if not _CombinedChunkSplitter._is_combined(chunk): + return [chunk] + + # Content chunk: keep the delta payload, clear the finish_reason. + content_chunk = copy.deepcopy(chunk) + content_chunk.choices[0].finish_reason = None + + # Finish chunk: keep finish_reason (and usage), clear the delta payload. + finish_chunk = copy.deepcopy(chunk) + finish_delta = finish_chunk.choices[0].delta + finish_delta.content = None + if hasattr(finish_delta, "tool_calls"): + finish_delta.tool_calls = None + if hasattr(finish_delta, "reasoning_content"): + finish_delta.reasoning_content = None + if hasattr(finish_delta, "thinking_blocks"): + finish_delta.thinking_blocks = None + return [content_chunk, finish_chunk] + + def __iter__(self) -> "Iterator[Any]": + return self + + def __next__(self) -> Any: + if self._buffer: + return self._buffer.popleft() + if self._sync_iter is None: + self._sync_iter = iter(self._stream) + chunk = next(self._sync_iter) # propagates StopIteration when exhausted + self._buffer.extend(self._split(chunk)) + return self._buffer.popleft() + + def __aiter__(self) -> "AsyncIterator[Any]": + return self + + async def __anext__(self) -> Any: + if self._buffer: + return self._buffer.popleft() + if self._async_iter is None: + self._async_iter = self._stream.__aiter__() + chunk = await self._async_iter.__anext__() # propagates StopAsyncIteration + self._buffer.extend(self._split(chunk)) + return self._buffer.popleft() + + class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): """ - first chunk return 'message_start' @@ -62,7 +155,10 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): compaction_block: Optional[CompactionBlock] = None, iterations_usage: Optional[List[UsageIteration]] = None, ): - super().__init__(completion_stream) + # Wrap the upstream stream so chunks that carry both content and a + # finish_reason (fake-streamed providers) are split into two — see + # _CombinedChunkSplitter. + super().__init__(_CombinedChunkSplitter(completion_stream)) self.model = model # Mapping of truncated tool names to original names (for OpenAI's 64-char limit) self.tool_name_mapping = tool_name_mapping or {} @@ -373,12 +469,16 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): if should_start_new_block and not self.sent_content_block_finish: # Queue the sequence: content_block_stop -> content_block_start - # For text blocks the trigger chunk is not emitted as a separate - # delta because content_block_start carries the information. - # For tool_use blocks we must also emit the trigger chunk's delta - # when it carries input_json_delta data, because some providers - # (e.g. xAI, Gemini) include tool arguments in the same streaming - # chunk as the function name/id. + # -> (optionally) the trigger chunk's delta. + # + # The synthesized content_block_start always carries an + # empty body, so the chunk that *triggered* the transition + # also carries the new block's first delta. It must be + # re-emitted or the first token of the new block is lost. + # This applies to text_delta and thinking_delta (the first + # non-empty text/thinking token) as well as input_json_delta + # (providers like xAI/Gemini bundle tool arguments with the + # function name/id in a single chunk). # 1. Stop current content block self.chunk_queue.append( @@ -397,14 +497,9 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): } ) - # 3. If the trigger chunk carries tool argument data, queue it - # so the input_json_delta is not silently dropped. - if ( - processed_chunk.get("type") == "content_block_delta" - and isinstance(processed_chunk.get("delta"), dict) - and processed_chunk["delta"].get("type") == "input_json_delta" - and processed_chunk["delta"].get("partial_json") - ): + # 3. If the trigger chunk carries delta content, queue it + # so the first delta of the new block is not silently dropped. + if self._trigger_delta_has_content(processed_chunk): self.chunk_queue.append(processed_chunk) self.sent_content_block_finish = False @@ -615,12 +710,16 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): if not self.queued_usage_chunk: if should_start_new_block and not self.sent_content_block_finish: # Queue the sequence: content_block_stop -> content_block_start - # For text blocks the trigger chunk is not emitted as a separate - # delta because content_block_start carries the information. - # For tool_use blocks we must also emit the trigger chunk's delta - # when it carries input_json_delta data, because some providers - # (e.g. xAI, Gemini) include tool arguments in the same streaming - # chunk as the function name/id. + # -> (optionally) the trigger chunk's delta. + # + # The synthesized content_block_start always carries an + # empty body, so the chunk that *triggered* the transition + # also carries the new block's first delta. It must be + # re-emitted or the first token of the new block is lost. + # This applies to text_delta and thinking_delta (the + # first non-empty text/thinking token) as well as + # input_json_delta (providers like xAI/Gemini bundle tool + # arguments with the function name/id in a single chunk). # 1. Stop current content block self.chunk_queue.append( @@ -637,15 +736,9 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): } ) - # 3. If the trigger chunk carries tool argument data, queue it - # so the input_json_delta is not silently dropped. - if ( - processed_chunk.get("type") == "content_block_delta" - and isinstance(processed_chunk.get("delta"), dict) - and processed_chunk["delta"].get("type") - == "input_json_delta" - and processed_chunk["delta"].get("partial_json") - ): + # 3. If the trigger chunk carries delta content, queue it + # so the first delta of the new block is not silently dropped. + if self._trigger_delta_has_content(processed_chunk): self.chunk_queue.append(processed_chunk) # Reset state for new block @@ -802,6 +895,38 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): def _increment_content_block_index(self): self.current_content_block_index += 1 + @staticmethod + def _trigger_delta_has_content(processed_chunk: Dict[str, Any]) -> bool: + """Return True if a translated trigger chunk carries a non-empty + ``content_block_delta`` payload that must be re-emitted after a + block transition. + + When an upstream chunk both *triggers* a new content block (its type + differs from the active block) and *carries* delta content, that + content belongs to the new block. The synthesized + ``content_block_start`` only ever carries an empty body — see + ``_translate_streaming_openai_chunk_to_anthropic_content_block``, + which returns an empty ``TextBlock``/``ToolUseBlock``/thinking block — + so the trigger chunk's delta must be re-queued or the first token of + the new block (the first non-empty text/thinking delta, or bundled + tool arguments) is silently dropped. + """ + if processed_chunk.get("type") != "content_block_delta": + return False + delta = processed_chunk.get("delta") + if not isinstance(delta, dict): + return False + delta_type = delta.get("type") + if delta_type == "text_delta": + return bool(delta.get("text")) + if delta_type == "input_json_delta": + return bool(delta.get("partial_json")) + if delta_type == "thinking_delta": + return bool(delta.get("thinking")) + if delta_type == "signature_delta": + return bool(delta.get("signature")) + return False + def _should_start_new_content_block(self, chunk: "ModelResponseStream") -> bool: """ Determine if we should start a new content block based on the processed chunk. diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py index 3a2c09f2183..07e8270b496 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py @@ -84,6 +84,15 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig): if isinstance(content, list): _process_content_list(content) + def should_strip_billing_metadata(self) -> bool: + """ + Whether to drop x-anthropic-billing-header system blocks before sending upstream. + + The first-party Anthropic API uses these blocks for Claude Code attribution, so the + base config keeps them. Providers that reject them override this to True. + """ + return False + @staticmethod def _filter_billing_headers_from_system(system_param): """ @@ -286,14 +295,12 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig): optional_params=anthropic_messages_optional_request_params, ) - # Filter out x-anthropic-billing-header from system messages system_param = anthropic_messages_optional_request_params.get("system") - if system_param is not None: + if self.should_strip_billing_metadata() and system_param is not None: filtered_system = self._filter_billing_headers_from_system(system_param) if filtered_system is not None and len(filtered_system) > 0: anthropic_messages_optional_request_params["system"] = filtered_system else: - # Remove system parameter if all content was filtered out anthropic_messages_optional_request_params.pop("system", None) # Transform context_management from OpenAI format to Anthropic format if needed diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py index f8c827ab057..70855afa81c 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py @@ -102,9 +102,9 @@ def _build_responses_kwargs( from litellm.types.utils import CallTypes if isinstance(value, LiteLLMLoggingObject): - # Reclassify as acompletion so the success handler doesn't try to - # validate the Responses API event as an AnthropicResponse. - # (Mirrors the pattern used in LiteLLMMessagesToCompletionTransformationHandler.) + # Keep call_type as anthropic_messages so spend_logs are billed + # against /v1/messages; the success handler translates the + # Responses API result back to a ModelResponse for the row. setattr(value, "call_type", CallTypes.anthropic_messages.value) responses_kwargs[key] = value elif key not in excluded and key not in responses_kwargs and value is not None: diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py index 94c5200be64..5f1362e259f 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py @@ -155,10 +155,24 @@ class AnthropicResponsesStreamWrapper: event.get("delta", "") if isinstance(event, dict) else "" ) block_idx = ( - self._item_id_to_block_index.get(item_id, self._current_block_index) + self._item_id_to_block_index.get(item_id, -1) if item_id else self._current_block_index ) + if block_idx < 0: + # Some providers (e.g. LMStudio) skip response.output_item.added, + # so no text block is open yet; synthesize content_block_start + # instead of emitting a delta with index -1 + block_idx = self._next_block_index() + if item_id: + self._item_id_to_block_index[item_id] = block_idx + self._chunk_queue.append( + { + "type": "content_block_start", + "index": block_idx, + "content_block": {"type": "text", "text": ""}, + } + ) self._chunk_queue.append( { "type": "content_block_delta", diff --git a/litellm/llms/azure/azure.py b/litellm/llms/azure/azure.py index 734b8ecef16..56cf035d0f7 100644 --- a/litellm/llms/azure/azure.py +++ b/litellm/llms/azure/azure.py @@ -43,7 +43,10 @@ from .common_utils import ( process_azure_headers, select_azure_base_url_or_endpoint, ) -from .image_generation import get_azure_image_generation_config +from .image_generation import ( + AzureFoundryMAIImageGenerationConfig, + get_azure_image_generation_config, +) from .image_generation.http_utils import azure_deployment_image_generation_json_body @@ -1097,10 +1100,14 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): ) def create_azure_base_url( - self, azure_client_params: dict, model: Optional[str] + self, + azure_client_params: dict, + model: Optional[str], + base_model: Optional[str] = None, ) -> str: from litellm.llms.azure_ai.image_generation import ( AzureFoundryFluxImageGenerationConfig, + AzureFoundryMAIImageGenerationConfig, ) api_base: str = azure_client_params.get( @@ -1112,6 +1119,12 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): if model is None: model = "" + if AzureFoundryMAIImageGenerationConfig.is_mai_model(base_model or model): + return AzureFoundryMAIImageGenerationConfig.get_mai_image_generation_url( + api_base=api_base, + api_version=api_version, + ) + # Handle FLUX 2 models on Azure AI which use a different URL pattern # e.g., /providers/blackforestlabs/v1/flux-2-pro instead of /openai/deployments/{model}/images/generations if AzureFoundryFluxImageGenerationConfig.is_flux2_model(model): @@ -1153,10 +1166,10 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): if api_base.endswith("/"): api_base = api_base.rstrip("/") api_version: str = azure_client_params.get("api_version", "") - # Use the deployment name (model) for URL construction, not the base_model from data img_gen_api_base = self.create_azure_base_url( azure_client_params=azure_client_params, model=model or data.get("model", ""), + base_model=data.get("model", ""), ) ## LOGGING @@ -1285,9 +1298,10 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): if aimg_generation is True: return self.aimage_generation(data=data, input=input, logging_obj=logging_obj, model_response=model_response, api_key=api_key, client=client, azure_client_params=azure_client_params, timeout=timeout, headers=headers, model=model) # type: ignore - # Use the deployment name (model) for URL construction, not the base_model from data img_gen_api_base = self.create_azure_base_url( - azure_client_params=azure_client_params, model=model + azure_client_params=azure_client_params, + model=model, + base_model=base_model, ) ## LOGGING @@ -1309,6 +1323,21 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): data=data, headers=headers, ) + provider_config = get_azure_image_generation_config( + data.get("model", "dall-e-2") + ) + if isinstance(provider_config, AzureFoundryMAIImageGenerationConfig): + return provider_config.transform_image_generation_response( + model=data.get("model", "dall-e-2"), + raw_response=httpx_response, + model_response=model_response or ImageResponse(), + logging_obj=logging_obj, + request_data=data, + optional_params=data, + litellm_params=data, + encoding=litellm.encoding, + ) + response = httpx_response.json() ## LOGGING diff --git a/litellm/llms/azure/image_edit/transformation.py b/litellm/llms/azure/image_edit/transformation.py index a450ee0b217..72f1eef36c0 100644 --- a/litellm/llms/azure/image_edit/transformation.py +++ b/litellm/llms/azure/image_edit/transformation.py @@ -97,8 +97,15 @@ class AzureImageEditConfig(OpenAIImageEditConfig): ) original_url = httpx.URL(api_base) - # Extract api_version or use default - api_version = cast(Optional[str], litellm_params.get("api_version")) + # Resolve api_version: litellm_params > litellm.api_version > AZURE_API_VERSION env > default. + # Mirrors the fallback chain used by the Azure chat path in common_utils.py, + # so callers that set a global / env api_version don't get an unversioned URL. + api_version = ( + cast(Optional[str], litellm_params.get("api_version")) + or litellm.api_version + or get_secret_str("AZURE_API_VERSION") + or litellm.AZURE_DEFAULT_API_VERSION + ) # Create a new dictionary with existing params query_params = dict(original_url.params) diff --git a/litellm/llms/azure/image_generation/__init__.py b/litellm/llms/azure/image_generation/__init__.py index f60e446f0c4..64636bc689d 100644 --- a/litellm/llms/azure/image_generation/__init__.py +++ b/litellm/llms/azure/image_generation/__init__.py @@ -1,4 +1,5 @@ from litellm._logging import verbose_logger +from litellm.llms.azure_ai.image_generation import AzureFoundryMAIImageGenerationConfig from litellm.llms.base_llm.image_generation.transformation import ( BaseImageGenerationConfig, ) @@ -24,6 +25,8 @@ def get_azure_image_generation_config(model: str) -> BaseImageGenerationConfig: return AzureDallE2ImageGenerationConfig() elif "dalle3" in model: return AzureDallE3ImageGenerationConfig() + elif AzureFoundryMAIImageGenerationConfig.is_mai_model(model): + return AzureFoundryMAIImageGenerationConfig() else: verbose_logger.debug( f"Using AzureGPTImageGenerationConfig for model: {model}. This follows the gpt-image model format." diff --git a/litellm/llms/azure/realtime/handler.py b/litellm/llms/azure/realtime/handler.py index 1f3357fd788..9c8de6c06a1 100644 --- a/litellm/llms/azure/realtime/handler.py +++ b/litellm/llms/azure/realtime/handler.py @@ -8,6 +8,7 @@ from typing import Any, Optional, cast from litellm._logging import _redact_string, verbose_proxy_logger from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES +from litellm.types.realtime import RealtimeQueryParams from ....litellm_core_utils.litellm_logging import Logging as LiteLLMLogging from ....litellm_core_utils.realtime_streaming import RealTimeStreaming @@ -35,6 +36,7 @@ class AzureOpenAIRealtime(AzureChatCompletion): model: str, api_version: Optional[str], realtime_protocol: Optional[str] = None, + query_params: Optional[RealtimeQueryParams] = None, ) -> str: """ Construct Azure realtime WebSocket URL. @@ -46,6 +48,7 @@ class AzureOpenAIRealtime(AzureChatCompletion): realtime_protocol: Protocol version to use: - "GA" or "v1": Uses /openai/v1/realtime (GA path) - "beta" or None: Uses /openai/realtime (beta path, default) + query_params: Extra query params to forward (e.g. intent=transcription). Returns: WebSocket URL string @@ -54,6 +57,8 @@ class AzureOpenAIRealtime(AzureChatCompletion): beta/default: "wss://.../openai/realtime?api-version=2024-10-01-preview&deployment=gpt-4o-realtime-preview" GA/v1: "wss://.../openai/v1/realtime?model=gpt-realtime-deployment" """ + from urllib.parse import urlencode + api_base = api_base.replace("https://", "wss://") # Determine path based on realtime_protocol (case-insensitive) @@ -61,13 +66,25 @@ class AzureOpenAIRealtime(AzureChatCompletion): "GA", "V1", ) + intent = (query_params or {}).get("intent") + if _is_ga: path = "/openai/v1/realtime" - return f"{api_base}{path}?model={model}" + query_parts = [] + if intent != "transcription" and ( + query_params is None or "model" in query_params + ): + query_parts.append(urlencode({"model": model})) else: # Default to beta path for backwards compatibility path = "/openai/realtime" - return f"{api_base}{path}?api-version={api_version}&deployment={model}" + query_parts = [urlencode({"api-version": api_version, "deployment": model})] + + if intent: + query_parts.append(urlencode({"intent": intent})) + + qs = "&".join(query_parts) + return f"{api_base}{path}?{qs}" if qs else f"{api_base}{path}" async def async_realtime( self, @@ -81,6 +98,7 @@ class AzureOpenAIRealtime(AzureChatCompletion): client: Optional[Any] = None, timeout: Optional[float] = None, realtime_protocol: Optional[str] = None, + query_params: Optional[RealtimeQueryParams] = None, user_api_key_dict: Optional[Any] = None, litellm_metadata: Optional[dict] = None, ): @@ -96,7 +114,11 @@ class AzureOpenAIRealtime(AzureChatCompletion): raise ValueError("api_version is required for Azure OpenAI calls") url = self._construct_url( - api_base, model, api_version, realtime_protocol=realtime_protocol + api_base, + model, + api_version, + realtime_protocol=realtime_protocol, + query_params=query_params, ) try: @@ -113,9 +135,15 @@ class AzureOpenAIRealtime(AzureChatCompletion): websocket, cast(ClientConnection, backend_ws), logging_obj, + model=model, user_api_key_dict=user_api_key_dict, request_data={"litellm_metadata": litellm_metadata or {}}, backend_uses_beta_protocol=backend_uses_beta_protocol, + force_transcription_model=( + model + if (query_params or {}).get("intent") == "transcription" + else None + ), ) await realtime_streaming.bidirectional_forward() diff --git a/litellm/llms/azure/realtime/http_transformation.py b/litellm/llms/azure/realtime/http_transformation.py index df1e2707af2..d6bdbd24db4 100644 --- a/litellm/llms/azure/realtime/http_transformation.py +++ b/litellm/llms/azure/realtime/http_transformation.py @@ -40,6 +40,13 @@ class AzureRealtimeHTTPConfig(BaseRealtimeHTTPConfig): version = api_version or get_secret_str("AZURE_API_VERSION") or "2024-12-17" return f"{base}/openai/realtime/calls?api-version={version}" + def get_transcription_session_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + base = self.get_api_base(api_base).rstrip("/") + version = api_version or get_secret_str("AZURE_API_VERSION") or "2024-12-17" + return f"{base}/openai/realtime/transcription_sessions?api-version={version}" + def get_realtime_calls_headers(self, ephemeral_key: str) -> dict: return { "api-key": ephemeral_key, diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.py index ca9293325ff..92ce5b49285 100644 --- a/litellm/llms/azure/responses/transformation.py +++ b/litellm/llms/azure/responses/transformation.py @@ -185,6 +185,40 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig): default_api_version=AZURE_DEFAULT_RESPONSES_API_VERSION, ) + def supports_native_websocket(self) -> bool: + return True + + def get_websocket_url( + self, + api_base: Optional[str], + litellm_params: dict, + ) -> str: + """ + Azure Responses WebSocket endpoint is at /openai/v1/responses with no + api-version query param. Auth is via Authorization header, model is sent + in the response.create body — not the URL. + """ + if api_base is None: + raise ValueError("api_base is required for Azure WebSocket") + + parsed_url = httpx.URL(api_base) + path = parsed_url.path.rstrip("/") + # Strip existing /openai/responses path if the api_base already contains it + for suffix in ("/openai/v1/responses", "/openai/responses"): + if path.endswith(suffix): + path = path[: -len(suffix)] + break + scheme = "wss" if parsed_url.scheme == "https" else "ws" + return str( + parsed_url.copy_with( + scheme=scheme, path=f"{path}/openai/v1/responses", query=None + ) + ) + + def model_in_websocket_url(self) -> bool: + # Azure sends the model in the response.create body, not the URL + return False + ######################################################### ########## DELETE RESPONSE API TRANSFORMATION ############## ######################################################### diff --git a/litellm/llms/azure_ai/anthropic/messages_transformation.py b/litellm/llms/azure_ai/anthropic/messages_transformation.py index a81218ab76a..59b6ee2b424 100644 --- a/litellm/llms/azure_ai/anthropic/messages_transformation.py +++ b/litellm/llms/azure_ai/anthropic/messages_transformation.py @@ -21,6 +21,9 @@ class AzureAnthropicMessagesConfig(AnthropicMessagesConfig): and Azure endpoint format. """ + def should_strip_billing_metadata(self) -> bool: + return True + def validate_anthropic_messages_environment( self, headers: dict, diff --git a/litellm/llms/azure_ai/anthropic/transformation.py b/litellm/llms/azure_ai/anthropic/transformation.py index e176a4d860e..367ca75c196 100644 --- a/litellm/llms/azure_ai/anthropic/transformation.py +++ b/litellm/llms/azure_ai/anthropic/transformation.py @@ -40,6 +40,9 @@ class AzureAnthropicConfig(AnthropicConfig): def custom_llm_provider(self) -> Optional[str]: return "azure_ai" + def should_strip_billing_metadata(self) -> bool: + return True + def validate_environment( self, headers: dict, diff --git a/litellm/llms/azure_ai/image_edit/__init__.py b/litellm/llms/azure_ai/image_edit/__init__.py index e3acd610446..42ece6d19ec 100644 --- a/litellm/llms/azure_ai/image_edit/__init__.py +++ b/litellm/llms/azure_ai/image_edit/__init__.py @@ -1,21 +1,33 @@ from litellm.llms.azure_ai.image_generation.flux_transformation import ( AzureFoundryFluxImageGenerationConfig, ) +from litellm.llms.azure_ai.image_generation.mai_transformation import ( + AzureFoundryMAIImageGenerationConfig, +) from litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig from .flux2_transformation import AzureFoundryFlux2ImageEditConfig +from .mai_transformation import AzureFoundryMAIImageEditConfig from .transformation import AzureFoundryFluxImageEditConfig -__all__ = ["AzureFoundryFluxImageEditConfig", "AzureFoundryFlux2ImageEditConfig"] +__all__ = [ + "AzureFoundryFluxImageEditConfig", + "AzureFoundryFlux2ImageEditConfig", + "AzureFoundryMAIImageEditConfig", +] def get_azure_ai_image_edit_config(model: str) -> BaseImageEditConfig: """ Get the appropriate image edit config for an Azure AI model. + - MAI models use /mai/v1/images/edits with multipart form data and size - FLUX 2 models use JSON with base64 image - FLUX 1 models use multipart/form-data """ + if AzureFoundryMAIImageGenerationConfig.is_mai_model(model): + return AzureFoundryMAIImageEditConfig() + # Check if it's a FLUX 2 model if AzureFoundryFluxImageGenerationConfig.is_flux2_model(model): return AzureFoundryFlux2ImageEditConfig() diff --git a/litellm/llms/azure_ai/image_edit/mai_transformation.py b/litellm/llms/azure_ai/image_edit/mai_transformation.py new file mode 100644 index 00000000000..75bfc913a8f --- /dev/null +++ b/litellm/llms/azure_ai/image_edit/mai_transformation.py @@ -0,0 +1,199 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast + +import httpx +from httpx._types import RequestFiles + +from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo +from litellm.llms.azure_ai.image_generation.mai_transformation import ( + AzureFoundryMAIImageGenerationConfig, +) +from litellm.llms.openai.common_utils import OpenAIError +from litellm.llms.openai.image_edit.transformation import OpenAIImageEditConfig +from litellm.secret_managers.main import get_secret_str +from litellm.types.images.main import ImageEditOptionalRequestParams +from litellm.types.llms.openai import FileTypes +from litellm.types.router import GenericLiteLLMParams +from litellm.types.utils import ImageResponse +from litellm.utils import convert_to_model_response_object + +if TYPE_CHECKING: + from litellm.litellm_core_utils.logging import Logging as LiteLLMLoggingObj + + +class AzureFoundryMAIImageEditConfig(OpenAIImageEditConfig): + """Azure AI Foundry MAI image editing (e.g. MAI-Image-2.5).""" + + DEFAULT_SIZE = "1024x1024" + + def get_supported_openai_params(self, model: str) -> list: + return ["prompt", "image", "model", "n", "size"] + + def map_openai_params( + self, + image_edit_optional_params: ImageEditOptionalRequestParams, + model: str, + drop_params: bool, + ) -> Dict: + optional_params: Dict[str, Any] = {} + supported_params = self.get_supported_openai_params(model) + + for key, value in dict(image_edit_optional_params).items(): + if value is None or key in optional_params: + continue + + if key in supported_params: + if key == "size" and value: + size_param = cast(str, value) + self._validate_size_param(size_param) + optional_params[key] = size_param + else: + optional_params[key] = value + elif not drop_params: + raise ValueError( + f"Parameter {key} is not supported for model {model}. " + f"Supported parameters are {supported_params}. " + f"Set drop_params=True to drop unsupported parameters." + ) + + if "size" not in optional_params: + optional_params["size"] = self.DEFAULT_SIZE + + return optional_params + + def _validate_size_param(self, size: str) -> None: + known_sizes = { + "1024x1024", + "1792x1024", + "1024x1792", + "512x512", + "256x256", + } + + if size in known_sizes: + return + + if "x" in size: + try: + tuple(map(int, size.lower().split("x", 1))) + return + except ValueError: + raise ValueError( + f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024')." + ) + + raise ValueError( + f"Unsupported size value: '{size}'. " + f"Use a known size (e.g., '1024x1024') or a custom 'WIDTHxHEIGHT' string." + ) + + def validate_environment( + self, + headers: dict, + model: str, + api_key: Optional[str] = None, + litellm_params: Optional[dict] = None, + api_base: Optional[str] = None, + ) -> dict: + api_key = AzureFoundryModelInfo.get_api_key(api_key) + + if not api_key: + raise ValueError( + f"Azure AI API key is required for model {model}. " + "Set AZURE_AI_API_KEY environment variable or pass api_key parameter." + ) + + headers.update({"api-key": api_key}) + return headers + + def get_complete_url( + self, + model: str, + api_base: Optional[str], + litellm_params: dict, + ) -> str: + api_base = AzureFoundryModelInfo.get_api_base(api_base) + + if api_base is None: + raise ValueError( + "Azure AI API base is required. Set AZURE_AI_API_BASE environment variable or pass api_base parameter." + ) + + api_version = ( + litellm_params.get("api_version") + or get_secret_str("AZURE_AI_API_VERSION") + or "preview" + ) + + return AzureFoundryMAIImageGenerationConfig.get_mai_image_edit_url( + api_base=api_base, + api_version=api_version, + ) + + def transform_image_edit_request( + self, + model: str, + prompt: Optional[str], + image: Optional[FileTypes], + image_edit_optional_request_params: Dict, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> Tuple[Dict, RequestFiles]: + request_params = { + "model": model, + **image_edit_optional_request_params, + } + if prompt is not None: + request_params["prompt"] = prompt + + data_without_files = { + key: value + for key, value in request_params.items() + if key not in ["image", "mask"] + } + files_list: List[Tuple[str, Any]] = [] + + if image is not None: + image_list = [image] if not isinstance(image, list) else image + for _image in image_list: + if _image is not None: + self._add_image_to_files( + files_list=files_list, + image=_image, + field_name="image", + ) + break + + return data_without_files, files_list + + def transform_image_edit_response( + self, + model: str, + raw_response: httpx.Response, + logging_obj: "LiteLLMLoggingObj", + ) -> ImageResponse: + try: + response = raw_response.json() + except Exception: + raise OpenAIError( + message=raw_response.text, status_code=raw_response.status_code + ) + + if "usage" in response: + response["usage"] = ( + AzureFoundryMAIImageGenerationConfig.normalize_mai_image_usage( + response.get("usage") + ) + ) + + logging_obj.post_call( + input="", + api_key="", + additional_args={"complete_input_dict": {}}, + original_response=response, + ) + + return convert_to_model_response_object( + response_object=response, + model_response_object=ImageResponse(), + response_type="image_generation", + ) diff --git a/litellm/llms/azure_ai/image_generation/__init__.py b/litellm/llms/azure_ai/image_generation/__init__.py index cebab3de16e..70821d5d764 100644 --- a/litellm/llms/azure_ai/image_generation/__init__.py +++ b/litellm/llms/azure_ai/image_generation/__init__.py @@ -7,12 +7,14 @@ from .dall_e_2_transformation import AzureFoundryDallE2ImageGenerationConfig from .dall_e_3_transformation import AzureFoundryDallE3ImageGenerationConfig from .flux_transformation import AzureFoundryFluxImageGenerationConfig from .gpt_transformation import AzureFoundryGPTImageGenerationConfig +from .mai_transformation import AzureFoundryMAIImageGenerationConfig __all__ = [ "AzureFoundryFluxImageGenerationConfig", "AzureFoundryGPTImageGenerationConfig", "AzureFoundryDallE2ImageGenerationConfig", "AzureFoundryDallE3ImageGenerationConfig", + "AzureFoundryMAIImageGenerationConfig", ] @@ -24,6 +26,8 @@ def get_azure_ai_image_generation_config(model: str) -> BaseImageGenerationConfi return AzureFoundryDallE2ImageGenerationConfig() elif "dalle3" in model: return AzureFoundryDallE3ImageGenerationConfig() + elif AzureFoundryMAIImageGenerationConfig.is_mai_model(model): + return AzureFoundryMAIImageGenerationConfig() elif "flux" in model: return AzureFoundryFluxImageGenerationConfig() else: diff --git a/litellm/llms/azure_ai/image_generation/cost_calculator.py b/litellm/llms/azure_ai/image_generation/cost_calculator.py index b67de9cb70d..f8c876bb5be 100644 --- a/litellm/llms/azure_ai/image_generation/cost_calculator.py +++ b/litellm/llms/azure_ai/image_generation/cost_calculator.py @@ -1,6 +1,9 @@ from typing import Any import litellm +from litellm.litellm_core_utils.llm_cost_calc.utils import ( + calculate_image_response_cost_from_usage, +) from litellm.types.utils import ImageResponse @@ -9,19 +12,28 @@ def cost_calculator( image_response: Any, ) -> float: """ - Recraft image generation cost calculator + Azure AI image generation cost calculator """ _model_info = litellm.get_model_info( model=model, custom_llm_provider=litellm.LlmProviders.AZURE_AI.value, ) - output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0 - num_images: int = 0 + if isinstance(image_response, ImageResponse): + token_based_cost = calculate_image_response_cost_from_usage( + model=model, + image_response=image_response, + custom_llm_provider=litellm.LlmProviders.AZURE_AI.value, + ) + if token_based_cost is not None: + return token_based_cost + + output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0 + num_images: int = 0 if image_response.data: num_images = len(image_response.data) return output_cost_per_image * num_images - else: - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + + raise ValueError( + f"image_response must be of type ImageResponse got type={type(image_response)}" + ) diff --git a/litellm/llms/azure_ai/image_generation/mai_transformation.py b/litellm/llms/azure_ai/image_generation/mai_transformation.py new file mode 100644 index 00000000000..071ca9d9895 --- /dev/null +++ b/litellm/llms/azure_ai/image_generation/mai_transformation.py @@ -0,0 +1,236 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +import httpx + +from litellm.llms.base_llm.image_generation.transformation import ( + BaseImageGenerationConfig, +) +from litellm.llms.openai.common_utils import OpenAIError +from litellm.types.llms.openai import OpenAIImageGenerationOptionalParams +from litellm.types.utils import ImageResponse +from litellm.utils import convert_to_model_response_object + +if TYPE_CHECKING: + from litellm.litellm_core_utils.logging import Logging as LiteLLMLoggingObj + + +class AzureFoundryMAIImageGenerationConfig(BaseImageGenerationConfig): + """Azure AI Foundry MAI image generation (e.g. MAI-Image-2.5).""" + + DEFAULT_WIDTH = 1024 + DEFAULT_HEIGHT = 1024 + + @staticmethod + def get_mai_image_generation_url( + api_base: Optional[str], + api_version: Optional[str], + ) -> str: + if api_base is None: + raise ValueError("api_base is required for Azure AI MAI image generation") + + api_version = api_version or "preview" + path, separator, query = api_base.partition("?") + path = path.rstrip("/") + + if "/mai/" in path: + prefix, _, _ = path.partition("/images/") + path = f"{prefix}/images/generations" + else: + path = f"{path}/mai/v1/images/generations" + + if separator: + return f"{path}?{query}" + return f"{path}?api-version={api_version}" + + @staticmethod + def get_mai_image_edit_url( + api_base: Optional[str], + api_version: Optional[str], + ) -> str: + if api_base is None: + raise ValueError("api_base is required for Azure AI MAI image editing") + + api_version = api_version or "preview" + path, separator, query = api_base.partition("?") + path = path.rstrip("/") + + if "/mai/" in path: + prefix, _, _ = path.partition("/images/") + path = f"{prefix}/images/edits" + else: + path = f"{path}/mai/v1/images/edits" + + if separator: + return f"{path}?{query}" + return f"{path}?api-version={api_version}" + + @staticmethod + def is_mai_model(model: str) -> bool: + model_normalized = model.lower().replace("-", "").replace("_", "") + return "maiimage" in model_normalized + + @staticmethod + def normalize_mai_image_usage(usage: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """Map Azure MAI usage fields to OpenAI ImageUsage schema.""" + if usage is None: + return { + "input_tokens": 0, + "input_tokens_details": {"image_tokens": 0, "text_tokens": 0}, + "output_tokens": 0, + "total_tokens": 0, + } + + normalized_usage = dict(usage) + input_tokens_details = normalized_usage.get("input_tokens_details") + if not isinstance(input_tokens_details, dict): + input_tokens_details = {} + + text_tokens = normalized_usage.get("num_input_text_tokens") + if text_tokens is None: + text_tokens = input_tokens_details.get("text_tokens") + if text_tokens is None: + text_tokens = normalized_usage.get("input_tokens", 0) or 0 + + image_tokens = normalized_usage.get("num_input_image_tokens") + if image_tokens is None: + image_tokens = input_tokens_details.get("image_tokens") + if image_tokens is None: + image_tokens = 0 + + output_tokens = normalized_usage.get("output_tokens") + if output_tokens is None: + output_tokens = normalized_usage.get("num_output_tokens") + if output_tokens is None: + output_tokens = normalized_usage.get("output_image_tokens") + if output_tokens is None: + output_tokens = 0 + + input_tokens = normalized_usage.get("input_tokens") + if input_tokens is None: + input_tokens = text_tokens + image_tokens + + total_tokens = normalized_usage.get("total_tokens") + if total_tokens is None: + total_tokens = input_tokens + output_tokens + + normalized_usage.update( + { + "input_tokens": input_tokens, + "input_tokens_details": { + "image_tokens": image_tokens, + "text_tokens": text_tokens, + }, + "output_tokens": output_tokens, + "total_tokens": total_tokens, + } + ) + return normalized_usage + + def get_supported_openai_params( + self, model: str + ) -> List[OpenAIImageGenerationOptionalParams]: + return ["n", "size"] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + supported_params = self.get_supported_openai_params(model) + + for k, v in non_default_params.items(): + if k in optional_params: + continue + + if k in supported_params: + if k == "size" and v: + self._map_size_param(v, optional_params) + else: + optional_params[k] = v + elif k in ("width", "height"): + optional_params[k] = v + elif not drop_params: + raise ValueError( + f"Parameter {k} is not supported for model {model}. " + f"Supported parameters are {supported_params} and width/height. " + f"Set drop_params=True to drop unsupported parameters." + ) + + if "width" not in optional_params: + optional_params["width"] = self.DEFAULT_WIDTH + if "height" not in optional_params: + optional_params["height"] = self.DEFAULT_HEIGHT + + optional_params.pop("size", None) + return optional_params + + def _map_size_param(self, size: str, optional_params: dict) -> None: + size_mapping = { + "1024x1024": (1024, 1024), + "1792x1024": (1792, 1024), + "1024x1792": (1024, 1792), + "512x512": (512, 512), + "256x256": (256, 256), + } + + if size in size_mapping: + width, height = size_mapping[size] + optional_params["width"] = width + optional_params["height"] = height + elif "x" in size: + try: + width, height = map(int, size.lower().split("x")) + optional_params["width"] = width + optional_params["height"] = height + except ValueError: + raise ValueError( + f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024')." + ) + else: + raise ValueError( + f"Unsupported size value: '{size}'. " + f"Use a known size (e.g., '1024x1024') or a custom 'WIDTHxHEIGHT' string." + ) + + def transform_image_generation_response( + self, + model: str, + raw_response: httpx.Response, + model_response: ImageResponse, + logging_obj: "LiteLLMLoggingObj", + request_data: dict, + optional_params: dict, + litellm_params: dict, + encoding: Any, + api_key: Optional[str] = None, + json_mode: Optional[bool] = None, + ) -> ImageResponse: + try: + response = raw_response.json() + except Exception: + raise OpenAIError( + message=raw_response.text, status_code=raw_response.status_code + ) + + if "usage" in response: + response["usage"] = self.normalize_mai_image_usage(response.get("usage")) + + logging_obj.post_call( + input=request_data.get("prompt", ""), + api_key=api_key, + additional_args={"complete_input_dict": request_data}, + original_response=response, + ) + + image_response: ImageResponse = convert_to_model_response_object( + response_object=response, + model_response_object=model_response, + response_type="image_generation", + ) + + width = optional_params.get("width", self.DEFAULT_WIDTH) + height = optional_params.get("height", self.DEFAULT_HEIGHT) + image_response.size = f"{width}x{height}" # type: ignore[assignment] + return image_response diff --git a/litellm/llms/base_llm/base_model_iterator.py b/litellm/llms/base_llm/base_model_iterator.py index cf1fd6f786e..bf1bfd06537 100644 --- a/litellm/llms/base_llm/base_model_iterator.py +++ b/litellm/llms/base_llm/base_model_iterator.py @@ -50,6 +50,11 @@ def convert_model_response_to_streaming( model=model_response.model, choices=streaming_choices, ) + # Carry usage onto the streaming chunk so fake-streamed responses + # (e.g. Vertex AI Gemma :predict) still report token counts. + usage = getattr(model_response, "usage", None) + if usage is not None: + setattr(processed_chunk, "usage", usage) return processed_chunk except Exception as e: raise ValueError( diff --git a/litellm/llms/base_llm/chat/transformation.py b/litellm/llms/base_llm/chat/transformation.py index 5f35a58ce1f..8f9d5cad7c4 100644 --- a/litellm/llms/base_llm/chat/transformation.py +++ b/litellm/llms/base_llm/chat/transformation.py @@ -442,6 +442,14 @@ class BaseConfig(ABC): """Hook for providers to post-process streaming responses. Default: pass-through.""" return stream + def apply_assembled_streaming_response_metadata( + self, + response: "ModelResponse", + chunks: List[Any], + ) -> None: + """Hook for providers to merge chunk metadata into assembled streaming responses.""" + return None + def calculate_additional_costs( self, model: str, prompt_tokens: int, completion_tokens: int ) -> Optional[dict]: diff --git a/litellm/llms/base_llm/realtime/http_transformation.py b/litellm/llms/base_llm/realtime/http_transformation.py index 712ec42380f..be1413a3c0b 100644 --- a/litellm/llms/base_llm/realtime/http_transformation.py +++ b/litellm/llms/base_llm/realtime/http_transformation.py @@ -59,6 +59,15 @@ class BaseRealtimeHTTPConfig(ABC): ) -> str: """Return the full URL for POST /realtime/client_secrets.""" + def get_transcription_session_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + """Return the full URL for POST /realtime/transcription_sessions.""" + base = (api_base or "").rstrip("/") + if base.endswith("/v1"): + base = base[:-3] + return f"{base}/v1/realtime/transcription_sessions" + @abstractmethod def validate_environment( self, diff --git a/litellm/llms/base_llm/responses/transformation.py b/litellm/llms/base_llm/responses/transformation.py index 853eb282758..c61ce52b530 100644 --- a/litellm/llms/base_llm/responses/transformation.py +++ b/litellm/llms/base_llm/responses/transformation.py @@ -62,6 +62,26 @@ class BaseResponsesAPIConfig(ABC): """ return False + def sign_request( + self, + headers: dict, + optional_params: dict, + request_data: dict, + api_base: str, + api_key: Optional[str] = None, + model: Optional[str] = None, + stream: Optional[bool] = None, + fake_stream: Optional[bool] = None, + ) -> Tuple[dict, Optional[bytes]]: + """Sign the request after the body is finalized. + + Default is a no-op (returns headers unchanged, no signed body). Providers + whose endpoint requires request signing (e.g. Bedrock Mantle SigV4) + override this and return the signed body bytes so the handler sends those + exact bytes. + """ + return headers, None + @abstractmethod def get_supported_openai_params(self, model: str) -> list: pass @@ -238,6 +258,31 @@ class BaseResponsesAPIConfig(ABC): """ return False + def get_websocket_url( + self, + api_base: Optional[str], + litellm_params: dict, + ) -> str: + """ + Return the wss:// URL for the provider's native Responses WebSocket endpoint. + + Defaults to converting the HTTP URL from get_complete_url. Providers whose + WebSocket path differs from their HTTP path (e.g. Azure uses + /openai/v1/responses without api-version) should override this. + """ + http_url = self.get_complete_url( + api_base=api_base, litellm_params=litellm_params + ) + return http_url.replace("https://", "wss://").replace("http://", "ws://") + + def model_in_websocket_url(self) -> bool: + """ + Return True if the model should be appended as a ?model= query param to + the WebSocket URL. Providers that identify the model via the request body + (e.g. Azure Responses API) should override this to return False. + """ + return True + ######################################################### ########## CANCEL RESPONSE API TRANSFORMATION ########## ######################################################### diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.py index 90dfa13e938..b5e5e4de6fc 100644 --- a/litellm/llms/bedrock/chat/converse_transformation.py +++ b/litellm/llms/bedrock/chat/converse_transformation.py @@ -920,10 +920,15 @@ class AmazonConverseConfig(BaseConfig): continue value = [value] optional_params["stopSequences"] = value - if param == "temperature": - optional_params["temperature"] = value - if param == "top_p": - optional_params["topP"] = value + if param == "temperature" or param == "top_p": + AnthropicConfig._apply_sampling_param( + optional_params=optional_params, + model=model, + param=param, + value=value, + drop_params=drop_params, + output_key="topP" if param == "top_p" else param, + ) if param == "tools" and isinstance(value, list): self._apply_tool_call_transformation( tools=cast(List[OpenAIChatCompletionToolParam], value), @@ -1221,7 +1226,9 @@ class AmazonConverseConfig(BaseConfig): inference_params["topK"] = inference_params.pop("top_k") return InferenceConfig(**inference_params) - def _handle_top_k_value(self, model: str, inference_params: dict) -> dict: + def _handle_top_k_value( + self, model: str, inference_params: dict, drop_params: bool = False + ) -> dict: base_model = BedrockModelInfo.get_base_model(model) val_top_k = None @@ -1230,16 +1237,25 @@ class AmazonConverseConfig(BaseConfig): elif "top_k" in inference_params: val_top_k = inference_params.pop("top_k") - if val_top_k: + if val_top_k is not None: if base_model.startswith("anthropic"): - return {"top_k": val_top_k} + top_k_params: dict = {} + AnthropicConfig._apply_sampling_param( + optional_params=top_k_params, + model=model, + param="top_k", + value=val_top_k, + drop_params=drop_params, + output_key="top_k", + ) + return top_k_params if base_model.startswith("amazon.nova"): return {"inferenceConfig": {"topK": val_top_k}} return {} def _prepare_request_params( - self, optional_params: dict, model: str + self, optional_params: dict, model: str, drop_params: bool = False ) -> Tuple[dict, dict, dict, Optional[OutputConfigBlock]]: """Prepare and separate request parameters.""" # Consume the internal ``_output_config_normalized`` marker set by @@ -1338,7 +1354,7 @@ class AmazonConverseConfig(BaseConfig): # Only set the topK value in for models that support it additional_request_params.update( - self._handle_top_k_value(model, inference_params) + self._handle_top_k_value(model, inference_params, drop_params) ) # Filter out internal/MCP-related parameters that shouldn't be sent to the API @@ -1572,6 +1588,7 @@ class AmazonConverseConfig(BaseConfig): optional_params: dict, messages: Optional[List[AllMessageValues]] = None, headers: Optional[dict] = None, + drop_params: bool = False, ) -> CommonRequestObject: ## VALIDATE REQUEST """ @@ -1618,7 +1635,7 @@ class AmazonConverseConfig(BaseConfig): additional_request_params, request_metadata, output_config, - ) = self._prepare_request_params(optional_params, model) + ) = self._prepare_request_params(optional_params, model, drop_params) original_tools = inference_params.pop("tools", []) @@ -1649,12 +1666,14 @@ class AmazonConverseConfig(BaseConfig): bedrock_tool_config["toolChoice"] = tool_choice_values data: CommonRequestObject = { - "additionalModelRequestFields": additional_request_params, - "system": system_content_blocks, "inferenceConfig": self._transform_inference_params( inference_params=inference_params ), } + if additional_request_params: + data["additionalModelRequestFields"] = additional_request_params + if system_content_blocks: + data["system"] = system_content_blocks # Handle all config blocks for config_name, config_class in self.get_config_blocks().items(): @@ -1699,6 +1718,7 @@ class AmazonConverseConfig(BaseConfig): optional_params=optional_params, messages=messages, headers=headers, + drop_params=litellm_params.get("drop_params") is True, ) bedrock_messages = ( @@ -1756,6 +1776,7 @@ class AmazonConverseConfig(BaseConfig): optional_params=optional_params, messages=messages, headers=headers, + drop_params=litellm_params.get("drop_params") is True, ) ## TRANSFORMATION ## diff --git a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py index a13336b6c88..4887cbd23be 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py @@ -60,6 +60,9 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig): def custom_llm_provider(self) -> Optional[str]: return "bedrock" + def should_strip_billing_metadata(self) -> bool: + return True + def get_supported_openai_params(self, model: str) -> List[str]: return AnthropicConfig.get_supported_openai_params(self, model) diff --git a/litellm/llms/bedrock/chat/mantle/transformation.py b/litellm/llms/bedrock/chat/mantle/transformation.py index ef0199031af..cbed2232be5 100644 --- a/litellm/llms/bedrock/chat/mantle/transformation.py +++ b/litellm/llms/bedrock/chat/mantle/transformation.py @@ -48,6 +48,30 @@ class AmazonMantleConfig(AmazonAnthropicClaudeConfig): region = self._get_aws_region_name(optional_params=optional_params, model=model) return MANTLE_ENDPOINT_TEMPLATE.format(region=region) + def validate_environment( + self, + headers: dict, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + headers = super().validate_environment( + headers=headers, + model=model, + messages=messages, + optional_params=optional_params, + litellm_params=litellm_params, + api_key=api_key, + api_base=api_base, + ) + project_id = litellm_params.get("aws_bedrock_project_id") + if project_id: + headers["anthropic-workspace"] = project_id + return headers + def transform_request( self, model: str, diff --git a/litellm/llms/bedrock/claude_platform/transformation.py b/litellm/llms/bedrock/claude_platform/transformation.py index 0167c457c96..c20dc63444f 100644 --- a/litellm/llms/bedrock/claude_platform/transformation.py +++ b/litellm/llms/bedrock/claude_platform/transformation.py @@ -17,6 +17,9 @@ class BedrockClaudePlatformConfig(BedrockClaudePlatformMixin, AnthropicConfig): def custom_llm_provider(self) -> Optional[str]: return "bedrock" + def should_strip_billing_metadata(self) -> bool: + return True + def validate_environment( self, headers: dict, diff --git a/litellm/llms/bedrock/count_tokens/transformation.py b/litellm/llms/bedrock/count_tokens/transformation.py index c967fd334bc..bdef3349e00 100644 --- a/litellm/llms/bedrock/count_tokens/transformation.py +++ b/litellm/llms/bedrock/count_tokens/transformation.py @@ -11,6 +11,11 @@ from typing import Any, Dict, List, Optional from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM from litellm.llms.bedrock.common_utils import get_bedrock_base_model +# Placeholder satisfying the Anthropic InvokeModel schema's required +# max_tokens field; CountTokens only counts input, so it has no effect +# on any generation. +DEFAULT_ANTHROPIC_INVOKE_MODEL_MAX_TOKENS = 1024 + class BedrockCountTokensConfig(BaseAWSLLM): """ @@ -32,8 +37,20 @@ class BedrockCountTokensConfig(BaseAWSLLM): Returns: 'converse' or 'invokeModel' """ - # If the request has messages in the expected Anthropic format, use converse - if "messages" in request_data and isinstance(request_data["messages"], list): + messages = request_data.get("messages") + if isinstance(messages, list): + # Anthropic content blocks carry a "type" key ({"type": "text", ...}); + # Converse blocks don't ({"text": ...}, {"toolUse": ...}). Converse + # rejects Anthropic-shape blocks, so route those to invokeModel, + # which forwards the body verbatim. + for message in messages: + if not isinstance(message, dict): + continue + content = message.get("content") + if isinstance(content, list) and any( + isinstance(block, dict) and "type" in block for block in content + ): + return "invokeModel" return "converse" # For raw text or other formats, use invokeModel @@ -68,7 +85,7 @@ class BedrockCountTokensConfig(BaseAWSLLM): { "input": { "invokeModel": { - "body": "{...raw model input...}" + "body": "" } } } @@ -168,13 +185,24 @@ class BedrockCountTokensConfig(BaseAWSLLM): self, request_data: Dict[str, Any] ) -> Dict[str, Any]: """Transform to InvokeModel input format.""" + import base64 import json # For InvokeModel, we need to provide the raw body that would be sent to the model # Remove the 'model' field from the body as it's not part of the model input body_data = {k: v for k, v in request_data.items() if k != "model"} - return {"input": {"invokeModel": {"body": json.dumps(body_data)}}} + if "messages" in body_data: + # Bedrock validates the body against the model's InvokeModel schema; + # Anthropic Messages bodies require these fields. + body_data.setdefault("anthropic_version", "bedrock-2023-05-31") + body_data.setdefault( + "max_tokens", DEFAULT_ANTHROPIC_INVOKE_MODEL_MAX_TOKENS + ) + + # The CountTokens API expects invokeModel.body as a base64-encoded blob + encoded_body = base64.b64encode(json.dumps(body_data).encode()).decode() + return {"input": {"invokeModel": {"body": encoded_body}}} def get_bedrock_count_tokens_endpoint( self, diff --git a/litellm/llms/bedrock/messages/mantle_transformation.py b/litellm/llms/bedrock/messages/mantle_transformation.py index a78f696a057..900d9aa97d8 100644 --- a/litellm/llms/bedrock/messages/mantle_transformation.py +++ b/litellm/llms/bedrock/messages/mantle_transformation.py @@ -6,7 +6,7 @@ AmazonAnthropicClaudeMessagesConfig. Overrides only the URL and model-prefix stripping that are specific to the bedrock-mantle endpoint. """ -from typing import TYPE_CHECKING, Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from litellm.llms.bedrock.messages.invoke_transformations.anthropic_claude3_transformation import ( AmazonAnthropicClaudeMessagesConfig, @@ -45,6 +45,30 @@ class AmazonMantleMessagesConfig(AmazonAnthropicClaudeMessagesConfig): region = self._get_aws_region_name(optional_params=optional_params, model=model) return MANTLE_ENDPOINT_TEMPLATE.format(region=region) + def validate_anthropic_messages_environment( + self, + headers: dict, + model: str, + messages: List[Any], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> Tuple[dict, Optional[str]]: + headers, api_base = super().validate_anthropic_messages_environment( + headers=headers, + model=model, + messages=messages, + optional_params=optional_params, + litellm_params=litellm_params, + api_key=api_key, + api_base=api_base, + ) + project_id = litellm_params.get("aws_bedrock_project_id") + if project_id: + headers["anthropic-workspace"] = project_id + return headers, api_base + def transform_anthropic_messages_request( self, model: str, diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py b/litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py new file mode 100644 index 00000000000..e38044afb36 --- /dev/null +++ b/litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py @@ -0,0 +1,5 @@ +from litellm.llms.bedrock.passthrough.guardrail_translation.handler import ( + BedrockPassthroughGuardrailHandler, +) + +__all__ = ["BedrockPassthroughGuardrailHandler"] diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py new file mode 100644 index 00000000000..2d6bdb5298a --- /dev/null +++ b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py @@ -0,0 +1,507 @@ +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union + +from litellm._logging import verbose_proxy_logger +from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation +from litellm.llms.base_llm.guardrail_translation.utils import ( + effective_skip_system_message_for_guardrail, + effective_skip_tool_message_for_guardrail, +) +from litellm.types.utils import GenericGuardrailAPIInputs + +if TYPE_CHECKING: + from litellm.integrations.custom_guardrail import CustomGuardrail + from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj + from litellm.proxy._types import UserAPIKeyAuth + from litellm.proxy.utils import ProxyLogging + +_CONVERSE_ACTIONS = frozenset({"converse", "converse-stream"}) +_EVENT_STREAM_CONTENT_TYPE = "vnd.amazon.eventstream" +_EVENT_STREAM_MEDIA_TYPE = "application/vnd.amazon.eventstream" + + +def _is_converse_endpoint(endpoint: str) -> bool: + parts = endpoint.rstrip("/").split("/") + return bool(parts) and parts[-1] in _CONVERSE_ACTIONS + + +def _generic_passthrough_handler() -> BaseTranslation: + """ + Fallback for non-Converse Bedrock routes (e.g. invoke). The generic + handler scans the full request/response payload so blocking guardrails + still run, matching how other passthrough providers are guarded. + """ + from litellm.llms.pass_through.guardrail_translation.handler import ( + PassThroughEndpointHandler, + ) + + return PassThroughEndpointHandler() + + +_StringHolder = Tuple[Any, Union[str, int]] + + +def _collect_strings(node: Any, holders: List[_StringHolder]) -> None: + """ + Record a (container, key) holder for every non-empty string value nested + under an arbitrary JSON node, so prompt content a caller hides in fields + like ``toolUse.input`` or ``toolResult.content[].json`` is still scanned + and can be written back in place. Iterative to avoid unbounded recursion + on deeply nested payloads. + """ + stack: List[Any] = [node] + while stack: + current = stack.pop() + if isinstance(current, dict): + for key, value in current.items(): + if isinstance(value, str): + if value: + holders.append((current, key)) + else: + stack.append(value) + elif isinstance(current, list): + for index, value in enumerate(current): + if isinstance(value, str): + if value: + holders.append((current, index)) + else: + stack.append(value) + + +def _collect_block_text(block: dict, holders: List[_StringHolder]) -> None: + text = block.get("text") + if isinstance(text, str) and text: + holders.append((block, "text")) + + +def _extract_converse_texts( + body: dict, + skip_system: bool, + skip_tool: bool, +) -> Tuple[List[str], List[_StringHolder]]: + """ + Walk a Bedrock Converse request body and collect text content. + + Returns (texts, holders) where each holder is the (container, key) pair + that owns the extracted string, so write-back mutates it in place. Besides + top-level ``text`` blocks this scans the arbitrary-JSON fields a caller can + hide prompt content in -- ``toolUse.input`` and + ``toolResult.content[].json`` (alongside ``toolResult.content[].text``) -- + as well as the request-level fields still forwarded to Bedrock that a caller + can route blocked content through: ``toolConfig.tools`` (tool names, + descriptions and input schemas) and ``additionalModelRequestFields``. Tool + message blocks are skipped when tool messages are excluded, but tool + definitions are always scanned to match the chat-completions guardrail path. + """ + holders: List[_StringHolder] = [] + + if not skip_system: + for block in body.get("system") or []: + if isinstance(block, dict): + _collect_block_text(block, holders) + + for message in body.get("messages") or []: + if not isinstance(message, dict): + continue + for block in message.get("content") or []: + if not isinstance(block, dict): + continue + if skip_tool and ("toolUse" in block or "toolResult" in block): + continue + _collect_block_text(block, holders) + tool_use = block.get("toolUse") + if isinstance(tool_use, dict): + _collect_strings(tool_use.get("input"), holders) + tool_result = block.get("toolResult") + if isinstance(tool_result, dict): + for inner in tool_result.get("content") or []: + if isinstance(inner, dict): + _collect_block_text(inner, holders) + _collect_strings(inner.get("json"), holders) + + tool_config = body.get("toolConfig") + if isinstance(tool_config, dict): + _collect_strings(tool_config.get("tools"), holders) + + _collect_strings(body.get("additionalModelRequestFields"), holders) + + texts = [container[key] for container, key in holders] + return texts, holders + + +def _extract_converse_output_texts( + content_blocks: List[Any], +) -> Tuple[List[str], List[_StringHolder]]: + """ + Collect user-visible text from Bedrock Converse output content blocks. + + Covers ``text`` blocks plus the other content-bearing fields a model can + emit -- ``toolUse.input``, ``reasoningContent.reasoningText.text`` and + ``citationsContent.content[].text`` -- while leaving structural values such + as reasoning signatures and citation sources untouched. + """ + holders: List[_StringHolder] = [] + for block in content_blocks: + if not isinstance(block, dict): + continue + _collect_block_text(block, holders) + tool_use = block.get("toolUse") + if isinstance(tool_use, dict): + _collect_strings(tool_use.get("input"), holders) + reasoning = block.get("reasoningContent") + if isinstance(reasoning, dict): + reasoning_text = reasoning.get("reasoningText") + if isinstance(reasoning_text, dict): + _collect_block_text(reasoning_text, holders) + citations = block.get("citationsContent") + if isinstance(citations, dict): + for cited in citations.get("content") or []: + if isinstance(cited, dict): + _collect_block_text(cited, holders) + texts = [container[key] for container, key in holders] + return texts, holders + + +def _write_back_texts( + guardrailed_texts: List[str], + holders: List[_StringHolder], +) -> None: + if len(guardrailed_texts) < len(holders): + verbose_proxy_logger.warning( + "BedrockPassthroughGuardrailHandler: guardrail returned %d texts for %d " + "extracted fields; the unreturned fields keep their original text", + len(guardrailed_texts), + len(holders), + ) + for idx, (container, key) in enumerate(holders): + if idx >= len(guardrailed_texts): + break + container[key] = guardrailed_texts[idx] + + +_DeltaHolder = Tuple[Any, Any, Union[str, int]] + + +def _collect_stream_delta_text_holders(delta: Any) -> List[_DeltaHolder]: + """ + Collect the user-visible text strings a Bedrock Converse ``contentBlockDelta`` + can carry, matching the coverage of the non-streaming output handler. + + Each holder is ``(group_key, container, key)`` where ``container[key]`` is the + text. ``group_key`` ties together fragments that belong to the same logical + stream (e.g. a single mask token split across frames) so they are + concatenated before guardrailing and redistributed afterwards. Structural + values such as reasoning signatures, redacted reasoning and citation sources + are left out so they are never rewritten. + """ + holders: List[_DeltaHolder] = [] + if not isinstance(delta, dict): + return holders + if isinstance(delta.get("text"), str): + holders.append(("text", delta, "text")) + tool_use = delta.get("toolUse") + if isinstance(tool_use, dict) and isinstance(tool_use.get("input"), str): + holders.append(("tool", tool_use, "input")) + reasoning = delta.get("reasoningContent") + if isinstance(reasoning, dict) and isinstance(reasoning.get("text"), str): + holders.append(("reasoning", reasoning, "text")) + citations = delta.get("citationsContent") + if isinstance(citations, dict): + for index, cited in enumerate(citations.get("content") or []): + if isinstance(cited, dict) and isinstance(cited.get("text"), str): + holders.append((("citation", index), cited, "text")) + return holders + + +class BedrockPassthroughGuardrailHandler(BaseTranslation): + @staticmethod + def is_event_stream_content_type(content_type: str) -> bool: + return _EVENT_STREAM_CONTENT_TYPE in content_type + + @staticmethod + def event_stream_media_type() -> str: + return _EVENT_STREAM_MEDIA_TYPE + + @staticmethod + def event_stream_endpoint_is_de_anonymizable(endpoint: str) -> bool: + return _is_converse_endpoint(endpoint) + + @staticmethod + async def de_anonymize_event_stream( # noqa: PLR0915 + body_bytes: bytes, + proxy_logging_obj: "ProxyLogging", + user_api_key_dict: "UserAPIKeyAuth", + data: dict, + ) -> bytes: + import json as _json + import struct + from binascii import crc32 as esm_crc32 + + from botocore.eventstream import EventStreamBuffer + + frames: list[dict] = [] + offset = 0 + + while offset + 16 <= len(body_bytes): + total_length = struct.unpack("!I", body_bytes[offset : offset + 4])[0] + if total_length < 16 or offset + total_length > len(body_bytes): + break + frame_raw = body_bytes[offset : offset + total_length] + offset += total_length + + try: + buf = EventStreamBuffer() + buf.add_data(frame_raw) + msg = next(iter(buf)) + event_type = msg.headers.get(":event-type") + payload_bytes = msg.payload + except Exception as e: + verbose_proxy_logger.debug( + "BedrockPassthroughGuardrailHandler: could not decode event-stream " + "frame, forwarding it unmodified: %s", + e, + ) + frames.append({"raw": frame_raw, "texts": []}) + continue + + texts: List[Tuple[Any, str]] = [] + if event_type == "contentBlockDelta": + try: + payload_dict = _json.loads(payload_bytes) + texts = [ + (group_key, container[key]) + for group_key, container, key in _collect_stream_delta_text_holders( + payload_dict.get("delta") + ) + ] + except Exception as e: + verbose_proxy_logger.debug( + "BedrockPassthroughGuardrailHandler: could not parse " + "contentBlockDelta payload, forwarding frame unmodified: %s", + e, + ) + + frames.append({"raw": frame_raw, "texts": texts}) + + trailing_bytes = body_bytes[offset:] + + group_order: List[Any] = [] + group_members: dict[Any, list[Tuple[int, int]]] = {} + group_texts: dict[Any, list[str]] = {} + for frame_idx, frame in enumerate(frames): + for local_idx, (group_key, text) in enumerate(frame["texts"]): + if group_key not in group_members: + group_members[group_key] = [] + group_texts[group_key] = [] + group_order.append(group_key) + group_members[group_key].append((frame_idx, local_idx)) + group_texts[group_key].append(text) + + active_groups = [gk for gk in group_order if "".join(group_texts[gk])] + if not active_groups: + return body_bytes + + synthetic_response: dict = { + "output": { + "message": { + "role": "assistant", + "content": [ + {"text": "".join(group_texts[gk])} for gk in active_groups + ], + } + }, + "stopReason": "end_turn", + } + + processed = await proxy_logging_obj.post_call_success_hook( + data=data, + user_api_key_dict=user_api_key_dict, + response=synthetic_response, # type: ignore[arg-type] + ) + + if not isinstance(processed, dict): + verbose_proxy_logger.debug( + "BedrockPassthroughGuardrailHandler: post_call_success_hook returned %s, " + "leaving event stream unmodified", + type(processed).__name__, + ) + return body_bytes + + try: + processed_blocks = processed["output"]["message"]["content"] # type: ignore[index] + de_anonymized_texts = [ + processed_blocks[i]["text"] for i in range(len(active_groups)) + ] + except (KeyError, IndexError, TypeError): + return body_bytes + + new_text_map: dict[Tuple[int, int], str] = {} + for group_key, de_anonymized_text in zip(active_groups, de_anonymized_texts): + members = group_members[group_key] + orig_texts = group_texts[group_key] + total_orig = sum(len(t) for t in orig_texts) or 1 + de_anon_len = len(de_anonymized_text) + pos = 0 + for k, member in enumerate(members): + if k == len(members) - 1: + new_text_map[member] = de_anonymized_text[pos:] + else: + end = pos + round(de_anon_len * len(orig_texts[k]) / total_orig) + new_text_map[member] = de_anonymized_text[pos:end] + pos = end + + result_parts: list[bytes] = [] + + for frame_idx, frame in enumerate(frames): + if not frame["texts"]: + result_parts.append(frame["raw"]) + continue + + frame_raw = frame["raw"] + orig_total = struct.unpack("!I", frame_raw[0:4])[0] + orig_hdrs_len = struct.unpack("!I", frame_raw[4:8])[0] + headers_bytes = frame_raw[12 : 12 + orig_hdrs_len] + + try: + payload_dict = _json.loads( + frame_raw[12 + orig_hdrs_len : orig_total - 4] + ) + for local_idx, (_, container, key) in enumerate( + _collect_stream_delta_text_holders(payload_dict.get("delta")) + ): + new_text = new_text_map.get((frame_idx, local_idx)) + if new_text is not None: + container[key] = new_text + new_payload = _json.dumps(payload_dict, separators=(",", ":")).encode() + except Exception: + result_parts.append(frame_raw) + continue + + new_total = 12 + orig_hdrs_len + len(new_payload) + 4 + prelude = struct.pack("!II", new_total, orig_hdrs_len) + prelude_crc_val = esm_crc32(prelude) & 0xFFFFFFFF + prelude_crc_b = struct.pack("!I", prelude_crc_val) + part_for_msg_crc = prelude_crc_b + headers_bytes + new_payload + msg_crc_val = esm_crc32(part_for_msg_crc, prelude_crc_val) & 0xFFFFFFFF + msg_crc_b = struct.pack("!I", msg_crc_val) + + result_parts.append( + prelude + prelude_crc_b + headers_bytes + new_payload + msg_crc_b + ) + + result_parts.append(trailing_bytes) + return b"".join(result_parts) + + async def process_input_messages( + self, + data: dict, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None, + ) -> Any: + endpoint = data.get("endpoint", "") + body = data.get("data") + + if not _is_converse_endpoint(endpoint): + return await _generic_passthrough_handler().process_input_messages( + data=data, + guardrail_to_apply=guardrail_to_apply, + litellm_logging_obj=litellm_logging_obj, + ) + + if not isinstance(body, dict) or not isinstance(body.get("messages"), list): + return data + + skip_system = effective_skip_system_message_for_guardrail(guardrail_to_apply) + skip_tool = effective_skip_tool_message_for_guardrail(guardrail_to_apply) + + texts, holders = _extract_converse_texts(body, skip_system, skip_tool) + + if not texts: + return data + + inputs = GenericGuardrailAPIInputs(texts=texts) + model = data.get("model") + if model: + inputs["model"] = model + + guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=inputs, + request_data=data, + input_type="request", + logging_obj=litellm_logging_obj, + ) + + guardrailed_texts = guardrailed_inputs.get("texts", []) + if guardrailed_texts: + _write_back_texts(guardrailed_texts, holders) + + return data + + async def process_output_response( + self, + response: Any, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None, + user_api_key_dict: Optional[Any] = None, + request_data: Optional[dict] = None, + ) -> Any: + endpoint = (request_data or {}).get("endpoint", "") + if endpoint and not _is_converse_endpoint(endpoint): + return await _generic_passthrough_handler().process_output_response( + response=response, + guardrail_to_apply=guardrail_to_apply, + litellm_logging_obj=litellm_logging_obj, + user_api_key_dict=user_api_key_dict, + request_data=request_data, + ) + + if not isinstance(response, dict): + return response + + output_message = ( + response.get("output", {}).get("message", {}) + if isinstance(response.get("output"), dict) + else {} + ) + content_blocks = ( + output_message.get("content") if isinstance(output_message, dict) else None + ) + + if not isinstance(content_blocks, list): + return response + + texts, holders = _extract_converse_output_texts(content_blocks) + + if not texts: + return response + + effective_request_data = request_data or {} + if ( + "litellm_metadata" not in effective_request_data + and user_api_key_dict is not None + ): + user_metadata = self.transform_user_api_key_dict_to_metadata( + user_api_key_dict + ) + if user_metadata: + effective_request_data = { + **effective_request_data, + "litellm_metadata": user_metadata, + } + + inputs = GenericGuardrailAPIInputs(texts=texts) + model = effective_request_data.get("model") if effective_request_data else None + if model: + inputs["model"] = model + + guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=inputs, + request_data=effective_request_data, + input_type="response", + logging_obj=litellm_logging_obj, + ) + + guardrailed_texts = guardrailed_inputs.get("texts", []) + if guardrailed_texts: + _write_back_texts(guardrailed_texts, holders) + + return response diff --git a/litellm/llms/bedrock_mantle/chat/transformation.py b/litellm/llms/bedrock_mantle/chat/transformation.py index 81a56030a5c..18f051f8524 100644 --- a/litellm/llms/bedrock_mantle/chat/transformation.py +++ b/litellm/llms/bedrock_mantle/chat/transformation.py @@ -8,11 +8,14 @@ Auth: AWS Bedrock API key as Bearer token (set via BEDROCK_MANTLE_API_KEY env va or region-aware key via BEDROCK_MANTLE_{REGION}_API_KEY. """ -from typing import Iterator, AsyncIterator, Any, Optional, Tuple, Union +from typing import Iterator, AsyncIterator, Any, List, Optional, Tuple, Union import litellm from litellm._logging import verbose_logger +from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM from litellm.secret_managers.main import get_secret_str +from litellm.types.llms.openai import AllMessageValues +from litellm.types.router import GenericLiteLLMParams from ...openai_like.chat.transformation import OpenAILikeChatConfig @@ -33,13 +36,19 @@ class BedrockMantleChatConfig(OpenAILikeChatConfig): return super().get_config() def _get_openai_compatible_provider_info( - self, api_base: Optional[str], api_key: Optional[str] + self, + api_base: Optional[str], + api_key: Optional[str], + litellm_params: Optional[GenericLiteLLMParams] = None, ) -> Tuple[Optional[str], Optional[str]]: region = ( - get_secret_str("BEDROCK_MANTLE_REGION") + (litellm_params.aws_region_name if litellm_params else None) + or get_secret_str("BEDROCK_MANTLE_REGION") + or get_secret_str("AWS_REGION_NAME") or get_secret_str("AWS_REGION") or BEDROCK_MANTLE_DEFAULT_REGION ) + BaseAWSLLM._validate_aws_region_name(region) api_base = ( api_base or get_secret_str("BEDROCK_MANTLE_API_BASE") @@ -48,6 +57,30 @@ class BedrockMantleChatConfig(OpenAILikeChatConfig): dynamic_api_key = api_key or get_secret_str("BEDROCK_MANTLE_API_KEY") return api_base, dynamic_api_key + def validate_environment( + self, + headers: dict, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + headers = super().validate_environment( + headers=headers, + model=model, + messages=messages, + optional_params=optional_params, + litellm_params=litellm_params, + api_key=api_key, + api_base=api_base, + ) + project_id = litellm_params.get("aws_bedrock_project_id") + if project_id: + headers["OpenAI-Project"] = project_id + return headers + def get_supported_openai_params(self, model: str) -> list: base_params = super().get_supported_openai_params(model) try: diff --git a/litellm/llms/bedrock_mantle/responses/__init__.py b/litellm/llms/bedrock_mantle/responses/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/litellm/llms/bedrock_mantle/responses/transformation.py b/litellm/llms/bedrock_mantle/responses/transformation.py new file mode 100644 index 00000000000..b409666a967 --- /dev/null +++ b/litellm/llms/bedrock_mantle/responses/transformation.py @@ -0,0 +1,239 @@ +""" +Amazon Bedrock Mantle - Responses API backend. + +Mantle serves Responses on two upstream paths: gpt frontier models (gpt-5.5 / +gpt-5.4) on `/openai/v1/responses`, and everything else that supports Responses +(e.g. gpt-oss) on the standard `/v1/responses`. The gate picks the path per +model and injects it via `use_openai_path`. Payloads and SSE follow the OpenAI +Responses spec, so this config inherits OpenAIResponsesAPIConfig and overrides +only the endpoint URL and authentication. + +Auth: Bearer token (BEDROCK_MANTLE_API_KEY or the standard +AWS_BEARER_TOKEN_BEDROCK, or litellm_params.api_key) when present; otherwise +AWS SigV4 (service name "bedrock") using the standard credential chain (IAM +role / access key / profile / web identity), signed via the shared +BaseAWSLLM._sign_request after the request body is finalized. +""" + +import re +from typing import Any, Dict, List, Optional, Tuple + +from botocore.exceptions import ( + CredentialRetrievalError, + NoCredentialsError, + PartialCredentialsError, + ProfileNotFound, +) + +from litellm._logging import verbose_logger +from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM +from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig +from litellm.secret_managers.main import get_secret_str +from litellm.types.llms.openai import ResponsesAPIOptionalRequestParams +from litellm.types.router import GenericLiteLLMParams +from litellm.types.utils import LlmProviders + +BEDROCK_MANTLE_DEFAULT_REGION = "us-east-1" + +# Checked longest/most-specific first so a full endpoint URL collapses to host +# in one pass and the appended path never doubles. +_BASE_SUFFIXES_TO_STRIP = ( + "/openai/v1/responses", + "/v1/responses", + "/responses", + "/openai/v1", + "/v1", +) + +# Standard Mantle host: https://bedrock-mantle..api.aws (group 1 = region). +_MANTLE_HOST_RE = re.compile( + r"^https?://bedrock-mantle\.([^/.]+)\.api\.aws", re.IGNORECASE +) + +# Per Bedrock Mantle Responses API validation errors. +_BEDROCK_MANTLE_SUPPORTED_RESPONSE_TOOL_TYPES = frozenset( + {"function", "mcp", "custom", "namespace", "tool_search"} +) + + +class BedrockMantleResponsesAPIConfig(OpenAIResponsesAPIConfig): + def __init__( + self, + aws_signer: Optional[BaseAWSLLM] = None, + use_openai_path: bool = True, + ): + super().__init__() + self._aws_signer = aws_signer or BaseAWSLLM() + self.use_openai_path = use_openai_path + + @property + def custom_llm_provider(self) -> LlmProviders: + return LlmProviders.BEDROCK_MANTLE + + @staticmethod + def _resolve_region(params: dict) -> str: + region = params.get("aws_region_name") + if region: + BaseAWSLLM._validate_aws_region_name(region) + return region + base = params.get("api_base") or get_secret_str("BEDROCK_MANTLE_API_BASE") + if base: + match = _MANTLE_HOST_RE.match(base.rstrip("/")) + if match: + return match.group(1) + return ( + get_secret_str("BEDROCK_MANTLE_REGION") + or get_secret_str("AWS_REGION_NAME") + or get_secret_str("AWS_REGION") + or BEDROCK_MANTLE_DEFAULT_REGION + ) + + def get_complete_url( + self, + api_base: Optional[str], + litellm_params: dict, + ) -> str: + region = self._resolve_region({**litellm_params, "api_base": api_base}) + base = ( + api_base + or get_secret_str("BEDROCK_MANTLE_API_BASE") + or f"https://bedrock-mantle.{region}.api.aws" + ) + base = base.rstrip("/") + for suffix in _BASE_SUFFIXES_TO_STRIP: + if base.endswith(suffix): + base = base[: -len(suffix)] + break + # For the standard Mantle host (including the default-region base that + # responses/main.py auto-injects into litellm_params.api_base), pin to the + # single resolved region so aws_region_name wins; preserve custom proxy hosts. + if _MANTLE_HOST_RE.match(base): + base = f"https://bedrock-mantle.{region}.api.aws" + path = "/openai/v1/responses" if self.use_openai_path else "/v1/responses" + return f"{base}{path}" + + def validate_environment( + self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] + ) -> dict: + litellm_params = litellm_params or GenericLiteLLMParams() + api_key = ( + litellm_params.api_key + or get_secret_str("BEDROCK_MANTLE_API_KEY") + or get_secret_str("AWS_BEARER_TOKEN_BEDROCK") + ) + if api_key: + headers["Authorization"] = f"Bearer {api_key}" + if litellm_params.aws_bedrock_project_id: + headers["OpenAI-Project"] = litellm_params.aws_bedrock_project_id + return headers + + def supports_native_file_search(self) -> bool: + return False + + def supports_native_websocket(self) -> bool: + return False + + @staticmethod + def _filter_unsupported_tools(tools: List[Any]) -> List[Any]: + """Keep only tool types Mantle's Responses API accepts.""" + kept: List[Any] = [] + dropped_types: List[str] = [] + for tool in tools: + if not isinstance(tool, dict): + kept.append(tool) + continue + tool_type = tool.get("type") + if tool_type in _BEDROCK_MANTLE_SUPPORTED_RESPONSE_TOOL_TYPES: + kept.append(tool) + else: + dropped_types.append(str(tool_type)) + + if dropped_types: + verbose_logger.warning( + "Bedrock Mantle Responses API: dropping unsupported tool type(s) " + "%s (supported: %s).", + sorted(set(dropped_types)), + sorted(_BEDROCK_MANTLE_SUPPORTED_RESPONSE_TOOL_TYPES), + ) + + return kept + + def map_openai_params( + self, + response_api_optional_params: ResponsesAPIOptionalRequestParams, + model: str, + drop_params: bool, + ) -> Dict: + params = super().map_openai_params( + response_api_optional_params=response_api_optional_params, + model=model, + drop_params=drop_params, + ) + + tools = params.get("tools") + if not tools: + return params + + tools_list = tools if isinstance(tools, list) else [tools] + filtered = self._filter_unsupported_tools(tools_list) + if filtered: + params["tools"] = filtered + else: + params.pop("tools", None) + + return params + + def sign_request( + self, + headers: dict, + optional_params: dict, + request_data: dict, + api_base: str, + api_key: Optional[str] = None, + model: Optional[str] = None, + stream: Optional[bool] = None, + fake_stream: Optional[bool] = None, + ) -> Tuple[dict, Optional[bytes]]: + bearer = ( + api_key + or get_secret_str("BEDROCK_MANTLE_API_KEY") + or get_secret_str("AWS_BEARER_TOKEN_BEDROCK") + ) + if not bearer: + # SigV4 path. Pin the credential-scope region to the region of the actual + # signing URL (api_base, already region-resolved by get_complete_url) so the + # SigV4 scope and the URL host can never disagree. Resolve from api_base first, + # then fall back to the regular precedence. Also drop any caller Authorization + # so _sign_request's restore-original-Authorization step cannot override the + # SigV4 header. + optional_params = { + **optional_params, + "aws_region_name": self._resolve_region( + {**optional_params, "api_base": api_base} + ), + } + headers = {k: v for k, v in headers.items() if k.lower() != "authorization"} + try: + return self._aws_signer._sign_request( + service_name="bedrock", + headers=headers, + optional_params=optional_params, + request_data=request_data, + api_base=api_base, + api_key=bearer, + model=model, + stream=stream, + fake_stream=fake_stream, + ) + except ( + NoCredentialsError, + PartialCredentialsError, + ProfileNotFound, + CredentialRetrievalError, + ) as e: + raise ValueError( + "Bedrock Mantle auth failed: no Bearer token and no usable AWS " + "credentials. Set BEDROCK_MANTLE_API_KEY (or AWS_BEARER_TOKEN_BEDROCK) " + "or pass api_key for Bearer auth, or provide AWS credentials " + "(IAM role / access key / profile / web identity) for SigV4." + ) from e diff --git a/litellm/llms/cohere/chat/v2_transformation.py b/litellm/llms/cohere/chat/v2_transformation.py index 190491adfc7..9aa8c114907 100644 --- a/litellm/llms/cohere/chat/v2_transformation.py +++ b/litellm/llms/cohere/chat/v2_transformation.py @@ -120,6 +120,7 @@ class CohereV2ChatConfig(OpenAIGPTConfig): "stream", "temperature", "max_tokens", + "max_completion_tokens", "top_p", "frequency_penalty", "presence_penalty", @@ -143,7 +144,12 @@ class CohereV2ChatConfig(OpenAIGPTConfig): optional_params["stream"] = value if param == "temperature": optional_params["temperature"] = value - if param == "max_tokens": + if ( + param == "max_tokens" + and "max_completion_tokens" not in non_default_params + ): + optional_params["max_tokens"] = value + if param == "max_completion_tokens": optional_params["max_tokens"] = value if param == "n": optional_params["num_generations"] = value diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py index e11d8532dbf..01c94476431 100644 --- a/litellm/llms/custom_httpx/http_handler.py +++ b/litellm/llms/custom_httpx/http_handler.py @@ -589,6 +589,7 @@ class AsyncHTTPHandler: params: Optional[dict] = None, headers: Optional[dict] = None, follow_redirects: Optional[bool] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, ): # Set follow_redirects to UseClientDefault if None _follow_redirects = ( @@ -599,7 +600,11 @@ class AsyncHTTPHandler: params.update(HTTPHandler.extract_query_params(url)) response = await self.client.get( - url, params=params, headers=headers, follow_redirects=_follow_redirects # type: ignore + url, + params=params, + headers=headers, # type: ignore + follow_redirects=_follow_redirects, # type: ignore + timeout=timeout if timeout is not None else USE_CLIENT_DEFAULT, ) return response @@ -1115,6 +1120,7 @@ class HTTPHandler: params: Optional[dict] = None, headers: Optional[dict] = None, follow_redirects: Optional[bool] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, ): # Set follow_redirects to UseClientDefault if None _follow_redirects = ( @@ -1128,6 +1134,7 @@ class HTTPHandler: params=params, headers=headers, follow_redirects=_follow_redirects, + timeout=timeout if timeout is not None else USE_CLIENT_DEFAULT, ) return response diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index 5c502c56ffe..c3f487997c3 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -125,6 +125,7 @@ from litellm.types.vector_stores import ( VectorStoreSearchOptionalRequestParams, VectorStoreSearchResponse, ) +from litellm.types.realtime import RealtimeQueryParams from litellm.types.videos.main import VideoObject from litellm.utils import ( CustomStreamWrapper, @@ -1751,6 +1752,7 @@ class BaseLLMHTTPHandler: api_base=api_base, optional_params=optional_params, data=data, + api_key=api_key, ) ## LOGGING @@ -1833,6 +1835,7 @@ class BaseLLMHTTPHandler: api_base=api_base, optional_params=optional_params, data=data, + api_key=api_key, ) ## LOGGING @@ -2303,6 +2306,7 @@ class BaseLLMHTTPHandler: if extra_body: data.update(extra_body) + stream = bool(stream or data.get("stream")) # Preserve the OpenAI-style request context (not sent to the provider) for streaming # hooks/metadata; the streaming iterator now consumes this to run deployment hooks @@ -2316,6 +2320,31 @@ class BaseLLMHTTPHandler: # but never included in the outbound provider payload. request_context["litellm_params"] = dict(litellm_params) + is_stream_request = bool(stream) + if is_stream_request and fake_stream is True: + stream, data = self._prepare_fake_stream_request( + stream=stream, + data=data, + fake_stream=fake_stream, + ) + + # Sign after the body is final (post-transform/normalize/extra_body and post + # fake-stream prep) so signed bytes match what we send. No-op for providers + # that inherit the default sign_request. + headers, signed_body = responses_api_provider_config.sign_request( + headers=headers, + optional_params=dict(litellm_params), + request_data=data, + api_base=api_base, + api_key=litellm_params.api_key, + model=model, + stream=stream, + fake_stream=fake_stream, + ) + body_kwargs: Dict[str, Any] = ( + {"data": signed_body} if signed_body is not None else {"json": data} + ) + ## LOGGING logging_obj.pre_call( input=input, @@ -2328,22 +2357,14 @@ class BaseLLMHTTPHandler: ) try: - if stream: - # For streaming, use stream=True in the request - if fake_stream is True: - stream, data = self._prepare_fake_stream_request( - stream=stream, - data=data, - fake_stream=fake_stream, - ) - + if is_stream_request: response = sync_httpx_client.post( url=api_base, headers=headers, - json=data, timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), stream=stream, + **body_kwargs, ) if fake_stream is True: return MockResponsesAPIStreamingIterator( @@ -2368,13 +2389,12 @@ class BaseLLMHTTPHandler: call_type=CallTypes.responses.value, ) else: - # For non-streaming requests response = sync_httpx_client.post( url=api_base, headers=headers, - json=data, timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), + **body_kwargs, ) except Exception as e: raise self._handle_error( @@ -2449,6 +2469,7 @@ class BaseLLMHTTPHandler: if extra_body: data.update(extra_body) + stream = bool(stream or data.get("stream")) # Preserve the OpenAI-style request context (not sent to the provider) for streaming # hooks/metadata; the streaming iterator now consumes this to run deployment hooks @@ -2462,6 +2483,28 @@ class BaseLLMHTTPHandler: # but never included in the outbound provider payload. request_context["litellm_params"] = dict(litellm_params) + is_stream_request = bool(stream) + if is_stream_request and fake_stream is True: + stream, data = self._prepare_fake_stream_request( + stream=stream, + data=data, + fake_stream=fake_stream, + ) + + headers, signed_body = responses_api_provider_config.sign_request( + headers=headers, + optional_params=dict(litellm_params), + request_data=data, + api_base=api_base, + api_key=litellm_params.api_key, + model=model, + stream=stream, + fake_stream=fake_stream, + ) + body_kwargs: Dict[str, Any] = ( + {"data": signed_body} if signed_body is not None else {"json": data} + ) + ## LOGGING logging_obj.pre_call( input=input, @@ -2474,22 +2517,14 @@ class BaseLLMHTTPHandler: ) try: - if stream: - # For streaming, we need to use stream=True in the request - if fake_stream is True: - stream, data = self._prepare_fake_stream_request( - stream=stream, - data=data, - fake_stream=fake_stream, - ) - + if is_stream_request: response = await async_httpx_client.post( url=api_base, headers=headers, - json=data, timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), stream=stream, + **body_kwargs, ) if fake_stream is True: @@ -2516,13 +2551,12 @@ class BaseLLMHTTPHandler: call_type=CallTypes.responses.value, ) else: - # For non-streaming, proceed as before response = await async_httpx_client.post( url=api_base, headers=headers, - json=data, timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), + **body_kwargs, ) except Exception as e: @@ -2586,6 +2620,8 @@ class BaseLLMHTTPHandler: headers=headers, ) + headers.setdefault("Content-Type", "application/json") + ## LOGGING logging_obj.pre_call( input=input, @@ -2676,6 +2712,8 @@ class BaseLLMHTTPHandler: headers=headers, ) + headers.setdefault("Content-Type", "application/json") + ## LOGGING logging_obj.pre_call( input=input, @@ -3999,6 +4037,18 @@ class BaseLLMHTTPHandler: ) data = BaseResponsesAPIConfig.normalize_responses_api_request_dict(data) + headers, signed_body = responses_api_provider_config.sign_request( + headers=headers, + optional_params=dict(litellm_params), + request_data=data, + api_base=url, + api_key=litellm_params.api_key, + model=model, + ) + body_kwargs: Dict[str, Any] = ( + {"data": signed_body} if signed_body is not None else {"json": data} + ) + ## LOGGING logging_obj.pre_call( input=input, @@ -4012,7 +4062,7 @@ class BaseLLMHTTPHandler: try: response = sync_httpx_client.post( - url=url, headers=headers, json=data, timeout=timeout + url=url, headers=headers, timeout=timeout, **body_kwargs ) except Exception as e: @@ -4082,6 +4132,18 @@ class BaseLLMHTTPHandler: ) data = BaseResponsesAPIConfig.normalize_responses_api_request_dict(data) + headers, signed_body = responses_api_provider_config.sign_request( + headers=headers, + optional_params=dict(litellm_params), + request_data=data, + api_base=url, + api_key=litellm_params.api_key, + model=model, + ) + body_kwargs: Dict[str, Any] = ( + {"data": signed_body} if signed_body is not None else {"json": data} + ) + ## LOGGING logging_obj.pre_call( input=input, @@ -4095,7 +4157,7 @@ class BaseLLMHTTPHandler: try: response = await async_httpx_client.post( - url=url, headers=headers, json=data, timeout=timeout + url=url, headers=headers, timeout=timeout, **body_kwargs ) except Exception as e: @@ -5256,6 +5318,23 @@ class BaseLLMHTTPHandler: headers=error_headers, ) + @staticmethod + def _append_query_params( + url: str, query_params: Optional[RealtimeQueryParams] + ) -> str: + """Append query_params to url, skipping keys already present in the URL.""" + if not query_params: + return url + from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse + + parsed = urlparse(url) + existing = dict(parse_qsl(parsed.query)) + extras = {k: v for k, v in query_params.items() if k not in existing} + if not extras: + return url + new_query = parsed.query + ("&" if parsed.query else "") + urlencode(extras) + return urlunparse(parsed._replace(query=new_query)) + async def async_realtime( self, model: str, @@ -5269,11 +5348,14 @@ class BaseLLMHTTPHandler: timeout: Optional[float] = None, user_api_key_dict: Optional[Any] = None, litellm_metadata: Optional[Dict[str, Any]] = None, + query_params: Optional[RealtimeQueryParams] = None, ): import websockets from websockets.asyncio.client import ClientConnection - url = provider_config.get_complete_url(api_base, model, api_key) + url = self._append_query_params( + provider_config.get_complete_url(api_base, model, api_key), query_params + ) headers = provider_config.validate_environment( headers=headers, model=model, @@ -5314,6 +5396,11 @@ class BaseLLMHTTPHandler: model, user_api_key_dict=user_api_key_dict, request_data=_request_data, + force_transcription_model=( + model + if (query_params or {}).get("intent") == "transcription" + else None + ), ) if _session_config: realtime_streaming.session_configuration_request = _session_config @@ -5378,6 +5465,69 @@ class BaseLLMHTTPHandler: """ Forward POST /v1/realtime/client_secrets to upstream provider. + Uses provider_config (BaseRealtimeHTTPConfig) for URL construction and + header auth when available; falls back to the legacy OpenAI-style defaults. + """ + return await self._async_realtime_session_post( + endpoint="client_secrets", + api_base=api_base, + api_key=api_key, + request_data=request_data, + logging_obj=logging_obj, + timeout=timeout, + provider_config=provider_config, + model=model, + extra_headers=extra_headers, + client=client, + api_version=api_version, + ) + + async def async_realtime_transcription_session_handler( + self, + api_base: str, + api_key: str, + request_data: Dict[str, Any], + logging_obj: LiteLLMLoggingObj, + timeout: Union[float, httpx.Timeout], + provider_config: Optional[Any] = None, + model: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + api_version: Optional[str] = None, + ) -> httpx.Response: + """Forward POST /v1/realtime/transcription_sessions to upstream provider.""" + return await self._async_realtime_session_post( + endpoint="transcription_sessions", + api_base=api_base, + api_key=api_key, + request_data=request_data, + logging_obj=logging_obj, + timeout=timeout, + provider_config=provider_config, + model=model, + extra_headers=extra_headers, + client=client, + api_version=api_version, + ) + + async def _async_realtime_session_post( + self, + endpoint: Literal["client_secrets", "transcription_sessions"], + api_base: str, + api_key: str, + request_data: Dict[str, Any], + logging_obj: LiteLLMLoggingObj, + timeout: Union[float, httpx.Timeout], + provider_config: Optional[Any] = None, + model: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + api_version: Optional[str] = None, + ) -> httpx.Response: + """ + Shared POST flow for the realtime HTTP session endpoints + (client_secrets and transcription_sessions). + Uses provider_config (BaseRealtimeHTTPConfig) for URL construction and header auth when available; falls back to the legacy OpenAI-style defaults. """ @@ -5389,14 +5539,19 @@ class BaseLLMHTTPHandler: async_httpx_client = client if provider_config is not None: - url = provider_config.get_complete_url( - api_base=api_base, model=model or "", api_version=api_version - ) + if endpoint == "transcription_sessions": + url = provider_config.get_transcription_session_url( + api_base=api_base, model=model or "", api_version=api_version + ) + else: + url = provider_config.get_complete_url( + api_base=api_base, model=model or "", api_version=api_version + ) headers: Dict[str, Any] = provider_config.validate_environment( headers={}, model=model or "", api_key=api_key ) else: - url = f"{api_base.rstrip('/')}/v1/realtime/client_secrets" + url = f"{api_base.rstrip('/')}/v1/realtime/{endpoint}" headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", @@ -5516,7 +5671,7 @@ class BaseLLMHTTPHandler: ) raise - async def async_responses_websocket( + async def async_responses_websocket( # noqa: PLR0915 self, model: str, websocket: Any, @@ -5569,7 +5724,11 @@ class BaseLLMHTTPHandler: import websockets from websockets.asyncio.client import ClientConnection - litellm_params = GenericLiteLLMParams() + litellm_params = GenericLiteLLMParams( + api_base=api_base, + api_key=api_key, + **kwargs, + ) headers = responses_api_provider_config.validate_environment( headers={}, model=model, @@ -5578,21 +5737,21 @@ class BaseLLMHTTPHandler: if api_key: headers["Authorization"] = f"Bearer {api_key}" - http_url = responses_api_provider_config.get_complete_url( + ws_url = responses_api_provider_config.get_websocket_url( api_base=api_base, - litellm_params={}, + litellm_params=dict(litellm_params), ) - ws_url = http_url.replace("https://", "wss://").replace("http://", "ws://") - # OpenAI's WebSocket responses endpoint requires ?model= in the URL, - # matching the Realtime API convention (wss://.../v1/realtime?model=...). - # Use urllib.parse so existing query params (e.g. api-version) are preserved. - _parsed = urlparse(ws_url) - _qs = parse_qs(_parsed.query) - if "model" not in _qs: - _qs["model"] = [model] - ws_url = urlunparse( - _parsed._replace(query=urlencode({k: v[0] for k, v in _qs.items()})) - ) + # Some providers (e.g. OpenAI) require ?model= in the WebSocket URL. + # Providers that send the model in the request body (e.g. Azure) set + # model_in_websocket_url() to False to suppress this append. + if responses_api_provider_config.model_in_websocket_url(): + _parsed = urlparse(ws_url) + _qs = parse_qs(_parsed.query) + if "model" not in _qs: + _qs["model"] = [model] + ws_url = urlunparse( + _parsed._replace(query=urlencode({k: v[0] for k, v in _qs.items()})) + ) try: ssl_context = get_shared_realtime_ssl_context() @@ -5620,6 +5779,41 @@ class BaseLLMHTTPHandler: _request_data: Dict[str, Any] = {} if litellm_metadata: _request_data["litellm_metadata"] = litellm_metadata + + _ws_guardrail_callbacks: list = [] + _ws_output_guardrail_callbacks: list = [] + try: + import litellm as _litellm + + # Use duck-typing so any guardrail that exposes the PII + # masking interface works, not just _OPTIONAL_PresidioPIIMasking. + # This avoids a layering violation (SDK importing from proxy). + _ws_guardrail_callbacks = [ + cb + for cb in _litellm.callbacks + if callable(getattr(cb, "check_pii", None)) + and callable( + getattr(cb, "get_presidio_settings_from_request_data", None) + ) + and callable(getattr(cb, "_unmask_pii_text", None)) + and getattr(cb, "output_parse_pii", False) + ] + _ws_output_guardrail_callbacks = [ + cb + for cb in _litellm.callbacks + if callable(getattr(cb, "check_pii", None)) + and callable( + getattr(cb, "get_presidio_settings_from_request_data", None) + ) + and getattr(cb, "apply_to_output", False) + ] + except Exception as _guardrail_exc: + verbose_logger.warning( + "Responses WebSocket: failed to collect guardrail " + "callbacks — PII masking will be skipped. Error: %s", + _guardrail_exc, + ) + streaming = ResponsesWebSocketStreaming( websocket=websocket, backend_ws=cast(ClientConnection, backend_ws), @@ -5627,6 +5821,9 @@ class BaseLLMHTTPHandler: user_api_key_dict=user_api_key_dict, request_data=_request_data, first_message=first_message, + guardrail_callbacks=_ws_guardrail_callbacks, + output_guardrail_callbacks=_ws_output_guardrail_callbacks, + authorized_model=model, ) await streaming.bidirectional_forward() diff --git a/litellm/llms/databricks/streaming_utils.py b/litellm/llms/databricks/streaming_utils.py index eebe3182881..7a7330227d6 100644 --- a/litellm/llms/databricks/streaming_utils.py +++ b/litellm/llms/databricks/streaming_utils.py @@ -25,6 +25,28 @@ class ModelResponseIterator: finish_reason = "" usage: Optional[ChatCompletionUsageBlock] = None + # Usage-only final chunk (OpenAI ``stream_options.include_usage``) + # arrives with an empty ``choices`` list — return usage without + # indexing ``choices[0]``. + if len(processed_chunk.choices) == 0: + final_usage = getattr(processed_chunk, "usage", None) + return GenericStreamingChunk( + text="", + tool_use=None, + is_finished=False, + finish_reason="", + usage=( + ChatCompletionUsageBlock( + prompt_tokens=final_usage.prompt_tokens or 0, + completion_tokens=final_usage.completion_tokens or 0, + total_tokens=final_usage.total_tokens or 0, + ) + if final_usage is not None + else None + ), + index=0, + ) + if processed_chunk.choices[0].delta.content is not None: # type: ignore text = processed_chunk.choices[0].delta.content # type: ignore diff --git a/litellm/llms/deepseek/messages/transformation.py b/litellm/llms/deepseek/messages/transformation.py index ad60478960e..63b736ffd1d 100644 --- a/litellm/llms/deepseek/messages/transformation.py +++ b/litellm/llms/deepseek/messages/transformation.py @@ -26,6 +26,9 @@ class DeepSeekAnthropicMessagesConfig(AnthropicMessagesConfig): def custom_llm_provider(self) -> Optional[str]: return "deepseek" + def should_strip_billing_metadata(self) -> bool: + return True + @staticmethod def get_api_key(api_key: Optional[str] = None) -> Optional[str]: return api_key or get_secret_str("DEEPSEEK_API_KEY") or litellm.api_key diff --git a/litellm/llms/fal_ai/image_generation/__init__.py b/litellm/llms/fal_ai/image_generation/__init__.py index 9deeb403c46..7f3358934a7 100644 --- a/litellm/llms/fal_ai/image_generation/__init__.py +++ b/litellm/llms/fal_ai/image_generation/__init__.py @@ -7,6 +7,7 @@ from .flux_pro_v11_transformation import FalAIFluxProV11Config from .flux_pro_v11_ultra_transformation import FalAIFluxProV11UltraConfig from .flux_schnell_transformation import FalAIFluxSchnellConfig from .imagen4_transformation import FalAIImagen4Config +from .nano_banana_transformation import FalAINanoBananaConfig from .recraft_v3_transformation import FalAIRecraftV3Config from .ideogram_v3_transformation import FalAIIdeogramV3Config from .stable_diffusion_transformation import FalAIStableDiffusionConfig @@ -20,6 +21,7 @@ __all__ = [ "FalAIBaseConfig", "FalAIImageGenerationConfig", "FalAIImagen4Config", + "FalAINanoBananaConfig", "FalAIRecraftV3Config", "FalAIBriaConfig", "FalAIFluxProV11Config", @@ -45,7 +47,9 @@ def get_fal_ai_image_generation_config(model: str) -> BaseImageGenerationConfig: model_lower = model.lower() # Map model names to their corresponding configuration classes - if "imagen4" in model_lower or "imagen-4" in model_lower: + if "nano-banana" in model_lower or "gemini-25-flash-image" in model_lower: + return FalAINanoBananaConfig() + elif "imagen4" in model_lower or "imagen-4" in model_lower: return FalAIImagen4Config() elif "recraft" in model_lower: return FalAIRecraftV3Config() diff --git a/litellm/llms/fal_ai/image_generation/nano_banana_transformation.py b/litellm/llms/fal_ai/image_generation/nano_banana_transformation.py new file mode 100644 index 00000000000..dd4758055ac --- /dev/null +++ b/litellm/llms/fal_ai/image_generation/nano_banana_transformation.py @@ -0,0 +1,105 @@ +from typing import List, Optional + +from litellm.secret_managers.main import get_secret_str +from litellm.types.llms.openai import OpenAIImageGenerationOptionalParams + +from .transformation import FalAIBaseConfig + + +class FalAINanoBananaConfig(FalAIBaseConfig): + """ + Configuration for Fal AI's Nano Banana / Gemini 2.5 Flash Image models. + + Serves the imagen4 deprecation migration path. The same underlying model is + exposed under two endpoints that share an identical schema: + - fal-ai/nano-banana + - fal-ai/gemini-25-flash-image + + Documentation: https://fal.ai/models/fal-ai/nano-banana + """ + + SUPPORTED_ASPECT_RATIOS: List[str] = [ + "21:9", + "16:9", + "3:2", + "4:3", + "5:4", + "1:1", + "4:5", + "3:4", + "2:3", + "9:16", + ] + + def get_complete_url( + self, + api_base: Optional[str], + api_key: Optional[str], + model: str, + optional_params: dict, + litellm_params: dict, + stream: Optional[bool] = None, + ) -> str: + base_url: str = ( + api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL + ).rstrip("/") + endpoint = model if model.startswith("fal-ai/") else f"fal-ai/{model}" + return f"{base_url}/{endpoint}" + + def get_supported_openai_params( + self, model: str + ) -> List[OpenAIImageGenerationOptionalParams]: + return ["n", "response_format", "size"] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + supported_params = self.get_supported_openai_params(model) + for key, value in non_default_params.items(): + if key == "response_format": + continue + elif key == "n": + if "num_images" not in optional_params: + optional_params["num_images"] = value + elif key == "size": + if "aspect_ratio" not in optional_params: + optional_params["aspect_ratio"] = self._map_aspect_ratio(value) + elif key not in optional_params and not drop_params: + raise ValueError( + f"Parameter {key} is not supported for model {model}. " + f"Supported parameters are {supported_params}. " + "Set drop_params=True to drop unsupported parameters." + ) + return optional_params + + def _map_aspect_ratio(self, size: str) -> str: + if not isinstance(size, str) or "x" not in size: + return "1:1" + try: + width, height = (int(part) for part in size.split("x")) + target = width / height + except (ValueError, ZeroDivisionError): + return "1:1" + + def ratio_of(aspect_ratio: str) -> float: + w, h = (int(part) for part in aspect_ratio.split(":")) + return w / h + + return min( + self.SUPPORTED_ASPECT_RATIOS, + key=lambda aspect_ratio: abs(ratio_of(aspect_ratio) - target), + ) + + def transform_image_generation_request( + self, + model: str, + prompt: str, + optional_params: dict, + litellm_params: dict, + headers: dict, + ) -> dict: + return {"prompt": prompt, **optional_params} diff --git a/litellm/llms/fireworks_ai/chat/transformation.py b/litellm/llms/fireworks_ai/chat/transformation.py index 9e9d300b585..cca3b3da37a 100644 --- a/litellm/llms/fireworks_ai/chat/transformation.py +++ b/litellm/llms/fireworks_ai/chat/transformation.py @@ -170,11 +170,6 @@ class FireworksAIConfig(OpenAIGPTConfig): is_response_format_supported=False, enforce_tool_choice=False, # tools and response_format are both set, don't enforce tool_choice ) - elif "json_schema" in value: - optional_params["response_format"] = { - "type": "json_object", - "schema": value["json_schema"]["schema"], - } else: optional_params["response_format"] = value elif param == "max_completion_tokens": diff --git a/litellm/llms/gemini/common_utils.py b/litellm/llms/gemini/common_utils.py index 42a807983b9..4cca2e2b850 100644 --- a/litellm/llms/gemini/common_utils.py +++ b/litellm/llms/gemini/common_utils.py @@ -174,12 +174,110 @@ def map_openai_image_params_to_gemini( mapped_params["imageConfig"] = image_config_param for key, value in filtered_params.items(): - if key not in ("n", "size", "imageConfig") and key not in optional_params: + if ( + key not in ("n", "size", "imageConfig", "tools", "web_search_options") + and key not in optional_params + ): mapped_params[key] = value return mapped_params +def _dedupe_gemini_search_tools(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( + VertexGeminiConfig, + ) + + search_tool_keys = VertexGeminiConfig._search_tool_keys() + seen_search_keys: set[str] = set() + deduped_tools: List[Dict[str, Any]] = [] + + for tool in tools: + if not isinstance(tool, dict): + deduped_tools.append(tool) + continue + + search_key = next((key for key in search_tool_keys if key in tool), None) + if search_key is None: + deduped_tools.append(tool) + continue + + if search_key in seen_search_keys: + continue + + seen_search_keys.add(search_key) + deduped_tools.append(tool) + + return deduped_tools + + +def _has_gemini_search_tool(tools: List[Any]) -> bool: + from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( + VertexGeminiConfig, + ) + + search_tool_keys = VertexGeminiConfig._search_tool_keys() + return any( + isinstance(tool, dict) and any(key in tool for key in search_tool_keys) + for tool in tools + ) + + +def map_gemini_image_tools_params( + non_default_params: Dict[str, Any], + mapped_params: Dict[str, Any], +) -> Dict[str, Any]: + from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( + VertexGeminiConfig, + ) + + gemini_config = VertexGeminiConfig() + result = dict(mapped_params) + result.pop("web_search_options", None) + + tools_value = non_default_params.get("tools") + if isinstance(tools_value, list) and tools_value: + mapped_tools = gemini_config._map_function( + value=tools_value, optional_params=result + ) + result = gemini_config._add_tools_to_optional_params(result, mapped_tools) + + web_search_options = non_default_params.get("web_search_options") + existing_tools = result.get("tools") + if isinstance(web_search_options, dict) and not ( + isinstance(existing_tools, list) and _has_gemini_search_tool(existing_tools) + ): + search_tool = gemini_config._map_web_search_options(web_search_options) + result = gemini_config._add_tools_to_optional_params(result, [search_tool]) + + gemini_config._drop_search_tools_mixed_with_functions(result) + + if isinstance(result.get("tools"), list): + result["tools"] = _dedupe_gemini_search_tools(result["tools"]) + + return result + + +def get_gemini_image_web_search_requests( + response_data: Dict[str, Any], +) -> Optional[int]: + from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( + VertexGeminiConfig, + ) + + grounding_metadata: List[Dict[str, Any]] = [] + for candidate in response_data.get("candidates", []): + if not isinstance(candidate, dict): + continue + candidate_grounding = candidate.get("groundingMetadata") + if isinstance(candidate_grounding, list): + grounding_metadata.extend(candidate_grounding) + elif isinstance(candidate_grounding, dict): + grounding_metadata.append(candidate_grounding) + + return VertexGeminiConfig._calculate_web_search_requests(grounding_metadata) + + def get_gemini_image_generation_config( model: str, optional_params: Dict[str, Any], diff --git a/litellm/llms/gemini/image_generation/cost_calculator.py b/litellm/llms/gemini/image_generation/cost_calculator.py index 3c8e69374af..380e2c21e9e 100644 --- a/litellm/llms/gemini/image_generation/cost_calculator.py +++ b/litellm/llms/gemini/image_generation/cost_calculator.py @@ -7,6 +7,7 @@ from typing import Any import litellm from litellm.litellm_core_utils.llm_cost_calc.utils import ( calculate_image_response_cost_from_usage, + calculate_image_response_web_search_cost, ) from litellm.types.utils import ImageResponse @@ -23,22 +24,25 @@ def cost_calculator( custom_llm_provider="gemini", ) - if isinstance(image_response, ImageResponse): - token_based_cost = calculate_image_response_cost_from_usage( - model=model, - image_response=image_response, - custom_llm_provider="gemini", - ) - if token_based_cost is not None: - return token_based_cost - - output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0 - num_images: int = 0 - if isinstance(image_response, ImageResponse): - if image_response.data: - num_images = len(image_response.data) - return output_cost_per_image * num_images - else: + if not isinstance(image_response, ImageResponse): raise ValueError( f"image_response must be of type ImageResponse got type={type(image_response)}" ) + + web_search_cost = calculate_image_response_web_search_cost( + image_response=image_response, + custom_llm_provider="gemini", + model_info=_model_info, + ) + + token_based_cost = calculate_image_response_cost_from_usage( + model=model, + image_response=image_response, + custom_llm_provider="gemini", + ) + if token_based_cost is not None: + return token_based_cost + web_search_cost + + output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0 + num_images: int = len(image_response.data) if image_response.data else 0 + return output_cost_per_image * num_images + web_search_cost diff --git a/litellm/llms/gemini/image_generation/transformation.py b/litellm/llms/gemini/image_generation/transformation.py index e6770a76bcb..ebfb0d68830 100644 --- a/litellm/llms/gemini/image_generation/transformation.py +++ b/litellm/llms/gemini/image_generation/transformation.py @@ -7,7 +7,9 @@ from litellm.llms.base_llm.image_generation.transformation import ( ) from litellm.llms.gemini.common_utils import ( get_gemini_image_generation_config, + get_gemini_image_web_search_requests, is_gemini_image_model, + map_gemini_image_tools_params, map_openai_image_params_to_gemini, ) from litellm.llms.gemini.image_usage_transformation import ( @@ -41,7 +43,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): """ supported_params = ["n", "size"] if is_gemini_image_model(model): - supported_params.append("imageConfig") + supported_params.extend(["imageConfig", "tools", "web_search_options"]) return supported_params # type: ignore[return-value] def map_openai_params( @@ -51,12 +53,17 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): model: str, drop_params: bool, ) -> dict: - return map_openai_image_params_to_gemini( + mapped_params = map_openai_image_params_to_gemini( params=non_default_params, model=model, supported_params=self.get_supported_openai_params(model), optional_params=optional_params, ) + if is_gemini_image_model(model): + mapped_params = map_gemini_image_tools_params( + non_default_params, mapped_params + ) + return mapped_params def get_complete_url( self, @@ -140,6 +147,10 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): optional_params=optional_params, ), } + if tools := optional_params.get("tools"): + request_body["tools"] = tools + if tool_config := optional_params.get("toolConfig"): + request_body["toolConfig"] = tool_config return request_body else: # For other Imagen models, use the original Imagen format @@ -217,6 +228,11 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): model_response.usage = transform_gemini_image_usage( response_data["usageMetadata"] ) + web_search_requests = get_gemini_image_web_search_requests(response_data) + if web_search_requests and model_response.usage is not None: + setattr( + model_response.usage, "web_search_requests", web_search_requests + ) else: # Original Imagen format - predictions with generated images predictions = response_data.get("predictions", []) diff --git a/litellm/llms/gemini/realtime/transformation.py b/litellm/llms/gemini/realtime/transformation.py index 212287fb7f8..51fa395d899 100644 --- a/litellm/llms/gemini/realtime/transformation.py +++ b/litellm/llms/gemini/realtime/transformation.py @@ -195,13 +195,48 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): def get_audio_mime_type(self, input_audio_format: str = "pcm16"): mime_types = { - "pcm16": "audio/pcm", + "pcm16": "audio/pcm;rate=24000", "g711_ulaw": "audio/pcmu", "g711_alaw": "audio/pcma", } return mime_types.get(input_audio_format, "application/octet-stream") + def _manual_turn_detection_enabled( + self, session_configuration_request: Optional[str] + ) -> bool: + if not session_configuration_request: + return False + try: + setup = json.loads(session_configuration_request).get("setup", {}) + automatic_detection = setup.get("realtimeInputConfig", {}).get( + "automaticActivityDetection", {} + ) + return ( + isinstance(automatic_detection, dict) + and automatic_detection.get("disabled") is True + ) + except (json.JSONDecodeError, TypeError, AttributeError): + return False + + def _handle_input_audio_buffer_commit_or_end( + self, session_configuration_request: Optional[str] + ) -> List[str]: + """Map OpenAI buffer commit/end to Gemini Live turn-boundary signals.""" + if self._manual_turn_detection_enabled(session_configuration_request): + realtime_input_dict: BidiGenerateContentRealtimeInput = { + "activityEnd": True, + } + verbose_logger.debug( + "Gemini Realtime: Sending activityEnd realtimeInput to backend" + ) + else: + realtime_input_dict = {"audioStreamEnd": True} + verbose_logger.debug( + "Gemini Realtime: Sending audioStreamEnd realtimeInput to backend" + ) + return [json.dumps({"realtimeInput": realtime_input_dict})] + def map_automatic_turn_detection( self, value: OpenAIRealtimeTurnDetection ) -> AutomaticActivityDetection: @@ -656,6 +691,19 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): ) messages.append(gemini_msg) return messages + + if msg_type in ("input_audio_buffer.commit", "input_audio_buffer.end"): + return self._handle_input_audio_buffer_commit_or_end( + session_configuration_request + ) + + if msg_type == "input_audio_buffer.clear": + # Local OpenAI buffer op — nothing to forward to Gemini Live. + verbose_logger.debug( + "Gemini Realtime: input_audio_buffer.clear is a local buffer op" + ) + return [] + # Unknown/unsupported OpenAI event type — drop silently rather than # forwarding raw JSON as text input to the model. return [] diff --git a/litellm/llms/gemini/videos/transformation.py b/litellm/llms/gemini/videos/transformation.py index 77a95bfa5ab..644e96a7dd1 100644 --- a/litellm/llms/gemini/videos/transformation.py +++ b/litellm/llms/gemini/videos/transformation.py @@ -265,7 +265,11 @@ class GeminiVideoConfig(BaseVideoConfig): { "instances": [ { - "prompt": "A cat playing with a ball of yarn" + "prompt": "A cat playing with a ball of yarn", + "image": { + "bytesBase64Encoded": "...", + "mimeType": "image/jpeg" + } } ], "parameters": { @@ -275,13 +279,18 @@ class GeminiVideoConfig(BaseVideoConfig): } } """ - instance = GeminiVideoGenerationInstance(prompt=prompt) + instance: GeminiVideoGenerationInstance = {"prompt": prompt} params_copy = video_create_optional_request_params.copy() - if "image" in params_copy and params_copy["image"] is not None: - image_data = _convert_image_to_gemini_format(params_copy["image"]) - params_copy["image"] = image_data + if "image" in params_copy: + image = params_copy.pop("image") + if image is not None: + if isinstance(image, dict): + image_data = image + else: + image_data = _convert_image_to_gemini_format(image) + instance["image"] = image_data parameters = GeminiVideoGenerationParameters(**params_copy) diff --git a/litellm/llms/github_copilot/responses/transformation.py b/litellm/llms/github_copilot/responses/transformation.py index 0929f95cf43..299f346a7eb 100644 --- a/litellm/llms/github_copilot/responses/transformation.py +++ b/litellm/llms/github_copilot/responses/transformation.py @@ -2,7 +2,7 @@ GitHub Copilot Responses API Configuration. This module provides the configuration for GitHub Copilot's Responses API, -which is required for models like gpt-5.1-codex that only support the /responses endpoint. +which is required for models like gpt-5.3-codex that only support the /responses endpoint. Implementation based on analysis of the copilot-api project by caozhiyuan: https://github.com/caozhiyuan/copilot-api @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional, Union import os +import litellm from litellm._logging import verbose_logger from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH from litellm.exceptions import AuthenticationError @@ -22,6 +23,7 @@ from litellm.types.llms.openai import ( ) from litellm.types.router import GenericLiteLLMParams from litellm.types.utils import LlmProviders +from litellm.utils import _cached_get_model_info_helper from ..authenticator import Authenticator from ..common_utils import ( @@ -38,6 +40,47 @@ else: LiteLLMLoggingObj = Any +def github_copilot_supports_responses_api(model: str) -> bool: + """ + Gate native /v1/responses dispatch per github_copilot model. + + Resolution (first match wins): mode "responses" -> True; mode "chat" -> + False (opt-out wins for dual-endpoint models); "/v1/responses" in + supported_endpoints -> True; else False. Unknown model -> False (the bridge + always works since every Copilot model supports /chat/completions). + + Reads merged model info (per-deployment model_info applied via the router's + register_model, which also clears the cache used here). + """ + try: + info = _cached_get_model_info_helper( + model=model, custom_llm_provider="github_copilot" + ) + except Exception as e: + verbose_logger.debug( + "github_copilot_supports_responses_api: get_model_info failed " + "for %s: %s", + model, + e, + ) + return False + + mode = info.get("mode") + if mode == "responses": + return True + if mode == "chat": + return False + + # supported_endpoints is dropped by ModelInfoBase; read it from the raw + # model_cost entry via the resolved key. + key = info.get("key") + raw_info = litellm.model_cost.get(key) if isinstance(key, str) else None + endpoints = ( + raw_info.get("supported_endpoints") if isinstance(raw_info, dict) else None + ) + return isinstance(endpoints, list) and "/v1/responses" in endpoints + + class GithubCopilotResponsesAPIConfig(OpenAIResponsesAPIConfig): """ Configuration for GitHub Copilot's Responses API. @@ -58,6 +101,7 @@ class GithubCopilotResponsesAPIConfig(OpenAIResponsesAPIConfig): def __init__(self) -> None: super().__init__() self.authenticator = Authenticator() + self._stream_item_ids_by_output_index: Dict[int, str] = {} @property def custom_llm_provider(self) -> LlmProviders: @@ -86,6 +130,61 @@ class GithubCopilotResponsesAPIConfig(OpenAIResponsesAPIConfig): """ return dict(response_api_optional_params) + def transform_streaming_response( + self, + model: str, + parsed_chunk: dict, + logging_obj: LiteLLMLoggingObj, + ) -> Any: + parsed_chunk = self._normalize_stream_item_id(parsed_chunk) + return super().transform_streaming_response( + model=model, + parsed_chunk=parsed_chunk, + logging_obj=logging_obj, + ) + + def _normalize_stream_item_id(self, parsed_chunk: dict) -> dict: + """Rewrite streamed item ids to one stable id per output_index. + + GitHub Copilot tags each event of a single output item with a different + item id, so clients that key streaming state by item id (e.g. the Vercel + AI SDK) crash with "reasoning part not found" / "text part not + found". Every sub-event carries a top-level ``item_id`` (whatever the + item type), so its presence is the rewrite signal; output_item.added / + .done instead nest the id under ``item``. The anchor is keyed by + output_index and taken from output_item.added, which the protocol always + emits first, so it is written before any sub-event reads it. Copilot + accepts that id paired with the final encrypted_content next turn, so + multi-turn replay is unaffected. + + State is keyed by output_index on this config, which + ProviderConfigManager builds fresh per request, so it is stream-scoped. + """ + output_index = parsed_chunk.get("output_index") + if not isinstance(output_index, int): + return parsed_chunk + + if parsed_chunk.get("type") == "response.output_item.added": + item = parsed_chunk.get("item") + if isinstance(item, dict) and isinstance(item.get("id"), str): + self._stream_item_ids_by_output_index[output_index] = item["id"] + return parsed_chunk + + stable_id = self._stream_item_ids_by_output_index.get(output_index) + if stable_id is None: + return parsed_chunk + + if isinstance(parsed_chunk.get("item_id"), str): + parsed_chunk = dict(parsed_chunk) + parsed_chunk["item_id"] = stable_id + elif parsed_chunk.get("type") == "response.output_item.done": + item = parsed_chunk.get("item") + if isinstance(item, dict): + parsed_chunk = dict(parsed_chunk) + parsed_chunk["item"] = {**item, "id": stable_id} + + return parsed_chunk + def validate_environment( self, headers: dict, diff --git a/litellm/llms/huggingface/embedding/handler.py b/litellm/llms/huggingface/embedding/handler.py index 226f6b2ebad..6be885b1f91 100644 --- a/litellm/llms/huggingface/embedding/handler.py +++ b/litellm/llms/huggingface/embedding/handler.py @@ -239,7 +239,7 @@ class HuggingFaceEmbedding(BaseLLM): model_response.model = model input_tokens = 0 for text in input: - input_tokens += len(encoding.encode(text)) + input_tokens += len(encoding.encode(text, disallowed_special=())) setattr( model_response, diff --git a/litellm/llms/litellm_proxy/skills/README.md b/litellm/llms/litellm_proxy/skills/README.md index 1dfeff1a42c..a896aa1166e 100644 --- a/litellm/llms/litellm_proxy/skills/README.md +++ b/litellm/llms/litellm_proxy/skills/README.md @@ -18,7 +18,7 @@ flowchart TB F[Request with container.skills] --> G[SkillsInjectionHook] G --> H{skill_id prefix?} - H -->|"litellm:skill_abc"| I[Fetch from LiteLLM DB] + H -->|"litellm_skill_abc"| I[Fetch from LiteLLM DB] H -->|"skill_xyz" no prefix| J[Pass to Anthropic as native skill] I --> K{Model provider?} @@ -57,7 +57,7 @@ sequenceDiagram Note over LiteLLM,PreHook: PRE-CALL HOOK LiteLLM->>PreHook: Intercept request - PreHook->>PreHook: Fetch skill from DB (litellm:skill_id) + PreHook->>PreHook: Fetch skill from DB (litellm_skill_id) PreHook->>PreHook: Extract SKILL.md from ZIP PreHook->>PreHook: Inject SKILL.md into system prompt PreHook->>PreHook: Add litellm_code_execution tool @@ -105,7 +105,7 @@ response = await litellm.acompletion( model="gpt-4o-mini", messages=[{"role": "user", "content": "Create a bouncing ball GIF"}], container={ - "skills": [{"type": "custom", "skill_id": "litellm:skill_abc123"}] + "skills": [{"type": "custom", "skill_id": "litellm_skill_abc123"}] }, ) @@ -261,7 +261,7 @@ response = litellm.completion( messages=[{"role": "user", "content": "Analyze this data..."}], container={ "skills": [ - {"type": "custom", "skill_id": "litellm:skill_abc123"} # litellm: prefix + {"type": "custom", "skill_id": "litellm_skill_abc123"} # litellm_skill_ prefix ] } ) @@ -277,7 +277,7 @@ response = litellm.completion( "messages": [{"role": "user", "content": "Help me analyze data"}], "container": { "skills": [ - {"type": "custom", "skill_id": "litellm:skill_abc123"} + {"type": "custom", "skill_id": "litellm_skill_abc123"} ] } } @@ -287,7 +287,7 @@ response = litellm.completion( The hook (`litellm/proxy/hooks/litellm_skills/main.py`) intercepts the request: -1. **Detects `litellm:` prefix** → Fetches skill from database +1. **Detects `litellm_skill_` prefix** → Fetches skill from database 2. **Checks model provider** → Bedrock is not Anthropic 3. **Extracts SKILL.md** from stored ZIP file 4. **Converts skill to tool** + **Injects content into system prompt** @@ -361,8 +361,8 @@ model LiteLLM_SkillsTable { | Create skill on Anthropic | `anthropic` | N/A | Forward to Anthropic API | | Create skill in LiteLLM DB | `litellm_proxy` | N/A | Store in database | | Use Anthropic native skill | N/A | `skill_xyz` | Pass to Anthropic container.skills | -| Use LiteLLM skill on Anthropic | N/A | `litellm:skill_abc` | Convert to tools | -| Use LiteLLM skill on Bedrock/OpenAI | N/A | `litellm:skill_abc` | Convert to tools + inject SKILL.md | +| Use LiteLLM skill on Anthropic | N/A | `litellm_skill_abc` | Convert to tools | +| Use LiteLLM skill on Bedrock/OpenAI | N/A | `litellm_skill_abc` | Convert to tools + inject SKILL.md | ## Testing diff --git a/litellm/llms/litellm_proxy/skills/constants.py b/litellm/llms/litellm_proxy/skills/constants.py index a8c2697fcee..0c60a60842a 100644 --- a/litellm/llms/litellm_proxy/skills/constants.py +++ b/litellm/llms/litellm_proxy/skills/constants.py @@ -4,6 +4,10 @@ Constants for LiteLLM Skills Centralized constants for skills processing, code execution, and sandbox configuration. """ +LITELLM_SKILL_ID_PREFIX: str = "litellm_skill_" +"""Prefix for DB-backed skill IDs. The model-facing tool name is the skill ID +with hyphens/spaces replaced by underscores, which leaves this prefix intact.""" + # Code execution loop settings DEFAULT_MAX_ITERATIONS: int = 10 """Maximum number of iterations for the automatic code execution loop.""" diff --git a/litellm/llms/litellm_proxy/skills/handler.py b/litellm/llms/litellm_proxy/skills/handler.py index 37aabd8b477..9138b9a712f 100644 --- a/litellm/llms/litellm_proxy/skills/handler.py +++ b/litellm/llms/litellm_proxy/skills/handler.py @@ -10,6 +10,7 @@ from typing import Any, Dict, List, Optional from litellm._logging import verbose_logger from litellm.caching.in_memory_cache import InMemoryCache +from litellm.llms.litellm_proxy.skills.constants import LITELLM_SKILL_ID_PREFIX from litellm.proxy._types import LiteLLM_SkillsTable, NewSkillRequest, UserAPIKeyAuth from litellm.proxy.common_utils.resource_ownership import ( get_primary_resource_owner_scope, @@ -17,6 +18,7 @@ from litellm.proxy.common_utils.resource_ownership import ( is_proxy_admin, user_can_access_resource_owner, ) +from litellm.repositories.table_repositories import SkillsRepository # Skills are looked up on every chat completion that has skills enabled # (`SkillsInjectionHook` calls ``fetch_skill_from_db``). 60s LRU/TTL cache @@ -67,7 +69,7 @@ class LiteLLMSkillsHandler: ) -> LiteLLM_SkillsTable: prisma_client = await LiteLLMSkillsHandler._get_prisma_client() - skill_id = f"litellm_skill_{uuid.uuid4()}" + skill_id = f"{LITELLM_SKILL_ID_PREFIX}{uuid.uuid4()}" owner = get_primary_resource_owner_scope(user_api_key_dict) or user_id if owner is None: # Identity-less callers (no user_id / team_id / org_id / @@ -107,7 +109,7 @@ class LiteLLMSkillsHandler: f"LiteLLMSkillsHandler: Creating skill {skill_id} with title={data.display_title}" ) - new_skill = await prisma_client.db.litellm_skillstable.create(data=skill_data) + new_skill = await SkillsRepository(prisma_client).table.create(data=skill_data) return _prisma_skill_to_litellm(new_skill) @staticmethod @@ -133,7 +135,7 @@ class LiteLLMSkillsHandler: return [] find_many_kwargs["where"] = {"created_by": {"in": owner_scopes}} - skills = await prisma_client.db.litellm_skillstable.find_many( + skills = await SkillsRepository(prisma_client).table.find_many( **find_many_kwargs ) return [_prisma_skill_to_litellm(s) for s in skills] @@ -150,7 +152,7 @@ class LiteLLMSkillsHandler: return cached prisma_client = await LiteLLMSkillsHandler._get_prisma_client() - skill = await prisma_client.db.litellm_skillstable.find_unique( + skill = await SkillsRepository(prisma_client).table.find_unique( where={"skill_id": skill_id} ) _SKILL_CACHE.set_cache( @@ -189,7 +191,7 @@ class LiteLLMSkillsHandler: ): raise ValueError(f"Skill not found: {skill_id}") - await prisma_client.db.litellm_skillstable.delete(where={"skill_id": skill_id}) + await SkillsRepository(prisma_client).table.delete(where={"skill_id": skill_id}) _SKILL_CACHE.set_cache(skill_id, _NEGATIVE_SKILL_SENTINEL) return {"id": skill_id, "type": "skill_deleted"} diff --git a/litellm/llms/minimax/messages/transformation.py b/litellm/llms/minimax/messages/transformation.py index 3190a5f5412..57cfcbf0621 100644 --- a/litellm/llms/minimax/messages/transformation.py +++ b/litellm/llms/minimax/messages/transformation.py @@ -28,6 +28,9 @@ class MinimaxMessagesConfig(AnthropicMessagesConfig): def custom_llm_provider(self) -> Optional[str]: return "minimax" + def should_strip_billing_metadata(self) -> bool: + return True + @staticmethod def get_api_key(api_key: Optional[str] = None) -> Optional[str]: """ diff --git a/litellm/llms/moonshot/chat/transformation.py b/litellm/llms/moonshot/chat/transformation.py index 4eb00fd81d6..da8687bce72 100644 --- a/litellm/llms/moonshot/chat/transformation.py +++ b/litellm/llms/moonshot/chat/transformation.py @@ -134,11 +134,15 @@ class MoonshotChatConfig(OpenAIGPTConfig): ########################################## # temperature limitations - # 1. `temperature` on KIMI API is [0, 1] but OpenAI is [0, 2] - # 2. If temperature < 0.3 and n > 1, KIMI will raise an exception. + # 1. reasoning models (kimi-k2.5, kimi-k2.6, ...) reject every temperature + # except 1, so the param is dropped and the model's default is used + # 2. `temperature` on KIMI API is [0, 1] but OpenAI is [0, 2] + # 3. If temperature < 0.3 and n > 1, KIMI will raise an exception. # If we enter this condition, we set the temperature to 0.3 as suggested by Moonshot AI ########################################## - if "temperature" in optional_params: + if supports_reasoning(model=model, custom_llm_provider="moonshot"): + optional_params.pop("temperature", None) + elif "temperature" in optional_params: if optional_params["temperature"] > 1: optional_params["temperature"] = 1 if optional_params["temperature"] < 0.3 and optional_params.get("n", 1) > 1: diff --git a/litellm/llms/oci/chat/transformation.py b/litellm/llms/oci/chat/transformation.py index f050f9eea36..d1248b6e518 100644 --- a/litellm/llms/oci/chat/transformation.py +++ b/litellm/llms/oci/chat/transformation.py @@ -25,6 +25,7 @@ from typing import ( import httpx import litellm +from litellm.constants import DEFAULT_OCI_CHAT_MAX_TOKENS from litellm.litellm_core_utils.logging_utils import track_llm_api_timing from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException from litellm.llms.custom_httpx.http_handler import ( @@ -87,15 +88,20 @@ STREAMING_TIMEOUT = 60 * 5 def _model_uses_max_completion_tokens(model: str) -> bool: """Return True for OCI-hosted models that require ``maxCompletionTokens``. - Reasoning models on OCI (e.g. the OpenAI GPT-5 family) reject ``maxTokens`` - with HTTP 400 and require ``maxCompletionTokens`` per OpenAI's reasoning-API - convention. Driven by ``supports_reasoning`` in - ``model_prices_and_context_window.json`` so new model families are picked - up via a catalog update rather than a code change. + OpenAI commercial models proxied through OCI (``openai.*``) reject + ``maxTokens`` with HTTP 400 on the reasoning families (gpt-5.x, o-series) + and accept ``maxCompletionTokens`` everywhere, so route the whole vendor + prefix to it rather than chasing each new release in + ``model_prices_and_context_window.json``. The ``openai.gpt-oss-*`` open + weights are served by OCI's own stack and keep ``maxTokens``. Any other + vendor falls back to the catalog's ``supports_reasoning`` flag. """ if not model: return False name = model[4:] if model.lower().startswith("oci/") else model + lowered = name.lower() + if lowered.startswith("openai."): + return not lowered.startswith("openai.gpt-oss") return supports_reasoning(model=name, custom_llm_provider="oci") @@ -193,19 +199,49 @@ def _normalize_response_format(selected_params: Dict, vendor: OCIVendors) -> Non rf = selected_params.get("responseFormat") if not isinstance(rf, dict) or "type" not in rf: return - rf_payload = dict(rf) - selected_params["responseFormat"] = rf_payload - response_type = rf_payload["type"] - if "json_schema" in rf_payload: - raw_schema = rf_payload.pop("json_schema") - rf_payload["jsonSchema"] = ( - dict(raw_schema) if isinstance(raw_schema, dict) else raw_schema - ) + + rf_type = str(rf["type"]).lower() + raw_schema = rf.get("json_schema") + json_schema = raw_schema if isinstance(raw_schema, dict) else None + + if rf_type == "text": + selected_params["responseFormat"] = {"type": "TEXT"} + return + if vendor == OCIVendors.COHERE: - rf_payload["type"] = response_type - else: - fmt = response_type.upper() - rf_payload["type"] = "JSON_OBJECT" if fmt == "JSON" else fmt + # OCI Cohere has no JSON_SCHEMA type; a schema rides on JSON_OBJECT. + payload: Dict[str, Any] = {"type": "JSON_OBJECT"} + if json_schema is not None and json_schema.get("schema") is not None: + payload["schema"] = json_schema["schema"] + selected_params["responseFormat"] = payload + return + + if rf_type == "json_schema": + if json_schema is None: + raise OCIError( + status_code=400, + message="response_format type 'json_schema' requires a 'json_schema' object", + ) + # OCI's ResponseJsonSchema accepts only name/description/schema/isStrict. + # OpenAI sends `strict` instead of `isStrict`; forwarding it (or any + # other extra key) makes OCI reject the whole request with HTTP 400. + oci_schema: Dict[str, Any] = {"name": json_schema.get("name") or "response"} + if json_schema.get("description") is not None: + oci_schema["description"] = json_schema["description"] + if json_schema.get("schema") is not None: + oci_schema["schema"] = json_schema["schema"] + if json_schema.get("strict") is not None: + oci_schema["isStrict"] = json_schema["strict"] + selected_params["responseFormat"] = { + "type": "JSON_SCHEMA", + "jsonSchema": oci_schema, + } + return + + fmt = rf_type.upper() + selected_params["responseFormat"] = { + "type": "JSON_OBJECT" if fmt == "JSON" else fmt + } def get_vendor_from_model(model: str) -> OCIVendors: @@ -297,6 +333,11 @@ class OCIChatConfig(BaseConfig): if get_vendor_from_model(model) == OCIVendors.COHERE else self.openai_to_oci_generic_param_map ) + # `n` is intentionally not advertised for Cohere even though n=1 is + # tolerated: Cohere has no numGenerations field, so n>1 cannot be + # honoured and advertising it would be misleading. Callers that gate on + # this list strip n=1 (a no-op, matching what map_openai_params does); + # callers that bypass it have n=1 dropped there. Both paths converge. return [key for key, value in param_map.items() if value] def map_openai_params( @@ -317,6 +358,19 @@ class OCIChatConfig(BaseConfig): for key, value in {**non_default_params, **optional_params}.items(): alias = param_map.get(key) if alias is False: + # max_retries is a litellm-level control param (litellm applies + # retries itself); it is never a generation param OCI accepts, so + # drop it silently. The litellm proxy injects it on every request, + # which otherwise 500s OCI calls unless drop_params is set. + if key == "max_retries": + continue + # n=1 (or None) is the OpenAI default: a single generation, which + # every OCI model produces anyway. Drop it silently so standard + # clients that always send n=1 (e.g. the MLflow gateway) are not + # rejected; only n>1 is genuinely unsupported on Cohere, which + # has no numGenerations field. + if key == "n" and (value is None or value == 1): + continue if drop_params or litellm.drop_params: continue raise OCIError( @@ -451,6 +505,13 @@ class OCIChatConfig(BaseConfig): elif oci_alias in optional_params: selected_params[target] = optional_params[oci_alias] # type: ignore[index] + # OCI's server-side default token cap is tiny (~20 tokens), so an + # omitted max_tokens silently truncates the response mid-string. Most + # callers never send a limit (MLflow judges among them), so inject a + # sane default when one is absent, mirroring litellm's Anthropic config. + if max_tokens_key not in selected_params: + selected_params[max_tokens_key] = DEFAULT_OCI_CHAT_MAX_TOKENS + # OCI expects uppercase reasoning levels (LOW/MEDIUM/HIGH/NONE); OpenAI # clients send lowercase. OpenAI's "disable" maps to OCI's "NONE". if "reasoningEffort" in selected_params: diff --git a/litellm/llms/openai/completion/handler.py b/litellm/llms/openai/completion/handler.py index 1641615126e..63d39151254 100644 --- a/litellm/llms/openai/completion/handler.py +++ b/litellm/llms/openai/completion/handler.py @@ -49,6 +49,8 @@ class OpenAITextCompletion(BaseLLM): headers: Optional[dict] = None, ): try: + if headers: + optional_params = {**optional_params, "extra_headers": headers} if headers is None: headers = self.validate_environment(api_key=api_key) if model is None or messages is None: diff --git a/litellm/llms/openai/realtime/handler.py b/litellm/llms/openai/realtime/handler.py index f34dae2df09..6751004f1b1 100644 --- a/litellm/llms/openai/realtime/handler.py +++ b/litellm/llms/openai/realtime/handler.py @@ -157,8 +157,14 @@ class OpenAIRealtime(OpenAIChatCompletion): websocket, cast(ClientConnection, backend_ws), logging_obj, + model=model, user_api_key_dict=user_api_key_dict, request_data={"litellm_metadata": litellm_metadata or {}}, + force_transcription_model=( + model + if (query_params or {}).get("intent") == "transcription" + else None + ), ) await realtime_streaming.bidirectional_forward() diff --git a/litellm/llms/openai/realtime/http_transformation.py b/litellm/llms/openai/realtime/http_transformation.py index 1663fcd1fcd..7a6af39ba65 100644 --- a/litellm/llms/openai/realtime/http_transformation.py +++ b/litellm/llms/openai/realtime/http_transformation.py @@ -41,6 +41,14 @@ class OpenAIRealtimeHTTPConfig(BaseRealtimeHTTPConfig): base = base[:-3] return f"{base}/v1/realtime/calls" + def get_transcription_session_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + base = self.get_api_base(api_base).rstrip("/") + if base.endswith("/v1"): + base = base[:-3] + return f"{base}/v1/realtime/transcription_sessions" + def validate_environment( self, headers: dict, diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py index f7dd68aec55..b5319797cc6 100644 --- a/litellm/llms/openai/responses/guardrail_translation/handler.py +++ b/litellm/llms/openai/responses/guardrail_translation/handler.py @@ -35,7 +35,6 @@ from pydantic import BaseModel from litellm._logging import verbose_proxy_logger from litellm.completion_extras.litellm_responses_transformation.transformation import ( - LiteLLMResponsesTransformationHandler, OpenAiResponsesToChatCompletionStreamIterator, ) from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation @@ -479,90 +478,137 @@ class OpenAIResponsesHandler(BaseTranslation): ) -> List[Any]: """ Process output streaming response by applying guardrails to text content. + + Mirrors the Chat Completions handler pattern: extract text from the final + chunk, apply the guardrail, then write the result back in-place so the + caller sees the modified content (e.g. PII tokens replaced). + + For ``response.completed`` events (the normal end-of-stream signal) we + use the same per-item extraction + task-mapping approach as + ``process_output_response`` so that unmasking / blocking works correctly + for every output item. """ + if not responses_so_far: + return responses_so_far final_chunk = responses_so_far[-1] + # Accept both plain dicts and Pydantic models (BaseLiteLLMOpenAIResponseObject + # exposes a .get() shim, so all the .get() calls below work for both). + if not (isinstance(final_chunk, dict) or hasattr(final_chunk, "get")): + return responses_so_far + # ------------------------------------------------------------------ # + # Case 1: response.completed — full response is available in the # + # final chunk; iterate output items, apply guardrail, write back. # + # ------------------------------------------------------------------ # + if final_chunk.get("type") == "response.completed": + response_obj = final_chunk.get("response") or {} + if not hasattr(response_obj, "get"): + return responses_so_far + outputs: List[Any] = response_obj.get("output") or [] + + texts_to_check: List[str] = [] + tool_calls_to_check: List[ChatCompletionToolCallChunk] = [] + task_mappings: List[Tuple[int, int]] = [] + + for output_idx, output_item in enumerate(outputs): + self._extract_output_text_and_images( + output_item=output_item, + output_idx=output_idx, + texts_to_check=texts_to_check, + images_to_check=[], + task_mappings=task_mappings, + tool_calls_to_check=tool_calls_to_check, + ) + + if texts_to_check or tool_calls_to_check: + if request_data is None: + request_data = {} + if "response" not in request_data: + request_data["response"] = response_obj + if "litellm_metadata" not in request_data: + user_metadata = self.transform_user_api_key_dict_to_metadata( + user_api_key_dict + ) + if user_metadata: + request_data["litellm_metadata"] = user_metadata + + inputs = GenericGuardrailAPIInputs(texts=texts_to_check) + if tool_calls_to_check: + inputs["tool_calls"] = cast( + List[ChatCompletionToolCallChunk], tool_calls_to_check + ) + response_model = response_obj.get("model") + if response_model: + inputs["model"] = response_model + + guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=litellm_logging_obj, + ) + + guardrailed_texts = guardrailed_inputs.get("texts", []) + + # Write guardrailed texts back into the output items in-place. + # final_chunk is a reference into responses_so_far so this + # mutates the list that the caller holds. + await self._apply_guardrail_responses_to_output( + response=response_obj, + responses=guardrailed_texts, + task_mappings=task_mappings, + ) + + return responses_so_far + + # ------------------------------------------------------------------ # + # Case 2: response.output_item.done — extract tool calls only. # + # ------------------------------------------------------------------ # if final_chunk.get("type") == "response.output_item.done": - # convert openai response to model response model_response_stream = OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream( final_chunk ) - tool_calls = model_response_stream.choices[0].delta.tool_calls if tool_calls: inputs = GenericGuardrailAPIInputs() inputs["tool_calls"] = cast( List[ChatCompletionToolCallChunk], tool_calls ) - # Include model information if available if ( hasattr(model_response_stream, "model") and model_response_stream.model ): inputs["model"] = model_response_stream.model - _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + await guardrail_to_apply.apply_guardrail( inputs=inputs, request_data=request_data if request_data is not None else {}, input_type="response", logging_obj=litellm_logging_obj, ) - return responses_so_far - elif final_chunk.get("type") == "response.completed": - # convert openai response to model response - outputs = final_chunk.get("response", {}).get("output", []) + return responses_so_far - model_response_choices = LiteLLMResponsesTransformationHandler._convert_response_output_to_choices( - output_items=outputs, - handle_raw_dict_callback=None, - ) - - if model_response_choices: - tool_calls = model_response_choices[0].message.tool_calls - text = model_response_choices[0].message.content - guardrail_inputs = GenericGuardrailAPIInputs() - if text: - guardrail_inputs["texts"] = [text] - if tool_calls: - guardrail_inputs["tool_calls"] = cast( - List[ChatCompletionToolCallChunk], tool_calls - ) - # Include model information from the response if available - response_model = final_chunk.get("response", {}).get("model") - if response_model: - guardrail_inputs["model"] = response_model - if tool_calls or text: - _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( - inputs=guardrail_inputs, - request_data=request_data if request_data is not None else {}, - input_type="response", - logging_obj=litellm_logging_obj, - ) - return responses_so_far - else: - verbose_proxy_logger.debug( - "Skipping output guardrail - model response has no choices" - ) - # model_response_stream = OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(final_chunk) - # tool_calls = model_response_stream.choices[0].tool_calls - # convert openai response to model response + # ------------------------------------------------------------------ # + # Fallback: apply guardrail to the accumulated text string. # + # No structured write-back is possible here; guardrails that only # + # need to block/flag (not rewrite) still work correctly. # + # ------------------------------------------------------------------ # string_so_far = self.get_streaming_string_so_far(responses_so_far) - inputs = GenericGuardrailAPIInputs(texts=[string_so_far]) - # Try to get model from the final chunk if available - if isinstance(final_chunk, dict): + if string_so_far: + fallback_inputs = GenericGuardrailAPIInputs(texts=[string_so_far]) response_model = ( final_chunk.get("response", {}).get("model") if isinstance(final_chunk.get("response"), dict) else None ) if response_model: - inputs["model"] = response_model - _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( - inputs=inputs, - request_data=request_data if request_data is not None else {}, - input_type="response", - logging_obj=litellm_logging_obj, - ) + fallback_inputs["model"] = response_model + await guardrail_to_apply.apply_guardrail( + inputs=fallback_inputs, + request_data=request_data if request_data is not None else {}, + input_type="response", + logging_obj=litellm_logging_obj, + ) return responses_so_far def _check_streaming_has_ended(self, responses_so_far: List[Any]) -> bool: @@ -721,7 +767,7 @@ class OpenAIResponsesHandler(BaseTranslation): async def _apply_guardrail_responses_to_output( self, - response: "ResponsesAPIResponse", + response: Union["ResponsesAPIResponse", Dict[Any, Any]], responses: List[str], task_mappings: List[Tuple[int, int]], ) -> None: diff --git a/litellm/llms/openai_like/dynamic_config.py b/litellm/llms/openai_like/dynamic_config.py index fac453447fa..9ed9734edae 100644 --- a/litellm/llms/openai_like/dynamic_config.py +++ b/litellm/llms/openai_like/dynamic_config.py @@ -187,6 +187,7 @@ def create_responses_config_class(provider: SimpleProviderConfig): from litellm.llms.openai_like.responses.transformation import ( OpenAILikeResponsesConfig, ) + from litellm.types.llms.openai import ResponseInputParam from litellm.types.router import GenericLiteLLMParams class JSONProviderResponsesConfig(OpenAILikeResponsesConfig): @@ -223,5 +224,23 @@ def create_responses_config_class(provider: SimpleProviderConfig): api_base = api_base.rstrip("/") return f"{api_base}/responses" + def transform_responses_api_request( + self, + model: str, + input: Union[str, ResponseInputParam], + response_api_optional_request_params: dict, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> dict: + if provider.special_handling.get("force_store_false"): + response_api_optional_request_params["store"] = False + return super().transform_responses_api_request( + model=model, + input=input, + response_api_optional_request_params=response_api_optional_request_params, + litellm_params=litellm_params, + headers=headers, + ) + _responses_config_cache[provider.slug] = JSONProviderResponsesConfig return JSONProviderResponsesConfig diff --git a/litellm/llms/openai_like/providers.json b/litellm/llms/openai_like/providers.json index c9257677fd1..13d22488838 100644 --- a/litellm/llms/openai_like/providers.json +++ b/litellm/llms/openai_like/providers.json @@ -115,6 +115,15 @@ "max_completion_tokens": "max_tokens" } }, + "neosantara": { + "base_url": "https://api.neosantara.xyz/v1", + "api_key_env": "NEOSANTARA_API_KEY", + "api_base_env": "NEOSANTARA_API_BASE", + "param_mappings": { + "max_completion_tokens": "max_tokens" + }, + "supported_endpoints": ["/v1/chat/completions", "/v1/responses"] + }, "tensormesh": { "base_url": "https://serverless.tensormesh.ai/v1", "api_key_env": "TENSORMESH_INFERENCE_API_KEY", @@ -123,5 +132,14 @@ "param_mappings": { "max_completion_tokens": "max_tokens" } + }, + "parasail": { + "base_url": "https://api.parasail.io/v1", + "api_key_env": "PARASAIL_API_KEY", + "api_base_env": "PARASAIL_API_BASE", + "supported_endpoints": ["/v1/chat/completions", "/v1/responses"], + "special_handling": { + "force_store_false": true + } } } diff --git a/litellm/llms/parallel_ai/search/transformation.py b/litellm/llms/parallel_ai/search/transformation.py index 12d570f1733..85602bf1d86 100644 --- a/litellm/llms/parallel_ai/search/transformation.py +++ b/litellm/llms/parallel_ai/search/transformation.py @@ -1,7 +1,7 @@ """ -Calls Parallel AI's /search endpoint to search the web. +Calls Parallel AI's /v1/search endpoint to search the web. -Parallel AI API Reference: https://docs.parallel.ai/api-reference/search-and-extract-api-beta/search +Parallel AI API Reference: https://docs.parallel.ai/api-reference/search/search """ from typing import Dict, List, Optional, TypedDict, Union @@ -18,36 +18,43 @@ from litellm.secret_managers.main import get_secret_str class _ParallelAISourcePolicy(TypedDict, total=False): - """Source policy for Parallel AI search results.""" - - allowed_domains: List[str] # Optional - list of allowed domains - disallowed_domains: List[str] # Optional - list of disallowed domains + include_domains: List[str] + exclude_domains: List[str] + after_date: str -class _ParallelAISearchRequestRequired(TypedDict): - """Required fields for Parallel AI Search API request.""" - - # Note: At least one of objective or search_queries must be provided - pass +class _ParallelAIExcerptSettings(TypedDict, total=False): + max_chars_per_result: int -class ParallelAISearchRequest(_ParallelAISearchRequestRequired, total=False): +class _ParallelAIAdvancedSettings(TypedDict, total=False): + source_policy: _ParallelAISourcePolicy + excerpt_settings: _ParallelAIExcerptSettings + fetch_policy: Dict + location: str + max_results: int + + +class ParallelAISearchRequest(TypedDict, total=False): """ - Parallel AI Search API request format. - Based on: https://docs.parallel.ai/api-reference/search-and-extract-api-beta/search + Parallel AI v1 Search API request format. + Based on: https://docs.parallel.ai/api-reference/search/search """ + search_queries: List[str] # Required - at least one keyword search query objective: str # Optional - natural-language description of search goal - search_queries: List[str] # Optional - list of keyword search queries - processor: str # Optional - search processor ('base', 'pro'), default 'base' - max_results: int # Optional - maximum number of results, default 10 - max_chars_per_result: int # Optional - max characters per result excerpt - source_policy: _ParallelAISourcePolicy # Optional - source policy for allowed/disallowed domains + mode: str # Optional - 'turbo', 'basic', or 'advanced' (default 'advanced') + max_chars_total: int # Optional - upper bound on total excerpt characters + session_id: str # Optional - tracks calls across search/extract requests + client_model: str # Optional - model consuming the results + advanced_settings: _ParallelAIAdvancedSettings + + +LEGACY_PROCESSOR_TO_MODE = {"base": "basic", "pro": "advanced"} class ParallelAISearchConfig(BaseSearchConfig): PARALLEL_AI_API_BASE = "https://api.parallel.ai" - PARALLEL_HEADER_SEARCH_EXTRACT_VALUE = "search-extract-2025-10-10" @staticmethod def ui_friendly_name() -> str: @@ -60,9 +67,6 @@ class ParallelAISearchConfig(BaseSearchConfig): api_base: Optional[str] = None, **kwargs, ) -> Dict: - """ - Validate environment and return headers. - """ api_key = ( api_key or get_secret_str("PARALLEL_AI_API_KEY") @@ -74,7 +78,6 @@ class ParallelAISearchConfig(BaseSearchConfig): ) headers["x-api-key"] = api_key headers["Content-Type"] = "application/json" - headers["parallel-beta"] = self.PARALLEL_HEADER_SEARCH_EXTRACT_VALUE return headers def get_complete_url( @@ -84,32 +87,18 @@ class ParallelAISearchConfig(BaseSearchConfig): data: Optional[Union[Dict, List[Dict]]] = None, **kwargs, ) -> str: - """ - Get complete URL for Search endpoint. - """ api_base = ( api_base or get_secret_str("PARALLEL_AI_API_BASE") or self.PARALLEL_AI_API_BASE ) - # Parallel AI search endpoint is at /v1beta/search - if not api_base.endswith("/v1beta/search"): - if api_base.endswith("/"): - api_base = f"{api_base}v1beta/search" - else: - api_base = f"{api_base}/v1beta/search" + api_base = api_base.rstrip("/") + if not api_base.endswith("/v1/search"): + api_base = f"{api_base.removesuffix('/v1')}/v1/search" return api_base - def _transform_query_to_objective(self, query: Union[str, List[str]]) -> str: - """ - Transform query to objective. - """ - if isinstance(query, list): - return " ".join(query) - return query - def transform_search_request( self, query: Union[str, List[str]], @@ -117,57 +106,78 @@ class ParallelAISearchConfig(BaseSearchConfig): **kwargs, ) -> Dict: """ - Transform Search request to Parallel AI API format. + Transform Search request to Parallel AI v1 API format. Args: query: Search query (string or list of strings) - - If string: maps to `objective` (natural language) + - If string: maps to `search_queries` (single item) and `objective` - If list: maps to `search_queries` (keyword queries) optional_params: Optional parameters for the request - - max_results: Maximum number of search results (default 10) - - search_domain_filter: List of domains to include -> maps to `source_policy.allowed_domains` - - exclude_domains: List of domains to exclude -> maps to `source_policy.disallowed_domains` - - processor: Search processor ('base', 'pro') - - max_chars_per_result: Max characters per result excerpt + - mode: Search mode ('turbo', 'basic', 'advanced'); defaults to 'basic' + - processor: Legacy v1beta param; 'base' maps to mode 'basic', 'pro' to 'advanced' + - max_results: Maximum number of search results -> `advanced_settings.max_results` + - search_domain_filter: Domains to include -> `advanced_settings.source_policy.include_domains` + - exclude_domains: Domains to exclude -> `advanced_settings.source_policy.exclude_domains` + - country: ISO 3166-1 alpha-2 code -> `advanced_settings.location` + - max_chars_per_result: -> `advanced_settings.excerpt_settings.max_chars_per_result` + - Any other params are passed through to the request body as-is Returns: - Dict with typed request data following ParallelAISearchRequest spec + Dict with request data following the v1 search request spec """ + params = dict(optional_params) + request_data: ParallelAISearchRequest = {} - # Map query to objective (string or list both become objective) if isinstance(query, list): - request_data["objective"] = self._transform_query_to_objective(query) + request_data["search_queries"] = query else: + request_data["search_queries"] = [query] request_data["objective"] = query - # Transform Perplexity unified spec parameters to Parallel AI format - if "max_results" in optional_params: - request_data["max_results"] = optional_params["max_results"] + mode = params.pop("mode", None) + processor = params.pop("processor", None) + if mode is None and processor is not None: + mode = LEGACY_PROCESSOR_TO_MODE.get(processor, processor) + # the v1 API defaults to 'advanced' when mode is omitted; default to 'basic' + # instead to keep v1beta's default tier (processor 'base') and litellm's + # $0.004/query cost map entry for `parallel_ai/search` accurate + request_data["mode"] = mode or "basic" + + advanced_settings: _ParallelAIAdvancedSettings = {} + + if "max_results" in params: + advanced_settings["max_results"] = params.pop("max_results") + + if "country" in params: + advanced_settings["location"] = params.pop("country") + + if "max_chars_per_result" in params: + advanced_settings["excerpt_settings"] = { + "max_chars_per_result": params.pop("max_chars_per_result") + } - # Map domain filters to source_policy source_policy: _ParallelAISourcePolicy = {} - if "search_domain_filter" in optional_params: - source_policy["allowed_domains"] = optional_params["search_domain_filter"] + if "search_domain_filter" in params: + source_policy["include_domains"] = params.pop("search_domain_filter") - if "exclude_domains" in optional_params: - source_policy["disallowed_domains"] = optional_params["exclude_domains"] + if "exclude_domains" in params: + source_policy["exclude_domains"] = params.pop("exclude_domains") if source_policy: - request_data["source_policy"] = source_policy + advanced_settings["source_policy"] = source_policy - # Convert to dict before dynamic key assignments - result_data = dict(request_data) + advanced_settings.update(params.pop("advanced_settings", {})) - # pass through all other parameters as-is - for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): - result_data[param] = value + if advanced_settings: + request_data["advanced_settings"] = advanced_settings + # unified-spec param with no v1 equivalent + params.pop("max_tokens_per_page", None) + + result_data: Dict = dict(request_data) + result_data.update(params) return result_data def transform_search_response( @@ -177,36 +187,27 @@ class ParallelAISearchConfig(BaseSearchConfig): **kwargs, ) -> SearchResponse: """ - Transform Parallel AI API response to LiteLLM unified SearchResponse format. + Transform Parallel AI v1 API response to LiteLLM unified SearchResponse format. - Parallel AI → LiteLLM mappings: - - results[].title → SearchResult.title - - results[].url → SearchResult.url - - results[].excerpts (array) → SearchResult.snippet (joined string) - - No date/last_updated fields in Parallel AI response (set to None) - - Args: - raw_response: Raw httpx response from Parallel AI API - logging_obj: Logging object for tracking - - Returns: - SearchResponse with standardized format + Parallel AI -> LiteLLM mappings: + - results[].title -> SearchResult.title + - results[].url -> SearchResult.url + - results[].excerpts (array) -> SearchResult.snippet (joined string) + - results[].publish_date -> SearchResult.date """ response_json = raw_response.json() - # Transform results to SearchResult objects results = [] for result in response_json.get("results", []): - # Join excerpts array into a single snippet string - excerpts = result.get("excerpts", []) + excerpts = result.get("excerpts") or [] snippet = " ... ".join(excerpts) if excerpts else "" search_result = SearchResult( - title=result.get("title", ""), - url=result.get("url", ""), + title=result.get("title") or "", + url=result.get("url") or "", snippet=snippet, - date=None, # Parallel AI doesn't provide date in response - last_updated=None, # Parallel AI doesn't provide last_updated in response + date=result.get("publish_date"), + last_updated=None, ) results.append(search_result) diff --git a/litellm/llms/pass_through/guardrail_translation/__init__.py b/litellm/llms/pass_through/guardrail_translation/__init__.py index db69c8e378a..46fea242c13 100644 --- a/litellm/llms/pass_through/guardrail_translation/__init__.py +++ b/litellm/llms/pass_through/guardrail_translation/__init__.py @@ -1,15 +1,18 @@ """Pass-Through Endpoint guardrail translation handler.""" from litellm.llms.pass_through.guardrail_translation.handler import ( + LlmPassthroughRouteHandler, PassThroughEndpointHandler, ) from litellm.types.utils import CallTypes guardrail_translation_mappings = { CallTypes.pass_through: PassThroughEndpointHandler, + CallTypes.allm_passthrough_route: LlmPassthroughRouteHandler, } __all__ = [ "guardrail_translation_mappings", + "LlmPassthroughRouteHandler", "PassThroughEndpointHandler", ] diff --git a/litellm/llms/pass_through/guardrail_translation/handler.py b/litellm/llms/pass_through/guardrail_translation/handler.py index a8cc42d7c54..db8d519d9be 100644 --- a/litellm/llms/pass_through/guardrail_translation/handler.py +++ b/litellm/llms/pass_through/guardrail_translation/handler.py @@ -6,7 +6,7 @@ It uses the field targeting configuration from litellm_logging_obj to extract specific fields for guardrail processing. """ -from typing import TYPE_CHECKING, Any, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type from litellm._logging import verbose_proxy_logger from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation @@ -16,6 +16,8 @@ from litellm.types.utils import GenericGuardrailAPIInputs if TYPE_CHECKING: from litellm.integrations.custom_guardrail import CustomGuardrail from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj + from litellm.proxy._types import UserAPIKeyAuth + from litellm.proxy.utils import ProxyLogging class PassThroughEndpointHandler(BaseTranslation): @@ -208,3 +210,128 @@ class PassThroughEndpointHandler(BaseTranslation): ) return response + + +_PROVIDER_HANDLERS: Dict[str, Type[BaseTranslation]] = {} + + +def _get_provider_handlers() -> Dict[str, Type[BaseTranslation]]: + global _PROVIDER_HANDLERS + if not _PROVIDER_HANDLERS: + from litellm.llms.bedrock.passthrough.guardrail_translation.handler import ( + BedrockPassthroughGuardrailHandler, + ) + + _PROVIDER_HANDLERS = {"bedrock": BedrockPassthroughGuardrailHandler} + return _PROVIDER_HANDLERS + + +class LlmPassthroughRouteHandler(BaseTranslation): + """ + Dispatcher for allm_passthrough_route guardrail translation. + + Routes to a per-provider handler based on data["custom_llm_provider"]. + Unknown providers are skipped with a debug log. + """ + + async def process_input_messages( + self, + data: dict, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None, + ) -> Any: + provider = data.get("custom_llm_provider") + handler_cls = _get_provider_handlers().get(provider or "") + if handler_cls is None: + verbose_proxy_logger.debug( + "LlmPassthroughRouteHandler: no handler for provider=%s, skipping guardrail", + provider, + ) + return data + return await handler_cls().process_input_messages( + data=data, + guardrail_to_apply=guardrail_to_apply, + litellm_logging_obj=litellm_logging_obj, + ) + + async def process_output_response( + self, + response: Any, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None, + user_api_key_dict: Optional[Any] = None, + request_data: Optional[dict] = None, + ) -> Any: + provider = (request_data or {}).get("custom_llm_provider") + handler_cls = _get_provider_handlers().get(provider or "") + if handler_cls is None: + verbose_proxy_logger.debug( + "LlmPassthroughRouteHandler: no handler for provider=%s, skipping guardrail", + provider, + ) + return response + return await handler_cls().process_output_response( + response=response, + guardrail_to_apply=guardrail_to_apply, + litellm_logging_obj=litellm_logging_obj, + user_api_key_dict=user_api_key_dict, + request_data=request_data, + ) + + @staticmethod + def is_event_stream_response(provider: Optional[str], content_type: str) -> bool: + handler_cls = _get_provider_handlers().get(provider or "") + detector = getattr(handler_cls, "is_event_stream_content_type", None) + if detector is None: + return False + return detector(content_type) + + @staticmethod + def event_stream_media_type(provider: Optional[str]) -> Optional[str]: + handler_cls = _get_provider_handlers().get(provider or "") + getter = getattr(handler_cls, "event_stream_media_type", None) + if getter is None: + return None + return getter() + + @staticmethod + def _resolve_event_stream_de_anonymizer(provider: Optional[str]): + handler_cls = _get_provider_handlers().get(provider or "") + return getattr(handler_cls, "de_anonymize_event_stream", None) + + @staticmethod + def supports_event_stream_de_anonymization( + provider: Optional[str], endpoint: Optional[str] + ) -> bool: + handler_cls = _get_provider_handlers().get(provider or "") + endpoint_check = getattr( + handler_cls, "event_stream_endpoint_is_de_anonymizable", None + ) + if endpoint_check is None: + return False + return endpoint_check(endpoint or "") + + @staticmethod + async def de_anonymize_event_stream( + body_bytes: bytes, + proxy_logging_obj: "ProxyLogging", + user_api_key_dict: "UserAPIKeyAuth", + data: dict, + ) -> bytes: + provider = data.get("custom_llm_provider") + de_anonymize = LlmPassthroughRouteHandler._resolve_event_stream_de_anonymizer( + provider + ) + if de_anonymize is None: + verbose_proxy_logger.debug( + "LlmPassthroughRouteHandler: no event-stream handler for provider=%s, " + "leaving stream unmodified", + provider, + ) + return body_bytes + return await de_anonymize( + body_bytes=body_bytes, + proxy_logging_obj=proxy_logging_obj, + user_api_key_dict=user_api_key_dict, + data=data, + ) diff --git a/litellm/llms/snowflake/utils.py b/litellm/llms/snowflake/utils.py index d84efdd9fcd..4f79006f6f8 100644 --- a/litellm/llms/snowflake/utils.py +++ b/litellm/llms/snowflake/utils.py @@ -25,6 +25,7 @@ class SnowflakeBaseConfig: "temperature", "max_tokens", "top_p", + "stream", "response_format", "tools", "tool_choice", diff --git a/litellm/llms/soniox/__init__.py b/litellm/llms/soniox/__init__.py new file mode 100644 index 00000000000..778211a2a53 --- /dev/null +++ b/litellm/llms/soniox/__init__.py @@ -0,0 +1 @@ +"""Soniox LLM provider implementation.""" diff --git a/litellm/llms/soniox/audio_transcription/__init__.py b/litellm/llms/soniox/audio_transcription/__init__.py new file mode 100644 index 00000000000..3da6032ce65 --- /dev/null +++ b/litellm/llms/soniox/audio_transcription/__init__.py @@ -0,0 +1 @@ +"""Soniox audio transcription implementation.""" diff --git a/litellm/llms/soniox/audio_transcription/handler.py b/litellm/llms/soniox/audio_transcription/handler.py new file mode 100644 index 00000000000..d4774fea460 --- /dev/null +++ b/litellm/llms/soniox/audio_transcription/handler.py @@ -0,0 +1,802 @@ +""" +Handler for Soniox async speech-to-text transcription. + +Soniox's async transcription API requires multiple HTTP calls: + 1. (optional) POST /v1/files — upload a local audio file + 2. POST /v1/transcriptions — create a transcription job + 3. GET /v1/transcriptions/{id} — poll until status == "completed" + 4. GET /v1/transcriptions/{id}/transcript — fetch the transcript + 5. (optional) DELETE /v1/transcriptions/{id} — cleanup + 6. (optional) DELETE /v1/files/{id} — cleanup + +Because this does not fit the single-request shape of +`base_llm_http_handler.audio_transcriptions`, the dispatch in +`litellm.main.transcription()` routes Soniox requests directly to this +handler (analogous to the OpenAI / Azure transcription handlers). +""" + +import asyncio +import math +import time +from typing import ( + TYPE_CHECKING, + Any, + Coroutine, + Dict, + List, + Optional, + Tuple, + Union, +) + +import httpx + +from litellm.litellm_core_utils.audio_utils.utils import ( + get_audio_file_name, + process_audio_file, +) +from litellm.llms.custom_httpx.http_handler import ( + AsyncHTTPHandler, + HTTPHandler, + _get_httpx_client, + get_async_httpx_client, +) +from litellm.llms.soniox.audio_transcription.transformation import ( + SonioxAudioTranscriptionConfig, +) +from litellm.llms.soniox.common_utils import ( + SONIOX_DEFAULT_CLEANUP, + SONIOX_DEFAULT_MAX_POLL_ATTEMPTS, + SONIOX_DEFAULT_POLL_INTERVAL, + SONIOX_MAX_POLL_ATTEMPTS, + SONIOX_MAX_POLL_INTERVAL, + SONIOX_MIN_POLL_INTERVAL, + SONIOX_SECRET_FIELDS, + SonioxException, + get_soniox_api_base, +) +from litellm.types.utils import FileTypes, TranscriptionResponse + +if TYPE_CHECKING: + from litellm.litellm_core_utils.litellm_logging import ( + Logging as LiteLLMLoggingObj, + ) +else: + LiteLLMLoggingObj = Any + + +class SonioxAudioTranscriptionHandler: + """Orchestrates the Soniox async transcription flow.""" + + # ------------------------------------------------------------------ + # Public entry points + # ------------------------------------------------------------------ + + def audio_transcriptions( + self, + model: str, + audio_file: Optional[FileTypes], + optional_params: dict, + litellm_params: dict, + model_response: TranscriptionResponse, + timeout: float, + max_retries: int, + logging_obj: LiteLLMLoggingObj, + api_key: Optional[str], + api_base: Optional[str], + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + atranscription: bool = False, + headers: Optional[Dict[str, Any]] = None, + provider_config: Optional[SonioxAudioTranscriptionConfig] = None, + ) -> Union[TranscriptionResponse, Coroutine[Any, Any, TranscriptionResponse]]: + """Sync/async dispatch for Soniox transcription requests. + + Note: ``max_retries`` is accepted for signature compatibility with + ``litellm.transcription`` but is **not yet implemented** for the Soniox + async pipeline. Transient HTTP failures during upload, create, poll, + or fetch will surface immediately. Wrap calls with the standard + ``litellm.Router`` / ``num_retries`` mechanism for retry behaviour. + """ + config = provider_config or SonioxAudioTranscriptionConfig() + + if atranscription is True: + return self._async_audio_transcriptions( + model=model, + audio_file=audio_file, + optional_params=optional_params, + litellm_params=litellm_params, + model_response=model_response, + timeout=timeout, + logging_obj=logging_obj, + api_key=api_key, + api_base=api_base, + client=client if isinstance(client, AsyncHTTPHandler) else None, + headers=headers or {}, + provider_config=config, + ) + + return self._sync_audio_transcriptions( + model=model, + audio_file=audio_file, + optional_params=optional_params, + litellm_params=litellm_params, + model_response=model_response, + timeout=timeout, + logging_obj=logging_obj, + api_key=api_key, + api_base=api_base, + client=client if isinstance(client, HTTPHandler) else None, + headers=headers or {}, + provider_config=config, + ) + + # ------------------------------------------------------------------ + # Helpers shared between sync and async paths + # ------------------------------------------------------------------ + + def _prepare( + self, + audio_file: Optional[FileTypes], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str], + api_base: Optional[str], + provider_config: SonioxAudioTranscriptionConfig, + headers: Dict[str, Any], + ) -> Tuple[ + Dict[str, str], # auth headers + str, # api_base (no trailing slash) + Dict[str, Any], # body for POST /v1/transcriptions (without file_id/audio_url) + Dict[str, Any], # handler-only options (poll interval, cleanup, ...) + ]: + # Validate env -> auth headers. + auth_headers = provider_config.validate_environment( + headers=headers, + model="", # unused + messages=[], + optional_params=optional_params, + litellm_params=litellm_params, + api_key=api_key, + api_base=api_base, + ) + + base_url = get_soniox_api_base(api_base) + + # Operate on a local copy so we don't mutate the caller's dict + # (the caller may reuse `optional_params` for retries or logging). + params = dict(optional_params) + + # Pull handler-only kwargs out of params so they aren't sent + # to Soniox. + poll_interval = float( + params.pop("soniox_polling_interval", SONIOX_DEFAULT_POLL_INTERVAL) + ) + try: + max_attempts = int( + params.pop( + "soniox_max_polling_attempts", SONIOX_DEFAULT_MAX_POLL_ATTEMPTS + ) + ) + except (ValueError, OverflowError): + max_attempts = SONIOX_DEFAULT_MAX_POLL_ATTEMPTS + cleanup_raw = params.pop("soniox_cleanup", SONIOX_DEFAULT_CLEANUP) + if cleanup_raw is None: + cleanup: List[str] = [] + elif isinstance(cleanup_raw, str): + cleanup = [cleanup_raw] + else: + cleanup = list(cleanup_raw) + filename_override = params.pop("filename", None) + + # Server-side clamps. Caller-supplied poll settings (from request kwargs) + # are bounded so an authenticated caller cannot force a worker into a + # tight poll loop (zero interval) or pin it indefinitely (huge attempt + # count). Total polling time is bounded by + # SONIOX_MAX_POLL_ATTEMPTS * SONIOX_MAX_POLL_INTERVAL. + if not math.isfinite(poll_interval): + poll_interval = SONIOX_DEFAULT_POLL_INTERVAL + clamped_poll_interval = max( + SONIOX_MIN_POLL_INTERVAL, min(poll_interval, SONIOX_MAX_POLL_INTERVAL) + ) + clamped_max_attempts = max(1, min(max_attempts, SONIOX_MAX_POLL_ATTEMPTS)) + + handler_opts: Dict[str, Any] = { + "poll_interval": clamped_poll_interval, + "max_attempts": clamped_max_attempts, + "cleanup": cleanup, + "filename_override": filename_override, + "audio_url": params.pop("audio_url", None), + "file_id": params.pop("file_id", None), + } + + # Soniox does not accept `language` directly; map_openai_params should + # already have translated it, but drop any leftover to be safe. + params.pop("language", None) + + # response_format is handled by LiteLLM post-processing, not Soniox. + handler_opts["response_format"] = params.pop("response_format", None) + + return auth_headers, base_url, params, handler_opts + + def _build_create_body( + self, + model: str, + optional_params: dict, + handler_opts: Dict[str, Any], + file_id: Optional[str], + ) -> Dict[str, Any]: + body: Dict[str, Any] = {"model": model} + # Soniox-native passthrough fields + for key, value in optional_params.items(): + if value is None: + continue + body[key] = value + + if handler_opts.get("audio_url"): + body["audio_url"] = handler_opts["audio_url"] + if file_id: + body["file_id"] = file_id + + return body + + @staticmethod + def _redact_body_for_logging(body: Dict[str, Any]) -> Dict[str, Any]: + """Return a shallow copy of ``body`` with secret fields redacted. + + Soniox's create-transcription body can include + ``webhook_auth_header_value`` (a shared secret used to authenticate + webhook callbacks). Forwarding that value to logging callbacks would + let anyone with read access to those sinks forge webhook requests, so + we replace any value of a known secret-bearing field with the literal + ``"[REDACTED]"`` before logging. Non-secret fields are passed through + unchanged. + """ + if not body: + return body + redacted = dict(body) + for field in SONIOX_SECRET_FIELDS: + if field in redacted and redacted[field] is not None: + redacted[field] = "[REDACTED]" + return redacted + + @staticmethod + def _safe_log_pre_call( + logging_obj: LiteLLMLoggingObj, + api_key: Optional[str], + api_base: str, + body: Dict[str, Any], + ) -> None: + try: + logging_obj.pre_call( + input=None, + api_key=api_key, + additional_args={ + "api_base": f"{api_base}/v1/transcriptions", + "atranscription": True, + "complete_input_dict": SonioxAudioTranscriptionHandler._redact_body_for_logging( + body + ), + }, + ) + except Exception: + # Logging hooks are best-effort: a misbehaving callback or third-party + # observability integration must never break a real Soniox call. + pass + + @staticmethod + def _safe_log_post_call( + logging_obj: LiteLLMLoggingObj, + audio_file: Optional[FileTypes], + api_key: Optional[str], + body: Dict[str, Any], + original_response: Any, + ) -> None: + try: + logging_obj.post_call( + input=get_audio_file_name(audio_file) if audio_file else None, + api_key=api_key, + additional_args={ + "complete_input_dict": SonioxAudioTranscriptionHandler._redact_body_for_logging( + body + ) + }, + original_response=original_response, + ) + except Exception: + # Logging hooks are best-effort: a misbehaving callback or third-party + # observability integration must never break a real Soniox call. + pass + + @staticmethod + def _raise_for_response( + response: httpx.Response, + provider_config: SonioxAudioTranscriptionConfig, + action: str, + ) -> None: + if response.status_code >= 400: + try: + payload = response.json() + message = ( + payload.get("error_message") + or payload.get("error") + or response.text + ) + except Exception: + message = response.text + raise provider_config.get_error_class( + error_message=f"Soniox {action} failed (HTTP {response.status_code}): {message}", + status_code=response.status_code, + headers=response.headers, + ) + + # ------------------------------------------------------------------ + # Sync flow + # ------------------------------------------------------------------ + + def _sync_audio_transcriptions( + self, + model: str, + audio_file: Optional[FileTypes], + optional_params: dict, + litellm_params: dict, + model_response: TranscriptionResponse, + timeout: float, + logging_obj: LiteLLMLoggingObj, + api_key: Optional[str], + api_base: Optional[str], + client: Optional[HTTPHandler], + headers: Dict[str, Any], + provider_config: SonioxAudioTranscriptionConfig, + ) -> TranscriptionResponse: + auth_headers, base_url, opt_params, handler_opts = self._prepare( + audio_file=audio_file, + optional_params=optional_params, + litellm_params=litellm_params, + api_key=api_key, + api_base=api_base, + provider_config=provider_config, + headers=headers, + ) + + http_client = ( + client + if isinstance(client, HTTPHandler) + else ( + _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + ) + ) + + file_id = handler_opts.get("file_id") + uploaded_file_id: Optional[str] = None + transcription_id: Optional[str] = None + + try: + if not file_id and not handler_opts.get("audio_url"): + if audio_file is None: + raise SonioxException( + message=( + "Soniox transcription requires one of: a file argument, " + "an `audio_url` kwarg, or a `file_id` kwarg." + ), + status_code=400, + headers=None, + ) + uploaded_file_id = self._sync_upload_file( + http_client=http_client, + base_url=base_url, + auth_headers=auth_headers, + audio_file=audio_file, + filename_override=handler_opts.get("filename_override"), + timeout=timeout, + provider_config=provider_config, + ) + file_id = uploaded_file_id + + body = self._build_create_body(model, opt_params, handler_opts, file_id) + self._safe_log_pre_call(logging_obj, api_key, base_url, body) + + create_resp = http_client.post( + url=f"{base_url}/v1/transcriptions", + headers=auth_headers, + json=body, + timeout=timeout, + ) + self._raise_for_response( + create_resp, provider_config, "create transcription" + ) + transcription_id = create_resp.json()["id"] + + transcription_meta = self._sync_poll_until_completed( + http_client=http_client, + base_url=base_url, + auth_headers=auth_headers, + transcription_id=transcription_id, + poll_interval=handler_opts["poll_interval"], + max_attempts=handler_opts["max_attempts"], + timeout=timeout, + provider_config=provider_config, + ) + + transcript_resp = http_client.get( + url=f"{base_url}/v1/transcriptions/{transcription_id}/transcript", + headers=auth_headers, + timeout=timeout, + ) + self._raise_for_response( + transcript_resp, provider_config, "fetch transcript" + ) + transcript = transcript_resp.json() + + payload = {"transcription": transcription_meta, "transcript": transcript} + response = provider_config._build_response_from_payload( + payload, + model_response=model_response, + response_format=handler_opts.get("response_format"), + ) + + self._safe_log_post_call(logging_obj, audio_file, api_key, body, payload) + + audio_duration_ms = transcription_meta.get("audio_duration_ms") + response._hidden_params.update( + { + "model": model, + "custom_llm_provider": "soniox", + "audio_transcription_duration": ( + float(audio_duration_ms) / 1000.0 + if audio_duration_ms is not None + else None + ), + } + ) + return response + finally: + self._sync_cleanup( + http_client=http_client, + base_url=base_url, + auth_headers=auth_headers, + cleanup=handler_opts["cleanup"], + file_id_to_cleanup=uploaded_file_id, + transcription_id=transcription_id, + timeout=timeout, + ) + + def _sync_upload_file( + self, + http_client: HTTPHandler, + base_url: str, + auth_headers: Dict[str, str], + audio_file: FileTypes, + filename_override: Optional[str], + timeout: float, + provider_config: SonioxAudioTranscriptionConfig, + ) -> str: + processed = process_audio_file(audio_file) + filename = filename_override or processed.filename + files = { + "file": (filename, processed.file_content, processed.content_type), + } + # `Authorization` header is fine; httpx sets multipart Content-Type. + upload_headers = {"Authorization": auth_headers["Authorization"]} + resp = http_client.post( + url=f"{base_url}/v1/files", + headers=upload_headers, + files=files, + timeout=timeout, + ) + self._raise_for_response(resp, provider_config, "upload file") + return resp.json()["id"] + + def _sync_poll_until_completed( + self, + http_client: HTTPHandler, + base_url: str, + auth_headers: Dict[str, str], + transcription_id: str, + poll_interval: float, + max_attempts: int, + timeout: float, + provider_config: SonioxAudioTranscriptionConfig, + ) -> Dict[str, Any]: + for _ in range(max_attempts): + resp = http_client.get( + url=f"{base_url}/v1/transcriptions/{transcription_id}", + headers=auth_headers, + timeout=timeout, + ) + self._raise_for_response(resp, provider_config, "poll transcription") + data = resp.json() + status = data.get("status") + if status == "completed": + return data + if status == "error": + raise provider_config.get_error_class( + error_message=( + f"Soniox transcription {transcription_id} failed: " + f"{data.get('error_message') or data.get('error_type') or 'unknown error'}" + ), + status_code=500, + headers=resp.headers, + ) + time.sleep(poll_interval) + raise provider_config.get_error_class( + error_message=( + f"Soniox transcription {transcription_id} did not complete after " + f"{max_attempts} polling attempts (interval={poll_interval}s)." + ), + status_code=504, + headers={}, + ) + + def _sync_cleanup( + self, + http_client: HTTPHandler, + base_url: str, + auth_headers: Dict[str, str], + cleanup: List[str], + file_id_to_cleanup: Optional[str], + transcription_id: Optional[str], + timeout: float, + ) -> None: + if not cleanup: + return + if "transcription" in cleanup and transcription_id: + try: + http_client.delete( + url=f"{base_url}/v1/transcriptions/{transcription_id}", + headers=auth_headers, + timeout=timeout, + ) + except Exception: + # Cleanup is best-effort: a failed delete leaves stale data on + # Soniox but must not mask the original transcription result + # (or, on the error path, the original error). + pass + if "file" in cleanup and file_id_to_cleanup: + try: + http_client.delete( + url=f"{base_url}/v1/files/{file_id_to_cleanup}", + headers=auth_headers, + timeout=timeout, + ) + except Exception: + # Cleanup is best-effort; see comment above. + pass + + # ------------------------------------------------------------------ + # Async flow + # ------------------------------------------------------------------ + + async def _async_audio_transcriptions( + self, + model: str, + audio_file: Optional[FileTypes], + optional_params: dict, + litellm_params: dict, + model_response: TranscriptionResponse, + timeout: float, + logging_obj: LiteLLMLoggingObj, + api_key: Optional[str], + api_base: Optional[str], + client: Optional[AsyncHTTPHandler], + headers: Dict[str, Any], + provider_config: SonioxAudioTranscriptionConfig, + ) -> TranscriptionResponse: + import litellm + + auth_headers, base_url, opt_params, handler_opts = self._prepare( + audio_file=audio_file, + optional_params=optional_params, + litellm_params=litellm_params, + api_key=api_key, + api_base=api_base, + provider_config=provider_config, + headers=headers, + ) + + http_client = ( + client + if isinstance(client, AsyncHTTPHandler) + else ( + get_async_httpx_client( + llm_provider=litellm.LlmProviders.SONIOX, + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + ) + ) + + file_id = handler_opts.get("file_id") + uploaded_file_id: Optional[str] = None + transcription_id: Optional[str] = None + + try: + if not file_id and not handler_opts.get("audio_url"): + if audio_file is None: + raise SonioxException( + message=( + "Soniox transcription requires one of: a file argument, " + "an `audio_url` kwarg, or a `file_id` kwarg." + ), + status_code=400, + headers=None, + ) + uploaded_file_id = await self._async_upload_file( + http_client=http_client, + base_url=base_url, + auth_headers=auth_headers, + audio_file=audio_file, + filename_override=handler_opts.get("filename_override"), + timeout=timeout, + provider_config=provider_config, + ) + file_id = uploaded_file_id + + body = self._build_create_body(model, opt_params, handler_opts, file_id) + self._safe_log_pre_call(logging_obj, api_key, base_url, body) + + create_resp = await http_client.post( + url=f"{base_url}/v1/transcriptions", + headers=auth_headers, + json=body, + timeout=timeout, + ) + self._raise_for_response( + create_resp, provider_config, "create transcription" + ) + transcription_id = create_resp.json()["id"] + + transcription_meta = await self._async_poll_until_completed( + http_client=http_client, + base_url=base_url, + auth_headers=auth_headers, + transcription_id=transcription_id, + poll_interval=handler_opts["poll_interval"], + max_attempts=handler_opts["max_attempts"], + timeout=timeout, + provider_config=provider_config, + ) + + transcript_resp = await http_client.get( + url=f"{base_url}/v1/transcriptions/{transcription_id}/transcript", + headers=auth_headers, + timeout=timeout, + ) + self._raise_for_response( + transcript_resp, provider_config, "fetch transcript" + ) + transcript = transcript_resp.json() + + payload = {"transcription": transcription_meta, "transcript": transcript} + response = provider_config._build_response_from_payload( + payload, + model_response=model_response, + response_format=handler_opts.get("response_format"), + ) + + self._safe_log_post_call(logging_obj, audio_file, api_key, body, payload) + + audio_duration_ms = transcription_meta.get("audio_duration_ms") + response._hidden_params.update( + { + "model": model, + "custom_llm_provider": "soniox", + "audio_transcription_duration": ( + float(audio_duration_ms) / 1000.0 + if audio_duration_ms is not None + else None + ), + } + ) + return response + finally: + await self._async_cleanup( + http_client=http_client, + base_url=base_url, + auth_headers=auth_headers, + cleanup=handler_opts["cleanup"], + file_id_to_cleanup=uploaded_file_id, + transcription_id=transcription_id, + timeout=timeout, + ) + + async def _async_upload_file( + self, + http_client: AsyncHTTPHandler, + base_url: str, + auth_headers: Dict[str, str], + audio_file: FileTypes, + filename_override: Optional[str], + timeout: float, + provider_config: SonioxAudioTranscriptionConfig, + ) -> str: + processed = process_audio_file(audio_file) + filename = filename_override or processed.filename + files = { + "file": (filename, processed.file_content, processed.content_type), + } + upload_headers = {"Authorization": auth_headers["Authorization"]} + resp = await http_client.post( + url=f"{base_url}/v1/files", + headers=upload_headers, + files=files, + timeout=timeout, + ) + self._raise_for_response(resp, provider_config, "upload file") + return resp.json()["id"] + + async def _async_poll_until_completed( + self, + http_client: AsyncHTTPHandler, + base_url: str, + auth_headers: Dict[str, str], + transcription_id: str, + poll_interval: float, + max_attempts: int, + timeout: float, + provider_config: SonioxAudioTranscriptionConfig, + ) -> Dict[str, Any]: + for _ in range(max_attempts): + resp = await http_client.get( + url=f"{base_url}/v1/transcriptions/{transcription_id}", + headers=auth_headers, + timeout=timeout, + ) + self._raise_for_response(resp, provider_config, "poll transcription") + data = resp.json() + status = data.get("status") + if status == "completed": + return data + if status == "error": + raise provider_config.get_error_class( + error_message=( + f"Soniox transcription {transcription_id} failed: " + f"{data.get('error_message') or data.get('error_type') or 'unknown error'}" + ), + status_code=500, + headers=resp.headers, + ) + await asyncio.sleep(poll_interval) + raise provider_config.get_error_class( + error_message=( + f"Soniox transcription {transcription_id} did not complete after " + f"{max_attempts} polling attempts (interval={poll_interval}s)." + ), + status_code=504, + headers={}, + ) + + async def _async_cleanup( + self, + http_client: AsyncHTTPHandler, + base_url: str, + auth_headers: Dict[str, str], + cleanup: List[str], + file_id_to_cleanup: Optional[str], + transcription_id: Optional[str], + timeout: float, + ) -> None: + if not cleanup: + return + if "transcription" in cleanup and transcription_id: + try: + await http_client.delete( + url=f"{base_url}/v1/transcriptions/{transcription_id}", + headers=auth_headers, + timeout=timeout, + ) + except Exception: + # Cleanup is best-effort: a failed delete leaves stale data on + # Soniox but must not mask the original transcription result + # (or, on the error path, the original error). + pass + if "file" in cleanup and file_id_to_cleanup: + try: + await http_client.delete( + url=f"{base_url}/v1/files/{file_id_to_cleanup}", + headers=auth_headers, + timeout=timeout, + ) + except Exception: + # Cleanup is best-effort; see comment above. + pass diff --git a/litellm/llms/soniox/audio_transcription/transformation.py b/litellm/llms/soniox/audio_transcription/transformation.py new file mode 100644 index 00000000000..681d4352dfe --- /dev/null +++ b/litellm/llms/soniox/audio_transcription/transformation.py @@ -0,0 +1,281 @@ +""" +Translates between OpenAI's `/v1/audio/transcriptions` shape and Soniox's +async transcription API (https://soniox.com/docs/stt/async/async-transcription). + +This config covers parameter mapping, env validation and response shaping. +The actual orchestration (file upload -> create -> poll -> fetch -> cleanup) +lives in `litellm.llms.soniox.audio_transcription.handler`, because Soniox's +async API requires multiple HTTP calls and does not fit the single-request +contract of `base_llm_http_handler.audio_transcriptions`. +""" + +from typing import Any, Dict, List, Optional, Union + +from httpx import Headers, Response + +from litellm.llms.base_llm.audio_transcription.transformation import ( + AudioTranscriptionRequestData, + BaseAudioTranscriptionConfig, +) +from litellm.llms.base_llm.chat.transformation import BaseLLMException +from litellm.llms.soniox.common_utils import ( + SonioxException, + get_soniox_api_base, + get_soniox_api_key, + render_soniox_tokens, + render_soniox_tokens_as_srt, + render_soniox_tokens_as_vtt, +) +from litellm.types.llms.openai import ( + AllMessageValues, + OpenAIAudioTranscriptionOptionalParams, +) +from litellm.types.utils import FileTypes, TranscriptionResponse + +# Soniox-native kwargs the user can pass through `litellm.transcription(..., **kwargs)` +# in addition to the standard OpenAI params. +SONIOX_PASSTHROUGH_PARAMS: List[str] = [ + "language_hints", + "language_hints_strict", + "enable_language_identification", + "enable_speaker_diarization", + "context", + "translation", + "client_reference_id", + "webhook_url", + "webhook_auth_header_name", + "webhook_auth_header_value", + "audio_url", + "file_id", +] + +# Handler-only kwargs (consumed by the handler, not sent to Soniox). +SONIOX_HANDLER_ONLY_PARAMS: List[str] = [ + "soniox_polling_interval", + "soniox_max_polling_attempts", + "soniox_cleanup", + "filename", +] + + +class SonioxAudioTranscriptionConfig(BaseAudioTranscriptionConfig): + """Configuration for Soniox async speech-to-text transcription.""" + + def get_supported_openai_params( + self, model: str + ) -> List[OpenAIAudioTranscriptionOptionalParams]: + # `language` is mapped onto Soniox's `language_hints`. + # `response_format` is handled by LiteLLM (Soniox doesn't support + # SRT/VTT natively but we synthesize them from token timestamps). + return ["language", "response_format"] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + # Translate the OpenAI `language` param into Soniox `language_hints`. + if "language" in non_default_params and non_default_params["language"]: + language = non_default_params["language"] + existing_hints = optional_params.get("language_hints") + if not existing_hints: + optional_params["language_hints"] = [language] + elif language not in existing_hints: + optional_params["language_hints"] = [language] + list(existing_hints) + + # Capture response_format for post-processing (not sent to Soniox API). + if "response_format" in non_default_params: + optional_params["response_format"] = non_default_params["response_format"] + + # Pass through Soniox-native kwargs unchanged. + for key in SONIOX_PASSTHROUGH_PARAMS + SONIOX_HANDLER_ONLY_PARAMS: + if key in non_default_params and non_default_params[key] is not None: + optional_params[key] = non_default_params[key] + + return optional_params + + def get_error_class( + self, error_message: str, status_code: int, headers: Union[dict, Headers] + ) -> BaseLLMException: + return SonioxException( + message=error_message, status_code=status_code, headers=headers + ) + + def validate_environment( + self, + headers: dict, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + resolved_key = get_soniox_api_key(api_key) + if not resolved_key: + raise SonioxException( + message=( + "Missing Soniox API key. Set the SONIOX_API_KEY environment " + "variable or pass api_key=... to litellm.transcription()." + ), + status_code=401, + headers=None, + ) + + merged_headers: Dict[str, str] = { + "Authorization": f"Bearer {resolved_key}", + } + if headers: + merged_headers.update(headers) + return merged_headers + + def get_complete_url( + self, + api_base: Optional[str], + api_key: Optional[str], + model: str, + optional_params: dict, + litellm_params: dict, + stream: Optional[bool] = None, + ) -> str: + # The handler builds per-call URLs (uploads, create, poll, fetch, delete); + # we just return the resolved base. + return get_soniox_api_base(api_base) + + def transform_audio_transcription_request( + self, + model: str, + audio_file: FileTypes, + optional_params: dict, + litellm_params: dict, + ) -> AudioTranscriptionRequestData: + """ + Build the JSON body for `POST /v1/transcriptions`. + + The handler is responsible for the file upload (if `audio_file` is bytes) + and for filling in `file_id`/`audio_url`. This method exists so the + config can be exercised in isolation by unit tests. + """ + body: Dict[str, Any] = {"model": model} + + for key in SONIOX_PASSTHROUGH_PARAMS: + value = optional_params.get(key) + if value is not None: + body[key] = value + + return AudioTranscriptionRequestData( + data=body, files=None, content_type="application/json" + ) + + def transform_audio_transcription_response( + self, + raw_response: Response, + model_response: Optional[TranscriptionResponse] = None, + ) -> TranscriptionResponse: + """ + Build a TranscriptionResponse from a Soniox transcript payload. + + `raw_response.json()` may be either: + - a Soniox transcript object: `{"id": "...", "text": "...", "tokens": [...]}` + - or a merged envelope: `{"transcription": {...}, "transcript": {...}}` + produced by the handler so transcription metadata is also available. + """ + try: + payload = raw_response.json() + except Exception as exc: + raise SonioxException( + message=f"Failed to parse Soniox response: {exc}", + status_code=getattr(raw_response, "status_code", 500), + headers=getattr(raw_response, "headers", None), + ) + + return self._build_response_from_payload(payload, model_response=model_response) + + def _build_response_from_payload( + self, + payload: Dict[str, Any], + model_response: Optional[TranscriptionResponse] = None, + response_format: Optional[str] = None, + ) -> TranscriptionResponse: + """Shared response-building logic (also used by the handler).""" + transcription_meta: Dict[str, Any] = {} + transcript: Dict[str, Any] + + if isinstance(payload, dict) and "transcript" in payload: + transcription_meta = payload.get("transcription") or {} + transcript = payload.get("transcript") or {} + else: + transcript = payload if isinstance(payload, dict) else {} + + tokens: List[Dict[str, Any]] = transcript.get("tokens") or [] + + # Decide what to put in `text` based on response_format: + # - "srt": render tokens as SRT subtitles (synthesized from timestamps) + # - "vtt": render tokens as WebVTT subtitles (synthesized from timestamps) + # - "verbose_json": return JSON with word-level timing (handled below) + # - "text" / "json" / None: default plain text rendering + if response_format == "srt" and tokens: + text = render_soniox_tokens_as_srt(tokens) + elif response_format == "vtt" and tokens: + text = render_soniox_tokens_as_vtt(tokens) + else: + # Default text rendering (also used for "json", "text", + # "verbose_json") + has_speaker = any(t.get("speaker") is not None for t in tokens) + has_language = any(t.get("language") is not None for t in tokens) + + if (has_speaker or has_language) and tokens: + text = render_soniox_tokens(tokens) + elif transcript.get("text"): + text = transcript["text"] + elif tokens: + text = "".join(t.get("text", "") for t in tokens) + else: + text = "" + + response = model_response or TranscriptionResponse(text=text) + response.text = text + response["task"] = "transcribe" + + # Best-effort metadata fields matching OpenAI's verbose_json shape. + if transcription_meta.get("audio_duration_ms") is not None: + try: + response["duration"] = ( + float(transcription_meta["audio_duration_ms"]) / 1000.0 + ) + except (TypeError, ValueError): + pass + + # Surface a representative language if all tokens agree. + has_language = any(t.get("language") is not None for t in tokens) + if has_language: + languages = {t.get("language") for t in tokens if t.get("language")} + if len(languages) == 1: + response["language"] = next(iter(languages)) + + # For verbose_json, include word-level timing from tokens. + if response_format == "verbose_json" and tokens: + words: List[Dict[str, Any]] = [] + for token in tokens: + word_entry: Dict[str, Any] = {"word": token.get("text", "")} + if token.get("start_ms") is not None: + word_entry["start"] = float(token["start_ms"]) / 1000.0 + if token.get("end_ms") is not None: + word_entry["end"] = float(token["end_ms"]) / 1000.0 + words.append(word_entry) + if words: + response["words"] = words + + # Stash the raw Soniox payload so power-users can read tokens, segments, + # speaker/language data, etc. + response._hidden_params.update( + { + "soniox_raw": { + "transcription": transcription_meta, + "transcript": transcript, + } + } + ) + return response diff --git a/litellm/llms/soniox/common_utils.py b/litellm/llms/soniox/common_utils.py new file mode 100644 index 00000000000..01f8062fc96 --- /dev/null +++ b/litellm/llms/soniox/common_utils.py @@ -0,0 +1,274 @@ +""" +Shared utilities for the Soniox provider (https://soniox.com). +""" + +from typing import Any, Dict, List, Optional + +from litellm.llms.base_llm.chat.transformation import BaseLLMException + +# Soniox API base URL. +SONIOX_API_BASE: str = "https://api.soniox.com" + +# Default polling interval in seconds when waiting for an async transcription +# to finish. Mirrors the Soniox SDK default. +SONIOX_DEFAULT_POLL_INTERVAL: float = 1.0 + +# Minimum polling interval (in seconds) the server will accept from caller- +# supplied `soniox_polling_interval` kwargs. Prevents an authenticated caller +# from forcing a worker into a tight poll loop with a zero/near-zero interval. +SONIOX_MIN_POLL_INTERVAL: float = 0.5 + +# Maximum polling interval (in seconds). Prevents a caller from setting an +# excessively large or non-finite interval that would keep a worker sleeping +# far longer than necessary between status checks. +SONIOX_MAX_POLL_INTERVAL: float = 60.0 + +# Default maximum number of polling attempts (1800 attempts * 1s ~= 30 minutes). +SONIOX_DEFAULT_MAX_POLL_ATTEMPTS: int = 1800 + +# Hard upper bound on polling attempts. Combined with `SONIOX_MIN_POLL_INTERVAL` +# this caps total polling time per request at ~3000s (50 minutes), preventing a +# caller from pinning a worker indefinitely via a huge attempt count. +SONIOX_MAX_POLL_ATTEMPTS: int = 6000 + +# Default cleanup behaviour: delete both the uploaded file (if any) and the +# transcription record after the transcript has been fetched. +SONIOX_DEFAULT_CLEANUP: List[str] = ["file", "transcription"] + +# Body fields that may carry secrets and must be redacted before being +# forwarded to logging callbacks. Soniox accepts a webhook auth header value +# alongside the create-transcription request; that value lets the recipient +# authenticate webhook callbacks and must not leak into observability sinks. +SONIOX_SECRET_FIELDS: List[str] = ["webhook_auth_header_value"] + + +class SonioxException(BaseLLMException): + """Provider-specific exception class for Soniox.""" + + pass + + +def get_soniox_api_key(api_key: Optional[str] = None) -> Optional[str]: + """Resolve the Soniox API key from arg or env var.""" + # Local import to avoid a circular import: litellm.secret_managers.main + # imports from litellm at top-level. + from litellm.secret_managers.main import get_secret_str + + return api_key or get_secret_str("SONIOX_API_KEY") + + +def get_soniox_api_base(api_base: Optional[str] = None) -> str: + """Resolve the Soniox API base URL from arg or env var (defaults to public API).""" + from litellm.secret_managers.main import get_secret_str + + base = api_base or get_secret_str("SONIOX_API_BASE") or SONIOX_API_BASE + return base.rstrip("/") + + +def render_soniox_tokens(tokens: List[Dict[str, Any]]) -> str: + """ + Render a list of Soniox tokens to a readable transcript string. + + Mirrors the behaviour of the official Soniox SDK's `renderTokens` helper: + - When the speaker changes, a `Speaker N:` tag is inserted. + - When the language changes, a `[lang]` (or `[Translation][lang]`) tag is + inserted. + + If neither speaker nor language information is present on any token (i.e. + diarization and language identification are disabled), the function simply + concatenates the token texts. + """ + if not tokens: + return "" + + text_parts: List[str] = [] + current_speaker: Optional[Any] = None + current_language: Optional[Any] = None + + for token in tokens: + text = token.get("text", "") + speaker = token.get("speaker") + language = token.get("language") + is_translation = token.get("translation_status") == "translation" + + # Speaker changed -> emit a speaker tag. + if speaker is not None and speaker != current_speaker: + if current_speaker is not None: + text_parts.append("\n\n") + current_speaker = speaker + current_language = None # reset language whenever speaker changes + text_parts.append(f"Speaker {current_speaker}:") + + # Language changed -> emit a language (or translation) tag. + if language is not None and language != current_language: + current_language = language + prefix = "[Translation] " if is_translation else "" + text_parts.append(f"\n{prefix}[{current_language}] ") + text = text.lstrip() if isinstance(text, str) else text + + text_parts.append(text) + + return "".join(text_parts) + + +# --------------------------------------------------------------------------- +# SRT / VTT subtitle rendering +# --------------------------------------------------------------------------- + +# Maximum number of tokens to group into a single subtitle cue. +_CUE_MAX_TOKENS: int = 15 + +# Maximum duration (in ms) for a single cue before forcing a break. +_CUE_MAX_DURATION_MS: int = 5000 + + +def _format_timestamp_srt(ms: int) -> str: + """Format milliseconds as SRT timestamp: HH:MM:SS,mmm""" + if ms < 0: + ms = 0 + hours = ms // 3_600_000 + ms %= 3_600_000 + minutes = ms // 60_000 + ms %= 60_000 + seconds = ms // 1_000 + millis = ms % 1_000 + return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}" + + +def _format_timestamp_vtt(ms: int) -> str: + """Format milliseconds as VTT timestamp: HH:MM:SS.mmm""" + if ms < 0: + ms = 0 + hours = ms // 3_600_000 + ms %= 3_600_000 + minutes = ms // 60_000 + ms %= 60_000 + seconds = ms // 1_000 + millis = ms % 1_000 + return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{millis:03d}" + + +def _group_tokens_into_cues( + tokens: List[Dict[str, Any]], +) -> List[Dict[str, Any]]: + """ + Group Soniox tokens into subtitle cues. + + Each cue has: + - start_ms: int + - end_ms: int + - text: str + + Grouping heuristics: + - A new cue starts when token count exceeds _CUE_MAX_TOKENS. + - A new cue starts when duration exceeds _CUE_MAX_DURATION_MS. + - A new cue starts when the speaker changes (if diarization is on). + - Tokens without timestamps are appended to the current cue. + """ + cues: List[Dict[str, Any]] = [] + current_tokens: List[str] = [] + current_start: Optional[int] = None + current_end: Optional[int] = None + current_speaker: Optional[Any] = None + + def _flush() -> None: + if current_tokens and current_start is not None: + text = "".join(current_tokens).strip() + if text: + cues.append( + { + "start_ms": current_start, + "end_ms": ( + current_end if current_end is not None else current_start + ), + "text": text, + } + ) + + for token in tokens: + start_ms = token.get("start_ms") + end_ms = token.get("end_ms") + text = token.get("text", "") + speaker = token.get("speaker") + + # Skip tokens with no timestamp data entirely if we have no cue started + if start_ms is None and current_start is None: + continue + + # Speaker change forces a new cue + if speaker is not None and speaker != current_speaker: + _flush() + current_tokens = [] + current_start = start_ms + current_end = end_ms + current_speaker = speaker + current_tokens.append(text) + continue + + # Duration or token count exceeded -> flush + should_break = False + if len(current_tokens) >= _CUE_MAX_TOKENS: + should_break = True + elif ( + current_start is not None + and start_ms is not None + and (start_ms - current_start) >= _CUE_MAX_DURATION_MS + ): + should_break = True + + if should_break: + _flush() + current_tokens = [] + current_start = start_ms + current_end = end_ms + current_tokens.append(text) + else: + if current_start is None: + current_start = start_ms + if end_ms is not None: + current_end = end_ms + current_tokens.append(text) + + _flush() + return cues + + +def render_soniox_tokens_as_srt(tokens: List[Dict[str, Any]]) -> str: + """ + Render Soniox tokens as SRT (SubRip) subtitle format. + + Returns an empty string if no tokens have timestamp data. + """ + cues = _group_tokens_into_cues(tokens) + if not cues: + return "" + + lines: List[str] = [] + for idx, cue in enumerate(cues, start=1): + start = _format_timestamp_srt(cue["start_ms"]) + end = _format_timestamp_srt(cue["end_ms"]) + lines.append(str(idx)) + lines.append(f"{start} --> {end}") + lines.append(cue["text"]) + lines.append("") # blank line between cues + + return "\n".join(lines) + + +def render_soniox_tokens_as_vtt(tokens: List[Dict[str, Any]]) -> str: + """ + Render Soniox tokens as WebVTT subtitle format. + + Returns the VTT header even if no cues are present. + """ + cues = _group_tokens_into_cues(tokens) + + lines: List[str] = ["WEBVTT", ""] + for cue in cues: + start = _format_timestamp_vtt(cue["start_ms"]) + end = _format_timestamp_vtt(cue["end_ms"]) + lines.append(f"{start} --> {end}") + lines.append(cue["text"]) + lines.append("") # blank line between cues + + return "\n".join(lines) diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py index e6e39651109..85c23d8603c 100644 --- a/litellm/llms/vertex_ai/common_utils.py +++ b/litellm/llms/vertex_ai/common_utils.py @@ -12,7 +12,11 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import unpack_defs from litellm.llms.base_llm.base_utils import BaseLLMModelInfo, BaseTokenCounter from litellm.llms.base_llm.chat.transformation import BaseLLMException from litellm.types.llms.openai import AllMessageValues -from litellm.types.llms.vertex_ai import PartType, Schema +from litellm.types.llms.vertex_ai import ( + VERTEX_AI_PROVIDER_METADATA_FIELDS, + PartType, + Schema, +) from litellm.types.utils import TokenCountResponse from litellm.utils import supports_response_schema, supports_system_messages @@ -27,6 +31,47 @@ class VertexAIError(BaseLLMException): super().__init__(message=message, status_code=status_code, headers=headers) +def redact_vertex_ai_metadata_from_logged_object(obj: Any) -> None: + if isinstance(obj, dict): + for field in VERTEX_AI_PROVIDER_METADATA_FIELDS: + if field in obj: + obj[field] = [] + hidden_params = obj.get("_hidden_params") + if isinstance(hidden_params, dict): + for field in VERTEX_AI_PROVIDER_METADATA_FIELDS: + hidden_params.pop(field, None) + return + + for field in VERTEX_AI_PROVIDER_METADATA_FIELDS: + if hasattr(obj, field): + setattr(obj, field, []) + hidden_params = getattr(obj, "_hidden_params", None) + if isinstance(hidden_params, dict): + for field in VERTEX_AI_PROVIDER_METADATA_FIELDS: + hidden_params.pop(field, None) + + +def redact_vertex_ai_metadata_from_litellm_params(model_call_details: dict) -> None: + """ + success_handler() merges response._hidden_params into + litellm_params.metadata['hidden_params'] before redaction runs, so the Vertex + metadata must be scrubbed from that copy too. + """ + litellm_params = model_call_details.get("litellm_params") + if not isinstance(litellm_params, dict): + return + + for metadata_key in ("metadata", "litellm_metadata"): + metadata = litellm_params.get(metadata_key) + if not isinstance(metadata, dict): + continue + hidden_params = metadata.get("hidden_params") + if not isinstance(hidden_params, dict): + continue + for field in VERTEX_AI_PROVIDER_METADATA_FIELDS: + hidden_params.pop(field, None) + + def vertex_request_labels_from_litellm_params( litellm_params: Optional[dict], ) -> Optional[Dict[str, str]]: diff --git a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py index 3f945adca0d..103801a1e8d 100644 --- a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py +++ b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py @@ -19,7 +19,7 @@ from litellm.types.llms.vertex_ai import ( VertexAICachedContentResponseObject, ) -from ..common_utils import VertexAIError +from ..common_utils import VertexAIError, get_vertex_base_url from ..vertex_llm_base import VertexBase from .transformation import ( separate_cached_messages, @@ -69,17 +69,13 @@ class ContextCachingEndpoints(VertexBase): elif custom_llm_provider == "vertex_ai": auth_header = vertex_auth_header endpoint = "cachedContents" - if vertex_location == "global": - url = f"https://aiplatform.googleapis.com/v1/projects/{vertex_project}/locations/{vertex_location}/{endpoint}" - else: - url = f"https://{vertex_location}-aiplatform.googleapis.com/v1/projects/{vertex_project}/locations/{vertex_location}/{endpoint}" + base_url = get_vertex_base_url(vertex_location) + url = f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/{endpoint}" else: auth_header = vertex_auth_header endpoint = "cachedContents" - if vertex_location == "global": - url = f"https://aiplatform.googleapis.com/v1beta1/projects/{vertex_project}/locations/{vertex_location}/{endpoint}" - else: - url = f"https://{vertex_location}-aiplatform.googleapis.com/v1beta1/projects/{vertex_project}/locations/{vertex_location}/{endpoint}" + base_url = get_vertex_base_url(vertex_location) + url = f"{base_url}/v1beta1/projects/{vertex_project}/locations/{vertex_location}/{endpoint}" return self._check_custom_proxy( api_base=api_base, @@ -337,6 +333,7 @@ class ContextCachingEndpoints(VertexBase): return messages, optional_params, None tools = optional_params.pop("tools", None) + tool_choice = optional_params.pop("tool_choice", None) ## AUTHORIZATION ## token, url = self._get_token_and_url_context_caching( @@ -371,7 +368,7 @@ class ContextCachingEndpoints(VertexBase): ## CHECK IF CACHED ALREADY generated_cache_key = local_cache_obj.get_cache_key( - messages=cached_messages, tools=tools, model=model + messages=cached_messages, tools=tools, tool_choice=tool_choice, model=model ) google_cache_name = self.check_cache( cache_key=generated_cache_key, @@ -402,6 +399,8 @@ class ContextCachingEndpoints(VertexBase): ) cached_content_request_body["tools"] = tools + if tool_choice is not None: + cached_content_request_body["toolConfig"] = tool_choice ## LOGGING logging_obj.pre_call( @@ -487,6 +486,7 @@ class ContextCachingEndpoints(VertexBase): return messages, optional_params, None tools = optional_params.pop("tools", None) + tool_choice = optional_params.pop("tool_choice", None) ## AUTHORIZATION ## token, url = self._get_token_and_url_context_caching( @@ -518,7 +518,7 @@ class ContextCachingEndpoints(VertexBase): ## CHECK IF CACHED ALREADY generated_cache_key = local_cache_obj.get_cache_key( - messages=cached_messages, tools=tools, model=model + messages=cached_messages, tools=tools, tool_choice=tool_choice, model=model ) google_cache_name = await self.async_check_cache( cache_key=generated_cache_key, @@ -550,6 +550,8 @@ class ContextCachingEndpoints(VertexBase): ) cached_content_request_body["tools"] = tools + if tool_choice is not None: + cached_content_request_body["toolConfig"] = tool_choice ## LOGGING logging_obj.pre_call( diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py index 5cd02293f14..3ec7b0814dd 100644 --- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py +++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py @@ -63,6 +63,7 @@ from litellm.types.llms.openai import ( OpenAIChatCompletionFinishReason, ) from litellm.types.llms.vertex_ai import ( + VERTEX_AI_PROVIDER_METADATA_FIELDS, VERTEX_CREDENTIALS_TYPES, Candidates, ContentType, @@ -1111,6 +1112,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): { "voice": "alloy", "format": "mp3", + "language_code": "en-US", } Expected output: @@ -1119,7 +1121,8 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): prebuiltVoiceConfig: { voiceName: "alloy", } - } + }, + languageCode: "en-US", } """ from litellm.types.llms.vertex_ai import ( @@ -1145,6 +1148,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): voice_config: VoiceConfig = {"prebuiltVoiceConfig": prebuilt_voice_config} speech_config["voiceConfig"] = voice_config + if "language_code" in value: + speech_config["languageCode"] = value["language_code"] + return cast(dict, speech_config) @staticmethod @@ -2253,6 +2259,71 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): citation_metadata, ) + @staticmethod + def _get_stream_chunk_attr(chunk: Any, field_name: str) -> Any: + if isinstance(chunk, dict): + value = chunk.get(field_name) + if value is not None: + return value + model_extra = chunk.get("model_extra") + if isinstance(model_extra, dict): + value = model_extra.get(field_name) + if value is not None: + return value + hidden_params = chunk.get("_hidden_params") + if isinstance(hidden_params, dict): + return hidden_params.get(field_name) + return None + return getattr(chunk, field_name, None) + + @staticmethod + def _set_stream_metadata_on_response( + model_response: Any, + grounding_metadata: List[dict], + url_context_metadata: List[dict], + safety_ratings: List[dict], + citation_metadata: List[dict], + ) -> None: + setattr(model_response, "vertex_ai_grounding_metadata", grounding_metadata) # type: ignore + if grounding_metadata: + model_response._hidden_params["vertex_ai_grounding_metadata"] = ( + grounding_metadata + ) + setattr(model_response, "vertex_ai_url_context_metadata", url_context_metadata) # type: ignore + if url_context_metadata: + model_response._hidden_params["vertex_ai_url_context_metadata"] = ( + url_context_metadata + ) + setattr(model_response, "vertex_ai_safety_ratings", safety_ratings) # type: ignore + setattr(model_response, "vertex_ai_safety_results", safety_ratings) # type: ignore + if safety_ratings: + model_response._hidden_params["vertex_ai_safety_ratings"] = safety_ratings + model_response._hidden_params["vertex_ai_safety_results"] = safety_ratings + setattr(model_response, "vertex_ai_citation_metadata", citation_metadata) # type: ignore + if citation_metadata: + model_response._hidden_params["vertex_ai_citation_metadata"] = ( + citation_metadata + ) + + def apply_assembled_streaming_response_metadata( + self, + response: ModelResponse, + chunks: List[Any], + ) -> None: + for field_name in VERTEX_AI_PROVIDER_METADATA_FIELDS: + merged: List[Any] = [] + for chunk in chunks: + value = VertexGeminiConfig._get_stream_chunk_attr(chunk, field_name) + if not value: + continue + if isinstance(value, list): + merged.extend(value) + else: + merged.append(value) + if merged: + setattr(response, field_name, merged) + response._hidden_params[field_name] = merged + @staticmethod def _convert_grounding_metadata_to_annotations( grounding_metadata: List[dict], @@ -3351,14 +3422,18 @@ class ModelResponseIterator: self.has_seen_tool_calls = True break - # Handle final chunk with finishReason but no content. - # _process_candidates skips candidates without "content", - # so the finish_reason from the final chunk is lost. + # _process_candidates skips candidates without a "content" part, so a + # content-less chunk leaves choices empty and the downstream streaming + # handler hits IndexError on choices[0]. This covers the final chunk + # (finishReason, no content) and mid-stream metadata-only chunks + # (grounding/web-search/thought, no content and no finishReason — seen + # with web_search + reasoning) by emitting an empty-delta choice. if not model_response.choices and _candidates: from litellm.types.utils import Delta, StreamingChoices for candidate in _candidates: finish_reason_str = candidate.get("finishReason") + mapped_finish_reason = None if finish_reason_str is not None: if self.has_seen_tool_calls: mapped_finish_reason = "tool_calls" @@ -3366,14 +3441,14 @@ class ModelResponseIterator: mapped_finish_reason = VertexGeminiConfig._check_finish_reason( None, finish_reason_str ) - choice = StreamingChoices( - finish_reason=mapped_finish_reason, - index=candidate.get("index", 0), - delta=Delta(content=None, role=None), - logprobs=None, - enhancements=None, - ) - model_response.choices.append(choice) + choice = StreamingChoices( + finish_reason=mapped_finish_reason, + index=candidate.get("index", 0), + delta=Delta(content=None, role=None), + logprobs=None, + enhancements=None, + ) + model_response.choices.append(choice) # Also handle the case where the final chunk has empty # content (e.g. text:"") WITH finishReason. In this case @@ -3385,10 +3460,13 @@ class ModelResponseIterator: if choice.finish_reason == "stop": choice.finish_reason = "tool_calls" - setattr(model_response, "vertex_ai_grounding_metadata", grounding_metadata) # type: ignore - setattr(model_response, "vertex_ai_url_context_metadata", url_context_metadata) # type: ignore - setattr(model_response, "vertex_ai_safety_ratings", safety_ratings) # type: ignore - setattr(model_response, "vertex_ai_citation_metadata", citation_metadata) # type: ignore + VertexGeminiConfig._set_stream_metadata_on_response( + model_response, + grounding_metadata, + url_context_metadata, + safety_ratings, + citation_metadata, + ) return ( grounding_metadata, diff --git a/litellm/llms/vertex_ai/image_generation/cost_calculator.py b/litellm/llms/vertex_ai/image_generation/cost_calculator.py index 012de5498cb..5c04ebf79ee 100644 --- a/litellm/llms/vertex_ai/image_generation/cost_calculator.py +++ b/litellm/llms/vertex_ai/image_generation/cost_calculator.py @@ -5,6 +5,7 @@ Vertex AI Image Generation Cost Calculator import litellm from litellm.litellm_core_utils.llm_cost_calc.utils import ( calculate_image_response_cost_from_usage, + calculate_image_response_web_search_cost, ) from litellm.types.utils import ImageResponse @@ -21,16 +22,20 @@ def cost_calculator( custom_llm_provider="vertex_ai", ) + web_search_cost = calculate_image_response_web_search_cost( + image_response=image_response, + custom_llm_provider="vertex_ai", + model_info=_model_info, + ) + token_based_cost = calculate_image_response_cost_from_usage( model=model, image_response=image_response, custom_llm_provider="vertex_ai", ) if token_based_cost is not None: - return token_based_cost + return token_based_cost + web_search_cost output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0 - num_images: int = 0 - if image_response.data: - num_images = len(image_response.data) - return output_cost_per_image * num_images + num_images: int = len(image_response.data) if image_response.data else 0 + return output_cost_per_image * num_images + web_search_cost diff --git a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py index f4bda8d1bed..103c7b2a28a 100644 --- a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py +++ b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py @@ -7,6 +7,10 @@ import litellm from litellm.llms.base_llm.image_generation.transformation import ( BaseImageGenerationConfig, ) +from litellm.llms.gemini.common_utils import ( + get_gemini_image_web_search_requests, + map_gemini_image_tools_params, +) from litellm.llms.vertex_ai.common_utils import get_vertex_base_url from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexLLM from litellm.secret_managers.main import get_secret_str @@ -52,6 +56,8 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): "aspect_ratio", "imageSize", "image_size", + "tools", + "web_search_options", ] def map_openai_params( @@ -77,9 +83,10 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): mapped_params["aspectRatio"] = v elif k in ("imageSize", "image_size"): mapped_params["imageSize"] = v - else: + elif k not in ("tools", "web_search_options"): mapped_params[k] = v + mapped_params = map_gemini_image_tools_params(non_default_params, mapped_params) return mapped_params def _map_size_to_aspect_ratio(self, size: str) -> str: @@ -247,6 +254,11 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): "generationConfig": generation_config, } + if tools := optional_params.get("tools"): + request_body["tools"] = tools + if tool_config := optional_params.get("toolConfig"): + request_body["toolConfig"] = tool_config + return request_body def _transform_image_usage(self, usage: dict) -> ImageUsage: @@ -324,4 +336,8 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): if usage_metadata := response_data.get("usageMetadata", None): model_response.usage = self._transform_image_usage(usage_metadata) + web_search_requests = get_gemini_image_web_search_requests(response_data) + if web_search_requests and model_response.usage is not None: + setattr(model_response.usage, "web_search_requests", web_search_requests) + return model_response diff --git a/litellm/llms/vertex_ai/realtime/transformation.py b/litellm/llms/vertex_ai/realtime/transformation.py index ea4dbccc8c8..d6441db7856 100644 --- a/litellm/llms/vertex_ai/realtime/transformation.py +++ b/litellm/llms/vertex_ai/realtime/transformation.py @@ -90,7 +90,8 @@ class VertexAIRealtimeConfig(GeminiRealtimeConfig): def get_audio_mime_type(self, input_audio_format: str = "pcm16") -> str: mime_types = { - "pcm16": "audio/pcm;rate=16000", + # Gemini Live native audio (OpenAI GA realtime default) is 24kHz PCM. + "pcm16": "audio/pcm;rate=24000", "g711_ulaw": "audio/pcmu", "g711_alaw": "audio/pcma", } diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py index 1e92754857b..8a92e7ec4a5 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py @@ -17,6 +17,9 @@ from ..output_params_utils import sanitize_vertex_anthropic_output_params class VertexAIPartnerModelsAnthropicMessagesConfig(AnthropicMessagesConfig, VertexBase): + def should_strip_billing_metadata(self) -> bool: + return True + def validate_anthropic_messages_environment( self, headers: dict, diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py index c852909d475..ae8bdc55443 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py @@ -52,6 +52,9 @@ class VertexAIAnthropicConfig(AnthropicConfig): def custom_llm_provider(self) -> Optional[str]: return "vertex_ai" + def should_strip_billing_metadata(self) -> bool: + return True + def _add_context_management_beta_headers( self, beta_set: set, context_management: dict ) -> None: diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py index c06928516ef..8019bb67991 100644 --- a/litellm/llms/xai/chat/transformation.py +++ b/litellm/llms/xai/chat/transformation.py @@ -5,6 +5,7 @@ import httpx import litellm from litellm._logging import verbose_logger from litellm.constants import XAI_API_BASE +from litellm.exceptions import AuthenticationError from litellm.litellm_core_utils.prompt_templates.common_utils import ( filter_value_from_dict, strip_name_from_messages, @@ -39,6 +40,72 @@ class XAIChatConfig(OpenAIGPTConfig): dynamic_api_key = XAIModelInfo.get_api_key(api_key) return api_base, dynamic_api_key + def validate_environment( + self, + headers: dict, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + from litellm.llms.xai.oauth import ( + XAIOAuthAuthenticator, + XAIOAuthError, + should_use_xai_oauth, + ) + + dynamic_api_key = XAIModelInfo.get_api_key(api_key) + if should_use_xai_oauth(litellm_params) and not dynamic_api_key: + try: + headers["Authorization"] = ( + f"Bearer {XAIOAuthAuthenticator().get_access_token()}" + ) + except XAIOAuthError as exc: + raise AuthenticationError( + model=model, + llm_provider=self.custom_llm_provider or "xai", + message=str(exc), + ) from exc + if "content-type" not in headers and "Content-Type" not in headers: + headers["Content-Type"] = "application/json" + return headers + + return super().validate_environment( + headers=headers, + model=model, + messages=messages, + optional_params=optional_params, + litellm_params=litellm_params, + api_key=dynamic_api_key, + api_base=api_base, + ) + + def get_complete_url( + self, + api_base: Optional[str], + api_key: Optional[str], + model: str, + optional_params: dict, + litellm_params: dict, + stream: Optional[bool] = None, + ) -> str: + from litellm.llms.xai.oauth import XAIOAuthAuthenticator, should_use_xai_oauth + + dynamic_api_key = XAIModelInfo.get_api_key(api_key) + if should_use_xai_oauth(litellm_params) and not dynamic_api_key: + api_base = XAIOAuthAuthenticator().get_api_base() + + return super().get_complete_url( + api_base=api_base, + api_key=dynamic_api_key, + model=model, + optional_params=optional_params, + litellm_params=litellm_params, + stream=stream, + ) + def get_supported_openai_params(self, model: str) -> list: base_openai_params = [ "logit_bias", diff --git a/litellm/llms/xai/oauth.py b/litellm/llms/xai/oauth.py new file mode 100644 index 00000000000..30c717b7ca0 --- /dev/null +++ b/litellm/llms/xai/oauth.py @@ -0,0 +1,421 @@ +import base64 +import hashlib +import json +import os +import secrets +import sys +import threading +import time +import uuid +import webbrowser +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import Any, Dict, Optional, Tuple, Union +from urllib.parse import parse_qs, urlencode, urlparse + +import httpx + +from litellm._logging import verbose_logger +from litellm.constants import XAI_API_BASE +from litellm.llms.custom_httpx.http_handler import HTTPHandler, _get_httpx_client +from litellm.secret_managers.main import get_secret_str + +XAI_OAUTH_ISSUER = "https://auth.x.ai" +XAI_OAUTH_DISCOVERY_URL = f"{XAI_OAUTH_ISSUER}/.well-known/openid-configuration" +XAI_OAUTH_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828" +XAI_OAUTH_SCOPE = "openid profile email offline_access grok-cli:access api:access" +XAI_OAUTH_REDIRECT_HOST = "127.0.0.1" +XAI_OAUTH_REDIRECT_PORT = 56121 +XAI_OAUTH_REDIRECT_PATH = "/callback" +XAI_OAUTH_EXPIRY_SKEW_SECONDS = 120 +XAI_OAUTH_CALLBACK_TIMEOUT_SECONDS = 180 +_XAI_OAUTH_REFRESH_LOCK = threading.Lock() + + +class XAIOAuthError(Exception): + pass + + +class XAIOAuthLoginRequiredError(XAIOAuthError): + pass + + +class _CallbackHandler(BaseHTTPRequestHandler): + server: "_CallbackServer" + + def do_GET(self) -> None: + parsed = urlparse(self.path) + if parsed.path != XAI_OAUTH_REDIRECT_PATH: + self.send_response(404) + self.end_headers() + return + + params = parse_qs(parsed.query) + result = { + "code": params.get("code", [None])[0], + "state": params.get("state", [None])[0], + "error": params.get("error", [None])[0], + "error_description": params.get("error_description", [None])[0], + } + self.server.callback_result = result + + if result["state"] != self.server.expected_state: + self.send_response(400) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.end_headers() + self.wfile.write( + b"

xAI authorization state mismatch.

" + ) + return + + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.end_headers() + body = ( + b"

xAI authorization failed.

You can close this tab." + if result["error"] + else b"

xAI authorization received.

You can close this tab." + ) + self.wfile.write(body) + + def log_message(self, format: str, *args: Any) -> None: + return + + +class _CallbackServer(HTTPServer): + expected_state: str + callback_result: Optional[Dict[str, Optional[str]]] + + +class XAIOAuthAuthenticator: + def __init__( + self, http_client: Optional[Union[httpx.Client, HTTPHandler]] = None + ) -> None: + self.token_dir = get_secret_str("XAI_OAUTH_TOKEN_DIR") or os.path.expanduser( + "~/.config/litellm/xai_oauth" + ) + self.auth_file = os.path.join( + self.token_dir, get_secret_str("XAI_OAUTH_AUTH_FILE") or "auth.json" + ) + self.http_client = http_client + + def get_api_base(self) -> str: + return ( + get_secret_str("XAI_OAUTH_API_BASE") + or get_secret_str("XAI_API_BASE") + or XAI_API_BASE + ) + + def get_access_token(self) -> str: + auth_data = self._read_auth_file() + if not auth_data: + raise XAIOAuthLoginRequiredError( + "xAI OAuth login required. Run `litellm xai-oauth login`." + ) + + access_token = auth_data.get("access_token") + if access_token and not self._is_expired(auth_data): + return access_token + + refresh_token = auth_data.get("refresh_token") + if not refresh_token: + raise XAIOAuthLoginRequiredError( + "xAI OAuth refresh token missing. Run `litellm xai-oauth login`." + ) + + with _XAI_OAUTH_REFRESH_LOCK: + locked_auth_data = self._read_auth_file() or auth_data + access_token = locked_auth_data.get("access_token") + if access_token and not self._is_expired(locked_auth_data): + return access_token + + refreshed = self._refresh_tokens(locked_auth_data) + return refreshed["access_token"] + + def login(self, force: bool = False, no_browser: bool = False) -> Dict[str, Any]: + existing = self._read_auth_file() + if existing and not force and existing.get("access_token"): + if not self._is_expired(existing): + return existing + if existing.get("refresh_token"): + try: + return self._refresh_tokens(existing) + except XAIOAuthError: + pass + + discovery = self._discover() + verifier, challenge = self._pkce_pair() + state = uuid.uuid4().hex + nonce = uuid.uuid4().hex + server, redirect_uri = self._start_callback_server(state) + authorize_url = self._build_authorize_url( + authorization_endpoint=discovery["authorization_endpoint"], + redirect_uri=redirect_uri, + challenge=challenge, + state=state, + nonce=nonce, + ) + + if no_browser or not webbrowser.open(authorize_url): + sys.stdout.write( + f"Open this URL to authenticate with xAI:\n{authorize_url}\n" + ) + sys.stdout.flush() + + result = self._wait_for_callback(server) + if result.get("state") != state: + raise XAIOAuthError("xAI OAuth state mismatch") + if result.get("error"): + description = result.get("error_description") or result["error"] + raise XAIOAuthError(f"xAI authorization failed: {description}") + code = result.get("code") + if not code: + raise XAIOAuthError("xAI authorization failed: no code returned") + + token_payload = self._exchange_token( + discovery["token_endpoint"], + { + "grant_type": "authorization_code", + "code": code, + "redirect_uri": redirect_uri, + "client_id": XAI_OAUTH_CLIENT_ID, + "code_verifier": verifier, + }, + ) + auth_data = self._build_auth_record(token_payload, discovery["token_endpoint"]) + self._write_auth_file(auth_data) + return auth_data + + def _client(self) -> Union[httpx.Client, HTTPHandler]: + return self.http_client or _get_httpx_client() + + def _ensure_token_dir(self) -> None: + os.makedirs(self.token_dir, mode=0o700, exist_ok=True) + try: + os.chmod(self.token_dir, 0o700) + except OSError: + verbose_logger.debug("Could not chmod xAI OAuth token directory") + + def _read_auth_file(self) -> Optional[Dict[str, Any]]: + try: + with open(self.auth_file, "r") as f: + data = json.load(f) + return data if isinstance(data, dict) else None + except (IOError, json.JSONDecodeError): + return None + + def _write_auth_file(self, data: Dict[str, Any]) -> None: + self._ensure_token_dir() + tmp_file = os.path.join( + self.token_dir, + f".{os.path.basename(self.auth_file)}.{uuid.uuid4().hex}.tmp", + ) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + fd = os.open(tmp_file, flags, 0o600) + try: + with os.fdopen(fd, "w") as f: + json.dump(data, f) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp_file, self.auth_file) + try: + os.chmod(self.auth_file, 0o600) + except OSError: + verbose_logger.debug("Could not chmod xAI OAuth auth file") + except Exception: + try: + os.close(fd) + except OSError: + pass + try: + os.unlink(tmp_file) + except OSError: + pass + raise + + def _is_expired(self, auth_data: Dict[str, Any]) -> bool: + expires_at = auth_data.get("expires_at") + if expires_at is None: + return True + try: + return time.time() >= float(expires_at) - XAI_OAUTH_EXPIRY_SKEW_SECONDS + except (TypeError, ValueError): + return True + + def _discover(self) -> Dict[str, str]: + try: + response = self._client().get( + XAI_OAUTH_DISCOVERY_URL, headers={"Accept": "application/json"} + ) + response.raise_for_status() + except httpx.HTTPStatusError as exc: + raise XAIOAuthError( + f"xAI OAuth discovery request failed: {exc.response.status_code} {exc.response.text}" + ) from exc + try: + data = response.json() + except ValueError as exc: + raise XAIOAuthError( + "xAI OAuth discovery response was not valid JSON" + ) from exc + authorization_endpoint = data.get("authorization_endpoint") + token_endpoint = data.get("token_endpoint") + if not authorization_endpoint or not token_endpoint: + raise XAIOAuthError("xAI OAuth discovery missing endpoints") + return { + "authorization_endpoint": self._validate_xai_endpoint( + authorization_endpoint + ), + "token_endpoint": self._validate_xai_endpoint(token_endpoint), + } + + def _validate_xai_endpoint(self, url: str) -> str: + parsed = urlparse(url) + host = (parsed.hostname or "").lower() + if parsed.scheme != "https" or (host != "x.ai" and not host.endswith(".x.ai")): + raise XAIOAuthError( + f"xAI OAuth discovery returned unexpected endpoint: {url}" + ) + return url + + def _pkce_pair(self) -> Tuple[str, str]: + verifier = ( + base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode() + ) + challenge = ( + base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) + .rstrip(b"=") + .decode() + ) + return verifier, challenge + + def _start_callback_server(self, state: str) -> Tuple[_CallbackServer, str]: + last_error: Optional[OSError] = None + for port in (XAI_OAUTH_REDIRECT_PORT, 0): + try: + server = _CallbackServer( + (XAI_OAUTH_REDIRECT_HOST, port), _CallbackHandler + ) + server.expected_state = state + server.callback_result = None + actual_port = server.server_address[1] + redirect_uri = f"http://{XAI_OAUTH_REDIRECT_HOST}:{actual_port}{XAI_OAUTH_REDIRECT_PATH}" + return server, redirect_uri + except OSError as exc: + last_error = exc + raise XAIOAuthError(f"Could not start xAI OAuth callback server: {last_error}") + + def _build_authorize_url( + self, + authorization_endpoint: str, + redirect_uri: str, + challenge: str, + state: str, + nonce: str, + ) -> str: + params = { + "response_type": "code", + "client_id": XAI_OAUTH_CLIENT_ID, + "redirect_uri": redirect_uri, + "scope": XAI_OAUTH_SCOPE, + "code_challenge": challenge, + "code_challenge_method": "S256", + "state": state, + "nonce": nonce, + } + return f"{authorization_endpoint}?{urlencode(params)}" + + def _wait_for_callback(self, server: _CallbackServer) -> Dict[str, Optional[str]]: + server.timeout = 1 + deadline = time.time() + XAI_OAUTH_CALLBACK_TIMEOUT_SECONDS + try: + while time.time() < deadline: + server.handle_request() + if server.callback_result is not None: + return server.callback_result + finally: + server.server_close() + raise XAIOAuthError("Timed out waiting for xAI OAuth callback") + + def _exchange_token( + self, token_endpoint: str, data: Dict[str, str] + ) -> Dict[str, Any]: + try: + response = self._client().post( + token_endpoint, + headers={ + "Accept": "application/json", + "Content-Type": "application/x-www-form-urlencoded", + }, + data=data, + ) + response.raise_for_status() + except httpx.HTTPStatusError as exc: + raise XAIOAuthError( + f"xAI OAuth token request failed: {exc.response.status_code} {exc.response.text}" + ) from exc + try: + body = response.json() + except ValueError as exc: + raise XAIOAuthError("xAI OAuth token response was not valid JSON") from exc + if not isinstance(body, dict): + raise XAIOAuthError("xAI OAuth token response was not an object") + return body + + def _build_auth_record( + self, + token_payload: Dict[str, Any], + token_endpoint: str, + fallback_refresh_token: Optional[str] = None, + ) -> Dict[str, Any]: + access_token = token_payload.get("access_token") + refresh_token = token_payload.get("refresh_token") or fallback_refresh_token + if not access_token: + raise XAIOAuthError("xAI OAuth token response missing access_token") + if not refresh_token: + raise XAIOAuthError("xAI OAuth token response missing refresh_token") + expires_in = token_payload.get("expires_in") or 3600 + try: + expires_at = int(time.time() + int(expires_in)) + except (TypeError, ValueError): + expires_at = int(time.time() + 3600) + return { + "access_token": access_token, + "refresh_token": refresh_token, + "id_token": token_payload.get("id_token"), + "token_type": token_payload.get("token_type") or "Bearer", + "token_endpoint": token_endpoint, + "expires_at": expires_at, + } + + def _refresh_tokens(self, auth_data: Dict[str, Any]) -> Dict[str, Any]: + token_endpoint = auth_data.get("token_endpoint") + if not token_endpoint: + token_endpoint = self._discover()["token_endpoint"] + token_endpoint = self._validate_xai_endpoint(token_endpoint) + refresh_token = auth_data.get("refresh_token") + if not refresh_token: + raise XAIOAuthLoginRequiredError( + "xAI OAuth refresh token missing. Run `litellm xai-oauth login`." + ) + + token_payload = self._exchange_token( + token_endpoint, + { + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "client_id": XAI_OAUTH_CLIENT_ID, + }, + ) + refreshed = self._build_auth_record( + token_payload, + token_endpoint, + fallback_refresh_token=refresh_token, + ) + self._write_auth_file(refreshed) + return refreshed + + +def should_use_xai_oauth(litellm_params: Optional[Dict[str, Any]]) -> bool: + return bool((litellm_params or {}).get("use_xai_oauth")) diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py index 55805ddaede..f81e860a8ce 100644 --- a/litellm/llms/xai/responses/transformation.py +++ b/litellm/llms/xai/responses/transformation.py @@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union import litellm from litellm._logging import verbose_logger from litellm.constants import XAI_API_BASE +from litellm.exceptions import AuthenticationError from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig from litellm.llms.xai.common_utils import XAIModelInfo from litellm.secret_managers.main import get_secret_str @@ -220,10 +221,27 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): litellm_params.api_key, legacy_generic_before_env=True ) + if not api_key: + from litellm.llms.xai.oauth import ( + XAIOAuthAuthenticator, + XAIOAuthError, + should_use_xai_oauth, + ) + + if should_use_xai_oauth(litellm_params.model_dump()): + try: + api_key = XAIOAuthAuthenticator().get_access_token() + except XAIOAuthError as exc: + raise AuthenticationError( + model=model, + llm_provider=self.custom_llm_provider.value, + message=str(exc), + ) from exc + if not api_key: raise ValueError( "XAI API key is required. Set api_key, litellm.xai_key, " - "litellm.api_key, or XAI_API_KEY." + "litellm.api_key, XAI_API_KEY, or use_xai_oauth=True." ) headers.update( @@ -244,12 +262,20 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): Returns: str: The full URL for the XAI /responses endpoint """ - api_base = ( - api_base - or litellm.api_base - or get_secret_str("XAI_API_BASE") - or XAI_API_BASE + from litellm.llms.xai.oauth import XAIOAuthAuthenticator, should_use_xai_oauth + + api_key = XAIModelInfo.get_api_key( + litellm_params.get("api_key"), legacy_generic_before_env=True ) + if should_use_xai_oauth(litellm_params) and not api_key: + api_base = XAIOAuthAuthenticator().get_api_base() + else: + api_base = ( + api_base + or litellm.api_base + or get_secret_str("XAI_API_BASE") + or XAI_API_BASE + ) # Remove trailing slashes api_base = api_base.rstrip("/") diff --git a/litellm/llms/you_com/__init__.py b/litellm/llms/you_com/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/litellm/llms/you_com/search/__init__.py b/litellm/llms/you_com/search/__init__.py new file mode 100644 index 00000000000..41bd9ce6b1a --- /dev/null +++ b/litellm/llms/you_com/search/__init__.py @@ -0,0 +1,7 @@ +""" +You.com Search API module. +""" + +from litellm.llms.you_com.search.transformation import YouComSearchConfig + +__all__ = ["YouComSearchConfig"] diff --git a/litellm/llms/you_com/search/transformation.py b/litellm/llms/you_com/search/transformation.py new file mode 100644 index 00000000000..3c94b991735 --- /dev/null +++ b/litellm/llms/you_com/search/transformation.py @@ -0,0 +1,193 @@ +""" +Calls You.com's /v1/search endpoint to search the web. + +You.com API Reference: https://you.com/docs/api-reference/search/v1-search +OpenAPI spec: https://you.com/specs/openapi_search_v1.yaml +""" + +from typing import Dict, List, Optional, TypedDict, Union + +import httpx + +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.base_llm.search.transformation import ( + BaseSearchConfig, + SearchResponse, + SearchResult, +) +from litellm.secret_managers.main import get_secret_str + + +class _YouComSearchRequestRequired(TypedDict): + """Required fields for You.com Search API request.""" + + query: str + + +class YouComSearchRequest(_YouComSearchRequestRequired, total=False): + """ + You.com Search API request format. + Based on: https://you.com/specs/openapi_search_v1.yaml + """ + + count: int + country: str + language: str + freshness: str + include_domains: List[str] + exclude_domains: List[str] + safesearch: str + + +class YouComSearchConfig(BaseSearchConfig): + # Keyed tier (higher rate limits): authenticate with X-API-Key. + YOU_COM_API_BASE = "https://ydc-index.io" + # Keyless free tier: IP-throttled (100 queries/day) and requires no auth. + # Used automatically when YOUCOM_API_KEY is not set. + YOU_COM_FREE_API_BASE = "https://api.you.com/v1/agents/search" + + @staticmethod + def ui_friendly_name() -> str: + return "You.com" + + def validate_environment( + self, + headers: Dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + **kwargs, + ) -> Dict: + """ + Set headers for the You.com Search API. + + If YOUCOM_API_KEY (or an explicit api_key) is present, use the keyed + endpoint with the `X-API-Key` header. Otherwise fall through to the + keyless free tier; no auth header is required. + """ + api_key = api_key or get_secret_str("YOUCOM_API_KEY") + headers["Content-Type"] = "application/json" + # Pin Accept-Encoding to identity: the keyless `api.you.com/v1/agents/search` + # endpoint advertises gzip content-encoding but returns body bytes the + # decoder rejects, which surfaces as httpx.DecodingError through litellm's + # http handler. Identity is harmless on the keyed endpoint. + headers.setdefault("Accept-Encoding", "identity") + if api_key: + headers["X-API-Key"] = api_key + return headers + + def get_complete_url( + self, + api_base: Optional[str], + optional_params: dict, + data: Optional[Union[Dict, List[Dict]]] = None, + **kwargs, + ) -> str: + """ + Pick the endpoint based on whether an API key is configured. + + - api_base explicit override -> use it as-is (normalized) + - YOUCOM_API_KEY set -> keyed endpoint (ydc-index.io/v1/search) + - no key -> keyless free tier (api.you.com/v1/agents/search) + """ + if api_base is None: + api_base = get_secret_str("YOUCOM_API_BASE") + + if api_base is None: + api_key = kwargs.get("api_key") or get_secret_str("YOUCOM_API_KEY") + if api_key: + api_base = self.YOU_COM_API_BASE + else: + # Keyless free tier already includes the full path. + return self.YOU_COM_FREE_API_BASE + + api_base = api_base.rstrip("/") + + if not api_base.endswith("/v1/search") and not api_base.endswith( + "/v1/agents/search" + ): + api_base = f"{api_base}/v1/search" + + return api_base + + def transform_search_request( + self, + query: Union[str, List[str]], + optional_params: dict, + **kwargs, + ) -> Dict: + """ + Transform Search request to You.com API format. + + Perplexity unified spec → You.com mappings: + - query → query + - max_results → count + - search_domain_filter → include_domains + - country → country + - max_tokens_per_page → (not applicable, ignored) + """ + if isinstance(query, list): + query = " ".join(query) + + request_data: YouComSearchRequest = { + "query": query, + } + + if "max_results" in optional_params: + request_data["count"] = optional_params["max_results"] + + if "search_domain_filter" in optional_params: + request_data["include_domains"] = optional_params["search_domain_filter"] + + if "country" in optional_params: + request_data["country"] = optional_params["country"].lower() + + result_data = dict(request_data) + + for param, value in optional_params.items(): + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): + result_data[param] = value + + return result_data + + def transform_search_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + **kwargs, + ) -> SearchResponse: + """ + Transform You.com API response to LiteLLM unified SearchResponse format. + + You.com → LiteLLM mappings (for both `results.web[]` and `results.news[]`): + - title → SearchResult.title + - url → SearchResult.url + - snippets[0] → SearchResult.snippet (falls back to `description`) + - page_age → SearchResult.date + """ + response_json = raw_response.json() + raw_results = response_json.get("results") or {} + + web_results = raw_results.get("web") or [] + news_results = raw_results.get("news") or [] + + results: List[SearchResult] = [] + for item in list(web_results) + list(news_results): + snippets = item.get("snippets") or [] + snippet = snippets[0] if snippets else item.get("description", "") + results.append( + SearchResult( + title=item.get("title", ""), + url=item.get("url", ""), + snippet=snippet, + date=item.get("page_age"), + last_updated=None, + ) + ) + + return SearchResponse( + results=results, + object="search", + ) diff --git a/litellm/main.py b/litellm/main.py index 5f5fe9ba359..792efe8243d 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -86,6 +86,7 @@ from litellm.litellm_core_utils.audio_utils.utils import ( get_audio_file_for_health_check, ) from litellm.litellm_core_utils.completion_timeout import CompletionTimeout +from litellm.litellm_core_utils.get_litellm_params import OPTIONAL_KWARGS_KEYS from litellm.litellm_core_utils.dd_tracing import tracer from litellm.litellm_core_utils.get_provider_specific_headers import ( ProviderSpecificHeaderUtils, @@ -1322,7 +1323,9 @@ def completion( # type: ignore # noqa: PLR0915 preset_cache_key = kwargs.get("preset_cache_key", None) hf_model_name = kwargs.get("hf_model_name", None) supports_system_message = kwargs.get("supports_system_message", None) - base_model = kwargs.get("base_model", None) + base_model = kwargs.get("base_model", None) or ( + model_info.get("base_model") if isinstance(model_info, dict) else None + ) ### DISABLE FLAGS ### disable_add_transform_inline_image_block = kwargs.get( "disable_add_transform_inline_image_block", None @@ -1405,11 +1408,19 @@ def completion( # type: ignore # noqa: PLR0915 if deployment_id is not None: # azure llms model = deployment_id custom_llm_provider = "azure" + _supplemental_provider_params = { + k: kwargs[k] for k in OPTIONAL_KWARGS_KEYS if k in kwargs + } model, custom_llm_provider, dynamic_api_key, api_base = get_llm_provider( model=model, custom_llm_provider=custom_llm_provider, api_base=api_base, api_key=api_key, + litellm_params=( + GenericLiteLLMParams(**_supplemental_provider_params) + if _supplemental_provider_params + else None + ), ) ## RESPONSES API BRIDGE LOGIC ## - check early and normalize model name @@ -1534,11 +1545,7 @@ def completion( # type: ignore # noqa: PLR0915 "logit_bias": logit_bias, "user": user, # params to identify the model - "model": ( - model_info.get("base_model") - if isinstance(model_info, dict) and model_info.get("base_model") - else model - ), + "model": model, "custom_llm_provider": custom_llm_provider, "response_format": response_format, "seed": seed, @@ -1640,6 +1647,8 @@ def completion( # type: ignore # noqa: PLR0915 litellm_request_debug=kwargs.get("litellm_request_debug", False), tpm=kwargs.get("tpm"), rpm=kwargs.get("rpm"), + use_xai_oauth=kwargs.get("use_xai_oauth", False), + aws_bedrock_project_id=kwargs.get("aws_bedrock_project_id"), gigachat_scope=kwargs.get("gigachat_scope"), gigachat_auth_url=kwargs.get("gigachat_auth_url"), gigachat_access_token=kwargs.get("gigachat_access_token"), @@ -2139,9 +2148,6 @@ def completion( # type: ignore # noqa: PLR0915 headers = headers or litellm.headers - if extra_headers is not None: - optional_params["extra_headers"] = extra_headers - ## LOAD CONFIG - if set config = litellm.OpenAITextCompletionConfig.get_config() for k, v in config.items(): @@ -2167,6 +2173,7 @@ def completion( # type: ignore # noqa: PLR0915 _response = openai_text_completions.completion( model=model, messages=messages, + headers=headers, model_response=model_response, print_verbose=print_verbose, api_key=api_key, @@ -6660,7 +6667,7 @@ async def atranscription(*args, **kwargs) -> TranscriptionResponse: @client -def transcription( +def transcription( # noqa: PLR0915 model: str, file: FileTypes, ## OPTIONAL OPENAI PARAMS ## @@ -6852,6 +6859,35 @@ def transcription( else None ), ) + elif custom_llm_provider == "soniox": + from litellm.llms.soniox.audio_transcription.handler import ( + SonioxAudioTranscriptionHandler, + ) + + response = SonioxAudioTranscriptionHandler().audio_transcriptions( + model=model, + audio_file=file, + optional_params=optional_params, + litellm_params=litellm_params_dict, + model_response=model_response, + atranscription=atranscription, + client=( + client + if client is not None + and ( + isinstance(client, HTTPHandler) + or isinstance(client, AsyncHTTPHandler) + ) + else None + ), + timeout=timeout, + max_retries=max_retries, + logging_obj=litellm_logging_obj, + api_base=api_base, + api_key=api_key, + headers=extra_headers, + provider_config=provider_config, # type: ignore[arg-type] + ) elif provider_config is not None: response = base_llm_http_handler.audio_transcriptions( model=model, @@ -7737,6 +7773,9 @@ def stream_chunk_builder( # noqa: PLR0915 "cost", logging_obj._response_cost_calculator(result=response), ) + processor.apply_provider_assembled_streaming_metadata( + response, chunks, logging_obj + ) return response tool_call_chunks = [ @@ -7916,6 +7955,9 @@ def stream_chunk_builder( # noqa: PLR0915 usage, "cost", logging_obj._response_cost_calculator(result=response) ) + processor.apply_provider_assembled_streaming_metadata( + response, chunks, logging_obj + ) return response except Exception as e: verbose_logger.exception( diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index ed6de4fa6b7..01a01ea7a76 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -1156,6 +1156,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1202,6 +1203,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1233,6 +1235,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1264,6 +1267,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1295,6 +1299,139 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_native_structured_output": true, + "supports_max_reasoning_effort": true, + "supports_output_config": true, + "bedrock_output_config_effort_ceiling": "xhigh" + }, + "anthropic.claude-fable-5": { + "cache_creation_input_token_cost": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 2e-05, + "cache_read_input_token_cost": 1e-06, + "input_cost_per_token": 1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_native_structured_output": true, + "supports_max_reasoning_effort": true, + "supports_output_config": true, + "bedrock_output_config_effort_ceiling": "xhigh" + }, + "global.anthropic.claude-fable-5": { + "cache_creation_input_token_cost": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 2e-05, + "cache_read_input_token_cost": 1e-06, + "input_cost_per_token": 1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_native_structured_output": true, + "supports_max_reasoning_effort": true, + "supports_output_config": true, + "bedrock_output_config_effort_ceiling": "xhigh" + }, + "us.anthropic.claude-fable-5": { + "cache_creation_input_token_cost": 1.375e-05, + "cache_creation_input_token_cost_above_1hr": 2.2e-05, + "cache_read_input_token_cost": 1.1e-06, + "input_cost_per_token": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5.5e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_native_structured_output": true, + "supports_max_reasoning_effort": true, + "supports_output_config": true, + "bedrock_output_config_effort_ceiling": "xhigh" + }, + "eu.anthropic.claude-fable-5": { + "cache_creation_input_token_cost": 1.375e-05, + "cache_creation_input_token_cost_above_1hr": 2.2e-05, + "cache_read_input_token_cost": 1.1e-06, + "input_cost_per_token": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5.5e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1319,6 +1456,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1326,6 +1464,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1350,6 +1489,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1357,6 +1497,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1381,6 +1522,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1388,6 +1530,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1412,6 +1555,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1419,6 +1563,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1443,6 +1588,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1450,6 +1596,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -1458,6 +1605,37 @@ "supports_output_config": true, "bedrock_output_config_effort_ceiling": "xhigh" }, + "jp.anthropic.claude-opus-4-7": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_read_input_token_cost": 5.5e-07, + "input_cost_per_token": 5.5e-06, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "tool_use_system_prompt_tokens": 346, + "supports_native_structured_output": true, + "supports_max_reasoning_effort": true, + "supports_minimal_reasoning_effort": true + }, "anthropic.claude-sonnet-4-6": { "cache_creation_input_token_cost": 3.75e-06, "cache_creation_input_token_cost_above_1hr": 6e-06, @@ -2173,6 +2351,37 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_max_reasoning_effort": true + }, + "azure_ai/claude-fable-5": { + "input_cost_per_token": 1e-05, + "output_cost_per_token": 5e-05, + "litellm_provider": "azure_ai", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "cache_creation_input_token_cost": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 2e-05, + "cache_read_input_token_cost": 1e-06, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -2194,6 +2403,7 @@ "cache_creation_input_token_cost": 6.25e-06, "cache_creation_input_token_cost_above_1hr": 1e-05, "cache_read_input_token_cost": 5e-07, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -2201,6 +2411,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -4198,6 +4409,23 @@ "/v1/audio/transcriptions" ] }, + "azure/gpt-realtime-whisper": { + "input_cost_per_second": 0.0002833333333333333, + "litellm_provider": "azure", + "mode": "audio_transcription", + "source": "https://learn.microsoft.com/en-us/azure/ai-foundry/openai/concepts/gpt-realtime-whisper", + "supported_endpoints": [ + "/v1/realtime", + "/v1/realtime/transcription_sessions" + ], + "supported_modalities": [ + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true + }, "azure/gpt-5.1-2025-11-13": { "cache_read_input_token_cost": 1.25e-07, "cache_read_input_token_cost_priority": 2.5e-07, @@ -6853,6 +7081,43 @@ "/v1/images/generations" ] }, + "azure_ai/MAI-Image-2.5": { + "input_cost_per_image_token": 8e-06, + "input_cost_per_token": 5e-06, + "litellm_provider": "azure_ai", + "mode": "image_generation", + "output_cost_per_image": 0.05, + "output_cost_per_image_token": 4.7e-05, + "source": "https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/new-mai-models-in-microsoft-foundry-across-text-image-voice-and-speech/4524632", + "supported_endpoints": [ + "/v1/images/generations", + "/v1/images/edits" + ] + }, + "azure_ai/MAI-Image-2.5-Flash": { + "input_cost_per_image_token": 1.75e-06, + "input_cost_per_token": 1.75e-06, + "litellm_provider": "azure_ai", + "mode": "image_generation", + "output_cost_per_image": 0.0338, + "output_cost_per_image_token": 3.3e-05, + "source": "https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/new-mai-models-in-microsoft-foundry-across-text-image-voice-and-speech/4524632", + "supported_endpoints": [ + "/v1/images/generations", + "/v1/images/edits" + ] + }, + "azure_ai/MAI-Image-2e": { + "input_cost_per_token": 5e-06, + "litellm_provider": "azure_ai", + "mode": "image_generation", + "output_cost_per_image": 0.02, + "output_cost_per_image_token": 1.95e-05, + "source": "https://aka.ms/mai-image-2e-foundryblog", + "supported_endpoints": [ + "/v1/images/generations" + ] + }, "azure_ai/Llama-3.2-11B-Vision-Instruct": { "input_cost_per_token": 3.7e-07, "litellm_provider": "azure_ai", @@ -7309,6 +7574,45 @@ "supports_function_calling": true, "supports_tool_choice": true }, + "azure_ai/deepseek-v3.1": { + "input_cost_per_token": 1.23e-06, + "litellm_provider": "azure_ai", + "max_input_tokens": 131072, + "max_output_tokens": 131072, + "max_tokens": 131072, + "mode": "chat", + "output_cost_per_token": 4.94e-06, + "source": "https://azure.microsoft.com/en-us/pricing/details/ai-foundry-models/deepseek/", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true + }, + "azure_ai/deepseek-v4-pro": { + "input_cost_per_token": 1.74e-06, + "litellm_provider": "azure_ai", + "max_input_tokens": 1000000, + "max_output_tokens": 384000, + "max_tokens": 384000, + "mode": "chat", + "output_cost_per_token": 3.48e-06, + "source": "https://azure.microsoft.com/en-us/pricing/details/ai-foundry-models/deepseek/", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true + }, + "azure_ai/deepseek-v4-flash": { + "input_cost_per_token": 1.9e-07, + "litellm_provider": "azure_ai", + "max_input_tokens": 1000000, + "max_output_tokens": 384000, + "max_tokens": 384000, + "mode": "chat", + "output_cost_per_token": 5.1e-07, + "source": "https://azure.microsoft.com/en-us/pricing/details/ai-foundry-models/deepseek/", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true + }, "azure_ai/embed-v-4-0": { "input_cost_per_token": 1.2e-07, "litellm_provider": "azure_ai", @@ -10097,6 +10401,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -10131,6 +10436,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -10141,6 +10447,40 @@ }, "supports_output_config": true }, + "claude-fable-5": { + "cache_creation_input_token_cost": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 2e-05, + "cache_read_input_token_cost": 1e-06, + "input_cost_per_token": 1e-05, + "litellm_provider": "anthropic", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_max_reasoning_effort": true, + "provider_specific_entry": { + "us": 1.1 + }, + "supports_output_config": true + }, "claude-opus-4-8": { "cache_creation_input_token_cost": 6.25e-06, "cache_creation_input_token_cost_above_1hr": 1e-05, @@ -10165,6 +10505,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -13978,6 +14319,22 @@ "/v1/images/generations" ] }, + "fal_ai/fal-ai/nano-banana": { + "litellm_provider": "fal_ai", + "mode": "image_generation", + "output_cost_per_image": 0.039, + "supported_endpoints": [ + "/v1/images/generations" + ] + }, + "fal_ai/fal-ai/gemini-25-flash-image": { + "litellm_provider": "fal_ai", + "mode": "image_generation", + "output_cost_per_image": 0.039, + "supported_endpoints": [ + "/v1/images/generations" + ] + }, "featherless_ai/featherless-ai/Qwerky-72B": { "litellm_provider": "featherless_ai", "max_input_tokens": 32768, @@ -14234,10 +14591,10 @@ "mode": "chat", "output_cost_per_token": 4.4e-06, "source": "https://fireworks.ai/models/fireworks/glm-5p1", - "supports_function_calling": false, + "supports_function_calling": true, "supports_reasoning": true, - "supports_response_schema": false, - "supports_tool_choice": false + "supports_response_schema": true, + "supports_tool_choice": true }, "fireworks_ai/accounts/fireworks/models/gpt-oss-120b": { "input_cost_per_token": 1.5e-07, @@ -14515,10 +14872,10 @@ "mode": "chat", "output_cost_per_token": 4.4e-06, "source": "https://fireworks.ai/models/fireworks/glm-5p1", - "supports_function_calling": false, + "supports_function_calling": true, "supports_reasoning": true, - "supports_response_schema": false, - "supports_tool_choice": false + "supports_response_schema": true, + "supports_tool_choice": true }, "fireworks_ai/kimi-k2p5": { "cache_read_input_token_cost": 1e-07, @@ -24090,6 +24447,24 @@ "max_input_tokens": 200000, "max_output_tokens": 8192 }, + "minimax/MiniMax-M3": { + "input_cost_per_token": 3e-07, + "input_cost_per_token_above_512k_tokens": 6e-07, + "output_cost_per_token": 1.2e-06, + "output_cost_per_token_above_512k_tokens": 2.4e-06, + "cache_read_input_token_cost": 6e-08, + "cache_read_input_token_cost_above_512k_tokens": 1.2e-07, + "litellm_provider": "minimax", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_system_messages": true, + "supports_vision": true, + "max_input_tokens": 1000000, + "max_output_tokens": 128000 + }, "mistral.devstral-2-123b": { "input_cost_per_token": 4e-07, "litellm_provider": "bedrock_converse", @@ -24972,6 +25347,7 @@ }, "moonshot/kimi-k2-0711-preview": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-05-25", "input_cost_per_token": 6e-07, "litellm_provider": "moonshot", "max_input_tokens": 131072, @@ -24986,6 +25362,7 @@ }, "moonshot/kimi-k2-0905-preview": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-05-25", "input_cost_per_token": 6e-07, "litellm_provider": "moonshot", "max_input_tokens": 262144, @@ -25000,6 +25377,7 @@ }, "moonshot/kimi-k2-turbo-preview": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-05-25", "input_cost_per_token": 1.15e-06, "litellm_provider": "moonshot", "max_input_tokens": 262144, @@ -25024,6 +25402,7 @@ "source": "https://platform.moonshot.ai/docs/guide/kimi-k2-5-quickstart", "supports_function_calling": true, "supports_reasoning": true, + "supports_response_schema": true, "supports_tool_choice": true, "supports_video_input": true, "supports_vision": true @@ -25040,12 +25419,14 @@ "source": "https://platform.kimi.ai/docs/pricing/chat-k26", "supports_function_calling": true, "supports_reasoning": true, + "supports_response_schema": true, "supports_tool_choice": true, "supports_video_input": true, "supports_vision": true }, "moonshot/kimi-latest": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-01-28", "input_cost_per_token": 2e-06, "litellm_provider": "moonshot", "max_input_tokens": 131072, @@ -25060,6 +25441,7 @@ }, "moonshot/kimi-latest-128k": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-01-28", "input_cost_per_token": 2e-06, "litellm_provider": "moonshot", "max_input_tokens": 131072, @@ -25074,6 +25456,7 @@ }, "moonshot/kimi-latest-32k": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-01-28", "input_cost_per_token": 1e-06, "litellm_provider": "moonshot", "max_input_tokens": 32768, @@ -25088,6 +25471,7 @@ }, "moonshot/kimi-latest-8k": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-01-28", "input_cost_per_token": 2e-07, "litellm_provider": "moonshot", "max_input_tokens": 8192, @@ -25102,6 +25486,7 @@ }, "moonshot/kimi-thinking-preview": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2025-11-11", "input_cost_per_token": 6e-07, "litellm_provider": "moonshot", "max_input_tokens": 131072, @@ -25114,6 +25499,7 @@ }, "moonshot/kimi-k2-thinking": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-05-25", "input_cost_per_token": 6e-07, "litellm_provider": "moonshot", "max_input_tokens": 262144, @@ -25129,6 +25515,7 @@ }, "moonshot/kimi-k2-thinking-turbo": { "cache_read_input_token_cost": 1.5e-07, + "deprecation_date": "2026-05-25", "input_cost_per_token": 1.15e-06, "litellm_provider": "moonshot", "max_input_tokens": 262144, @@ -25152,9 +25539,11 @@ "output_cost_per_token": 5e-06, "source": "https://platform.moonshot.ai/docs/pricing", "supports_function_calling": true, + "supports_response_schema": true, "supports_tool_choice": true }, "moonshot/moonshot-v1-128k-0430": { + "deprecation_date": "2024-04-30", "input_cost_per_token": 2e-06, "litellm_provider": "moonshot", "max_input_tokens": 131072, @@ -25176,6 +25565,7 @@ "output_cost_per_token": 5e-06, "source": "https://platform.moonshot.ai/docs/pricing", "supports_function_calling": true, + "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true }, @@ -25189,9 +25579,11 @@ "output_cost_per_token": 3e-06, "source": "https://platform.moonshot.ai/docs/pricing", "supports_function_calling": true, + "supports_response_schema": true, "supports_tool_choice": true }, "moonshot/moonshot-v1-32k-0430": { + "deprecation_date": "2024-04-30", "input_cost_per_token": 1e-06, "litellm_provider": "moonshot", "max_input_tokens": 32768, @@ -25213,6 +25605,7 @@ "output_cost_per_token": 3e-06, "source": "https://platform.moonshot.ai/docs/pricing", "supports_function_calling": true, + "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true }, @@ -25226,9 +25619,11 @@ "output_cost_per_token": 2e-06, "source": "https://platform.moonshot.ai/docs/pricing", "supports_function_calling": true, + "supports_response_schema": true, "supports_tool_choice": true }, "moonshot/moonshot-v1-8k-0430": { + "deprecation_date": "2024-04-30", "input_cost_per_token": 2e-07, "litellm_provider": "moonshot", "max_input_tokens": 8192, @@ -25250,6 +25645,7 @@ "output_cost_per_token": 2e-06, "source": "https://platform.moonshot.ai/docs/pricing", "supports_function_calling": true, + "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true }, @@ -25263,6 +25659,7 @@ "output_cost_per_token": 5e-06, "source": "https://platform.moonshot.ai/docs/pricing", "supports_function_calling": true, + "supports_response_schema": true, "supports_tool_choice": true }, "morph/morph-v3-fast": { @@ -33878,6 +34275,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -33906,6 +34304,67 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_max_reasoning_effort": true + }, + "vertex_ai/claude-fable-5": { + "cache_creation_input_token_cost": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 2e-05, + "cache_read_input_token_cost": 1e-06, + "input_cost_per_token": 1e-05, + "litellm_provider": "vertex_ai-anthropic_models", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "supports_max_reasoning_effort": true + }, + "vertex_ai/claude-fable-5@default": { + "cache_creation_input_token_cost": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 2e-05, + "cache_read_input_token_cost": 1e-06, + "input_cost_per_token": 1e-05, + "litellm_provider": "vertex_ai-anthropic_models", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -33927,6 +34386,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -33934,6 +34394,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -33955,6 +34416,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -33962,6 +34424,7 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, + "supports_sampling_params": false, "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, @@ -36004,7 +36467,8 @@ "supports_prompt_caching": true, "supports_response_schema": false, "supports_tool_choice": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-3-beta": { "cache_read_input_token_cost": 7.5e-07, @@ -36203,7 +36667,8 @@ "supports_function_calling": true, "supports_prompt_caching": true, "supports_tool_choice": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-4-fast-non-reasoning": { "cache_read_input_token_cost": 5e-08, @@ -36220,7 +36685,8 @@ "supports_function_calling": true, "supports_prompt_caching": true, "supports_tool_choice": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-4-0709": { "input_cost_per_token": 3e-06, @@ -36236,7 +36702,8 @@ "supports_function_calling": true, "supports_prompt_caching": true, "supports_tool_choice": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-4-latest": { "input_cost_per_token": 3e-06, @@ -36294,7 +36761,8 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-4-1-fast-reasoning-latest": { "cache_read_input_token_cost": 5e-08, @@ -36315,7 +36783,8 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-4-1-fast-non-reasoning": { "cache_read_input_token_cost": 5e-08, @@ -36335,7 +36804,8 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-4-1-fast-non-reasoning-latest": { "cache_read_input_token_cost": 5e-08, @@ -36355,7 +36825,8 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "deprecation_date": "2026-05-15" }, "xai/grok-4.20-multi-agent-beta-0309": { "cache_read_input_token_cost": 2e-07, @@ -36506,7 +36977,8 @@ "supports_function_calling": true, "supports_prompt_caching": true, "supports_reasoning": true, - "supports_tool_choice": true + "supports_tool_choice": true, + "deprecation_date": "2026-05-15" }, "xai/grok-code-fast-1-0825": { "cache_read_input_token_cost": 2e-08, @@ -36521,7 +36993,8 @@ "supports_function_calling": true, "supports_prompt_caching": true, "supports_reasoning": true, - "supports_tool_choice": true + "supports_tool_choice": true, + "deprecation_date": "2026-05-15" }, "xai/grok-vision-beta": { "input_cost_per_image": 5e-06, @@ -40499,6 +40972,23 @@ "supports_system_messages": true, "supports_tool_choice": true }, + "gpt-realtime-whisper": { + "input_cost_per_second": 0.0002833333333333333, + "litellm_provider": "openai", + "mode": "audio_transcription", + "source": "https://platform.openai.com/docs/models/gpt-realtime-whisper", + "supported_endpoints": [ + "/v1/realtime", + "/v1/realtime/transcription_sessions" + ], + "supported_modalities": [ + "audio" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_input": true + }, "sora-2": { "litellm_provider": "openai", "mode": "video_generation", @@ -41223,6 +41713,46 @@ "supports_response_schema": true, "supports_tool_choice": true }, + "bedrock_mantle/openai.gpt-5.5": { + "input_cost_per_token": 5.5e-06, + "cache_read_input_token_cost": 5.5e-07, + "output_cost_per_token": 3.3e-05, + "litellm_provider": "bedrock_mantle", + "max_input_tokens": 272000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "responses", + "use_openai_responses_path": true, + "supported_endpoints": ["/v1/responses"], + "supported_modalities": ["text", "image"], + "supported_output_modalities": ["text"], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, + "bedrock_mantle/openai.gpt-5.4": { + "input_cost_per_token": 2.75e-06, + "cache_read_input_token_cost": 2.75e-07, + "output_cost_per_token": 1.65e-05, + "litellm_provider": "bedrock_mantle", + "max_input_tokens": 272000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "responses", + "use_openai_responses_path": true, + "supported_endpoints": ["/v1/responses"], + "supported_modalities": ["text", "image"], + "supported_output_modalities": ["text"], + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true + }, "volcengine/doubao-seed-2-0-pro-260215": { "litellm_provider": "volcengine", "max_input_tokens": 256000, @@ -41501,5 +42031,177 @@ "supports_vision": true, "supports_native_structured_output": true, "supports_pdf_input": true + }, + "soniox/stt-async-v4": { + "litellm_provider": "soniox", + "max_output_tokens": 8000, + "max_tokens": 8000, + "input_cost_per_second": 0.0, + "output_cost_per_second": 0.0000277778, + "mode": "audio_transcription", + "source": "https://soniox.com/pricing", + "supported_endpoints": [ + "/v1/audio/transcriptions" + ], + "supports_audio_input": true + }, + "tensormesh/Qwen/Qwen3.5-397B-A17B-FP8": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 6e-07, + "output_cost_per_token": 3.6e-06, + "cache_read_input_token_cost": 0, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 4.5e-07, + "output_cost_per_token": 1.8e-06, + "cache_read_input_token_cost": 0, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/Qwen/Qwen3.6-27B-FP8": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 3.2e-07, + "output_cost_per_token": 3.2e-06, + "cache_read_input_token_cost": 0, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/lukealonso/GLM-5.1-NVFP4-MTP": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 1.4e-06, + "output_cost_per_token": 4.4e-06, + "cache_read_input_token_cost": 0, + "max_input_tokens": 202752, + "max_output_tokens": 202752, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/deepseek-ai/DeepSeek-V4-Flash": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 2.8e-07, + "cache_read_input_token_cost": 0, + "max_input_tokens": 32768, + "max_output_tokens": 32768, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/moonshotai/Kimi-K2.6": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 9.6e-07, + "output_cost_per_token": 4e-06, + "cache_read_input_token_cost": 0, + "max_input_tokens": 32768, + "max_output_tokens": 32768, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/MiniMaxAI/MiniMax-M2.5": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 3e-07, + "output_cost_per_token": 1.2e-06, + "cache_read_input_token_cost": 0, + "max_input_tokens": 196608, + "max_output_tokens": 196608, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/google/gemma-4-31B-it": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 1.4e-07, + "output_cost_per_token": 5.6e-07, + "cache_read_input_token_cost": 0, + "max_input_tokens": 32768, + "max_output_tokens": 32768, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/openai/gpt-oss-120b": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 6e-07, + "cache_read_input_token_cost": 0, + "max_input_tokens": 131072, + "max_output_tokens": 131072, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" + }, + "tensormesh/openai/gpt-oss-20b": { + "litellm_provider": "tensormesh", + "mode": "chat", + "input_cost_per_token": 7e-08, + "output_cost_per_token": 2.8e-07, + "cache_read_input_token_cost": 0, + "max_input_tokens": 131072, + "max_output_tokens": 131072, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true, + "supports_prompt_caching": true, + "supports_system_messages": true, + "supports_reasoning": true, + "source": "https://serverless.tensormesh.ai/v1/models/openrouter" } -} +} \ No newline at end of file diff --git a/litellm/models/__init__.py b/litellm/models/__init__.py new file mode 100644 index 00000000000..7e2d2c0ed9d --- /dev/null +++ b/litellm/models/__init__.py @@ -0,0 +1,66 @@ +""" +Domain models for LiteLLM backend. +""" + +from litellm.models.access_group import LiteLLM_AccessGroupTable +from litellm.models.budget import ( + LiteLLM_BudgetTable, + LiteLLM_BudgetTableFull, + LiteLLM_TeamMemberTable, +) +from litellm.models.config import LiteLLM_Config +from litellm.models.credentials import ( + CreateCredentialItem, + CredentialBase, + CredentialItem, +) +from litellm.models.end_user import LiteLLM_EndUserTable +from litellm.models.managed_files import ( + LiteLLM_ManagedFileTable, + LiteLLM_ManagedObjectTable, + LiteLLM_ManagedVectorStoresTable, + LiteLLM_ManagedVectorStoreTable, +) +from litellm.models.mcp_server import LiteLLM_MCPServerTable +from litellm.models.model import LiteLLM_ProxyModelTable +from litellm.models.object_permission import LiteLLM_ObjectPermissionTable +from litellm.models.organization import LiteLLM_OrganizationTable +from litellm.models.organization_membership import LiteLLM_OrganizationMembershipTable +from litellm.models.project import LiteLLM_ProjectTable +from litellm.models.skills import LiteLLM_SkillsTable +from litellm.models.spend_logs import LiteLLM_ErrorLogs, LiteLLM_SpendLogs +from litellm.models.tag import LiteLLM_TagTable +from litellm.models.team import LiteLLM_TeamTable +from litellm.models.team_membership import LiteLLM_TeamMembership +from litellm.models.user import LiteLLM_UserTable +from litellm.models.verification_token import LiteLLM_VerificationToken + +__all__ = [ + "LiteLLM_AccessGroupTable", + "LiteLLM_BudgetTable", + "LiteLLM_BudgetTableFull", + "LiteLLM_TeamMemberTable", + "LiteLLM_Config", + "CredentialBase", + "CredentialItem", + "CreateCredentialItem", + "LiteLLM_EndUserTable", + "LiteLLM_ManagedFileTable", + "LiteLLM_ManagedObjectTable", + "LiteLLM_ManagedVectorStoreTable", + "LiteLLM_ManagedVectorStoresTable", + "LiteLLM_MCPServerTable", + "LiteLLM_ProxyModelTable", + "LiteLLM_ObjectPermissionTable", + "LiteLLM_OrganizationTable", + "LiteLLM_OrganizationMembershipTable", + "LiteLLM_ProjectTable", + "LiteLLM_SkillsTable", + "LiteLLM_ErrorLogs", + "LiteLLM_SpendLogs", + "LiteLLM_TagTable", + "LiteLLM_TeamTable", + "LiteLLM_TeamMembership", + "LiteLLM_UserTable", + "LiteLLM_VerificationToken", +] diff --git a/litellm/models/access_group.py b/litellm/models/access_group.py new file mode 100644 index 00000000000..682e779e531 --- /dev/null +++ b/litellm/models/access_group.py @@ -0,0 +1,26 @@ +""" +Access group table model. + +Canonical definition for ``litellm_accessgrouptable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import List, Optional + +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_AccessGroupTable(LiteLLMPydanticObjectBase): + access_group_id: str + access_group_name: str + description: Optional[str] = None + access_model_names: List[str] = [] + access_mcp_server_ids: List[str] = [] + access_agent_ids: List[str] = [] + assigned_team_ids: List[str] = [] + assigned_key_ids: List[str] = [] + created_at: Optional[datetime] = None + created_by: Optional[str] = None + updated_at: Optional[datetime] = None + updated_by: Optional[str] = None diff --git a/litellm/models/base.py b/litellm/models/base.py new file mode 100644 index 00000000000..01981297bd5 --- /dev/null +++ b/litellm/models/base.py @@ -0,0 +1,38 @@ +""" +Base model class for domain models. +""" + +from datetime import datetime +from typing import Any, Dict, Optional + +from pydantic import BaseModel, ConfigDict + + +class DomainModel(BaseModel): + """Base class for all domain models.""" + + model_config = ConfigDict( + from_attributes=True, + protected_namespaces=(), + extra="ignore", + ) + + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + + @classmethod + def from_db_record(cls, record: Any) -> "DomainModel": + """Create a domain model from a database record.""" + if record is None: + raise ValueError("Cannot create domain model from None record") + if isinstance(record, dict): + return cls(**record) + if hasattr(record, "model_dump") and callable(record.model_dump): + return cls(**record.model_dump()) + if hasattr(record, "dict") and callable(record.dict): + return cls(**record.dict()) + return cls(**dict(record)) + + def to_db_dict(self, exclude_unset: bool = False) -> Dict[str, Any]: + """Convert domain model to a dictionary for database operations.""" + return self.model_dump(exclude_none=True, exclude_unset=exclude_unset) diff --git a/litellm/models/budget.py b/litellm/models/budget.py new file mode 100644 index 00000000000..e7dfe2f8fbc --- /dev/null +++ b/litellm/models/budget.py @@ -0,0 +1,56 @@ +""" +Budget table model. + +Canonical definition for ``litellm_budgettable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import List, Optional + +from pydantic import ConfigDict + +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_BudgetTable(LiteLLMPydanticObjectBase): + """Represents user-controllable params for a LiteLLM_BudgetTable record. + + Budget-write paths use `model_fields.keys()` on this class as an allowlist + for user input. Keep server-managed fields (e.g. `budget_reset_at`) on + `LiteLLM_BudgetTableFull` so they aren't user-settable. + """ + + budget_id: Optional[str] = None + soft_budget: Optional[float] = None + max_budget: Optional[float] = None + max_parallel_requests: Optional[int] = None + tpm_limit: Optional[int] = None + rpm_limit: Optional[int] = None + model_max_budget: Optional[dict] = None + budget_duration: Optional[str] = None + allowed_models: Optional[List[str]] = ( + None # per-member model scope; empty = inherit team models + ) + + model_config = ConfigDict(protected_namespaces=()) + + +class LiteLLM_BudgetTableFull(LiteLLM_BudgetTable): + """LiteLLM_BudgetTable + server-managed fields returned on API responses.""" + + budget_reset_at: Optional[datetime] = None + created_at: datetime + + +class LiteLLM_TeamMemberTable(LiteLLM_BudgetTable): + """ + Used to track spend of a user_id within a team_id + """ + + spend: Optional[float] = None + user_id: Optional[str] = None + team_id: Optional[str] = None + budget_id: Optional[str] = None + + model_config = ConfigDict(protected_namespaces=()) diff --git a/litellm/models/config.py b/litellm/models/config.py new file mode 100644 index 00000000000..99b5c5692fd --- /dev/null +++ b/litellm/models/config.py @@ -0,0 +1,15 @@ +""" +Config table model. + +Canonical definition for ``litellm_config``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from typing import Dict + +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_Config(LiteLLMPydanticObjectBase): + param_name: str + param_value: Dict diff --git a/litellm/models/credentials.py b/litellm/models/credentials.py new file mode 100644 index 00000000000..b74ea055d21 --- /dev/null +++ b/litellm/models/credentials.py @@ -0,0 +1,31 @@ +""" +Credential table models. + +These are the canonical credential types for the proxy. They live in the model +layer; ``litellm.types.utils`` re-exports them for backwards compatibility. +""" + +from typing import Optional + +from pydantic import BaseModel, model_validator + + +class CredentialBase(BaseModel): + credential_name: str + credential_info: dict + + +class CredentialItem(CredentialBase): + credential_values: dict + + +class CreateCredentialItem(CredentialBase): + credential_values: Optional[dict] = None + model_id: Optional[str] = None + + @model_validator(mode="before") + @classmethod + def check_credential_params(cls, values): + if not values.get("credential_values") and not values.get("model_id"): + raise ValueError("Either credential_values or model_id must be set") + return values diff --git a/litellm/models/end_user.py b/litellm/models/end_user.py new file mode 100644 index 00000000000..15fd03ec2ca --- /dev/null +++ b/litellm/models/end_user.py @@ -0,0 +1,35 @@ +""" +End-user table model. + +Canonical definition for ``litellm_endusertable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from typing import Literal, Optional + +from pydantic import ConfigDict, model_validator + +from litellm.models.budget import LiteLLM_BudgetTable +from litellm.models.object_permission import LiteLLM_ObjectPermissionTable +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_EndUserTable(LiteLLMPydanticObjectBase): + user_id: str + blocked: bool + alias: Optional[str] = None + spend: float = 0.0 + allowed_model_region: Optional[Literal["eu", "us"]] = None + default_model: Optional[str] = None + litellm_budget_table: Optional[LiteLLM_BudgetTable] = None + object_permission_id: Optional[str] = None + object_permission: Optional[LiteLLM_ObjectPermissionTable] = None + + @model_validator(mode="before") + @classmethod + def set_model_info(cls, values): + if values.get("spend") is None: + values.update({"spend": 0.0}) + return values + + model_config = ConfigDict(protected_namespaces=()) diff --git a/litellm/models/managed_files.py b/litellm/models/managed_files.py new file mode 100644 index 00000000000..24154768860 --- /dev/null +++ b/litellm/models/managed_files.py @@ -0,0 +1,62 @@ +""" +Managed file, object, and vector store table models. + +Canonical definitions for the ``litellm_managed*`` tables. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import Any, Dict, List, Literal, Optional, Union + +from litellm.types.llms.base import LiteLLMPydanticObjectBase +from litellm.types.llms.openai import OpenAIFileObject, ResponsesAPIResponse +from litellm.types.utils import LiteLLMBatch, LiteLLMFineTuningJob + + +class LiteLLM_ManagedFileTable(LiteLLMPydanticObjectBase): + unified_file_id: str + file_object: Optional[OpenAIFileObject] = None + model_mappings: Dict[str, str] + flat_model_file_ids: List[str] + created_by: Optional[str] = None + team_id: Optional[str] = None + updated_by: Optional[str] = None + storage_backend: Optional[str] = None + storage_url: Optional[str] = None + + +class LiteLLM_ManagedObjectTable(LiteLLMPydanticObjectBase): + unified_object_id: str + model_object_id: str + file_purpose: Literal["batch", "fine-tune", "response", "container"] + file_object: Union[LiteLLMBatch, LiteLLMFineTuningJob, ResponsesAPIResponse] + created_by: Optional[str] = None + team_id: Optional[str] = None + + +class LiteLLM_ManagedVectorStoreTable(LiteLLMPydanticObjectBase): + """Table for managing vector stores with target_model_names support.""" + + unified_resource_id: str + resource_object: Optional[Any] = None + model_mappings: Dict[str, str] + flat_model_resource_ids: List[str] + created_by: Optional[str] = None + team_id: Optional[str] = None + updated_by: Optional[str] = None + storage_backend: Optional[str] = None + storage_url: Optional[str] = None + + +class LiteLLM_ManagedVectorStoresTable(LiteLLMPydanticObjectBase): + vector_store_id: str + custom_llm_provider: str + vector_store_name: Optional[str] + vector_store_description: Optional[str] + vector_store_metadata: Optional[Dict[str, Any]] + created_at: Optional[datetime] + updated_at: Optional[datetime] + litellm_credential_name: Optional[str] + litellm_params: Optional[Dict[str, Any]] + team_id: Optional[str] + user_id: Optional[str] diff --git a/litellm/models/mcp_server.py b/litellm/models/mcp_server.py new file mode 100644 index 00000000000..3d03eff6df8 --- /dev/null +++ b/litellm/models/mcp_server.py @@ -0,0 +1,103 @@ +""" +MCP server table model. + +Canonical definition for ``litellm_mcpservertable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +import enum +from datetime import datetime +from typing import Dict, List, Literal, Optional + +from pydantic import Field + +from litellm.types.llms.base import LiteLLMPydanticObjectBase +from litellm.types.mcp import MCPAuthType, MCPCredentials, MCPTransportType +from litellm.types.mcp_server.mcp_server_manager import MCPInfo + + +class MCPEnvVarScope(str, enum.Enum): + """Scope for an MCP server environment variable. + + - ``global``: value is provided by the admin and used for all users. + - ``user``: each user must provide their own value via the per-user + env-var endpoint. The admin-supplied ``value`` is treated as a + placeholder/hint and is not used at request time. + """ + + global_ = "global" + user = "user" + + +class MCPEnvVar(LiteLLMPydanticObjectBase): + """One environment variable for an MCP server. + + Variables can be interpolated into ``static_headers`` using ``${NAME}`` + syntax. ``scope=global`` values are stored on the server. ``scope=user`` + values are stored per-user in ``LiteLLM_MCPUserEnvVars`` and supplied by + each user. + """ + + name: str + value: str = "" + scope: MCPEnvVarScope = MCPEnvVarScope.global_ + description: Optional[str] = None + + +class LiteLLM_MCPServerTable(LiteLLMPydanticObjectBase): + """Represents a LiteLLM_MCPServerTable record""" + + server_id: str + server_name: Optional[str] = None + alias: Optional[str] = None + description: Optional[str] = None + url: Optional[str] = None + spec_path: Optional[str] = None + transport: MCPTransportType + auth_type: Optional[MCPAuthType] = None + credentials: Optional[MCPCredentials] = None + instructions: Optional[str] = None + created_at: Optional[datetime] = None + created_by: Optional[str] = None + updated_at: Optional[datetime] = None + updated_by: Optional[str] = None + teams: List[Dict[str, Optional[str]]] = Field(default_factory=list) + mcp_access_groups: List[str] = Field(default_factory=list) + allowed_tools: List[str] = Field(default_factory=list) + tool_name_to_display_name: Optional[Dict[str, str]] = None + tool_name_to_description: Optional[Dict[str, str]] = None + extra_headers: List[str] = Field(default_factory=list) + mcp_info: Optional[MCPInfo] = None + static_headers: Optional[Dict[str, str]] = None + env_vars: Optional[List[MCPEnvVar]] = None + status: Optional[Literal["healthy", "unhealthy", "unknown"]] = Field( + default="unknown", + description="Health status: 'healthy', 'unhealthy', 'unknown'", + ) + last_health_check: Optional[datetime] = None + health_check_error: Optional[str] = None + command: Optional[str] = None + args: List[str] = Field(default_factory=list) + env: Dict[str, str] = Field(default_factory=dict) + authorization_url: Optional[str] = None + token_url: Optional[str] = None + registration_url: Optional[str] = None + oauth2_flow: Optional[Literal["client_credentials", "authorization_code"]] = None + allow_all_keys: bool = False + available_on_public_internet: bool = True + delegate_auth_to_upstream: bool = False + oauth_passthrough: bool = False + is_byok: bool = False + byok_description: List[str] = Field(default_factory=list) + byok_api_key_help_url: Optional[str] = None + has_user_credential: Optional[bool] = None + source_url: Optional[str] = None + timeout: Optional[float] = None + approval_status: Optional[str] = Field( + default="active", + description="Approval status: 'pending_review', 'active', 'rejected'", + ) + submitted_by: Optional[str] = None + submitted_at: Optional[datetime] = None + reviewed_at: Optional[datetime] = None + review_notes: Optional[str] = None diff --git a/litellm/models/model.py b/litellm/models/model.py new file mode 100644 index 00000000000..7657e4d30f8 --- /dev/null +++ b/litellm/models/model.py @@ -0,0 +1,59 @@ +""" +Proxy model table model. + +Canonical definition for ``litellm_proxymodeltable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +import json +from datetime import datetime +from typing import Optional + +from pydantic import ConfigDict, model_validator + +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_ProxyModelTable(LiteLLMPydanticObjectBase): + model_id: str + model_name: str + litellm_params: dict + model_info: Optional[dict] = None + blocked: bool = False + created_at: Optional[datetime] = None + created_by: Optional[str] = None + updated_at: Optional[datetime] = None + updated_by: Optional[str] = None + + model_config = ConfigDict(protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def check_potential_json_str(cls, values): + if isinstance(values.get("litellm_params"), str): + try: + values["litellm_params"] = json.loads(values["litellm_params"]) + except json.JSONDecodeError: + pass + if isinstance(values.get("model_info"), str): + try: + values["model_info"] = json.loads(values["model_info"]) + except json.JSONDecodeError: + pass + return values + + @property + def is_blocked(self) -> bool: + return self.blocked + + @property + def team_id(self) -> Optional[str]: + if self.model_info: + return self.model_info.get("team_id") + return None + + @property + def team_public_model_name(self) -> Optional[str]: + if self.model_info: + return self.model_info.get("team_public_model_name") + return None diff --git a/litellm/models/object_permission.py b/litellm/models/object_permission.py new file mode 100644 index 00000000000..6c0d100046c --- /dev/null +++ b/litellm/models/object_permission.py @@ -0,0 +1,26 @@ +""" +Object permission table model. + +Canonical definition for ``litellm_objectpermissiontable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from typing import Dict, List, Optional + +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_ObjectPermissionTable(LiteLLMPydanticObjectBase): + """Represents a LiteLLM_ObjectPermissionTable record""" + + object_permission_id: str + mcp_servers: Optional[List[str]] = [] + mcp_access_groups: Optional[List[str]] = [] + mcp_tool_permissions: Optional[Dict[str, List[str]]] = None + vector_stores: Optional[List[str]] = [] + agents: Optional[List[str]] = [] + agent_access_groups: Optional[List[str]] = [] + models: Optional[List[str]] = [] + mcp_toolsets: Optional[List[str]] = None + blocked_tools: Optional[List[str]] = [] + search_tools: Optional[List[str]] = [] diff --git a/litellm/models/organization.py b/litellm/models/organization.py new file mode 100644 index 00000000000..8b2d95c3e09 --- /dev/null +++ b/litellm/models/organization.py @@ -0,0 +1,31 @@ +""" +Organization table model. + +Canonical definition for ``litellm_organizationtable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from typing import List, Optional + +from litellm.models.budget import LiteLLM_BudgetTable +from litellm.models.object_permission import LiteLLM_ObjectPermissionTable +from litellm.models.user import LiteLLM_UserTable +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_OrganizationTable(LiteLLMPydanticObjectBase): + """Represents user-controllable params for a LiteLLM_OrganizationTable record""" + + organization_id: Optional[str] = None + organization_alias: Optional[str] = None + budget_id: str + spend: float = 0.0 + metadata: Optional[dict] = None + models: List[str] = [] + model_spend: Optional[dict] = {} + created_by: str + updated_by: str + users: Optional[List[LiteLLM_UserTable]] = None + litellm_budget_table: Optional[LiteLLM_BudgetTable] = None + object_permission: Optional[LiteLLM_ObjectPermissionTable] = None + object_permission_id: Optional[str] = None diff --git a/litellm/models/organization_membership.py b/litellm/models/organization_membership.py new file mode 100644 index 00000000000..9957c0c21af --- /dev/null +++ b/litellm/models/organization_membership.py @@ -0,0 +1,40 @@ +""" +Organization membership table model. + +Canonical definition for ``litellm_organizationmembership``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import Any, Optional + +from pydantic import ConfigDict, model_validator + +from litellm.models.budget import LiteLLM_BudgetTable +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_OrganizationMembershipTable(LiteLLMPydanticObjectBase): + """Tracks which organizations a user belongs to and their spend within it.""" + + user_id: str + organization_id: str + user_role: Optional[str] = None + spend: float = 0.0 + budget_id: Optional[str] = None + created_at: datetime + updated_at: datetime + user: Optional[Any] = None + litellm_budget_table: Optional[LiteLLM_BudgetTable] = None + user_email: Optional[str] = None + + model_config = ConfigDict(protected_namespaces=()) + + @model_validator(mode="after") + def populate_user_email(self) -> "LiteLLM_OrganizationMembershipTable": + if self.user_email is None and self.user is not None: + if isinstance(self.user, dict): + self.user_email = self.user.get("user_email") + else: + self.user_email = getattr(self.user, "user_email", None) + return self diff --git a/litellm/models/project.py b/litellm/models/project.py new file mode 100644 index 00000000000..083c7ee3cc5 --- /dev/null +++ b/litellm/models/project.py @@ -0,0 +1,41 @@ +""" +Project table model. + +Canonical definition for ``litellm_projecttable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import List, Optional + +from litellm.models.budget import LiteLLM_BudgetTable +from litellm.models.object_permission import LiteLLM_ObjectPermissionTable +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_ProjectTable(LiteLLMPydanticObjectBase): + """Database model representation for project""" + + project_id: str + project_alias: Optional[str] = None + description: Optional[str] = None + team_id: Optional[str] = None + budget_id: Optional[str] = None + metadata: Optional[dict] = None + models: List[str] = [] + spend: float = 0.0 + model_spend: Optional[dict] = None + model_rpm_limit: Optional[dict] = None + model_tpm_limit: Optional[dict] = None + blocked: bool = False + object_permission_id: Optional[str] = None + created_by: Optional[str] = None + updated_by: Optional[str] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + litellm_budget_table: Optional[LiteLLM_BudgetTable] = None + object_permission: Optional[LiteLLM_ObjectPermissionTable] = None + + @property + def is_blocked(self) -> bool: + return self.blocked diff --git a/litellm/models/skills.py b/litellm/models/skills.py new file mode 100644 index 00000000000..62091c0ca01 --- /dev/null +++ b/litellm/models/skills.py @@ -0,0 +1,30 @@ +""" +Skills table model. + +Canonical definition for ``litellm_skillstable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import Any, Dict, Optional + +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_SkillsTable(LiteLLMPydanticObjectBase): + """Represents a LiteLLM_SkillsTable record""" + + skill_id: str + display_title: Optional[str] = None + description: Optional[str] = None + instructions: Optional[str] = None + source: str = "custom" + latest_version: Optional[str] = None + file_content: Optional[bytes] = None + file_name: Optional[str] = None + file_type: Optional[str] = None + metadata: Optional[Dict[str, Any]] = None + created_at: Optional[datetime] = None + created_by: Optional[str] = None + updated_at: Optional[datetime] = None + updated_by: Optional[str] = None diff --git a/litellm/models/spend_logs.py b/litellm/models/spend_logs.py new file mode 100644 index 00000000000..96bd328c3ca --- /dev/null +++ b/litellm/models/spend_logs.py @@ -0,0 +1,50 @@ +""" +Spend and error log table models. + +Canonical definitions for ``litellm_spendlogs`` and ``litellm_errorlogs``. +Re-exported from ``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import Optional, Union + +from pydantic import Json + +from litellm._uuid import uuid +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_SpendLogs(LiteLLMPydanticObjectBase): + request_id: str + api_key: str + model: Optional[str] = "" + api_base: Optional[str] = "" + call_type: str + spend: Optional[float] = 0.0 + total_tokens: Optional[int] = 0 + prompt_tokens: Optional[int] = 0 + completion_tokens: Optional[int] = 0 + startTime: Union[str, datetime, None] + endTime: Union[str, datetime, None] + user: Optional[str] = "" + metadata: Optional[Json] = {} + cache_hit: Optional[str] = "False" + cache_key: Optional[str] = None + request_tags: Optional[Json] = None + requester_ip_address: Optional[str] = None + messages: Optional[Union[str, list, dict]] + response: Optional[Union[str, list, dict]] + + +class LiteLLM_ErrorLogs(LiteLLMPydanticObjectBase): + request_id: Optional[str] = str(uuid.uuid4()) + api_base: Optional[str] = "" + model_group: Optional[str] = "" + litellm_model_name: Optional[str] = "" + model_id: Optional[str] = "" + request_kwargs: Optional[dict] = {} + exception_type: Optional[str] = "" + status_code: Optional[str] = "" + exception_string: Optional[str] = "" + startTime: Union[str, datetime, None] + endTime: Union[str, datetime, None] diff --git a/litellm/models/tag.py b/litellm/models/tag.py new file mode 100644 index 00000000000..02d8f58916d --- /dev/null +++ b/litellm/models/tag.py @@ -0,0 +1,36 @@ +""" +Tag table model. + +Canonical definition for ``litellm_tagtable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import List, Optional + +from pydantic import model_validator + +from litellm.models.budget import LiteLLM_BudgetTable +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_TagTable(LiteLLMPydanticObjectBase): + tag_name: str + description: Optional[str] = None + models: List[str] = [] + model_info: Optional[dict] = None + spend: float = 0.0 + budget_id: Optional[str] = None + litellm_budget_table: Optional[LiteLLM_BudgetTable] = None + created_at: Optional[datetime] = None + created_by: Optional[str] = None + updated_at: Optional[datetime] = None + + @model_validator(mode="before") + @classmethod + def set_model_info(cls, values): + if values.get("spend") is None: + values.update({"spend": 0.0}) + if values.get("models") is None: + values.update({"models": []}) + return values diff --git a/litellm/models/team.py b/litellm/models/team.py new file mode 100644 index 00000000000..aa0798955f2 --- /dev/null +++ b/litellm/models/team.py @@ -0,0 +1,154 @@ +""" +Team table models. + +Canonical definitions for ``litellm_teamtable`` (plus the shared Member and +budget-window value types and the team-model alias table). Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +import json +from datetime import datetime +from typing import List, Literal, Optional, Union + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from litellm.models.object_permission import LiteLLM_ObjectPermissionTable +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class MemberBase(LiteLLMPydanticObjectBase): + user_id: Optional[str] = Field( + default=None, + description="The unique ID of the user to add. Either user_id or user_email must be provided", + ) + user_email: Optional[str] = Field( + default=None, + description="The email address of the user to add. Either user_id or user_email must be provided", + ) + + @model_validator(mode="before") + @classmethod + def check_user_info(cls, values): + if not isinstance(values, dict): + raise ValueError("input needs to be a dictionary") + if values.get("user_id") is None and values.get("user_email") is None: + raise ValueError("Either user id or user email must be provided") + return values + + +class Member(MemberBase): + role: Literal["admin", "user"] = Field( + description="The role of the user within the team. 'admin' users can manage team settings and members, 'user' is a regular team member" + ) + + +class BudgetLimitEntry(LiteLLMPydanticObjectBase): + """A single budget window with its own limit and independent reset schedule.""" + + budget_duration: str + max_budget: float + reset_at: Optional[datetime] = None + + +class LiteLLM_ModelTable(LiteLLMPydanticObjectBase): + id: Optional[int] = None + model_aliases: Optional[Union[str, dict]] = None + created_by: str + updated_by: str + team: Optional["LiteLLM_TeamTable"] = None + + model_config = ConfigDict(protected_namespaces=()) + + +class TeamBase(LiteLLMPydanticObjectBase): + team_alias: Optional[str] = None + team_id: Optional[str] = None + organization_id: Optional[str] = None + admins: list = [] + members: list = [] + members_with_roles: List[Member] = [] + team_member_permissions: Optional[List[str]] = None + metadata: Optional[dict] = None + tpm_limit: Optional[int] = None + rpm_limit: Optional[int] = None + max_budget: Optional[float] = None + soft_budget: Optional[float] = None + budget_duration: Optional[str] = None + budget_limits: Optional[List[BudgetLimitEntry]] = None + models: list = [] + blocked: bool = False + router_settings: Optional[dict] = None + access_group_ids: Optional[List[str]] = None + default_team_member_models: Optional[List[str]] = None + + +class LiteLLM_TeamTable(TeamBase): + team_id: str # type: ignore + spend: Optional[float] = None + max_parallel_requests: Optional[int] = None + budget_duration: Optional[str] = None + budget_reset_at: Optional[datetime] = None + model_id: Optional[int] = None + model_spend: Optional[dict] = {} + model_max_budget: Optional[dict] = {} + policies: Optional[List[str]] = None + allow_team_guardrail_config: Optional[bool] = False + litellm_model_table: Optional[LiteLLM_ModelTable] = None + object_permission: Optional[LiteLLM_ObjectPermissionTable] = None + object_permission_id: Optional[str] = None + updated_at: Optional[datetime] = None + created_at: Optional[datetime] = None + + model_config = ConfigDict(protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def set_model_info(cls, values): + dict_fields = [ + "metadata", + "aliases", + "config", + "permissions", + "model_max_budget", + "model_aliases", + "router_settings", + "budget_limits", + ] + + if isinstance(values, BaseModel): + values = values.model_dump() + + if ( + isinstance(values.get("members_with_roles"), dict) + and not values["members_with_roles"] + ): + values["members_with_roles"] = [] + + for field in dict_fields: + value = values.get(field) + if value is not None and isinstance(value, str): + try: + values[field] = json.loads(value) + except json.JSONDecodeError: + raise ValueError(f"Field {field} should be a valid dictionary") + + return values + + +class LiteLLM_TeamTableCachedObj(LiteLLM_TeamTable): + last_refreshed_at: Optional[float] = None + + +class LiteLLM_DeletedTeamTable(LiteLLM_TeamTable): + """Audit record for deleted teams; mirrors the team plus deletion metadata.""" + + id: Optional[str] = None + deleted_at: Optional[datetime] = None + deleted_by: Optional[str] = None + deleted_by_api_key: Optional[str] = None + litellm_changed_by: Optional[str] = None + + model_config = ConfigDict(protected_namespaces=()) + + +LiteLLM_ModelTable.model_rebuild() diff --git a/litellm/models/team_membership.py b/litellm/models/team_membership.py new file mode 100644 index 00000000000..d0a1308ce7c --- /dev/null +++ b/litellm/models/team_membership.py @@ -0,0 +1,32 @@ +""" +Team membership table model. + +Canonical definition for ``litellm_teammembership``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from typing import Optional, Union + +from litellm.models.budget import LiteLLM_BudgetTable, LiteLLM_BudgetTableFull +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_TeamMembership(LiteLLMPydanticObjectBase): + user_id: str + team_id: str + budget_id: Optional[str] = None + spend: Optional[float] = 0.0 + total_spend: Optional[float] = 0.0 + litellm_budget_table: Optional[ + Union[LiteLLM_BudgetTableFull, LiteLLM_BudgetTable] + ] = None + + def safe_get_team_member_rpm_limit(self) -> Optional[int]: + if self.litellm_budget_table is not None: + return self.litellm_budget_table.rpm_limit + return None + + def safe_get_team_member_tpm_limit(self) -> Optional[int]: + if self.litellm_budget_table is not None: + return self.litellm_budget_table.tpm_limit + return None diff --git a/litellm/models/user.py b/litellm/models/user.py new file mode 100644 index 00000000000..cd7e9db4aec --- /dev/null +++ b/litellm/models/user.py @@ -0,0 +1,70 @@ +""" +User table model. + +Canonical definition for ``litellm_usertable``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import Dict, List, Optional + +from pydantic import ConfigDict, Field, model_validator + +from litellm.models.object_permission import LiteLLM_ObjectPermissionTable +from litellm.models.organization_membership import ( + LiteLLM_OrganizationMembershipTable, +) +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_UserTable(LiteLLMPydanticObjectBase): + user_id: str + user_alias: Optional[str] = None + team_id: Optional[str] = None + sso_user_id: Optional[str] = None + organization_id: Optional[str] = None + object_permission_id: Optional[str] = None + password: Optional[str] = Field(default=None, exclude=True) + teams: List[str] = [] + user_role: Optional[str] = None + max_budget: Optional[float] = None + spend: float = 0.0 + user_email: Optional[str] = None + models: list = [] + metadata: Optional[dict] = None + max_parallel_requests: Optional[int] = None + tpm_limit: Optional[int] = None + rpm_limit: Optional[int] = None + budget_duration: Optional[str] = None + budget_reset_at: Optional[datetime] = None + allowed_cache_controls: List[str] = [] + policies: List[str] = [] + model_spend: Optional[Dict] = {} + model_max_budget: Optional[Dict] = {} + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + organization_memberships: Optional[List[LiteLLM_OrganizationMembershipTable]] = None + object_permission: Optional[LiteLLM_ObjectPermissionTable] = None + + model_config = ConfigDict(protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def set_model_info(cls, values): + if values.get("spend") is None: + values.update({"spend": 0.0}) + if values.get("models") is None: + values.update({"models": []}) + if values.get("teams") is None: + values.update({"teams": []}) + return values + + def is_over_budget(self) -> bool: + if self.max_budget is None: + return False + return self.spend >= self.max_budget + + def has_model_access(self, model_name: str) -> bool: + if not self.models: + return True + return model_name in self.models diff --git a/litellm/models/verification_token.py b/litellm/models/verification_token.py new file mode 100644 index 00000000000..8bddd1c1619 --- /dev/null +++ b/litellm/models/verification_token.py @@ -0,0 +1,74 @@ +""" +Verification token table model. + +Canonical definition for ``litellm_verificationtoken``. Re-exported from +``litellm.proxy._types`` for backwards compatibility. +""" + +from datetime import datetime +from typing import Dict, List, Optional, Union + +from pydantic import ConfigDict + +from litellm.models.object_permission import LiteLLM_ObjectPermissionTable +from litellm.types.llms.base import LiteLLMPydanticObjectBase + + +class LiteLLM_VerificationToken(LiteLLMPydanticObjectBase): + token: Optional[str] = None + key_name: Optional[str] = None + key_alias: Optional[str] = None + spend: float = 0.0 + max_budget: Optional[float] = None + expires: Optional[Union[str, datetime]] = None + models: List = [] + aliases: Dict = {} + config: Dict = {} + user_id: Optional[str] = None + team_id: Optional[str] = None + agent_id: Optional[str] = None + project_id: Optional[str] = None + max_parallel_requests: Optional[int] = None + metadata: Dict = {} + tpm_limit: Optional[int] = None + rpm_limit: Optional[int] = None + budget_duration: Optional[str] = None + budget_reset_at: Optional[datetime] = None + allowed_cache_controls: Optional[list] = [] + allowed_routes: Optional[list] = [] + permissions: Dict = {} + model_spend: Dict = {} + model_max_budget: Dict = {} + soft_budget_cooldown: bool = False + blocked: Optional[bool] = None + litellm_budget_table: Optional[dict] = None + budget_id: Optional[str] = None + org_id: Optional[str] = None # org id for a given key + created_at: Optional[datetime] = None + created_by: Optional[str] = None + updated_at: Optional[datetime] = None + updated_by: Optional[str] = None + last_active: Optional[datetime] = None + object_permission_id: Optional[str] = None + object_permission: Optional[LiteLLM_ObjectPermissionTable] = None + access_group_ids: Optional[List[str]] = None + rotation_count: Optional[int] = 0 + auto_rotate: Optional[bool] = False + rotation_interval: Optional[str] = None + last_rotation_at: Optional[datetime] = None + key_rotation_at: Optional[datetime] = None + router_settings: Optional[dict] = None + budget_limits: Optional[List[dict]] = None + model_config = ConfigDict(protected_namespaces=()) + + +class LiteLLM_DeletedVerificationToken(LiteLLM_VerificationToken): + """Audit record for deleted keys; mirrors the token plus deletion metadata.""" + + id: Optional[str] = None + deleted_at: Optional[datetime] = None + deleted_by: Optional[str] = None + deleted_by_api_key: Optional[str] = None + litellm_changed_by: Optional[str] = None + + model_config = ConfigDict(protected_namespaces=()) diff --git a/litellm/passthrough/main.py b/litellm/passthrough/main.py index 2c654a3f23b..5c3e7aa1884 100644 --- a/litellm/passthrough/main.py +++ b/litellm/passthrough/main.py @@ -20,7 +20,6 @@ from typing import ( import httpx from httpx._types import CookieTypes, QueryParamTypes, RequestFiles -import litellm from litellm._logging import verbose_logger from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler @@ -400,12 +399,6 @@ def llm_passthrough_route( _is_async = allm_passthrough_route - if client is None: - if _is_async: - client = litellm.module_level_aclient - else: - client = litellm.module_level_client - litellm_logging_obj = cast("LiteLLMLoggingObj", kwargs.get("litellm_logging_obj")) model, custom_llm_provider, api_key, api_base = get_llm_provider( @@ -417,6 +410,26 @@ def llm_passthrough_route( litellm_params_dict = get_litellm_params(**kwargs) + if client is None: + from litellm.llms.custom_httpx.http_handler import ( + _get_httpx_client, + get_async_httpx_client, + ) + from litellm.passthrough.timeout_utils import resolve_llm_passthrough_timeout + from litellm.types.llms.custom_http import httpxSpecialProvider + + resolved_timeout = resolve_llm_passthrough_timeout( + kwargs=kwargs, + litellm_params=litellm_params_dict, + ) + if _is_async: + client = get_async_httpx_client( + llm_provider=httpxSpecialProvider.PassThroughEndpoint, + params={"timeout": resolved_timeout}, + ) + else: + client = _get_httpx_client(params={"timeout": resolved_timeout}) + # Add model_id to litellm_params if present in kwargs (for Bedrock Application Inference Profiles) if "model_id" in kwargs: litellm_params_dict["model_id"] = kwargs["model_id"] diff --git a/litellm/passthrough/timeout_utils.py b/litellm/passthrough/timeout_utils.py new file mode 100644 index 00000000000..a423db2aa91 --- /dev/null +++ b/litellm/passthrough/timeout_utils.py @@ -0,0 +1,58 @@ +import sys +from typing import Optional + +DEFAULT_PASS_THROUGH_REQUEST_TIMEOUT_SECONDS = 600.0 + + +def resolve_pass_through_request_timeout( + endpoint_timeout: Optional[float] = None, +) -> float: + """ + Resolve the upstream httpx timeout for pass_through_request. + + Precedence: per-endpoint timeout -> general_settings.pass_through_request_timeout -> 600s default. + + Uses sys.modules to read general_settings only when the proxy module is already + loaded, avoiding a fastapi transitive import in pure SDK contexts. + """ + if endpoint_timeout is not None: + return float(endpoint_timeout) + + try: + proxy_server = sys.modules.get("litellm.proxy.proxy_server") + if proxy_server is not None: + global_timeout = getattr(proxy_server, "general_settings", {}).get( + "pass_through_request_timeout" + ) + if global_timeout is not None: + return float(global_timeout) + except Exception: + pass + + return DEFAULT_PASS_THROUGH_REQUEST_TIMEOUT_SECONDS + + +def resolve_llm_passthrough_timeout( + kwargs: Optional[dict] = None, + litellm_params: Optional[dict] = None, + router_timeout: Optional[float] = None, +) -> float: + """ + Resolve upstream httpx timeout for SDK native passthrough (e.g. Bedrock /converse). + + Precedence: kwargs timeout/request_timeout -> litellm_params timeout/request_timeout + -> router_timeout -> general_settings.pass_through_request_timeout -> 600s default. + """ + kwargs = kwargs or {} + litellm_params = litellm_params or {} + + for source in (kwargs, litellm_params): + for key in ("timeout", "request_timeout"): + val = source.get(key) + if val is not None: + return float(val) + + if router_timeout is not None: + return float(router_timeout) + + return resolve_pass_through_request_timeout() diff --git a/litellm/provider_endpoints_support_backup.json b/litellm/provider_endpoints_support_backup.json index 0562b41d2cd..e0eeb014c51 100644 --- a/litellm/provider_endpoints_support_backup.json +++ b/litellm/provider_endpoints_support_backup.json @@ -1539,6 +1539,23 @@ "interactions": true } }, + "neosantara": { + "display_name": "Neosantara (`neosantara`)", + "url": "https://docs.litellm.ai/docs/providers/neosantara", + "endpoints": { + "chat_completions": true, + "messages": false, + "responses": true, + "embeddings": false, + "image_generations": false, + "audio_transcriptions": false, + "audio_speech": false, + "moderations": false, + "batches": false, + "rerank": false, + "a2a": false + } + }, "nvidia_nim": { "display_name": "Nvidia NIM (`nvidia_nim`)", "url": "https://docs.litellm.ai/docs/providers/nvidia_nim", diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py index 863e6acd41e..dcf7660d002 100644 --- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py +++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py @@ -14,8 +14,12 @@ from litellm.proxy._types import ( SpecialHeaders, UserAPIKeyAuth, ) -from litellm.proxy.auth.user_api_key_auth import user_api_key_auth from litellm.proxy.auth.ip_address_utils import IPAddressUtils +from litellm.proxy.auth.user_api_key_auth import user_api_key_auth +from litellm.repositories.table_repositories import ( + AgentsRepository, + MCPServerRepository, +) def _parse_mcp_server_names_from_path( @@ -1445,7 +1449,7 @@ class MCPRequestHandler: return None if object_permission_id is None: - agent_row = await prisma_client.db.litellm_agentstable.find_unique( + agent_row = await AgentsRepository(prisma_client).table.find_unique( where={"agent_id": agent_id}, ) object_permission_id = ( @@ -1600,7 +1604,7 @@ class MCPRequestHandler: server_ids: Set[str] = set() if access_groups and prisma_client is not None: try: - mcp_servers = await prisma_client.db.litellm_mcpservertable.find_many( + mcp_servers = await MCPServerRepository(prisma_client).table.find_many( where={"mcp_access_groups": {"hasSome": access_groups}} ) for server in mcp_servers: diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.py index d7b2224eb64..8edb831a9df 100644 --- a/litellm/proxy/_experimental/mcp_server/db.py +++ b/litellm/proxy/_experimental/mcp_server/db.py @@ -1,16 +1,20 @@ import base64 import binascii +import hashlib import json from datetime import datetime, timedelta, timezone from typing import Any, Dict, Iterable, List, Optional, Set, Union, cast from litellm._logging import verbose_proxy_logger from litellm._uuid import uuid +from litellm.constants import MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS +from litellm.llms.custom_httpx.http_handler import get_async_httpx_client from litellm.proxy._types import ( LiteLLM_MCPServerTable, LiteLLM_ObjectPermissionTable, LiteLLM_TeamTable, MCPApprovalStatus, + MCPEnvVarScope, MCPSubmissionsSummary, NewMCPServerRequest, SpecialMCPServerName, @@ -22,12 +26,158 @@ from litellm.proxy.common_utils.encrypt_decrypt_utils import ( decrypt_value_helper, encrypt_value_helper, ) -from litellm.llms.custom_httpx.http_handler import get_async_httpx_client from litellm.proxy.utils import PrismaClient +from litellm.repositories.object_permission_repository import ObjectPermissionRepository +from litellm.repositories.table_repositories import ( + MCPServerRepository, + MCPUserCredentialsRepository, +) +from litellm.repositories.team_repository import TeamRepository +from litellm.repositories.verification_token_repository import ( + VerificationTokenRepository, +) from litellm.types.llms.custom_http import httpxSpecialProvider from litellm.types.mcp import MCPCredentials +def _is_global_env_var_scope(scope: Any) -> bool: + """``scope="user"`` entries are placeholders the user fills in; everything + else (including a missing scope) is an admin-supplied global value.""" + return scope != MCPEnvVarScope.user and scope != "user" + + +def _encrypt_global_env_var_values(env_vars: Iterable[Dict[str, Any]]) -> None: + """Encrypt ``scope="global"`` env var values in place before persisting. + + Global values hold admin-supplied secrets (API keys, passwords) that get + interpolated into headers, so they are encrypted at rest like credentials + and the per-user ``values_b64`` column. Per-user placeholders are not + secrets and are stored verbatim. + """ + for entry in env_vars: + if not _is_global_env_var_scope(entry.get("scope")): + continue + value = entry.get("value") + if value: + entry["value"] = encrypt_value_helper(value) + + +def decrypt_global_env_var_values(env_vars: Optional[Iterable[Any]]) -> None: + """Decrypt ``scope="global"`` env var values in place after reading the DB. + + Accepts ``MCPEnvVar`` models (``LiteLLM_MCPServerTable``) or plain dicts + (raw rows / deserialized JSON). Global values are always stored encrypted, + so a value that no longer decrypts (e.g. after a salt-key change) is dropped + and a warning is logged rather than forwarding the ciphertext into upstream + ``${NAME}`` headers, where it would silently fail. + """ + if not env_vars: + return + for entry in env_vars: + is_dict = isinstance(entry, dict) + scope = entry.get("scope") if is_dict else getattr(entry, "scope", None) + if not _is_global_env_var_scope(scope): + continue + value = entry.get("value") if is_dict else getattr(entry, "value", None) + if not value: + continue + decrypted = decrypt_value_helper( + value=value, + key="mcp_global_env_var", + exception_type="debug", + return_original_value=False, + ) + if decrypted is None: + name = entry.get("name") if is_dict else getattr(entry, "name", None) + verbose_proxy_logger.warning( + "MCP global env var %s failed to decrypt (LITELLM_SALT_KEY " + "changed?); dropping it so ciphertext is not sent upstream", + name, + ) + decrypted = "" + if is_dict: + entry["value"] = decrypted + else: + entry.value = decrypted + + +def _decrypt_env_vars_on_returned_row(row: Any) -> None: + """Decrypt ``scope="global"`` env var values on a row returned by Prisma create/update. + + Prisma may hand back ``env_vars`` either as a parsed list (the common case for + JSONB columns) or as a raw JSON string (observed for some write paths). The + in-place decrypt helper only mutates iterables of dicts/models, so a string + payload would silently skip decryption and ciphertext would leak into the + registry via ``add_server``/``update_server`` (which trust the caller). + Parse the string back to a list so the in-place decrypt actually runs, and + write the decrypted list back onto the row so downstream consumers see plain + values. + """ + env_vars = getattr(row, "env_vars", None) + if env_vars is None: + return + if isinstance(env_vars, str): + try: + env_vars = json.loads(env_vars) + except (json.JSONDecodeError, TypeError): + return + if not isinstance(env_vars, list): + return + try: + setattr(row, "env_vars", env_vars) + except (AttributeError, TypeError): + pass + decrypt_global_env_var_values(env_vars) + + +def _reencrypt_global_env_var_values( + env_vars: Optional[Iterable[Any]], new_encryption_key: str +) -> Optional[List[Dict[str, Any]]]: + """Re-encrypt ``scope="global"`` env var values for master-key rotation. + + Each global value is decrypted with the current salt key and re-encrypted + under ``new_encryption_key``. Returns the rebuilt list when at least one + value was rotated, else ``None`` so the caller can skip the DB write. A + value that fails to decrypt is left untouched (and logged) so a corrupt + entry is preserved for recovery rather than overwritten. + """ + if not env_vars: + return None + if isinstance(env_vars, str): + try: + env_vars = json.loads(env_vars) + except (json.JSONDecodeError, TypeError): + return None + if not env_vars: + return None + rebuilt = [dict(v) for v in env_vars] + rotated = False + for entry in rebuilt: + if not _is_global_env_var_scope(entry.get("scope")): + continue + value = entry.get("value") + if not value: + continue + decrypted = decrypt_value_helper( + value=value, + key="mcp_global_env_var", + exception_type="debug", + return_original_value=False, + ) + if decrypted is None: + verbose_proxy_logger.warning( + "rotate_mcp_server_credentials_master_key: could not decrypt " + "global env var %s, skipping", + entry.get("name"), + ) + continue + entry["value"] = encrypt_value_helper( + decrypted, new_encryption_key=new_encryption_key + ) + rotated = True + return rebuilt if rotated else None + + def _prepare_mcp_server_data( data: Union[NewMCPServerRequest, UpdateMCPServerRequest], exclude_unset: bool = False, @@ -98,6 +248,16 @@ def _prepare_mcp_server_data( if data_dict.get("static_headers") is not None: data_dict["static_headers"] = safe_dumps(data_dict["static_headers"]) + # env_vars is read from ``data_dict`` (not ``data``) like every other JSON + # column so the exclude_unset filter is respected: a partial update that + # omits env_vars never overwrites the stored value. Global values are + # encrypted at rest before serialization. + env_vars = data_dict.get("env_vars") + if env_vars is not None: + serialized_env_vars = [dict(v) for v in env_vars] + _encrypt_global_env_var_values(serialized_env_vars) + data_dict["env_vars"] = safe_dumps(serialized_env_vars) + if data_dict.get("mcp_info") is not None: data_dict["mcp_info"] = safe_dumps(data_dict["mcp_info"]) @@ -203,14 +363,17 @@ async def get_all_mcp_servers( where: Dict[str, Any] = {} if approval_status is not None: where["approval_status"] = approval_status - mcp_servers = await prisma_client.db.litellm_mcpservertable.find_many( + mcp_servers = await MCPServerRepository(prisma_client).table.find_many( where=where if where else {} ) - return [ + tables = [ LiteLLM_MCPServerTable(**mcp_server.model_dump()) for mcp_server in mcp_servers ] + for table in tables: + decrypt_global_env_var_values(table.env_vars) + return tables except Exception as e: verbose_proxy_logger.debug( "litellm.proxy._experimental.mcp_server.db.py::get_all_mcp_servers - {}".format( @@ -226,14 +389,18 @@ async def get_mcp_server( """ Returns the matching mcp server from the db iff exists """ - mcp_server: Optional[LiteLLM_MCPServerTable] = ( - await prisma_client.db.litellm_mcpservertable.find_unique( - where={ - "server_id": server_id, - } - ) + mcp_server: Optional[LiteLLM_MCPServerTable] = await MCPServerRepository( + prisma_client + ).table.find_unique( + where={ + "server_id": server_id, + } ) - return mcp_server + if mcp_server is None: + return None + table = LiteLLM_MCPServerTable(**mcp_server.model_dump()) + decrypt_global_env_var_values(table.env_vars) + return table async def get_mcp_servers( @@ -242,16 +409,18 @@ async def get_mcp_servers( """ Returns the matching mcp servers from the db with the server_ids """ - _mcp_servers: List[LiteLLM_MCPServerTable] = ( - await prisma_client.db.litellm_mcpservertable.find_many( - where={ - "server_id": {"in": server_ids}, - } - ) + _mcp_servers: List[LiteLLM_MCPServerTable] = await MCPServerRepository( + prisma_client + ).table.find_many( + where={ + "server_id": {"in": server_ids}, + } ) final_mcp_servers: List[LiteLLM_MCPServerTable] = [] for _mcp_server in _mcp_servers: - final_mcp_servers.append(LiteLLM_MCPServerTable(**_mcp_server.model_dump())) + table = LiteLLM_MCPServerTable(**_mcp_server.model_dump()) + decrypt_global_env_var_values(table.env_vars) + final_mcp_servers.append(table) return final_mcp_servers @@ -262,15 +431,15 @@ async def get_mcp_servers_by_verificationtoken( """ Returns the mcp servers from the db for the verification token """ - verification_token_record: LiteLLM_TeamTable = ( - await prisma_client.db.litellm_verificationtoken.find_unique( - where={ - "token": token, - }, - include={ - "object_permission": True, - }, - ) + verification_token_record: LiteLLM_TeamTable = await VerificationTokenRepository( + prisma_client + ).table.find_unique( + where={ + "token": token, + }, + include={ + "object_permission": True, + }, ) mcp_servers: Optional[List[str]] = [] @@ -288,15 +457,15 @@ async def get_mcp_servers_by_team( """ Returns the mcp servers from the db for the team id """ - team_record: LiteLLM_TeamTable = ( - await prisma_client.db.litellm_teamtable.find_unique( - where={ - "team_id": team_id, - }, - include={ - "object_permission": True, - }, - ) + team_record: LiteLLM_TeamTable = await TeamRepository( + prisma_client + ).table.find_unique( + where={ + "team_id": team_id, + }, + include={ + "object_permission": True, + }, ) mcp_servers: Optional[List[str]] = [] @@ -347,16 +516,16 @@ async def get_objectpermissions_for_mcp_server( """ Get all the object permissions records and the associated team and verficiationtoken records that have access to the mcp server """ - object_permission_records = ( - await prisma_client.db.litellm_objectpermissiontable.find_many( - where={ - "mcp_servers": {"has": mcp_server_id}, - }, - include={ - "teams": True, - "verification_tokens": True, - }, - ) + object_permission_records = await ObjectPermissionRepository( + prisma_client + ).table.find_many( + where={ + "mcp_servers": {"has": mcp_server_id}, + }, + include={ + "teams": True, + "verification_tokens": True, + }, ) return object_permission_records @@ -368,7 +537,7 @@ async def get_virtualkeys_for_mcp_server( """ Get all the virtual keys that have access to the mcp server """ - virtual_keys = await prisma_client.db.litellm_verificationtoken.find_many( + virtual_keys = await VerificationTokenRepository(prisma_client).table.find_many( where={ "mcp_servers": {"has": server_id}, }, @@ -399,13 +568,35 @@ async def delete_mcp_server( """ Delete the mcp server from the db by server_id + The server-row delete is the commit point. Per-user credential and env var + rows have no FK cascade, so they are cleaned up afterwards on a best-effort + basis: a transient failure there leaves only orphaned rows pointing at a + now-missing server and must not turn a successful delete into a + caller-visible error. Each table is cleaned independently so a failure on one + still attempts the other. + Returns the deleted mcp server record if it exists, otherwise None """ - deleted_server = await prisma_client.db.litellm_mcpservertable.delete( + deleted_server = await MCPServerRepository(prisma_client).table.delete( where={ "server_id": server_id, }, ) + if deleted_server is not None: + for model, label in ( + (prisma_client.db.litellm_mcpusercredentials, "credential"), + (prisma_client.db.litellm_mcpuserenvvars, "env var"), + ): + try: + await model.delete_many(where={"server_id": server_id}) + except Exception as e: + verbose_proxy_logger.warning( + "MCP server %s deleted but per-user %s cleanup failed; " + "orphaned rows can be removed on a later delete: %s", + server_id, + label, + e, + ) return deleted_server @@ -425,10 +616,11 @@ async def create_mcp_server( data_dict["created_by"] = touched_by data_dict["updated_by"] = touched_by - new_mcp_server = await prisma_client.db.litellm_mcpservertable.create( + new_mcp_server = await MCPServerRepository(prisma_client).table.create( data=data_dict # type: ignore ) + _decrypt_env_vars_on_returned_row(new_mcp_server) return new_mcp_server @@ -459,7 +651,7 @@ async def update_mcp_server( "credentials" in data_dict and data_dict["credentials"] is not None ) if data.auth_type or has_credentials: - existing = await prisma_client.db.litellm_mcpservertable.find_unique( + existing = await MCPServerRepository(prisma_client).table.find_unique( where={"server_id": data.server_id} ) @@ -502,44 +694,56 @@ async def update_mcp_server( # Add audit fields data_dict["updated_by"] = touched_by - updated_mcp_server = await prisma_client.db.litellm_mcpservertable.update( + updated_mcp_server = await MCPServerRepository(prisma_client).table.update( where={"server_id": data.server_id}, data=data_dict # type: ignore ) + _decrypt_env_vars_on_returned_row(updated_mcp_server) return updated_mcp_server async def rotate_mcp_server_credentials_master_key( prisma_client: PrismaClient, touched_by: str, new_master_key: str ): - mcp_servers = await prisma_client.db.litellm_mcpservertable.find_many() + from litellm.litellm_core_utils.safe_json_dumps import safe_dumps + mcp_servers = await MCPServerRepository(prisma_client).table.find_many() + + updated = 0 for mcp_server in mcp_servers: + update_data: Dict[str, Any] = {} + credentials = mcp_server.credentials - if not credentials: + if credentials: + # Decrypt with current key first, then re-encrypt with new key + decrypted_credentials = decrypt_credentials( + credentials=cast(MCPCredentials, dict(credentials)), + ) + encrypted_credentials = encrypt_credentials( + credentials=decrypted_credentials, + encryption_key=new_master_key, + ) + update_data["credentials"] = safe_dumps(encrypted_credentials) + + rotated_env_vars = _reencrypt_global_env_var_values( + mcp_server.env_vars, new_master_key + ) + if rotated_env_vars is not None: + update_data["env_vars"] = safe_dumps(rotated_env_vars) + + if not update_data: continue - credentials_copy = dict(credentials) - # Decrypt with current key first, then re-encrypt with new key - decrypted_credentials = decrypt_credentials( - credentials=cast(MCPCredentials, credentials_copy), - ) - encrypted_credentials = encrypt_credentials( - credentials=decrypted_credentials, - encryption_key=new_master_key, - ) - - from litellm.litellm_core_utils.safe_json_dumps import safe_dumps - - serialized_credentials = safe_dumps(encrypted_credentials) - - await prisma_client.db.litellm_mcpservertable.update( + update_data["updated_by"] = touched_by + await MCPServerRepository(prisma_client).table.update( where={"server_id": mcp_server.server_id}, - data={ - "credentials": serialized_credentials, - "updated_by": touched_by, - }, + data=update_data, ) + updated += 1 + verbose_proxy_logger.info( + "rotate_mcp_server_credentials_master_key: rotated %d MCP server row(s)", + updated, + ) def _decode_user_credential(stored: str) -> Optional[str]: @@ -593,7 +797,9 @@ async def rotate_mcp_user_credentials_master_key( under the new master key. Rows that are unreadable under both paths are logged and skipped so one corrupt row does not abort the rotation. """ - rows = await prisma_client.db.litellm_mcpusercredentials.find_many() + rows = await MCPUserCredentialsRepository(prisma_client).table.find_many() + rotated = 0 + skipped = 0 for row in rows: plaintext = _decode_user_credential(row.credential_b64) if plaintext is None: @@ -603,11 +809,12 @@ async def rotate_mcp_user_credentials_master_key( row.user_id, row.server_id, ) + skipped += 1 continue re_encrypted = encrypt_value_helper( plaintext, new_encryption_key=new_master_key ) - await prisma_client.db.litellm_mcpusercredentials.update( + await MCPUserCredentialsRepository(prisma_client).table.update( where={ "user_id_server_id": { "user_id": row.user_id, @@ -616,6 +823,61 @@ async def rotate_mcp_user_credentials_master_key( }, data={"credential_b64": re_encrypted}, ) + rotated += 1 + verbose_proxy_logger.info( + "rotate_mcp_user_credentials_master_key: rotated %d row(s), skipped %d", + rotated, + skipped, + ) + + +async def rotate_mcp_user_env_vars_master_key( + prisma_client: PrismaClient, new_master_key: str +): + """Re-encrypt every ``LiteLLM_MCPUserEnvVars`` row with ``new_master_key``. + + Reads each ``values_b64`` blob with the current salt key and writes it back + encrypted under the new master key. Rows that fail to decrypt are logged and + skipped so one corrupt row does not abort the rotation nor overwrite values + that may still be recoverable. + """ + rows = await prisma_client.db.litellm_mcpuserenvvars.find_many() + rotated = 0 + skipped = 0 + for row in rows: + plaintext = decrypt_value_helper( + value=row.values_b64, + key="mcp_user_env_vars", + exception_type="debug", + return_original_value=False, + ) + if plaintext is None: + verbose_proxy_logger.warning( + "rotate_mcp_user_env_vars_master_key: could not decrypt env vars " + "for user_id=%s server_id=%s, skipping", + row.user_id, + row.server_id, + ) + skipped += 1 + continue + re_encrypted = encrypt_value_helper( + plaintext, new_encryption_key=new_master_key + ) + await prisma_client.db.litellm_mcpuserenvvars.update( + where={ + "user_id_server_id": { + "user_id": row.user_id, + "server_id": row.server_id, + } + }, + data={"values_b64": re_encrypted}, + ) + rotated += 1 + verbose_proxy_logger.info( + "rotate_mcp_user_env_vars_master_key: rotated %d row(s), skipped %d", + rotated, + skipped, + ) async def store_user_credential( @@ -627,7 +889,7 @@ async def store_user_credential( """Store a user credential for a BYOK MCP server.""" encoded = encrypt_value_helper(credential) - await prisma_client.db.litellm_mcpusercredentials.upsert( + await MCPUserCredentialsRepository(prisma_client).table.upsert( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}, data={ "create": { @@ -647,7 +909,7 @@ async def get_user_credential( ) -> Optional[str]: """Return credential for a user+server pair, or None.""" - row = await prisma_client.db.litellm_mcpusercredentials.find_unique( + row = await MCPUserCredentialsRepository(prisma_client).table.find_unique( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} ) if row is None: @@ -661,7 +923,7 @@ async def has_user_credential( server_id: str, ) -> bool: """Return True if the user has a stored credential for this server.""" - row = await prisma_client.db.litellm_mcpusercredentials.find_unique( + row = await MCPUserCredentialsRepository(prisma_client).table.find_unique( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} ) return row is not None @@ -673,7 +935,7 @@ async def delete_user_credential( server_id: str, ) -> None: """Delete the user's stored credential for a BYOK MCP server.""" - await prisma_client.db.litellm_mcpusercredentials.delete( + await MCPUserCredentialsRepository(prisma_client).table.delete( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} ) @@ -720,7 +982,7 @@ async def store_user_oauth_credential( # Skip the guard when the caller knows the row is already an OAuth2 credential # (e.g. during token refresh), saving an extra DB round-trip. if not skip_byok_guard: - existing = await prisma_client.db.litellm_mcpusercredentials.find_unique( + existing = await MCPUserCredentialsRepository(prisma_client).table.find_unique( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} ) if ( @@ -738,7 +1000,7 @@ async def store_user_oauth_credential( ) encoded = encrypt_value_helper(json.dumps(payload)) - await prisma_client.db.litellm_mcpusercredentials.upsert( + await MCPUserCredentialsRepository(prisma_client).table.upsert( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}, data={ "create": { @@ -751,11 +1013,14 @@ async def store_user_oauth_credential( ) -def is_oauth_credential_expired(cred: Dict[str, Any]) -> bool: +def is_oauth_credential_expired(cred: Dict[str, Any], buffer_seconds: int = 0) -> bool: """Return True if the OAuth2 credential's access_token has expired. Checks the ``expires_at`` ISO-format string stored in the credential payload. Returns False when ``expires_at`` is absent or unparseable (treat as non-expired). + With ``buffer_seconds`` > 0, a token that is still valid but expires within the + buffer is also treated as expired, so callers can refresh proactively instead of + handing back a token that may lapse mid-request. """ expires_at = cred.get("expires_at") if not expires_at: @@ -764,7 +1029,7 @@ def is_oauth_credential_expired(cred: Dict[str, Any]) -> bool: exp_dt = datetime.fromisoformat(expires_at) if exp_dt.tzinfo is None: exp_dt = exp_dt.replace(tzinfo=timezone.utc) - return datetime.now(timezone.utc) > exp_dt + return datetime.now(timezone.utc) + timedelta(seconds=buffer_seconds) > exp_dt except (ValueError, TypeError): return False @@ -776,7 +1041,7 @@ async def get_user_oauth_credential( ) -> Optional[Dict[str, Any]]: """Return the decoded OAuth2 payload dict for a user+server pair, or None.""" - row = await prisma_client.db.litellm_mcpusercredentials.find_unique( + row = await MCPUserCredentialsRepository(prisma_client).table.find_unique( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} ) if row is None: @@ -790,7 +1055,7 @@ async def list_user_oauth_credentials( ) -> List[Dict[str, Any]]: """Return all OAuth2 credential payloads for a user, tagged with server_id.""" - rows = await prisma_client.db.litellm_mcpusercredentials.find_many( + rows = await MCPUserCredentialsRepository(prisma_client).table.find_many( where={"user_id": user_id} ) results: List[Dict[str, Any]] = [] @@ -912,6 +1177,50 @@ async def refresh_user_oauth_token( return await get_user_oauth_credential(prisma_client, user_id, server_id) +async def resolve_valid_user_oauth_token( + user_id: str, + server: Any, + cred: Optional[Dict[str, Any]], + prisma_client: Optional[PrismaClient] = None, +) -> Optional[Dict[str, Any]]: + """Return an OAuth2 credential whose access_token is good for the next request. + + Returns the credential unchanged while its token is valid for at least + ``MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS``. Only when the token is expired (or + expiring within that buffer) and a refresh_token is stored does it mint a new one + via ``refresh_user_oauth_token``. Returns None when there is no usable token + (missing token, expired with no refresh_token, or a failed refresh). + + The refresh_token is only ever sent to the server's token_url inside + ``refresh_user_oauth_token``; it is never exposed to the caller beyond the cred + dict it already holds. ``prisma_client`` is fetched lazily and only when a refresh + actually happens, so the valid-token path never requires a DB handle. + """ + if not cred or not cred.get("access_token"): + return None + if not is_oauth_credential_expired( + cred, buffer_seconds=MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS + ): + return cred + if not cred.get("refresh_token"): + return None + if prisma_client is None: + from litellm.proxy.utils import get_prisma_client_or_throw + + prisma_client = get_prisma_client_or_throw( + "Database not connected. Cannot refresh OAuth token." + ) + refreshed = await refresh_user_oauth_token( + prisma_client=prisma_client, + user_id=user_id, + server=server, + cred=cred, + ) + if not refreshed or not refreshed.get("access_token"): + return None + return refreshed + + async def approve_mcp_server( prisma_client: PrismaClient, server_id: str, @@ -919,7 +1228,7 @@ async def approve_mcp_server( ) -> LiteLLM_MCPServerTable: """Set approval_status=active and record reviewed_at.""" now = datetime.now(timezone.utc) - updated = await prisma_client.db.litellm_mcpservertable.update( + updated = await MCPServerRepository(prisma_client).table.update( where={"server_id": server_id}, data={ "approval_status": MCPApprovalStatus.active, @@ -927,7 +1236,9 @@ async def approve_mcp_server( "updated_by": touched_by, }, ) - return LiteLLM_MCPServerTable(**updated.model_dump()) + table = LiteLLM_MCPServerTable(**updated.model_dump()) + decrypt_global_env_var_values(table.env_vars) + return table async def reject_mcp_server( @@ -945,11 +1256,13 @@ async def reject_mcp_server( } if review_notes is not None: data["review_notes"] = review_notes - updated = await prisma_client.db.litellm_mcpservertable.update( + updated = await MCPServerRepository(prisma_client).table.update( where={"server_id": server_id}, data=data, ) - return LiteLLM_MCPServerTable(**updated.model_dump()) + table = LiteLLM_MCPServerTable(**updated.model_dump()) + decrypt_global_env_var_values(table.env_vars) + return table async def get_mcp_submissions( @@ -960,12 +1273,14 @@ async def get_mcp_submissions( along with a summary count breakdown by approval_status. Mirrors get_guardrail_submissions() from guardrail_endpoints.py. """ - rows = await prisma_client.db.litellm_mcpservertable.find_many( + rows = await MCPServerRepository(prisma_client).table.find_many( where={"submitted_at": {"not": None}}, order={"submitted_at": "desc"}, take=500, # safety cap; paginate if needed in a future iteration ) items = [LiteLLM_MCPServerTable(**r.model_dump()) for r in rows] + for item in items: + decrypt_global_env_var_values(item.env_vars) pending = sum( 1 for i in items if i.approval_status == MCPApprovalStatus.pending_review @@ -980,3 +1295,121 @@ async def get_mcp_submissions( rejected=rejected, items=items, ) + + +# ── Per-user MCP environment variables ──────────────────────────────────── + + +def _decode_user_env_vars(stored: str) -> Dict[str, str]: + """Decrypt a ``values_b64`` blob and parse it as a flat ``{name: value}`` dict.""" + decrypted = decrypt_value_helper( + value=stored, + key="mcp_user_env_vars", + exception_type="debug", + return_original_value=False, + ) + if decrypted is None: + if stored: + verbose_proxy_logger.warning( + "MCP per-user env vars failed to decrypt (LITELLM_SALT_KEY " + "changed?); treating as unset so the user is prompted to " + "re-enter them rather than silently forwarding ciphertext" + ) + return {} + try: + parsed = json.loads(decrypted) + except (ValueError, TypeError): + return {} + if not isinstance(parsed, dict): + return {} + return {str(k): str(v) for k, v in parsed.items()} + + +async def get_user_env_vars( + prisma_client: PrismaClient, + user_id: str, + server_id: str, +) -> Dict[str, str]: + """Return the calling user's env var dict for ``server_id`` (empty if none).""" + row = await prisma_client.db.litellm_mcpuserenvvars.find_unique( + where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} + ) + if row is None: + return {} + return _decode_user_env_vars(row.values_b64) + + +async def get_user_env_vars_bulk( + prisma_client: PrismaClient, + user_id: str, + server_ids: Iterable[str], +) -> Dict[str, Dict[str, str]]: + """Return ``{server_id: {var_name: value}}`` for one user across many servers. + + Servers with no stored row are simply absent from the result. + """ + ids = list(server_ids) + if not ids: + return {} + rows = await prisma_client.db.litellm_mcpuserenvvars.find_many( + where={"user_id": user_id, "server_id": {"in": ids}} + ) + return {row.server_id: _decode_user_env_vars(row.values_b64) for row in rows} + + +async def merge_user_env_vars( + prisma_client: PrismaClient, + user_id: str, + server_id: str, + updates: Dict[str, str], + allowed_names: Iterable[str], +) -> Dict[str, str]: + """Merge ``updates`` into the user's stored env vars for ``server_id`` and + return the resulting set. + + The read-modify-write runs inside a transaction guarded by a + ``(user_id, server_id)`` advisory lock so two concurrent writes from the + same user can't drop one update. Names outside ``allowed_names`` are pruned, + so an admin retiring a user-scoped variable also clears its stored value. + """ + allowed = set(allowed_names) + lock_key = int.from_bytes( + hashlib.blake2b(f"{user_id}:{server_id}".encode(), digest_size=8).digest(), + "big", + signed=True, + ) + async with prisma_client.db.tx() as tx: + await tx.execute_raw("SELECT pg_advisory_xact_lock($1::bigint)", lock_key) + row = await tx.litellm_mcpuserenvvars.find_unique( + where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} + ) + existing = _decode_user_env_vars(row.values_b64) if row is not None else {} + merged = {k: v for k, v in {**existing, **updates}.items() if k in allowed} + encoded = encrypt_value_helper(json.dumps(merged)) + await tx.litellm_mcpuserenvvars.upsert( + where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}, + data={ + "create": { + "user_id": user_id, + "server_id": server_id, + "values_b64": encoded, + }, + "update": {"values_b64": encoded}, + }, + ) + return merged + + +async def delete_user_env_vars( + prisma_client: PrismaClient, + user_id: str, + server_id: str, +) -> None: + """Remove the calling user's env var values for ``server_id``. + + Uses ``delete_many`` so a missing row is a no-op; real DB errors still + propagate to the caller instead of being silently swallowed. + """ + await prisma_client.db.litellm_mcpuserenvvars.delete_many( + where={"user_id": user_id, "server_id": server_id} + ) diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py index ed374635fea..3beddd2c435 100644 --- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py @@ -512,12 +512,13 @@ async def exchange_token_with_server( result = { "access_token": access_token, "token_type": token_response.get("token_type", "Bearer"), - "expires_in": token_response.get("expires_in", 3600), } - if "refresh_token" in token_response and token_response["refresh_token"]: + if token_response.get("expires_in") is not None: + result["expires_in"] = token_response["expires_in"] + if token_response.get("refresh_token"): result["refresh_token"] = token_response["refresh_token"] - if "scope" in token_response and token_response["scope"]: + if token_response.get("scope"): result["scope"] = token_response["scope"] # RFC 6749 §5.1: token responses must not be cached. diff --git a/litellm/proxy/_experimental/mcp_server/elicitation_handler.py b/litellm/proxy/_experimental/mcp_server/elicitation_handler.py new file mode 100644 index 00000000000..e42270bf10b --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/elicitation_handler.py @@ -0,0 +1,163 @@ +""" +MCP Elicitation Handler +Handles `elicitation/create` requests from upstream MCP servers by either: +1. Relaying them to the connected downstream MCP client (if it supports elicitation) +2. Returning a decline/error response (if no downstream client or unsupported) +Supports both Form mode (structured data collection) and URL mode (external URL +navigation for sensitive interactions like OAuth). +MCP Spec Reference: + https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation +""" + +from typing import Any, Optional, Union +from litellm._logging import verbose_logger + +# Guard imports that require the mcp package +try: + from mcp.types import ( + ElicitRequestFormParams, + ElicitRequestParams, + ElicitRequestURLParams, + ElicitResult, + ErrorData, + ) + + MCP_ELICITATION_AVAILABLE = True +except ImportError: + MCP_ELICITATION_AVAILABLE = False + + +async def handle_elicitation_request( + context: Any, + params: "ElicitRequestParams", + downstream_session: Optional[Any] = None, + downstream_capabilities: Optional[Any] = None, +) -> Union["ElicitResult", "ErrorData"]: + """ + Handle an MCP elicitation/create request from an upstream MCP server. + In Gateway mode (Mode A), we relay the elicitation request to the + connected downstream client if they declared elicitation capabilities. + In Tool Bridge mode (Mode B), there's no persistent downstream MCP + client, so we return a decline response. + Args: + context: MCP RequestContext from the upstream server connection. + params: The ElicitRequestParams (either form or URL mode). + downstream_session: The ServerSession to the downstream client, + if available (for relaying). + downstream_capabilities: The downstream client's declared + capabilities, used to check elicitation support. + Returns: + ElicitResult with the user's response, or ErrorData on failure. + """ + if not MCP_ELICITATION_AVAILABLE: + return ErrorData( + code=-1, + message="MCP elicitation is not available (mcp package not installed)", + ) + try: + mode = getattr(params, "mode", "form") + verbose_logger.info( + "MCP elicitation: received request mode=%s, message=%s", + mode, + getattr(params, "message", ""), + ) + # Check if we have a downstream session to relay to + if downstream_session is not None: + return await _relay_elicitation_to_downstream( + params=params, + downstream_session=downstream_session, + downstream_capabilities=downstream_capabilities, + ) + # No downstream session — we're in Tool Bridge mode + # or the client doesn't support elicitation + verbose_logger.info( + "MCP elicitation: no downstream session available, declining" + ) + return ElicitResult( + action="decline", + ) + except Exception as e: + verbose_logger.exception("MCP elicitation handler failed: %s", e) + return ErrorData( + code=-1, + message=f"Elicitation failed: {str(e)}", + ) + + +async def _relay_elicitation_to_downstream( + params: "ElicitRequestParams", + downstream_session: Any, + downstream_capabilities: Optional[Any] = None, +) -> Union["ElicitResult", "ErrorData"]: + """ + Relay an elicitation request to the downstream MCP client. + Uses the ServerSession's elicit_form() or elicit_url() methods to + send the elicitation request back to the connected client. + Args: + params: The elicitation request parameters. + downstream_session: The ServerSession connected to the downstream client. + downstream_capabilities: Client capabilities to check support. + Returns: + ElicitResult from the downstream client. + """ + mode = getattr(params, "mode", "form") + # Check if the downstream client supports the requested mode + if downstream_capabilities is not None: + elicit_caps = getattr(downstream_capabilities, "elicitation", None) + if elicit_caps is None: + verbose_logger.info( + "MCP elicitation: downstream client does not support elicitation" + ) + return ElicitResult(action="decline") + if mode == "url": + url_cap = getattr(elicit_caps, "url", None) + if url_cap is None: + verbose_logger.info( + "MCP elicitation: downstream client does not support URL mode" + ) + return ElicitResult(action="decline") + if mode == "form": + form_cap = getattr(elicit_caps, "form", None) + if form_cap is None: + verbose_logger.info( + "MCP elicitation: downstream client does not support form mode" + ) + return ElicitResult(action="decline") + try: + if mode == "url" and isinstance(params, ElicitRequestURLParams): + # URL mode: relay URL to client for external navigation + verbose_logger.info( + "MCP elicitation: relaying URL mode to downstream, url=%s", + getattr(params, "url", ""), + ) + result = await downstream_session.elicit_url( + message=params.message, + url=params.url, + elicitation_id=getattr(params, "elicitationId", None), + ) + elif isinstance(params, ElicitRequestFormParams): + # Form mode: relay structured form to client + verbose_logger.info("MCP elicitation: relaying form mode to downstream") + result = await downstream_session.elicit_form( + message=params.message, + requestedSchema=getattr(params, "requestedSchema", None), + ) + else: + # Fallback for generic ElicitRequestParams — pass an empty schema + # since elicit() requires requestedSchema as a positional arg. + verbose_logger.info( + "MCP elicitation: relaying generic elicitation to downstream" + ) + result = await downstream_session.elicit( + message=getattr(params, "message", ""), + requestedSchema=getattr(params, "requestedSchema", {}), + ) + verbose_logger.info( + "MCP elicitation: downstream responded with action=%s", + getattr(result, "action", "unknown"), + ) + return result + except Exception as e: + verbose_logger.warning("MCP elicitation: failed to relay to downstream: %s", e) + # If relay fails, decline gracefully + return ElicitResult(action="decline") diff --git a/litellm/proxy/_experimental/mcp_server/exceptions.py b/litellm/proxy/_experimental/mcp_server/exceptions.py index fd8fc3d5e58..a00e797a6bd 100644 --- a/litellm/proxy/_experimental/mcp_server/exceptions.py +++ b/litellm/proxy/_experimental/mcp_server/exceptions.py @@ -10,8 +10,9 @@ class MCPUpstreamAuthError(Exception): (typically HTTP 401) and the gateway should surface it transparently to the client instead of swallowing it. - Only relevant for pass-through MCP servers (see - ``MCPServer.is_oauth_passthrough``). The gateway converts this exception + Relevant for MCP servers that delegate OAuth to the upstream server, + including pass-through servers and OAuth2 servers with + ``delegate_auth_to_upstream`` enabled. The gateway converts this exception into an HTTP 401 response on single-server routes, preserving any ``WWW-Authenticate`` challenge emitted by the upstream so standards- compliant MCP clients can trigger the upstream OAuth flow. diff --git a/litellm/proxy/_experimental/mcp_server/mcp_context.py b/litellm/proxy/_experimental/mcp_server/mcp_context.py index a60138dd340..51918509441 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_context.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_context.py @@ -19,3 +19,9 @@ _mcp_active_toolset_id: ContextVar[Optional[str]] = ContextVar( _mcp_gateway_initialize_instructions: ContextVar[Optional[str]] = ContextVar( "_mcp_gateway_initialize_instructions", default=None ) + +# Per-request scoped server name; set in MCP HTTP/SSE handlers when the path +# identifies exactly one upstream server. Never populated from client-supplied headers. +_mcp_gateway_server_name: ContextVar[Optional[str]] = ContextVar( + "_mcp_gateway_server_name", default=None +) diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py index d9b112f6c21..5e419b5c0a3 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py @@ -42,30 +42,42 @@ from litellm.constants import ( MCP_TOOL_LISTING_TIMEOUT, ) from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException -from litellm.litellm_core_utils.url_utils import SSRFError, async_safe_get from litellm.experimental_mcp_client.client import MCPClient, MCPSigV4Auth +from litellm.litellm_core_utils.url_utils import SSRFError, async_safe_get from litellm.llms.custom_httpx.http_handler import get_async_httpx_client from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import ( MCPRequestHandler, ) from litellm.proxy._experimental.mcp_server.exceptions import MCPUpstreamAuthError +from litellm.proxy._experimental.mcp_server.elicitation_handler import ( + MCP_ELICITATION_AVAILABLE, +) +from litellm.proxy._experimental.mcp_server.sampling_handler import ( + MCP_SAMPLING_AVAILABLE, +) from litellm.proxy._experimental.mcp_server.oauth2_token_cache import resolve_mcp_auth from litellm.proxy._experimental.mcp_server.utils import ( MCP_TOOL_PREFIX_SEPARATOR, + MCPMissingUserEnvVarsError, add_server_prefix_to_name, + build_env_var_setup_url, + collect_env_var_references, compute_short_server_prefix, get_server_prefix, + interpolate_headers, is_short_mcp_tool_prefix_enabled, is_tool_name_prefixed, iter_known_server_prefixes, merge_mcp_headers, normalize_server_name, + parse_admin_env_vars, split_server_prefix_from_name, validate_mcp_server_name, ) from litellm.proxy._types import ( LiteLLM_MCPServerTable, MCPAuthType, + MCPEnvVar, MCPTransport, MCPTransportType, UserAPIKeyAuth, @@ -73,6 +85,7 @@ from litellm.proxy._types import ( from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_value_helper from litellm.proxy.utils import ProxyLogging +from litellm.repositories.table_repositories import MCPServerRepository from litellm.types.llms.custom_http import httpxSpecialProvider from litellm.types.mcp import MCPAuth, MCPStdioConfig from litellm.types.mcp_server.mcp_server_manager import ( @@ -118,6 +131,33 @@ _AZURE_ENTRA_HOSTS = { "login.chinacloudapi.cn", # China } +# Short-lived in-memory cache for per-user MCP env var values, mirroring the +# BYOK credential cache. Keyed by (user_id, server_id); value is +# (values_dict, monotonic_timestamp). Keeps the tool-call and tool-listing +# paths off the DB on every request within the TTL window. +_user_env_vars_cache: Dict[Tuple[str, str], Tuple[Dict[str, str], float]] = {} +_USER_ENV_VARS_CACHE_TTL = 60 # seconds +_USER_ENV_VARS_CACHE_MAX_SIZE = 4096 # cap to prevent unbounded growth + + +def invalidate_user_env_vars_cache(user_id: str, server_id: str) -> None: + """Drop a cached entry after the user stores or clears their env var values + so the next request reads the fresh value instead of a stale one.""" + _user_env_vars_cache.pop((user_id, server_id), None) + + +def _write_user_env_vars_cache( + user_id: str, server_id: str, values: Dict[str, str] +) -> None: + cache_key = (user_id, server_id) + # Re-insert at the tail so eviction drops the oldest-written entry, not a + # freshly refreshed one, and only sheds a single entry instead of wiping the + # whole cache (which would stampede the DB). + _user_env_vars_cache.pop(cache_key, None) + if len(_user_env_vars_cache) >= _USER_ENV_VARS_CACHE_MAX_SIZE: + _user_env_vars_cache.pop(next(iter(_user_env_vars_cache)), None) + _user_env_vars_cache[cache_key] = (values, time.monotonic()) + def _should_strip_caller_authorization( mcp_server: MCPServer, @@ -289,6 +329,153 @@ def _deserialize_json_dict(data: Any) -> Optional[Dict[str, str]]: return data +def _deserialize_json_list(data: Any) -> Optional[List[Dict[str, Any]]]: + """Deserialize a JSON array stored in the DB (``env_vars`` and friends). + + Returns ``None`` for empty / null / unparseable input. Accepts strings + (raw JSON), already-materialized lists of dicts, and lists of Pydantic + models (Prisma may hydrate a JSON column such as ``env_vars`` into + ``MCPEnvVar`` objects); model entries are normalized to plain dicts so + downstream consumers expecting ``List[Dict[str, Any]]`` validate. + """ + if data is None or data == "" or data == []: + return None + if isinstance(data, str): + try: + parsed = json.loads(data) + except (json.JSONDecodeError, TypeError): + return None + data = parsed + if not isinstance(data, list): + return None + return [ + item.model_dump(mode="json") if hasattr(item, "model_dump") else item + for item in data + ] + + +def _normalize_mcp_server_cost_info(mcp_info: MCPInfo) -> None: + """Coerce ``mcp_server_cost_info`` numeric fields to ``float`` at ingest. + + YAML 1.1 parses scientific notation without a decimal point (e.g. + ``7e-05``) as a string, and ``MCPServerCostInfo`` is a TypedDict with no + runtime validation, so string-typed costs flow through to the UI and + crash its ``.toFixed`` formatting. Values that cannot be coerced are + dropped with a warning instead of failing the server load. + """ + cost_info = mcp_info.get("mcp_server_cost_info") + if not isinstance(cost_info, dict): + return + + server_name = mcp_info.get("server_name") + normalized = dict(cost_info) + + default_cost = normalized.get("default_cost_per_query") + if default_cost is not None: + try: + normalized["default_cost_per_query"] = float(default_cost) + except (TypeError, ValueError): + verbose_logger.warning( + "MCP server '%s' has non-numeric default_cost_per_query %r; ignoring it", + server_name, + default_cost, + ) + del normalized["default_cost_per_query"] + + tool_costs = normalized.get("tool_name_to_cost_per_query") + if isinstance(tool_costs, dict): + normalized_tool_costs = {} + for tool_name, cost in tool_costs.items(): + try: + normalized_tool_costs[tool_name] = float(cost) + except (TypeError, ValueError): + verbose_logger.warning( + "MCP server '%s' has non-numeric cost %r for tool '%s'; ignoring it", + server_name, + cost, + tool_name, + ) + normalized["tool_name_to_cost_per_query"] = normalized_tool_costs + + mcp_info["mcp_server_cost_info"] = normalized + + +def _create_sampling_callback(user_api_key_auth: Optional[Any] = None): + """ + Create a sampling callback for MCP ClientSession. + Returns a callable that handles sampling/createMessage requests from + upstream MCP servers by routing them through litellm.acompletion(). + """ + if not MCP_SAMPLING_AVAILABLE: + return None + + async def _sampling_callback(context, params): + from litellm.proxy._experimental.mcp_server.sampling_handler import ( + handle_sampling_create_message, + ) + import litellm + from litellm.proxy._experimental.mcp_server.server import ( + get_active_auth_context, + ) + + auth_context = get_active_auth_context() + resolved_auth = user_api_key_auth or ( + auth_context.user_api_key_auth if auth_context else None + ) + # Forward original HTTP headers and client IP so that + # header-dependent guardrails, tag-based routing, trace + # correlation, and forward_llm_provider_auth_headers work + # correctly for sampling sub-calls. + _raw_headers = getattr(auth_context, "raw_headers", None) + _client_ip = getattr(auth_context, "client_ip", None) + + return await handle_sampling_create_message( + context=context, + params=params, + default_model=getattr(litellm, "default_mcp_sampling_model", None), + user_api_key_auth=resolved_auth, + raw_headers=_raw_headers, + client_ip=_client_ip, + ) + + return _sampling_callback + + +def _create_elicitation_callback(): + """ + Create an elicitation callback for MCP ClientSession. + Returns a callable that handles elicitation/create requests from + upstream MCP servers. In gateway mode, this relays to the downstream + client; in tool bridge mode, it returns a decline response. + """ + if not MCP_ELICITATION_AVAILABLE: + return None + + async def _elicitation_callback(context, params): + from litellm.proxy._experimental.mcp_server.elicitation_handler import ( + handle_elicitation_request, + ) + from litellm.proxy._experimental.mcp_server.server import get_active_mcp_session + + # In Gateway mode, we relay the elicitation request to the downstream client + # that triggered the current operation. + downstream_session = get_active_mcp_session() + downstream_capabilities = ( + getattr(downstream_session, "capabilities", None) + if downstream_session + else None + ) + + return await handle_elicitation_request( + context=context, + params=params, + downstream_session=downstream_session, + downstream_capabilities=downstream_capabilities, + ) + + return _elicitation_callback + + class MCPServerManager: _STDIO_ENV_TEMPLATE_PATTERN = re.compile(r"^\$\{(X-[^}]+)\}$") @@ -374,7 +561,8 @@ class MCPServerManager: - server is OpenAPI (spec_path), - non-empty upstream instructions are already cached, - auth preconditions match health_check_server's skip rules - (per-user auth / missing static auth token), + (per-user auth / missing static auth token / static headers that + reference a per-user env var), - a prior probe attempt for this server is within MCP_HEALTH_CHECK_TIMEOUT seconds (the probe is a health-check-shaped op and already uses this knob for its inner call timeout; reusing it @@ -389,6 +577,8 @@ class MCPServerManager: return if server.requires_per_user_auth: return + if self._references_per_user_env_var(server): + return if ( server.auth_type and server.auth_type != MCPAuth.none @@ -413,8 +603,13 @@ class MCPServerManager: ) try: + resolved_static_headers = await self._resolve_static_headers_with_env_vars( + server=server, + user_api_key_auth=None, + raise_on_missing=False, + ) extra_headers: Optional[Dict[str, str]] = ( - dict(server.static_headers) if server.static_headers else None + dict(resolved_static_headers) if resolved_static_headers else None ) client = await self._create_mcp_client( server=server, @@ -472,6 +667,7 @@ class MCPServerManager: mcp_info["server_name"] = server_name if "description" not in mcp_info and server_config.get("description"): mcp_info["description"] = server_config.get("description") + _normalize_mcp_server_cost_info(mcp_info) # Use alias for name if present, else server_name alias = server_config.get("alias", None) @@ -574,6 +770,7 @@ class MCPServerManager: allowed_params=server_config.get("allowed_params", None), access_groups=server_config.get("access_groups", None), static_headers=server_config.get("static_headers", None), + env_vars=server_config.get("env_vars", None), allow_all_keys=bool(server_config.get("allow_all_keys", False)), available_on_public_internet=bool( server_config.get("available_on_public_internet", True) @@ -600,6 +797,9 @@ class MCPServerManager: "subject_token_type", "urn:ietf:params:oauth:token-type:access_token", ), + allow_sampling=bool(server_config.get("allow_sampling", False)), + allow_elicitation=bool(server_config.get("allow_elicitation", False)), + timeout=server_config.get("timeout", None), ) self._assign_unique_short_prefix(new_server) _warn_internal_delegate_pkce_if_applicable(new_server, source="config") @@ -699,8 +899,7 @@ class MCPServerManager: ) verbose_logger.debug( - f"Using headers for OpenAPI tools (excluding sensitive values): " - f"{list(headers.keys())}" + f"Using headers for OpenAPI tools (excluding sensitive values): {list(headers.keys())}" ) # Extract and register tools from OpenAPI paths @@ -836,17 +1035,41 @@ class MCPServerManager: f"Server ID {mcp_server.server_id} not found in registry" ) + def _resolve_env_vars_list( + self, + mcp_server: LiteLLM_MCPServerTable, + *, + env_vars_are_encrypted: bool, + ) -> Optional[List[Dict[str, Any]]]: + env_vars_list = _deserialize_json_list(getattr(mcp_server, "env_vars", None)) + if env_vars_are_encrypted: + from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 + decrypt_global_env_var_values, + ) + + decrypt_global_env_var_values(env_vars_list) + return env_vars_list + async def build_mcp_server_from_table( self, mcp_server: LiteLLM_MCPServerTable, *, credentials_are_encrypted: bool = True, + env_vars_are_encrypted: Optional[bool] = None, ) -> MCPServer: _mcp_info: MCPInfo = mcp_server.mcp_info or {} env_dict = _deserialize_json_dict(getattr(mcp_server, "env", None)) static_headers_dict = _deserialize_json_dict( getattr(mcp_server, "static_headers", None) ) + env_vars_list = self._resolve_env_vars_list( + mcp_server, + env_vars_are_encrypted=( + credentials_are_encrypted + if env_vars_are_encrypted is None + else env_vars_are_encrypted + ), + ) credentials_dict = _deserialize_json_dict( getattr(mcp_server, "credentials", None) ) @@ -915,6 +1138,7 @@ class MCPServerManager: mcp_info["server_name"] = mcp_server.server_name or mcp_server.server_id if "description" not in mcp_info and mcp_server.description: mcp_info["description"] = mcp_server.description + _normalize_mcp_server_cost_info(mcp_info) auth_type = cast(MCPAuthType, mcp_server.auth_type) server_url = mcp_server.url @@ -946,6 +1170,7 @@ class MCPServerManager: mcp_info=mcp_info, extra_headers=getattr(mcp_server, "extra_headers", None), static_headers=static_headers_dict, + env_vars=env_vars_list, client_id=client_id_value or getattr(mcp_server, "client_id", None), client_secret=client_secret_value or getattr(mcp_server, "client_secret", None), @@ -1013,6 +1238,7 @@ class MCPServerManager: credentials_dict.get("subject_token_type") if credentials_dict else None ) or "urn:ietf:params:oauth:token-type:access_token", + timeout=getattr(mcp_server, "timeout", None), ) _warn_internal_delegate_pkce_if_applicable(new_server, source="database") return new_server @@ -1043,7 +1269,14 @@ class MCPServerManager: return try: if mcp_server.server_id not in self.registry: - new_server = await self.build_mcp_server_from_table(mcp_server) + # Callers hand us a record returned by the db.py read/write + # helpers, which already decrypt global env var values (the + # `credentials` field is the only one still encrypted here). + # Re-decrypting plaintext would zero the values, so build with + # env_vars_are_encrypted=False. + new_server = await self.build_mcp_server_from_table( + mcp_server, env_vars_are_encrypted=False + ) self._assign_unique_short_prefix(new_server) self.registry[mcp_server.server_id] = new_server await self._maybe_register_openapi_tools(new_server) @@ -1066,7 +1299,11 @@ class MCPServerManager: return try: if mcp_server.server_id in self.registry: - new_server = await self.build_mcp_server_from_table(mcp_server) + # See add_server: db.py helpers already decrypted env var + # values, so don't decrypt them a second time here. + new_server = await self.build_mcp_server_from_table( + mcp_server, env_vars_are_encrypted=False + ) # Carry the previously-resolved short prefix across so the # tool names stay stable for clients holding cached lists. existing_prefix = self.registry[mcp_server.server_id].short_prefix @@ -1487,6 +1724,180 @@ class MCPServerManager: return resolved_env + def _references_per_user_env_var(self, server: MCPServer) -> bool: + """True when ``server.static_headers`` reference a per-user ``${NAME}`` env var. + + Such placeholders can only be filled from a calling user's stored values, + so a userless probe (health check / instructions prefetch) would forward + the literal ``${NAME}`` upstream and get rejected. Callers skip the probe + and report ``unknown`` instead of a misleading ``unhealthy``. + """ + static_headers = server.static_headers + env_vars = getattr(server, "env_vars", None) + if not static_headers or not env_vars: + return False + _global_values, user_specs = parse_admin_env_vars(env_vars) + user_var_names = {spec["name"] for spec in user_specs} + if not user_var_names: + return False + referenced = collect_env_var_references(strings=static_headers.values()) + return bool(referenced & user_var_names) + + async def _resolve_static_headers_with_env_vars( + self, + server: MCPServer, + user_api_key_auth: Optional[UserAPIKeyAuth], + *, + raise_on_missing: bool = True, + ) -> Optional[Dict[str, str]]: + """Return server.static_headers with ``${NAME}`` interpolated. + + Globals come from ``server.env_vars`` entries with ``scope=="global"``. + Per-user values come from the ``LiteLLM_MCPUserEnvVars`` row for the + calling user. + + When ``raise_on_missing`` is ``True`` (the tool-*call* path), raises + ``MCPMissingUserEnvVarsError`` if ``static_headers`` reference a per-user + variable the calling user has not yet supplied — converted into a + user-facing 412 by the REST layer. + + When ``raise_on_missing`` is ``False`` (the tool-*list* path), missing + per-user vars are non-blocking: we interpolate whatever is available and + leave unfilled ``${NAME}`` references untouched, so the server's tools + still appear in the listing. The user only hits the friendly error when + they actually invoke a tool that needs the missing value. + """ + static_headers = server.static_headers + env_vars = getattr(server, "env_vars", None) + if not static_headers and not env_vars: + return static_headers + + global_values, user_specs = parse_admin_env_vars(env_vars) + # An empty-valued global is treated as unset: it must not mask a per-user + # var the user still has to supply, nor override a value the user did + # supply. The unresolved ${NAME} is then left untouched, like any other + # undefined reference. + global_values = {name: value for name, value in global_values.items() if value} + user_var_names = {spec["name"] for spec in user_specs} + + # If no env vars are configured, return static_headers as-is. + if not global_values and not user_specs: + return static_headers + + # Figure out which user-scoped vars are actually referenced. A var that + # also carries a global value is always covered by that global (globals + # win in the merge below), so it can never be genuinely "missing" even if + # the user hasn't filled it in -- only vars without a global fallback do. + referenced = collect_env_var_references(strings=(static_headers or {}).values()) + referenced_user_vars = referenced & user_var_names + required_user_vars = { + name for name in referenced_user_vars if name not in global_values + } + + user_values: Dict[str, str] = {} + if required_user_vars: + try: + user_values = await self._load_user_env_vars(server, user_api_key_auth) + except Exception as exc: + # On the tool-call path a DB failure must surface as a real + # server error, not a misleading "set up your credentials" 412. + # On the listing path we stay best-effort and leave the + # unfilled ${NAME} references untouched so tools still appear. + if raise_on_missing: + raise + verbose_logger.warning( + "MCPServerManager: best-effort user env var load failed for " + "server=%s: %s", + server.server_id, + exc, + ) + + if raise_on_missing: + missing = sorted( + name for name in required_user_vars if not user_values.get(name) + ) + if missing: + # A cached negative must never produce a 412: cache + # invalidation is process-local, so a user who just stored + # values on another worker would otherwise be told their + # credentials are missing until the entry expires. Confirm + # against the DB before raising. + user_values = await self._load_user_env_vars( + server, user_api_key_auth, force_refresh=True + ) + missing = sorted( + name for name in required_user_vars if not user_values.get(name) + ) + if missing: + raise MCPMissingUserEnvVarsError( + server_id=server.server_id, + server_name=server.server_name or server.name, + missing=missing, + setup_url=build_env_var_setup_url(server.server_id), + ) + + # Only honor stored user values for currently user-scoped vars, and let + # admin globals win, so a stale row from when a var was user-scoped can + # never override the global value the admin set after switching it. + scoped_user_values = { + name: value for name, value in user_values.items() if name in user_var_names + } + merged_vars: Dict[str, str] = {**scoped_user_values, **global_values} + if not static_headers: + return static_headers + return interpolate_headers(static_headers, merged_vars) + + async def _load_user_env_vars( + self, + server: MCPServer, + user_api_key_auth: Optional[UserAPIKeyAuth], + *, + force_refresh: bool = False, + ) -> Dict[str, str]: + """Look up the calling user's env var values for ``server``. + + Returns an empty dict when no user is available. Results are cached in a + short-lived in-memory map keyed by (user_id, server_id) so the tool-call + and tool-listing paths avoid a DB round-trip per request within the TTL + window; the cache is invalidated when the user stores or clears values. + Pass ``force_refresh`` to bypass the cache read and re-fetch from the DB + (used before raising a "missing credentials" error so a process-local + stale entry cannot mask values stored on another worker). A missing DB + connection and any other DB error propagate so the caller can decide + between failing the request (tool-call path) and staying best-effort + (listing path); they must never be mistaken for "user has no values", + which would send the user a misleading "set up your credentials" 412. + """ + if user_api_key_auth is None: + return {} + user_id = getattr(user_api_key_auth, "user_id", None) + if not user_id: + return {} + + cache_key = (user_id, server.server_id) + if not force_refresh: + cached = _user_env_vars_cache.get(cache_key) + if cached is not None: + values, ts = cached + if time.monotonic() - ts < _USER_ENV_VARS_CACHE_TTL: + return values + + from litellm.proxy.proxy_server import prisma_client # noqa: PLC0415 + + if prisma_client is None: + raise RuntimeError( + "MCP per-user env vars require a database connection, but none " + "is configured. Connect a database to your proxy to use per-user " + "MCP env vars." + ) + from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 + get_user_env_vars, + ) + + values = await get_user_env_vars(prisma_client, user_id, server.server_id) + _write_user_env_vars_cache(user_id, server.server_id, values) + return values + async def _create_mcp_client( self, server: MCPServer, @@ -1494,6 +1905,7 @@ class MCPServerManager: extra_headers: Optional[Dict[str, str]] = None, stdio_env: Optional[Dict[str, str]] = None, subject_token: Optional[str] = None, + user_api_key_auth: Optional[UserAPIKeyAuth] = None, ) -> MCPClient: """ Create an MCPClient instance for the given server. @@ -1510,6 +1922,7 @@ class MCPServerManager: extra_headers: Additional headers to forward. stdio_env: Environment variables for stdio transport. subject_token: Optional user JWT for token exchange (OBO) flow. + user_api_key_auth: Optional auth context for sampling callbacks. Returns: Configured MCP client instance. @@ -1520,23 +1933,44 @@ class MCPServerManager: transport = server.transport or MCPTransport.sse + # Create sampling and elicitation callbacks for this client + sampling_cb = ( + _create_sampling_callback(user_api_key_auth=user_api_key_auth) + if server.allow_sampling + else None + ) + elicitation_cb = ( + _create_elicitation_callback() if server.allow_elicitation else None + ) + # Handle stdio transport if transport == MCPTransport.stdio: resolved_env = ( - stdio_env if stdio_env is not None else dict(server.env or {}) + stdio_env + if stdio_env is not None + else (dict(server.env) if server.env is not None else None) ) # Ensure npm-based STDIO MCP servers have a writable cache dir. # In containers the default (~/.npm or /app/.npm) may not exist # or be read-only, causing npx to fail with ENOENT. - if "NPM_CONFIG_CACHE" not in resolved_env: + if resolved_env is not None and "NPM_CONFIG_CACHE" not in resolved_env: resolved_env["NPM_CONFIG_CACHE"] = MCP_NPM_CACHE_DIR # Defense-in-depth: block commands not in the allowlist. # The Pydantic validator blocks new servers; this catches legacy # config/DB records predating the allowlist. if server.command: base_command = os.path.basename(server.command) - if base_command not in MCP_STDIO_ALLOWED_COMMANDS: + # Strip .exe/.cmd/.bat/.com suffix for Windows compatibility + base_command_no_ext = base_command.lower() + for ext in [".exe", ".cmd", ".bat", ".com"]: + if base_command.lower().endswith(ext): + base_command_no_ext = base_command[: -len(ext)].lower() + break + if ( + base_command.lower() not in MCP_STDIO_ALLOWED_COMMANDS + and base_command_no_ext not in MCP_STDIO_ALLOWED_COMMANDS + ): raise HTTPException( status_code=403, detail=f"MCP stdio command '{server.command}' is not in the allowlist ({sorted(MCP_STDIO_ALLOWED_COMMANDS)}). " @@ -1556,9 +1990,13 @@ class MCPServerManager: transport_type=transport, auth_type=server.auth_type, auth_value=auth_value, - timeout=MCP_CLIENT_TIMEOUT, + timeout=( + server.timeout if server.timeout is not None else MCP_CLIENT_TIMEOUT + ), stdio_config=stdio_config, extra_headers=extra_headers, + sampling_callback=sampling_cb, + elicitation_callback=elicitation_cb, ) else: # For HTTP/SSE transports @@ -1582,9 +2020,13 @@ class MCPServerManager: transport_type=transport, auth_type=server.auth_type, auth_value=auth_value, - timeout=MCP_CLIENT_TIMEOUT, + timeout=( + server.timeout if server.timeout is not None else MCP_CLIENT_TIMEOUT + ), extra_headers=extra_headers, aws_auth=aws_auth, + sampling_callback=sampling_cb, + elicitation_callback=elicitation_cb, ) async def _get_tools_from_server( @@ -1616,10 +2058,17 @@ class MCPServerManager: client = None try: - if server.static_headers: + # Tool *listing* must not be blocked by missing per-user env vars — + # the server's tools should still appear so the client connects. The + # friendly "missing vars" error is raised only on the tool-*call* + # path (see _call_regular_mcp_tool). + resolved_static_headers = await self._resolve_static_headers_with_env_vars( + server, user_api_key_auth, raise_on_missing=False + ) + if resolved_static_headers: if extra_headers is None: extra_headers = {} - extra_headers.update(server.static_headers) + extra_headers.update(resolved_static_headers) # MCPJWTSigner: inject signed JWT for tools/list (list path skips pre_call_hook). # Skip entirely when the signer is not configured (avoid an unnecessary @@ -1668,6 +2117,7 @@ class MCPServerManager: mcp_auth_header=mcp_auth_header, extra_headers=extra_headers, stdio_env=stdio_env, + user_api_key_auth=user_api_key_auth, ) ## HANDLE OPENAPI TOOLS @@ -2327,28 +2777,40 @@ class MCPServerManager: Uses anyio.fail_after() instead of asyncio.wait_for() to avoid conflicts with the MCP SDK's anyio TaskGroup. See GitHub issue #20715 for details. - For pass-through MCP servers (``MCPServer.is_oauth_passthrough``) an + For OAuth pass-through and upstream-delegated OAuth2 MCP servers, an upstream HTTP 401 is converted into :class:`MCPUpstreamAuthError` instead of being swallowed to an empty tool list. That lets the single-server HTTP routes surface a proper 401 + ``WWW-Authenticate`` challenge so standards-compliant MCP clients trigger the upstream - OAuth flow. Non-pass-through servers keep today's swallow-and-log - behaviour so the multi-server ``/mcp`` aggregator doesn't get - tainted by a single bad server. + OAuth flow. Other servers keep today's swallow-and-log behaviour so + the multi-server ``/mcp`` aggregator doesn't get tainted by a single + bad server. Args: client: MCP client instance server_name: Name of the server for logging - server: Optional MCPServer; when pass-through, auth errors are - re-raised as :class:`MCPUpstreamAuthError`. + server: Optional MCPServer; when upstream auth is delegated, auth + errors are re-raised as :class:`MCPUpstreamAuthError`. Returns: List of tools from the server """ - is_passthrough = bool(server is not None and server.is_oauth_passthrough) + should_surface_upstream_auth = bool( + server is not None + and ( + server.is_oauth_passthrough + or ( + server.auth_type == MCPAuth.oauth2 + and getattr(server, "delegate_auth_to_upstream", False) is True + and not server.has_client_credentials + ) + ) + ) try: with anyio.fail_after(MCP_TOOL_LISTING_TIMEOUT): - tools = await client.list_tools(raise_on_error=is_passthrough) + tools = await client.list_tools( + raise_on_error=should_surface_upstream_auth + ) verbose_logger.debug(f"Tools from {server_name}: {tools}") return tools except TimeoutError: @@ -2365,12 +2827,12 @@ class MCPServerManager: ) return [] except Exception as e: - if is_passthrough: + if should_surface_upstream_auth: auth_info = _extract_upstream_auth_failure(e) if auth_info is not None: status_code, www_authenticate = auth_info verbose_logger.info( - f"Upstream auth failure from pass-through MCP server " + f"Upstream auth failure from MCP server " f"{server_name}: HTTP {status_code}" ) raise MCPUpstreamAuthError( @@ -2988,10 +3450,17 @@ class MCPServerManager: continue extra_headers[header] = header_value - if mcp_server.static_headers: + # Interpolate env vars into static_headers. Raises + # MCPMissingUserEnvVarsError when the calling user has not filled in + # a required per-user variable — the REST layer converts that into + # a friendly 412 with a setup URL. + resolved_static_headers = await self._resolve_static_headers_with_env_vars( + mcp_server, user_api_key_auth + ) + if resolved_static_headers: if extra_headers is None: extra_headers = {} - extra_headers.update(mcp_server.static_headers) + extra_headers.update(resolved_static_headers) if hook_extra_headers: if extra_headers is None: @@ -3030,6 +3499,7 @@ class MCPServerManager: extra_headers=extra_headers, stdio_env=stdio_env, subject_token=subject_token, + user_api_key_auth=user_api_key_auth, ) call_tool_params = MCPCallToolRequestParams( @@ -3046,14 +3516,26 @@ class MCPServerManager: asyncio.create_task(_call_tool_via_client(client, call_tool_params)) ) + _timeout = ( + mcp_server.timeout if mcp_server.timeout is not None else MCP_CLIENT_TIMEOUT + ) try: - mcp_responses = await asyncio.gather(*tasks) + mcp_responses = await asyncio.wait_for( + asyncio.gather(*tasks), timeout=_timeout + ) + except asyncio.TimeoutError: + raise HTTPException( + status_code=504, + detail={ + "error": "timeout", + "message": f"MCP tool call timed out after {_timeout}s", + }, + ) except ( BlockedPiiEntityError, GuardrailRaisedException, HTTPException, ) as e: - # Re-raise guardrail exceptions to properly fail the MCP call verbose_logger.error( f"Guardrail blocked MCP tool call during result check: {str(e)}" ) @@ -3260,7 +3742,6 @@ class MCPServerManager: ) ) else: - # For regular MCP servers, use the MCP client return await self._call_regular_mcp_tool( mcp_server=mcp_server, original_tool_name=name, @@ -3397,7 +3878,7 @@ class MCPServerManager: # Pending/rejected servers are excluded at the DB level so we never load them. from litellm.proxy._experimental.mcp_server.db import LiteLLM_MCPServerTable - raw_rows = await prisma_client.db.litellm_mcpservertable.find_many( + raw_rows = await MCPServerRepository(prisma_client).table.find_many( where={ "OR": [ {"approval_status": None}, @@ -3437,7 +3918,13 @@ class MCPServerManager: verbose_logger.debug( f"Building server from DB: {server.server_id} ({server.server_name})" ) - new_server = await self.build_mcp_server_from_table(server) + # raw_rows come straight from the DB, so their global env var + # values (like credentials) are still encrypted here, unlike the + # already-decrypted records add_server/update_server are handed. + # Decrypt them while building the registry entry. + new_server = await self.build_mcp_server_from_table( + server, env_vars_are_encrypted=True + ) # Carry the cached short_prefix from the previous registry entry # (if any) so the prefix is stable across reloads. if existing_server is not None and existing_server.short_prefix: @@ -3777,11 +4264,21 @@ class MCPServerManager: and not server.authentication_token ): should_skip_health_check = True + # Skip if static_headers reference a per-user env var: a userless probe + # can't fill ${NAME} and would forward the literal placeholder upstream, + # flipping the server to unhealthy even though real user calls succeed. + elif self._references_per_user_env_var(server): + should_skip_health_check = True if not should_skip_health_check: - extra_headers = {} - if server.static_headers: - extra_headers.update(server.static_headers) + resolved_static_headers = await self._resolve_static_headers_with_env_vars( + server=server, + user_api_key_auth=None, + raise_on_missing=False, + ) + extra_headers = ( + dict(resolved_static_headers) if resolved_static_headers else {} + ) client = await self._create_mcp_client( server=server, @@ -3831,6 +4328,7 @@ class MCPServerManager: extra_headers=server.extra_headers or [], mcp_info=server.mcp_info, static_headers=server.static_headers, + env_vars=self._env_vars_to_models(server.env_vars), status=status, last_health_check=datetime.now(), health_check_error=health_check_error, @@ -3842,6 +4340,7 @@ class MCPServerManager: registration_url=server.registration_url, allow_all_keys=server.allow_all_keys, instructions=server.instructions, + timeout=server.timeout, ) async def get_all_mcp_servers_with_health_and_teams( @@ -3903,6 +4402,14 @@ class MCPServerManager: return list_mcp_servers + @staticmethod + def _env_vars_to_models( + env_vars: Optional[List[Dict[str, Any]]], + ) -> Optional[List[MCPEnvVar]]: + if env_vars is None: + return None + return [MCPEnvVar.model_validate(env_var) for env_var in env_vars] + def _build_mcp_server_table(self, server: MCPServer) -> LiteLLM_MCPServerTable: return LiteLLM_MCPServerTable( server_id=server.server_id, @@ -3923,6 +4430,7 @@ class MCPServerManager: extra_headers=server.extra_headers or [], mcp_info=server.mcp_info, static_headers=server.static_headers, + env_vars=self._env_vars_to_models(server.env_vars), status=None, # No health check performed last_health_check=None, # No health check performed health_check_error=None, @@ -3941,6 +4449,7 @@ class MCPServerManager: byok_api_key_help_url=server.byok_api_key_help_url, source_url=server.source_url, instructions=server.instructions, + timeout=server.timeout, ) async def get_all_mcp_servers_unfiltered(self) -> List[LiteLLM_MCPServerTable]: diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py index e20c9f3a082..2149f079a3d 100644 --- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py @@ -1,3 +1,4 @@ +import asyncio import importlib from datetime import datetime from typing import ( @@ -13,6 +14,7 @@ from typing import ( Union, ) +import httpx from fastapi import APIRouter, Depends, HTTPException, Query, Request, status from litellm._logging import verbose_logger @@ -20,7 +22,10 @@ from litellm.proxy._experimental.mcp_server.exceptions import MCPUpstreamAuthErr from litellm.proxy._experimental.mcp_server.ui_session_utils import ( build_effective_auth_contexts, ) -from litellm.proxy._experimental.mcp_server.utils import merge_mcp_headers +from litellm.proxy._experimental.mcp_server.utils import ( + MCPMissingUserEnvVarsError, + merge_mcp_headers, +) from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.auth.user_api_key_auth import user_api_key_auth @@ -41,6 +46,28 @@ router = APIRouter( tags=["mcp"], ) + +def _connection_error_message(exc: BaseException) -> str: + if isinstance(exc, httpx.LocalProtocolError): + return ( + "Failed to connect to MCP server: a request header is malformed. " + "Check static headers for leading/trailing spaces or illegal characters." + ) + if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)): + return ( + "Failed to connect to MCP server: the server is unreachable. " + "Check the URL and that the server is running." + ) + if isinstance(exc, httpx.TimeoutException): + return "Failed to connect to MCP server: the connection timed out." + if isinstance(exc, httpx.HTTPStatusError): + return ( + f"Failed to connect to MCP server: it returned HTTP " + f"{exc.response.status_code}." + ) + return "Failed to connect to MCP server. Check proxy logs for details." + + if MCP_AVAILABLE: from mcp.types import Tool as MCPTool @@ -119,9 +146,10 @@ if MCP_AVAILABLE: try: from litellm.proxy._experimental.mcp_server.db import ( get_user_oauth_credential, - is_oauth_credential_expired, + resolve_valid_user_oauth_token, ) + prisma_client = None if prefetched_creds is not None: cred = prefetched_creds.get(server_id) else: @@ -133,13 +161,13 @@ if MCP_AVAILABLE: cred = await get_user_oauth_credential( prisma_client, user_id, server_id ) + cred = await resolve_valid_user_oauth_token( + user_id=user_id, + server=server, + cred=cred, + prisma_client=prisma_client, + ) if cred and cred.get("access_token"): - if is_oauth_credential_expired(cred): - verbose_logger.debug( - f"_get_user_oauth_extra_headers: token expired for " - f"user={user_id} server={server_id}" - ) - return None return {"Authorization": f"Bearer {cred['access_token']}"} except Exception as e: verbose_logger.warning( @@ -358,8 +386,15 @@ if MCP_AVAILABLE: raw_headers: Optional[Dict[str, str]] = None, user_api_key_auth: Optional[UserAPIKeyAuth] = None, extra_headers: Optional[Dict[str, str]] = None, + apply_tool_filters: bool = True, ): - """Helper function to get tools for a single server.""" + """Helper function to get tools for a single server. + + When ``apply_tool_filters`` is False the raw server catalog is returned + without the allowed_tools/disallowed_tools gate or the per-key tool + permissions. This is the admin-only configuration view; every runtime + path keeps the default True so callable tools stay filtered. + """ tools = await global_mcp_server_manager._get_tools_from_server( server=server, mcp_auth_header=server_auth_header, @@ -369,6 +404,9 @@ if MCP_AVAILABLE: user_api_key_auth=user_api_key_auth, ) + if not apply_tool_filters: + return _create_tool_response_objects(tools, server.mcp_info) + # Always apply allowed_tools/disallowed_tools so the blacklist is # enforced even when no allowlist is set (matches the SSE/HTTP path). tools = filter_tools_by_allowed_tools(tools, server) @@ -435,6 +473,7 @@ if MCP_AVAILABLE: mcp_auth_header: Optional[str], raw_headers_from_request: dict, user_api_key_dict: UserAPIKeyAuth, + apply_tool_filters: bool = True, ) -> dict: """Handle tool listing for a single server_id request.""" # Resolve a server name to its UUID if needed @@ -499,6 +538,7 @@ if MCP_AVAILABLE: raw_headers_from_request, user_api_key_dict, extra_headers=user_oauth_extra_headers, + apply_tool_filters=apply_tool_filters, ) except MCPUpstreamAuthError: # Surface the upstream 401/403 to the caller so it can emit the @@ -524,6 +564,14 @@ if MCP_AVAILABLE: server_id: Optional[str] = Query( None, description="The server id to list tools for" ), + include_disabled_tools: bool = Query( + False, + description=( + "Admin only. Return the full server tool catalog without the " + "allowed_tools filter or per-key tool permissions, so the MCP " + "settings UI can configure the allowlist. Ignored for non-admins." + ), + ), user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ) -> dict: """ @@ -551,6 +599,13 @@ if MCP_AVAILABLE: ) try: + # The full catalog (allowlist filter skipped) is admin-only so the + # REST endpoint can't be used to enumerate deliberately-disabled tools. + apply_tool_filters = not ( + include_disabled_tools + and user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN + ) + # Extract auth headers from request headers = request.headers raw_headers_from_request = dict(headers) @@ -592,6 +647,7 @@ if MCP_AVAILABLE: mcp_auth_header=mcp_auth_header, raw_headers_from_request=raw_headers_from_request, user_api_key_dict=user_api_key_dict, + apply_tool_filters=apply_tool_filters, ) else: if not allowed_server_ids: @@ -649,6 +705,7 @@ if MCP_AVAILABLE: raw_headers_from_request, user_api_key_dict, extra_headers=user_oauth_extra_headers, + apply_tool_filters=apply_tool_filters, ) list_tools_result.extend(tools_result) except Exception as e: @@ -812,6 +869,23 @@ if MCP_AVAILABLE: requested_server_id=canonical_server_id, ) return result + except MCPMissingUserEnvVarsError as e: + verbose_logger.info( + "MCP tool call missing per-user env vars: server_id=%s missing=%s", + e.server_id, + e.missing, + ) + raise HTTPException( + status_code=412, + detail={ + "error": "missing_user_env_vars", + "message": str(e), + "server_id": e.server_id, + "server_name": e.server_name, + "missing": e.missing, + "setup_url": e.setup_url, + }, + ) except BlockedPiiEntityError as e: verbose_logger.error(f"BlockedPiiEntityError in MCP tool call: {str(e)}") raise HTTPException( @@ -961,14 +1035,14 @@ if MCP_AVAILABLE: return await operation(client) - except (KeyboardInterrupt, SystemExit): + except (KeyboardInterrupt, SystemExit, asyncio.CancelledError): raise except BaseException as e: verbose_logger.error("Error in MCP operation: %s", e, exc_info=True) return { "status": "error", "error": True, - "message": "Failed to connect to MCP server. Check proxy logs for details.", + "message": _connection_error_message(e), } async def _preview_openapi_tools(spec_path: str) -> dict: diff --git a/litellm/proxy/_experimental/mcp_server/sampling_handler.py b/litellm/proxy/_experimental/mcp_server/sampling_handler.py new file mode 100644 index 00000000000..1637c9eb0b9 --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/sampling_handler.py @@ -0,0 +1,1279 @@ +""" +MCP Sampling Handler +Handles `sampling/createMessage` requests from upstream MCP servers by +routing them through LiteLLM's internal completion infrastructure. +This allows MCP servers to perform agentic reasoning (e.g., multi-step +tool calling, chain-of-thought) without needing their own LLM API keys — +LiteLLM acts as the LLM provider using its existing 100+ provider support, +cost tracking, rate limiting, and model routing. +MCP Spec Reference: + https://modelcontextprotocol.io/specification/2025-11-25/client/sampling +""" + +from typing import Any, Dict, List, Optional, Union +import typing + +if typing.TYPE_CHECKING: + from litellm.proxy.utils import ProxyLogging + +from litellm._logging import verbose_logger + +from fastapi import HTTPException + +# Guard imports that require the mcp package +try: + from mcp.types import ( + CreateMessageRequestParams, + CreateMessageResult, + CreateMessageResultWithTools, + ErrorData, + ModelPreferences, + SamplingMessage, + TextContent, + Tool, + ToolChoice, + ToolUseContent, + ) + + MCP_SAMPLING_AVAILABLE = True +except ImportError as _sampling_import_err: + MCP_SAMPLING_AVAILABLE = False + verbose_logger.warning( + "MCP sampling disabled: failed to import required types from mcp.types — %s. " + "This usually means the 'mcp' package is not installed or is an older version " + "that does not support sampling. Install/upgrade with: pip install 'mcp>=1.1'", + _sampling_import_err, + ) + + +def _resolve_model_from_preferences( + model_preferences: Optional["ModelPreferences"], + default_model: Optional[str] = None, +) -> str: + """ + Resolve an LLM model name from MCP ModelPreferences. + Strategy: + 1. Check hints for substring matches against known model names. + 2. Fall back to priority-based selection (cost/speed/intelligence). + 3. Fall back to the configured default model. + Args: + model_preferences: MCP ModelPreferences with hints and priorities. + default_model: Fallback model if no hint matches. + Returns: + A model string suitable for litellm.acompletion(). + """ + import litellm + + # Build list of available model names from proxy Router or litellm.model_list + available_model_names: list = [] + try: + from litellm.proxy.proxy_server import llm_router + + if llm_router is not None: + available_model_names = llm_router.get_model_names() + except Exception: + pass + if not available_model_names and litellm.model_list: + for entry in litellm.model_list: + if isinstance(entry, dict): + name = entry.get("model_name") + if name: + available_model_names.append(name) + elif isinstance(entry, str): + available_model_names.append(entry) + if model_preferences and model_preferences.hints: + for hint in model_preferences.hints: + hint_name = getattr(hint, "name", None) + if not hint_name: + continue + # Try direct match first + if hint_name in available_model_names: + verbose_logger.debug( + "MCP sampling model resolution: direct hint match '%s'", + hint_name, + ) + return hint_name + # Try substring match against known models + for model_name in available_model_names: + if hint_name.lower() in model_name.lower(): + verbose_logger.debug( + "MCP sampling model resolution: substring hint match " + "'%s' -> '%s'", + hint_name, + model_name, + ) + return model_name + verbose_logger.debug( + "MCP sampling model resolution: no hint matched from %s " + "against %d available models", + [getattr(h, "name", None) for h in model_preferences.hints], + len(available_model_names), + ) + + # 2. Priority-based selection (cost/speed/intelligence) + if ( + model_preferences + and available_model_names + and _has_priorities(model_preferences) + ): + best = _select_model_by_priority(available_model_names, model_preferences) + if best is not None: + verbose_logger.debug( + "MCP sampling model resolution: priority-based selection chose '%s'", + best, + ) + return best + + # 3. Use default model from caller + if default_model: + verbose_logger.debug( + "MCP sampling model resolution: using caller-provided default '%s'", + default_model, + ) + return default_model + # Fall back to first available model + if available_model_names: + verbose_logger.debug( + "MCP sampling model resolution: no default configured, " + "falling back to first available model '%s'", + available_model_names[0], + ) + return available_model_names[0] + # Last resort - use LiteLLM default or raise error + default_sampling_model = getattr(litellm, "default_mcp_sampling_model", None) + if default_sampling_model: + verbose_logger.debug( + "MCP sampling model resolution: using litellm.default_mcp_sampling_model='%s'", + default_sampling_model, + ) + return default_sampling_model + raise ValueError( + "No model could be resolved for MCP sampling. Please configure 'default_mcp_sampling_model' in your LiteLLM configuration." + ) + + +def _has_priorities(model_preferences: "ModelPreferences") -> bool: + """Return True if any priority weight is set (non-None and > 0).""" + return any( + (getattr(model_preferences, attr, None) or 0) > 0 + for attr in ("costPriority", "speedPriority", "intelligencePriority") + ) + + +def _select_model_by_priority( + model_names: List[str], + model_preferences: "ModelPreferences", +) -> Optional[str]: + """Score available models by MCP priority weights and return the best. + + Scoring strategy (per the MCP spec, priorities are 0-1 floats): + + * **costPriority** — higher means "prefer cheaper models". + Metric: combined (input + output) cost per token from + ``model_prices_and_context_window.json``. Lower cost → higher score. + + * **speedPriority** — higher means "prefer faster models". + Metric: ``output_tokens_per_second`` from model info when available; + otherwise a neutral score for every candidate, since no reliable + latency proxy exists (context-window size does not track speed). + + * **intelligencePriority** — higher means "prefer smarter models". + Metric: ``max_output_tokens`` is used as a rough capability proxy + (frontier models expose larger context windows). + + Each metric is min-max normalised across the candidate set so that + every model gets a 0-1 score per dimension. The final score is the + weighted sum of the three normalised dimensions. + + Returns the highest-scoring model name, or None if scoring fails for + all candidates (e.g. no model_info available). + """ + import litellm as _litellm + + cost_weight = getattr(model_preferences, "costPriority", None) or 0.0 + speed_weight = getattr(model_preferences, "speedPriority", None) or 0.0 + intel_weight = getattr(model_preferences, "intelligencePriority", None) or 0.0 + + # Gather raw metrics for each model + scored: List[Dict[str, Any]] = [] + for name in model_names: + try: + info = _litellm.get_model_info(name) + except Exception: + continue + input_cost = info.get("input_cost_per_token") or 0.0 + output_cost = info.get("output_cost_per_token") or 0.0 + total_cost = input_cost + output_cost + max_output = info.get("max_output_tokens") or info.get("max_tokens") or 0 + output_tps = info.get("output_tokens_per_second") or 0.0 + scored.append( + { + "name": name, + "cost": total_cost, + "max_output": max_output, + "output_tps": output_tps, + } + ) + + if not scored: + return None + + # Min-max normalisation helpers + def _normalise(values: List[float], invert: bool = False) -> List[float]: + """Normalise to [0, 1]. If *invert*, lower raw → higher score.""" + lo, hi = min(values), max(values) + if hi == lo: + return [0.5] * len(values) # all equal → neutral score + normed = [(v - lo) / (hi - lo) for v in values] + if invert: + normed = [1.0 - n for n in normed] + return normed + + costs = [s["cost"] for s in scored] + max_outputs = [float(s["max_output"]) for s in scored] + output_tps_values = [s["output_tps"] for s in scored] + + # costPriority: lower cost → higher score (invert) + cost_scores = _normalise(costs, invert=True) + # speedPriority: use output_tokens_per_second if any model has it, + # otherwise a neutral score (no reliable latency proxy is available). + if any(v > 0 for v in output_tps_values): + speed_scores = _normalise(output_tps_values, invert=False) + else: + speed_scores = [0.5] * len(scored) + # intelligencePriority: higher max_output → smarter + intel_scores = _normalise(max_outputs, invert=False) + + best_name = None + best_score = -1.0 + for i, entry in enumerate(scored): + score = ( + cost_weight * cost_scores[i] + + speed_weight * speed_scores[i] + + intel_weight * intel_scores[i] + ) + verbose_logger.debug( + "MCP priority scoring: model=%s cost_score=%.3f speed_score=%.3f " + "intel_score=%.3f → weighted=%.3f", + entry["name"], + cost_scores[i], + speed_scores[i], + intel_scores[i], + score, + ) + if score > best_score: + best_score = score + best_name = entry["name"] + + return best_name + + +def _convert_mcp_content_to_openai( + content: Any, +) -> Union[str, Dict[str, Any], List[Dict[str, Any]]]: + """ + Convert MCP SamplingMessage content to OpenAI message content format. + Handles: + - TextContent → string or {"type": "text", "text": ...} + - ImageContent → {"type": "image_url", "image_url": {"url": "data:..."}} + - AudioContent → {"type": "input_audio", "input_audio": {...}} + - ToolUseContent → function call representation + - ToolResultContent → tool result representation + - List of mixed content → list of content parts + """ + if isinstance(content, list): + parts = [] + for item in content: + converted = _convert_single_content(item) + if isinstance(converted, list): + parts.extend(converted) + else: + parts.append(converted) + return parts + return _convert_single_content(content) + + +def _convert_single_content( + content: Any, +) -> Union[Dict[str, Any], List[Dict[str, Any]]]: + """Convert a single MCP content item to OpenAI format. + + For text/image/audio content, returns a single content-part dict. + For tool_use/tool_result, returns a dict with a ``_marker_type`` key + so the caller (``_convert_mcp_messages_to_openai``) can hoist it to + the correct message-level position (``tool_calls`` array or a + separate ``role: "tool"`` message). + """ + import json + + content_type = getattr(content, "type", None) + if content_type == "text": + return {"type": "text", "text": content.text} + elif content_type == "image": + data = getattr(content, "data", "") + mime_type = getattr(content, "mimeType", "image/png") + return { + "type": "image_url", + "image_url": {"url": f"data:{mime_type};base64,{data}"}, + } + elif content_type == "audio": + data = getattr(content, "data", "") + mime_type = getattr(content, "mimeType", "audio/wav") + # Map MIME type to OpenAI audio format + format_map = { + "audio/wav": "wav", + "audio/mp3": "mp3", + "audio/mpeg": "mp3", + "audio/flac": "flac", + "audio/ogg": "ogg", + } + audio_format = format_map.get(mime_type, "wav") + return { + "type": "input_audio", + "input_audio": {"data": data, "format": audio_format}, + } + elif content_type == "tool_use": + # ToolUseContent → proper OpenAI function-call representation. + # The ``_marker_type`` key lets the message-level converter + # hoist this into the ``tool_calls`` array on the assistant + # message instead of embedding it inline as a content part. + return { + "_marker_type": "tool_use", + "id": getattr(content, "id", f"call_{id(content)}"), + "type": "function", + "function": { + "name": getattr(content, "name", ""), + "arguments": json.dumps(getattr(content, "input", {}), default=str), + }, + } + elif content_type == "tool_result": + # ToolResultContent → proper OpenAI tool-role message. + # Marked so the message-level converter can emit it as a + # separate ``{"role": "tool", ...}`` message. + tool_use_id = getattr(content, "toolUseId", "") + nested_content = getattr(content, "content", []) + if isinstance(nested_content, list): + text_parts = [ + getattr(c, "text", str(c)) + for c in nested_content + if getattr(c, "type", None) == "text" + ] + result_text = "\n".join(text_parts) if text_parts else "" + else: + result_text = str(nested_content) + return { + "_marker_type": "tool_result", + "role": "tool", + "tool_call_id": tool_use_id, + "content": result_text, + } + # Fallback: treat as text + return {"type": "text", "text": str(content)} + + +def _convert_mcp_messages_to_openai( + messages: List["SamplingMessage"], + system_prompt: Optional[str] = None, +) -> List[Dict[str, Any]]: + """ + Convert MCP SamplingMessage list to OpenAI messages format. + MCP messages use: + - role: "user" | "assistant" + - content: TextContent | ImageContent | AudioContent | ToolUseContent + | ToolResultContent | list[...] + OpenAI messages use: + - role: "system" | "user" | "assistant" | "tool" + - content: str | list[content_part] + """ + openai_messages: List[Dict[str, Any]] = [] + # Add system prompt if provided + if system_prompt: + openai_messages.append({"role": "system", "content": system_prompt}) + for msg in messages: + role = msg.role + content = msg.content + # Handle tool use content from assistant + if role == "assistant" and _has_tool_use(content): + tool_calls = _extract_tool_calls(content) + if tool_calls: + openai_msg: Dict[str, Any] = { + "role": "assistant", + "tool_calls": tool_calls, + } + # Also include any text content alongside tool calls + text_parts = _extract_text_parts(content) + if text_parts: + openai_msg["content"] = text_parts + openai_messages.append(openai_msg) + continue + # Handle tool result content from user + if role == "user" and _has_tool_result(content): + tool_results = _extract_tool_results(content) + for tool_result in tool_results: + openai_messages.append(tool_result) + continue + # Standard text/image/audio message — also handles any stray + # tool_use / tool_result that slipped past the fast-path checks + # above (e.g. unexpected role, single non-list content). + converted = _convert_mcp_content_to_openai(content) + converted_parts = ( + converted + if isinstance(converted, list) + else ([converted] if isinstance(converted, dict) else []) + ) + + # Separate marker items from regular content parts + tool_call_markers = [] + tool_result_markers = [] + regular_parts = [] + for part in converted_parts: + marker = part.get("_marker_type") if isinstance(part, dict) else None + if marker == "tool_use": + # Strip the internal marker before emitting + tc = {k: v for k, v in part.items() if k != "_marker_type"} + tool_call_markers.append(tc) + elif marker == "tool_result": + tr = {k: v for k, v in part.items() if k != "_marker_type"} + tool_result_markers.append(tr) + else: + regular_parts.append(part) + + # Emit assistant message with tool_calls if any were found + if tool_call_markers: + openai_msg_tc: Dict[str, Any] = { + "role": "assistant", + "tool_calls": tool_call_markers, + } + if regular_parts: + openai_msg_tc["content"] = regular_parts + openai_messages.append(openai_msg_tc) + elif regular_parts: + if isinstance(converted, str): + openai_messages.append({"role": role, "content": converted}) + else: + openai_messages.append({"role": role, "content": regular_parts}) + + # Emit separate tool-result messages + for tr in tool_result_markers: + openai_messages.append(tr) + + return openai_messages + + +def _has_tool_use(content: Any) -> bool: + """Check if content contains ToolUseContent.""" + if isinstance(content, list): + return any(getattr(c, "type", None) == "tool_use" for c in content) + return getattr(content, "type", None) == "tool_use" + + +def _has_tool_result(content: Any) -> bool: + """Check if content contains ToolResultContent.""" + if isinstance(content, list): + return any(getattr(c, "type", None) == "tool_result" for c in content) + return getattr(content, "type", None) == "tool_result" + + +def _extract_tool_calls(content: Any) -> List[Dict[str, Any]]: + """Extract OpenAI-format tool_calls from MCP ToolUseContent.""" + import json + + items = content if isinstance(content, list) else [content] + tool_calls = [] + for item in items: + if getattr(item, "type", None) == "tool_use": + tool_calls.append( + { + "id": getattr(item, "id", f"call_{id(item)}"), + "type": "function", + "function": { + "name": getattr(item, "name", ""), + "arguments": json.dumps( + getattr(item, "input", {}), default=str + ), + }, + } + ) + return tool_calls + + +def _extract_text_parts(content: Any) -> Optional[str]: + """Extract text parts from mixed content.""" + items = content if isinstance(content, list) else [content] + texts = [] + for item in items: + if getattr(item, "type", None) == "text": + texts.append(getattr(item, "text", "")) + return "\n".join(texts) if texts else None + + +def _extract_tool_results(content: Any) -> List[Dict[str, Any]]: + """Extract OpenAI-format tool messages from MCP ToolResultContent.""" + items = content if isinstance(content, list) else [content] + results = [] + for item in items: + if getattr(item, "type", None) == "tool_result": + tool_use_id = getattr(item, "toolUseId", "") + # Extract text from nested content + nested_content = getattr(item, "content", []) + if isinstance(nested_content, list): + text_parts = [ + getattr(c, "text", str(c)) + for c in nested_content + if getattr(c, "type", None) == "text" + ] + result_text = "\n".join(text_parts) if text_parts else "" + else: + result_text = str(nested_content) + results.append( + { + "role": "tool", + "tool_call_id": tool_use_id, + "content": result_text, + } + ) + return results + + +def _convert_mcp_tools_to_openai( + tools: Optional[List["Tool"]], +) -> Optional[List[Dict[str, Any]]]: + """ + Convert MCP Tool definitions to OpenAI function calling format. + MCP Tool: {name, description, inputSchema} + OpenAI Tool: {type: "function", function: {name, description, parameters}} + """ + if not tools: + return None + openai_tools = [] + for tool in tools: + openai_tool = { + "type": "function", + "function": { + "name": tool.name, + "description": tool.description or "", + "parameters": tool.inputSchema + or { + "type": "object", + "properties": {}, + }, + }, + } + openai_tools.append(openai_tool) + return openai_tools + + +def _convert_mcp_tool_choice_to_openai( + tool_choice: Optional["ToolChoice"], +) -> Optional[Union[str, Dict[str, Any]]]: + """ + Convert MCP ToolChoice to OpenAI tool_choice format. + MCP: {mode: "auto"} | {mode: "required"} | {mode: "none"} + OpenAI: "auto" | "required" | "none" + """ + if not tool_choice: + return None + mode = getattr(tool_choice, "mode", "auto") + if mode == "auto": + return "auto" + elif mode == "required": + return "required" + elif mode == "none": + return "none" + return "auto" + + +def _convert_openai_response_to_mcp_result( + response: Any, + model_name: str, +) -> Union["CreateMessageResult", "CreateMessageResultWithTools", "ErrorData"]: + """ + Convert a litellm completion response to MCP CreateMessageResult. + Args: + response: The litellm ModelResponse. + model_name: The model that was used. + Returns: + MCP CreateMessageResult or CreateMessageResultWithTools. + """ + if not response.choices: + verbose_logger.warning( + "MCP sampling: LLM returned empty choices list for model=%s " + "(possible content filter or provider error)", + model_name, + ) + return ErrorData( + code=-1, + message=( + f"LLM returned no choices for model '{model_name}'. " + "This may indicate content filtering or a provider-side error." + ), + ) + choice = response.choices[0] + message = choice.message + # Determine stop reason + finish_reason = getattr(choice, "finish_reason", "stop") + if finish_reason == "tool_calls": + stop_reason = "toolUse" + elif finish_reason == "length": + stop_reason = "maxTokens" + else: + stop_reason = "endTurn" + actual_model = getattr(response, "model", model_name) or model_name + # Check if response has tool calls + tool_calls = getattr(message, "tool_calls", None) + if tool_calls: + # Build ToolUseContent items + content_parts: "List[Any]" = [] + # Include text content if present + if message.content: + content_parts.append(TextContent(type="text", text=message.content)) + # Convert tool calls to MCP ToolUseContent + for tc in tool_calls: + import json + + tool_input = tc.function.arguments + if isinstance(tool_input, str): + try: + tool_input = json.loads(tool_input) + except (json.JSONDecodeError, TypeError): + tool_input = {"raw": tool_input} + content_parts.append( + ToolUseContent( + type="tool_use", + id=tc.id, + name=tc.function.name, + input=tool_input, + ) + ) + return CreateMessageResultWithTools( + role="assistant", + content=content_parts, + model=actual_model, + stopReason=stop_reason, + ) + # Simple text response + text = message.content or "" + return CreateMessageResult( + role="assistant", + content=TextContent(type="text", text=text), + model=actual_model, + stopReason=stop_reason, + ) + + +async def _check_model_access( # noqa: PLR0915 + model: str, user_api_key_auth: Any +) -> Optional["ErrorData"]: + """Enforce model-permission checks for MCP sampling requests. + + Runs the same authorization checks as ``/chat/completions``: + key-level, team-level, per-member, user-level, and project-level + model restrictions. The model name comes from the upstream MCP + server (untrusted input). + + Returns None if authorized, or an ErrorData describing the denial. + """ + if user_api_key_auth is None: + return None + + _api_key = getattr(user_api_key_auth, "api_key", None) + _token = getattr(user_api_key_auth, "token", None) + _user_role = getattr(user_api_key_auth, "user_role", None) + + _has_real_credential = bool(_api_key) or bool(_token) + _is_admin = ( + _user_role in ("proxy_admin", "proxy_admin_viewer") if _user_role else False + ) + + if not _has_real_credential and not _is_admin: + verbose_logger.warning( + "MCP sampling: denying model access for model=%s — " + "auth context has no real LiteLLM credential (possible " + "OAuth passthrough placeholder). api_key=%s, token=%s, role=%s", + model, + bool(_api_key), + bool(_token), + _user_role, + ) + return ErrorData( + code=-1, + message=( + "Model access denied: sampling requires a valid LiteLLM " + "API key or admin credential. OAuth-only sessions cannot " + "trigger proxy model calls without explicit authorization." + ), + ) + + try: + import litellm + from litellm.proxy.auth.auth_checks import ( + can_key_call_model, + can_team_access_model, + can_user_call_model, + can_project_access_model, + _check_team_member_model_access, + get_team_object, + get_user_object, + get_project_object, + ) + + try: + from litellm.proxy.proxy_server import llm_router as _llm_router + except ImportError: + _llm_router = None + + await can_key_call_model( + model=model, + llm_model_list=getattr(litellm, "model_list", None), + valid_token=user_api_key_auth, + llm_router=_llm_router, + ) + + _team_id = getattr(user_api_key_auth, "team_id", None) + _user_id = getattr(user_api_key_auth, "user_id", None) + _project_id = getattr(user_api_key_auth, "project_id", None) + + try: + from litellm.proxy.proxy_server import ( + prisma_client as _prisma_client, + user_api_key_cache as _user_api_key_cache, + proxy_logging_obj as _proxy_logging_obj, + ) + except ImportError: + _prisma_client = None + _user_api_key_cache = None # type: ignore[assignment] + _proxy_logging_obj = None # type: ignore[assignment] + + if _team_id and _prisma_client and _user_api_key_cache: + try: + team_obj = await get_team_object( + team_id=_team_id, + prisma_client=_prisma_client, + user_api_key_cache=_user_api_key_cache, + proxy_logging_obj=_proxy_logging_obj, + ) + except Exception: + team_obj = None + + if team_obj: + await can_team_access_model( + model=model, + team_object=team_obj, + llm_router=_llm_router, + team_model_aliases=getattr( + user_api_key_auth, "team_model_aliases", None + ), + ) + if _user_id and _proxy_logging_obj: + await _check_team_member_model_access( + model=model, + team_object=team_obj, + valid_token=user_api_key_auth, + llm_router=_llm_router, + prisma_client=_prisma_client, + user_api_key_cache=_user_api_key_cache, + proxy_logging_obj=_proxy_logging_obj, + ) + elif not _team_id and _user_id and _prisma_client and _user_api_key_cache: + try: + user_obj = await get_user_object( + user_id=_user_id, + prisma_client=_prisma_client, + user_api_key_cache=_user_api_key_cache, + user_id_upsert=False, + proxy_logging_obj=_proxy_logging_obj, + ) + except Exception: + user_obj = None + + if user_obj: + await can_user_call_model( + model=model, + llm_router=_llm_router, + user_object=user_obj, + ) + + if _project_id and _prisma_client and _user_api_key_cache: + try: + project_obj = await get_project_object( + project_id=_project_id, + prisma_client=_prisma_client, + user_api_key_cache=_user_api_key_cache, + proxy_logging_obj=_proxy_logging_obj, + ) + except Exception: + project_obj = None + + if project_obj: + can_project_access_model( + model=model, + project_object=project_obj, + llm_router=_llm_router, + ) + + verbose_logger.debug( + "MCP sampling: model access check passed for model=%s", + model, + ) + return None + except Exception as access_err: + verbose_logger.warning( + "MCP sampling: model access denied for model=%s: %s", + model, + access_err, + ) + return ErrorData( + code=-1, + message=( + f"Model access denied: the API key is not authorized " + f"to use model '{model}'. {access_err}" + ), + ) + + +async def _run_budget_checks( + model: str, + user_api_key_auth: Any, + raw_headers: Optional[Dict[str, str]] = None, + client_ip: Optional[str] = None, +) -> Optional["ErrorData"]: + """Enforce key/team/user/org/global budget checks for sampling requests. + + Runs the same ``common_checks`` path that ``/chat/completions`` uses, + so sampling cannot bypass budget limits. + + Returns None if all checks pass, or an ErrorData describing the denial. + """ + try: + from litellm.proxy.auth.auth_checks import common_checks + from litellm.proxy.proxy_server import ( + general_settings, + llm_router as _llm_router, + prisma_client as _prisma_client, + proxy_logging_obj as _proxy_logging_obj, + user_api_key_cache as _user_api_key_cache, + ) + from litellm.proxy.auth.auth_checks import ( + get_team_object, + get_user_object, + ) + import litellm + except ImportError as import_err: + verbose_logger.warning( + "MCP sampling: budget check imports unavailable: %s", import_err + ) + return None # Can't enforce budgets without the modules + + _team_id = getattr(user_api_key_auth, "team_id", None) + _user_id = getattr(user_api_key_auth, "user_id", None) + + team_obj = None + if _team_id and _prisma_client and _user_api_key_cache: + try: + team_obj = await get_team_object( + team_id=_team_id, + prisma_client=_prisma_client, + user_api_key_cache=_user_api_key_cache, + proxy_logging_obj=_proxy_logging_obj, + ) + except Exception: + pass + + user_obj = None + if _user_id and _prisma_client and _user_api_key_cache: + try: + user_obj = await get_user_object( + user_id=_user_id, + prisma_client=_prisma_client, + user_api_key_cache=_user_api_key_cache, + user_id_upsert=False, + proxy_logging_obj=_proxy_logging_obj, + ) + except Exception: + pass + + dummy_request = _build_sampling_request( + raw_headers=raw_headers, + client_ip=client_ip, + ) + + # Enforce virtual-key route restrictions: a key limited to MCP routes + # must not be able to trigger a /chat/completions call via sampling. + # This mirrors the RouteChecks.should_call_route gate that runs in + # user_api_key_auth before common_checks for regular requests. + try: + from litellm.proxy.auth.route_checks import RouteChecks + + RouteChecks.should_call_route( + route="/chat/completions", + valid_token=user_api_key_auth, + request=dummy_request, + ) + except HTTPException as route_err: + verbose_logger.warning( + "MCP sampling: route check denied /chat/completions for key: %s", + route_err.detail, + ) + return ErrorData( + code=-1, + message=f"Sampling denied: virtual key is not allowed to call /chat/completions. {route_err.detail}", + ) + + global_proxy_spend = getattr(litellm, "_global_proxy_spend", None) + + # Build request body and merge x-litellm-tags from MCP headers BEFORE + # common_checks runs. _tag_max_budget_check inside common_checks only + # inspects request_body; without this pre-merge, header-supplied tags + # bypass per-tag budget enforcement (mirroring the regular auth path). + request_body: Dict[str, Any] = {"model": model} + try: + from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup + + LiteLLMProxyRequestSetup.apply_client_tag_policy_pre_auth( + request=dummy_request, + request_data=request_body, + user_api_key_dict=user_api_key_auth, + ) + except Exception: + # Non-fatal: tag merge is defense-in-depth; don't block sampling + # if the merge utility is unavailable or fails. + pass + + try: + await common_checks( + request_body=request_body, + team_object=team_obj, + user_object=user_obj, + end_user_object=None, + global_proxy_spend=global_proxy_spend, + general_settings=general_settings or {}, + route="/chat/completions", + llm_router=_llm_router, + proxy_logging_obj=typing.cast("ProxyLogging", _proxy_logging_obj), + valid_token=user_api_key_auth, + request=dummy_request, + ) + except Exception as budget_err: + verbose_logger.warning( + "MCP sampling: budget check failed for model=%s: %s", + model, + budget_err, + ) + return ErrorData( + code=-1, + message=f"Sampling denied: {budget_err}", + ) + + verbose_logger.debug("MCP sampling: budget checks passed for model=%s", model) + return None + + +def _build_sampling_request( + raw_headers: Optional[Dict[str, str]] = None, + client_ip: Optional[str] = None, +) -> Any: + """Build a synthetic FastAPI Request for sampling sub-calls. + + Converts the original MCP connection's HTTP headers into ASGI + scope format so that ``add_litellm_data_to_request`` can apply + header-dependent guardrails, tag-based routing, trace correlation, + and ``forward_llm_provider_auth_headers``. + + Key fields populated: + - **headers**: All original HTTP headers are forwarded (except + hop-by-hop: content-length, transfer-encoding). This ensures + ``traceparent``, ``authorization``, ``user-agent``, and + ``x-litellm-api-key`` are visible to pre-call utils. + - **client**: The ASGI ``(host, port)`` tuple so that + ``request.client.host`` returns the real client IP for + IP-based routing and guardrails. + - **server**: Derived from the running proxy's ``server_host`` + / ``server_port`` when available, avoiding the misleading + ``127.0.0.1:0`` placeholder. + - **x-forwarded-for**: Injected from ``client_ip`` if the + original headers don't already carry it, as a fallback for + IP attribution. + """ + from fastapi import Request + + # --- Build ASGI headers --- + _scope_headers: list = [(b"content-type", b"application/json")] + # Hop-by-hop headers that must NOT be forwarded into the + # synthetic request (they describe the original HTTP framing, + # not the logical request). + _HOP_BY_HOP = frozenset( + { + "content-length", + "transfer-encoding", + "connection", + "keep-alive", + "upgrade", + "te", + "trailer", + } + ) + if raw_headers: + for hdr_name, hdr_value in raw_headers.items(): + _key = hdr_name.lower() + # Skip content-type (already set), x-forwarded-for (use resolved + # client_ip instead to prevent spoofing), and hop-by-hop headers + if _key in {"content-type", "x-forwarded-for"} or _key in _HOP_BY_HOP: + continue + _scope_headers.append( + ( + _key.encode("latin-1", errors="replace"), + hdr_value.encode("utf-8"), + ) + ) + + # Inject x-forwarded-for from captured client_ip if the + # original headers don't already carry it + if client_ip and not any(h[0] == b"x-forwarded-for" for h in _scope_headers): + _scope_headers.append((b"x-forwarded-for", client_ip.encode("utf-8"))) + + # --- Derive server (host, port) from the running proxy --- + _server_host = "127.0.0.1" + _server_port = 4000 # LiteLLM default + try: + import litellm.proxy.proxy_server as proxy_server + + _proxy_host = getattr(proxy_server, "server_host", None) + _proxy_port = getattr(proxy_server, "server_port", None) + + if _proxy_host: + _server_host = str(_proxy_host) + if _proxy_port: + _server_port = int(_proxy_port) + except (ImportError, AttributeError, TypeError, ValueError): + pass + + # --- Build ASGI client tuple for request.client.host --- + _client_tuple = None + if client_ip: + _client_tuple = (client_ip, 0) + + scope: Dict[str, Any] = { + "type": "http", + "method": "POST", + "path": "/mcp/sampling/createMessage", + "scheme": "http", + "server": (_server_host, _server_port), + "query_string": b"", + "root_path": "", + "headers": _scope_headers, + } + if _client_tuple is not None: + scope["client"] = _client_tuple + + return Request(scope=scope) + + +async def _build_completion_kwargs( + params: "CreateMessageRequestParams", + model: str, + user_api_key_auth: Any, + raw_headers: Optional[Dict[str, str]], + client_ip: Optional[str], +) -> Dict[str, Any]: + openai_messages = _convert_mcp_messages_to_openai( + messages=params.messages, + system_prompt=params.systemPrompt, + ) + completion_kwargs: Dict[str, Any] = { + "model": model, + "messages": openai_messages, + "max_tokens": params.maxTokens, + } + if params.temperature is not None: + completion_kwargs["temperature"] = params.temperature + if params.stopSequences: + completion_kwargs["stop"] = params.stopSequences + openai_tools = _convert_mcp_tools_to_openai(params.tools) + if openai_tools: + completion_kwargs["tools"] = openai_tools + openai_tool_choice = _convert_mcp_tool_choice_to_openai(params.toolChoice) + if openai_tool_choice is not None: + completion_kwargs["tool_choice"] = openai_tool_choice + completion_kwargs["metadata"] = {} + if params.metadata: + completion_kwargs["metadata"]["mcp_metadata"] = params.metadata + + from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request + from litellm.proxy.proxy_server import proxy_config + + completion_kwargs["user"] = getattr(user_api_key_auth, "user_id", None) + _dummy_request = _build_sampling_request( + raw_headers=raw_headers, client_ip=client_ip + ) + completion_kwargs = await add_litellm_data_to_request( + data=completion_kwargs, + request=_dummy_request, + user_api_key_dict=user_api_key_auth, + proxy_config=proxy_config, + ) + return completion_kwargs + + +async def _run_guardrails_and_call_llm( + completion_kwargs: Dict[str, Any], + user_api_key_auth: Any, +) -> Any: + try: + from litellm.proxy.proxy_server import proxy_logging_obj as _plo + + if _plo is not None: + completion_kwargs = await typing.cast("ProxyLogging", _plo).pre_call_hook( + user_api_key_dict=user_api_key_auth, + data=completion_kwargs, + call_type="acompletion", + ) + except ImportError: + pass + except Exception as guardrail_err: + verbose_logger.warning( + "MCP sampling: pre-call guardrail rejected request: %s", + guardrail_err, + ) + raise + + import litellm + + try: + from litellm.proxy.proxy_server import llm_router + + if llm_router is not None: + return await llm_router.acompletion(**completion_kwargs) + return await litellm.acompletion(**completion_kwargs) + except ImportError: + return await litellm.acompletion(**completion_kwargs) + + +async def handle_sampling_create_message( + context: Any, + params: "CreateMessageRequestParams", + default_model: Optional[str] = None, + user_api_key_auth: Optional[Any] = None, + raw_headers: Optional[Dict[str, str]] = None, + client_ip: Optional[str] = None, +) -> Union["CreateMessageResult", "CreateMessageResultWithTools", "ErrorData"]: + """ + Handle an MCP sampling/createMessage request by routing through LiteLLM. + This is the main entry point called by the MCP client session when an + upstream MCP server requests LLM inference. + Args: + context: MCP RequestContext (contains session info). + params: The CreateMessageRequestParams from the MCP server. + default_model: Default model to use if no preferences match. + user_api_key_auth: Auth context for the requesting user. + raw_headers: Original HTTP headers from the MCP connection. + Forwarded into the internal acompletion call so that + header-dependent guardrails, IP-routing, trace-id + correlation, and forward_llm_provider_auth_headers + work correctly for sampling sub-calls. + client_ip: Original client IP address for IP-based guardrails. + Returns: + CreateMessageResult with the LLM's response, or ErrorData on failure. + """ + if not MCP_SAMPLING_AVAILABLE: + return ErrorData( + code=-1, + message="MCP sampling is not available (mcp package not installed)", + ) + + if user_api_key_auth is None: + return ErrorData( + code=-1, + message=( + "Sampling requires an authenticated user context. " + "Internal or unauthenticated sessions cannot trigger " + "upstream-initiated model calls." + ), + ) + + try: + model = _resolve_model_from_preferences( + model_preferences=params.modelPreferences, + default_model=default_model, + ) + verbose_logger.info( + "MCP sampling: resolved model=%s from preferences=%s", + model, + params.modelPreferences, + ) + + access_denial = await _check_model_access(model, user_api_key_auth) + if access_denial is not None: + return access_denial + + budget_denial = await _run_budget_checks( + model=model, + user_api_key_auth=user_api_key_auth, + raw_headers=raw_headers, + client_ip=client_ip, + ) + if budget_denial is not None: + return budget_denial + + completion_kwargs = await _build_completion_kwargs( + params=params, + model=model, + user_api_key_auth=user_api_key_auth, + raw_headers=raw_headers, + client_ip=client_ip, + ) + + openai_messages = completion_kwargs["messages"] + openai_tools = completion_kwargs.get("tools") + verbose_logger.debug( + "MCP sampling: calling litellm.acompletion with model=%s, num_messages=%d, has_tools=%s", + model, + len(openai_messages), + bool(openai_tools), + ) + + response = await _run_guardrails_and_call_llm( + completion_kwargs=completion_kwargs, + user_api_key_auth=user_api_key_auth, + ) + + result = _convert_openai_response_to_mcp_result( + response=response, model_name=model + ) + verbose_logger.info( + "MCP sampling: completed successfully, model=%s, stopReason=%s", + getattr(result, "model", "unknown"), + getattr(result, "stopReason", "unknown"), + ) + return result + except Exception as e: + from litellm.exceptions import ( + AuthenticationError, + BudgetExceededError, + ContextWindowExceededError, + PermissionDeniedError, + RateLimitError, + ServiceUnavailableError, + ) + + from litellm.proxy._types import ProxyException + + if isinstance( + e, + ( + HTTPException, + BudgetExceededError, + RateLimitError, + AuthenticationError, + PermissionDeniedError, + ContextWindowExceededError, + ServiceUnavailableError, + ProxyException, + ), + ): + raise + + verbose_logger.exception("MCP sampling handler failed: %s", e) + return ErrorData( + code=-1, + message=f"Sampling failed: {str(e)}", + ) diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py index 6e33a105ec8..746fc4e7d3f 100644 --- a/litellm/proxy/_experimental/mcp_server/server.py +++ b/litellm/proxy/_experimental/mcp_server/server.py @@ -6,6 +6,7 @@ LiteLLM MCP Server Routes import asyncio import contextlib +import contextvars import hashlib import json import time @@ -46,12 +47,14 @@ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import ( from litellm.proxy._experimental.mcp_server.mcp_context import ( _mcp_active_toolset_id, _mcp_gateway_initialize_instructions, + _mcp_gateway_server_name, ) from litellm.proxy._experimental.mcp_server.mcp_debug import MCPDebug from litellm.proxy._experimental.mcp_server.utils import ( LITELLM_MCP_SERVER_DESCRIPTION, LITELLM_MCP_SERVER_NAME, LITELLM_MCP_SERVER_VERSION, + MCPMissingUserEnvVarsError, add_server_prefix_to_name, get_server_prefix, iter_known_server_prefixes, @@ -125,6 +128,18 @@ try: GetPromptResult, ResourceTemplate, TextResourceContents, + Tool, + ) + from mcp.server.session import ServerSession as _McpServerSession + import weakref + + # Robust auth lookup keyed by session_object. + _session_obj_auth_storage: ( + "weakref.WeakKeyDictionary[Any, MCPAuthenticatedUser]" + ) = weakref.WeakKeyDictionary() + + active_mcp_session_var: contextvars.ContextVar[Optional[_McpServerSession]] = ( + contextvars.ContextVar("active_mcp_session", default=None) ) except ImportError as e: verbose_logger.debug(f"MCP module not found: {e}") @@ -160,6 +175,60 @@ def _mcp_session_id_from_headers( return None +def _jsonrpc_text_has_top_level_method(text: str) -> bool: + """Whether a (possibly truncated) JSON-RPC envelope has a ``method`` key at + the root object's top level. + + Used to tell a request/notification (carries ``method``) apart from a + response (carries ``result``/``error`` and no top-level ``method``). A + response payload can itself nest a ``method`` field, so only keys at the + root object's depth are inspected rather than searching the whole string. + Returns ``True`` only when a top-level ``method`` key is positively found; + truncation that hides it yields ``False``. + """ + depth = 0 + in_string = False + escaped = False + in_object: List[bool] = [] + reading_key = False + expect_key = False + key_chars: List[str] = [] + for ch in text: + if in_string: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + if reading_key and depth == 1 and "".join(key_chars) == "method": + return True + elif reading_key: + key_chars.append(ch) + continue + if ch == '"': + in_string = True + reading_key = expect_key and depth >= 1 and in_object[-1] + key_chars = [] + expect_key = False + elif ch == "{" or ch == "[": + depth += 1 + in_object.append(ch == "{") + expect_key = ch == "{" + elif ch == "}" or ch == "]": + if in_object: + in_object.pop() + depth -= 1 + if depth <= 0: + break + expect_key = False + elif ch == ",": + expect_key = bool(in_object) and in_object[-1] + elif ch == ":": + expect_key = False + return False + + if MCP_AVAILABLE: from mcp.server import Server from mcp.server.lowlevel.server import NotificationOptions @@ -201,6 +270,9 @@ if MCP_AVAILABLE: global_mcp_tool_registry, ) from litellm.proxy._experimental.mcp_server.utils import ( + MCP_TOOL_PREFIX_SEPARATOR, + is_tool_name_prefixed, + normalize_server_name, split_server_prefix_from_name, ) @@ -255,10 +327,14 @@ if MCP_AVAILABLE: notification_options=notification_options, experimental_capabilities=experimental_capabilities or {}, ) + updates: Dict[str, Any] = {} merged = _mcp_gateway_initialize_instructions.get() if merged is not None: - return opts.model_copy(update={"instructions": merged}) - return opts + updates["instructions"] = merged + scoped_server_name = _mcp_gateway_server_name.get() + if scoped_server_name is not None: + updates["server_name"] = scoped_server_name + return opts.model_copy(update=updates) if updates else opts ######################################################## ############ Initialize the MCP Server ################# @@ -483,10 +559,18 @@ if MCP_AVAILABLE: ######################################################## @server.list_tools() - async def list_tools() -> List[MCPTool]: + async def handle_list_tools() -> List[Tool]: """ - List all available tools + List all available tools. + Also captures the active session for propagation to callbacks. """ + from mcp.server.lowlevel.server import request_ctx + + req_ctx = request_ctx.get(None) + _session_reset_token = None + if req_ctx: + _session_reset_token = active_mcp_session_var.set(req_ctx.session) + try: # Get user authentication from context variable ( @@ -497,7 +581,7 @@ if MCP_AVAILABLE: oauth2_headers, raw_headers, _client_ip, - ) = get_auth_context() + ) = await get_or_extract_auth_context() verbose_logger.debug( f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}" ) @@ -528,152 +612,188 @@ if MCP_AVAILABLE: # Return empty list instead of failing completely # This prevents the HTTP stream from failing and allows the client to get a response return [] + finally: + if _session_reset_token is not None: + active_mcp_session_var.reset(_session_reset_token) @server.call_tool() - async def mcp_server_tool_call( - name: str, arguments: Optional[Dict[str, Any]] + async def mcp_server_tool_call( # noqa: PLR0915 + name: str, arguments: Dict[str, Any] | None ) -> CallToolResult: """ Call a specific tool with the provided arguments - Args: name (str): Name of the tool to call arguments (Dict[str, Any] | None): Arguments to pass to the tool - Returns: List[Union[MCPTextContent, MCPImageContent, MCPEmbeddedResource]]: Tool execution results - Raises: HTTPException: If tool not found or arguments missing """ from fastapi import Request - from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request from litellm.proxy.proxy_server import proxy_config + from mcp.types import CallToolResult + from mcp.server.lowlevel.server import request_ctx - # Validate arguments - ( - user_api_key_auth, - mcp_auth_header, - mcp_servers, - mcp_server_auth_headers, - oauth2_headers, - raw_headers, - _client_ip, - ) = get_auth_context() + req_ctx = request_ctx.get(None) + _session_reset_token = None + if req_ctx: + _session_reset_token = active_mcp_session_var.set(req_ctx.session) - verbose_logger.debug( - f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}" - ) - host_progress_callback = None try: - host_ctx = server.request_context - if host_ctx and hasattr(host_ctx, "meta") and host_ctx.meta: - host_token = getattr(host_ctx.meta, "progressToken", None) - if host_token and hasattr(host_ctx, "session") and host_ctx.session: - host_session = host_ctx.session - - async def forward_progress(progress: float, total: Optional[float]): - """Forward progress notifications from external MCP to Host""" - try: - await host_session.send_progress_notification( - progress_token=host_token, - progress=progress, - total=total, - ) - verbose_logger.debug( - f"Forwarded progress {progress}/{total} to Host" - ) - except Exception as e: - verbose_logger.error( - f"Failed to forward progress to Host: {e}" - ) - - host_progress_callback = forward_progress - verbose_logger.debug( - f"Host progressToken captured: {host_token[:8]}..." - ) - except Exception as e: - verbose_logger.warning(f"Could not capture host progress context: {e}") - try: - # Create a body date for logging - body_data = {"name": name, "arguments": arguments} - # Set trace/session id from raw_headers so spend logs and logging_obj stay consistent (same as A2A) - chain_id = get_chain_id_from_headers(raw_headers) - if chain_id: - body_data["litellm_trace_id"] = chain_id - body_data["litellm_session_id"] = chain_id - - request = Request( - scope={ - "type": "http", - "method": "POST", - "path": "/mcp/tools/call", - "headers": [(b"content-type", b"application/json")], - } + # Validate arguments + ( + user_api_key_auth, + mcp_auth_header, + mcp_servers, + mcp_server_auth_headers, + oauth2_headers, + raw_headers, + _client_ip, + ) = await get_or_extract_auth_context() + verbose_logger.debug( + f"MCP mcp_server_tool_call - user_api_key_auth={user_api_key_auth}, user_role={getattr(user_api_key_auth, 'user_role', 'N/A')}" ) - if user_api_key_auth is not None: - data = await add_litellm_data_to_request( - data=body_data, - request=request, - user_api_key_dict=user_api_key_auth, - proxy_config=proxy_config, + + verbose_logger.debug( + f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}" + ) + host_progress_callback = None + try: + host_ctx = server.request_context + if host_ctx and hasattr(host_ctx, "meta") and host_ctx.meta: + host_token = getattr(host_ctx.meta, "progressToken", None) + if host_token and hasattr(host_ctx, "session") and host_ctx.session: + host_session = host_ctx.session + + async def forward_progress( + progress: float, total: Optional[float] + ): + """Forward progress notifications from external MCP to Host""" + try: + await host_session.send_progress_notification( + progress_token=host_token, + progress=progress, + total=total, + ) + verbose_logger.debug( + f"Forwarded progress {progress}/{total} to Host" + ) + except Exception as e: + verbose_logger.error( + f"Failed to forward progress to Host: {e}" + ) + + host_progress_callback = forward_progress + verbose_logger.debug( + f"Host progressToken captured: {host_token[:8]}..." + ) + except Exception as e: + verbose_logger.warning(f"Could not capture host progress context: {e}") + try: + # Create a body date for logging + body_data = {"name": name, "arguments": arguments} + # Set trace/session id from raw_headers so spend logs and logging_obj stay consistent (same as A2A) + chain_id = get_chain_id_from_headers(raw_headers) + if chain_id: + body_data["litellm_trace_id"] = chain_id + body_data["litellm_session_id"] = chain_id + + request = Request( + scope={ + "type": "http", + "method": "POST", + "path": "/mcp/tools/call", + "headers": [(b"content-type", b"application/json")], + } ) - else: - data = body_data - - response = await call_mcp_tool( - user_api_key_auth=user_api_key_auth, - mcp_auth_header=mcp_auth_header, - mcp_servers=mcp_servers, - mcp_server_auth_headers=mcp_server_auth_headers, - oauth2_headers=oauth2_headers, - raw_headers=raw_headers, - host_progress_callback=host_progress_callback, - **data, # for logging - ) - except BlockedPiiEntityError as e: - verbose_logger.error(f"BlockedPiiEntityError in MCP tool call: {str(e)}") - return CallToolResult( - content=[ - TextContent( - text=f"Error: Blocked PII entity detected - {str(e)}", - type="text", + if user_api_key_auth is not None: + data = await add_litellm_data_to_request( + data=body_data, + request=request, + user_api_key_dict=user_api_key_auth, + proxy_config=proxy_config, ) - ], - isError=True, - ) - except GuardrailRaisedException as e: - verbose_logger.error(f"GuardrailRaisedException in MCP tool call: {str(e)}") - return CallToolResult( - content=[ - TextContent( - text=f"Error: Guardrail violation - {str(e)}", type="text" - ) - ], - isError=True, - ) - except HTTPException as e: - verbose_logger.error(f"HTTPException in MCP tool call: {str(e)}") - return CallToolResult( - content=[TextContent(text=f"Error: {str(e.detail)}", type="text")], - isError=True, - ) - except Exception as e: - verbose_logger.exception(f"MCP mcp_server_tool_call - error: {e}") - return CallToolResult( - content=[TextContent(text=f"Error: {str(e)}", type="text")], - isError=True, - ) + else: + data = body_data - return response + response = await call_mcp_tool( + user_api_key_auth=user_api_key_auth, + mcp_auth_header=mcp_auth_header, + mcp_servers=mcp_servers, + mcp_server_auth_headers=mcp_server_auth_headers, + oauth2_headers=oauth2_headers, + raw_headers=raw_headers, + host_progress_callback=host_progress_callback, + **data, # for logging + ) + except MCPMissingUserEnvVarsError as e: + verbose_logger.info( + "MCP mcp_server_tool_call missing per-user env vars: server_id=%s missing=%s", + e.server_id, + e.missing, + ) + return CallToolResult( + content=[TextContent(text=str(e), type="text")], + isError=True, + ) + except BlockedPiiEntityError as e: + verbose_logger.error( + f"BlockedPiiEntityError in MCP tool call: {str(e)}" + ) + return CallToolResult( + content=[ + TextContent( + text=f"Error: Blocked PII entity detected - {str(e)}", + type="text", + ) + ], + isError=True, + ) + except GuardrailRaisedException as e: + verbose_logger.error( + f"GuardrailRaisedException in MCP tool call: {str(e)}" + ) + return CallToolResult( + content=[ + TextContent( + text=f"Error: Guardrail violation - {str(e)}", type="text" + ) + ], + isError=True, + ) + except HTTPException as e: + verbose_logger.error(f"HTTPException in MCP tool call: {str(e)}") + return CallToolResult( + content=[TextContent(text=f"Error: {str(e.detail)}", type="text")], + isError=True, + ) + except Exception as e: + verbose_logger.exception(f"MCP mcp_server_tool_call - error: {e}") + return CallToolResult( + content=[TextContent(text=f"Error: {str(e)}", type="text")], + isError=True, + ) + + return response + finally: + if _session_reset_token is not None: + active_mcp_session_var.reset(_session_reset_token) @server.list_prompts() async def list_prompts() -> List[Prompt]: """ List all available prompts """ + from mcp.server.lowlevel.server import request_ctx + + req_ctx = request_ctx.get(None) + _session_reset_token = None + if req_ctx: + _session_reset_token = active_mcp_session_var.set(req_ctx.session) + try: # Get user authentication from context variable ( @@ -684,7 +804,7 @@ if MCP_AVAILABLE: oauth2_headers, raw_headers, _client_ip, - ) = get_auth_context() + ) = await get_or_extract_auth_context() verbose_logger.debug( f"MCP list_prompts - User API Key Auth from context: {user_api_key_auth}" ) @@ -713,6 +833,9 @@ if MCP_AVAILABLE: # Return empty list instead of failing completely # This prevents the HTTP stream from failing and allows the client to get a response return [] + finally: + if _session_reset_token is not None: + active_mcp_session_var.reset(_session_reset_token) @server.get_prompt() async def get_prompt( @@ -730,33 +853,13 @@ if MCP_AVAILABLE: """ # Validate arguments - ( - user_api_key_auth, - mcp_auth_header, - mcp_servers, - mcp_server_auth_headers, - oauth2_headers, - raw_headers, - _client_ip, - ) = get_auth_context() + from mcp.server.lowlevel.server import request_ctx - verbose_logger.debug( - f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}" - ) - return await mcp_get_prompt( - name=name, - arguments=arguments, - user_api_key_auth=user_api_key_auth, - mcp_auth_header=mcp_auth_header, - mcp_servers=mcp_servers, - mcp_server_auth_headers=mcp_server_auth_headers, - oauth2_headers=oauth2_headers, - raw_headers=raw_headers, - ) + req_ctx = request_ctx.get(None) + _session_reset_token = None + if req_ctx: + _session_reset_token = active_mcp_session_var.set(req_ctx.session) - @server.list_resources() - async def list_resources() -> List[Resource]: - """List all available resources.""" try: ( user_api_key_auth, @@ -766,7 +869,45 @@ if MCP_AVAILABLE: oauth2_headers, raw_headers, _client_ip, - ) = get_auth_context() + ) = await get_or_extract_auth_context() + + verbose_logger.debug( + f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}" + ) + return await mcp_get_prompt( + name=name, + arguments=arguments, + user_api_key_auth=user_api_key_auth, + mcp_auth_header=mcp_auth_header, + mcp_servers=mcp_servers, + mcp_server_auth_headers=mcp_server_auth_headers, + oauth2_headers=oauth2_headers, + raw_headers=raw_headers, + ) + finally: + if _session_reset_token is not None: + active_mcp_session_var.reset(_session_reset_token) + + @server.list_resources() + async def list_resources() -> List[Resource]: + """List all available resources.""" + from mcp.server.lowlevel.server import request_ctx + + req_ctx = request_ctx.get(None) + _session_reset_token = None + if req_ctx: + _session_reset_token = active_mcp_session_var.set(req_ctx.session) + + try: + ( + user_api_key_auth, + mcp_auth_header, + mcp_servers, + mcp_server_auth_headers, + oauth2_headers, + raw_headers, + _client_ip, + ) = await get_or_extract_auth_context() verbose_logger.debug( f"MCP list_resources - User API Key Auth from context: {user_api_key_auth}" ) @@ -792,10 +933,20 @@ if MCP_AVAILABLE: except Exception as e: verbose_logger.exception(f"Error in list_resources endpoint: {str(e)}") return [] + finally: + if _session_reset_token is not None: + active_mcp_session_var.reset(_session_reset_token) @server.list_resource_templates() async def list_resource_templates() -> List[ResourceTemplate]: """List all available resource templates.""" + from mcp.server.lowlevel.server import request_ctx + + req_ctx = request_ctx.get(None) + _session_reset_token = None + if req_ctx: + _session_reset_token = active_mcp_session_var.set(req_ctx.session) + try: ( user_api_key_auth, @@ -805,7 +956,7 @@ if MCP_AVAILABLE: oauth2_headers, raw_headers, _client_ip, - ) = get_auth_context() + ) = await get_or_extract_auth_context() verbose_logger.debug( f"MCP list_resource_templates - User API Key Auth from context: {user_api_key_auth}" ) @@ -825,8 +976,7 @@ if MCP_AVAILABLE: raw_headers=raw_headers, ) verbose_logger.info( - "MCP list_resource_templates - Successfully returned " - f"{len(resource_templates)} resource templates" + f"MCP list_resource_templates - Successfully returned {len(resource_templates)} resource templates" ) return resource_templates except Exception as e: @@ -834,30 +984,44 @@ if MCP_AVAILABLE: f"Error in list_resource_templates endpoint: {str(e)}" ) return [] + finally: + if _session_reset_token is not None: + active_mcp_session_var.reset(_session_reset_token) @server.read_resource() async def read_resource(url: AnyUrl) -> list[ReadResourceContents]: - ( - user_api_key_auth, - mcp_auth_header, - mcp_servers, - mcp_server_auth_headers, - oauth2_headers, - raw_headers, - _client_ip, - ) = get_auth_context() + from mcp.server.lowlevel.server import request_ctx - read_resource_result = await mcp_read_resource( - url=url, - user_api_key_auth=user_api_key_auth, - mcp_auth_header=mcp_auth_header, - mcp_servers=mcp_servers, - mcp_server_auth_headers=mcp_server_auth_headers, - oauth2_headers=oauth2_headers, - raw_headers=raw_headers, - ) + req_ctx = request_ctx.get(None) + _session_reset_token = None + if req_ctx: + _session_reset_token = active_mcp_session_var.set(req_ctx.session) - return _normalize_resource_contents(read_resource_result.contents) + try: + ( + user_api_key_auth, + mcp_auth_header, + mcp_servers, + mcp_server_auth_headers, + oauth2_headers, + raw_headers, + _client_ip, + ) = await get_or_extract_auth_context() + + read_resource_result = await mcp_read_resource( + url=url, + user_api_key_auth=user_api_key_auth, + mcp_auth_header=mcp_auth_header, + mcp_servers=mcp_servers, + mcp_server_auth_headers=mcp_server_auth_headers, + oauth2_headers=oauth2_headers, + raw_headers=raw_headers, + ) + + return _normalize_resource_contents(read_resource_result.contents) + finally: + if _session_reset_token is not None: + active_mcp_session_var.reset(_session_reset_token) ######################################################## ############ End of MCP Server Routes ################## @@ -1166,8 +1330,7 @@ if MCP_AVAILABLE: try: from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 get_user_oauth_credential, - is_oauth_credential_expired, - refresh_user_oauth_token, + resolve_valid_user_oauth_token, ) from litellm.proxy._experimental.mcp_server.oauth2_token_cache import ( # noqa: PLC0415 _compute_per_user_token_ttl, @@ -1180,14 +1343,14 @@ if MCP_AVAILABLE: cached_token = await mcp_per_user_token_cache.get(user_id, server_id) if cached_token is not None: verbose_logger.debug( - "_get_user_oauth_extra_headers_from_db: Redis hit for " - "user=%s server=%s", + "_get_user_oauth_extra_headers_from_db: Redis hit for user=%s server=%s", user_id, server_id, ) return {"Authorization": f"Bearer {cached_token}"} # ── Slow path: DB lookup ────────────────────────────────────────── + prisma_client = None if prefetched_creds is not None: cred = prefetched_creds.get(server_id) else: @@ -1205,45 +1368,17 @@ if MCP_AVAILABLE: if not cred or not cred.get("access_token"): return None - if is_oauth_credential_expired(cred): - verbose_logger.debug( - "_get_user_oauth_extra_headers_from_db: token expired for " - "user=%s server=%s — attempting refresh", - user_id, - server_id, - ) - # Attempt token refresh; requires a DB client (not available from prefetch) - if cred.get("refresh_token"): - try: - from litellm.proxy.utils import ( # noqa: PLC0415 - get_prisma_client_or_throw, - ) - - prisma_client = get_prisma_client_or_throw( - "Database not connected. Cannot refresh OAuth token." - ) - cred = await refresh_user_oauth_token( - prisma_client=prisma_client, - user_id=user_id, - server=server, - cred=cred, - ) - except Exception as refresh_exc: - verbose_logger.warning( - "_get_user_oauth_extra_headers_from_db: refresh failed " - "for user=%s server=%s: %s", - user_id, - server_id, - refresh_exc, - ) - cred = None - - if not cred or not cred.get("access_token"): - # Clear stale Redis/cache entry so we don't serve it again. - # Do this for both the individual and prefetch paths so the - # next request doesn't get a stale cache hit. - await mcp_per_user_token_cache.delete(user_id, server_id) - return None + cred = await resolve_valid_user_oauth_token( + user_id=user_id, + server=server, + cred=cred, + prisma_client=prisma_client, + ) + if cred is None: + # Refresh failed or token expired with no usable refresh_token — + # clear the stale Redis entry so the next request doesn't reuse it. + await mcp_per_user_token_cache.delete(user_id, server_id) + return None access_token: str = cred["access_token"] @@ -1275,8 +1410,7 @@ if MCP_AVAILABLE: return {"Authorization": f"Bearer {access_token}"} except Exception as e: verbose_logger.warning( - "_get_user_oauth_extra_headers_from_db: failed to retrieve credential for " - "user=%s server=%s: %s", + "_get_user_oauth_extra_headers_from_db: failed to retrieve credential for user=%s server=%s: %s", user_id, server_id, e, @@ -1418,6 +1552,7 @@ if MCP_AVAILABLE: user_api_key_auth: Optional[UserAPIKeyAuth], mcp_servers: Optional[List[str]], client_ip: Optional[str], + scoped_server_endpoint: bool = False, ) -> AsyncIterator[None]: allowed = await _get_allowed_mcp_servers( user_api_key_auth=user_api_key_auth, @@ -1439,11 +1574,22 @@ if MCP_AVAILABLE: return_exceptions=True, ) merged = _merge_gateway_initialize_instructions(allowed_mcp_servers=allowed) - tok = _mcp_gateway_initialize_instructions.set(merged) + scoped_server_name = None + if scoped_server_endpoint and len(allowed) == 1: + scoped_server = allowed[0] + scoped_server_name = ( + scoped_server.alias + or scoped_server.server_name + or scoped_server.name + or scoped_server.server_id + ) + instructions_token = _mcp_gateway_initialize_instructions.set(merged) + server_name_token = _mcp_gateway_server_name.set(scoped_server_name) try: yield finally: - _mcp_gateway_initialize_instructions.reset(tok) + _mcp_gateway_initialize_instructions.reset(instructions_token) + _mcp_gateway_server_name.reset(server_name_token) async def _get_tools_from_mcp_servers( # noqa: PLR0915 user_api_key_auth: Optional[UserAPIKeyAuth], @@ -2340,47 +2486,60 @@ if MCP_AVAILABLE: None, ) - # Resolve the actual MCP server up-front so the permission check uses - # the canonical server.name even when the tool name is prefixed with a - # short ID (LITELLM_USE_SHORT_MCP_TOOL_PREFIX) that doesn't match the - # server's display name directly. - mcp_server = global_mcp_server_manager._get_mcp_server_from_tool_name(name) - if mcp_server is None and requested_server is not None: - # REST callers may pass the raw tool name (no prefix) plus a - # ``requested_server_id``. The mapping might only contain the - # prefixed form, so retry the lookup with every known prefix of - # the requested server before treating the tool as unresolved — - # otherwise the tool_server_mismatch guard below is silently - # bypassed. - for known_prefix in iter_known_server_prefixes(requested_server): - candidate = global_mcp_server_manager._get_mcp_server_from_tool_name( - add_server_prefix_to_name(name, known_prefix) - ) - if candidate is not None: - mcp_server = candidate - break - if mcp_server is not None: - server_name = mcp_server.name + name_is_prefixed = False + if requested_server is not None and MCP_TOOL_PREFIX_SEPARATOR in name: + all_registry_prefixes: Set[str] = set() + for registry_server in global_mcp_server_manager.get_registry().values(): + for known_prefix in iter_known_server_prefixes(registry_server): + all_registry_prefixes.add(normalize_server_name(known_prefix)) + name_is_prefixed = is_tool_name_prefixed( + name, known_server_prefixes=all_registry_prefixes + ) - # REST /mcp-rest/tools/call passes server_id — tool must belong to that server - if requested_server is not None: - if ( - mcp_server is not None - and mcp_server.server_id != requested_server.server_id - ): - raise HTTPException( - status_code=403, - detail={ - "error": "tool_server_mismatch", - "message": ( - f"Tool '{name}' belongs to MCP server '{mcp_server.name}' " - f"but request specified server_id for '{requested_server.name}'." - ), - }, - ) - if mcp_server is None: - mcp_server = requested_server - server_name = requested_server.name + if requested_server is not None and not name_is_prefixed: + # REST callers may pass server_id with the upstream tool name (no + # LiteLLM prefix). The first segment is not a registered server + # prefix, so the whole string is the upstream tool name and may + # legitimately contain the separator (e.g. "text-to-speech"). + # server_id is authoritative for routing and auth. + mcp_server = requested_server + server_name = requested_server.name + original_tool_name = name + else: + # Resolve from tool name (MCP JSON-RPC or prefixed REST tool names). + mcp_server = global_mcp_server_manager._get_mcp_server_from_tool_name(name) + if mcp_server is None and requested_server is not None: + for known_prefix in iter_known_server_prefixes(requested_server): + candidate = ( + global_mcp_server_manager._get_mcp_server_from_tool_name( + add_server_prefix_to_name(name, known_prefix) + ) + ) + if candidate is not None: + mcp_server = candidate + break + if mcp_server is not None: + server_name = mcp_server.name + + if requested_server is not None: + if ( + mcp_server is not None + and mcp_server.server_id != requested_server.server_id + ): + raise HTTPException( + status_code=403, + detail={ + "error": "tool_server_mismatch", + "message": ( + f"Tool '{name}' belongs to MCP server " + f"'{mcp_server.name}' but request specified " + f"server_id for '{requested_server.name}'." + ), + }, + ) + if mcp_server is None: + mcp_server = requested_server + server_name = requested_server.name # Only enforce server-level permissions when we can resolve a server if server_name: @@ -2409,6 +2568,7 @@ if MCP_AVAILABLE: standard_logging_mcp_tool_call ) litellm_logging_obj.model = f"MCP: {name}" + litellm_logging_obj.model_call_details["model"] = f"MCP: {name}" # Resolve the MCP server early so BYOK checks and credential injection # apply to ALL dispatch paths (local tool registry AND managed MCP server). if mcp_server is None: @@ -2485,7 +2645,7 @@ if MCP_AVAILABLE: arguments=arguments or {}, server_name=server_name or mcp_server.name, user_api_key_auth=user_api_key_auth, - proxy_logging_obj=proxy_logging_obj, + proxy_logging_obj=proxy_logging_obj, # type: ignore[arg-type] server=mcp_server, raw_headers=raw_headers, ) @@ -2744,8 +2904,7 @@ if MCP_AVAILABLE: raise HTTPException( status_code=400, detail=( - "Multiple MCP servers configured; read_resource currently " - "supports exactly one allowed server." + "Multiple MCP servers configured; read_resource currently supports exactly one allowed server." ), ) @@ -3124,8 +3283,7 @@ if MCP_AVAILABLE: return False except Exception: verbose_logger.debug( - "Unable to inspect active MCP sessions for '%s'. " - "Deferring to session manager.", + "Unable to inspect active MCP sessions for '%s'. Deferring to session manager.", _session_id, ) return False @@ -3136,8 +3294,7 @@ if MCP_AVAILABLE: if method == "DELETE": _remove_stateful_session_tracking(_session_id) verbose_logger.info( - "DELETE request for non-existent MCP session '%s'. " - "Returning success (idempotent DELETE).", + "DELETE request for non-existent MCP session '%s'. Returning success (idempotent DELETE).", _session_id, ) success_response = JSONResponse( @@ -3286,6 +3443,8 @@ if MCP_AVAILABLE: ) if stored_oauth_headers: continue + if getattr(server, "delegate_auth_to_upstream", False) is True: + continue request = StarletteRequest(scope) base_url = get_request_base_url(request) @@ -3497,6 +3656,7 @@ if MCP_AVAILABLE: oauth2_headers, raw_headers, ) = await extract_mcp_auth_context(scope, path) + scoped_server_endpoint = len(_get_mcp_servers_in_path(path) or []) == 1 # Extract client IP for MCP access control _client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope)) @@ -3615,6 +3775,7 @@ if MCP_AVAILABLE: return session_id = _get_session_id_from_scope(scope) + body = b"" if scope.get("method") == "POST": consumed_messages, body = await _read_request_body_for_routing(receive) is_initialize = _is_initialize_request(body) @@ -3639,8 +3800,7 @@ if MCP_AVAILABLE: ) if not await _enforce_stateful_session_cap_for_owner(request_owner): verbose_logger.warning( - "Rejecting MCP initialize: caller already holds the maximum " - "number of active stateful sessions." + "Rejecting MCP initialize: caller already holds the maximum number of active stateful sessions." ) too_many_response = JSONResponse( status_code=429, @@ -3672,9 +3832,56 @@ if MCP_AVAILABLE: # POST/DELETE are the methods that actually mutate the shared # auth context, so serializing those is sufficient for the # clobbering race between concurrent JSON-RPC calls. - session_lock: Optional[asyncio.Lock] = None + # + # Also skip the lock for JSON-RPC *responses* (POSTs that carry + # a ``result`` or ``error`` but no ``method``). These are replies + # to server-initiated requests such as ``elicitation/create`` or + # ``sampling/createMessage``. The in-flight tool-call POST that + # triggered the server request already holds the session lock, so + # trying to acquire it again for the response POST would deadlock. + is_jsonrpc_response = False request_method = (scope.get("method") or "").upper() - if use_stateful and session_id and request_method in ("POST", "DELETE"): + if body and request_method == "POST": + try: + _peeked = json.loads(body) + if ( + isinstance(_peeked, dict) + and _peeked.get("jsonrpc") == "2.0" + and "id" in _peeked + and "method" not in _peeked + and ("result" in _peeked or "error" in _peeked) + ): + is_jsonrpc_response = True + verbose_logger.debug( + "MCP: detected JSON-RPC response POST (id=%s), skipping session lock to avoid deadlock", + _peeked.get("id"), + ) + except (json.JSONDecodeError, TypeError): + # Peek cap truncated the body, so it can't be fully parsed. + # Scan the top-level keys (depth-aware) instead of a flat + # substring search: a response's result payload may nest a + # "method" field, and misreading that would acquire the lock + # and deadlock the in-flight tool call awaiting this + # response. A false skip is harmless; a false acquire is not. + _body_str = body.decode("utf-8", errors="replace") + if ( + '"jsonrpc"' in _body_str + and ('"result"' in _body_str or '"error"' in _body_str) + and not _jsonrpc_text_has_top_level_method(_body_str) + ): + is_jsonrpc_response = True + verbose_logger.debug( + "MCP: detected truncated JSON-RPC response POST via " + "top-level key scan, skipping session lock to avoid deadlock" + ) + + session_lock: Optional[asyncio.Lock] = None + if ( + use_stateful + and session_id + and request_method in ("POST", "DELETE") + and not is_jsonrpc_response + ): session_lock = _stateful_session_locks.setdefault( session_id, asyncio.Lock() ) @@ -3726,6 +3933,7 @@ if MCP_AVAILABLE: user_api_key_auth, mcp_servers, _client_ip, + scoped_server_endpoint=scoped_server_endpoint, ): await target_manager.handle_request(scope, receive, local_send) if use_stateful and session_id and scope.get("method") == "DELETE": @@ -3771,7 +3979,7 @@ if MCP_AVAILABLE: ): _stateful_session_locks.pop(active_request_session_id, None) except MCPUpstreamAuthError as e: - # Pass-through server returned 401 — surface it to the client so + # Upstream delegated auth returned 401; surface it to the client so # standards-compliant MCP clients trigger the upstream OAuth flow. raise e.to_http_exception( base_url=get_request_base_url(StarletteRequest(scope)), @@ -3810,6 +4018,7 @@ if MCP_AVAILABLE: oauth2_headers, raw_headers, ) = await extract_mcp_auth_context(scope, path) + scoped_server_endpoint = len(_get_mcp_servers_in_path(path) or []) == 1 # Extract client IP for MCP access control _sse_client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope)) @@ -3882,10 +4091,11 @@ if MCP_AVAILABLE: user_api_key_auth, mcp_servers, _sse_client_ip, + scoped_server_endpoint=scoped_server_endpoint, ): await sse_session_manager.handle_request(scope, receive, send) except MCPUpstreamAuthError as e: - # Pass-through server returned 401 — surface it to the client so + # Upstream delegated auth returned 401; surface it to the client so # standards-compliant MCP clients trigger the upstream OAuth flow. raise e.to_http_exception( base_url=get_request_base_url(StarletteRequest(scope)), @@ -4099,6 +4309,119 @@ if MCP_AVAILABLE: ) return None, None, None, None, None, None, None + def _get_current_session(): + try: + from mcp.server.lowlevel.server import request_ctx + + return request_ctx.get().session + except (LookupError, ImportError): + return None + + def _cache_auth_context_lazily(): + session = _get_current_session() + if session is None: + return + try: + if session in _session_obj_auth_storage: + return + except TypeError: + verbose_logger.debug( + "_cache_auth_context_lazily: session object is unhashable (type=%s), cannot cache auth context", + type(session).__name__, + ) + return + + auth = auth_context_var.get() + if auth and isinstance(auth, MCPAuthenticatedUser): + try: + _session_obj_auth_storage[session] = auth + except TypeError: + verbose_logger.debug( + "_cache_auth_context_lazily: could not store auth via " + "session identity — session object is unhashable" + ) + + def _recover_auth_from_session() -> Optional[MCPAuthenticatedUser]: + session = _get_current_session() + if session is None: + return None + + stored: Optional[MCPAuthenticatedUser] = None + try: + stored = _session_obj_auth_storage.get(session) + except TypeError: + verbose_logger.debug( + "_recover_auth_from_session: session object is unhashable " + "(type=%s), skipping _session_obj_auth_storage lookup", + type(session).__name__, + ) + + return stored + + async def get_or_extract_auth_context() -> Tuple[ + Optional[UserAPIKeyAuth], + Optional[str], + Optional[List[str]], + Optional[Dict[str, Dict[str, str]]], + Optional[Dict[str, str]], + Optional[Dict[str, str]], + Optional[str], + ]: + """ + Get auth context from ContextVar first, then fall back to session + storage (which survives cross-task boundaries in the MCP SDK). + """ + ( + user_api_key_auth, + mcp_auth_header, + mcp_servers, + mcp_server_auth_headers, + oauth2_headers, + raw_headers, + _client_ip, + ) = get_auth_context() + + if user_api_key_auth is not None: + _cache_auth_context_lazily() + else: + stored = _recover_auth_from_session() + + if stored: + user_api_key_auth = stored.user_api_key_auth + mcp_auth_header = stored.mcp_auth_header + mcp_servers = stored.mcp_servers + mcp_server_auth_headers = stored.mcp_server_auth_headers + oauth2_headers = stored.oauth2_headers + raw_headers = stored.raw_headers + _client_ip = stored.client_ip + return ( + user_api_key_auth, + mcp_auth_header, + mcp_servers, + mcp_server_auth_headers, + oauth2_headers, + raw_headers, + _client_ip, + ) + + def get_active_mcp_session() -> Optional[_McpServerSession]: + """Return the active MCP session captured during handler execution.""" + session = active_mcp_session_var.get() + if session is not None: + return session + return _get_current_session() + + def get_active_auth_context() -> Optional[MCPAuthenticatedUser]: + """Return auth context from ContextVar or session storage.""" + auth = auth_context_var.get() + if auth and isinstance(auth, MCPAuthenticatedUser): + return auth + + stored = _recover_auth_from_session() + if stored is not None: + return stored + return None + ######################################################## ############ End of Auth Context Functions ############# ######################################################## diff --git a/litellm/proxy/_experimental/mcp_server/toolset_db.py b/litellm/proxy/_experimental/mcp_server/toolset_db.py index 08ac7dbd33b..a996131653f 100644 --- a/litellm/proxy/_experimental/mcp_server/toolset_db.py +++ b/litellm/proxy/_experimental/mcp_server/toolset_db.py @@ -4,6 +4,7 @@ from typing import List, Optional from litellm._logging import verbose_proxy_logger from litellm._uuid import uuid from litellm.proxy.utils import PrismaClient +from litellm.repositories.table_repositories import MCPToolsetRepository from litellm.types.mcp_server.mcp_toolset import ( MCPToolset, NewMCPToolsetRequest, @@ -30,7 +31,7 @@ async def create_mcp_toolset( data_dict["tools"] = json.dumps(data_dict.get("tools", [])) data_dict["created_by"] = touched_by data_dict["updated_by"] = touched_by - row = await prisma_client.db.litellm_mcptoolsettable.create(data=data_dict) + row = await MCPToolsetRepository(prisma_client).table.create(data=data_dict) return _toolset_from_row(row) @@ -38,7 +39,7 @@ async def get_mcp_toolset( prisma_client: PrismaClient, toolset_id: str, ) -> Optional[MCPToolset]: - row = await prisma_client.db.litellm_mcptoolsettable.find_unique( + row = await MCPToolsetRepository(prisma_client).table.find_unique( where={"toolset_id": toolset_id} ) if row is None: @@ -54,7 +55,7 @@ async def list_mcp_toolsets( where = {} if toolset_ids is not None: where = {"toolset_id": {"in": toolset_ids}} - rows = await prisma_client.db.litellm_mcptoolsettable.find_many(where=where) + rows = await MCPToolsetRepository(prisma_client).table.find_many(where=where) return [_toolset_from_row(r) for r in rows] except Exception as e: verbose_proxy_logger.warning( @@ -69,7 +70,7 @@ async def get_mcp_toolset_by_name( prisma_client: PrismaClient, toolset_name: str, ) -> Optional[MCPToolset]: - row = await prisma_client.db.litellm_mcptoolsettable.find_first( + row = await MCPToolsetRepository(prisma_client).table.find_first( where={"toolset_name": toolset_name} ) if row is None: @@ -87,7 +88,7 @@ async def update_mcp_toolset( data_dict["tools"] = json.dumps(data_dict["tools"]) data_dict["updated_by"] = touched_by try: - row = await prisma_client.db.litellm_mcptoolsettable.update( + row = await MCPToolsetRepository(prisma_client).table.update( where={"toolset_id": data.toolset_id}, data=data_dict, ) @@ -105,7 +106,7 @@ async def delete_mcp_toolset( toolset_id: str, ) -> Optional[MCPToolset]: try: - row = await prisma_client.db.litellm_mcptoolsettable.delete( + row = await MCPToolsetRepository(prisma_client).table.delete( where={"toolset_id": toolset_id} ) except Exception as e: diff --git a/litellm/proxy/_experimental/mcp_server/utils.py b/litellm/proxy/_experimental/mcp_server/utils.py index b66dfa85b9c..97cfa74ea45 100644 --- a/litellm/proxy/_experimental/mcp_server/utils.py +++ b/litellm/proxy/_experimental/mcp_server/utils.py @@ -4,11 +4,23 @@ MCP Server Utilities import json import re -from typing import Any, Dict, Iterator, Mapping, Optional, Tuple, Union +from typing import ( + Any, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Set, + Tuple, + Union, +) import hashlib import importlib import os +from urllib.parse import quote # Constants LITELLM_MCP_SERVER_NAME = "litellm-mcp-server" @@ -370,6 +382,130 @@ def validate_mcp_server_name( raise Exception(error_message) +class MCPMissingUserEnvVarsError(Exception): + """Raised when an MCP request can't be built because the calling user has + not supplied one or more required per-user environment variables. + + The error message is user-facing and includes a URL the user can visit + to fill them in. + """ + + def __init__( + self, + *, + server_id: str, + server_name: Optional[str], + missing: List[str], + setup_url: str, + ) -> None: + self.server_id = server_id + self.server_name = server_name + self.missing = missing + self.setup_url = setup_url + label = server_name or server_id + bullet_list = "\n".join(f"- {name}" for name in missing) + message = ( + f'Cannot connect to MCP server "{label}".\n\n' + f"Your administrator configured this server to require per-user " + f"variables, but you haven't set the following yet:\n" + f"{bullet_list}\n\n" + f"Set your credentials here:\n" + f"{setup_url}" + ) + super().__init__(message) + + +# Pattern for ``${NAME}`` substitution. Matches the standard env-var +# identifier rules — letters, digits, underscores, can't start with a digit. +_ENV_VAR_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}") + + +def parse_admin_env_vars( + env_vars: Optional[Iterable[Any]], +) -> Tuple[Dict[str, str], List[Dict[str, Any]]]: + """Split admin-configured env var entries into globals and per-user specs. + + Accepts the raw value of ``MCPServer.env_vars`` (list of dicts or Pydantic + models). Returns: + + - ``global_values``: ``{name: value}`` for entries with ``scope=="global"``. + - ``user_specs``: list of ``{name, description}`` for entries with + ``scope=="user"`` — these are the names the user must fill in. + + Unknown / malformed entries are skipped silently. + """ + global_values: Dict[str, str] = {} + user_specs: List[Dict[str, Any]] = [] + if not env_vars: + return global_values, user_specs + for raw in env_vars: + if raw is None: + continue + if hasattr(raw, "model_dump"): + entry = raw.model_dump() + elif isinstance(raw, dict): + entry = raw + else: + continue + name = entry.get("name") + if not isinstance(name, str) or not name: + continue + scope = entry.get("scope") or "global" + if scope == "user": + user_specs.append({"name": name, "description": entry.get("description")}) + else: + value = entry.get("value") + global_values[name] = "" if value is None else str(value) + return global_values, user_specs + + +def find_env_var_references(value: str) -> Set[str]: + """Return the set of ``${NAME}`` identifiers referenced inside ``value``.""" + if not value: + return set() + return set(_ENV_VAR_PATTERN.findall(value)) + + +def collect_env_var_references(*, strings: Iterable[str]) -> Set[str]: + """Union of every ``${NAME}`` reference across a collection of strings.""" + refs: Set[str] = set() + for s in strings: + if isinstance(s, str): + refs |= find_env_var_references(s) + return refs + + +def interpolate_env_vars(value: str, variables: Mapping[str, str]) -> str: + """Replace ``${NAME}`` references in ``value`` with the matching mapping + entry. Unknown names are left untouched so callers can detect them via + ``find_env_var_references`` on the result if needed. + """ + if not value: + return value + + def _sub(match: "re.Match[str]") -> str: + name = match.group(1) + if name in variables: + return variables[name] + return match.group(0) + + return _ENV_VAR_PATTERN.sub(_sub, value) + + +def interpolate_headers( + headers: Mapping[str, str], variables: Mapping[str, str] +) -> Dict[str, str]: + """Return a copy of ``headers`` with every value passed through ``interpolate_env_vars``.""" + return {k: interpolate_env_vars(v, variables) for k, v in headers.items()} + + +def build_env_var_setup_url(server_id: str) -> str: + """The frontend URL where a user can fill in their per-user env vars.""" + base = os.environ.get("PROXY_BASE_URL", "").rstrip("/") + path = f"/ui/?page=mcp-servers&fill_env_vars={quote(server_id, safe='')}" + return f"{base}{path}" if base else path + + def merge_mcp_headers( *, extra_headers: Optional[Mapping[str, str]] = None, diff --git a/litellm/proxy/_experimental/out/404.html b/litellm/proxy/_experimental/out/404.html index f27612ff54e..45de348c4d5 100644 --- a/litellm/proxy/_experimental/out/404.html +++ b/litellm/proxy/_experimental/out/404.html @@ -1 +1 @@ -404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file +404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file diff --git a/litellm/proxy/_experimental/out/404/index.html b/litellm/proxy/_experimental/out/404/index.html index f27612ff54e..45de348c4d5 100644 --- a/litellm/proxy/_experimental/out/404/index.html +++ b/litellm/proxy/_experimental/out/404/index.html @@ -1 +1 @@ -404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file +404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file diff --git a/litellm/proxy/_experimental/out/__next.__PAGE__.txt b/litellm/proxy/_experimental/out/__next.__PAGE__.txt index c024136e8dc..095c8f4339f 100644 --- a/litellm/proxy/_experimental/out/__next.__PAGE__.txt +++ b/litellm/proxy/_experimental/out/__next.__PAGE__.txt @@ -1,10 +1,10 @@ 1:"$Sreact.fragment" 2:I[347257,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientPageRoot"] -3:I[952683,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js","/litellm-asset-prefix/_next/static/chunks/52c4ecc57f72065e.js","/litellm-asset-prefix/_next/static/chunks/4bb663ff806dc32f.js","/litellm-asset-prefix/_next/static/chunks/ee8f89c672745c59.js","/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","/litellm-asset-prefix/_next/static/chunks/9710770c6333a72f.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/d734cb3d5659b0da.js","/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","/litellm-asset-prefix/_next/static/chunks/09c1f51da7e82268.js","/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","/litellm-asset-prefix/_next/static/chunks/d028f8c28935d281.js","/litellm-asset-prefix/_next/static/chunks/61aa637257592262.js","/litellm-asset-prefix/_next/static/chunks/bf962cd5264be987.js","/litellm-asset-prefix/_next/static/chunks/37f229ef9335f8c3.js","/litellm-asset-prefix/_next/static/chunks/36d1c027ba991a4f.js","/litellm-asset-prefix/_next/static/chunks/786e88f4abdd5c58.js","/litellm-asset-prefix/_next/static/chunks/43c3db1352241a8b.js","/litellm-asset-prefix/_next/static/chunks/31275eb5c6f6332f.js","/litellm-asset-prefix/_next/static/chunks/0ac09b227f50edb4.js","/litellm-asset-prefix/_next/static/chunks/4c848b12d4ecda3d.js","/litellm-asset-prefix/_next/static/chunks/91c828abd7c0aff5.js","/litellm-asset-prefix/_next/static/chunks/08c348f8e09a5cb0.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/b323e0ef008e6348.js","/litellm-asset-prefix/_next/static/chunks/4ac3235460262f36.js","/litellm-asset-prefix/_next/static/chunks/51494a4a4b6fc437.js","/litellm-asset-prefix/_next/static/chunks/878832edb30e99a4.js","/litellm-asset-prefix/_next/static/chunks/9f1486622270556b.js"],"default"] +3:I[952683,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js","/litellm-asset-prefix/_next/static/chunks/bee4095c26818f05.js","/litellm-asset-prefix/_next/static/chunks/81937424fe90f746.js","/litellm-asset-prefix/_next/static/chunks/e2257d8308d35cf4.js","/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","/litellm-asset-prefix/_next/static/chunks/eb1ba04e211a533f.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/4cb93eefa53f21a3.js","/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","/litellm-asset-prefix/_next/static/chunks/40a2744137b1aec2.js","/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","/litellm-asset-prefix/_next/static/chunks/84a27349dda457cd.js","/litellm-asset-prefix/_next/static/chunks/8ddf82e7e0b331fc.js","/litellm-asset-prefix/_next/static/chunks/1d7b3500478e93ae.js","/litellm-asset-prefix/_next/static/chunks/f0e079183e7bb90c.js","/litellm-asset-prefix/_next/static/chunks/10757c2146f43db4.js","/litellm-asset-prefix/_next/static/chunks/786e88f4abdd5c58.js","/litellm-asset-prefix/_next/static/chunks/ffa46de7b8384155.js","/litellm-asset-prefix/_next/static/chunks/31275eb5c6f6332f.js","/litellm-asset-prefix/_next/static/chunks/80f4410629229bf9.js","/litellm-asset-prefix/_next/static/chunks/75ee9aba04c74e23.js","/litellm-asset-prefix/_next/static/chunks/193886179a5779b5.js","/litellm-asset-prefix/_next/static/chunks/2063ca6435a47940.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/b323e0ef008e6348.js","/litellm-asset-prefix/_next/static/chunks/4ac3235460262f36.js","/litellm-asset-prefix/_next/static/chunks/51494a4a4b6fc437.js","/litellm-asset-prefix/_next/static/chunks/d7c18aec4a87a237.js","/litellm-asset-prefix/_next/static/chunks/dac86522fa98e760.js"],"default"] 6:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] 7:"$Sreact.suspense" :HL["/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","style"] -0:{"buildId":"TrcGiQpTupSbDYFFfkFHY","rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/52c4ecc57f72065e.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/4bb663ff806dc32f.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/ee8f89c672745c59.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/9710770c6333a72f.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/d734cb3d5659b0da.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/09c1f51da7e82268.js","async":true}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","async":true}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/d028f8c28935d281.js","async":true}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/61aa637257592262.js","async":true}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/bf962cd5264be987.js","async":true}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/37f229ef9335f8c3.js","async":true}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/36d1c027ba991a4f.js","async":true}],["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/786e88f4abdd5c58.js","async":true}],["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/43c3db1352241a8b.js","async":true}],["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/31275eb5c6f6332f.js","async":true}],["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/0ac09b227f50edb4.js","async":true}],["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/4c848b12d4ecda3d.js","async":true}],["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/91c828abd7c0aff5.js","async":true}],["$","script","script-22",{"src":"/litellm-asset-prefix/_next/static/chunks/08c348f8e09a5cb0.js","async":true}],["$","script","script-23",{"src":"/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","async":true}],["$","script","script-24",{"src":"/litellm-asset-prefix/_next/static/chunks/b323e0ef008e6348.js","async":true}],["$","script","script-25",{"src":"/litellm-asset-prefix/_next/static/chunks/4ac3235460262f36.js","async":true}],["$","script","script-26",{"src":"/litellm-asset-prefix/_next/static/chunks/51494a4a4b6fc437.js","async":true}],["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/878832edb30e99a4.js","async":true}],["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/9f1486622270556b.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"loading":null,"isPartial":false} +0:{"buildId":"LpqGBJeKQM0vUG-9uVaiY","rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/bee4095c26818f05.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/81937424fe90f746.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/e2257d8308d35cf4.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/eb1ba04e211a533f.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/4cb93eefa53f21a3.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/40a2744137b1aec2.js","async":true}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","async":true}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/84a27349dda457cd.js","async":true}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/8ddf82e7e0b331fc.js","async":true}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/1d7b3500478e93ae.js","async":true}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/f0e079183e7bb90c.js","async":true}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/10757c2146f43db4.js","async":true}],["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/786e88f4abdd5c58.js","async":true}],["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/ffa46de7b8384155.js","async":true}],["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/31275eb5c6f6332f.js","async":true}],["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/80f4410629229bf9.js","async":true}],["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/75ee9aba04c74e23.js","async":true}],["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/193886179a5779b5.js","async":true}],["$","script","script-22",{"src":"/litellm-asset-prefix/_next/static/chunks/2063ca6435a47940.js","async":true}],["$","script","script-23",{"src":"/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","async":true}],["$","script","script-24",{"src":"/litellm-asset-prefix/_next/static/chunks/b323e0ef008e6348.js","async":true}],["$","script","script-25",{"src":"/litellm-asset-prefix/_next/static/chunks/4ac3235460262f36.js","async":true}],["$","script","script-26",{"src":"/litellm-asset-prefix/_next/static/chunks/51494a4a4b6fc437.js","async":true}],["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/d7c18aec4a87a237.js","async":true}],["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/dac86522fa98e760.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"loading":null,"isPartial":false} 4:{} 5:"$0:rsc:props:children:0:props:serverProvidedParams:params" 8:null diff --git a/litellm/proxy/_experimental/out/__next._full.txt b/litellm/proxy/_experimental/out/__next._full.txt index 0c119086b9e..2b2b3850207 100644 --- a/litellm/proxy/_experimental/out/__next._full.txt +++ b/litellm/proxy/_experimental/out/__next._full.txt @@ -1,34 +1,34 @@ 1:"$Sreact.fragment" -2:I[867271,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js"],"default"] -3:I[71195,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js"],"default"] -4:I[557951,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js"],"AuthProvider"] +2:I[867271,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js"],"default"] +3:I[71195,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js"],"default"] +4:I[557951,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js"],"AuthProvider"] 5:I[339756,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] 6:I[837457,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] 7:I[347257,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientPageRoot"] -8:I[952683,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js","/litellm-asset-prefix/_next/static/chunks/52c4ecc57f72065e.js","/litellm-asset-prefix/_next/static/chunks/4bb663ff806dc32f.js","/litellm-asset-prefix/_next/static/chunks/ee8f89c672745c59.js","/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","/litellm-asset-prefix/_next/static/chunks/9710770c6333a72f.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/d734cb3d5659b0da.js","/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","/litellm-asset-prefix/_next/static/chunks/09c1f51da7e82268.js","/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","/litellm-asset-prefix/_next/static/chunks/d028f8c28935d281.js","/litellm-asset-prefix/_next/static/chunks/61aa637257592262.js","/litellm-asset-prefix/_next/static/chunks/bf962cd5264be987.js","/litellm-asset-prefix/_next/static/chunks/37f229ef9335f8c3.js","/litellm-asset-prefix/_next/static/chunks/36d1c027ba991a4f.js","/litellm-asset-prefix/_next/static/chunks/786e88f4abdd5c58.js","/litellm-asset-prefix/_next/static/chunks/43c3db1352241a8b.js","/litellm-asset-prefix/_next/static/chunks/31275eb5c6f6332f.js","/litellm-asset-prefix/_next/static/chunks/0ac09b227f50edb4.js","/litellm-asset-prefix/_next/static/chunks/4c848b12d4ecda3d.js","/litellm-asset-prefix/_next/static/chunks/91c828abd7c0aff5.js","/litellm-asset-prefix/_next/static/chunks/08c348f8e09a5cb0.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/b323e0ef008e6348.js","/litellm-asset-prefix/_next/static/chunks/4ac3235460262f36.js","/litellm-asset-prefix/_next/static/chunks/51494a4a4b6fc437.js","/litellm-asset-prefix/_next/static/chunks/878832edb30e99a4.js","/litellm-asset-prefix/_next/static/chunks/9f1486622270556b.js"],"default"] +8:I[952683,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js","/litellm-asset-prefix/_next/static/chunks/bee4095c26818f05.js","/litellm-asset-prefix/_next/static/chunks/81937424fe90f746.js","/litellm-asset-prefix/_next/static/chunks/e2257d8308d35cf4.js","/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","/litellm-asset-prefix/_next/static/chunks/eb1ba04e211a533f.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/4cb93eefa53f21a3.js","/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","/litellm-asset-prefix/_next/static/chunks/40a2744137b1aec2.js","/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","/litellm-asset-prefix/_next/static/chunks/84a27349dda457cd.js","/litellm-asset-prefix/_next/static/chunks/8ddf82e7e0b331fc.js","/litellm-asset-prefix/_next/static/chunks/1d7b3500478e93ae.js","/litellm-asset-prefix/_next/static/chunks/f0e079183e7bb90c.js","/litellm-asset-prefix/_next/static/chunks/10757c2146f43db4.js","/litellm-asset-prefix/_next/static/chunks/786e88f4abdd5c58.js","/litellm-asset-prefix/_next/static/chunks/ffa46de7b8384155.js","/litellm-asset-prefix/_next/static/chunks/31275eb5c6f6332f.js","/litellm-asset-prefix/_next/static/chunks/80f4410629229bf9.js","/litellm-asset-prefix/_next/static/chunks/75ee9aba04c74e23.js","/litellm-asset-prefix/_next/static/chunks/193886179a5779b5.js","/litellm-asset-prefix/_next/static/chunks/2063ca6435a47940.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/b323e0ef008e6348.js","/litellm-asset-prefix/_next/static/chunks/4ac3235460262f36.js","/litellm-asset-prefix/_next/static/chunks/51494a4a4b6fc437.js","/litellm-asset-prefix/_next/static/chunks/d7c18aec4a87a237.js","/litellm-asset-prefix/_next/static/chunks/dac86522fa98e760.js"],"default"] 1a:I[168027,[],"default"] :HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/1bcca3c38c9deb02.css","style"] +:HL["/litellm-asset-prefix/_next/static/chunks/47150bfa067220d3.css","style"] :HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.3a6ba036.woff2","font",{"crossOrigin":"","type":"font/woff2"}] :HL["/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","style"] -0:{"P":null,"b":"TrcGiQpTupSbDYFFfkFHY","c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/1bcca3c38c9deb02.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]}]}]}]}]]}],{"children":[["$","$1","c",{"children":[["$","$L7",null,{"Component":"$8","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@9","$@a"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/52c4ecc57f72065e.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/4bb663ff806dc32f.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/ee8f89c672745c59.js","async":true,"nonce":"$undefined"}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","async":true,"nonce":"$undefined"}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","async":true,"nonce":"$undefined"}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/9710770c6333a72f.js","async":true,"nonce":"$undefined"}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true,"nonce":"$undefined"}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/d734cb3d5659b0da.js","async":true,"nonce":"$undefined"}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","async":true,"nonce":"$undefined"}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/09c1f51da7e82268.js","async":true,"nonce":"$undefined"}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","async":true,"nonce":"$undefined"}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/d028f8c28935d281.js","async":true,"nonce":"$undefined"}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/61aa637257592262.js","async":true,"nonce":"$undefined"}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/bf962cd5264be987.js","async":true,"nonce":"$undefined"}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/37f229ef9335f8c3.js","async":true,"nonce":"$undefined"}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/36d1c027ba991a4f.js","async":true,"nonce":"$undefined"}],"$Lb","$Lc","$Ld","$Le","$Lf","$L10","$L11","$L12","$L13","$L14","$L15","$L16","$L17"],"$L18"]}],{},null,false,false]},null,false,false],"$L19",false]],"m":"$undefined","G":["$1a",[]],"S":true} +0:{"P":null,"b":"LpqGBJeKQM0vUG-9uVaiY","c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/47150bfa067220d3.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]}]}]}]}]]}],{"children":[["$","$1","c",{"children":[["$","$L7",null,{"Component":"$8","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@9","$@a"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/bee4095c26818f05.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/81937424fe90f746.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/e2257d8308d35cf4.js","async":true,"nonce":"$undefined"}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/2954392b7a60a6a1.js","async":true,"nonce":"$undefined"}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/04711b0f8ffa7bbd.js","async":true,"nonce":"$undefined"}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/eb1ba04e211a533f.js","async":true,"nonce":"$undefined"}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true,"nonce":"$undefined"}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/4cb93eefa53f21a3.js","async":true,"nonce":"$undefined"}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","async":true,"nonce":"$undefined"}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/40a2744137b1aec2.js","async":true,"nonce":"$undefined"}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/542a1a209eb732c6.js","async":true,"nonce":"$undefined"}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/84a27349dda457cd.js","async":true,"nonce":"$undefined"}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/8ddf82e7e0b331fc.js","async":true,"nonce":"$undefined"}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/1d7b3500478e93ae.js","async":true,"nonce":"$undefined"}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/f0e079183e7bb90c.js","async":true,"nonce":"$undefined"}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/10757c2146f43db4.js","async":true,"nonce":"$undefined"}],"$Lb","$Lc","$Ld","$Le","$Lf","$L10","$L11","$L12","$L13","$L14","$L15","$L16","$L17"],"$L18"]}],{},null,false,false]},null,false,false],"$L19",false]],"m":"$undefined","G":["$1a",[]],"S":true} 1b:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] 1c:"$Sreact.suspense" 1e:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ViewportBoundary"] 20:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"MetadataBoundary"] b:["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/786e88f4abdd5c58.js","async":true,"nonce":"$undefined"}] -c:["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/43c3db1352241a8b.js","async":true,"nonce":"$undefined"}] +c:["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/ffa46de7b8384155.js","async":true,"nonce":"$undefined"}] d:["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/31275eb5c6f6332f.js","async":true,"nonce":"$undefined"}] -e:["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/0ac09b227f50edb4.js","async":true,"nonce":"$undefined"}] -f:["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/4c848b12d4ecda3d.js","async":true,"nonce":"$undefined"}] -10:["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/91c828abd7c0aff5.js","async":true,"nonce":"$undefined"}] -11:["$","script","script-22",{"src":"/litellm-asset-prefix/_next/static/chunks/08c348f8e09a5cb0.js","async":true,"nonce":"$undefined"}] +e:["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/80f4410629229bf9.js","async":true,"nonce":"$undefined"}] +f:["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/75ee9aba04c74e23.js","async":true,"nonce":"$undefined"}] +10:["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/193886179a5779b5.js","async":true,"nonce":"$undefined"}] +11:["$","script","script-22",{"src":"/litellm-asset-prefix/_next/static/chunks/2063ca6435a47940.js","async":true,"nonce":"$undefined"}] 12:["$","script","script-23",{"src":"/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","async":true,"nonce":"$undefined"}] 13:["$","script","script-24",{"src":"/litellm-asset-prefix/_next/static/chunks/b323e0ef008e6348.js","async":true,"nonce":"$undefined"}] 14:["$","script","script-25",{"src":"/litellm-asset-prefix/_next/static/chunks/4ac3235460262f36.js","async":true,"nonce":"$undefined"}] 15:["$","script","script-26",{"src":"/litellm-asset-prefix/_next/static/chunks/51494a4a4b6fc437.js","async":true,"nonce":"$undefined"}] -16:["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/878832edb30e99a4.js","async":true,"nonce":"$undefined"}] -17:["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/9f1486622270556b.js","async":true,"nonce":"$undefined"}] +16:["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/d7c18aec4a87a237.js","async":true,"nonce":"$undefined"}] +17:["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/dac86522fa98e760.js","async":true,"nonce":"$undefined"}] 18:["$","$L1b",null,{"children":["$","$1c",null,{"name":"Next.MetadataOutlet","children":"$@1d"}]}] 19:["$","$1","h",{"children":[null,["$","$L1e",null,{"children":"$L1f"}],["$","div",null,{"hidden":true,"children":["$","$L20",null,{"children":["$","$1c",null,{"name":"Next.Metadata","children":"$L21"}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}] 9:{} @@ -36,4 +36,4 @@ a:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" 1f:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]] 22:I[27201,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"IconMark"] 1d:null -21:[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"./favicon.ico"}],["$","$L22","4",{}]] +21:[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"/get_favicon"}],["$","$L22","4",{}]] diff --git a/litellm/proxy/_experimental/out/__next._head.txt b/litellm/proxy/_experimental/out/__next._head.txt index ea6e5095458..870c89c7e11 100644 --- a/litellm/proxy/_experimental/out/__next._head.txt +++ b/litellm/proxy/_experimental/out/__next._head.txt @@ -3,4 +3,4 @@ 3:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"MetadataBoundary"] 4:"$Sreact.suspense" 5:I[27201,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"IconMark"] -0:{"buildId":"TrcGiQpTupSbDYFFfkFHY","rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"./favicon.ico"}],["$","$L5","4",{}]]}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}],"loading":null,"isPartial":false} +0:{"buildId":"LpqGBJeKQM0vUG-9uVaiY","rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"/get_favicon"}],["$","$L5","4",{}]]}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}],"loading":null,"isPartial":false} diff --git a/litellm/proxy/_experimental/out/__next._index.txt b/litellm/proxy/_experimental/out/__next._index.txt index ebf6d8fec08..67c452e8c21 100644 --- a/litellm/proxy/_experimental/out/__next._index.txt +++ b/litellm/proxy/_experimental/out/__next._index.txt @@ -1,9 +1,9 @@ 1:"$Sreact.fragment" -2:I[867271,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js"],"default"] -3:I[71195,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js"],"default"] -4:I[557951,["/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js"],"AuthProvider"] +2:I[867271,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js"],"default"] +3:I[71195,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js"],"default"] +4:I[557951,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js"],"AuthProvider"] 5:I[339756,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] 6:I[837457,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] :HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/1bcca3c38c9deb02.css","style"] -0:{"buildId":"TrcGiQpTupSbDYFFfkFHY","rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/1bcca3c38c9deb02.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/aefca6f40ea185cd.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/632b4c8e836bd956.js","async":true}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","template":["$","$L6",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]}]}]}]}]]}],"loading":null,"isPartial":false} +:HL["/litellm-asset-prefix/_next/static/chunks/47150bfa067220d3.css","style"] +0:{"buildId":"LpqGBJeKQM0vUG-9uVaiY","rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/47150bfa067220d3.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/25c705f79a0254af.js","async":true}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","template":["$","$L6",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]}]}]}]}]]}],"loading":null,"isPartial":false} diff --git a/litellm/proxy/_experimental/out/__next._tree.txt b/litellm/proxy/_experimental/out/__next._tree.txt index 4a08f4f9e11..86dc121c5f9 100644 --- a/litellm/proxy/_experimental/out/__next._tree.txt +++ b/litellm/proxy/_experimental/out/__next._tree.txt @@ -1,5 +1,5 @@ :HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/1bcca3c38c9deb02.css","style"] +:HL["/litellm-asset-prefix/_next/static/chunks/47150bfa067220d3.css","style"] :HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.3a6ba036.woff2","font",{"crossOrigin":"","type":"font/woff2"}] :HL["/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","style"] -0:{"buildId":"TrcGiQpTupSbDYFFfkFHY","tree":{"name":"","paramType":null,"paramKey":"","hasRuntimePrefetch":false,"slots":{"children":{"name":"__PAGE__","paramType":null,"paramKey":"__PAGE__","hasRuntimePrefetch":false,"slots":null,"isRootLayout":false}},"isRootLayout":true},"staleTime":300} +0:{"buildId":"LpqGBJeKQM0vUG-9uVaiY","tree":{"name":"","paramType":null,"paramKey":"","hasRuntimePrefetch":false,"slots":{"children":{"name":"__PAGE__","paramType":null,"paramKey":"__PAGE__","hasRuntimePrefetch":false,"slots":null,"isRootLayout":false}},"isRootLayout":true},"staleTime":300} diff --git a/litellm/proxy/_experimental/out/_next/static/TrcGiQpTupSbDYFFfkFHY/_buildManifest.js b/litellm/proxy/_experimental/out/_next/static/LpqGBJeKQM0vUG-9uVaiY/_buildManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/TrcGiQpTupSbDYFFfkFHY/_buildManifest.js rename to litellm/proxy/_experimental/out/_next/static/LpqGBJeKQM0vUG-9uVaiY/_buildManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/TrcGiQpTupSbDYFFfkFHY/_clientMiddlewareManifest.json b/litellm/proxy/_experimental/out/_next/static/LpqGBJeKQM0vUG-9uVaiY/_clientMiddlewareManifest.json similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/TrcGiQpTupSbDYFFfkFHY/_clientMiddlewareManifest.json rename to litellm/proxy/_experimental/out/_next/static/LpqGBJeKQM0vUG-9uVaiY/_clientMiddlewareManifest.json diff --git a/litellm/proxy/_experimental/out/_next/static/TrcGiQpTupSbDYFFfkFHY/_ssgManifest.js b/litellm/proxy/_experimental/out/_next/static/LpqGBJeKQM0vUG-9uVaiY/_ssgManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/TrcGiQpTupSbDYFFfkFHY/_ssgManifest.js rename to litellm/proxy/_experimental/out/_next/static/LpqGBJeKQM0vUG-9uVaiY/_ssgManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/adfb3758f3e2c464.js b/litellm/proxy/_experimental/out/_next/static/chunks/10376d0955336027.js similarity index 98% rename from litellm/proxy/_experimental/out/_next/static/chunks/adfb3758f3e2c464.js rename to litellm/proxy/_experimental/out/_next/static/chunks/10376d0955336027.js index 825fe327e97..55ce00c27b0 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/adfb3758f3e2c464.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/10376d0955336027.js @@ -1,4 +1,4 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,295320,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M704 446H320c-4.4 0-8 3.6-8 8v402c0 4.4 3.6 8 8 8h384c4.4 0 8-3.6 8-8V454c0-4.4-3.6-8-8-8zm-328 64h272v117H376V510zm272 290H376V683h272v117z"}},{tag:"path",attrs:{d:"M424 748a32 32 0 1064 0 32 32 0 10-64 0zm0-178a32 32 0 1064 0 32 32 0 10-64 0z"}},{tag:"path",attrs:{d:"M811.4 368.9C765.6 248 648.9 162 512.2 162S258.8 247.9 213 368.8C126.9 391.5 63.5 470.2 64 563.6 64.6 668 145.6 752.9 247.6 762c4.7.4 8.7-3.3 8.7-8v-60.4c0-4-3-7.4-7-7.9-27-3.4-52.5-15.2-72.1-34.5-24-23.5-37.2-55.1-37.2-88.6 0-28 9.1-54.4 26.2-76.4 16.7-21.4 40.2-36.9 66.1-43.7l37.9-10 13.9-36.7c8.6-22.8 20.6-44.2 35.7-63.5 14.9-19.2 32.6-36 52.4-50 41.1-28.9 89.5-44.2 140-44.2s98.9 15.3 140 44.3c19.9 14 37.5 30.8 52.4 50 15.1 19.3 27.1 40.7 35.7 63.5l13.8 36.6 37.8 10c54.2 14.4 92.1 63.7 92.1 120 0 33.6-13.2 65.1-37.2 88.6-19.5 19.2-44.9 31.1-71.9 34.5-4 .5-6.9 3.9-6.9 7.9V754c0 4.7 4.1 8.4 8.8 8 101.7-9.2 182.5-94 183.2-198.2.6-93.4-62.7-172.1-148.6-194.9z"}}]},name:"cloud-server",theme:"outlined"};var n=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(n.default,(0,t.default)({},e,{ref:a,icon:r}))});e.s(["CloudServerOutlined",0,a],295320)},283713,e=>{"use strict";var t=e.i(271645),i=e.i(764205),r=e.i(612256);let n="litellm_selected_worker_id";e.s(["useWorker",0,()=>{let{data:e}=(0,r.useUIConfig)(),a=e?.is_control_plane??!1,o=e?.workers??[],[l,s]=(0,t.useState)(()=>localStorage.getItem(n));(0,t.useEffect)(()=>{if(!l||0===o.length)return;let e=o.find(e=>e.worker_id===l);e&&(0,i.switchToWorkerUrl)(e.url)},[l,o]);let c=o.find(e=>e.worker_id===l)??null,d=(0,t.useCallback)(e=>{let t=o.find(t=>t.worker_id===e);t&&(s(e),localStorage.setItem(n,e),(0,i.switchToWorkerUrl)(t.url))},[o]);return{isControlPlane:a,workers:o,selectedWorkerId:l,selectedWorker:c,selectWorker:d,disconnectFromWorker:(0,t.useCallback)(()=>{s(null),localStorage.removeItem(n),(0,i.switchToWorkerUrl)(null)},[])}}])},954616,e=>{"use strict";var t=e.i(271645),i=e.i(114272),r=e.i(540143),n=e.i(915823),a=e.i(619273),o=class extends n.Subscribable{#e;#t=void 0;#i;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#n()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,a.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#i,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,a.hashKey)(t.mutationKey)!==(0,a.hashKey)(this.options.mutationKey)?this.reset():this.#i?.state.status==="pending"&&this.#i.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#i?.removeObserver(this)}onMutationUpdate(e){this.#n(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#i?.removeObserver(this),this.#i=void 0,this.#n(),this.#a()}mutate(e,t){return this.#r=t,this.#i?.removeObserver(this),this.#i=this.#e.getMutationCache().build(this.#e,this.options),this.#i.addObserver(this),this.#i.execute(e)}#n(){let e=this.#i?.state??(0,i.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#a(e){r.notifyManager.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,i=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#r.onSuccess?.(e.data,t,i,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,i,r)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#r.onError?.(e.error,t,i,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,i,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},l=e.i(912598);function s(e,i){let n=(0,l.useQueryClient)(i),[s]=t.useState(()=>new o(n,e));t.useEffect(()=>{s.setOptions(e)},[s,e]);let c=t.useSyncExternalStore(t.useCallback(e=>s.subscribe(r.notifyManager.batchCalls(e)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),d=t.useCallback((e,t)=>{s.mutate(e,t).catch(a.noop)},[s]);if(c.error&&(0,a.shouldThrowError)(s.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:d,mutateAsync:c.mutate}}e.s(["useMutation",()=>s],954616)},175712,e=>{"use strict";e.i(247167);var t=e.i(271645),i=e.i(343794),r=e.i(529681),n=e.i(242064),a=e.i(517455),o=e.i(185793),l=e.i(721369),s=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};let c=e=>{var{prefixCls:r,className:a,hoverable:o=!0}=e,l=s(e,["prefixCls","className","hoverable"]);let{getPrefixCls:c}=t.useContext(n.ConfigContext),d=c("card",r),u=(0,i.default)(`${d}-grid`,a,{[`${d}-grid-hoverable`]:o});return t.createElement("div",Object.assign({},l,{className:u}))};e.i(296059);var d=e.i(915654),u=e.i(183293),m=e.i(246422),p=e.i(838378);let g=(0,m.genStyleHooks)("Card",e=>{let t=(0,p.mergeToken)(e,{cardShadow:e.boxShadowCard,cardHeadPadding:e.padding,cardPaddingBase:e.paddingLG,cardActionsIconSize:e.fontSize});return[(e=>{let{componentCls:t,cardShadow:i,cardHeadPadding:r,colorBorderSecondary:n,boxShadowTertiary:a,bodyPadding:o,extraColor:l}=e;return{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"relative",background:e.colorBgContainer,borderRadius:e.borderRadiusLG,[`&:not(${t}-bordered)`]:{boxShadow:a},[`${t}-head`]:(e=>{let{antCls:t,componentCls:i,headerHeight:r,headerPadding:n,tabsMarginBottom:a}=e;return Object.assign(Object.assign({display:"flex",justifyContent:"center",flexDirection:"column",minHeight:r,marginBottom:-1,padding:`0 ${(0,d.unit)(n)}`,color:e.colorTextHeading,fontWeight:e.fontWeightStrong,fontSize:e.headerFontSize,background:e.headerBg,borderBottom:`${(0,d.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorderSecondary}`,borderRadius:`${(0,d.unit)(e.borderRadiusLG)} ${(0,d.unit)(e.borderRadiusLG)} 0 0`},(0,u.clearFix)()),{"&-wrapper":{width:"100%",display:"flex",alignItems:"center"},"&-title":Object.assign(Object.assign({display:"inline-block",flex:1},u.textEllipsis),{[` +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,295320,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M704 446H320c-4.4 0-8 3.6-8 8v402c0 4.4 3.6 8 8 8h384c4.4 0 8-3.6 8-8V454c0-4.4-3.6-8-8-8zm-328 64h272v117H376V510zm272 290H376V683h272v117z"}},{tag:"path",attrs:{d:"M424 748a32 32 0 1064 0 32 32 0 10-64 0zm0-178a32 32 0 1064 0 32 32 0 10-64 0z"}},{tag:"path",attrs:{d:"M811.4 368.9C765.6 248 648.9 162 512.2 162S258.8 247.9 213 368.8C126.9 391.5 63.5 470.2 64 563.6 64.6 668 145.6 752.9 247.6 762c4.7.4 8.7-3.3 8.7-8v-60.4c0-4-3-7.4-7-7.9-27-3.4-52.5-15.2-72.1-34.5-24-23.5-37.2-55.1-37.2-88.6 0-28 9.1-54.4 26.2-76.4 16.7-21.4 40.2-36.9 66.1-43.7l37.9-10 13.9-36.7c8.6-22.8 20.6-44.2 35.7-63.5 14.9-19.2 32.6-36 52.4-50 41.1-28.9 89.5-44.2 140-44.2s98.9 15.3 140 44.3c19.9 14 37.5 30.8 52.4 50 15.1 19.3 27.1 40.7 35.7 63.5l13.8 36.6 37.8 10c54.2 14.4 92.1 63.7 92.1 120 0 33.6-13.2 65.1-37.2 88.6-19.5 19.2-44.9 31.1-71.9 34.5-4 .5-6.9 3.9-6.9 7.9V754c0 4.7 4.1 8.4 8.8 8 101.7-9.2 182.5-94 183.2-198.2.6-93.4-62.7-172.1-148.6-194.9z"}}]},name:"cloud-server",theme:"outlined"};var n=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(n.default,(0,t.default)({},e,{ref:a,icon:r}))});e.s(["CloudServerOutlined",0,a],295320)},283713,e=>{"use strict";var t=e.i(271645),i=e.i(602869),r=e.i(612256);let n="litellm_selected_worker_id";e.s(["useWorker",0,()=>{let{data:e}=(0,r.useUIConfig)(),a=e?.is_control_plane??!1,o=e?.workers??[],[l,s]=(0,t.useState)(()=>localStorage.getItem(n));(0,t.useEffect)(()=>{if(!l||0===o.length)return;let e=o.find(e=>e.worker_id===l);e&&(0,i.switchToWorkerUrl)(e.url)},[l,o]);let c=o.find(e=>e.worker_id===l)??null,d=(0,t.useCallback)(e=>{let t=o.find(t=>t.worker_id===e);t&&(s(e),localStorage.setItem(n,e),(0,i.switchToWorkerUrl)(t.url))},[o]);return{isControlPlane:a,workers:o,selectedWorkerId:l,selectedWorker:c,selectWorker:d,disconnectFromWorker:(0,t.useCallback)(()=>{s(null),localStorage.removeItem(n),(0,i.switchToWorkerUrl)(null)},[])}}])},954616,e=>{"use strict";var t=e.i(271645),i=e.i(114272),r=e.i(540143),n=e.i(915823),a=e.i(619273),o=class extends n.Subscribable{#e;#t=void 0;#i;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#n()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,a.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#i,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,a.hashKey)(t.mutationKey)!==(0,a.hashKey)(this.options.mutationKey)?this.reset():this.#i?.state.status==="pending"&&this.#i.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#i?.removeObserver(this)}onMutationUpdate(e){this.#n(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#i?.removeObserver(this),this.#i=void 0,this.#n(),this.#a()}mutate(e,t){return this.#r=t,this.#i?.removeObserver(this),this.#i=this.#e.getMutationCache().build(this.#e,this.options),this.#i.addObserver(this),this.#i.execute(e)}#n(){let e=this.#i?.state??(0,i.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#a(e){r.notifyManager.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,i=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#r.onSuccess?.(e.data,t,i,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,i,r)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#r.onError?.(e.error,t,i,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,i,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},l=e.i(912598);function s(e,i){let n=(0,l.useQueryClient)(i),[s]=t.useState(()=>new o(n,e));t.useEffect(()=>{s.setOptions(e)},[s,e]);let c=t.useSyncExternalStore(t.useCallback(e=>s.subscribe(r.notifyManager.batchCalls(e)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),d=t.useCallback((e,t)=>{s.mutate(e,t).catch(a.noop)},[s]);if(c.error&&(0,a.shouldThrowError)(s.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:d,mutateAsync:c.mutate}}e.s(["useMutation",()=>s],954616)},175712,e=>{"use strict";e.i(247167);var t=e.i(271645),i=e.i(343794),r=e.i(529681),n=e.i(242064),a=e.i(517455),o=e.i(185793),l=e.i(721369),s=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};let c=e=>{var{prefixCls:r,className:a,hoverable:o=!0}=e,l=s(e,["prefixCls","className","hoverable"]);let{getPrefixCls:c}=t.useContext(n.ConfigContext),d=c("card",r),u=(0,i.default)(`${d}-grid`,a,{[`${d}-grid-hoverable`]:o});return t.createElement("div",Object.assign({},l,{className:u}))};e.i(296059);var d=e.i(915654),u=e.i(183293),m=e.i(246422),p=e.i(838378);let g=(0,m.genStyleHooks)("Card",e=>{let t=(0,p.mergeToken)(e,{cardShadow:e.boxShadowCard,cardHeadPadding:e.padding,cardPaddingBase:e.paddingLG,cardActionsIconSize:e.fontSize});return[(e=>{let{componentCls:t,cardShadow:i,cardHeadPadding:r,colorBorderSecondary:n,boxShadowTertiary:a,bodyPadding:o,extraColor:l}=e;return{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"relative",background:e.colorBgContainer,borderRadius:e.borderRadiusLG,[`&:not(${t}-bordered)`]:{boxShadow:a},[`${t}-head`]:(e=>{let{antCls:t,componentCls:i,headerHeight:r,headerPadding:n,tabsMarginBottom:a}=e;return Object.assign(Object.assign({display:"flex",justifyContent:"center",flexDirection:"column",minHeight:r,marginBottom:-1,padding:`0 ${(0,d.unit)(n)}`,color:e.colorTextHeading,fontWeight:e.fontWeightStrong,fontSize:e.headerFontSize,background:e.headerBg,borderBottom:`${(0,d.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorderSecondary}`,borderRadius:`${(0,d.unit)(e.borderRadiusLG)} ${(0,d.unit)(e.borderRadiusLG)} 0 0`},(0,u.clearFix)()),{"&-wrapper":{width:"100%",display:"flex",alignItems:"center"},"&-title":Object.assign(Object.assign({display:"inline-block",flex:1},u.textEllipsis),{[` > ${i}-typography, > ${i}-typography-edit-content `]:{insetInlineStart:0,marginTop:0,marginBottom:0}}),[`${t}-tabs-top`]:{clear:"both",marginBottom:a,color:e.colorText,fontWeight:"normal",fontSize:e.fontSize,"&-bar":{borderBottom:`${(0,d.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorderSecondary}`}}})})(e),[`${t}-extra`]:{marginInlineStart:"auto",color:l,fontWeight:"normal",fontSize:e.fontSize},[`${t}-body`]:{padding:o,borderRadius:`0 0 ${(0,d.unit)(e.borderRadiusLG)} ${(0,d.unit)(e.borderRadiusLG)}`},[`${t}-grid`]:(e=>{let{cardPaddingBase:t,colorBorderSecondary:i,cardShadow:r,lineWidth:n}=e;return{width:"33.33%",padding:t,border:0,borderRadius:0,boxShadow:` @@ -9,4 +9,4 @@ 0 ${(0,d.unit)(n)} 0 0 ${i} inset; `,transition:`all ${e.motionDurationMid}`,"&-hoverable:hover":{position:"relative",zIndex:1,boxShadow:r}}})(e),[`${t}-cover`]:{"> *":{display:"block",width:"100%",borderRadius:`${(0,d.unit)(e.borderRadiusLG)} ${(0,d.unit)(e.borderRadiusLG)} 0 0`}},[`${t}-actions`]:(e=>{let{componentCls:t,iconCls:i,actionsLiMargin:r,cardActionsIconSize:n,colorBorderSecondary:a,actionsBg:o}=e;return Object.assign(Object.assign({margin:0,padding:0,listStyle:"none",background:o,borderTop:`${(0,d.unit)(e.lineWidth)} ${e.lineType} ${a}`,display:"flex",borderRadius:`0 0 ${(0,d.unit)(e.borderRadiusLG)} ${(0,d.unit)(e.borderRadiusLG)}`},(0,u.clearFix)()),{"& > li":{margin:r,color:e.colorTextDescription,textAlign:"center","> span":{position:"relative",display:"block",minWidth:e.calc(e.cardActionsIconSize).mul(2).equal(),fontSize:e.fontSize,lineHeight:e.lineHeight,cursor:"pointer","&:hover":{color:e.colorPrimary,transition:`color ${e.motionDurationMid}`},[`a:not(${t}-btn), > ${i}`]:{display:"inline-block",width:"100%",color:e.colorIcon,lineHeight:(0,d.unit)(e.fontHeight),transition:`color ${e.motionDurationMid}`,"&:hover":{color:e.colorPrimary}},[`> ${i}`]:{fontSize:n,lineHeight:(0,d.unit)(e.calc(n).mul(e.lineHeight).equal())}},"&:not(:last-child)":{borderInlineEnd:`${(0,d.unit)(e.lineWidth)} ${e.lineType} ${a}`}}})})(e),[`${t}-meta`]:Object.assign(Object.assign({margin:`${(0,d.unit)(e.calc(e.marginXXS).mul(-1).equal())} 0`,display:"flex"},(0,u.clearFix)()),{"&-avatar":{paddingInlineEnd:e.padding},"&-detail":{overflow:"hidden",flex:1,"> div:not(:last-child)":{marginBottom:e.marginXS}},"&-title":Object.assign({color:e.colorTextHeading,fontWeight:e.fontWeightStrong,fontSize:e.fontSizeLG},u.textEllipsis),"&-description":{color:e.colorTextDescription}})}),[`${t}-bordered`]:{border:`${(0,d.unit)(e.lineWidth)} ${e.lineType} ${n}`,[`${t}-cover`]:{marginTop:-1,marginInlineStart:-1,marginInlineEnd:-1}},[`${t}-hoverable`]:{cursor:"pointer",transition:`box-shadow ${e.motionDurationMid}, border-color ${e.motionDurationMid}`,"&:hover":{borderColor:"transparent",boxShadow:i}},[`${t}-contain-grid`]:{borderRadius:`${(0,d.unit)(e.borderRadiusLG)} ${(0,d.unit)(e.borderRadiusLG)} 0 0 `,[`${t}-body`]:{display:"flex",flexWrap:"wrap"},[`&:not(${t}-loading) ${t}-body`]:{marginBlockStart:e.calc(e.lineWidth).mul(-1).equal(),marginInlineStart:e.calc(e.lineWidth).mul(-1).equal(),padding:0}},[`${t}-contain-tabs`]:{[`> div${t}-head`]:{minHeight:0,[`${t}-head-title, ${t}-extra`]:{paddingTop:r}}},[`${t}-type-inner`]:(e=>{let{componentCls:t,colorFillAlter:i,headerPadding:r,bodyPadding:n}=e;return{[`${t}-head`]:{padding:`0 ${(0,d.unit)(r)}`,background:i,"&-title":{fontSize:e.fontSize}},[`${t}-body`]:{padding:`${(0,d.unit)(e.padding)} ${(0,d.unit)(n)}`}}})(e),[`${t}-loading`]:(e=>{let{componentCls:t}=e;return{overflow:"hidden",[`${t}-body`]:{userSelect:"none"}}})(e),[`${t}-rtl`]:{direction:"rtl"}}})(t),(e=>{let{componentCls:t,bodyPaddingSM:i,headerPaddingSM:r,headerHeightSM:n,headerFontSizeSM:a}=e;return{[`${t}-small`]:{[`> ${t}-head`]:{minHeight:n,padding:`0 ${(0,d.unit)(r)}`,fontSize:a,[`> ${t}-head-wrapper`]:{[`> ${t}-extra`]:{fontSize:e.fontSize}}},[`> ${t}-body`]:{padding:i}},[`${t}-small${t}-contain-tabs`]:{[`> ${t}-head`]:{[`${t}-head-title, ${t}-extra`]:{paddingTop:0,display:"flex",alignItems:"center"}}}}})(t)]},e=>{var t,i;return{headerBg:"transparent",headerFontSize:e.fontSizeLG,headerFontSizeSM:e.fontSize,headerHeight:e.fontSizeLG*e.lineHeightLG+2*e.padding,headerHeightSM:e.fontSize*e.lineHeight+2*e.paddingXS,actionsBg:e.colorBgContainer,actionsLiMargin:`${e.paddingSM}px 0`,tabsMarginBottom:-e.padding-e.lineWidth,extraColor:e.colorText,bodyPaddingSM:12,headerPaddingSM:12,bodyPadding:null!=(t=e.bodyPadding)?t:e.paddingLG,headerPadding:null!=(i=e.headerPadding)?i:e.paddingLG}});var h=e.i(792812),f=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};let b=e=>{let{actionClasses:i,actions:r=[],actionStyle:n}=e;return t.createElement("ul",{className:i,style:n},r.map((e,i)=>{let n=`action-${i}`;return t.createElement("li",{style:{width:`${100/r.length}%`},key:n},t.createElement("span",null,e))}))},y=t.forwardRef((e,s)=>{let d,{prefixCls:u,className:m,rootClassName:p,style:y,extra:v,headStyle:x={},bodyStyle:$={},title:S,loading:j,bordered:w,variant:O,size:C,type:E,cover:I,actions:N,tabList:k,children:z,activeTabKey:L,defaultActiveTabKey:M,tabBarExtraContent:R,hoverable:P,tabProps:T={},classNames:_,styles:G}=e,B=f(e,["prefixCls","className","rootClassName","style","extra","headStyle","bodyStyle","title","loading","bordered","variant","size","type","cover","actions","tabList","children","activeTabKey","defaultActiveTabKey","tabBarExtraContent","hoverable","tabProps","classNames","styles"]),{getPrefixCls:A,direction:H,card:U}=t.useContext(n.ConfigContext),[W]=(0,h.default)("card",O,w),D=e=>{var t;return(0,i.default)(null==(t=null==U?void 0:U.classNames)?void 0:t[e],null==_?void 0:_[e])},F=e=>{var t;return Object.assign(Object.assign({},null==(t=null==U?void 0:U.styles)?void 0:t[e]),null==G?void 0:G[e])},K=t.useMemo(()=>{let e=!1;return t.Children.forEach(z,t=>{(null==t?void 0:t.type)===c&&(e=!0)}),e},[z]),q=A("card",u),[V,X,J]=g(q),Q=t.createElement(o.default,{loading:!0,active:!0,paragraph:{rows:4},title:!1},z),Y=void 0!==L,Z=Object.assign(Object.assign({},T),{[Y?"activeKey":"defaultActiveKey"]:Y?L:M,tabBarExtraContent:R}),ee=(0,a.default)(C),et=ee&&"default"!==ee?ee:"large",ei=k?t.createElement(l.default,Object.assign({size:et},Z,{className:`${q}-head-tabs`,onChange:t=>{var i;null==(i=e.onTabChange)||i.call(e,t)},items:k.map(e=>{var{tab:t}=e;return Object.assign({label:t},f(e,["tab"]))})})):null;if(S||v||ei){let e=(0,i.default)(`${q}-head`,D("header")),r=(0,i.default)(`${q}-head-title`,D("title")),n=(0,i.default)(`${q}-extra`,D("extra")),a=Object.assign(Object.assign({},x),F("header"));d=t.createElement("div",{className:e,style:a},t.createElement("div",{className:`${q}-head-wrapper`},S&&t.createElement("div",{className:r,style:F("title")},S),v&&t.createElement("div",{className:n,style:F("extra")},v)),ei)}let er=(0,i.default)(`${q}-cover`,D("cover")),en=I?t.createElement("div",{className:er,style:F("cover")},I):null,ea=(0,i.default)(`${q}-body`,D("body")),eo=Object.assign(Object.assign({},$),F("body")),el=t.createElement("div",{className:ea,style:eo},j?Q:z),es=(0,i.default)(`${q}-actions`,D("actions")),ec=(null==N?void 0:N.length)?t.createElement(b,{actionClasses:es,actionStyle:F("actions"),actions:N}):null,ed=(0,r.default)(B,["onTabChange"]),eu=(0,i.default)(q,null==U?void 0:U.className,{[`${q}-loading`]:j,[`${q}-bordered`]:"borderless"!==W,[`${q}-hoverable`]:P,[`${q}-contain-grid`]:K,[`${q}-contain-tabs`]:null==k?void 0:k.length,[`${q}-${ee}`]:ee,[`${q}-type-${E}`]:!!E,[`${q}-rtl`]:"rtl"===H},m,p,X,J),em=Object.assign(Object.assign({},null==U?void 0:U.style),y);return V(t.createElement("div",Object.assign({ref:s},ed,{className:eu,style:em}),d,en,el,ec))});var v=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};y.Grid=c,y.Meta=e=>{let{prefixCls:r,className:a,avatar:o,title:l,description:s}=e,c=v(e,["prefixCls","className","avatar","title","description"]),{getPrefixCls:d}=t.useContext(n.ConfigContext),u=d("card",r),m=(0,i.default)(`${u}-meta`,a),p=o?t.createElement("div",{className:`${u}-meta-avatar`},o):null,g=l?t.createElement("div",{className:`${u}-meta-title`},l):null,h=s?t.createElement("div",{className:`${u}-meta-description`},s):null,f=g||h?t.createElement("div",{className:`${u}-meta-detail`},g,h):null;return t.createElement("div",Object.assign({},c,{className:m}),p,f)},e.s(["Card",0,y],175712)},770914,908286,38243,e=>{"use strict";e.i(247167);var t=e.i(271645),i=e.i(343794),r=e.i(876556);function n(e){return["small","middle","large"].includes(e)}function a(e){return!!e&&"number"==typeof e&&!Number.isNaN(e)}e.s(["isPresetSize",()=>n,"isValidGapNumber",()=>a],908286);var o=e.i(242064),l=e.i(249616),s=e.i(372409),c=e.i(246422);let d=(0,c.genStyleHooks)(["Space","Addon"],e=>[(e=>{let{componentCls:t,borderRadius:i,paddingSM:r,colorBorder:n,paddingXS:a,fontSizeLG:o,fontSizeSM:l,borderRadiusLG:c,borderRadiusSM:d,colorBgContainerDisabled:u,lineWidth:m}=e;return{[t]:[{display:"inline-flex",alignItems:"center",gap:0,paddingInline:r,margin:0,background:u,borderWidth:m,borderStyle:"solid",borderColor:n,borderRadius:i,"&-large":{fontSize:o,borderRadius:c},"&-small":{paddingInline:a,borderRadius:d,fontSize:l},"&-compact-last-item":{borderEndStartRadius:0,borderStartStartRadius:0},"&-compact-first-item":{borderEndEndRadius:0,borderStartEndRadius:0},"&-compact-item:not(:first-child):not(:last-child)":{borderRadius:0},"&-compact-item:not(:last-child)":{borderInlineEndWidth:0}},(0,s.genCompactItemStyle)(e,{focus:!1})]}})(e)]);var u=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};let m=t.default.forwardRef((e,r)=>{let{className:n,children:a,style:s,prefixCls:c}=e,m=u(e,["className","children","style","prefixCls"]),{getPrefixCls:p,direction:g}=t.default.useContext(o.ConfigContext),h=p("space-addon",c),[f,b,y]=d(h),{compactItemClassnames:v,compactSize:x}=(0,l.useCompactItemContext)(h,g),$=(0,i.default)(h,b,v,y,{[`${h}-${x}`]:x},n);return f(t.default.createElement("div",Object.assign({ref:r,className:$,style:s},m),a))}),p=t.default.createContext({latestIndex:0}),g=p.Provider,h=({className:e,index:i,children:r,split:n,style:a})=>{let{latestIndex:o}=t.useContext(p);return null==r?null:t.createElement(t.Fragment,null,t.createElement("div",{className:e,style:a},r),i{let t=(0,f.mergeToken)(e,{spaceGapSmallSize:e.paddingXS,spaceGapMiddleSize:e.padding,spaceGapLargeSize:e.paddingLG});return[(e=>{let{componentCls:t,antCls:i}=e;return{[t]:{display:"inline-flex","&-rtl":{direction:"rtl"},"&-vertical":{flexDirection:"column"},"&-align":{flexDirection:"column","&-center":{alignItems:"center"},"&-start":{alignItems:"flex-start"},"&-end":{alignItems:"flex-end"},"&-baseline":{alignItems:"baseline"}},[`${t}-item:empty`]:{display:"none"},[`${t}-item > ${i}-badge-not-a-wrapper:only-child`]:{display:"block"}}}})(t),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-row-small":{rowGap:e.spaceGapSmallSize},"&-gap-row-middle":{rowGap:e.spaceGapMiddleSize},"&-gap-row-large":{rowGap:e.spaceGapLargeSize},"&-gap-col-small":{columnGap:e.spaceGapSmallSize},"&-gap-col-middle":{columnGap:e.spaceGapMiddleSize},"&-gap-col-large":{columnGap:e.spaceGapLargeSize}}}})(t)]},()=>({}),{resetStyle:!1});var y=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};let v=t.forwardRef((e,l)=>{var s;let{getPrefixCls:c,direction:d,size:u,className:m,style:p,classNames:f,styles:v}=(0,o.useComponentConfig)("space"),{size:x=null!=u?u:"small",align:$,className:S,rootClassName:j,children:w,direction:O="horizontal",prefixCls:C,split:E,style:I,wrap:N=!1,classNames:k,styles:z}=e,L=y(e,["size","align","className","rootClassName","children","direction","prefixCls","split","style","wrap","classNames","styles"]),[M,R]=Array.isArray(x)?x:[x,x],P=n(R),T=n(M),_=a(R),G=a(M),B=(0,r.default)(w,{keepEmpty:!0}),A=void 0===$&&"horizontal"===O?"center":$,H=c("space",C),[U,W,D]=b(H),F=(0,i.default)(H,m,W,`${H}-${O}`,{[`${H}-rtl`]:"rtl"===d,[`${H}-align-${A}`]:A,[`${H}-gap-row-${R}`]:P,[`${H}-gap-col-${M}`]:T},S,j,D),K=(0,i.default)(`${H}-item`,null!=(s=null==k?void 0:k.item)?s:f.item),q=Object.assign(Object.assign({},v.item),null==z?void 0:z.item),V=B.map((e,i)=>{let r=(null==e?void 0:e.key)||`${K}-${i}`;return t.createElement(h,{className:K,key:r,index:i,split:E,style:q},e)}),X=t.useMemo(()=>({latestIndex:B.reduce((e,t,i)=>null!=t?i:e,0)}),[B]);if(0===B.length)return null;let J={};return N&&(J.flexWrap="wrap"),!T&&G&&(J.columnGap=M),!P&&_&&(J.rowGap=R),U(t.createElement("div",Object.assign({ref:l,className:F,style:Object.assign(Object.assign(Object.assign({},J),p),I)},L),t.createElement(g,{value:X},V)))});v.Compact=l.default,v.Addon=m,e.s(["default",0,v],38243),e.s(["Space",0,v],770914)},560445,e=>{"use strict";e.i(247167);var t=e.i(271645),i=e.i(201072),r=e.i(726289),n=e.i(864517),a=e.i(562901),o=e.i(779573),l=e.i(343794),s=e.i(361275),c=e.i(244009),d=e.i(611935),u=e.i(763731),m=e.i(242064);e.i(296059);var p=e.i(915654),g=e.i(183293),h=e.i(246422);let f=(e,t,i,r,n)=>({background:e,border:`${(0,p.unit)(r.lineWidth)} ${r.lineType} ${t}`,[`${n}-icon`]:{color:i}}),b=(0,h.genStyleHooks)("Alert",e=>[(e=>{let{componentCls:t,motionDurationSlow:i,marginXS:r,marginSM:n,fontSize:a,fontSizeLG:o,lineHeight:l,borderRadiusLG:s,motionEaseInOutCirc:c,withDescriptionIconSize:d,colorText:u,colorTextHeading:m,withDescriptionPadding:p,defaultPadding:h}=e;return{[t]:Object.assign(Object.assign({},(0,g.resetComponent)(e)),{position:"relative",display:"flex",alignItems:"center",padding:h,wordWrap:"break-word",borderRadius:s,[`&${t}-rtl`]:{direction:"rtl"},[`${t}-content`]:{flex:1,minWidth:0},[`${t}-icon`]:{marginInlineEnd:r,lineHeight:0},"&-description":{display:"none",fontSize:a,lineHeight:l},"&-message":{color:m},[`&${t}-motion-leave`]:{overflow:"hidden",opacity:1,transition:`max-height ${i} ${c}, opacity ${i} ${c}, padding-top ${i} ${c}, padding-bottom ${i} ${c}, - margin-bottom ${i} ${c}`},[`&${t}-motion-leave-active`]:{maxHeight:0,marginBottom:"0 !important",paddingTop:0,paddingBottom:0,opacity:0}}),[`${t}-with-description`]:{alignItems:"flex-start",padding:p,[`${t}-icon`]:{marginInlineEnd:n,fontSize:d,lineHeight:0},[`${t}-message`]:{display:"block",marginBottom:r,color:m,fontSize:o},[`${t}-description`]:{display:"block",color:u}},[`${t}-banner`]:{marginBottom:0,border:"0 !important",borderRadius:0}}})(e),(e=>{let{componentCls:t,colorSuccess:i,colorSuccessBorder:r,colorSuccessBg:n,colorWarning:a,colorWarningBorder:o,colorWarningBg:l,colorError:s,colorErrorBorder:c,colorErrorBg:d,colorInfo:u,colorInfoBorder:m,colorInfoBg:p}=e;return{[t]:{"&-success":f(n,r,i,e,t),"&-info":f(p,m,u,e,t),"&-warning":f(l,o,a,e,t),"&-error":Object.assign(Object.assign({},f(d,c,s,e,t)),{[`${t}-description > pre`]:{margin:0,padding:0}})}}})(e),(e=>{let{componentCls:t,iconCls:i,motionDurationMid:r,marginXS:n,fontSizeIcon:a,colorIcon:o,colorIconHover:l}=e;return{[t]:{"&-action":{marginInlineStart:n},[`${t}-close-icon`]:{marginInlineStart:n,padding:0,overflow:"hidden",fontSize:a,lineHeight:(0,p.unit)(a),backgroundColor:"transparent",border:"none",outline:"none",cursor:"pointer",[`${i}-close`]:{color:o,transition:`color ${r}`,"&:hover":{color:l}}},"&-close-text":{color:o,transition:`color ${r}`,"&:hover":{color:l}}}}})(e)],e=>({withDescriptionIconSize:e.fontSizeHeading3,defaultPadding:`${e.paddingContentVerticalSM}px 12px`,withDescriptionPadding:`${e.paddingMD}px ${e.paddingContentHorizontalLG}px`}));var y=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};let v={success:i.default,info:o.default,error:r.default,warning:a.default},x=e=>{let{icon:i,prefixCls:r,type:n}=e,a=v[n]||null;return i?(0,u.replaceElement)(i,t.createElement("span",{className:`${r}-icon`},i),()=>({className:(0,l.default)(`${r}-icon`,i.props.className)})):t.createElement(a,{className:`${r}-icon`})},$=e=>{let{isClosable:i,prefixCls:r,closeIcon:a,handleClose:o,ariaProps:l}=e,s=!0===a||void 0===a?t.createElement(n.default,null):a;return i?t.createElement("button",Object.assign({type:"button",onClick:o,className:`${r}-close-icon`,tabIndex:0},l),s):null},S=t.forwardRef((e,i)=>{let{description:r,prefixCls:n,message:a,banner:o,className:u,rootClassName:p,style:g,onMouseEnter:h,onMouseLeave:f,onClick:v,afterClose:S,showIcon:j,closable:w,closeText:O,closeIcon:C,action:E,id:I}=e,N=y(e,["description","prefixCls","message","banner","className","rootClassName","style","onMouseEnter","onMouseLeave","onClick","afterClose","showIcon","closable","closeText","closeIcon","action","id"]),[k,z]=t.useState(!1),L=t.useRef(null);t.useImperativeHandle(i,()=>({nativeElement:L.current}));let{getPrefixCls:M,direction:R,closable:P,closeIcon:T,className:_,style:G}=(0,m.useComponentConfig)("alert"),B=M("alert",n),[A,H,U]=b(B),W=t=>{var i;z(!0),null==(i=e.onClose)||i.call(e,t)},D=t.useMemo(()=>void 0!==e.type?e.type:o?"warning":"info",[e.type,o]),F=t.useMemo(()=>"object"==typeof w&&!!w.closeIcon||!!O||("boolean"==typeof w?w:!1!==C&&null!=C||!!P),[O,C,w,P]),K=!!o&&void 0===j||j,q=(0,l.default)(B,`${B}-${D}`,{[`${B}-with-description`]:!!r,[`${B}-no-icon`]:!K,[`${B}-banner`]:!!o,[`${B}-rtl`]:"rtl"===R},_,u,p,U,H),V=(0,c.default)(N,{aria:!0,data:!0}),X=t.useMemo(()=>"object"==typeof w&&w.closeIcon?w.closeIcon:O||(void 0!==C?C:"object"==typeof P&&P.closeIcon?P.closeIcon:T),[C,w,P,O,T]),J=t.useMemo(()=>{let e=null!=w?w:P;if("object"==typeof e){let{closeIcon:t}=e;return y(e,["closeIcon"])}return{}},[w,P]);return A(t.createElement(s.default,{visible:!k,motionName:`${B}-motion`,motionAppear:!1,motionEnter:!1,onLeaveStart:e=>({maxHeight:e.offsetHeight}),onLeaveEnd:S},({className:i,style:n},o)=>t.createElement("div",Object.assign({id:I,ref:(0,d.composeRef)(L,o),"data-show":!k,className:(0,l.default)(q,i),style:Object.assign(Object.assign(Object.assign({},G),g),n),onMouseEnter:h,onMouseLeave:f,onClick:v,role:"alert"},V),K?t.createElement(x,{description:r,icon:e.icon,prefixCls:B,type:D}):null,t.createElement("div",{className:`${B}-content`},a?t.createElement("div",{className:`${B}-message`},a):null,r?t.createElement("div",{className:`${B}-description`},r):null),E?t.createElement("div",{className:`${B}-action`},E):null,t.createElement($,{isClosable:F,prefixCls:B,closeIcon:X,handleClose:W,ariaProps:J}))))});var j=e.i(278409),w=e.i(233848),O=e.i(487806),C=e.i(479671),E=e.i(480002),I=e.i(868917);let N=function(e){function i(){var e,t,r;return(0,j.default)(this,i),t=i,r=arguments,t=(0,O.default)(t),(e=(0,E.default)(this,(0,C.default)()?Reflect.construct(t,r||[],(0,O.default)(this).constructor):t.apply(this,r))).state={error:void 0,info:{componentStack:""}},e}return(0,I.default)(i,e),(0,w.default)(i,[{key:"componentDidCatch",value:function(e,t){this.setState({error:e,info:t})}},{key:"render",value:function(){let{message:e,description:i,id:r,children:n}=this.props,{error:a,info:o}=this.state,l=(null==o?void 0:o.componentStack)||null,s=void 0===e?(a||"").toString():e;return a?t.createElement(S,{id:r,type:"error",message:s,description:t.createElement("pre",{style:{fontSize:"0.9em",overflowX:"auto"}},void 0===i?l:i)}):n}}])}(t.Component);S.ErrorBoundary=N,e.s(["Alert",0,S],560445)},936578,571303,e=>{"use strict";var t=e.i(843476),i=e.i(115504),r=e.i(271645);function n({className:e="",...n}){var a,o;let l=(0,r.useId)();return a=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),t=e.find(e=>e.effect.target?.getAttribute("data-spinner-id")===l),i=e.find(e=>e.effect instanceof KeyframeEffect&&e.effect.target?.getAttribute("data-spinner-id")!==l);t&&i&&(t.currentTime=i.currentTime)},o=[l],(0,r.useLayoutEffect)(a,o),(0,t.jsxs)("svg",{"data-spinner-id":l,className:(0,i.cx)("pointer-events-none size-12 animate-spin text-current",e),fill:"none",viewBox:"0 0 24 24",...n,children:[(0,t.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,t.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}function a(){return(0,t.jsxs)("div",{className:(0,i.cx)("h-screen","flex items-center justify-center gap-4"),children:[(0,t.jsx)("div",{className:"text-lg font-medium py-2 pr-4 border-r border-r-gray-200",children:"🚅 LiteLLM"}),(0,t.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,t.jsx)(n,{className:"size-4"}),(0,t.jsx)("span",{className:"text-gray-600 text-sm",children:"Loading..."})]})]})}e.s(["UiLoadingSpinner",()=>n],571303),e.s(["default",()=>a],936578)},594542,e=>{"use strict";var t=e.i(843476),i=e.i(954616),r=e.i(764205),n=e.i(612256),a=e.i(936578),o=e.i(268004),l=e.i(161281),s=e.i(321836),c=e.i(827252),d=e.i(295320),u=e.i(560445),m=e.i(464571),p=e.i(175712),g=e.i(808613),h=e.i(311451),f=e.i(282786),b=e.i(199133),y=e.i(770914),v=e.i(898586),x=e.i(618566),$=e.i(271645),S=e.i(283713);function j(){let[e,j]=(0,$.useState)(""),[w,O]=(0,$.useState)(""),[C,E]=(0,$.useState)(!0),{data:I,isLoading:N}=(0,n.useUIConfig)(),k=(0,i.useMutation)({mutationFn:async({username:e,password:t,useV3:i})=>await (0,r.loginCall)(e,t,i)}),z=(0,x.useRouter)(),{workers:L,selectWorker:M}=(0,S.useWorker)(),[R,P]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=new URLSearchParams(window.location.search).get("worker");e&&P(e)},[]),(0,$.useEffect)(()=>{if(N)return;if(I&&I.admin_ui_disabled)return void E(!1);let e=new URLSearchParams(window.location.search),t=e.get("code"),i=t&&/^[a-zA-Z0-9._~+/=-]+$/.test(t)?t:null;if(i){let t=localStorage.getItem("litellm_worker_url"),n=t&&/^https?:\/\/.+/.test(t)?t:null;(0,r.exchangeLoginCode)(i,n).then(()=>{e.delete("code");let t=e.toString();window.history.replaceState(null,"",window.location.pathname+(t?`?${t}`:"")),z.replace("/ui/?login=success")});return}if(e.has("worker")&&I?.is_control_plane){(0,o.clearTokenCookies)(),E(!1);return}let n=(0,o.getCookieFromDocument)("token");if(n&&!(0,l.isJwtExpired)(n)){let e=(0,s.consumeReturnUrl)();e?z.replace(e):z.replace("/ui");return}if(I&&I.auto_redirect_to_sso){let e=(0,s.getReturnUrl)(),t=`${(0,r.getProxyBaseUrl)()}/sso/key/generate`;e&&(0,s.isValidReturnUrl)(e)&&(t+=`?redirect_to=${encodeURIComponent(e)}`),z.push(t);return}E(!1)},[N,z,I]);let T=k.error instanceof Error?k.error.message:null,_=k.isPending,{Title:G,Text:B,Paragraph:A}=v.Typography;return N||C?(0,t.jsx)(a.default,{}):I&&I.admin_ui_disabled?(0,t.jsx)("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:(0,t.jsx)(p.Card,{className:"w-full max-w-lg shadow-md",children:(0,t.jsxs)(y.Space,{direction:"vertical",size:"middle",className:"w-full",children:[(0,t.jsx)("div",{className:"text-center",children:(0,t.jsx)(G,{level:2,children:"🚅 LiteLLM"})}),(0,t.jsx)(u.Alert,{message:"Admin UI Disabled",description:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(A,{className:"text-sm",children:"The Admin UI has been disabled by the administrator. To re-enable it, please update the following environment variable:"}),(0,t.jsx)(A,{className:"text-sm",children:(0,t.jsx)("code",{className:"bg-gray-100 px-1 py-0.5 rounded text-xs",children:"DISABLE_ADMIN_UI=False"})})]}),type:"warning",showIcon:!0})]})})}):(0,t.jsx)("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:(0,t.jsxs)(p.Card,{className:"w-full max-w-lg shadow-md",children:[(0,t.jsxs)(y.Space,{direction:"vertical",size:"middle",className:"w-full",children:[(0,t.jsx)("div",{className:"text-center",children:(0,t.jsx)(G,{level:2,children:"🚅 LiteLLM"})}),(0,t.jsxs)("div",{className:"text-center",children:[(0,t.jsx)(G,{level:3,children:"Login"}),(0,t.jsx)(B,{type:"secondary",children:"Access your LiteLLM Admin UI."})]}),(0,t.jsx)(u.Alert,{message:"Default Credentials",description:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(A,{className:"text-sm",children:["By default, Username is ",(0,t.jsx)("code",{className:"bg-gray-100 px-1 py-0.5 rounded text-xs",children:"admin"})," and Password is your set LiteLLM Proxy",(0,t.jsx)("code",{className:"bg-gray-100 px-1 py-0.5 rounded text-xs",children:"MASTER_KEY"}),"."]}),(0,t.jsxs)(A,{className:"text-sm",children:["Need to set UI credentials or SSO?"," ",(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/ui",target:"_blank",rel:"noopener noreferrer",children:"Check the documentation"}),"."]})]}),type:"info",icon:(0,t.jsx)(c.InfoCircleOutlined,{}),showIcon:!0}),T&&(0,t.jsx)(u.Alert,{message:T,type:"error",showIcon:!0}),(0,t.jsxs)(g.Form,{onFinish:()=>{let t=L.find(e=>e.worker_id===R);t&&(0,r.switchToWorkerUrl)(t.url),k.mutate({username:e,password:w,useV3:!!t},{onSuccess:e=>{if(t)M(t.worker_id),z.push("/ui/?login=success");else{let t=(0,s.consumeReturnUrl)();t?z.push(t):z.push(e.redirect_url)}},onError:()=>{t&&(0,r.switchToWorkerUrl)(null)}})},layout:"vertical",requiredMark:!1,children:[I?.is_control_plane&&L.length>0&&(0,t.jsx)(g.Form.Item,{label:"Worker",style:{marginBottom:16},children:(0,t.jsx)(b.Select,{value:R||void 0,onChange:e=>P(e),placeholder:"Choose a worker to connect to",size:"large",suffixIcon:(0,t.jsx)(d.CloudServerOutlined,{}),options:L.map(e=>({label:e.name,value:e.worker_id}))})}),(0,t.jsx)(g.Form.Item,{label:"Username",name:"username",rules:[{required:!0,message:"Please enter your username"}],children:(0,t.jsx)(h.Input,{placeholder:"Enter your username",autoComplete:"username",value:e,onChange:e=>j(e.target.value),disabled:_,size:"large",className:"rounded-md border-gray-300"})}),(0,t.jsx)(g.Form.Item,{label:"Password",name:"password",rules:[{required:!0,message:"Please enter your password"}],children:(0,t.jsx)(h.Input.Password,{placeholder:"Enter your password",autoComplete:"current-password",value:w,onChange:e=>O(e.target.value),disabled:_,size:"large"})}),(0,t.jsx)(g.Form.Item,{children:(0,t.jsx)(m.Button,{type:"primary",htmlType:"submit",loading:_,disabled:_,block:!0,size:"large",children:_?"Logging in...":"Login"})}),(0,t.jsx)(g.Form.Item,{children:I?.sso_configured?(0,t.jsx)(m.Button,{disabled:_||!!R&&0===L.length,onClick:()=>{let e=L.find(e=>e.worker_id===R);e&&(localStorage.setItem("litellm_selected_worker_id",R),(0,r.switchToWorkerUrl)(e.url));let t=e?.url??(0,r.getProxyBaseUrl)(),i=encodeURIComponent(window.location.origin+"/ui/login");z.push(`${t}/sso/key/generate?return_to=${i}`)},block:!0,size:"large",children:"Login with SSO"}):(0,t.jsx)(f.Popover,{content:"Please configure SSO to log in with SSO.",trigger:"hover",children:(0,t.jsx)(m.Button,{disabled:!0,block:!0,size:"large",children:"Login with SSO"})})})]})]}),I?.sso_configured&&(0,t.jsx)(u.Alert,{type:"info",showIcon:!0,closable:!0,message:(0,t.jsxs)(B,{children:["Single Sign-On (SSO) is enabled. LiteLLM no longer automatically redirects to the SSO login flow upon loading this page. To re-enable auto-redirect-to-SSO, set ",(0,t.jsx)(B,{code:!0,children:"AUTO_REDIRECT_UI_LOGIN_TO_SSO=true"})," in your environment configuration."]})})]})})}e.s(["default",0,function(){return(0,t.jsx)(j,{})}],594542)}]); \ No newline at end of file + margin-bottom ${i} ${c}`},[`&${t}-motion-leave-active`]:{maxHeight:0,marginBottom:"0 !important",paddingTop:0,paddingBottom:0,opacity:0}}),[`${t}-with-description`]:{alignItems:"flex-start",padding:p,[`${t}-icon`]:{marginInlineEnd:n,fontSize:d,lineHeight:0},[`${t}-message`]:{display:"block",marginBottom:r,color:m,fontSize:o},[`${t}-description`]:{display:"block",color:u}},[`${t}-banner`]:{marginBottom:0,border:"0 !important",borderRadius:0}}})(e),(e=>{let{componentCls:t,colorSuccess:i,colorSuccessBorder:r,colorSuccessBg:n,colorWarning:a,colorWarningBorder:o,colorWarningBg:l,colorError:s,colorErrorBorder:c,colorErrorBg:d,colorInfo:u,colorInfoBorder:m,colorInfoBg:p}=e;return{[t]:{"&-success":f(n,r,i,e,t),"&-info":f(p,m,u,e,t),"&-warning":f(l,o,a,e,t),"&-error":Object.assign(Object.assign({},f(d,c,s,e,t)),{[`${t}-description > pre`]:{margin:0,padding:0}})}}})(e),(e=>{let{componentCls:t,iconCls:i,motionDurationMid:r,marginXS:n,fontSizeIcon:a,colorIcon:o,colorIconHover:l}=e;return{[t]:{"&-action":{marginInlineStart:n},[`${t}-close-icon`]:{marginInlineStart:n,padding:0,overflow:"hidden",fontSize:a,lineHeight:(0,p.unit)(a),backgroundColor:"transparent",border:"none",outline:"none",cursor:"pointer",[`${i}-close`]:{color:o,transition:`color ${r}`,"&:hover":{color:l}}},"&-close-text":{color:o,transition:`color ${r}`,"&:hover":{color:l}}}}})(e)],e=>({withDescriptionIconSize:e.fontSizeHeading3,defaultPadding:`${e.paddingContentVerticalSM}px 12px`,withDescriptionPadding:`${e.paddingMD}px ${e.paddingContentHorizontalLG}px`}));var y=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);nt.indexOf(r[n])&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};let v={success:i.default,info:o.default,error:r.default,warning:a.default},x=e=>{let{icon:i,prefixCls:r,type:n}=e,a=v[n]||null;return i?(0,u.replaceElement)(i,t.createElement("span",{className:`${r}-icon`},i),()=>({className:(0,l.default)(`${r}-icon`,i.props.className)})):t.createElement(a,{className:`${r}-icon`})},$=e=>{let{isClosable:i,prefixCls:r,closeIcon:a,handleClose:o,ariaProps:l}=e,s=!0===a||void 0===a?t.createElement(n.default,null):a;return i?t.createElement("button",Object.assign({type:"button",onClick:o,className:`${r}-close-icon`,tabIndex:0},l),s):null},S=t.forwardRef((e,i)=>{let{description:r,prefixCls:n,message:a,banner:o,className:u,rootClassName:p,style:g,onMouseEnter:h,onMouseLeave:f,onClick:v,afterClose:S,showIcon:j,closable:w,closeText:O,closeIcon:C,action:E,id:I}=e,N=y(e,["description","prefixCls","message","banner","className","rootClassName","style","onMouseEnter","onMouseLeave","onClick","afterClose","showIcon","closable","closeText","closeIcon","action","id"]),[k,z]=t.useState(!1),L=t.useRef(null);t.useImperativeHandle(i,()=>({nativeElement:L.current}));let{getPrefixCls:M,direction:R,closable:P,closeIcon:T,className:_,style:G}=(0,m.useComponentConfig)("alert"),B=M("alert",n),[A,H,U]=b(B),W=t=>{var i;z(!0),null==(i=e.onClose)||i.call(e,t)},D=t.useMemo(()=>void 0!==e.type?e.type:o?"warning":"info",[e.type,o]),F=t.useMemo(()=>"object"==typeof w&&!!w.closeIcon||!!O||("boolean"==typeof w?w:!1!==C&&null!=C||!!P),[O,C,w,P]),K=!!o&&void 0===j||j,q=(0,l.default)(B,`${B}-${D}`,{[`${B}-with-description`]:!!r,[`${B}-no-icon`]:!K,[`${B}-banner`]:!!o,[`${B}-rtl`]:"rtl"===R},_,u,p,U,H),V=(0,c.default)(N,{aria:!0,data:!0}),X=t.useMemo(()=>"object"==typeof w&&w.closeIcon?w.closeIcon:O||(void 0!==C?C:"object"==typeof P&&P.closeIcon?P.closeIcon:T),[C,w,P,O,T]),J=t.useMemo(()=>{let e=null!=w?w:P;if("object"==typeof e){let{closeIcon:t}=e;return y(e,["closeIcon"])}return{}},[w,P]);return A(t.createElement(s.default,{visible:!k,motionName:`${B}-motion`,motionAppear:!1,motionEnter:!1,onLeaveStart:e=>({maxHeight:e.offsetHeight}),onLeaveEnd:S},({className:i,style:n},o)=>t.createElement("div",Object.assign({id:I,ref:(0,d.composeRef)(L,o),"data-show":!k,className:(0,l.default)(q,i),style:Object.assign(Object.assign(Object.assign({},G),g),n),onMouseEnter:h,onMouseLeave:f,onClick:v,role:"alert"},V),K?t.createElement(x,{description:r,icon:e.icon,prefixCls:B,type:D}):null,t.createElement("div",{className:`${B}-content`},a?t.createElement("div",{className:`${B}-message`},a):null,r?t.createElement("div",{className:`${B}-description`},r):null),E?t.createElement("div",{className:`${B}-action`},E):null,t.createElement($,{isClosable:F,prefixCls:B,closeIcon:X,handleClose:W,ariaProps:J}))))});var j=e.i(278409),w=e.i(233848),O=e.i(487806),C=e.i(479671),E=e.i(480002),I=e.i(868917);let N=function(e){function i(){var e,t,r;return(0,j.default)(this,i),t=i,r=arguments,t=(0,O.default)(t),(e=(0,E.default)(this,(0,C.default)()?Reflect.construct(t,r||[],(0,O.default)(this).constructor):t.apply(this,r))).state={error:void 0,info:{componentStack:""}},e}return(0,I.default)(i,e),(0,w.default)(i,[{key:"componentDidCatch",value:function(e,t){this.setState({error:e,info:t})}},{key:"render",value:function(){let{message:e,description:i,id:r,children:n}=this.props,{error:a,info:o}=this.state,l=(null==o?void 0:o.componentStack)||null,s=void 0===e?(a||"").toString():e;return a?t.createElement(S,{id:r,type:"error",message:s,description:t.createElement("pre",{style:{fontSize:"0.9em",overflowX:"auto"}},void 0===i?l:i)}):n}}])}(t.Component);S.ErrorBoundary=N,e.s(["Alert",0,S],560445)},936578,571303,e=>{"use strict";var t=e.i(843476),i=e.i(115504),r=e.i(271645);function n({className:e="",...n}){var a,o;let l=(0,r.useId)();return a=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),t=e.find(e=>e.effect.target?.getAttribute("data-spinner-id")===l),i=e.find(e=>e.effect instanceof KeyframeEffect&&e.effect.target?.getAttribute("data-spinner-id")!==l);t&&i&&(t.currentTime=i.currentTime)},o=[l],(0,r.useLayoutEffect)(a,o),(0,t.jsxs)("svg",{"data-spinner-id":l,className:(0,i.cx)("pointer-events-none size-12 animate-spin text-current",e),fill:"none",viewBox:"0 0 24 24",...n,children:[(0,t.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,t.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}function a(){return(0,t.jsxs)("div",{className:(0,i.cx)("h-screen","flex items-center justify-center gap-4"),children:[(0,t.jsx)("div",{className:"text-lg font-medium py-2 pr-4 border-r border-r-gray-200",children:"🚅 LiteLLM"}),(0,t.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,t.jsx)(n,{className:"size-4"}),(0,t.jsx)("span",{className:"text-gray-600 text-sm",children:"Loading..."})]})]})}e.s(["UiLoadingSpinner",()=>n],571303),e.s(["default",()=>a],936578)},594542,e=>{"use strict";var t=e.i(843476),i=e.i(954616),r=e.i(602869),n=e.i(612256),a=e.i(936578),o=e.i(268004),l=e.i(161281),s=e.i(321836),c=e.i(827252),d=e.i(295320),u=e.i(560445),m=e.i(464571),p=e.i(175712),g=e.i(808613),h=e.i(311451),f=e.i(282786),b=e.i(199133),y=e.i(770914),v=e.i(898586),x=e.i(618566),$=e.i(271645),S=e.i(283713);function j(){let[e,j]=(0,$.useState)(""),[w,O]=(0,$.useState)(""),[C,E]=(0,$.useState)(!0),{data:I,isLoading:N}=(0,n.useUIConfig)(),k=(0,i.useMutation)({mutationFn:async({username:e,password:t,useV3:i})=>await (0,r.loginCall)(e,t,i)}),z=(0,x.useRouter)(),{workers:L,selectWorker:M}=(0,S.useWorker)(),[R,P]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=new URLSearchParams(window.location.search).get("worker");e&&P(e)},[]),(0,$.useEffect)(()=>{if(N)return;if(I&&I.admin_ui_disabled)return void E(!1);let e=new URLSearchParams(window.location.search),t=e.get("code"),i=t&&/^[a-zA-Z0-9._~+/=-]+$/.test(t)?t:null;if(i){let t=localStorage.getItem("litellm_worker_url"),n=t&&/^https?:\/\/.+/.test(t)?t:null;(0,r.exchangeLoginCode)(i,n).then(()=>{e.delete("code");let t=e.toString();window.history.replaceState(null,"",window.location.pathname+(t?`?${t}`:"")),z.replace("/ui/?login=success")});return}if(e.has("worker")&&I?.is_control_plane){(0,o.clearTokenCookies)(),E(!1);return}let n=(0,o.getCookieFromDocument)("token");if(n&&!(0,l.isJwtExpired)(n)){let e=(0,s.consumeReturnUrl)();e?z.replace(e):z.replace("/ui");return}if(I&&I.auto_redirect_to_sso){let e=(0,s.getReturnUrl)(),t=`${(0,r.getProxyBaseUrl)()}/sso/key/generate`;e&&(0,s.isValidReturnUrl)(e)&&(t+=`?redirect_to=${encodeURIComponent(e)}`),z.push(t);return}E(!1)},[N,z,I]);let T=k.error instanceof Error?k.error.message:null,_=k.isPending,{Title:G,Text:B,Paragraph:A}=v.Typography;return N||C?(0,t.jsx)(a.default,{}):I&&I.admin_ui_disabled?(0,t.jsx)("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:(0,t.jsx)(p.Card,{className:"w-full max-w-lg shadow-md",children:(0,t.jsxs)(y.Space,{direction:"vertical",size:"middle",className:"w-full",children:[(0,t.jsx)("div",{className:"text-center",children:(0,t.jsx)(G,{level:2,children:"🚅 LiteLLM"})}),(0,t.jsx)(u.Alert,{message:"Admin UI Disabled",description:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(A,{className:"text-sm",children:"The Admin UI has been disabled by the administrator. To re-enable it, please update the following environment variable:"}),(0,t.jsx)(A,{className:"text-sm",children:(0,t.jsx)("code",{className:"bg-gray-100 px-1 py-0.5 rounded text-xs",children:"DISABLE_ADMIN_UI=False"})})]}),type:"warning",showIcon:!0})]})})}):(0,t.jsx)("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:(0,t.jsxs)(p.Card,{className:"w-full max-w-lg shadow-md",children:[(0,t.jsxs)(y.Space,{direction:"vertical",size:"middle",className:"w-full",children:[(0,t.jsx)("div",{className:"text-center",children:(0,t.jsx)(G,{level:2,children:"🚅 LiteLLM"})}),(0,t.jsxs)("div",{className:"text-center",children:[(0,t.jsx)(G,{level:3,children:"Login"}),(0,t.jsx)(B,{type:"secondary",children:"Access your LiteLLM Admin UI."})]}),(0,t.jsx)(u.Alert,{message:"Default Credentials",description:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(A,{className:"text-sm",children:["By default, Username is ",(0,t.jsx)("code",{className:"bg-gray-100 px-1 py-0.5 rounded text-xs",children:"admin"})," and Password is your set LiteLLM Proxy",(0,t.jsx)("code",{className:"bg-gray-100 px-1 py-0.5 rounded text-xs",children:"MASTER_KEY"}),"."]}),(0,t.jsxs)(A,{className:"text-sm",children:["Need to set UI credentials or SSO?"," ",(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/ui",target:"_blank",rel:"noopener noreferrer",children:"Check the documentation"}),"."]})]}),type:"info",icon:(0,t.jsx)(c.InfoCircleOutlined,{}),showIcon:!0}),T&&(0,t.jsx)(u.Alert,{message:T,type:"error",showIcon:!0}),(0,t.jsxs)(g.Form,{onFinish:()=>{let t=L.find(e=>e.worker_id===R);t&&(0,r.switchToWorkerUrl)(t.url),k.mutate({username:e,password:w,useV3:!!t},{onSuccess:e=>{if(t)M(t.worker_id),z.push("/ui/?login=success");else{let t=(0,s.consumeReturnUrl)();t?z.push(t):z.push(e.redirect_url)}},onError:()=>{t&&(0,r.switchToWorkerUrl)(null)}})},layout:"vertical",requiredMark:!1,children:[I?.is_control_plane&&L.length>0&&(0,t.jsx)(g.Form.Item,{label:"Worker",style:{marginBottom:16},children:(0,t.jsx)(b.Select,{value:R||void 0,onChange:e=>P(e),placeholder:"Choose a worker to connect to",size:"large",suffixIcon:(0,t.jsx)(d.CloudServerOutlined,{}),options:L.map(e=>({label:e.name,value:e.worker_id}))})}),(0,t.jsx)(g.Form.Item,{label:"Username",name:"username",rules:[{required:!0,message:"Please enter your username"}],children:(0,t.jsx)(h.Input,{placeholder:"Enter your username",autoComplete:"username",value:e,onChange:e=>j(e.target.value),disabled:_,size:"large",className:"rounded-md border-gray-300"})}),(0,t.jsx)(g.Form.Item,{label:"Password",name:"password",rules:[{required:!0,message:"Please enter your password"}],children:(0,t.jsx)(h.Input.Password,{placeholder:"Enter your password",autoComplete:"current-password",value:w,onChange:e=>O(e.target.value),disabled:_,size:"large"})}),(0,t.jsx)(g.Form.Item,{children:(0,t.jsx)(m.Button,{type:"primary",htmlType:"submit",loading:_,disabled:_,block:!0,size:"large",children:_?"Logging in...":"Login"})}),(0,t.jsx)(g.Form.Item,{children:I?.sso_configured?(0,t.jsx)(m.Button,{disabled:_||!!R&&0===L.length,onClick:()=>{let e=L.find(e=>e.worker_id===R);e&&(localStorage.setItem("litellm_selected_worker_id",R),(0,r.switchToWorkerUrl)(e.url));let t=e?.url??(0,r.getProxyBaseUrl)(),i=encodeURIComponent(window.location.origin+"/ui/login");z.push(`${t}/sso/key/generate?return_to=${i}`)},block:!0,size:"large",children:"Login with SSO"}):(0,t.jsx)(f.Popover,{content:"Please configure SSO to log in with SSO.",trigger:"hover",children:(0,t.jsx)(m.Button,{disabled:!0,block:!0,size:"large",children:"Login with SSO"})})})]})]}),I?.sso_configured&&(0,t.jsx)(u.Alert,{type:"info",showIcon:!0,closable:!0,message:(0,t.jsxs)(B,{children:["Single Sign-On (SSO) is enabled. LiteLLM no longer automatically redirects to the SSO login flow upon loading this page. To re-enable auto-redirect-to-SSO, set"," ",(0,t.jsx)(B,{code:!0,children:"AUTO_REDIRECT_UI_LOGIN_TO_SSO=true"})," in your environment configuration."]})})]})})}e.s(["default",0,function(){return(0,t.jsx)(j,{})}],594542)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/36d1c027ba991a4f.js b/litellm/proxy/_experimental/out/_next/static/chunks/10757c2146f43db4.js similarity index 66% rename from litellm/proxy/_experimental/out/_next/static/chunks/36d1c027ba991a4f.js rename to litellm/proxy/_experimental/out/_next/static/chunks/10757c2146f43db4.js index 091c3b70110..3b6538f90e1 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/36d1c027ba991a4f.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/10757c2146f43db4.js @@ -1,6 +1,6 @@ (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,127952,869216,368869,e=>{"use strict";var t=e.i(843476),n=e.i(560445),r=e.i(175712);e.i(247167);var l=e.i(271645),a=e.i(343794),o=e.i(908206),i=e.i(242064),s=e.i(517455),d=e.i(150073);let c={xxl:3,xl:3,lg:3,md:3,sm:2,xs:1},u=l.default.createContext({});var f=e.i(876556),m=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,r=Object.getOwnPropertySymbols(e);lt.indexOf(r[l])&&Object.prototype.propertyIsEnumerable.call(e,r[l])&&(n[r[l]]=e[r[l]]);return n},p=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,r=Object.getOwnPropertySymbols(e);lt.indexOf(r[l])&&Object.prototype.propertyIsEnumerable.call(e,r[l])&&(n[r[l]]=e[r[l]]);return n};let g=e=>{let{itemPrefixCls:t,component:n,span:r,className:o,style:i,labelStyle:s,contentStyle:d,bordered:c,label:f,content:m,colon:p,type:g,styles:h}=e,{classNames:x}=l.useContext(u),v=Object.assign(Object.assign({},s),null==h?void 0:h.label),b=Object.assign(Object.assign({},d),null==h?void 0:h.content);if(c)return l.createElement(n,{colSpan:r,style:i,className:(0,a.default)(o,{[`${t}-item-${g}`]:"label"===g||"content"===g,[null==x?void 0:x.label]:(null==x?void 0:x.label)&&"label"===g,[null==x?void 0:x.content]:(null==x?void 0:x.content)&&"content"===g})},null!=f&&l.createElement("span",{style:v},f),null!=m&&l.createElement("span",{style:b},m));return l.createElement(n,{colSpan:r,style:i,className:(0,a.default)(`${t}-item`,o)},l.createElement("div",{className:`${t}-item-container`},null!=f&&l.createElement("span",{style:v,className:(0,a.default)(`${t}-item-label`,null==x?void 0:x.label,{[`${t}-item-no-colon`]:!p})},f),null!=m&&l.createElement("span",{style:b,className:(0,a.default)(`${t}-item-content`,null==x?void 0:x.content)},m)))};function h(e,{colon:t,prefixCls:n,bordered:r},{component:a,type:o,showLabel:i,showContent:s,labelStyle:d,contentStyle:c,styles:u}){return e.map(({label:e,children:f,prefixCls:m=n,className:p,style:h,labelStyle:x,contentStyle:v,span:b=1,key:y,styles:w},j)=>"string"==typeof a?l.createElement(g,{key:`${o}-${y||j}`,className:p,style:h,styles:{label:Object.assign(Object.assign(Object.assign(Object.assign({},d),null==u?void 0:u.label),x),null==w?void 0:w.label),content:Object.assign(Object.assign(Object.assign(Object.assign({},c),null==u?void 0:u.content),v),null==w?void 0:w.content)},span:b,colon:t,component:a,itemPrefixCls:m,bordered:r,label:i?e:null,content:s?f:null,type:o}):[l.createElement(g,{key:`label-${y||j}`,className:p,style:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},d),null==u?void 0:u.label),h),x),null==w?void 0:w.label),span:1,colon:t,component:a[0],itemPrefixCls:m,bordered:r,label:e,type:"label"}),l.createElement(g,{key:`content-${y||j}`,className:p,style:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},c),null==u?void 0:u.content),h),v),null==w?void 0:w.content),span:2*b-1,component:a[1],itemPrefixCls:m,bordered:r,content:f,type:"content"})])}let x=e=>{let t=l.useContext(u),{prefixCls:n,vertical:r,row:a,index:o,bordered:i}=e;return r?l.createElement(l.Fragment,null,l.createElement("tr",{key:`label-${o}`,className:`${n}-row`},h(a,e,Object.assign({component:"th",type:"label",showLabel:!0},t))),l.createElement("tr",{key:`content-${o}`,className:`${n}-row`},h(a,e,Object.assign({component:"td",type:"content",showContent:!0},t)))):l.createElement("tr",{key:o,className:`${n}-row`},h(a,e,Object.assign({component:i?["th","td"]:"td",type:"item",showLabel:!0,showContent:!0},t)))};e.i(296059);var v=e.i(915654),b=e.i(183293),y=e.i(246422),w=e.i(838378);let j=(0,y.genStyleHooks)("Descriptions",e=>(e=>{let{componentCls:t,extraColor:n,itemPaddingBottom:r,itemPaddingEnd:l,colonMarginRight:a,colonMarginLeft:o,titleMarginBottom:i}=e;return{[t]:Object.assign(Object.assign(Object.assign({},(0,b.resetComponent)(e)),(e=>{let{componentCls:t,labelBg:n}=e;return{[`&${t}-bordered`]:{[`> ${t}-view`]:{border:`${(0,v.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"> table":{tableLayout:"auto"},[`${t}-row`]:{borderBottom:`${(0,v.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"&:first-child":{"> th:first-child, > td:first-child":{borderStartStartRadius:e.borderRadiusLG}},"&:last-child":{borderBottom:"none","> th:first-child, > td:first-child":{borderEndStartRadius:e.borderRadiusLG}},[`> ${t}-item-label, > ${t}-item-content`]:{padding:`${(0,v.unit)(e.padding)} ${(0,v.unit)(e.paddingLG)}`,borderInlineEnd:`${(0,v.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"&:last-child":{borderInlineEnd:"none"}},[`> ${t}-item-label`]:{color:e.colorTextSecondary,backgroundColor:n,"&::after":{display:"none"}}}},[`&${t}-middle`]:{[`${t}-row`]:{[`> ${t}-item-label, > ${t}-item-content`]:{padding:`${(0,v.unit)(e.paddingSM)} ${(0,v.unit)(e.paddingLG)}`}}},[`&${t}-small`]:{[`${t}-row`]:{[`> ${t}-item-label, > ${t}-item-content`]:{padding:`${(0,v.unit)(e.paddingXS)} ${(0,v.unit)(e.padding)}`}}}}}})(e)),{"&-rtl":{direction:"rtl"},[`${t}-header`]:{display:"flex",alignItems:"center",marginBottom:i},[`${t}-title`]:Object.assign(Object.assign({},b.textEllipsis),{flex:"auto",color:e.titleColor,fontWeight:e.fontWeightStrong,fontSize:e.fontSizeLG,lineHeight:e.lineHeightLG}),[`${t}-extra`]:{marginInlineStart:"auto",color:n,fontSize:e.fontSize},[`${t}-view`]:{width:"100%",borderRadius:e.borderRadiusLG,table:{width:"100%",tableLayout:"fixed",borderCollapse:"collapse"}},[`${t}-row`]:{"> th, > td":{paddingBottom:r,paddingInlineEnd:l},"> th:last-child, > td:last-child":{paddingInlineEnd:0},"&:last-child":{borderBottom:"none","> th, > td":{paddingBottom:0}}},[`${t}-item-label`]:{color:e.labelColor,fontWeight:"normal",fontSize:e.fontSize,lineHeight:e.lineHeight,textAlign:"start","&::after":{content:'":"',position:"relative",top:-.5,marginInline:`${(0,v.unit)(o)} ${(0,v.unit)(a)}`},[`&${t}-item-no-colon::after`]:{content:'""'}},[`${t}-item-no-label`]:{"&::after":{margin:0,content:'""'}},[`${t}-item-content`]:{display:"table-cell",flex:1,color:e.contentColor,fontSize:e.fontSize,lineHeight:e.lineHeight,wordBreak:"break-word",overflowWrap:"break-word"},[`${t}-item`]:{paddingBottom:0,verticalAlign:"top","&-container":{display:"flex",[`${t}-item-label`]:{display:"inline-flex",alignItems:"baseline"},[`${t}-item-content`]:{display:"inline-flex",alignItems:"baseline",minWidth:"1em"}}},"&-middle":{[`${t}-row`]:{"> th, > td":{paddingBottom:e.paddingSM}}},"&-small":{[`${t}-row`]:{"> th, > td":{paddingBottom:e.paddingXS}}}})}})((0,w.mergeToken)(e,{})),e=>({labelBg:e.colorFillAlter,labelColor:e.colorTextTertiary,titleColor:e.colorText,titleMarginBottom:e.fontSizeSM*e.lineHeightSM,itemPaddingBottom:e.padding,itemPaddingEnd:e.padding,colonMarginRight:e.marginXS,colonMarginLeft:e.marginXXS/2,contentColor:e.colorText,extraColor:e.colorText}));var k=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,r=Object.getOwnPropertySymbols(e);lt.indexOf(r[l])&&Object.prototype.propertyIsEnumerable.call(e,r[l])&&(n[r[l]]=e[r[l]]);return n};let C=e=>{let t,{prefixCls:n,title:r,extra:g,column:h,colon:v=!0,bordered:b,layout:y,children:w,className:C,rootClassName:S,style:N,size:E,labelStyle:_,contentStyle:O,styles:$,items:T,classNames:I}=e,P=k(e,["prefixCls","title","extra","column","colon","bordered","layout","children","className","rootClassName","style","size","labelStyle","contentStyle","styles","items","classNames"]),{getPrefixCls:M,direction:R,className:L,style:D,classNames:A,styles:K}=(0,i.useComponentConfig)("descriptions"),B=M("descriptions",n),F=(0,d.default)(),z=l.useMemo(()=>{var e;return"number"==typeof h?h:null!=(e=(0,o.matchScreen)(F,Object.assign(Object.assign({},c),h)))?e:3},[F,h]),H=(t=l.useMemo(()=>T||(0,f.default)(w).map(e=>Object.assign(Object.assign({},null==e?void 0:e.props),{key:e.key})),[T,w]),l.useMemo(()=>t.map(e=>{var{span:t}=e,n=m(e,["span"]);return"filled"===t?Object.assign(Object.assign({},n),{filled:!0}):Object.assign(Object.assign({},n),{span:"number"==typeof t?t:(0,o.matchScreen)(F,t)})}),[t,F])),V=(0,s.default)(E),W=((e,t)=>{let[n,r]=(0,l.useMemo)(()=>{let n,r,l,a;return n=[],r=[],l=!1,a=0,t.filter(e=>e).forEach(t=>{let{filled:o}=t,i=p(t,["filled"]);if(o){r.push(i),n.push(r),r=[],a=0;return}let s=e-a;(a+=t.span||1)>=e?(a>e?(l=!0,r.push(Object.assign(Object.assign({},i),{span:s}))):r.push(i),n.push(r),r=[],a=0):r.push(i)}),r.length>0&&n.push(r),[n=n.map(t=>{let n=t.reduce((e,t)=>e+(t.span||1),0);if(n({labelStyle:_,contentStyle:O,styles:{content:Object.assign(Object.assign({},K.content),null==$?void 0:$.content),label:Object.assign(Object.assign({},K.label),null==$?void 0:$.label)},classNames:{label:(0,a.default)(A.label,null==I?void 0:I.label),content:(0,a.default)(A.content,null==I?void 0:I.content)}}),[_,O,$,I,A,K]);return U(l.createElement(u.Provider,{value:X},l.createElement("div",Object.assign({className:(0,a.default)(B,L,A.root,null==I?void 0:I.root,{[`${B}-${V}`]:V&&"default"!==V,[`${B}-bordered`]:!!b,[`${B}-rtl`]:"rtl"===R},C,S,q,G),style:Object.assign(Object.assign(Object.assign(Object.assign({},D),K.root),null==$?void 0:$.root),N)},P),(r||g)&&l.createElement("div",{className:(0,a.default)(`${B}-header`,A.header,null==I?void 0:I.header),style:Object.assign(Object.assign({},K.header),null==$?void 0:$.header)},r&&l.createElement("div",{className:(0,a.default)(`${B}-title`,A.title,null==I?void 0:I.title),style:Object.assign(Object.assign({},K.title),null==$?void 0:$.title)},r),g&&l.createElement("div",{className:(0,a.default)(`${B}-extra`,A.extra,null==I?void 0:I.extra),style:Object.assign(Object.assign({},K.extra),null==$?void 0:$.extra)},g)),l.createElement("div",{className:`${B}-view`},l.createElement("table",null,l.createElement("tbody",null,W.map((e,t)=>l.createElement(x,{key:t,index:t,colon:v,prefixCls:B,vertical:"vertical"===y,bordered:b,row:e}))))))))};C.Item=({children:e})=>e,e.s(["Descriptions",0,C],869216);var S=e.i(311451),N=e.i(212931),E=e.i(898586),_=e.i(868297),O=e.i(732961),$=e.i(289882),T=e.i(170517),I=e.i(628882),P=e.i(320890),M=e.i(104458),R=e.i(722319),L=e.i(8398),D=e.i(279728);e.i(765846);var A=e.i(602716),K=e.i(328052);e.i(262370);var B=e.i(135551);let F=(e,t)=>new B.FastColor(e).setA(t).toRgbString(),z=(e,t)=>new B.FastColor(e).lighten(t).toHexString(),H=e=>{let t=(0,A.generate)(e,{theme:"dark"});return{1:t[0],2:t[1],3:t[2],4:t[3],5:t[6],6:t[5],7:t[4],8:t[6],9:t[5],10:t[4]}},V=(e,t)=>{let n=e||"#000",r=t||"#fff";return{colorBgBase:n,colorTextBase:r,colorText:F(r,.85),colorTextSecondary:F(r,.65),colorTextTertiary:F(r,.45),colorTextQuaternary:F(r,.25),colorFill:F(r,.18),colorFillSecondary:F(r,.12),colorFillTertiary:F(r,.08),colorFillQuaternary:F(r,.04),colorBgSolid:F(r,.95),colorBgSolidHover:F(r,1),colorBgSolidActive:F(r,.9),colorBgElevated:z(n,12),colorBgContainer:z(n,8),colorBgLayout:z(n,0),colorBgSpotlight:z(n,26),colorBgBlur:F(r,.04),colorBorder:z(n,26),colorBorderSecondary:z(n,19)}},W={defaultSeed:P.defaultConfig.token,useToken:function(){let[e,t,n]=(0,M.useToken)();return{theme:e,token:t,hashId:n}},defaultAlgorithm:R.default,darkAlgorithm:(e,t)=>{let n=Object.keys(T.defaultPresetColors).map(t=>{let n=(0,A.generate)(e[t],{theme:"dark"});return Array.from({length:10},()=>1).reduce((e,r,l)=>(e[`${t}-${l+1}`]=n[l],e[`${t}${l+1}`]=n[l],e),{})}).reduce((e,t)=>e=Object.assign(Object.assign({},e),t),{}),r=null!=t?t:(0,R.default)(e),l=(0,K.default)(e,{generateColorPalettes:H,generateNeutralColorPalettes:V});return Object.assign(Object.assign(Object.assign(Object.assign({},r),n),l),{colorPrimaryBg:l.colorPrimaryBorder,colorPrimaryBgHover:l.colorPrimaryBorderHover})},compactAlgorithm:(e,t)=>{let n=null!=t?t:(0,R.default)(e),r=n.fontSizeSM,l=n.controlHeight-4;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n),function(e){let{sizeUnit:t,sizeStep:n}=e,r=n-2;return{sizeXXL:t*(r+10),sizeXL:t*(r+6),sizeLG:t*(r+2),sizeMD:t*(r+2),sizeMS:t*(r+1),size:t*r,sizeSM:t*r,sizeXS:t*(r-1),sizeXXS:t*(r-1)}}(null!=t?t:e)),(0,D.default)(r)),{controlHeight:l}),(0,L.default)(Object.assign(Object.assign({},n),{controlHeight:l})))},getDesignToken:e=>{let t=(null==e?void 0:e.algorithm)?(0,_.createTheme)(e.algorithm):$.default,n=Object.assign(Object.assign({},T.default),null==e?void 0:e.token);return(0,O.getComputedToken)(n,{override:null==e?void 0:e.token},t,I.default)},defaultConfig:P.defaultConfig,_internalContext:P.DesignTokenContext};e.s(["theme",0,W],368869);var U=e.i(270377);function q({isOpen:e,title:a,alertMessage:o,message:i,resourceInformationTitle:s,resourceInformation:d,onCancel:c,onOk:u,confirmLoading:f,requiredConfirmation:m}){let{Title:p,Text:g}=E.Typography,{token:h}=W.useToken(),[x,v]=(0,l.useState)("");return(0,l.useEffect)(()=>{e&&v("")},[e]),(0,t.jsx)(N.Modal,{title:a,open:e,onOk:u,onCancel:c,confirmLoading:f,okText:f?"Deleting...":"Delete",cancelText:"Cancel",okButtonProps:{danger:!0,disabled:!!m&&x!==m||f},cancelButtonProps:{disabled:f},children:(0,t.jsxs)("div",{className:"space-y-4",children:[o&&(0,t.jsx)(n.Alert,{message:o,type:"warning"}),(0,t.jsx)(r.Card,{title:s,className:"mt-4",styles:{body:{padding:"16px"},header:{backgroundColor:h.colorErrorBg,borderColor:h.colorErrorBorder}},style:{backgroundColor:h.colorErrorBg,borderColor:h.colorErrorBorder},children:(0,t.jsx)(C,{column:1,size:"small",children:d&&d.map(({label:e,value:n,...r})=>(0,t.jsx)(C.Item,{label:(0,t.jsx)("span",{className:"font-semibold",children:e}),children:(0,t.jsx)(g,{...r,children:n??"-"})},e))})}),(0,t.jsx)("div",{children:(0,t.jsx)(g,{children:i})}),m&&(0,t.jsxs)("div",{className:"mb-6 mt-4 pt-4 border-t border-gray-200 dark:border-gray-700",children:[(0,t.jsxs)(g,{className:"block text-base font-medium text-gray-700 dark:text-gray-300 mb-2",children:[(0,t.jsx)(g,{children:"Type "}),(0,t.jsx)(g,{strong:!0,type:"danger",children:m}),(0,t.jsx)(g,{children:" to confirm deletion:"})]}),(0,t.jsx)(S.Input,{value:x,onChange:e=>v(e.target.value),placeholder:m,className:"rounded-md",prefix:(0,t.jsx)(U.ExclamationCircleOutlined,{style:{color:h.colorError}}),autoFocus:!0})]})]})})}e.s(["default",()=>q],127952)},950724,(e,t,n)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},100236,(e,t,n)=>{t.exports=e.g&&e.g.Object===Object&&e.g},139088,(e,t,n)=>{var r=e.r(100236),l="object"==typeof self&&self&&self.Object===Object&&self;t.exports=r||l||Function("return this")()},631926,(e,t,n)=>{var r=e.r(139088);t.exports=function(){return r.Date.now()}},748891,(e,t,n)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}},830364,(e,t,n)=>{var r=e.r(748891),l=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(l,""):e}},630353,(e,t,n)=>{t.exports=e.r(139088).Symbol},243436,(e,t,n)=>{var r=e.r(630353),l=Object.prototype,a=l.hasOwnProperty,o=l.toString,i=r?r.toStringTag:void 0;t.exports=function(e){var t=a.call(e,i),n=e[i];try{e[i]=void 0;var r=!0}catch(e){}var l=o.call(e);return r&&(t?e[i]=n:delete e[i]),l}},223243,(e,t,n)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}},377684,(e,t,n)=>{var r=e.r(630353),l=e.r(243436),a=e.r(223243),o=r?r.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":o&&o in Object(e)?l(e):a(e)}},877289,(e,t,n)=>{t.exports=function(e){return null!=e&&"object"==typeof e}},361884,(e,t,n)=>{var r=e.r(377684),l=e.r(877289);t.exports=function(e){return"symbol"==typeof e||l(e)&&"[object Symbol]"==r(e)}},773759,(e,t,n)=>{var r=e.r(830364),l=e.r(950724),a=e.r(361884),o=0/0,i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,d=/^0o[0-7]+$/i,c=parseInt;t.exports=function(e){if("number"==typeof e)return e;if(a(e))return o;if(l(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=l(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=r(e);var n=s.test(e);return n||d.test(e)?c(e.slice(2),n?2:8):i.test(e)?o:+e}},374009,(e,t,n)=>{var r=e.r(950724),l=e.r(631926),a=e.r(773759),o=Math.max,i=Math.min;t.exports=function(e,t,n){var s,d,c,u,f,m,p=0,g=!1,h=!1,x=!0;if("function"!=typeof e)throw TypeError("Expected a function");function v(t){var n=s,r=d;return s=d=void 0,p=t,u=e.apply(r,n)}function b(e){var n=e-m,r=e-p;return void 0===m||n>=t||n<0||h&&r>=c}function y(){var e,n,r,a=l();if(b(a))return w(a);f=setTimeout(y,(e=a-m,n=a-p,r=t-e,h?i(r,c-n):r))}function w(e){return(f=void 0,x&&s)?v(e):(s=d=void 0,u)}function j(){var e,n=l(),r=b(n);if(s=arguments,d=this,m=n,r){if(void 0===f)return p=e=m,f=setTimeout(y,t),g?v(e):u;if(h)return clearTimeout(f),f=setTimeout(y,t),v(m)}return void 0===f&&(f=setTimeout(y,t)),u}return t=a(t)||0,r(n)&&(g=!!n.leading,c=(h="maxWait"in n)?o(a(n.maxWait)||0,t):c,x="trailing"in n?!!n.trailing:x),j.cancel=function(){void 0!==f&&clearTimeout(f),p=0,s=m=d=f=void 0},j.flush=function(){return void 0===f?u:w(l())},j}},436289,503269,214520,814379,992704,684653,877891,401141,952744,605083,101852,249578,571616,e=>{"use strict";var t=e.i(271645);function n(e,t){return null!==e&&null!==t&&"object"==typeof e&&"object"==typeof t&&"id"in e&&"id"in t?e.id===t.id:e===t}function r(e=n){return(0,t.useCallback)((t,n)=>"string"==typeof e?(null==t?void 0:t[e])===(null==n?void 0:n[e]):e(t,n),[e])}e.s(["useByComparator",()=>r],436289);var l=e.i(914189);function a(e,n,r){let[a,o]=(0,t.useState)(r),i=void 0!==e,s=(0,t.useRef)(i),d=(0,t.useRef)(!1),c=(0,t.useRef)(!1);return!i||s.current||d.current?i||!s.current||c.current||(c.current=!0,s.current=i,console.error("A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen.")):(d.current=!0,s.current=i,console.error("A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen.")),[i?e:a,(0,l.useEvent)(e=>(i||o(e),null==n?void 0:n(e)))]}function o(e){let[n]=(0,t.useState)(e);return n}e.s(["useControllable",()=>a],503269),e.s(["useDefaultValue",()=>o],214520);var i=e.i(835696);function s(e,n){let r=(0,t.useRef)({left:0,top:0});if((0,i.useIsoMorphicEffect)(()=>{if(!n)return;let e=n.getBoundingClientRect();e&&(r.current=e)},[e,n]),null==n||!e||n===document.activeElement)return!1;let l=n.getBoundingClientRect();return l.top!==r.current.top||l.left!==r.current.left}function d(e,n=!1){let[r,l]=(0,t.useReducer)(()=>({}),{}),a=(0,t.useMemo)(()=>(function(e){if(null===e)return{width:0,height:0};let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}})(e),[e,r]);return(0,i.useIsoMorphicEffect)(()=>{if(!e)return;let t=new ResizeObserver(l);return t.observe(e),()=>{t.disconnect()}},[e]),n?{width:`${a.width}px`,height:`${a.height}px`}:a}e.s(["useDidElementMove",()=>s],814379),e.s(["useElementSize",()=>d],992704);var c=e.i(544508),u=e.i(402155);class f extends Map{constructor(e){super(),this.factory=e}get(e){let t=super.get(e);return void 0===t&&(t=this.factory(e),this.set(e,t)),t}}function m(e,t){let n=e(),r=new Set;return{getSnapshot:()=>n,subscribe:e=>(r.add(e),()=>r.delete(e)),dispatch(e,...l){let a=t[e].call(n,...l);a&&(n=a,r.forEach(e=>e()))}}}function p(e){return(0,t.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot)}let g=new f(()=>m(()=>[],{ADD(e){return this.includes(e)?this:[...this,e]},REMOVE(e){let t=this.indexOf(e);if(-1===t)return this;let n=this.slice();return n.splice(t,1),n}}));function h(e,n){let r=g.get(n),l=(0,t.useId)(),a=p(r);if((0,i.useIsoMorphicEffect)(()=>{if(e)return r.dispatch("ADD",l),()=>r.dispatch("REMOVE",l)},[r,e]),!e)return!1;let o=a.indexOf(l),s=a.length;return -1===o&&(o=s,s+=1),o===s-1}let x=new Map,v=new Map;function b(e){var t;let n=null!=(t=v.get(e))?t:0;return v.set(e,n+1),0!==n||(x.set(e,{"aria-hidden":e.getAttribute("aria-hidden"),inert:e.inert}),e.setAttribute("aria-hidden","true"),e.inert=!0),()=>(function(e){var t;let n=null!=(t=v.get(e))?t:1;if(1===n?v.delete(e):v.set(e,n-1),1!==n)return;let r=x.get(e);r&&(null===r["aria-hidden"]?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",r["aria-hidden"]),e.inert=r.inert,x.delete(e))})(e)}function y(e,{allowed:t,disallowed:n}={}){let r=h(e,"inert-others");(0,i.useIsoMorphicEffect)(()=>{var e,l;if(!r)return;let a=(0,c.disposables)();for(let t of null!=(e=null==n?void 0:n())?e:[])t&&a.add(b(t));let o=null!=(l=null==t?void 0:t())?l:[];for(let e of o){if(!e)continue;let t=(0,u.getOwnerDocument)(e);if(!t)continue;let n=e.parentElement;for(;n&&n!==t.body;){for(let e of n.children)o.some(t=>e.contains(t))||a.add(b(e));n=n.parentElement}}return a.dispose},[r,t,n])}e.s(["useInertOthers",()=>y],684653);var w=e.i(941444);function j(e,n,r){let l=(0,w.useLatestValue)(e=>{let t=e.getBoundingClientRect();0===t.x&&0===t.y&&0===t.width&&0===t.height&&r()});(0,t.useEffect)(()=>{if(!e)return;let t=null===n?null:n instanceof HTMLElement?n:n.current;if(!t)return;let r=(0,c.disposables)();if("u">typeof ResizeObserver){let e=new ResizeObserver(()=>l.current(t));e.observe(t),r.add(()=>e.disconnect())}if("u">typeof IntersectionObserver){let e=new IntersectionObserver(()=>l.current(t));e.observe(t),r.add(()=>e.disconnect())}return()=>r.dispose()},[n,l,e])}e.s(["useOnDisappear",()=>j],877891);var k=e.i(652265);function C(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function S(e,n,r,l){let a=(0,w.useLatestValue)(r);(0,t.useEffect)(()=>{if(e)return document.addEventListener(n,t,l),()=>document.removeEventListener(n,t,l);function t(e){a.current(e)}},[e,n,l])}function N(e,n,r,l){let a=(0,w.useLatestValue)(r);(0,t.useEffect)(()=>{if(e)return window.addEventListener(n,t,l),()=>window.removeEventListener(n,t,l);function t(e){a.current(e)}},[e,n,l])}function E(e,n,r){let l=h(e,"outside-click"),a=(0,w.useLatestValue)(r),o=(0,t.useCallback)(function(e,t){if(e.defaultPrevented)return;let r=t(e);if(null!==r&&r.getRootNode().contains(r)&&r.isConnected){for(let t of function e(t){return"function"==typeof t?e(t()):Array.isArray(t)||t instanceof Set?t:[t]}(n))if(null!==t&&(t.contains(r)||e.composed&&e.composedPath().includes(t)))return;return(0,k.isFocusableElement)(r,k.FocusableMode.Loose)||-1===r.tabIndex||e.preventDefault(),a.current(e,r)}},[a,n]),i=(0,t.useRef)(null);S(l,"pointerdown",e=>{var t,n;i.current=(null==(n=null==(t=e.composedPath)?void 0:t.call(e))?void 0:n[0])||e.target},!0),S(l,"mousedown",e=>{var t,n;i.current=(null==(n=null==(t=e.composedPath)?void 0:t.call(e))?void 0:n[0])||e.target},!0),S(l,"click",e=>{C()||/Android/gi.test(window.navigator.userAgent)||i.current&&(o(e,()=>i.current),i.current=null)},!0);let s=(0,t.useRef)({x:0,y:0});S(l,"touchstart",e=>{s.current.x=e.touches[0].clientX,s.current.y=e.touches[0].clientY},!0),S(l,"touchend",e=>{let t={x:e.changedTouches[0].clientX,y:e.changedTouches[0].clientY};if(!(Math.abs(t.x-s.current.x)>=30||Math.abs(t.y-s.current.y)>=30))return o(e,()=>e.target instanceof HTMLElement?e.target:null)},!0),N(l,"blur",e=>o(e,()=>window.document.activeElement instanceof HTMLIFrameElement?window.document.activeElement:null),!0)}function _(...e){return(0,t.useMemo)(()=>(0,u.getOwnerDocument)(...e),[...e])}e.s(["useWindowEvent",()=>N],401141),e.s(["useOutsideClick",()=>E],952744),e.s(["useOwnerDocument",()=>_],605083);let O=m(()=>new Map,{PUSH(e,t){var n;let r=null!=(n=this.get(e))?n:{doc:e,count:0,d:(0,c.disposables)(),meta:new Set};return r.count++,r.meta.add(t),this.set(e,r),this},POP(e,t){let n=this.get(e);return n&&(n.count--,n.meta.delete(t)),this},SCROLL_PREVENT({doc:e,d:t,meta:n}){let r,l={doc:e,d:t,meta:function(e){let t={};for(let n of e)Object.assign(t,n(t));return t}(n)},a=[C()?{before({doc:e,d:t,meta:n}){function r(e){return n.containers.flatMap(e=>e()).some(t=>t.contains(e))}t.microTask(()=>{var n;if("auto"!==window.getComputedStyle(e.documentElement).scrollBehavior){let n=(0,c.disposables)();n.style(e.documentElement,"scrollBehavior","auto"),t.add(()=>t.microTask(()=>n.dispose()))}let l=null!=(n=window.scrollY)?n:window.pageYOffset,a=null;t.addEventListener(e,"click",t=>{if(t.target instanceof HTMLElement)try{let n=t.target.closest("a");if(!n)return;let{hash:l}=new URL(n.href),o=e.querySelector(l);o&&!r(o)&&(a=o)}catch{}},!0),t.addEventListener(e,"touchstart",e=>{if(e.target instanceof HTMLElement)if(r(e.target)){let n=e.target;for(;n.parentElement&&r(n.parentElement);)n=n.parentElement;t.style(n,"overscrollBehavior","contain")}else t.style(e.target,"touchAction","none")}),t.addEventListener(e,"touchmove",e=>{if(e.target instanceof HTMLElement&&"INPUT"!==e.target.tagName)if(r(e.target)){let t=e.target;for(;t.parentElement&&""!==t.dataset.headlessuiPortal&&!(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth);)t=t.parentElement;""===t.dataset.headlessuiPortal&&e.preventDefault()}else e.preventDefault()},{passive:!1}),t.add(()=>{var e;l!==(null!=(e=window.scrollY)?e:window.pageYOffset)&&window.scrollTo(0,l),a&&a.isConnected&&(a.scrollIntoView({block:"nearest"}),a=null)})})}}:{},{before({doc:e}){var t;let n=e.documentElement;r=Math.max(0,(null!=(t=e.defaultView)?t:window).innerWidth-n.clientWidth)},after({doc:e,d:t}){let n=e.documentElement,l=Math.max(0,n.clientWidth-n.offsetWidth),a=Math.max(0,r-l);t.style(n,"paddingRight",`${a}px`)}},{before({doc:e,d:t}){t.style(e.documentElement,"overflow","hidden")}}];a.forEach(({before:e})=>null==e?void 0:e(l)),a.forEach(({after:e})=>null==e?void 0:e(l))},SCROLL_ALLOW({d:e}){e.dispose()},TEARDOWN({doc:e}){this.delete(e)}});function $(e,t,n=()=>[document.body]){!function(e,t,n=()=>({containers:[]})){let r=p(O),l=t?r.get(t):void 0;l&&l.count,(0,i.useIsoMorphicEffect)(()=>{if(!(!t||!e))return O.dispatch("PUSH",t,n),()=>O.dispatch("POP",t,n)},[e,t])}(h(e,"scroll-lock"),t,e=>{var t;return{containers:[...null!=(t=e.containers)?t:[],n]}})}O.subscribe(()=>{let e=O.getSnapshot(),t=new Map;for(let[n]of e)t.set(n,n.documentElement.style.overflow);for(let n of e.values()){let e="hidden"===t.get(n.doc),r=0!==n.count;(r&&!e||!r&&e)&&O.dispatch(n.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",n),0===n.count&&O.dispatch("TEARDOWN",n)}}),e.s(["useScrollLock",()=>$],101852);let T=/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g;function I(e){var t,n;let r=null!=(t=e.innerText)?t:"",l=e.cloneNode(!0);if(!(l instanceof HTMLElement))return r;let a=!1;for(let e of l.querySelectorAll('[hidden],[aria-hidden],[role="img"]'))e.remove(),a=!0;let o=a?null!=(n=l.innerText)?n:"":r;return T.test(o)&&(o=o.replace(T,"")),o}function P(e){let n=(0,t.useRef)(""),r=(0,t.useRef)("");return(0,l.useEvent)(()=>{let t=e.current;if(!t)return"";let l=t.innerText;if(n.current===l)return r.current;let a=(function(e){let t=e.getAttribute("aria-label");if("string"==typeof t)return t.trim();let n=e.getAttribute("aria-labelledby");if(n){let e=n.split(" ").map(e=>{let t=document.getElementById(e);if(t){let e=t.getAttribute("aria-label");return"string"==typeof e?e.trim():I(t).trim()}return null}).filter(Boolean);if(e.length>0)return e.join(", ")}return I(e).trim()})(t).trim().toLowerCase();return n.current=l,r.current=a,a})}function M(e){return[e.screenX,e.screenY]}function R(){let e=(0,t.useRef)([-1,-1]);return{wasMoved(t){let n=M(t);return(e.current[0]!==n[0]||e.current[1]!==n[1])&&(e.current=n,!0)},update(t){e.current=M(t)}}}e.s(["useTextValue",()=>P],249578),e.s(["useTrackedPointer",()=>R],571616)},83733,e=>{"use strict";let t;var n,r,l=e.i(247167),a=e.i(271645),o=e.i(544508),i=e.i(746725),s=e.i(835696);void 0!==l.default&&"u">typeof globalThis&&"u">typeof Element&&(null==(n=null==l.default?void 0:l.default.env)?void 0:n.NODE_ENV)==="test"&&void 0===(null==(r=null==Element?void 0:Element.prototype)?void 0:r.getAnimations)&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` `)),[]});var d=((t=d||{})[t.None=0]="None",t[t.Closed=1]="Closed",t[t.Enter=2]="Enter",t[t.Leave=4]="Leave",t);function c(e){let t={};for(let n in e)!0===e[n]&&(t[`data-${n}`]="");return t}function u(e,t,n,r){let[l,d]=(0,a.useState)(n),{hasFlag:c,addFlag:u,removeFlag:f}=function(e=0){let[t,n]=(0,a.useState)(e),r=(0,a.useCallback)(e=>n(e),[t]),l=(0,a.useCallback)(e=>n(t=>t|e),[t]),o=(0,a.useCallback)(e=>(t&e)===e,[t]);return{flags:t,setFlag:r,addFlag:l,hasFlag:o,removeFlag:(0,a.useCallback)(e=>n(t=>t&~e),[n]),toggleFlag:(0,a.useCallback)(e=>n(t=>t^e),[n])}}(e&&l?3:0),m=(0,a.useRef)(!1),p=(0,a.useRef)(!1),g=(0,i.useDisposables)();return(0,s.useIsoMorphicEffect)(()=>{var l;if(e){if(n&&d(!0),!t){n&&u(3);return}return null==(l=null==r?void 0:r.start)||l.call(r,n),function(e,{prepare:t,run:n,done:r,inFlight:l}){let a=(0,o.disposables)();return function(e,{inFlight:t,prepare:n}){if(null!=t&&t.current)return n();let r=e.style.transition;e.style.transition="none",n(),e.offsetHeight,e.style.transition=r}(e,{prepare:t,inFlight:l}),a.nextFrame(()=>{n(),a.requestAnimationFrame(()=>{a.add(function(e,t){var n,r;let l=(0,o.disposables)();if(!e)return l.dispose;let a=!1;l.add(()=>{a=!0});let i=null!=(r=null==(n=e.getAnimations)?void 0:n.call(e).filter(e=>e instanceof CSSTransition))?r:[];return 0===i.length?t():Promise.allSettled(i.map(e=>e.finished)).then(()=>{a||t()}),l.dispose}(e,r))})}),a.dispose}(t,{inFlight:m,prepare(){p.current?p.current=!1:p.current=m.current,m.current=!0,p.current||(n?(u(3),f(4)):(u(4),f(2)))},run(){p.current?n?(f(3),u(4)):(f(4),u(3)):n?f(1):u(1)},done(){var e;p.current&&"function"==typeof t.getAnimations&&t.getAnimations().length>0||(m.current=!1,f(7),n||d(!1),null==(e=null==r?void 0:r.end)||e.call(r,n))}})}},[e,n,t,g]),e?[l,{closed:c(1),enter:c(2),leave:c(4),transition:c(2)||c(4)}]:[n,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}e.s(["transitionDataAttributes",()=>c,"useTransition",()=>u],83733)},601893,919751,694421,140721,904016,942803,e=>{"use strict";var t=e.i(271645);let n=(0,t.createContext)(void 0);function r(){return(0,t.useContext)(n)}e.s(["useDisabled",()=>r],601893);var l=e.i(953760),a=e.i(174080),o="u">typeof document?t.useLayoutEffect:function(){};function i(e,t){let n,r,l;if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if((n=e.length)!==t.length)return!1;for(r=n;0!=r--;)if(!i(e[r],t[r]))return!1;return!0}if((n=(l=Object.keys(e)).length)!==Object.keys(t).length)return!1;for(r=n;0!=r--;)if(!({}).hasOwnProperty.call(t,l[r]))return!1;for(r=n;0!=r--;){let n=l[r];if(("_owner"!==n||!e.$$typeof)&&!i(e[n],t[n]))return!1}return!0}return e!=e&&t!=t}function s(e){return"u"{n.current=e}),n}let u=(e,t)=>({...(0,l.offset)(e),options:[e,t]});e.i(247167);var f=e.i(229315),m=e.i(343084);e.i(397126);let p={...t},g=p.useInsertionEffect||(e=>e());function h(e){let n=t.useRef(()=>{});return g(()=>{n.current=e}),t.useCallback(function(){for(var e=arguments.length,t=Array(e),r=0;rtypeof document?t.useLayoutEffect:t.useEffect;let v=!1,b=0,y=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+b++,w=p.useId||function(){let[e,n]=t.useState(()=>v?y():void 0);return x(()=>{null==e&&n(y())},[]),t.useEffect(()=>{v=!0},[]),e},j=t.createContext(null),k=t.createContext(null),C="active",S="selected";function N(e,t,n){let r=new Map,l="item"===n,a=e;if(l&&e){let{[C]:t,[S]:n,...r}=e;a=r}return{..."floating"===n&&{tabIndex:-1,"data-floating-ui-focusable":""},...a,...t.map(t=>{let r=t?t[n]:null;return"function"==typeof r?e?r(e):null:r}).concat(e).reduce((e,t)=>(t&&Object.entries(t).forEach(t=>{let[n,a]=t;if(!(l&&[C,S].includes(n)))if(0===n.indexOf("on")){if(r.has(n)||r.set(n,[]),"function"==typeof a){var o;null==(o=r.get(n))||o.push(a),e[n]=function(){for(var e,t=arguments.length,l=Array(t),a=0;ae(...l)).find(e=>void 0!==e)}}}else e[n]=a}),e),{})}}function E(e,t){return{...e,rects:{...e.rects,floating:{...e.rects.floating,height:t}}}}var _=e.i(746725),O=e.i(914189),$=e.i(835696);let T=(0,t.createContext)({styles:void 0,setReference:()=>{},setFloating:()=>{},getReferenceProps:()=>({}),getFloatingProps:()=>({}),slot:{}});T.displayName="FloatingContext";let I=(0,t.createContext)(null);function P(e){return(0,t.useMemo)(()=>e?"string"==typeof e?{to:e}:e:null,[e])}function M(){return(0,t.useContext)(T).setReference}function R(){return(0,t.useContext)(T).getReferenceProps}function L(){let{getFloatingProps:e,slot:n}=(0,t.useContext)(T);return(0,t.useCallback)((...t)=>Object.assign({},e(...t),{"data-anchor":n.anchor}),[e,n])}function D(e=null){!1===e&&(e=null),"string"==typeof e&&(e={to:e});let n=(0,t.useContext)(I),r=(0,t.useMemo)(()=>e,[JSON.stringify(e,(e,t)=>{var n;return null!=(n=null==t?void 0:t.outerHTML)?n:t})]);(0,$.useIsoMorphicEffect)(()=>{null==n||n(null!=r?r:null)},[n,r]);let l=(0,t.useContext)(T);return(0,t.useMemo)(()=>[l.setFloating,e?l.styles:{}],[l.setFloating,e,l.styles])}function A({children:e,enabled:n=!0}){var r,p,g,v,b,y,C;let S,_,P,M,R,L,D,A,B,F,z,H,V,W,U,q,[G,X]=(0,t.useState)(null),[Q,Y]=(0,t.useState)(0),J=(0,t.useRef)(null),[Z,ee]=(0,t.useState)(null);p=Z,(0,$.useIsoMorphicEffect)(()=>{if(!p)return;let e=new MutationObserver(()=>{let e=window.getComputedStyle(p).maxHeight,t=parseFloat(e);if(isNaN(t))return;let n=parseInt(e);isNaN(n)||t!==n&&(p.style.maxHeight=`${Math.ceil(t)}px`)});return e.observe(p,{attributes:!0,attributeFilter:["style"]}),()=>{e.disconnect()}},[p]);let et=n&&null!==G&&null!==Z,{to:en="bottom",gap:er=0,offset:el=0,padding:ea=0,inner:eo}=(g=G,v=Z,S=K(null!=(b=null==g?void 0:g.gap)?b:"var(--anchor-gap, 0)",v),_=K(null!=(y=null==g?void 0:g.offset)?y:"var(--anchor-offset, 0)",v),P=K(null!=(C=null==g?void 0:g.padding)?C:"var(--anchor-padding, 0)",v),{...g,gap:S,offset:_,padding:P}),[ei,es="center"]=en.split(" ");(0,$.useIsoMorphicEffect)(()=>{et&&Y(0)},[et]);let{refs:ed,floatingStyles:ec,context:eu}=function(e){void 0===e&&(e={});let{nodeId:n}=e,r=function(e){var n;let{open:r=!1,onOpenChange:l,elements:a}=e,o=w(),i=t.useRef({}),[s]=t.useState(()=>{let e;return e=new Map,{emit(t,n){var r;null==(r=e.get(t))||r.forEach(e=>e(n))},on(t,n){e.set(t,[...e.get(t)||[],n])},off(t,n){var r;e.set(t,(null==(r=e.get(t))?void 0:r.filter(e=>e!==n))||[])}}}),d=null!=((null==(n=t.useContext(j))?void 0:n.id)||null),[c,u]=t.useState(a.reference),f=h((e,t,n)=>{i.current.openEvent=e?t:void 0,s.emit("openchange",{open:e,event:t,reason:n,nested:d}),null==l||l(e,t,n)}),m=t.useMemo(()=>({setPositionReference:u}),[]),p=t.useMemo(()=>({reference:c||a.reference||null,floating:a.floating||null,domReference:a.reference}),[c,a.reference,a.floating]);return t.useMemo(()=>({dataRef:i,open:r,onOpenChange:f,elements:p,events:s,floatingId:o,refs:m}),[r,f,p,s,o,m])}({...e,elements:{reference:null,floating:null,...e.elements}}),u=e.rootContext||r,m=u.elements,[p,g]=t.useState(null),[v,b]=t.useState(null),y=(null==m?void 0:m.domReference)||p,C=t.useRef(null),S=t.useContext(k);x(()=>{y&&(C.current=y)},[y]);let N=function(e){void 0===e&&(e={});let{placement:n="bottom",strategy:r="absolute",middleware:u=[],platform:f,elements:{reference:m,floating:p}={},transform:g=!0,whileElementsMounted:h,open:x}=e,[v,b]=t.useState({x:0,y:0,strategy:r,placement:n,middlewareData:{},isPositioned:!1}),[y,w]=t.useState(u);i(y,u)||w(u);let[j,k]=t.useState(null),[C,S]=t.useState(null),N=t.useCallback(e=>{e!==$.current&&($.current=e,k(e))},[]),E=t.useCallback(e=>{e!==T.current&&(T.current=e,S(e))},[]),_=m||j,O=p||C,$=t.useRef(null),T=t.useRef(null),I=t.useRef(v),P=null!=h,M=c(h),R=c(f),L=c(x),D=t.useCallback(()=>{if(!$.current||!T.current)return;let e={placement:n,strategy:r,middleware:y};R.current&&(e.platform=R.current),(0,l.computePosition)($.current,T.current,e).then(e=>{let t={...e,isPositioned:!1!==L.current};A.current&&!i(I.current,t)&&(I.current=t,a.flushSync(()=>{b(t)}))})},[y,n,r,R,L]);o(()=>{!1===x&&I.current.isPositioned&&(I.current.isPositioned=!1,b(e=>({...e,isPositioned:!1})))},[x]);let A=t.useRef(!1);o(()=>(A.current=!0,()=>{A.current=!1}),[]),o(()=>{if(_&&($.current=_),O&&(T.current=O),_&&O){if(M.current)return M.current(_,O,D);D()}},[_,O,D,M,P]);let K=t.useMemo(()=>({reference:$,floating:T,setReference:N,setFloating:E}),[N,E]),B=t.useMemo(()=>({reference:_,floating:O}),[_,O]),F=t.useMemo(()=>{let e={position:r,left:0,top:0};if(!B.floating)return e;let t=d(B.floating,v.x),n=d(B.floating,v.y);return g?{...e,transform:"translate("+t+"px, "+n+"px)",...s(B.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:n}},[r,g,B.floating,v.x,v.y]);return t.useMemo(()=>({...v,update:D,refs:K,elements:B,floatingStyles:F}),[v,D,K,B,F])}({...e,elements:{...m,...v&&{reference:v}}}),E=t.useCallback(e=>{let t=(0,f.isElement)(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),contextElement:e}:e;b(t),N.refs.setReference(t)},[N.refs]),_=t.useCallback(e=>{((0,f.isElement)(e)||null===e)&&(C.current=e,g(e)),((0,f.isElement)(N.refs.reference.current)||null===N.refs.reference.current||null!==e&&!(0,f.isElement)(e))&&N.refs.setReference(e)},[N.refs]),O=t.useMemo(()=>({...N.refs,setReference:_,setPositionReference:E,domReference:C}),[N.refs,_,E]),$=t.useMemo(()=>({...N.elements,domReference:y}),[N.elements,y]),T=t.useMemo(()=>({...N,...u,refs:O,elements:$,nodeId:n}),[N,O,$,n,u]);return x(()=>{u.dataRef.current.floatingContext=T;let e=null==S?void 0:S.nodesRef.current.find(e=>e.id===n);e&&(e.context=T)}),t.useMemo(()=>({...N,context:T,refs:O,elements:$}),[N,O,$,T])}({open:et,placement:"selection"===ei?"center"===es?"bottom":`bottom-${es}`:"center"===es?`${ei}`:`${ei}-${es}`,strategy:"absolute",transform:!1,middleware:[u({mainAxis:"selection"===ei?0:er,crossAxis:el}),(M={padding:ea},{...(0,l.shift)(M),options:[M,R]}),"selection"!==ei&&(L={padding:ea},{...(0,l.flip)(L),options:[L,D]}),"selection"===ei&&eo?{name:"inner",options:A={...eo,padding:ea,overflowRef:J,offset:Q,minItemsVisible:4,referenceOverflowThreshold:ea,onFallbackChange(e){var t,n;if(!e)return;let r=eu.elements.floating;if(!r)return;let l=parseFloat(getComputedStyle(r).scrollPaddingBottom)||0,a=Math.min(4,r.childElementCount),o=0,i=0;for(let e of null!=(n=null==(t=eu.elements.floating)?void 0:t.childNodes)?n:[])if(e instanceof HTMLElement){let t=e.offsetTop,n=t+e.clientHeight+l,s=r.scrollTop,d=s+r.clientHeight;if(t>=s&&n<=d)a--;else{i=Math.max(0,Math.min(n,d)-Math.max(t,s)),o=e.clientHeight;break}}a>=1&&Y(e=>{let t=o*a-i+l;return e>=t?e:t})}},async fn(e){let{listRef:t,overflowRef:n,onFallbackChange:r,offset:o=0,index:i=0,minItemsVisible:s=4,referenceOverflowThreshold:d=0,scrollRef:c,...f}=(0,m.evaluate)(A,e),{rects:p,elements:{floating:g}}=e,h=t.current[i],x=(null==c?void 0:c.current)||g,v=g.clientTop||x.clientTop,b=0!==g.clientTop,y=0!==x.clientTop,w=g===x;if(!h)return{};let j={...e,...await u(-h.offsetTop-g.clientTop-p.reference.height/2-h.offsetHeight/2-o).fn(e)},k=await (0,l.detectOverflow)(E(j,x.scrollHeight+v+g.clientTop),f),C=await (0,l.detectOverflow)(j,{...f,elementContext:"reference"}),S=(0,m.max)(0,k.top),N=j.y+S,_=(x.scrollHeight>x.clientHeight?e=>e:m.round)((0,m.max)(0,x.scrollHeight+(b&&w||y?2*v:0)-S-(0,m.max)(0,k.bottom)));if(x.style.maxHeight=_+"px",x.scrollTop=S,r){let e=x.offsetHeight=-d||C.bottom>=-d;a.flushSync(()=>r(e))}return n&&(n.current=await (0,l.detectOverflow)(E({...j,y:N},x.offsetHeight+v+g.clientTop),f)),{y:N}}}:null,(B={padding:ea,apply({availableWidth:e,availableHeight:t,elements:n}){Object.assign(n.floating.style,{overflow:"auto",maxWidth:`${e}px`,maxHeight:`min(var(--anchor-max-height, 100vh), ${t}px)`})}},{...(0,l.size)(B),options:[B,F]})].filter(Boolean),whileElementsMounted:l.autoUpdate}),[ef=ei,em=es]=eu.placement.split("-");"selection"===ei&&(ef="selection");let ep=(0,t.useMemo)(()=>({anchor:[ef,em].filter(Boolean).join(" ")}),[ef,em]),{getReferenceProps:eg,getFloatingProps:eh}=(z=(r=[function(e,n){let{open:r,elements:l}=e,{enabled:o=!0,overflowRef:i,scrollRef:s,onChange:d}=n,c=h(d),u=t.useRef(!1),f=t.useRef(null),m=t.useRef(null);t.useEffect(()=>{if(!o)return;function e(e){if(e.ctrlKey||!t||null==i.current)return;let n=e.deltaY,r=i.current.top>=-.5,l=i.current.bottom>=-.5,o=t.scrollHeight-t.clientHeight,s=n<0?-1:1,d=n<0?"max":"min";if(!(t.scrollHeight<=t.clientHeight))if(!r&&n>0||!l&&n<0)e.preventDefault(),a.flushSync(()=>{c(e=>e+Math[d](n,o*s))});else{let e;/firefox/i.test((e=navigator.userAgentData)&&Array.isArray(e.brands)?e.brands.map(e=>{let{brand:t,version:n}=e;return t+"/"+n}).join(" "):navigator.userAgent)&&(t.scrollTop+=n)}}let t=(null==s?void 0:s.current)||l.floating;if(r&&t)return t.addEventListener("wheel",e),requestAnimationFrame(()=>{f.current=t.scrollTop,null!=i.current&&(m.current={...i.current})}),()=>{f.current=null,m.current=null,t.removeEventListener("wheel",e)}},[o,r,l.floating,i,s,c]);let p=t.useMemo(()=>({onKeyDown(){u.current=!0},onWheel(){u.current=!1},onPointerMove(){u.current=!1},onScroll(){let e=(null==s?void 0:s.current)||l.floating;if(i.current&&e&&u.current){if(null!==f.current){let t=e.scrollTop-f.current;(i.current.bottom<-.5&&t<-1||i.current.top<-.5&&t>1)&&a.flushSync(()=>c(e=>e+t))}requestAnimationFrame(()=>{f.current=e.scrollTop})}}}),[l.floating,c,i,s]);return t.useMemo(()=>o?{floating:p}:{},[o,p])}(eu,{overflowRef:J,onChange:Y})]).map(e=>null==e?void 0:e.reference),H=r.map(e=>null==e?void 0:e.floating),V=r.map(e=>null==e?void 0:e.item),W=t.useCallback(e=>N(e,r,"reference"),z),U=t.useCallback(e=>N(e,r,"floating"),H),q=t.useCallback(e=>N(e,r,"item"),V),t.useMemo(()=>({getReferenceProps:W,getFloatingProps:U,getItemProps:q}),[W,U,q])),ex=(0,O.useEvent)(e=>{ee(e),ed.setFloating(e)});return t.createElement(I.Provider,{value:X},t.createElement(T.Provider,{value:{setFloating:ex,setReference:ed.setReference,styles:ec,getReferenceProps:eg,getFloatingProps:eh,slot:ep}},e))}function K(e,n,r){let l=(0,_.useDisposables)(),a=(0,O.useEvent)((e,t)=>{if(null==e)return[r,null];if("number"==typeof e)return[e,null];if("string"==typeof e){if(!t)return[r,null];let n=B(e,t);return[n,r=>{let a=function e(t){let n=/var\((.*)\)/.exec(t);if(n){let t=n[1].indexOf(",");if(-1===t)return[n[1]];let r=n[1].slice(0,t).trim(),l=n[1].slice(t+1).trim();return l?[r,...e(l)]:[r]}return[]}(e);{let o=a.map(e=>window.getComputedStyle(t).getPropertyValue(e));l.requestAnimationFrame(function i(){l.nextFrame(i);let s=!1;for(let[e,n]of a.entries()){let r=window.getComputedStyle(t).getPropertyValue(n);if(o[e]!==r){o[e]=r,s=!0;break}}if(!s)return;let d=B(e,t);n!==d&&(r(d),n=d)})}return l.dispose}]}return[r,null]}),o=(0,t.useMemo)(()=>a(e,n)[0],[e,n]),[i=o,s]=(0,t.useState)();return(0,$.useIsoMorphicEffect)(()=>{let[t,r]=a(e,n);if(s(t),r)return r(s)},[e,n]),i}function B(e,t){let n=document.createElement("div");t.appendChild(n),n.style.setProperty("margin-top","0px","important"),n.style.setProperty("margin-top",e,"important");let r=parseFloat(window.getComputedStyle(n).marginTop)||0;return t.removeChild(n),r}function F(e={},t=null,n=[]){for(let[r,l]of Object.entries(e))!function e(t,n,r){if(Array.isArray(r))for(let[l,a]of r.entries())e(t,z(n,l.toString()),a);else r instanceof Date?t.push([n,r.toISOString()]):"boolean"==typeof r?t.push([n,r?"1":"0"]):"string"==typeof r?t.push([n,r]):"number"==typeof r?t.push([n,`${r}`]):null==r?t.push([n,""]):F(r,n,t)}(n,z(t,r),l);return n}function z(e,t){return e?e+"["+t+"]":t}function H(e){var t,n;let r=null!=(t=null==e?void 0:e.form)?t:e.closest("form");if(r){for(let t of r.elements)if(t!==e&&("INPUT"===t.tagName&&"submit"===t.type||"BUTTON"===t.tagName&&"submit"===t.type||"INPUT"===t.nodeName&&"image"===t.type))return void t.click();null==(n=r.requestSubmit)||n.call(r)}}I.displayName="PlacementContext",e.s(["FloatingProvider",()=>A,"useFloatingPanel",()=>D,"useFloatingPanelProps",()=>L,"useFloatingReference",()=>M,"useFloatingReferenceProps",()=>R,"useResolvedAnchor",()=>P],919751),e.s(["attemptSubmit",()=>H,"objectToFormEntries",()=>F],694421);var V=e.i(700020),W=e.i(2788);let U=(0,t.createContext)(null);function q({children:e}){let n=(0,t.useContext)(U);if(!n)return t.default.createElement(t.default.Fragment,null,e);let{target:r}=n;return r?(0,a.createPortal)(t.default.createElement(t.default.Fragment,null,e),r):null}function G({data:e,form:n,disabled:r,onReset:l,overrides:a}){let[o,i]=(0,t.useState)(null),s=(0,_.useDisposables)();return(0,t.useEffect)(()=>{if(l&&o)return s.addEventListener(o,"reset",l)},[o,n,l]),t.default.createElement(q,null,t.default.createElement(X,{setForm:i,formId:n}),F(e).map(([e,l])=>t.default.createElement(W.Hidden,{features:W.HiddenFeatures.Hidden,...(0,V.compact)({key:e,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:n,disabled:r,name:e,value:l,...a})})))}function X({setForm:e,formId:n}){return(0,t.useEffect)(()=>{if(n){let t=document.getElementById(n);t&&e(t)}},[e,n]),n?null:t.default.createElement(W.Hidden,{features:W.HiddenFeatures.Hidden,as:"input",type:"hidden",hidden:!0,readOnly:!0,ref:t=>{if(!t)return;let n=t.closest("form");n&&e(n)}})}function Q(e,n){let[r,l]=(0,t.useState)(n);return e||r===n||l(n),e?r:n}e.s(["FormFields",()=>G],140721),e.s(["useFrozenData",()=>Q],904016);let Y=(0,t.createContext)(void 0);function J(){return(0,t.useContext)(Y)}e.s(["useProvidedId",()=>J],942803)},233137,233538,e=>{"use strict";let t;var n=e.i(271645);let r=(0,n.createContext)(null);r.displayName="OpenClosedContext";var l=((t=l||{})[t.Open=1]="Open",t[t.Closed=2]="Closed",t[t.Closing=4]="Closing",t[t.Opening=8]="Opening",t);function a(){return(0,n.useContext)(r)}function o({value:e,children:t}){return n.default.createElement(r.Provider,{value:e},t)}function i({children:e}){return n.default.createElement(r.Provider,{value:null},e)}function s(e){let t=e.parentElement,n=null;for(;t&&!(t instanceof HTMLFieldSetElement);)t instanceof HTMLLegendElement&&(n=t),t=t.parentElement;let r=(null==t?void 0:t.getAttribute("disabled"))==="";return!(r&&function(e){if(!e)return!1;let t=e.previousElementSibling;for(;null!==t;){if(t instanceof HTMLLegendElement)return!1;t=t.previousElementSibling}return!0}(n))&&r}e.s(["OpenClosedProvider",()=>o,"ResetOpenClosedProvider",()=>i,"State",()=>l,"useOpenClosed",()=>a],233137),e.s(["isDisabledReactIssue7711",()=>s],233538)},35983,35889,722678,178677,635307,495470,333771,e=>{"use strict";let t,n,r,l,a;var o=e.i(290571),i=e.i(271645),s=e.i(429427),d=e.i(371330),c=e.i(174080),u=e.i(394487),f=e.i(436289),m=e.i(503269),p=e.i(214520),g=e.i(814379),h=e.i(746725),x=e.i(992704),v=e.i(914189),b=e.i(684653),y=e.i(835696),w=e.i(941444),j=e.i(877891),k=e.i(952744),C=e.i(605083),S=e.i(144279),N=e.i(101852),E=e.i(294316),_=e.i(249578),O=e.i(571616),$=e.i(83733),T=e.i(601893),I=e.i(919751),P=e.i(140721),M=e.i(904016),R=e.i(942803),L=e.i(233137),D=e.i(233538),A=((t=A||{})[t.First=0]="First",t[t.Previous=1]="Previous",t[t.Next=2]="Next",t[t.Last=3]="Last",t[t.Specific=4]="Specific",t[t.Nothing=5]="Nothing",t);function K(e,t){let n=t.resolveItems();if(n.length<=0)return null;let r=t.resolveActiveIndex(),l=null!=r?r:-1;switch(e.focus){case 0:for(let e=0;e=0;--e)if(!t.resolveDisabled(n[e],e,n))return e;return r;case 2:for(let e=l+1;e=0;--e)if(!t.resolveDisabled(n[e],e,n))return e;return r;case 4:for(let r=0;r0?e.join(" "):void 0,(0,i.useMemo)(()=>function(e){let n=(0,v.useEvent)(e=>(t(t=>[...t,e]),()=>t(t=>{let n=t.slice(),r=n.indexOf(e);return -1!==r&&n.splice(r,1),n}))),r=(0,i.useMemo)(()=>({register:n,slot:e.slot,name:e.name,props:e.props,value:e.value}),[n,e.slot,e.name,e.props,e.value]);return i.default.createElement(U.Provider,{value:r},e.children)},[t])]}U.displayName="DescriptionContext";let X=Object.assign((0,W.forwardRefWithAs)(function(e,t){let n=(0,i.useId)(),r=(0,T.useDisabled)(),{id:l=`headlessui-description-${n}`,...a}=e,o=function e(){let t=(0,i.useContext)(U);if(null===t){let t=Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(t,e),t}return t}(),s=(0,E.useSyncRefs)(t);(0,y.useIsoMorphicEffect)(()=>o.register(l),[l,o.register]);let d=r||!1,c=(0,i.useMemo)(()=>({...o.slot,disabled:d}),[o.slot,d]),u={ref:s,...o.props,id:l};return(0,W.useRender)()({ourProps:u,theirProps:a,slot:c,defaultTag:"p",name:o.name||"Description"})}),{});e.s(["Description",()=>X,"useDescribedBy",()=>q,"useDescriptions",()=>G],35889);var Q=e.i(998348);let Y=(0,i.createContext)(null);function J(e){var t,n,r;let l=null!=(n=null==(t=(0,i.useContext)(Y))?void 0:t.value)?n:void 0;return(null!=(r=null==e?void 0:e.length)?r:0)>0?[l,...e].filter(Boolean).join(" "):l}function Z({inherit:e=!1}={}){let t=J(),[n,r]=(0,i.useState)([]),l=e?[t,...n].filter(Boolean):n;return[l.length>0?l.join(" "):void 0,(0,i.useMemo)(()=>function(e){let t=(0,v.useEvent)(e=>(r(t=>[...t,e]),()=>r(t=>{let n=t.slice(),r=n.indexOf(e);return -1!==r&&n.splice(r,1),n}))),n=(0,i.useMemo)(()=>({register:t,slot:e.slot,name:e.name,props:e.props,value:e.value}),[t,e.slot,e.name,e.props,e.value]);return i.default.createElement(Y.Provider,{value:n},e.children)},[r])]}Y.displayName="LabelContext";let ee=Object.assign((0,W.forwardRefWithAs)(function(e,t){var n;let r=(0,i.useId)(),l=function e(){let t=(0,i.useContext)(Y);if(null===t){let t=Error("You used a