mirror of
https://github.com/BerriAI/litellm.git
synced 2026-08-28 05:25:59 +00:00
Compare commits
50 commits
efd860ffc1
...
1a476cf8eb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a476cf8eb | ||
|
|
493bca667b | ||
|
|
63cb18db7d | ||
|
|
2d0c9eed4d | ||
|
|
955b26ac08 | ||
|
|
0fba05800d | ||
|
|
490face7de | ||
|
|
938ed2c2a5 | ||
|
|
6a766ae4f7 | ||
|
|
462942de65 | ||
|
|
ca9007be39 | ||
|
|
a7da7928fa | ||
|
|
62341e96ae | ||
|
|
e44e2fe242 | ||
|
|
02dcc4d347 | ||
|
|
a21eed6c77 | ||
|
|
ef4c84dc36 | ||
|
|
982d3a5476 | ||
|
|
86365263aa | ||
|
|
98d231c09b | ||
|
|
86ef1fb08b | ||
|
|
ae95acfb05 | ||
|
|
63d7920f8b | ||
|
|
cd63c7e5a7 | ||
|
|
586e3d8de5 | ||
|
|
192ccaaf02 | ||
|
|
2e2d68e869 | ||
|
|
81dc8dba1c | ||
|
|
8ebcb3e181 | ||
|
|
0ec2d95506 | ||
|
|
2e55fa1411 | ||
|
|
807ee7f232 | ||
|
|
d3c8b5d44d | ||
|
|
166694948f | ||
|
|
a215ecaf3d | ||
|
|
b95801172c | ||
|
|
84dfc18f6b | ||
|
|
cd9dcb55b4 | ||
|
|
e9f3963869 | ||
|
|
898ff74673 | ||
|
|
afe5a240e5 | ||
|
|
cc400502fa | ||
|
|
19a1d5c4c6 | ||
|
|
41192ef085 | ||
|
|
e47e989341 | ||
|
|
ec03baa0a5 | ||
|
|
ed8480a821 | ||
|
|
729a952322 | ||
|
|
d80608eca6 | ||
|
|
dfb7424b4b |
87 changed files with 14263 additions and 1311 deletions
18
.github/workflows/check-ui-api-types.yml
vendored
18
.github/workflows/check-ui-api-types.yml
vendored
|
|
@ -83,6 +83,24 @@ jobs:
|
|||
if: steps.changes.outputs.relevant == 'true'
|
||||
run: uv run --no-sync prisma generate --schema litellm/proxy/schema.prisma
|
||||
|
||||
- name: Regenerate the lazy OpenAPI snapshot
|
||||
if: steps.changes.outputs.relevant == 'true'
|
||||
run: uv run --no-sync python -m litellm.proxy._lazy_openapi_snapshot
|
||||
|
||||
- name: Fail if the lazy OpenAPI snapshot is stale
|
||||
if: steps.changes.outputs.relevant == 'true'
|
||||
run: |
|
||||
if ! git diff --exit-code -- litellm/proxy/_lazy_openapi_snapshot.json; then
|
||||
echo "::error file=litellm/proxy/_lazy_openapi_snapshot.json::The lazy OpenAPI snapshot is out of sync with the lazily loaded routes."
|
||||
echo ""
|
||||
echo "A lazily loaded route or model changed without regenerating the snapshot that /openapi.json serves for unloaded features."
|
||||
echo "To fix, run from the repo root:"
|
||||
echo " uv run python -m litellm.proxy._lazy_openapi_snapshot"
|
||||
echo "then run npm run gen:api from ui/litellm-dashboard and commit both files."
|
||||
exit 1
|
||||
fi
|
||||
echo "_lazy_openapi_snapshot.json is in sync with the lazily loaded routes."
|
||||
|
||||
- name: Set up Node.js
|
||||
if: steps.changes.outputs.relevant == 'true'
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
|
|
|
|||
|
|
@ -1473,6 +1473,12 @@ LITELLM_PROXY_MASTER_KEY_ALIAS: Final = "litellm_proxy_master_key"
|
|||
# ``ProxyLogging._handle_logging_proxy_only_error``.
|
||||
LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL: Final = "litellm_no_upstream_llm_call"
|
||||
|
||||
# Key/team metadata fields naming the OTel Resource ``service.name``, highest
|
||||
# precedence first. Shared between the OTel v2 tenant router (which reads them
|
||||
# out of ``user_api_key_auth_metadata``) and proxy request setup (which re-applies
|
||||
# the key's values after the team metadata merge so a key outranks its team).
|
||||
OTEL_SERVICE_NAME_METADATA_KEYS: Final = ("otel_service_name_override", "otel_service_name")
|
||||
|
||||
# Key Rotation Constants
|
||||
LITELLM_KEY_ROTATION_ENABLED: Final = os.getenv("LITELLM_KEY_ROTATION_ENABLED", "false")
|
||||
LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS: Final = int(
|
||||
|
|
|
|||
|
|
@ -557,9 +557,10 @@ def cost_per_token(
|
|||
)
|
||||
elif call_type == "atranscription" or call_type == "transcription":
|
||||
if _transcription_usage_has_token_details(usage_block):
|
||||
return openai_cost_per_token(
|
||||
return generic_cost_per_token(
|
||||
model=model_without_prefix,
|
||||
usage=usage_block,
|
||||
custom_llm_provider=custom_llm_provider,
|
||||
service_tier=service_tier,
|
||||
data_residency=data_residency,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ class CustomBatchLogger(CustomLogger):
|
|||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def periodic_flush(self):
|
||||
async def periodic_flush(self) -> None:
|
||||
while True:
|
||||
await asyncio.sleep(self.flush_interval)
|
||||
verbose_logger.debug("CustomLogger periodic flush after %s seconds", self.flush_interval)
|
||||
|
|
|
|||
|
|
@ -149,7 +149,6 @@ class PromptManager:
|
|||
)
|
||||
self.prompts[template_id] = template
|
||||
except Exception:
|
||||
# Optional: print(f"Error loading prompt from JSON: {template_id}")
|
||||
pass
|
||||
|
||||
def _load_prompt_file(self, file_path: str | Path, prompt_id: str) -> PromptTemplate:
|
||||
|
|
|
|||
395
litellm/integrations/newrelic/newrelic_metrics.py
Normal file
395
litellm/integrations/newrelic/newrelic_metrics.py
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
"""
|
||||
New Relic Metric API Integration - sends per-team cost/usage metrics to /metric/v1
|
||||
|
||||
NR Reference API: https://docs.newrelic.com/docs/data-apis/ingest-apis/metric-api/introduction-metric-api/
|
||||
|
||||
`async_log_success_event` / `async_log_failure_event` queue one record per request;
|
||||
at flush the queue is aggregated by (team, model group, model, provider, status)
|
||||
into count/summary metrics. `interval.ms` is the real window between flushes,
|
||||
computed at flush time.
|
||||
|
||||
Team-scoped by construction: the ingest key is injected explicitly and there is
|
||||
deliberately no environment-variable fallback, so a team's metrics are never sent
|
||||
with the proxy operator's credentials (mirrors ``allow_env_credentials=False`` on
|
||||
the Datadog team logger).
|
||||
|
||||
Error policy on flush: 4xx drops the batch (a retry would fail identically; 403
|
||||
is a permanent credential failure), 5xx/network re-queues capped at
|
||||
``max_queue_size`` records with the oldest dropped.
|
||||
|
||||
For batching specific details see CustomBatchLogger class
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
import time
|
||||
import traceback
|
||||
from collections.abc import Mapping
|
||||
from math import ceil
|
||||
from types import MappingProxyType
|
||||
from typing import Final
|
||||
|
||||
from httpx import HTTPStatusError, Response
|
||||
|
||||
from litellm._logging import verbose_logger
|
||||
from litellm.integrations.custom_batch_logger import CustomBatchLogger
|
||||
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
|
||||
from litellm.llms.custom_httpx.http_handler import (
|
||||
get_async_httpx_client,
|
||||
httpxSpecialProvider,
|
||||
)
|
||||
from litellm.types.integrations.newrelic import (
|
||||
NEWRELIC_DEFAULT_REGION,
|
||||
NEWRELIC_METRIC_ATTRIBUTE_MAX_LEN,
|
||||
NEWRELIC_METRIC_COMPLETION_TOKENS,
|
||||
NEWRELIC_METRIC_COST_USD,
|
||||
NEWRELIC_METRIC_ENDPOINT_BY_REGION,
|
||||
NEWRELIC_METRIC_PROMPT_TOKENS,
|
||||
NEWRELIC_METRIC_REQUEST_DURATION_MS,
|
||||
NEWRELIC_METRIC_REQUESTS,
|
||||
NEWRELIC_METRIC_TOTAL_TOKENS,
|
||||
NEWRELIC_METRICS_MAX_BATCH_SIZE,
|
||||
NEWRELIC_METRICS_MAX_DRAIN_PASSES,
|
||||
NEWRELIC_METRICS_MAX_RETRY_QUEUE_SIZE,
|
||||
NewRelicCountMetric,
|
||||
NewRelicMetric,
|
||||
NewRelicMetricCommon,
|
||||
NewRelicMetricEnvelope,
|
||||
NewRelicMetricRecord,
|
||||
NewRelicSummaryMetric,
|
||||
NewRelicSummaryValue,
|
||||
)
|
||||
from litellm.types.utils import StandardLoggingPayload
|
||||
|
||||
# 408 (request timeout) and 429 (rate limit) are transient client errors the
|
||||
# Metric API expects a retry on, unlike 400/403 which a retry would only repeat.
|
||||
_RETRYABLE_CLIENT_STATUSES: Final = frozenset({408, 429})
|
||||
|
||||
|
||||
def resolve_newrelic_metric_endpoint(newrelic_region: str | None) -> str:
|
||||
if not newrelic_region:
|
||||
return NEWRELIC_METRIC_ENDPOINT_BY_REGION[NEWRELIC_DEFAULT_REGION]
|
||||
endpoint: Final = NEWRELIC_METRIC_ENDPOINT_BY_REGION.get(newrelic_region.lower())
|
||||
if endpoint is None:
|
||||
verbose_logger.warning(
|
||||
"New Relic: unknown newrelic_region %r; supported regions: %s. Using the default (US) endpoint.",
|
||||
newrelic_region,
|
||||
", ".join(sorted(NEWRELIC_METRIC_ENDPOINT_BY_REGION)),
|
||||
)
|
||||
return NEWRELIC_METRIC_ENDPOINT_BY_REGION[NEWRELIC_DEFAULT_REGION]
|
||||
return endpoint
|
||||
|
||||
|
||||
def _metric_record_from_payload(standard_logging_object: StandardLoggingPayload) -> NewRelicMetricRecord:
|
||||
metadata: Final = standard_logging_object.get("metadata")
|
||||
team_id: Final = ((metadata.get("user_api_key_team_id") or metadata.get("team_id")) if metadata else None) or ""
|
||||
team_alias: Final = (
|
||||
(metadata.get("user_api_key_team_alias") or metadata.get("team_alias")) if metadata else None
|
||||
) or ""
|
||||
return NewRelicMetricRecord(
|
||||
team_id=team_id,
|
||||
team_alias=team_alias,
|
||||
model_group=standard_logging_object.get("model_group") or "",
|
||||
model=standard_logging_object.get("model") or "",
|
||||
custom_llm_provider=standard_logging_object.get("custom_llm_provider") or "",
|
||||
status=str(standard_logging_object.get("status") or "success"),
|
||||
response_cost=float(standard_logging_object.get("response_cost") or 0.0),
|
||||
prompt_tokens=int(standard_logging_object.get("prompt_tokens") or 0),
|
||||
completion_tokens=int(standard_logging_object.get("completion_tokens") or 0),
|
||||
total_tokens=int(standard_logging_object.get("total_tokens") or 0),
|
||||
duration_ms=float(standard_logging_object.get("response_time") or 0.0) * 1000.0,
|
||||
)
|
||||
|
||||
|
||||
def _bucket_metrics(bucket_records: tuple[NewRelicMetricRecord, ...]) -> tuple[NewRelicMetric, ...]:
|
||||
first: Final = bucket_records[0]
|
||||
attributes: Final[Mapping[str, str]] = { # mutable-ok: JSON leaf; safe_dumps stringifies MappingProxyType
|
||||
key: value[:NEWRELIC_METRIC_ATTRIBUTE_MAX_LEN]
|
||||
for key, value in (
|
||||
("team_id", first.team_id),
|
||||
("team_alias", first.team_alias),
|
||||
("model_group", first.model_group),
|
||||
("model", first.model),
|
||||
("custom_llm_provider", first.custom_llm_provider),
|
||||
("status", first.status),
|
||||
)
|
||||
if value
|
||||
}
|
||||
durations: Final = tuple(record.duration_ms for record in bucket_records)
|
||||
counts: Final[tuple[tuple[str, float], ...]] = (
|
||||
(NEWRELIC_METRIC_REQUESTS, float(len(bucket_records))),
|
||||
(NEWRELIC_METRIC_COST_USD, sum(record.response_cost for record in bucket_records)),
|
||||
(NEWRELIC_METRIC_PROMPT_TOKENS, float(sum(record.prompt_tokens for record in bucket_records))),
|
||||
(NEWRELIC_METRIC_COMPLETION_TOKENS, float(sum(record.completion_tokens for record in bucket_records))),
|
||||
(NEWRELIC_METRIC_TOTAL_TOKENS, float(sum(record.total_tokens for record in bucket_records))),
|
||||
)
|
||||
count_metrics: Final[tuple[NewRelicMetric, ...]] = tuple(
|
||||
NewRelicCountMetric(name=name, type="count", value=value, attributes=attributes) for name, value in counts
|
||||
)
|
||||
summary_metric: Final = NewRelicSummaryMetric(
|
||||
name=NEWRELIC_METRIC_REQUEST_DURATION_MS,
|
||||
type="summary",
|
||||
value=NewRelicSummaryValue(
|
||||
count=len(durations),
|
||||
sum=sum(durations),
|
||||
min=min(durations),
|
||||
max=max(durations),
|
||||
),
|
||||
attributes=attributes,
|
||||
)
|
||||
return (*count_metrics, summary_metric)
|
||||
|
||||
|
||||
def build_metric_payload(
|
||||
records: tuple[NewRelicMetricRecord, ...],
|
||||
*,
|
||||
window_start: float,
|
||||
now: float,
|
||||
) -> tuple[NewRelicMetricEnvelope, ...]:
|
||||
"""Aggregates records into one Metric API envelope for the flush window."""
|
||||
interval_ms: Final = max(1, int((now - window_start) * 1000))
|
||||
bucket_keys: Final = tuple(dict.fromkeys(record.bucket_key for record in records))
|
||||
metrics: Final = tuple(
|
||||
metric
|
||||
for key in bucket_keys
|
||||
for metric in _bucket_metrics(tuple(record for record in records if record.bucket_key == key))
|
||||
)
|
||||
common: Final[NewRelicMetricCommon] = {
|
||||
"timestamp": int(window_start * 1000),
|
||||
"interval.ms": interval_ms,
|
||||
}
|
||||
return (NewRelicMetricEnvelope(common=common, metrics=metrics),)
|
||||
|
||||
|
||||
class NewRelicMetricsLogger(CustomBatchLogger):
|
||||
def __init__(
|
||||
self,
|
||||
newrelic_api_key: str,
|
||||
newrelic_region: str | None = None,
|
||||
) -> None:
|
||||
if not newrelic_api_key:
|
||||
raise ValueError(
|
||||
"newrelic_api_key is required for NewRelicMetricsLogger; "
|
||||
"team-scoped metrics never fall back to environment credentials"
|
||||
)
|
||||
self.newrelic_api_key: Final = newrelic_api_key
|
||||
self.metric_api_url: Final = resolve_newrelic_metric_endpoint(newrelic_region)
|
||||
self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback)
|
||||
self._stopped: bool = False
|
||||
self._drain_lock = asyncio.Lock()
|
||||
asyncio.create_task(self.periodic_flush())
|
||||
self.flush_lock = asyncio.Lock()
|
||||
super().__init__(
|
||||
flush_lock=self.flush_lock,
|
||||
batch_size=NEWRELIC_METRICS_MAX_BATCH_SIZE,
|
||||
max_queue_size=NEWRELIC_METRICS_MAX_RETRY_QUEUE_SIZE,
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Ends the periodic flush loop; called on DynamicLoggingCache eviction.
|
||||
|
||||
Schedules one final drain of anything still queued, so eviction never
|
||||
silently discards records. Guarded so it can never raise into the
|
||||
cache's eviction path.
|
||||
"""
|
||||
self._stopped = True
|
||||
try:
|
||||
asyncio.get_running_loop().create_task(self._final_drain())
|
||||
except Exception: # noqa: BLE001 # no running loop / shutdown; the periodic loop's final drain still runs
|
||||
verbose_logger.debug("New Relic Metrics: could not schedule final drain on stop()", exc_info=True)
|
||||
|
||||
async def _drain_with_retry(self) -> None:
|
||||
"""Deliver everything queued on a stopped logger, or drop it with a log.
|
||||
|
||||
A stopped logger has no periodic loop left, so every post-stop path
|
||||
funnels through here. ``_drain_lock`` serializes drains: a callback that
|
||||
appends and starts its own drain queues behind the running one instead
|
||||
of racing it. Each pass attempts the whole current queue in
|
||||
``batch_size`` chunks, unlike the periodic path it does not stop at the
|
||||
first failing chunk, so a persistently failing head never starves the
|
||||
tail. Only after ``_MAX_DRAIN_PASSES`` against a permanently failing
|
||||
destination is the remainder dropped, and then only the records that were
|
||||
queued when this drain began, so every dropped record got the full retry
|
||||
budget: a record a callback appended mid-drain is not in that snapshot,
|
||||
so it is left for its own serialized drain rather than dropped after
|
||||
fewer attempts, and is never stranded.
|
||||
"""
|
||||
async with self._drain_lock:
|
||||
attempted: Final = tuple(self.log_queue)
|
||||
for _pass in range(NEWRELIC_METRICS_MAX_DRAIN_PASSES):
|
||||
await self._drain_flush_once()
|
||||
if not self.log_queue:
|
||||
return
|
||||
if _pass < NEWRELIC_METRICS_MAX_DRAIN_PASSES - 1:
|
||||
await asyncio.sleep(2**_pass)
|
||||
async with self.flush_lock:
|
||||
tried_ids: Final = frozenset(id(record) for record in attempted)
|
||||
survivors: Final = tuple(record for record in self.log_queue if id(record) not in tried_ids)
|
||||
dropped: Final = len(self.log_queue) - len(survivors)
|
||||
if dropped:
|
||||
verbose_logger.warning(
|
||||
"New Relic Metrics: dropping %s records after %s drain passes",
|
||||
dropped,
|
||||
NEWRELIC_METRICS_MAX_DRAIN_PASSES,
|
||||
)
|
||||
self.log_queue[:] = list(survivors) # mutable-ok: leave late arrivals for the next serialized drain
|
||||
|
||||
async def _drain_flush_once(self) -> None:
|
||||
"""Attempt every queued record once, in ``batch_size`` chunks, without
|
||||
stopping at the first failing chunk so a persistently failing head does
|
||||
not starve the tail (the periodic ``flush_queue`` deliberately stops
|
||||
instead). Takes the queue under ``flush_lock`` and re-queues only the
|
||||
chunks a 5xx/network error left undelivered, so records a concurrent
|
||||
request appends during the sends survive for the next pass."""
|
||||
async with self.flush_lock:
|
||||
pending: Final = tuple(self.log_queue)
|
||||
window_start: Final = self.last_flush_time
|
||||
self.last_flush_time = time.time()
|
||||
del self.log_queue[:]
|
||||
if not pending:
|
||||
return
|
||||
chunks: Final = tuple(
|
||||
pending[start : start + self.batch_size] for start in range(0, len(pending), self.batch_size)
|
||||
)
|
||||
delivered: Final = tuple([await self._classify_and_send(chunk, window_start) for chunk in chunks])
|
||||
failed: Final = tuple(record for chunk, ok in zip(chunks, delivered) for record in (() if ok else chunk))
|
||||
if failed:
|
||||
self._requeue(failed)
|
||||
|
||||
async def _final_drain(self) -> None:
|
||||
await self._drain_with_retry()
|
||||
|
||||
async def periodic_flush(self) -> None:
|
||||
while not self._stopped:
|
||||
await asyncio.sleep(self.flush_interval)
|
||||
if self._stopped:
|
||||
break
|
||||
await self.flush_queue()
|
||||
await self._final_drain()
|
||||
|
||||
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None:
|
||||
try:
|
||||
await self._log_async_event(standard_logging_object=kwargs.get("standard_logging_object", None))
|
||||
except Exception as e: # noqa: BLE001 # logging must never break the request path
|
||||
verbose_logger.exception("New Relic Metrics Layer Error - %s\n%s", e, traceback.format_exc())
|
||||
|
||||
async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time) -> None:
|
||||
try:
|
||||
await self._log_async_event(standard_logging_object=kwargs.get("standard_logging_object", None))
|
||||
except Exception as e: # noqa: BLE001 # logging must never break the request path
|
||||
verbose_logger.exception("New Relic Metrics Layer Error - %s\n%s", e, traceback.format_exc())
|
||||
|
||||
async def _log_async_event(self, standard_logging_object: StandardLoggingPayload | None) -> None:
|
||||
if standard_logging_object is None:
|
||||
raise ValueError("standard_logging_object not found in kwargs")
|
||||
self.log_queue.append(_metric_record_from_payload(standard_logging_object))
|
||||
if self._stopped:
|
||||
# A stopped logger has no periodic loop left; an in-flight callback
|
||||
# that appends after the eviction drain delivers its own record.
|
||||
await self._drain_with_retry()
|
||||
return
|
||||
if len(self.log_queue) >= self.batch_size:
|
||||
await self.flush_queue()
|
||||
|
||||
async def flush_queue(self) -> None:
|
||||
async with self.flush_lock:
|
||||
window_start: Final = self.last_flush_time
|
||||
self.last_flush_time = time.time()
|
||||
queued: Final = len(self.log_queue)
|
||||
if not queued:
|
||||
return
|
||||
verbose_logger.debug("New Relic Metrics: Flushing %s queued records", queued)
|
||||
# Bounded by what is queued now: records appended mid-flush belong to
|
||||
# the next window, and looping until empty would never end under load.
|
||||
for _chunk in range(ceil(queued / self.batch_size)):
|
||||
if not await self.async_send_batch(window_start=window_start):
|
||||
return
|
||||
|
||||
async def async_send_batch(self, window_start: float | None = None) -> bool:
|
||||
"""Sends the oldest ``batch_size`` records only, so a queue grown past that
|
||||
by re-queues cannot breach the Metric API data point cap in one request.
|
||||
Returns False once a chunk fails and is re-queued, so the caller stops."""
|
||||
if not self.log_queue:
|
||||
return False
|
||||
|
||||
batch_to_send: Final[tuple[NewRelicMetricRecord, ...]] = tuple(self.log_queue[: self.batch_size])
|
||||
del self.log_queue[: len(batch_to_send)]
|
||||
|
||||
delivered: Final = await self._classify_and_send(
|
||||
batch_to_send, window_start if window_start is not None else self.last_flush_time
|
||||
)
|
||||
if not delivered:
|
||||
self._requeue(batch_to_send)
|
||||
return delivered
|
||||
|
||||
async def _classify_and_send(self, batch: tuple[NewRelicMetricRecord, ...], window_start: float) -> bool:
|
||||
"""Send one chunk and classify the outcome, never touching the queue.
|
||||
Returns True when the batch is done with (delivered on any 2xx, or a 4xx
|
||||
a retry would only repeat, 403 being a permanent bad-key rejection), and
|
||||
False when a 5xx or network error means the caller should re-queue it.
|
||||
|
||||
``AsyncHTTPHandler.post`` raises ``HTTPStatusError`` on any non-2xx, so a
|
||||
4xx never returns a response here; the status is read off the raised
|
||||
error to keep the client-error path (drop) distinct from 5xx (retry)."""
|
||||
payload: Final = build_metric_payload(records=batch, window_start=window_start, now=time.time())
|
||||
try:
|
||||
status = (
|
||||
await self.async_send_compressed_data(payload)
|
||||
).status_code # rebind-ok: reassigned from the raised HTTPStatusError below
|
||||
except HTTPStatusError as e:
|
||||
status = e.response.status_code
|
||||
except Exception as e: # noqa: BLE001 # transport/network failure re-queues the batch
|
||||
verbose_logger.warning(
|
||||
"New Relic Metrics: network error sending %s records, will retry - %s",
|
||||
len(batch),
|
||||
e,
|
||||
)
|
||||
return False
|
||||
|
||||
if 200 <= status < 300:
|
||||
return True
|
||||
|
||||
if 400 <= status < 500 and status not in _RETRYABLE_CLIENT_STATUSES:
|
||||
verbose_logger.warning(
|
||||
"New Relic Metrics: %s from Metric API%s, dropping %s records.",
|
||||
status,
|
||||
" (permanent credential failure: invalid or revoked team ingest key)" if status == 403 else "",
|
||||
len(batch),
|
||||
)
|
||||
return True
|
||||
|
||||
verbose_logger.warning(
|
||||
"New Relic Metrics: %s from Metric API, will retry %s records",
|
||||
status,
|
||||
len(batch),
|
||||
)
|
||||
return False
|
||||
|
||||
def _requeue(self, batch: tuple[NewRelicMetricRecord, ...]) -> None:
|
||||
"""Prepends ``batch`` in place (never by assignment: records appended by
|
||||
concurrent requests during the flush await must survive), keeping
|
||||
chronological order so the cap drops the oldest records first."""
|
||||
self.log_queue[:0] = batch
|
||||
overflow: Final = len(self.log_queue) - self.max_queue_size
|
||||
if overflow > 0:
|
||||
del self.log_queue[:overflow]
|
||||
verbose_logger.warning(
|
||||
"New Relic Metrics: retry queue exceeded max_queue_size=%s; dropped %s oldest records.",
|
||||
self.max_queue_size,
|
||||
overflow,
|
||||
)
|
||||
|
||||
async def async_send_compressed_data(self, payload: tuple[NewRelicMetricEnvelope, ...]) -> Response:
|
||||
compressed_data: Final = gzip.compress(safe_dumps(payload).encode("utf-8"))
|
||||
headers: Final[Mapping[str, str]] = MappingProxyType(
|
||||
{
|
||||
"Content-Type": "application/json",
|
||||
"Content-Encoding": "gzip",
|
||||
"Api-Key": self.newrelic_api_key,
|
||||
}
|
||||
)
|
||||
return await self.async_client.post(
|
||||
url=self.metric_api_url,
|
||||
data=compressed_data,
|
||||
headers=headers,
|
||||
)
|
||||
90
litellm/integrations/newrelic/newrelic_team_handler.py
Normal file
90
litellm/integrations/newrelic/newrelic_team_handler.py
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
"""
|
||||
New Relic Team Handler
|
||||
|
||||
Used to get the NewRelicMetricsLogger for a given request.
|
||||
Handles Key/Team Based New Relic metrics, following the same pattern as DataDogHandler.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from typing_extensions import ReadOnly, TypedDict
|
||||
|
||||
from litellm._logging import verbose_logger
|
||||
from litellm.litellm_core_utils.litellm_logging import StandardCallbackDynamicParams
|
||||
|
||||
from .newrelic_metrics import NewRelicMetricsLogger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from litellm.litellm_core_utils.litellm_logging import DynamicLoggingCache
|
||||
|
||||
|
||||
class NewRelicLoggingConfig(TypedDict):
|
||||
newrelic_api_key: ReadOnly[str | None]
|
||||
newrelic_region: ReadOnly[str | None]
|
||||
|
||||
|
||||
class NewRelicHandler:
|
||||
@staticmethod
|
||||
def get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params: StandardCallbackDynamicParams,
|
||||
in_memory_dynamic_logger_cache: "DynamicLoggingCache",
|
||||
) -> NewRelicMetricsLogger:
|
||||
"""
|
||||
Get a team-scoped NewRelicMetricsLogger for a given request.
|
||||
|
||||
Resolves and caches per-team NewRelicMetricsLogger instances using
|
||||
DynamicLoggingCache, keyed by the team's New Relic credentials. Each unique
|
||||
set of credentials gets its own logger instance with its own batch/flush loop.
|
||||
|
||||
Note: This handler is only called when a team-scoped newrelic_api_key is
|
||||
present. The trace logger for the ``newrelic`` callback (OTel v2 / legacy
|
||||
agent) is managed separately by _init_custom_logger_compatible_class via
|
||||
_in_memory_loggers.
|
||||
"""
|
||||
_credentials: Final = NewRelicHandler.get_dynamic_newrelic_logging_config(
|
||||
standard_callback_dynamic_params=standard_callback_dynamic_params,
|
||||
)
|
||||
|
||||
temp_newrelic_logger = in_memory_dynamic_logger_cache.get_cache(
|
||||
credentials=_credentials, service_name="newrelic"
|
||||
)
|
||||
|
||||
if temp_newrelic_logger is None:
|
||||
temp_newrelic_logger = NewRelicHandler._create_newrelic_logger_from_credentials(
|
||||
credentials=_credentials,
|
||||
in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,
|
||||
)
|
||||
|
||||
return temp_newrelic_logger
|
||||
|
||||
@staticmethod
|
||||
def _create_newrelic_logger_from_credentials(
|
||||
credentials: NewRelicLoggingConfig,
|
||||
in_memory_dynamic_logger_cache: "DynamicLoggingCache",
|
||||
) -> NewRelicMetricsLogger:
|
||||
newrelic_logger: Final = NewRelicMetricsLogger(
|
||||
newrelic_api_key=credentials.get("newrelic_api_key") or "",
|
||||
newrelic_region=credentials.get("newrelic_region"),
|
||||
)
|
||||
in_memory_dynamic_logger_cache.set_cache(
|
||||
credentials=credentials,
|
||||
service_name="newrelic",
|
||||
logging_obj=newrelic_logger,
|
||||
)
|
||||
verbose_logger.debug("New Relic: Created and cached new NewRelicMetricsLogger for team-scoped credentials")
|
||||
return newrelic_logger
|
||||
|
||||
@staticmethod
|
||||
def get_dynamic_newrelic_logging_config(
|
||||
standard_callback_dynamic_params: StandardCallbackDynamicParams,
|
||||
) -> NewRelicLoggingConfig:
|
||||
return NewRelicLoggingConfig(
|
||||
newrelic_api_key=standard_callback_dynamic_params.get("newrelic_api_key"),
|
||||
newrelic_region=standard_callback_dynamic_params.get("newrelic_region"),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _dynamic_newrelic_credentials_are_passed(
|
||||
standard_callback_dynamic_params: StandardCallbackDynamicParams,
|
||||
) -> bool:
|
||||
return standard_callback_dynamic_params.get("newrelic_api_key") is not None
|
||||
|
|
@ -2,12 +2,13 @@
|
|||
|
||||
When a request carries team/key vendor credentials in
|
||||
``standard_callback_dynamic_params``, or the key/team config resolved at auth
|
||||
names a destination project, its spans must export through a
|
||||
``TracerProvider`` whose OTLP headers carry those credentials / that project.
|
||||
``TenantTracerCache`` builds and caches one provider per distinct
|
||||
(credentials, project) pair, and otherwise hands back the logger's default
|
||||
tracer. This lets a single logger fan requests out to many tenants without
|
||||
needing a logger per tenant.
|
||||
names a destination project or a service name, its spans must export through a
|
||||
``TracerProvider`` whose OTLP headers carry those credentials / that project,
|
||||
or whose Resource carries that ``service.name``. ``TenantTracerCache`` builds
|
||||
and caches one provider per distinct (credentials, project, service name)
|
||||
tuple, and otherwise hands back the logger's default tracer. This lets a
|
||||
single logger fan requests out to many tenants without needing a logger per
|
||||
tenant.
|
||||
"""
|
||||
|
||||
import threading
|
||||
|
|
@ -22,6 +23,7 @@ from opentelemetry.sdk.trace import TracerProvider
|
|||
from opentelemetry.trace import Tracer
|
||||
|
||||
from litellm._logging import verbose_logger
|
||||
from litellm.constants import OTEL_SERVICE_NAME_METADATA_KEYS
|
||||
from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
|
||||
from litellm.integrations.otel.plumbing.providers import (
|
||||
build_tracer_provider,
|
||||
|
|
@ -65,8 +67,30 @@ _MAX_RETIRED_PROVIDERS: Final = 64
|
|||
|
||||
_HeaderItems: TypeAlias = tuple[tuple[str, str], ...]
|
||||
|
||||
_RouteKey: TypeAlias = tuple[_HeaderItems, _HeaderItems, str | None, str | None]
|
||||
|
||||
_NO_HEADERS: Final[Mapping[str, str]] = MappingProxyType({})
|
||||
|
||||
#: Key/team config fields naming the Resource ``service.name``, highest
|
||||
#: precedence first. Read only from ``user_api_key_auth_metadata`` (the config
|
||||
#: the proxy resolved at auth), never from client-supplied request metadata:
|
||||
#: the service name picks the dataset/service traces land in (Honeycomb routes
|
||||
#: datasets by it), so a caller must not be able to choose one.
|
||||
_SERVICE_NAME_KEYS: Final = OTEL_SERVICE_NAME_METADATA_KEYS
|
||||
|
||||
|
||||
def tenant_service_name(auth_metadata: Mapping[str, str] | None) -> str | None:
|
||||
"""The per-request ``service.name`` override for this key/team, if any.
|
||||
|
||||
``None`` keeps the env-configured default (``OTEL_SERVICE_NAME``).
|
||||
"""
|
||||
if not auth_metadata:
|
||||
return None
|
||||
return next(
|
||||
(stripped for key in _SERVICE_NAME_KEYS if (stripped := (auth_metadata.get(key) or "").strip())),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _shutdown_provider(provider: TracerProvider) -> None:
|
||||
"""Flush + stop an evicted provider's processors (reclaims their threads).
|
||||
|
|
@ -116,7 +140,7 @@ class TenantRoute:
|
|||
|
||||
|
||||
class TenantTracerCache:
|
||||
"""Credential/project-scoped ``TracerProvider`` cache keyed by the routing headers."""
|
||||
"""Tenant-scoped ``TracerProvider`` cache keyed by routing headers and service name."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
|
@ -131,7 +155,7 @@ class TenantTracerCache:
|
|||
# thread-pool workers concurrently with the event loop, so cache
|
||||
# updates, span counts, and retirement must be atomic.
|
||||
self._lock: Final = threading.Lock()
|
||||
self._providers: OrderedDict[tuple[_HeaderItems, _HeaderItems, str | None], TracerProvider] = (
|
||||
self._providers: OrderedDict[_RouteKey, TracerProvider] = (
|
||||
OrderedDict() # mutable-ok: bounded LRU; eviction needs in-place ordered mutation
|
||||
)
|
||||
self._open_span_counts: dict[TracerProvider, int] = {} # mutable-ok: live refcount state
|
||||
|
|
@ -172,10 +196,11 @@ class TenantTracerCache:
|
|||
) -> TenantRoute:
|
||||
"""Return the tracer (and trace-detachment flag) for this request.
|
||||
|
||||
Use ``default`` unless the request's dynamic credentials or its key/team
|
||||
project require a scoped tracer, in which case build (or reuse) one. The
|
||||
cache is a bounded LRU: the least-recently-used provider is flushed and
|
||||
shut down on overflow so its exporter threads don't accumulate.
|
||||
Use ``default`` unless the request's dynamic credentials, its key/team
|
||||
project, or its key/team service name require a scoped tracer, in
|
||||
which case build (or reuse) one. The cache is a bounded LRU: the
|
||||
least-recently-used provider is flushed and shut down on overflow so
|
||||
its exporter threads don't accumulate.
|
||||
|
||||
A routed provider is returned already held — its open-span count is
|
||||
incremented in the same critical section as the cache update — so a
|
||||
|
|
@ -184,7 +209,8 @@ class TenantTracerCache:
|
|||
"""
|
||||
credential_headers: Final = dynamic_otlp_headers(self._callback_name, dynamic_params) or _NO_HEADERS
|
||||
project_headers: Final = self._project_headers(auth_metadata)
|
||||
if not credential_headers and not project_headers:
|
||||
service_name: Final = tenant_service_name(auth_metadata)
|
||||
if not credential_headers and not project_headers and service_name is None:
|
||||
return TenantRoute(tracer=default, detached=False)
|
||||
# A fixed per-integration region endpoint (New Relic us/eu), never a
|
||||
# caller-supplied host; ``None`` keeps the preset's own endpoint.
|
||||
|
|
@ -193,9 +219,12 @@ class TenantTracerCache:
|
|||
tuple(sorted(credential_headers.items())),
|
||||
tuple(sorted(project_headers.items())),
|
||||
endpoint,
|
||||
service_name,
|
||||
)
|
||||
with self._lock:
|
||||
provider: Final = self._cached_provider_locked(cache_key, credential_headers, project_headers, endpoint)
|
||||
provider: Final = self._cached_provider_locked(
|
||||
cache_key, credential_headers, project_headers, endpoint, service_name
|
||||
)
|
||||
self._open_span_counts[provider] = self._open_span_counts.get(provider, 0) + 1
|
||||
evicted: Final = self._evicted_on_overflow_locked()
|
||||
if evicted is not None:
|
||||
|
|
@ -208,16 +237,19 @@ class TenantTracerCache:
|
|||
|
||||
def _cached_provider_locked(
|
||||
self,
|
||||
cache_key: tuple[_HeaderItems, _HeaderItems, str | None],
|
||||
cache_key: _RouteKey,
|
||||
credential_headers: Mapping[str, str],
|
||||
project_headers: Mapping[str, str],
|
||||
endpoint: str | None,
|
||||
service_name: str | None,
|
||||
) -> TracerProvider:
|
||||
cached: Final = self._providers.get(cache_key)
|
||||
if cached is not None:
|
||||
self._providers.move_to_end(cache_key)
|
||||
return cached
|
||||
built: Final = build_tracer_provider(self._routed_config(credential_headers, project_headers, endpoint))
|
||||
built: Final = build_tracer_provider(
|
||||
self._routed_config(credential_headers, project_headers, endpoint, service_name)
|
||||
)
|
||||
self._providers[cache_key] = built
|
||||
return built
|
||||
|
||||
|
|
@ -267,6 +299,7 @@ class TenantTracerCache:
|
|||
credential_headers: Mapping[str, str],
|
||||
project_headers: Mapping[str, str],
|
||||
endpoint: str | None = None,
|
||||
service_name: str | None = None,
|
||||
) -> OpenTelemetryV2Config:
|
||||
"""Clone the config, rewriting headers on the callback's own exporter.
|
||||
|
||||
|
|
@ -285,7 +318,10 @@ class TenantTracerCache:
|
|||
self._routed_exporter(spec, credential_headers, project_headers, endpoint)
|
||||
for spec in self._config.exporters
|
||||
]
|
||||
return self._config.model_copy(update={"exporters": exporters})
|
||||
update: Final = (
|
||||
{"exporters": exporters} if service_name is None else {"exporters": exporters, "service_name": service_name}
|
||||
)
|
||||
return self._config.model_copy(update=update)
|
||||
|
||||
def _routed_exporter(
|
||||
self,
|
||||
|
|
|
|||
|
|
@ -2341,6 +2341,7 @@ def exception_type(
|
|||
litellm_response_headers: Final = _get_response_headers(original_exception=original_exception)
|
||||
try:
|
||||
error_str = redact_string(str(original_exception)) if _ENABLE_SECRET_REDACTION else str(original_exception)
|
||||
extra_information = ""
|
||||
if model or custom_llm_provider:
|
||||
if hasattr(original_exception, "message"):
|
||||
error_str = (
|
||||
|
|
@ -2357,7 +2358,6 @@ def exception_type(
|
|||
# Common Extra information needed for all providers
|
||||
# We pass num retries, api_base, vertex_deployment etc to the exception here
|
||||
################################################################################
|
||||
extra_information = ""
|
||||
try:
|
||||
_api_base: Final = litellm.get_api_base(model=model, optional_params=extra_kwargs)
|
||||
messages: Final = litellm.get_first_chars_messages(kwargs=completion_kwargs)
|
||||
|
|
|
|||
|
|
@ -613,37 +613,60 @@ class Logging(LiteLLMLoggingBaseClass):
|
|||
processed_list: Final[list[str | Callable | CustomLogger]] = []
|
||||
for callback in callback_list:
|
||||
if isinstance(callback, str) and callback in litellm._known_custom_logger_compatible_callbacks:
|
||||
# For callbacks that support team-scoped credentials (e.g. datadog),
|
||||
# pass only the relevant dynamic params as custom_logger_init_args.
|
||||
_custom_logger_init_args: dict | None = None
|
||||
if callback == "datadog":
|
||||
# dd_* params are blocked from standard_callback_dynamic_params
|
||||
# (request-level security); only the proxy-stamped team/key
|
||||
# callback vars are admin-configured and trusted.
|
||||
_custom_logger_init_args = {k: v for k, v in self._trusted_callback_vars if k.startswith("dd_")}
|
||||
|
||||
callback_class = _init_custom_logger_compatible_class(
|
||||
callback,
|
||||
internal_usage_cache=None,
|
||||
llm_router=None,
|
||||
custom_logger_init_args=_custom_logger_init_args,
|
||||
)
|
||||
if callback_class is not None:
|
||||
processed_list.append(callback_class)
|
||||
for callback_instance in self._resolve_dynamic_callback_string(callback):
|
||||
processed_list.append(callback_instance)
|
||||
|
||||
# If processing dynamic_success_callbacks, add to dynamic_async_success_callbacks
|
||||
if dynamic_callbacks_type == "success":
|
||||
if self.dynamic_async_success_callbacks is None:
|
||||
self.dynamic_async_success_callbacks = []
|
||||
self.dynamic_async_success_callbacks.append(callback_class)
|
||||
self.dynamic_async_success_callbacks.append(callback_instance)
|
||||
elif dynamic_callbacks_type == "failure":
|
||||
if self.dynamic_async_failure_callbacks is None:
|
||||
self.dynamic_async_failure_callbacks = []
|
||||
self.dynamic_async_failure_callbacks.append(callback_class)
|
||||
self.dynamic_async_failure_callbacks.append(callback_instance)
|
||||
else:
|
||||
processed_list.append(callback)
|
||||
return processed_list
|
||||
|
||||
def _resolve_dynamic_callback_string(self, callback: str) -> "tuple[CustomLogger, ...]":
|
||||
"""
|
||||
Resolve a known callback name to the logger instance(s) it dispatches to.
|
||||
|
||||
For callbacks that support team-scoped credentials (datadog, newrelic),
|
||||
only the proxy-stamped team/key callback vars are passed as
|
||||
custom_logger_init_args: dd_*/newrelic_* params are blocked from
|
||||
standard_callback_dynamic_params (request-level security), so the
|
||||
trusted-vars channel is the only way credentials reach a per-team logger.
|
||||
"""
|
||||
_trusted_var_prefix: Final = "dd_" if callback == "datadog" else "newrelic_" if callback == "newrelic" else None
|
||||
_custom_logger_init_args: Final[dict | None] = (
|
||||
{k: v for k, v in self._trusted_callback_vars if k.startswith(_trusted_var_prefix)}
|
||||
if _trusted_var_prefix is not None
|
||||
else None
|
||||
)
|
||||
|
||||
callback_class: Final = _init_custom_logger_compatible_class(
|
||||
callback,
|
||||
internal_usage_cache=None,
|
||||
llm_router=None,
|
||||
custom_logger_init_args=_custom_logger_init_args,
|
||||
)
|
||||
if callback_class is None:
|
||||
return ()
|
||||
|
||||
# With team creds, "newrelic" resolves to the per-team METRICS logger;
|
||||
# resolve the name again without creds so the trace logger (OTel v2 /
|
||||
# legacy agent) keeps receiving this request.
|
||||
_newrelic_trace_class: Final = (
|
||||
_init_custom_logger_compatible_class(callback, internal_usage_cache=None, llm_router=None)
|
||||
if callback == "newrelic" and _custom_logger_init_args and _custom_logger_init_args.get("newrelic_api_key")
|
||||
else None
|
||||
)
|
||||
if _newrelic_trace_class is not None and _newrelic_trace_class is not callback_class:
|
||||
return (callback_class, _newrelic_trace_class)
|
||||
return (callback_class,)
|
||||
|
||||
def initialize_standard_callback_dynamic_params(self, kwargs: dict | None = None) -> StandardCallbackDynamicParams:
|
||||
"""
|
||||
Initialize the standard callback dynamic params from the kwargs
|
||||
|
|
@ -4642,6 +4665,19 @@ def _init_custom_logger_compatible_class(
|
|||
_in_memory_loggers.append(gitlab_logger)
|
||||
return gitlab_logger
|
||||
elif logging_integration == "newrelic":
|
||||
if custom_logger_init_args.get("newrelic_api_key"):
|
||||
# Team-scoped credentials: per-team METRICS logger, isolated per
|
||||
# credential set via DynamicLoggingCache. The trace logger for
|
||||
# this name stays on the global path below.
|
||||
from litellm.integrations.newrelic.newrelic_team_handler import (
|
||||
NewRelicHandler,
|
||||
)
|
||||
|
||||
return NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=custom_logger_init_args,
|
||||
in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,
|
||||
)
|
||||
|
||||
_v2 = _maybe_construct_otel_v2("newrelic", _in_memory_loggers)
|
||||
if _v2 is not None:
|
||||
return _v2
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@ from typing import Any, Final, Literal
|
|||
|
||||
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.litellm_core_utils.llm_cost_calc.utils import (
|
||||
get_web_search_requests_from_usage,
|
||||
)
|
||||
from litellm.types.llms.openai import (
|
||||
FileSearchTool,
|
||||
ResponsesAPIResponse,
|
||||
|
|
@ -368,7 +370,7 @@ class StandardBuiltInToolCostTracking:
|
|||
get_anthropic_web_search_requests_from_response,
|
||||
)
|
||||
|
||||
if usage is not None and (get_web_search_requests(getattr(usage, "server_tool_use", None)) is not None):
|
||||
if usage is not None and (get_web_search_requests_from_usage(usage) is not None):
|
||||
return usage
|
||||
web_search_requests: Final = get_anthropic_web_search_requests_from_response(response_object)
|
||||
if web_search_requests is None:
|
||||
|
|
@ -416,7 +418,7 @@ class StandardBuiltInToolCostTracking:
|
|||
# Anthropic Claude (direct API and Vertex AI) uses server_tool_use.web_search_requests.
|
||||
# Without this check, Claude ModelResponse always falls through to return False
|
||||
# and _handle_web_search_cost() is never called.
|
||||
if hasattr(usage, "server_tool_use") and get_web_search_requests(usage.server_tool_use) is not None:
|
||||
if get_web_search_requests_from_usage(usage) is not None:
|
||||
return True
|
||||
# xAI reports usage.server_side_tool_usage_details.web_search_calls; a searched
|
||||
# answer with no url_citation annotations has no other chat-path signal
|
||||
|
|
@ -429,16 +431,12 @@ class StandardBuiltInToolCostTracking:
|
|||
response_object=response_object, output_type="web_search_call"
|
||||
)
|
||||
elif usage is not None:
|
||||
if (
|
||||
hasattr(usage, "server_tool_use")
|
||||
and get_web_search_requests(usage.server_tool_use) is not None
|
||||
or (
|
||||
hasattr(usage, "prompt_tokens_details")
|
||||
and usage.prompt_tokens_details is not None
|
||||
and isinstance(usage.prompt_tokens_details, PromptTokensDetailsWrapper)
|
||||
and hasattr(usage.prompt_tokens_details, "web_search_requests")
|
||||
and usage.prompt_tokens_details.web_search_requests is not None
|
||||
)
|
||||
if get_web_search_requests_from_usage(usage) is not None or (
|
||||
hasattr(usage, "prompt_tokens_details")
|
||||
and usage.prompt_tokens_details is not None
|
||||
and isinstance(usage.prompt_tokens_details, PromptTokensDetailsWrapper)
|
||||
and hasattr(usage.prompt_tokens_details, "web_search_requests")
|
||||
and usage.prompt_tokens_details.web_search_requests is not None
|
||||
):
|
||||
return True
|
||||
if _usage_reports_server_side_web_search_calls(usage):
|
||||
|
|
|
|||
|
|
@ -92,6 +92,16 @@ def get_web_search_requests(server_tool_use: Any) -> int | None:
|
|||
return getattr(server_tool_use, "web_search_requests", None)
|
||||
|
||||
|
||||
def get_web_search_requests_from_usage(usage: Usage) -> int | None:
|
||||
"""Read ``web_search_requests`` from a ``Usage``'s ``server_tool_use``.
|
||||
|
||||
``Usage`` deletes unset optional fields from ``__dict__`` (see
|
||||
``SafeAttributeModel``), so direct attribute access can raise
|
||||
``AttributeError``; ``getattr`` with a default is required here.
|
||||
"""
|
||||
return get_web_search_requests(getattr(usage, "server_tool_use", None))
|
||||
|
||||
|
||||
def _is_above_128k(tokens: float) -> bool:
|
||||
if tokens > 128000:
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -955,6 +955,7 @@ class RealTimeStreaming:
|
|||
transcript = event.get("transcript", "")
|
||||
self._collect_user_input_from_backend_event(cast(dict, event))
|
||||
self.store_message(event_str)
|
||||
self._capture_transcription_usage(event)
|
||||
await self._send_event_to_client(event, event_str)
|
||||
blocked = await self.run_realtime_guardrails(
|
||||
cast(str, transcript),
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import json
|
|||
from typing import Any, Final
|
||||
|
||||
import litellm
|
||||
from litellm._logging import verbose_logger
|
||||
from litellm.constants import _DEFAULT_TTL_FOR_HTTPX_CLIENTS
|
||||
|
||||
from ...caching import InMemoryCache
|
||||
|
|
@ -46,6 +47,15 @@ class LangfuseInMemoryCache(InMemoryCache):
|
|||
_created_langfuse_logger.Langfuse.flush()
|
||||
_created_langfuse_logger.Langfuse.shutdown()
|
||||
|
||||
# Loggers with a periodic flush task (e.g. NewRelicMetricsLogger) expose
|
||||
# stop() so eviction actually ends the task instead of leaking it.
|
||||
_evicted_stop: Final = getattr(self.cache_dict[key], "stop", None)
|
||||
if callable(_evicted_stop):
|
||||
try:
|
||||
_evicted_stop()
|
||||
except Exception: # noqa: BLE001 # a failing stop() must not block eviction
|
||||
verbose_logger.debug("DynamicLoggingCache: stop() raised during eviction", exc_info=True)
|
||||
|
||||
#########################################################
|
||||
# Call parent class to remove key from cache
|
||||
#########################################################
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from pydantic import BaseModel, ValidationError
|
|||
from litellm.litellm_core_utils.llm_cost_calc.utils import (
|
||||
generic_cost_per_token,
|
||||
get_provider_specific_geo_multiplier,
|
||||
get_web_search_requests,
|
||||
get_web_search_requests_from_usage,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -104,7 +104,7 @@ def get_cost_for_anthropic_web_search(
|
|||
|
||||
if usage is None:
|
||||
return 0.0
|
||||
web_search_requests: Final = get_web_search_requests(getattr(usage, "server_tool_use", None))
|
||||
web_search_requests: Final = get_web_search_requests_from_usage(usage)
|
||||
if web_search_requests is None:
|
||||
return 0.0
|
||||
|
||||
|
|
|
|||
|
|
@ -1358,12 +1358,10 @@ class LiteLLMAnthropicMessagesAdapter:
|
|||
@classmethod
|
||||
def _get_web_search_request_count(cls, usage: Usage) -> int:
|
||||
from litellm.litellm_core_utils.llm_cost_calc.utils import (
|
||||
get_web_search_requests,
|
||||
get_web_search_requests_from_usage,
|
||||
)
|
||||
|
||||
from_server_tool_use: Final = cls._positive_int(
|
||||
get_web_search_requests(getattr(usage, "server_tool_use", None))
|
||||
)
|
||||
from_server_tool_use: Final = cls._positive_int(get_web_search_requests_from_usage(usage))
|
||||
if from_server_tool_use > 0:
|
||||
return from_server_tool_use
|
||||
return cls._first_positive_prompt_tokens_detail_value(usage, ("web_search_requests",))
|
||||
|
|
|
|||
|
|
@ -1434,9 +1434,12 @@ class BaseAWSLLM:
|
|||
data: str | bytes,
|
||||
headers: dict,
|
||||
api_key: str | None = None,
|
||||
supports_bearer_token: bool = True,
|
||||
) -> AWSPreparedRequest:
|
||||
if api_key is not None:
|
||||
aws_bearer_token: str | None = api_key
|
||||
if not supports_bearer_token:
|
||||
aws_bearer_token: str | None = None
|
||||
elif api_key is not None:
|
||||
aws_bearer_token = api_key
|
||||
else:
|
||||
aws_bearer_token = get_secret_str("AWS_BEARER_TOKEN_BEDROCK")
|
||||
|
||||
|
|
|
|||
|
|
@ -138,11 +138,6 @@ class BedrockRerankHandler(BaseAWSLLM):
|
|||
data: dict,
|
||||
optional_params: dict,
|
||||
) -> BedrockPreparedRequest:
|
||||
try:
|
||||
from botocore.auth import SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
except ImportError:
|
||||
raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.")
|
||||
boto3_credentials_info: Final = self._get_boto_credentials_from_optional_params(optional_params, model)
|
||||
|
||||
### SET RUNTIME ENDPOINT ###
|
||||
|
|
@ -153,24 +148,21 @@ class BedrockRerankHandler(BaseAWSLLM):
|
|||
)
|
||||
proxy_endpoint_url = proxy_endpoint_url.replace("bedrock-runtime", "bedrock-agent-runtime")
|
||||
proxy_endpoint_url = f"{proxy_endpoint_url}/rerank"
|
||||
sigv4: Final = SigV4Auth(
|
||||
boto3_credentials_info.credentials,
|
||||
"bedrock",
|
||||
boto3_credentials_info.aws_region_name,
|
||||
)
|
||||
# Make POST Request
|
||||
body: Final = json.dumps(data).encode("utf-8")
|
||||
|
||||
body: Final = json.dumps(data).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if extra_headers is not None:
|
||||
headers = {"Content-Type": "application/json", **extra_headers}
|
||||
request: Final = AWSRequest(method="POST", url=proxy_endpoint_url, data=body, headers=headers)
|
||||
sigv4.add_auth(request)
|
||||
if (
|
||||
extra_headers is not None and "Authorization" in extra_headers
|
||||
): # prevent sigv4 from overwriting the auth header
|
||||
request.headers["Authorization"] = extra_headers["Authorization"]
|
||||
prepped: Final = request.prepare()
|
||||
|
||||
prepped: Final = self.get_request_headers(
|
||||
credentials=boto3_credentials_info.credentials,
|
||||
aws_region_name=boto3_credentials_info.aws_region_name,
|
||||
extra_headers=extra_headers,
|
||||
endpoint_url=proxy_endpoint_url,
|
||||
data=body,
|
||||
headers=headers,
|
||||
supports_bearer_token=False,
|
||||
)
|
||||
|
||||
return BedrockPreparedRequest(
|
||||
endpoint_url=proxy_endpoint_url,
|
||||
|
|
|
|||
0
litellm/llms/gemini/audio_transcription/__init__.py
Normal file
0
litellm/llms/gemini/audio_transcription/__init__.py
Normal file
250
litellm/llms/gemini/audio_transcription/transformation.py
Normal file
250
litellm/llms/gemini/audio_transcription/transformation.py
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
import base64
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Final
|
||||
|
||||
from httpx import Headers, Response
|
||||
|
||||
from litellm.litellm_core_utils.audio_utils.utils import (
|
||||
normalize_transcription_language_to_bcp47,
|
||||
process_audio_file,
|
||||
)
|
||||
from litellm.llms.base_llm.audio_transcription.transformation import (
|
||||
AudioTranscriptionRequestData,
|
||||
BaseAudioTranscriptionConfig,
|
||||
)
|
||||
from litellm.llms.base_llm.chat.transformation import BaseLLMException
|
||||
from litellm.llms.gemini.common_utils import GeminiError, GeminiModelInfo
|
||||
from litellm.types.llms.gemini_audio_transcription import (
|
||||
GeminiTranscriptionAudioInput,
|
||||
GeminiTranscriptionConfig,
|
||||
GeminiTranscriptionInteractionRequest,
|
||||
GeminiTranscriptionInteractionResponse,
|
||||
GeminiTranscriptionWordAnnotation,
|
||||
)
|
||||
from litellm.types.llms.openai import (
|
||||
AllMessageValues,
|
||||
OpenAIAudioTranscriptionOptionalParams,
|
||||
)
|
||||
from litellm.types.utils import (
|
||||
FileTypes,
|
||||
TranscriptionResponse,
|
||||
TranscriptionUsageInputTokenDetailsObject,
|
||||
TranscriptionUsageTokensObject,
|
||||
)
|
||||
|
||||
INTERACTIONS_API_REVISION: Final = "2026-05-20"
|
||||
WORD_INFO_ANNOTATION_TYPE: Final = "word_info"
|
||||
|
||||
|
||||
class GeminiAudioTranscriptionConfig(BaseAudioTranscriptionConfig):
|
||||
"""
|
||||
Maps OpenAI /v1/audio/transcriptions onto the Gemini Interactions API
|
||||
(POST /v1beta/interactions) for transcription models like
|
||||
gemini-3.5-transcribe. https://ai.google.dev/gemini-api/docs/transcribe
|
||||
"""
|
||||
|
||||
def get_supported_openai_params(
|
||||
self, model: str
|
||||
) -> list[OpenAIAudioTranscriptionOptionalParams]: # mutable-ok: BaseAudioTranscriptionConfig signature
|
||||
return ["language", "response_format", "timestamp_granularities"] # mutable-ok: base contract returns a list
|
||||
|
||||
def map_openai_params(
|
||||
self,
|
||||
non_default_params: Mapping[str, object],
|
||||
optional_params: Mapping[str, object],
|
||||
model: str,
|
||||
drop_params: bool,
|
||||
) -> dict: # mutable-ok: BaseAudioTranscriptionConfig signature
|
||||
supported_params: Final = frozenset(self.get_supported_openai_params(model))
|
||||
accepted: Final = tuple((k, v) for k, v in non_default_params.items() if k in supported_params)
|
||||
return dict((*optional_params.items(), *accepted)) # mutable-ok: base contract returns a plain dict
|
||||
|
||||
def get_error_class(
|
||||
self,
|
||||
error_message: str,
|
||||
status_code: int,
|
||||
headers: dict | Headers, # mutable-ok: base signature and BaseLLMException take dict | Headers
|
||||
) -> BaseLLMException:
|
||||
return GeminiError(status_code=status_code, message=error_message, headers=headers)
|
||||
|
||||
def validate_environment(
|
||||
self,
|
||||
headers: Mapping[str, str],
|
||||
model: str,
|
||||
messages: Sequence[AllMessageValues],
|
||||
optional_params: Mapping[str, object],
|
||||
litellm_params: Mapping[str, object],
|
||||
api_key: str | None = None,
|
||||
api_base: str | None = None,
|
||||
) -> dict: # mutable-ok: BaseAudioTranscriptionConfig signature
|
||||
resolved_api_key: Final = GeminiModelInfo.get_api_key(api_key)
|
||||
if not resolved_api_key:
|
||||
raise GeminiError(
|
||||
status_code=401,
|
||||
message="Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable.",
|
||||
)
|
||||
return { # mutable-ok: the http handler passes these headers straight to httpx
|
||||
**headers,
|
||||
"Content-Type": "application/json",
|
||||
"x-goog-api-key": resolved_api_key,
|
||||
"Api-Revision": INTERACTIONS_API_REVISION,
|
||||
}
|
||||
|
||||
def get_complete_url(
|
||||
self,
|
||||
api_base: str | None,
|
||||
api_key: str | None,
|
||||
model: str,
|
||||
optional_params: Mapping[str, object],
|
||||
litellm_params: Mapping[str, object],
|
||||
stream: bool | None = None,
|
||||
) -> str:
|
||||
resolved_api_base: Final = GeminiModelInfo.get_api_base(api_base)
|
||||
return f"{resolved_api_base}/v1beta/interactions"
|
||||
|
||||
def transform_audio_transcription_request(
|
||||
self,
|
||||
model: str,
|
||||
audio_file: FileTypes,
|
||||
optional_params: Mapping[str, object],
|
||||
litellm_params: Mapping[str, object],
|
||||
) -> AudioTranscriptionRequestData:
|
||||
processed_audio: Final = process_audio_file(audio_file)
|
||||
audio_input: Final = GeminiTranscriptionAudioInput(
|
||||
type="audio",
|
||||
data=base64.b64encode(processed_audio.file_content).decode("utf-8"),
|
||||
mime_type=processed_audio.content_type,
|
||||
)
|
||||
request: Final = _build_interaction_request(
|
||||
model=model,
|
||||
audio_input=audio_input,
|
||||
transcription_config=_build_transcription_config(optional_params),
|
||||
)
|
||||
return AudioTranscriptionRequestData(data=dict(request)) # mutable-ok: AudioTranscriptionRequestData wants dict
|
||||
|
||||
def transform_audio_transcription_response(
|
||||
self,
|
||||
raw_response: Response,
|
||||
) -> TranscriptionResponse:
|
||||
try:
|
||||
response_json: Final = raw_response.json()
|
||||
except ValueError:
|
||||
raise GeminiError(
|
||||
status_code=raw_response.status_code,
|
||||
message=f"Received non-JSON response from Gemini Interactions API: {raw_response.text}",
|
||||
)
|
||||
parsed: Final = GeminiTranscriptionInteractionResponse.model_validate(response_json)
|
||||
if parsed.status != "completed":
|
||||
raise GeminiError(
|
||||
status_code=raw_response.status_code,
|
||||
message=f"Gemini transcription interaction did not complete (status={parsed.status}): {raw_response.text}",
|
||||
)
|
||||
text_contents: Final = tuple(
|
||||
content
|
||||
for step in parsed.steps
|
||||
for content in step.content
|
||||
if content.type == "text" and content.text is not None
|
||||
)
|
||||
response: Final = TranscriptionResponse(text=" ".join(content.text or "" for content in text_contents))
|
||||
response["task"] = "transcribe"
|
||||
words: Final = tuple(
|
||||
word
|
||||
for content in text_contents
|
||||
for annotation in content.annotations
|
||||
if (word := _annotation_to_word(annotation)) is not None
|
||||
)
|
||||
if words:
|
||||
response["words"] = list(words) # mutable-ok: verbose_json words is a JSON array
|
||||
last_word_end: Final = words[-1].get("end")
|
||||
if last_word_end is not None:
|
||||
response["duration"] = last_word_end
|
||||
if parsed.usage is not None:
|
||||
audio_tokens: Final = sum(
|
||||
by_modality.tokens
|
||||
for by_modality in parsed.usage.input_tokens_by_modality
|
||||
if by_modality.modality == "audio"
|
||||
)
|
||||
response.usage = TranscriptionUsageTokensObject(
|
||||
type="tokens",
|
||||
input_tokens=parsed.usage.total_input_tokens,
|
||||
output_tokens=parsed.usage.total_output_tokens,
|
||||
total_tokens=parsed.usage.total_tokens,
|
||||
input_token_details=TranscriptionUsageInputTokenDetailsObject(
|
||||
audio_tokens=audio_tokens,
|
||||
text_tokens=parsed.usage.total_input_tokens - audio_tokens,
|
||||
),
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
_EMPTY_TRANSCRIPTION_CONFIG: Final[GeminiTranscriptionConfig] = {}
|
||||
_WORD_TIMESTAMP_CONFIG: Final[GeminiTranscriptionConfig] = {
|
||||
"mode": {
|
||||
"type": "verbatim",
|
||||
"timestamp_granularities": ("word",),
|
||||
"diarization_mode": "speaker",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_interaction_request(
|
||||
model: str,
|
||||
audio_input: GeminiTranscriptionAudioInput,
|
||||
transcription_config: GeminiTranscriptionConfig,
|
||||
) -> GeminiTranscriptionInteractionRequest:
|
||||
if not transcription_config:
|
||||
bare_request: Final[GeminiTranscriptionInteractionRequest] = {
|
||||
"model": model.removeprefix("gemini/"),
|
||||
"input": (audio_input,),
|
||||
}
|
||||
return bare_request
|
||||
configured_request: Final[GeminiTranscriptionInteractionRequest] = {
|
||||
"model": model.removeprefix("gemini/"),
|
||||
"input": (audio_input,),
|
||||
"generation_config": {"transcription_config": transcription_config},
|
||||
}
|
||||
return configured_request
|
||||
|
||||
|
||||
def _language_config(language: object) -> GeminiTranscriptionConfig:
|
||||
if not isinstance(language, str) or not language:
|
||||
return _EMPTY_TRANSCRIPTION_CONFIG
|
||||
language_config: Final[GeminiTranscriptionConfig] = {
|
||||
"language_codes": (normalize_transcription_language_to_bcp47(language),),
|
||||
}
|
||||
return language_config
|
||||
|
||||
|
||||
def _timestamp_config(timestamp_granularities: object) -> GeminiTranscriptionConfig:
|
||||
if isinstance(timestamp_granularities, list) and "word" in timestamp_granularities:
|
||||
return _WORD_TIMESTAMP_CONFIG
|
||||
return _EMPTY_TRANSCRIPTION_CONFIG
|
||||
|
||||
|
||||
def _build_transcription_config(optional_params: Mapping[str, object]) -> GeminiTranscriptionConfig:
|
||||
transcription_config: Final[GeminiTranscriptionConfig] = {
|
||||
**_language_config(optional_params.get("language")),
|
||||
**_timestamp_config(optional_params.get("timestamp_granularities")),
|
||||
}
|
||||
return transcription_config
|
||||
|
||||
|
||||
def _annotation_to_word(annotation: GeminiTranscriptionWordAnnotation) -> Mapping[str, str | float] | None:
|
||||
if annotation.type != WORD_INFO_ANNOTATION_TYPE or annotation.text is None:
|
||||
return None
|
||||
entries: Final = (
|
||||
("word", annotation.text),
|
||||
("start", _parse_offset_seconds(annotation.start_offset)),
|
||||
("end", _parse_offset_seconds(annotation.end_offset)),
|
||||
("speaker", annotation.speaker),
|
||||
)
|
||||
return {key: value for key, value in entries if value is not None} # mutable-ok: word entries serialize to JSON
|
||||
|
||||
|
||||
def _parse_offset_seconds(offset: str | None) -> float | None:
|
||||
if offset is None or not offset.endswith("s"):
|
||||
return None
|
||||
try:
|
||||
return float(offset[:-1])
|
||||
except ValueError:
|
||||
return None
|
||||
|
|
@ -39,7 +39,9 @@ def cost_per_web_search_request(usage: "Usage", model_info: "ModelInfo") -> floa
|
|||
``model_info`` when available, falling back to $0.035 for models not
|
||||
yet updated in the pricing JSON.
|
||||
"""
|
||||
from litellm.litellm_core_utils.llm_cost_calc.utils import get_web_search_requests
|
||||
from litellm.litellm_core_utils.llm_cost_calc.utils import (
|
||||
get_web_search_requests_from_usage,
|
||||
)
|
||||
from litellm.types.utils import PromptTokensDetailsWrapper
|
||||
|
||||
_DEFAULT_COST: Final = 35e-3
|
||||
|
|
@ -57,7 +59,7 @@ def cost_per_web_search_request(usage: "Usage", model_info: "ModelInfo") -> floa
|
|||
)
|
||||
else None
|
||||
)
|
||||
requests_from_server_tool_use: Final = get_web_search_requests(getattr(usage, "server_tool_use", None))
|
||||
requests_from_server_tool_use: Final = get_web_search_requests_from_usage(usage)
|
||||
number_of_web_search_requests: Final = requests_from_prompt_details or requests_from_server_tool_use or 0
|
||||
|
||||
billing_mode: Final = model_info.get("web_search_billing_unit") or "per_prompt"
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ This file contains the transformation logic for the Gemini realtime API.
|
|||
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Mapping
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, Final, cast
|
||||
|
||||
import litellm
|
||||
|
|
@ -53,6 +53,7 @@ from litellm.types.llms.vertex_ai import (
|
|||
)
|
||||
from litellm.types.realtime import (
|
||||
ALL_DELTA_TYPES,
|
||||
RealtimeInputAudioTranscriptionUsage,
|
||||
RealtimeModalityResponseTransformOutput,
|
||||
RealtimeResponseTransformInput,
|
||||
RealtimeResponseTypedDict,
|
||||
|
|
@ -95,6 +96,18 @@ def _gemini_live_speech_config(voice: object) -> Mapping[str, object] | None:
|
|||
return VertexGeminiConfig()._map_audio_params({"voice": voice})
|
||||
|
||||
|
||||
# Google bills Live transcription at an estimated 25 audio tokens/sec of input and
|
||||
# 175 text tokens/min of output (ai.google.dev/gemini-api/docs/pricing).
|
||||
GEMINI_LIVE_TRANSCRIBE_AUDIO_TOKENS_PER_SECOND: Final = 25
|
||||
GEMINI_LIVE_TRANSCRIBE_OUTPUT_TEXT_TOKENS_PER_MINUTE: Final = 175
|
||||
PCM16_INPUT_AUDIO_BYTES_PER_SECOND: Final = 48000
|
||||
|
||||
|
||||
def _base64_decoded_byte_count(data: str) -> int:
|
||||
padding: Final = 2 if data.endswith("==") else 1 if data.endswith("=") else 0
|
||||
return max(len(data) * 3 // 4 - padding, 0)
|
||||
|
||||
|
||||
class GeminiRealtimeConfig(BaseRealtimeConfig):
|
||||
_TOOL_CALL_ID_TO_NAME_MAX = 256 # LRU cap for call_id→name mapping
|
||||
|
||||
|
|
@ -104,6 +117,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
# Gemini Live sometimes emits usageMetadata in a standalone frame between
|
||||
# turns; buffer it here so the next response.done carries the token counts.
|
||||
self._pending_usage_metadata: dict | None = None
|
||||
self._unbilled_input_audio_bytes: int = 0
|
||||
|
||||
def is_setup_message(self, msg_obj: dict) -> bool:
|
||||
return "setup" in msg_obj
|
||||
|
|
@ -384,17 +398,25 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
return bool(entry.get("gemini_native_audio") or entry.get("gemini_audio_only_live"))
|
||||
|
||||
@staticmethod
|
||||
def _coerce_response_modalities(model: str, modalities: list[Any]) -> list[str]:
|
||||
"""Map unsupported TEXT responseModalities to AUDIO for audio-only Live models."""
|
||||
normalized: Final = [
|
||||
def _is_text_only_live_model(model: str) -> bool:
|
||||
return GeminiRealtimeConfig._model_cost_entry(model).get("mode") == "audio_transcription"
|
||||
|
||||
@staticmethod
|
||||
def _default_response_modality(model: str) -> GeminiResponseModalities:
|
||||
return "TEXT" if GeminiRealtimeConfig._is_text_only_live_model(model) else "AUDIO"
|
||||
|
||||
@staticmethod
|
||||
def _coerce_response_modalities(model: str, modalities: Sequence[Any]) -> tuple[str, ...]:
|
||||
"""Swap responseModalities a Live model cannot produce: TEXT to AUDIO for
|
||||
audio-only models, AUDIO to TEXT for text-only ones (e.g. transcribe-live)."""
|
||||
normalized: Final = tuple(
|
||||
modality.upper() if isinstance(modality, str) else str(modality).upper() for modality in modalities
|
||||
]
|
||||
if not GeminiRealtimeConfig._is_audio_only_live_model(model):
|
||||
return normalized
|
||||
if "TEXT" not in normalized:
|
||||
return normalized
|
||||
without_text: Final = [modality for modality in normalized if modality != "TEXT"]
|
||||
return without_text if without_text else ["AUDIO"]
|
||||
)
|
||||
if GeminiRealtimeConfig._is_audio_only_live_model(model) and "TEXT" in normalized:
|
||||
return tuple(modality for modality in normalized if modality != "TEXT") or ("AUDIO",)
|
||||
if GeminiRealtimeConfig._is_text_only_live_model(model) and "AUDIO" in normalized:
|
||||
return tuple(modality for modality in normalized if modality != "AUDIO") or ("TEXT",)
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _finalize_gemini_live_setup(model: str, setup: dict[str, Any]) -> dict[str, Any]:
|
||||
|
|
@ -436,7 +458,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
|
||||
if session_configuration_request is None:
|
||||
generation_config: Final = new_overrides.setdefault("generationConfig", {})
|
||||
generation_config.setdefault("responseModalities", ["AUDIO"])
|
||||
generation_config.setdefault("responseModalities", [GeminiRealtimeConfig._default_response_modality(model)])
|
||||
new_overrides.setdefault("inputAudioTranscription", {})
|
||||
new_overrides["model"] = f"models/{model}"
|
||||
verbose_logger.debug("Gemini Realtime: Sending initial setup with tools to backend")
|
||||
|
|
@ -558,9 +580,10 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
return self._handle_conversation_item(json_message)
|
||||
|
||||
if msg_type == "input_audio_buffer.append":
|
||||
realtime_input_dict["audio"] = HttpxBlobType(
|
||||
mimeType=self.get_audio_mime_type(), data=json_message["audio"]
|
||||
)
|
||||
audio_b64: Final = json_message["audio"]
|
||||
if isinstance(audio_b64, str):
|
||||
self._unbilled_input_audio_bytes += _base64_decoded_byte_count(audio_b64)
|
||||
realtime_input_dict["audio"] = HttpxBlobType(mimeType=self.get_audio_mime_type(), data=audio_b64)
|
||||
|
||||
realtime_input_dict = cast(
|
||||
BidiGenerateContentRealtimeInput,
|
||||
|
|
@ -1151,6 +1174,23 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
raise ValueError(f"Unknown openai event: {key}, value: {value}")
|
||||
return openai_event
|
||||
|
||||
def _consume_input_transcription_usage_estimate(self, model: str) -> RealtimeInputAudioTranscriptionUsage | None:
|
||||
"""Gemini Live sends no usageMetadata for transcribe sessions; estimate billing from streamed audio duration."""
|
||||
if self._unbilled_input_audio_bytes <= 0 or not self._is_text_only_live_model(model):
|
||||
return None
|
||||
audio_seconds: Final = self._unbilled_input_audio_bytes / PCM16_INPUT_AUDIO_BYTES_PER_SECOND
|
||||
self._unbilled_input_audio_bytes = 0
|
||||
audio_tokens: Final = round(audio_seconds * GEMINI_LIVE_TRANSCRIBE_AUDIO_TOKENS_PER_SECOND)
|
||||
output_tokens: Final = round(audio_seconds * GEMINI_LIVE_TRANSCRIBE_OUTPUT_TEXT_TOKENS_PER_MINUTE / 60)
|
||||
usage: Final[RealtimeInputAudioTranscriptionUsage] = {
|
||||
"type": "tokens",
|
||||
"input_tokens": audio_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"total_tokens": audio_tokens + output_tokens,
|
||||
"input_token_details": {"text_tokens": 0, "audio_tokens": audio_tokens},
|
||||
}
|
||||
return usage
|
||||
|
||||
def transform_realtime_response(
|
||||
self,
|
||||
message: str | bytes,
|
||||
|
|
@ -1190,6 +1230,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
if isinstance(server_content, dict):
|
||||
input_tx: Final = server_content.get("inputTranscription")
|
||||
if isinstance(input_tx, dict) and input_tx.get("text"):
|
||||
transcription_usage: Final = self._consume_input_transcription_usage_estimate(model)
|
||||
returned_message.append(
|
||||
cast(
|
||||
OpenAIRealtimeEvents,
|
||||
|
|
@ -1199,6 +1240,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
"transcript": input_tx["text"],
|
||||
"item_id": f"item_{uuid.uuid4()}",
|
||||
"content_index": 0,
|
||||
**({} if transcription_usage is None else {"usage": transcription_usage}),
|
||||
},
|
||||
)
|
||||
)
|
||||
|
|
@ -1235,6 +1277,12 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
)
|
||||
)
|
||||
|
||||
# Transcription-only models emit generationComplete with no prior
|
||||
# modelTurn delta; there is no started OpenAI response to close, so
|
||||
# drop it and let siblings (turnComplete, usageMetadata) process.
|
||||
if current_delta_type is None and "modelTurn" not in server_content:
|
||||
server_content.pop("generationComplete", None)
|
||||
|
||||
# Mark transcription-only serverContent as handled so the main loop
|
||||
# skips it; sibling keys like toolCall are still processed below.
|
||||
_model_content_keys: Final = {
|
||||
|
|
@ -1583,7 +1631,9 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
|
|||
```
|
||||
"""
|
||||
|
||||
response_modalities: Final[list[GeminiResponseModalities]] = ["AUDIO"]
|
||||
response_modalities: Final[list[GeminiResponseModalities]] = [
|
||||
GeminiRealtimeConfig._default_response_modality(model)
|
||||
]
|
||||
output_audio_transcription: Final = False
|
||||
# if "audio" in model: ## UNCOMMENT THIS WHEN AUDIO IS SUPPORTED
|
||||
# output_audio_transcription = True
|
||||
|
|
|
|||
|
|
@ -51340,6 +51340,47 @@
|
|||
"supports_audio_output": true,
|
||||
"tpm": 250000
|
||||
},
|
||||
"gemini/gemini-3.5-transcribe": {
|
||||
"input_cost_per_audio_token": 2e-06,
|
||||
"input_cost_per_token": 2e-06,
|
||||
"litellm_provider": "gemini",
|
||||
"mode": "audio_transcription",
|
||||
"output_cost_per_token": 1.2e-05,
|
||||
"source": "https://ai.google.dev/gemini-api/docs/pricing",
|
||||
"supported_endpoints": [
|
||||
"/v1/audio/transcriptions"
|
||||
],
|
||||
"supported_modalities": [
|
||||
"text",
|
||||
"audio"
|
||||
],
|
||||
"supported_output_modalities": [
|
||||
"text"
|
||||
],
|
||||
"supports_audio_input": true,
|
||||
"tpm": 800000,
|
||||
"rpm": 2000
|
||||
},
|
||||
"gemini/gemini-3.5-transcribe-live": {
|
||||
"input_cost_per_audio_token": 3.5e-06,
|
||||
"input_cost_per_token": 3.5e-06,
|
||||
"litellm_provider": "gemini",
|
||||
"mode": "audio_transcription",
|
||||
"output_cost_per_token": 2.1e-05,
|
||||
"source": "https://ai.google.dev/gemini-api/docs/pricing",
|
||||
"supported_endpoints": [
|
||||
"/v1/realtime"
|
||||
],
|
||||
"supported_modalities": [
|
||||
"audio"
|
||||
],
|
||||
"supported_output_modalities": [
|
||||
"text"
|
||||
],
|
||||
"supports_audio_input": true,
|
||||
"tpm": 250000,
|
||||
"rpm": 10
|
||||
},
|
||||
"perplexity/pplx-embed-context-v1-0.6b": {
|
||||
"input_cost_per_token": 8e-09,
|
||||
"litellm_provider": "perplexity",
|
||||
|
|
|
|||
|
|
@ -239,5 +239,6 @@ def resolve_bridge_envelope(
|
|||
if opened.identity.server_id != expected_server_id:
|
||||
return BridgeEnvelopeInvalid()
|
||||
grant: Final = opened.grant
|
||||
upstream_authorization: Final = f"{grant.token_type} {grant.access_token.get_secret_value()}"
|
||||
authorization_scheme: Final = "Bearer" if grant.token_type.lower() == "bearer" else grant.token_type
|
||||
upstream_authorization: Final = f"{authorization_scheme} {grant.access_token.get_secret_value()}"
|
||||
return BridgeEnvelopeAdmitted(identity=opened.identity, upstream_authorization=SecretStr(upstream_authorization))
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -3,18 +3,27 @@ Per-feature OpenAPI snapshot for lazy-loaded routers.
|
|||
|
||||
The committed JSON is generated by `python -m litellm.proxy._lazy_openapi_snapshot`
|
||||
and consumed at runtime so /openapi.json can show full route info for unloaded
|
||||
features without importing them. No CI job regenerates this file; drift surfaces
|
||||
only indirectly through check-ui-api-types.yml, which rebuilds schema.d.ts from
|
||||
app.openapi() with the committed snapshot injected. After changing any lazily
|
||||
loaded route or this generator, rerun the module and commit the JSON, then run
|
||||
`npm run gen:api` in ui/litellm-dashboard and commit schema.d.ts.
|
||||
features without importing them. check-ui-api-types.yml (mirrored locally by
|
||||
`make check`) regenerates this file and fails when the committed copy differs,
|
||||
then rebuilds schema.d.ts from app.openapi() with the snapshot injected. After
|
||||
changing any lazily loaded route or this generator, rerun the module and commit
|
||||
the JSON, then run `npm run gen:api` in ui/litellm-dashboard and commit schema.d.ts.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from typing_extensions import ReadOnly, TypedDict
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import FastAPI
|
||||
|
||||
from litellm.proxy._lazy_features import LazyFeature
|
||||
|
||||
SNAPSHOT_FILE: Final = Path(__file__).parent / "_lazy_openapi_snapshot.json"
|
||||
HTTP_METHOD_SUFFIXES: Final = {
|
||||
|
|
@ -83,51 +92,84 @@ def _normalize_operation_ids(paths: dict[str, dict]) -> None:
|
|||
break
|
||||
|
||||
|
||||
def generate_snapshot() -> dict[str, dict]:
|
||||
class SnapshotFragment(TypedDict):
|
||||
paths: ReadOnly[Mapping[str, Mapping[str, object]]]
|
||||
components: ReadOnly[Mapping[str, Mapping[str, object]]]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SnapshotResult:
|
||||
fragments: Mapping[str, SnapshotFragment]
|
||||
skipped: tuple[str, ...]
|
||||
|
||||
|
||||
def _register_feature(app: "FastAPI", feat: "LazyFeature") -> str | None:
|
||||
import importlib
|
||||
|
||||
try:
|
||||
feat.register_fn(app, importlib.import_module(feat.module_path))
|
||||
except Exception as exc:
|
||||
sys.stderr.write(f"warning: skip {feat.name}: {exc}\n")
|
||||
return feat.name
|
||||
return None
|
||||
|
||||
|
||||
def _feature_fragment(app: "FastAPI", feat: "LazyFeature", used_operation_ids: set[str]) -> SnapshotFragment | None:
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
|
||||
from litellm.proxy.proxy_server import ensure_unique_openapi_operation_ids
|
||||
|
||||
feat_routes: Final = [r for r in app.routes if feat.matches(getattr(r, "path", ""))]
|
||||
if not feat_routes:
|
||||
return None
|
||||
_stabilize_multi_method_route_ids(feat_routes)
|
||||
full: Final = get_openapi(title=app.title, version=app.version, routes=feat_routes)
|
||||
paths: Final = full.get("paths", {})
|
||||
_normalize_operation_ids(paths)
|
||||
# Group all of a feature's routes under one tag.
|
||||
for path_ops in paths.values():
|
||||
for method, op in path_ops.items():
|
||||
if isinstance(op, dict):
|
||||
operation_id = op.get("operationId")
|
||||
if isinstance(operation_id, str):
|
||||
for suffix in HTTP_METHOD_SUFFIXES:
|
||||
if operation_id.endswith(f"_{suffix}"):
|
||||
op["operationId"] = operation_id[: -len(suffix)] + method
|
||||
break
|
||||
op["tags"] = [feat.name]
|
||||
unique: Final = ensure_unique_openapi_operation_ids(full, used_operation_ids)
|
||||
return {
|
||||
"paths": paths,
|
||||
"components": {"schemas": unique.get("components", {}).get("schemas", {})},
|
||||
}
|
||||
|
||||
|
||||
def generate_snapshot() -> SnapshotResult:
|
||||
from litellm.proxy._lazy_features import LAZY_FEATURES
|
||||
from litellm.proxy.proxy_server import app, ensure_unique_openapi_operation_ids
|
||||
from litellm.proxy.proxy_server import app
|
||||
|
||||
for feat in LAZY_FEATURES:
|
||||
try:
|
||||
module = importlib.import_module(feat.module_path)
|
||||
feat.register_fn(app, module)
|
||||
except Exception as exc:
|
||||
sys.stderr.write(f"warning: skip {feat.name}: {exc}\n")
|
||||
|
||||
fragments: Final[dict[str, dict]] = {}
|
||||
skipped: Final = tuple(name for feat in LAZY_FEATURES if (name := _register_feature(app, feat)) is not None)
|
||||
used_operation_ids: Final[set[str]] = set()
|
||||
for feat in LAZY_FEATURES:
|
||||
feat_routes = [r for r in app.routes if feat.matches(getattr(r, "path", ""))]
|
||||
if not feat_routes:
|
||||
continue
|
||||
_stabilize_multi_method_route_ids(feat_routes)
|
||||
full = get_openapi(title=app.title, version=app.version, routes=feat_routes)
|
||||
paths = full.get("paths", {})
|
||||
_normalize_operation_ids(paths)
|
||||
# Group all of a feature's routes under one tag.
|
||||
for path_ops in full.get("paths", {}).values():
|
||||
for method, op in path_ops.items():
|
||||
if isinstance(op, dict):
|
||||
operation_id = op.get("operationId")
|
||||
if isinstance(operation_id, str):
|
||||
for suffix in HTTP_METHOD_SUFFIXES:
|
||||
if operation_id.endswith(f"_{suffix}"):
|
||||
op["operationId"] = operation_id[: -len(suffix)] + method
|
||||
break
|
||||
op["tags"] = [feat.name]
|
||||
full = ensure_unique_openapi_operation_ids(full, used_operation_ids)
|
||||
fragments[feat.name] = {
|
||||
"paths": paths,
|
||||
"components": {"schemas": full.get("components", {}).get("schemas", {})},
|
||||
}
|
||||
return fragments
|
||||
fragments: Final = {
|
||||
feat.name: fragment
|
||||
for feat in LAZY_FEATURES
|
||||
if (fragment := _feature_fragment(app, feat, used_operation_ids)) is not None
|
||||
}
|
||||
return SnapshotResult(fragments=fragments, skipped=skipped)
|
||||
|
||||
|
||||
def main(snapshot_file: Path = SNAPSHOT_FILE, generate: Callable[[], SnapshotResult] = generate_snapshot) -> int:
|
||||
result: Final = generate()
|
||||
if result.skipped:
|
||||
sys.stderr.write(
|
||||
f"error: {len(result.skipped)} feature(s) failed to import, so their fragments would vanish from the "
|
||||
f"snapshot: {', '.join(result.skipped)}\n"
|
||||
)
|
||||
return 1
|
||||
snapshot_file.write_text(json.dumps(result.fragments, indent=2, sort_keys=True) + "\n")
|
||||
sys.stdout.write(f"wrote {len(result.fragments)} feature fragments to {snapshot_file}\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
fragments: Final = generate_snapshot()
|
||||
SNAPSHOT_FILE.write_text(json.dumps(fragments, indent=2, sort_keys=True) + "\n")
|
||||
sys.stdout.write(f"wrote {len(fragments)} feature fragments to {SNAPSHOT_FILE}\n")
|
||||
sys.exit(main())
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ from litellm.constants import (
|
|||
CONSUMED_REQUEST_TAGS_METADATA_KEY,
|
||||
INTERNAL_CALL_ORIGIN_METADATA_KEY,
|
||||
LITELLM_PROXY_MASTER_KEY_ALIAS,
|
||||
OTEL_SERVICE_NAME_METADATA_KEYS,
|
||||
PRE_CALL_EXECUTED_GUARDRAILS_KEY,
|
||||
SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY,
|
||||
)
|
||||
|
|
@ -2003,6 +2004,19 @@ async def add_litellm_data_to_request(
|
|||
_metadata_variable_name=_metadata_variable_name,
|
||||
)
|
||||
|
||||
# A key's OTel service name outranks its team's, so the key's values are
|
||||
# re-applied after the last-writer-wins team metadata merge above
|
||||
_key_otel_service_names: Final = {
|
||||
field: value
|
||||
for field, value in (key_metadata or {}).items()
|
||||
if field in OTEL_SERVICE_NAME_METADATA_KEYS and isinstance(value, str) and value.strip()
|
||||
}
|
||||
data = LiteLLMProxyRequestSetup.add_management_endpoint_metadata_to_request_metadata(
|
||||
data=data,
|
||||
management_endpoint_metadata=_key_otel_service_names,
|
||||
_metadata_variable_name=_metadata_variable_name,
|
||||
)
|
||||
|
||||
# Team spend, budget - used by prometheus.py
|
||||
data[_metadata_variable_name]["user_api_key_team_max_budget"] = user_api_key_dict.team_max_budget
|
||||
data[_metadata_variable_name]["user_api_key_team_spend"] = user_api_key_dict.team_spend
|
||||
|
|
|
|||
|
|
@ -808,6 +808,15 @@ def normalize_email(email: str | None) -> str | None:
|
|||
return email.lower() if isinstance(email, str) else email
|
||||
|
||||
|
||||
# Ordered highest to lowest privilege
|
||||
LITELLM_USER_ROLE_HIERARCHY: Final = (
|
||||
LitellmUserRoles.PROXY_ADMIN,
|
||||
LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
|
||||
LitellmUserRoles.INTERNAL_USER,
|
||||
LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
|
||||
)
|
||||
|
||||
|
||||
def determine_role_from_groups(
|
||||
user_groups: list[str],
|
||||
role_mappings: "RoleMappings",
|
||||
|
|
@ -832,19 +841,11 @@ def determine_role_from_groups(
|
|||
# No role mappings configured, return default_role
|
||||
return role_mappings.default_role
|
||||
|
||||
# Role hierarchy (highest to lowest)
|
||||
role_hierarchy: Final = [
|
||||
LitellmUserRoles.PROXY_ADMIN,
|
||||
LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
|
||||
LitellmUserRoles.INTERNAL_USER,
|
||||
LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
|
||||
]
|
||||
|
||||
# Convert user_groups to a set for efficient lookup
|
||||
user_groups_set: Final = set(user_groups) if isinstance(user_groups, list) else set()
|
||||
|
||||
# Find the highest privilege role the user belongs to
|
||||
for role in role_hierarchy:
|
||||
for role in LITELLM_USER_ROLE_HIERARCHY:
|
||||
if role in role_mappings.roles:
|
||||
role_groups = role_mappings.roles[role]
|
||||
if isinstance(role_groups, list) and user_groups_set.intersection(set(role_groups)):
|
||||
|
|
@ -4236,15 +4237,7 @@ class MicrosoftSSOHandler:
|
|||
verbose_proxy_logger.debug("Extracted app roles from id_token: %s", app_roles)
|
||||
|
||||
# Combine groups and app roles
|
||||
user_role: LitellmUserRoles | None = None
|
||||
if app_roles:
|
||||
# Check if any app role is a valid LitellmUserRoles
|
||||
for role_str in app_roles:
|
||||
role = get_litellm_user_role(role_str)
|
||||
if role is not None:
|
||||
user_role = role
|
||||
verbose_proxy_logger.debug("Found valid LitellmUserRoles '%s' in app_roles", role.value)
|
||||
break
|
||||
user_role: Final = MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles)
|
||||
|
||||
verbose_proxy_logger.debug("Combined team_ids (groups + app roles): %s", user_team_ids)
|
||||
|
||||
|
|
@ -4282,6 +4275,27 @@ class MicrosoftSSOHandler:
|
|||
verbose_proxy_logger.debug("Microsoft SSO OpenID Response: %s", openid_response)
|
||||
return openid_response
|
||||
|
||||
@staticmethod
|
||||
def get_user_role_from_app_roles(
|
||||
app_roles: Sequence[str] | None,
|
||||
) -> LitellmUserRoles | None:
|
||||
"""
|
||||
Resolve the one role LiteLLM stores for a user from their Entra app roles.
|
||||
|
||||
Entra does not guarantee `roles` claim ordering, so a user holding several app
|
||||
roles resolves to the highest privilege one rather than whichever the claim
|
||||
listed first. Roles the hierarchy does not rank (org_admin, team, customer)
|
||||
resolve by name to stay deterministic
|
||||
"""
|
||||
resolved: Final = frozenset(
|
||||
role for role in (get_litellm_user_role(role_str) for role_str in app_roles or ()) if role is not None
|
||||
)
|
||||
if not resolved:
|
||||
return None
|
||||
|
||||
ranked: Final = next((role for role in LITELLM_USER_ROLE_HIERARCHY if role in resolved), None)
|
||||
return ranked if ranked is not None else min(resolved, key=lambda role: role.value)
|
||||
|
||||
@staticmethod
|
||||
def get_app_roles_from_id_token(id_token: str | None) -> list[str]:
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -1045,6 +1045,21 @@ def _estimate_request_max_cost_for_model(
|
|||
return max(valid_estimates) if valid_estimates else None
|
||||
|
||||
|
||||
_TIER_OUTPUT_RATE_KEYS: Final = ("output_cost_per_token", "output_cost_per_reasoning_token")
|
||||
|
||||
|
||||
def _tier_output_rate(tier: Mapping[str, object], model_info: Mapping[str, object]) -> float:
|
||||
"""Output rate to reserve for a request billed at ``tier``.
|
||||
|
||||
A tier table that prices only input falls back to the model's own output rates when
|
||||
the request is billed, so reserving the tier's missing rate as 0 leaves every
|
||||
completion under-reserved. The reasoning-token share is unknown before the request
|
||||
runs, so the higher of the two rates is used either way.
|
||||
"""
|
||||
rates: Final = tier if any(key in tier for key in _TIER_OUTPUT_RATE_KEYS) else model_info
|
||||
return max(_to_float(rates.get(key)) or 0.0 for key in _TIER_OUTPUT_RATE_KEYS)
|
||||
|
||||
|
||||
def _max_cost_for_cost_info(
|
||||
request_body: dict,
|
||||
route: str,
|
||||
|
|
@ -1079,12 +1094,8 @@ def _max_cost_for_cost_info(
|
|||
if isinstance(tiered_pricing, list) and tiered_pricing:
|
||||
tier: Final = select_tier_for_input(tiered_pricing=tiered_pricing, input_tokens=estimated_input_tokens)
|
||||
if tier is not None:
|
||||
output_rate = max(
|
||||
tier_rate(tier, "output_cost_per_token"),
|
||||
tier_rate(tier, "output_cost_per_reasoning_token"),
|
||||
)
|
||||
return (estimated_input_tokens * tier_rate(tier, "input_cost_per_token")) + (
|
||||
output_tokens * output_multiplier * output_rate
|
||||
output_tokens * output_multiplier * _tier_output_rate(tier=tier, model_info=model_info)
|
||||
)
|
||||
|
||||
input_cost_per_token: Final = _to_float(model_info.get("input_cost_per_token"))
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ from typing_extensions import ReadOnly
|
|||
|
||||
import litellm
|
||||
from litellm._logging import verbose_proxy_logger
|
||||
from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
|
||||
from litellm.proxy._types import *
|
||||
from litellm.proxy._types import ProviderBudgetResponse, ProviderBudgetResponseObject
|
||||
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
|
||||
|
|
@ -54,6 +55,11 @@ router: Final = APIRouter()
|
|||
|
||||
SPEND_LOGS_PAGINATION_COUNT_CAP: Final = 10000
|
||||
|
||||
_INTERNAL_HEALTH_CHECK_API_KEYS: Final = (
|
||||
LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
|
||||
hash_token(token=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME),
|
||||
)
|
||||
|
||||
_RowT = TypeVar("_RowT")
|
||||
|
||||
|
||||
|
|
@ -2248,6 +2254,10 @@ async def ui_view_spend_logs(
|
|||
status_filter: str | None = fastapi.Query(
|
||||
default=None, description="Filter logs by status (e.g., success, failure)"
|
||||
),
|
||||
cache_hit_filter: str | None = fastapi.Query(
|
||||
default=None,
|
||||
description="Filter logs by cache state: 'hit' or 'miss'. Miss includes legacy rows with a null/unknown cache state",
|
||||
),
|
||||
model: str | None = fastapi.Query(default=None, description="Filter logs by model"),
|
||||
model_id: str | None = fastapi.Query(
|
||||
default=None,
|
||||
|
|
@ -2268,6 +2278,10 @@ async def ui_view_spend_logs(
|
|||
default="desc",
|
||||
description="Sort order: asc or desc",
|
||||
),
|
||||
exclude_internal_health_checks: bool = fastapi.Query(
|
||||
default=False,
|
||||
description="Exclude LiteLLM internal health check requests from results",
|
||||
),
|
||||
):
|
||||
"""
|
||||
View spend logs with pagination support.
|
||||
|
|
@ -2320,6 +2334,13 @@ async def ui_view_spend_logs(
|
|||
param="sort_order",
|
||||
code=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
if isinstance(cache_hit_filter, str) and cache_hit_filter not in {"hit", "miss"}:
|
||||
raise ProxyException(
|
||||
message=f"Invalid cache_hit_filter: {cache_hit_filter}. Must be one of: hit, miss",
|
||||
type="bad_request",
|
||||
param="cache_hit_filter",
|
||||
code=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
try:
|
||||
is_admin_view: Final = _is_admin_view_safe(user_api_key_dict=user_api_key_dict)
|
||||
|
|
@ -2560,6 +2581,16 @@ async def ui_view_spend_logs(
|
|||
sql_params.append(status_filter)
|
||||
p += 1
|
||||
|
||||
if cache_hit_filter == "hit":
|
||||
sql_conditions.append("LOWER(cache_hit) = 'true'")
|
||||
elif cache_hit_filter == "miss":
|
||||
sql_conditions.append("(cache_hit IS NULL OR LOWER(cache_hit) != 'true')")
|
||||
|
||||
if exclude_internal_health_checks:
|
||||
sql_conditions.append(f"api_key NOT IN (${p}, ${p + 1})")
|
||||
sql_params.extend(_INTERNAL_HEALTH_CHECK_API_KEYS)
|
||||
p += 2 # rebind-ok: advances the file's shared $N placeholder counter
|
||||
|
||||
# Spend range
|
||||
if min_spend is not None:
|
||||
sql_conditions.append(f"spend >= ${p}")
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from types import MappingProxyType
|
||||
from typing import Final, Literal
|
||||
|
||||
from typing_extensions import ReadOnly, TypedDict
|
||||
|
||||
from litellm.types.integrations.custom_logger import StandardCustomLoggerInitParams
|
||||
|
||||
|
||||
|
|
@ -5,3 +12,110 @@ class NewRelicInitParams(StandardCustomLoggerInitParams):
|
|||
"""
|
||||
Params for initializing a New Relic logger on litellm
|
||||
"""
|
||||
|
||||
|
||||
#: Region -> Metric API endpoint. A fixed table by design: team config picks a
|
||||
#: region enum rather than a free-form endpoint, so callback vars can never
|
||||
#: redirect metrics to an arbitrary host.
|
||||
NEWRELIC_METRIC_ENDPOINT_BY_REGION: Final[Mapping[str, str]] = MappingProxyType(
|
||||
{
|
||||
"us": "https://metric-api.newrelic.com/metric/v1",
|
||||
"eu": "https://metric-api.eu.newrelic.com/metric/v1",
|
||||
}
|
||||
)
|
||||
|
||||
NEWRELIC_DEFAULT_REGION: Final = "us"
|
||||
|
||||
#: Metric API caps a payload at 2000 data points / 1MB compressed; each queued
|
||||
#: record expands to at most 6 metrics, so cap the per-flush record count well
|
||||
#: below that.
|
||||
NEWRELIC_METRICS_MAX_BATCH_SIZE: Final = 250
|
||||
|
||||
#: Hard cap on records retained across failed flushes (5xx/network requeue).
|
||||
#: Beyond this the oldest records are dropped.
|
||||
NEWRELIC_METRICS_MAX_RETRY_QUEUE_SIZE: Final = 10_000
|
||||
# Outer passes over a stopped logger's queue: each pass retries the whole
|
||||
# queue, so records that arrive mid-drain still get attempts before the bounded
|
||||
# terminal drop. Serialized by a per-logger drain lock, so this bounds work.
|
||||
NEWRELIC_METRICS_MAX_DRAIN_PASSES: Final = 3
|
||||
# Metric API caps attribute values; 255 keeps caller-controlled model strings
|
||||
# from inflating the shared batch payload into a 413
|
||||
NEWRELIC_METRIC_ATTRIBUTE_MAX_LEN: Final = 255
|
||||
|
||||
NEWRELIC_METRIC_REQUESTS: Final = "litellm.requests"
|
||||
NEWRELIC_METRIC_COST_USD: Final = "litellm.cost.usd"
|
||||
NEWRELIC_METRIC_PROMPT_TOKENS: Final = "litellm.tokens.prompt"
|
||||
NEWRELIC_METRIC_COMPLETION_TOKENS: Final = "litellm.tokens.completion"
|
||||
NEWRELIC_METRIC_TOTAL_TOKENS: Final = "litellm.tokens.total"
|
||||
NEWRELIC_METRIC_REQUEST_DURATION_MS: Final = "litellm.request.duration_ms"
|
||||
|
||||
|
||||
class NewRelicSummaryValue(TypedDict):
|
||||
"""Value shape of a Metric API ``summary`` data point."""
|
||||
|
||||
count: ReadOnly[int]
|
||||
sum: ReadOnly[float]
|
||||
min: ReadOnly[float]
|
||||
max: ReadOnly[float]
|
||||
|
||||
|
||||
class NewRelicCountMetric(TypedDict):
|
||||
name: ReadOnly[str]
|
||||
type: ReadOnly[Literal["count"]]
|
||||
value: ReadOnly[float]
|
||||
attributes: ReadOnly[Mapping[str, str]]
|
||||
|
||||
|
||||
class NewRelicSummaryMetric(TypedDict):
|
||||
name: ReadOnly[str]
|
||||
type: ReadOnly[Literal["summary"]]
|
||||
value: ReadOnly[NewRelicSummaryValue]
|
||||
attributes: ReadOnly[Mapping[str, str]]
|
||||
|
||||
|
||||
NewRelicMetric = NewRelicCountMetric | NewRelicSummaryMetric
|
||||
|
||||
|
||||
#: ``interval.ms`` has a dot in it, so the functional TypedDict form is required.
|
||||
NewRelicMetricCommon = TypedDict(
|
||||
"NewRelicMetricCommon",
|
||||
{ # mutable-ok: functional TypedDict requires a dict-literal fields argument ("interval.ms" key)
|
||||
"timestamp": ReadOnly[int],
|
||||
"interval.ms": ReadOnly[int],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class NewRelicMetricEnvelope(TypedDict):
|
||||
"""One element of the Metric API request body (``[{common, metrics}]``)."""
|
||||
|
||||
common: ReadOnly[NewRelicMetricCommon]
|
||||
metrics: ReadOnly[Sequence[NewRelicMetric]]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class NewRelicMetricRecord:
|
||||
"""One request's contribution to the per-flush aggregation."""
|
||||
|
||||
team_id: str
|
||||
team_alias: str
|
||||
model_group: str
|
||||
model: str
|
||||
custom_llm_provider: str
|
||||
status: str
|
||||
response_cost: float
|
||||
prompt_tokens: int
|
||||
completion_tokens: int
|
||||
total_tokens: int
|
||||
duration_ms: float
|
||||
|
||||
@property
|
||||
def bucket_key(self) -> tuple[str, str, str, str, str, str]:
|
||||
return (
|
||||
self.team_id,
|
||||
self.team_alias,
|
||||
self.model_group,
|
||||
self.model,
|
||||
self.custom_llm_provider,
|
||||
self.status,
|
||||
)
|
||||
|
|
|
|||
81
litellm/types/llms/gemini_audio_transcription.py
Normal file
81
litellm/types/llms/gemini_audio_transcription.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
from typing import Literal, Required
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing_extensions import ReadOnly, TypedDict
|
||||
|
||||
|
||||
class GeminiTranscriptionAudioInput(TypedDict):
|
||||
type: ReadOnly[Literal["audio"]]
|
||||
data: ReadOnly[str]
|
||||
mime_type: ReadOnly[str]
|
||||
|
||||
|
||||
class GeminiTranscriptionVerbatimMode(TypedDict, total=False):
|
||||
type: ReadOnly[Required[Literal["verbatim"]]]
|
||||
timestamp_granularities: ReadOnly[tuple[Literal["word"], ...]]
|
||||
diarization_mode: ReadOnly[Literal["speaker"]]
|
||||
|
||||
|
||||
class GeminiTranscriptionConfig(TypedDict, total=False):
|
||||
language_codes: ReadOnly[tuple[str, ...]]
|
||||
mode: ReadOnly[GeminiTranscriptionVerbatimMode]
|
||||
|
||||
|
||||
class GeminiTranscriptionGenerationConfig(TypedDict):
|
||||
transcription_config: ReadOnly[GeminiTranscriptionConfig]
|
||||
|
||||
|
||||
class GeminiTranscriptionInteractionRequest(TypedDict, total=False):
|
||||
model: ReadOnly[Required[str]]
|
||||
input: ReadOnly[Required[tuple[GeminiTranscriptionAudioInput, ...]]]
|
||||
generation_config: ReadOnly[GeminiTranscriptionGenerationConfig]
|
||||
|
||||
|
||||
class GeminiTranscriptionWordAnnotation(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
type: str | None = None
|
||||
text: str | None = None
|
||||
speaker: str | None = None
|
||||
start_offset: str | None = None
|
||||
end_offset: str | None = None
|
||||
|
||||
|
||||
class GeminiTranscriptionContent(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
type: str | None = None
|
||||
text: str | None = None
|
||||
annotations: tuple[GeminiTranscriptionWordAnnotation, ...] = ()
|
||||
|
||||
|
||||
class GeminiTranscriptionStep(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
type: str | None = None
|
||||
content: tuple[GeminiTranscriptionContent, ...] = ()
|
||||
|
||||
|
||||
class GeminiTranscriptionModalityTokens(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
modality: str | None = None
|
||||
tokens: int = 0
|
||||
|
||||
|
||||
class GeminiTranscriptionUsage(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
total_tokens: int = 0
|
||||
total_input_tokens: int = 0
|
||||
total_output_tokens: int = 0
|
||||
input_tokens_by_modality: tuple[GeminiTranscriptionModalityTokens, ...] = ()
|
||||
|
||||
|
||||
class GeminiTranscriptionInteractionResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
id: str | None = None
|
||||
status: str | None = None
|
||||
usage: GeminiTranscriptionUsage | None = None
|
||||
steps: tuple[GeminiTranscriptionStep, ...] = ()
|
||||
|
|
@ -162,3 +162,16 @@ class RealtimeErrorDetail(TypedDict):
|
|||
class RealtimeErrorEvent(TypedDict):
|
||||
type: ReadOnly[Literal["error"]]
|
||||
error: ReadOnly[RealtimeErrorDetail]
|
||||
|
||||
|
||||
class RealtimeInputAudioTranscriptionUsageInputTokenDetails(TypedDict):
|
||||
text_tokens: ReadOnly[int]
|
||||
audio_tokens: ReadOnly[int]
|
||||
|
||||
|
||||
class RealtimeInputAudioTranscriptionUsage(TypedDict):
|
||||
type: ReadOnly[Literal["tokens"]]
|
||||
input_tokens: ReadOnly[int]
|
||||
output_tokens: ReadOnly[int]
|
||||
total_tokens: ReadOnly[int]
|
||||
input_token_details: ReadOnly[RealtimeInputAudioTranscriptionUsageInputTokenDetails]
|
||||
|
|
|
|||
|
|
@ -8503,6 +8503,12 @@ class ProviderConfigManager:
|
|||
)
|
||||
|
||||
return VertexAIAudioTranscriptionConfig()
|
||||
elif litellm.LlmProviders.GEMINI == provider:
|
||||
from litellm.llms.gemini.audio_transcription.transformation import (
|
||||
GeminiAudioTranscriptionConfig,
|
||||
)
|
||||
|
||||
return GeminiAudioTranscriptionConfig()
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
|
|
|
|||
|
|
@ -51340,6 +51340,47 @@
|
|||
"supports_audio_output": true,
|
||||
"tpm": 250000
|
||||
},
|
||||
"gemini/gemini-3.5-transcribe": {
|
||||
"input_cost_per_audio_token": 2e-06,
|
||||
"input_cost_per_token": 2e-06,
|
||||
"litellm_provider": "gemini",
|
||||
"mode": "audio_transcription",
|
||||
"output_cost_per_token": 1.2e-05,
|
||||
"source": "https://ai.google.dev/gemini-api/docs/pricing",
|
||||
"supported_endpoints": [
|
||||
"/v1/audio/transcriptions"
|
||||
],
|
||||
"supported_modalities": [
|
||||
"text",
|
||||
"audio"
|
||||
],
|
||||
"supported_output_modalities": [
|
||||
"text"
|
||||
],
|
||||
"supports_audio_input": true,
|
||||
"tpm": 800000,
|
||||
"rpm": 2000
|
||||
},
|
||||
"gemini/gemini-3.5-transcribe-live": {
|
||||
"input_cost_per_audio_token": 3.5e-06,
|
||||
"input_cost_per_token": 3.5e-06,
|
||||
"litellm_provider": "gemini",
|
||||
"mode": "audio_transcription",
|
||||
"output_cost_per_token": 2.1e-05,
|
||||
"source": "https://ai.google.dev/gemini-api/docs/pricing",
|
||||
"supported_endpoints": [
|
||||
"/v1/realtime"
|
||||
],
|
||||
"supported_modalities": [
|
||||
"audio"
|
||||
],
|
||||
"supported_output_modalities": [
|
||||
"text"
|
||||
],
|
||||
"supports_audio_input": true,
|
||||
"tpm": 250000,
|
||||
"rpm": 10
|
||||
},
|
||||
"perplexity/pplx-embed-context-v1-0.6b": {
|
||||
"input_cost_per_token": 8e-09,
|
||||
"litellm_provider": "perplexity",
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
# - tests/e2e Python -> `make lint-e2e-basedpyright` (test-linting.yml's e2e type-check step)
|
||||
# + raw HTTP client ban (test-code-quality.yml's check_e2e_no_raw_requests)
|
||||
# - dashboard -> prettier + eslint + lint budgets (test-litellm-ui-build.yml's frontend-lint)
|
||||
# - proxy/types -> regenerate dashboard API types and fail on drift (check-ui-api-types.yml)
|
||||
# - proxy/types -> regenerate the lazy OpenAPI snapshot and dashboard API types, fail on drift (check-ui-api-types.yml)
|
||||
#
|
||||
# Each block is skipped when no matching files are in scope, so unrelated commits
|
||||
# stay fast. This is intentionally not auto-installed as a git hook (see
|
||||
|
|
@ -244,7 +244,7 @@ fi
|
|||
|
||||
genapi_checks() {
|
||||
local status=0
|
||||
echo "check: checking dashboard API types are in sync (npm run gen:api)"
|
||||
echo "check: checking the lazy OpenAPI snapshot and dashboard API types are in sync (npm run gen:api)"
|
||||
# gen-api-types.mjs imports litellm.proxy.proxy_server, which needs the proxy deps
|
||||
# and an up-to-date Prisma client; check-ui-api-types.yml installs those and runs
|
||||
# prisma generate before gen:api, so mirror that here or a stale client can mask
|
||||
|
|
@ -260,7 +260,14 @@ genapi_checks() {
|
|||
elif ! uv run --no-sync python scripts/prisma_generate_if_needed.py; then
|
||||
echo "✗ Could not regenerate Prisma client (prisma generate failed)." >&2
|
||||
status=1
|
||||
elif ! uv run --no-sync python -m litellm.proxy._lazy_openapi_snapshot; then
|
||||
echo "✗ Could not regenerate the lazy OpenAPI snapshot (python -m litellm.proxy._lazy_openapi_snapshot failed)." >&2
|
||||
status=1
|
||||
elif ( cd ui/litellm-dashboard && LITELLM_PYTHON="uv run --no-sync python" npm run gen:api ); then
|
||||
if ! git diff --quiet -- litellm/proxy/_lazy_openapi_snapshot.json; then
|
||||
echo "✗ The lazy OpenAPI snapshot is stale; regenerated litellm/proxy/_lazy_openapi_snapshot.json. Stage it and commit; re-run make check only if other checks failed too." >&2
|
||||
status=1
|
||||
fi
|
||||
if ! git diff --quiet -- ui/litellm-dashboard/src/lib/http/schema.d.ts; then
|
||||
echo "✗ Dashboard API types are stale; regenerated src/lib/http/schema.d.ts. Stage it and commit; re-run make check only if other checks failed too." >&2
|
||||
status=1
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ at call time. The provider table below is the source of truth; edit `PROVIDERS`
|
|||
| openai | `openai-realtime` | `openai/gpt-realtime-2` |
|
||||
| azure | `azure-realtime` | `azure/gpt-realtime-2` (GA protocol) |
|
||||
| gemini | `gemini-realtime` | `gemini/gemini-3.1-flash-live-preview` |
|
||||
| vertex_ai | `vertex-realtime` | `vertex_ai/gemini-live-2.5-flash-preview-native-audio-09-2025` |
|
||||
| vertex_ai | `vertex-realtime` | `vertex_ai/gemini-live-2.5-flash-native-audio` |
|
||||
|
||||
Bedrock and xai (`xai/grok-4-1-fast-non-reasoning`) are supported by the proxy but
|
||||
kept commented out in `PROVIDERS` until they pass end-to-end here; re-enable them by
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ PROVIDERS = (
|
|||
"vertex_ai",
|
||||
"vertex-realtime",
|
||||
LiteLLMParamsBody(
|
||||
model="vertex_ai/gemini-live-2.5-flash-preview-native-audio-09-2025",
|
||||
model="vertex_ai/gemini-live-2.5-flash-native-audio",
|
||||
vertex_location="us-central1",
|
||||
vertex_credentials="os.environ/VERTEXAI_CREDENTIALS",
|
||||
),
|
||||
|
|
|
|||
|
|
@ -308,7 +308,8 @@ class TestGeminiChatCompletions:
|
|||
content=f"Reply with the single word pong. marker={tag}",
|
||||
)
|
||||
],
|
||||
max_tokens=32,
|
||||
max_tokens=64,
|
||||
reasoning_effort="none",
|
||||
),
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -50,11 +50,14 @@ CACHE_WARM_CONSECUTIVE_READS = 3
|
|||
|
||||
|
||||
def _cacheable_system_block(marker: str) -> TextBlock:
|
||||
"""A system prompt comfortably above the 4096-token minimum cacheable size
|
||||
of Haiku 4.5 (the smallest model here), unique per run so no other run's
|
||||
cache entry can satisfy the read."""
|
||||
text = " ".join(
|
||||
f"Reference paragraph {index} for run {marker}." for index in range(300)
|
||||
"""A system prompt at roughly twice the 4096-token minimum cacheable size of
|
||||
Haiku 4.5 (the smallest model here), unique per run so no other run's cache
|
||||
entry can satisfy the read. The marker appears once instead of in every
|
||||
paragraph: repeating it swung the block's size by ~1800 tokens with the
|
||||
marker's own tokenization and left it under the minimum on ~15% of runs, so
|
||||
the system breakpoint went uncached and the priming loop never saw a read."""
|
||||
text = f"Run {marker}.\n" + " ".join(
|
||||
f"Reference paragraph {index}." for index in range(1500)
|
||||
)
|
||||
return TextBlock(text=text, cache_control=CacheControl())
|
||||
|
||||
|
|
@ -101,8 +104,8 @@ def _first_turn_user_text(marker: str) -> str:
|
|||
"""A first user turn heavy enough (hundreds of tokens) that losing its cache
|
||||
entry is unambiguous in the usage numbers, unique per attempt so priming
|
||||
retries never depend on the proxy's response cache behavior."""
|
||||
notes = " ".join(f"Session note {index} for attempt {marker}." for index in range(100))
|
||||
return f"Reply with one word.\n{notes}"
|
||||
notes = " ".join(f"Session note {index}." for index in range(100))
|
||||
return f"Reply with one word. Attempt {marker}.\n{notes}"
|
||||
|
||||
|
||||
class PrimedCache(BaseModel):
|
||||
|
|
|
|||
|
|
@ -70,9 +70,15 @@ def _vertex_params(model: str, location: str) -> LiteLLMParamsBody:
|
|||
|
||||
|
||||
def _cacheable_system_block(marker: str) -> TextBlock:
|
||||
"""A system prompt comfortably above the 1024-token minimum cacheable size,
|
||||
unique per run so no other run's cache entry can satisfy the read."""
|
||||
text = " ".join(f"Reference paragraph {index} for run {marker}." for index in range(300))
|
||||
"""A system prompt at roughly twice the 4096-token minimum cacheable size of
|
||||
Haiku 4.5 (the smallest model here), unique per run so no other run's cache
|
||||
entry can satisfy the read. The marker appears once instead of in every
|
||||
paragraph: repeating it swung the block's size by ~1800 tokens with the
|
||||
marker's own tokenization and left it under the minimum on ~15% of runs, so
|
||||
the system breakpoint went uncached and the priming loop never saw a read."""
|
||||
text = f"Run {marker}.\n" + " ".join(
|
||||
f"Reference paragraph {index}." for index in range(1500)
|
||||
)
|
||||
return TextBlock(text=text, cache_control=CacheControl())
|
||||
|
||||
|
||||
|
|
@ -110,8 +116,8 @@ def _first_turn_user_text(marker: str) -> str:
|
|||
"""A first user turn heavy enough (hundreds of tokens) that losing its cache
|
||||
entry is unambiguous in the usage numbers, unique per attempt so priming
|
||||
retries never depend on the proxy's response cache behavior."""
|
||||
notes = " ".join(f"Session note {index} for attempt {marker}." for index in range(100))
|
||||
return f"Reply with one word.\n{notes}"
|
||||
notes = " ".join(f"Session note {index}." for index in range(100))
|
||||
return f"Reply with one word. Attempt {marker}.\n{notes}"
|
||||
|
||||
|
||||
class PrimedCache(BaseModel):
|
||||
|
|
|
|||
|
|
@ -256,6 +256,7 @@ class ChatBody(BaseModel):
|
|||
reasoning_effort: str | None = None
|
||||
thinking: ThinkingParam | None = None
|
||||
service_tier: str | None = None
|
||||
prompt_cache_key: str | None = None
|
||||
tools: Sequence[ChatTool | McpChatTool] | None = None
|
||||
tool_choice: str | None = None
|
||||
guardrails: list[str] | None = None
|
||||
|
|
|
|||
|
|
@ -12,11 +12,16 @@ header is exercised with a real nonzero value instead of passing vacuously. The
|
|||
backend is gpt-5.5 because it reports cached tokens on the second call; the
|
||||
gpt-5.6 line reports cache writes and never a read, which would leave the
|
||||
cache-read header at zero forever. The raw-transport send is used because the
|
||||
typed chat client validates bodies and drops headers. OpenAI caching is
|
||||
best-effort, so the prime+measure round retries with a fresh prefix before
|
||||
failing.
|
||||
typed chat client validates bodies and drops headers.
|
||||
|
||||
OpenAI publishes a primed prefix asynchronously and routes lookups by
|
||||
prompt_cache_key, so a measure fired the instant the prime returns can miss a
|
||||
prefix that is about to become readable. Each round pins a cache key and re-reads
|
||||
the prefix it already paid to prime before spending a fresh one.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from cost_rows import approx_equal, cacheable_prefix, register_priced_model
|
||||
|
|
@ -31,6 +36,8 @@ pytestmark = pytest.mark.e2e
|
|||
BACKEND = "openai/gpt-5.5"
|
||||
OPENAI_API_KEY = "os.environ/OPENAI_API_KEY"
|
||||
CACHE_ATTEMPTS = 3
|
||||
CACHE_REREADS = 3
|
||||
CACHE_SETTLE_SECONDS = 2.0
|
||||
|
||||
INPUT_RATE = 4e-05
|
||||
OUTPUT_RATE = 8e-05
|
||||
|
|
@ -70,7 +77,7 @@ class TestCostHeaders:
|
|||
),
|
||||
)
|
||||
|
||||
def priced_call(content: str) -> StreamingResponse:
|
||||
def priced_call(content: str, cache_key: str) -> StreamingResponse:
|
||||
response = client.proxy.transport.send(
|
||||
"/chat/completions",
|
||||
headers=client.proxy.transport.bearer(scoped_key),
|
||||
|
|
@ -78,21 +85,30 @@ class TestCostHeaders:
|
|||
model=model,
|
||||
messages=[ChatMessage(role="user", content=content)],
|
||||
max_completion_tokens=4000,
|
||||
prompt_cache_key=cache_key,
|
||||
),
|
||||
)
|
||||
assert response.ok, f"chat failed (status {response.status_code}): {response.body[:300]}"
|
||||
return response
|
||||
|
||||
for _ in range(CACHE_ATTEMPTS):
|
||||
prefix = cacheable_prefix(unique_marker())
|
||||
priced_call(f"{prefix}\nReply with the single word ready.")
|
||||
measured = priced_call(f"{prefix}\nReply with the single word measured.")
|
||||
if _header_cost(measured, "x-litellm-response-cost-cache-read") > 0:
|
||||
break
|
||||
else:
|
||||
def prime_then_reread() -> StreamingResponse | None:
|
||||
marker = unique_marker()
|
||||
prefix = cacheable_prefix(marker)
|
||||
priced_call(f"{prefix}\nReply with the single word ready.", marker)
|
||||
for _ in range(CACHE_REREADS):
|
||||
time.sleep(CACHE_SETTLE_SECONDS)
|
||||
response = priced_call(f"{prefix}\nReply with the single word measured.", marker)
|
||||
if _header_cost(response, "x-litellm-response-cost-cache-read") > 0:
|
||||
return response
|
||||
return None
|
||||
|
||||
rounds = (prime_then_reread() for _ in range(CACHE_ATTEMPTS))
|
||||
measured = next((response for response in rounds if response is not None), None)
|
||||
if measured is None:
|
||||
pytest.fail(
|
||||
f"no cache read landed across {CACHE_ATTEMPTS} prime+measure rounds; "
|
||||
"the cache-read cost header was never exercised with a nonzero value"
|
||||
f"no cache read landed across {CACHE_ATTEMPTS} prime rounds of "
|
||||
f"{CACHE_REREADS} re-reads each; the cache-read cost header was never "
|
||||
"exercised with a nonzero value"
|
||||
)
|
||||
|
||||
total = measured.response_cost
|
||||
|
|
|
|||
|
|
@ -117,6 +117,11 @@ const ADMIN_AUTH = {
|
|||
Authorization: `Bearer ${users[Role.ProxyAdmin].password}`,
|
||||
};
|
||||
|
||||
// Five probes 2s apart outlast the e2e stack's proxy_config_reload_interval_seconds of 7.
|
||||
const SETTLE_INTERVAL_MS = 2_000;
|
||||
const SETTLE_PROBES = 5;
|
||||
const SETTLE_TIMEOUT_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Apply a router_settings patch through the typed /config/update contract. The
|
||||
* server merges it over existing settings (request wins), so only the passed keys
|
||||
|
|
@ -133,6 +138,21 @@ async function patchRouterSettings(
|
|||
expect(res.ok(), `seed /config/update failed: ${res.status()} ${await res.text()}`).toBeTruthy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Spreads its samples across more than one reload cycle: a single reply only proves the one
|
||||
* replica that served it has reloaded, not the sibling still on the pre-update config.
|
||||
*/
|
||||
async function sampleStatuses(probe: () => Promise<number>): Promise<readonly number[]> {
|
||||
return Array.from({ length: SETTLE_PROBES }).reduce<Promise<readonly number[]>>(
|
||||
async (taken, _unused, index) => {
|
||||
const sofar = await taken;
|
||||
if (index > 0) await new Promise((resolve) => setTimeout(resolve, SETTLE_INTERVAL_MS));
|
||||
return [...sofar, await probe()];
|
||||
},
|
||||
Promise.resolve([]),
|
||||
);
|
||||
}
|
||||
|
||||
test.describe("Router Settings - Loadbalancing", () => {
|
||||
test.use({ storageState: ADMIN_STORAGE_PATH });
|
||||
|
||||
|
|
@ -252,28 +272,34 @@ test.describe("Router Settings - Fallbacks serve the request", () => {
|
|||
});
|
||||
|
||||
test("a request to an unreachable model is answered by its fallback", async ({ page, request }) => {
|
||||
const chat = async () =>
|
||||
request.post("/v1/chat/completions", {
|
||||
headers: { ...ADMIN_AUTH, "Content-Type": "application/json" },
|
||||
data: {
|
||||
model: BROKEN_PRIMARY,
|
||||
messages: [{ role: "user", content: "fallback probe" }],
|
||||
},
|
||||
});
|
||||
const chatStatus = async () =>
|
||||
(
|
||||
await request.post("/v1/chat/completions", {
|
||||
headers: { ...ADMIN_AUTH, "Content-Type": "application/json" },
|
||||
data: {
|
||||
model: BROKEN_PRIMARY,
|
||||
messages: [{ role: "user", content: "fallback probe" }],
|
||||
},
|
||||
})
|
||||
).status();
|
||||
|
||||
// The control: it proves the reply below could only have come from the fallback.
|
||||
expect((await chat()).status(), "broken primary unexpectedly succeeded on its own").toBeGreaterThanOrEqual(400);
|
||||
// The control: every replica must reject, or the reply below could have come from one
|
||||
// that was still serving a fallback left behind by an earlier attempt.
|
||||
await expect
|
||||
.poll(async () => (await sampleStatuses(chatStatus)).every((status) => status >= 400), {
|
||||
timeout: SETTLE_TIMEOUT_MS,
|
||||
message: "broken primary unexpectedly succeeded on its own",
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
await patchRouterSettings(request, {
|
||||
fallbacks: [{ [BROKEN_PRIMARY]: [PRIMARY] }],
|
||||
} as Partial<NonNullable<ConfigYAML["router_settings"]>>);
|
||||
|
||||
// Same call now succeeds, served by the fallback model.
|
||||
// One success is the whole claim here, so this waits for a first sighting rather than
|
||||
// for every replica: demanding a streak would also assert a fallback hit rate.
|
||||
await expect
|
||||
.poll(async () => (await chat()).status(), {
|
||||
timeout: 30_000,
|
||||
message: "fallback never took effect",
|
||||
})
|
||||
.poll(chatStatus, { timeout: SETTLE_TIMEOUT_MS, message: "fallback never took effect" })
|
||||
.toBe(200);
|
||||
|
||||
// And the playground renders a reply for a model whose own upstream is down.
|
||||
|
|
|
|||
|
|
@ -2661,7 +2661,7 @@ async def test_run_direct_health_check_drops_only_the_rejected_kwarg(monkeypatch
|
|||
rejected argument alongside working ones would probe deployments the operator opted out."""
|
||||
import litellm.proxy.proxy_server as proxy_server
|
||||
|
||||
seen: list = []
|
||||
seen: list[tuple[dict[str, str] | None, bool]] = []
|
||||
|
||||
async def fake_perform_health_check(
|
||||
model_list,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,825 @@
|
|||
"""
|
||||
Batching tests for NewRelicMetricsLogger: flush-window interval computation,
|
||||
dimension-bucket aggregation, the 4xx-drop vs 5xx/network-requeue policy, the
|
||||
retry-queue cap, and the stop flag that ends the periodic flush loop.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from httpx import HTTPStatusError, Request, Response
|
||||
|
||||
from litellm.integrations.newrelic.newrelic_metrics import (
|
||||
NewRelicMetricsLogger,
|
||||
_bucket_metrics,
|
||||
build_metric_payload,
|
||||
)
|
||||
from litellm.types.integrations.newrelic import (
|
||||
NEWRELIC_METRIC_COMPLETION_TOKENS,
|
||||
NEWRELIC_METRIC_COST_USD,
|
||||
NEWRELIC_METRIC_ENDPOINT_BY_REGION,
|
||||
NEWRELIC_METRIC_PROMPT_TOKENS,
|
||||
NEWRELIC_METRIC_REQUEST_DURATION_MS,
|
||||
NEWRELIC_METRIC_REQUESTS,
|
||||
NEWRELIC_METRIC_TOTAL_TOKENS,
|
||||
NewRelicMetricRecord,
|
||||
)
|
||||
|
||||
|
||||
def _record(
|
||||
team_id="team-a",
|
||||
team_alias=None,
|
||||
model="gpt-4o",
|
||||
model_group=None,
|
||||
status="success",
|
||||
response_cost=0.5,
|
||||
prompt_tokens=10,
|
||||
completion_tokens=20,
|
||||
total_tokens=30,
|
||||
duration_ms=100.0,
|
||||
) -> NewRelicMetricRecord:
|
||||
return NewRelicMetricRecord(
|
||||
team_id=team_id,
|
||||
team_alias=team_alias if team_alias is not None else f"{team_id}-alias",
|
||||
model_group=model_group if model_group is not None else f"{model}-group",
|
||||
model=model,
|
||||
custom_llm_provider="openai",
|
||||
status=status,
|
||||
response_cost=response_cost,
|
||||
prompt_tokens=prompt_tokens,
|
||||
completion_tokens=completion_tokens,
|
||||
total_tokens=total_tokens,
|
||||
duration_ms=duration_ms,
|
||||
)
|
||||
|
||||
|
||||
def _standard_logging_object(team_id="team-a", response_cost=0.25) -> dict:
|
||||
return {
|
||||
"metadata": {"user_api_key_team_id": team_id, "user_api_key_team_alias": f"{team_id}-alias"},
|
||||
"model_group": "gpt-4o-group",
|
||||
"model": "gpt-4o",
|
||||
"custom_llm_provider": "openai",
|
||||
"status": "success",
|
||||
"response_cost": response_cost,
|
||||
"prompt_tokens": 10,
|
||||
"completion_tokens": 20,
|
||||
"total_tokens": 30,
|
||||
"response_time": 0.1,
|
||||
}
|
||||
|
||||
|
||||
def _make_logger(**kwargs) -> NewRelicMetricsLogger:
|
||||
with patch("asyncio.create_task"):
|
||||
return NewRelicMetricsLogger(newrelic_api_key="test-key", **kwargs)
|
||||
|
||||
|
||||
def _response(status_code: int, text: str = "") -> Response:
|
||||
return Response(status_code, request=Request("POST", "https://example.com"), text=text)
|
||||
|
||||
|
||||
def _raises(status_code: int):
|
||||
"""Mock the way AsyncHTTPHandler.post really behaves: raise_for_status() turns
|
||||
every non-2xx into an HTTPStatusError rather than returning the response."""
|
||||
resp = _response(status_code)
|
||||
return AsyncMock(side_effect=HTTPStatusError("err", request=resp.request, response=resp))
|
||||
|
||||
|
||||
def _metrics_by_name(payload, name):
|
||||
return [m for m in payload[0]["metrics"] if m["name"] == name]
|
||||
|
||||
|
||||
class TestBuildMetricPayload:
|
||||
def test_interval_and_timestamp_reflect_flush_window(self):
|
||||
payload = build_metric_payload((_record(),), window_start=1_000.0, now=1_007.5)
|
||||
|
||||
assert payload[0]["common"]["timestamp"] == 1_000_000
|
||||
assert payload[0]["common"]["interval.ms"] == 7_500
|
||||
|
||||
def test_interval_is_at_least_one_ms(self):
|
||||
payload = build_metric_payload((_record(),), window_start=1_000.0, now=1_000.0)
|
||||
|
||||
assert payload[0]["common"]["interval.ms"] == 1
|
||||
|
||||
def test_single_record_metric_values(self):
|
||||
payload = build_metric_payload(
|
||||
(_record(response_cost=0.5, prompt_tokens=10, completion_tokens=20, total_tokens=30, duration_ms=100.0),),
|
||||
window_start=1_000.0,
|
||||
now=1_005.0,
|
||||
)
|
||||
|
||||
by_name = {m["name"]: m for m in payload[0]["metrics"]}
|
||||
assert by_name[NEWRELIC_METRIC_REQUESTS]["value"] == 1.0
|
||||
assert by_name[NEWRELIC_METRIC_REQUESTS]["type"] == "count"
|
||||
assert by_name[NEWRELIC_METRIC_COST_USD]["value"] == 0.5
|
||||
assert by_name[NEWRELIC_METRIC_PROMPT_TOKENS]["value"] == 10.0
|
||||
assert by_name[NEWRELIC_METRIC_COMPLETION_TOKENS]["value"] == 20.0
|
||||
assert by_name[NEWRELIC_METRIC_TOTAL_TOKENS]["value"] == 30.0
|
||||
duration = by_name[NEWRELIC_METRIC_REQUEST_DURATION_MS]
|
||||
assert duration["type"] == "summary"
|
||||
assert duration["value"] == {"count": 1, "sum": 100.0, "min": 100.0, "max": 100.0}
|
||||
assert by_name[NEWRELIC_METRIC_REQUESTS]["attributes"] == {
|
||||
"team_id": "team-a",
|
||||
"team_alias": "team-a-alias",
|
||||
"model_group": "gpt-4o-group",
|
||||
"model": "gpt-4o",
|
||||
"custom_llm_provider": "openai",
|
||||
"status": "success",
|
||||
}
|
||||
|
||||
def test_aggregates_across_dimension_buckets(self):
|
||||
"""Two teams x two models in one queue land in the right bucket sums.
|
||||
|
||||
team_alias and model_group are held constant so bucketing provably keys on
|
||||
team_id and model themselves, not on correlated fields.
|
||||
"""
|
||||
shared = {"team_alias": "shared-alias", "model_group": "shared-group"}
|
||||
records = (
|
||||
_record(team_id="team-a", model="gpt-4o", response_cost=0.1, total_tokens=10, duration_ms=50.0, **shared),
|
||||
_record(team_id="team-a", model="gpt-4o", response_cost=0.2, total_tokens=20, duration_ms=150.0, **shared),
|
||||
_record(
|
||||
team_id="team-a", model="claude-4", response_cost=0.4, total_tokens=40, duration_ms=200.0, **shared
|
||||
),
|
||||
_record(team_id="team-b", model="gpt-4o", response_cost=0.8, total_tokens=80, duration_ms=300.0, **shared),
|
||||
)
|
||||
payload = build_metric_payload(records, window_start=1_000.0, now=1_005.0)
|
||||
|
||||
cost_by_bucket = {
|
||||
(m["attributes"]["team_id"], m["attributes"]["model"]): m["value"]
|
||||
for m in _metrics_by_name(payload, NEWRELIC_METRIC_COST_USD)
|
||||
}
|
||||
assert cost_by_bucket == {
|
||||
("team-a", "gpt-4o"): pytest.approx(0.3),
|
||||
("team-a", "claude-4"): pytest.approx(0.4),
|
||||
("team-b", "gpt-4o"): pytest.approx(0.8),
|
||||
}
|
||||
|
||||
requests_by_bucket = {
|
||||
(m["attributes"]["team_id"], m["attributes"]["model"]): m["value"]
|
||||
for m in _metrics_by_name(payload, NEWRELIC_METRIC_REQUESTS)
|
||||
}
|
||||
assert requests_by_bucket == {
|
||||
("team-a", "gpt-4o"): 2.0,
|
||||
("team-a", "claude-4"): 1.0,
|
||||
("team-b", "gpt-4o"): 1.0,
|
||||
}
|
||||
|
||||
duration_by_bucket = {
|
||||
(m["attributes"]["team_id"], m["attributes"]["model"]): m["value"]
|
||||
for m in _metrics_by_name(payload, NEWRELIC_METRIC_REQUEST_DURATION_MS)
|
||||
}
|
||||
assert duration_by_bucket[("team-a", "gpt-4o")] == {"count": 2, "sum": 200.0, "min": 50.0, "max": 150.0}
|
||||
|
||||
def test_status_is_a_bucket_dimension(self):
|
||||
records = (
|
||||
_record(status="success", response_cost=0.1),
|
||||
_record(status="failure", response_cost=0.0),
|
||||
)
|
||||
payload = build_metric_payload(records, window_start=1_000.0, now=1_005.0)
|
||||
|
||||
statuses = {m["attributes"]["status"] for m in _metrics_by_name(payload, NEWRELIC_METRIC_REQUESTS)}
|
||||
assert statuses == {"success", "failure"}
|
||||
|
||||
def test_empty_attribute_values_are_omitted(self):
|
||||
record = NewRelicMetricRecord(
|
||||
team_id="",
|
||||
team_alias="",
|
||||
model_group="",
|
||||
model="gpt-4o",
|
||||
custom_llm_provider="openai",
|
||||
status="success",
|
||||
response_cost=0.0,
|
||||
prompt_tokens=0,
|
||||
completion_tokens=0,
|
||||
total_tokens=0,
|
||||
duration_ms=0.0,
|
||||
)
|
||||
payload = build_metric_payload((record,), window_start=1_000.0, now=1_005.0)
|
||||
|
||||
attributes = payload[0]["metrics"][0]["attributes"]
|
||||
assert "team_id" not in attributes
|
||||
assert "team_alias" not in attributes
|
||||
assert "model_group" not in attributes
|
||||
|
||||
|
||||
class TestQueueAndFlush:
|
||||
@pytest.mark.asyncio
|
||||
async def test_log_event_queues_record_from_standard_logging_object(self):
|
||||
logger = _make_logger()
|
||||
|
||||
await logger.async_log_success_event(
|
||||
kwargs={"standard_logging_object": _standard_logging_object()},
|
||||
response_obj={},
|
||||
start_time=None,
|
||||
end_time=None,
|
||||
)
|
||||
|
||||
assert len(logger.log_queue) == 1
|
||||
record = logger.log_queue[0]
|
||||
assert record.team_id == "team-a"
|
||||
assert record.response_cost == 0.25
|
||||
assert record.duration_ms == pytest.approx(100.0)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failure_event_queues_record(self):
|
||||
logger = _make_logger()
|
||||
|
||||
slo = _standard_logging_object()
|
||||
slo["status"] = "failure"
|
||||
await logger.async_log_failure_event(
|
||||
kwargs={"standard_logging_object": slo},
|
||||
response_obj={},
|
||||
start_time=None,
|
||||
end_time=None,
|
||||
)
|
||||
|
||||
assert len(logger.log_queue) == 1
|
||||
assert logger.log_queue[0].status == "failure"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_threshold_flush_uses_flush_queue(self):
|
||||
logger = _make_logger()
|
||||
logger.batch_size = 1
|
||||
logger.flush_queue = AsyncMock()
|
||||
|
||||
await logger.async_log_success_event(
|
||||
kwargs={"standard_logging_object": _standard_logging_object()},
|
||||
response_obj={},
|
||||
start_time=None,
|
||||
end_time=None,
|
||||
)
|
||||
|
||||
logger.flush_queue.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flush_queue_updates_last_flush_time_on_success(self):
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record()]
|
||||
logger.last_flush_time = 0
|
||||
logger.async_client.post = AsyncMock(return_value=_response(202))
|
||||
|
||||
await logger.flush_queue()
|
||||
|
||||
assert logger.log_queue == []
|
||||
assert logger.last_flush_time > 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flush_advances_window_even_on_requeue(self):
|
||||
# The window start advances every flush cycle so requeued records report
|
||||
# in the next window instead of freezing interval.ms under sustained
|
||||
# failure, and an idle gap never inflates the next batch's window
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record()]
|
||||
logger.last_flush_time = 123.0
|
||||
logger.async_client.post = _raises(500)
|
||||
|
||||
await logger.flush_queue()
|
||||
|
||||
assert logger.last_flush_time > 123.0
|
||||
assert len(logger.log_queue) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sent_payload_window_starts_at_last_flush_time(self):
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record()]
|
||||
logger.last_flush_time = 2_000.0
|
||||
logger.async_client.post = AsyncMock(return_value=_response(202))
|
||||
|
||||
with patch("litellm.integrations.newrelic.newrelic_metrics.time.time", return_value=2_010.0):
|
||||
await logger.async_send_batch()
|
||||
|
||||
sent = logger.async_client.post.await_args.kwargs
|
||||
body = json.loads(gzip.decompress(sent["data"]).decode("utf-8"))
|
||||
assert body[0]["common"]["timestamp"] == 2_000_000
|
||||
assert body[0]["common"]["interval.ms"] == 10_000
|
||||
assert sent["headers"]["Api-Key"] == "test-key"
|
||||
assert sent["headers"]["Content-Encoding"] == "gzip"
|
||||
assert sent["url"] == NEWRELIC_METRIC_ENDPOINT_BY_REGION["us"]
|
||||
|
||||
|
||||
class TestBatchSizeCap:
|
||||
@pytest.mark.asyncio
|
||||
async def test_flush_sends_at_most_batch_size_records_per_request(self):
|
||||
"""A queue grown past the batch size by requeues must go out in chunks:
|
||||
one oversized request would breach the Metric API data point cap and get
|
||||
the whole retry backlog dropped as a 4xx."""
|
||||
logger = _make_logger()
|
||||
logger.batch_size = 2
|
||||
logger.log_queue = [_record(model=f"model-{i}") for i in range(5)]
|
||||
logger.async_client.post = AsyncMock(return_value=_response(202))
|
||||
|
||||
await logger.flush_queue()
|
||||
|
||||
sent_counts = [
|
||||
sum(
|
||||
metric["value"]
|
||||
for metric in json.loads(gzip.decompress(call.kwargs["data"]).decode("utf-8"))[0]["metrics"]
|
||||
if metric["name"] == NEWRELIC_METRIC_REQUESTS
|
||||
)
|
||||
for call in logger.async_client.post.await_args_list
|
||||
]
|
||||
assert sent_counts == [2.0, 2.0, 1.0]
|
||||
assert logger.log_queue == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_chunk_stops_the_flush_and_keeps_order(self):
|
||||
"""A 5xx on the first chunk ends the flush instead of hammering the same
|
||||
failing endpoint with the rest of the backlog, and the requeue keeps the
|
||||
records in chronological order."""
|
||||
logger = _make_logger()
|
||||
logger.batch_size = 2
|
||||
records = [_record(model=f"model-{i}") for i in range(5)]
|
||||
logger.log_queue = list(records)
|
||||
logger.async_client.post = _raises(500)
|
||||
|
||||
await logger.flush_queue()
|
||||
|
||||
assert logger.async_client.post.await_count == 1
|
||||
assert logger.log_queue == records
|
||||
|
||||
|
||||
class TestFlushConcurrency:
|
||||
@pytest.mark.asyncio
|
||||
async def test_records_appended_during_flush_await_survive(self):
|
||||
"""A record appended by a concurrent request while the POST is in flight
|
||||
must survive the flush, not be clobbered by a queue replacement."""
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record(team_id="team-a")]
|
||||
interleaved = _record(team_id="team-interleaved")
|
||||
|
||||
async def _post_appending_mid_flight(**kwargs):
|
||||
logger.log_queue.append(interleaved)
|
||||
return _response(202)
|
||||
|
||||
logger.async_client.post = AsyncMock(side_effect=_post_appending_mid_flight)
|
||||
|
||||
await logger.async_send_batch()
|
||||
|
||||
assert logger.log_queue == [interleaved]
|
||||
body = json.loads(gzip.decompress(logger.async_client.post.await_args.kwargs["data"]).decode("utf-8"))
|
||||
team_ids = {m["attributes"]["team_id"] for m in body[0]["metrics"]}
|
||||
assert team_ids == {"team-a"}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_records_appended_during_failed_flush_await_survive_requeue(self):
|
||||
"""The requeue path must also preserve interleaved records: batch is
|
||||
prepended in place, never assigned over the live queue."""
|
||||
logger = _make_logger()
|
||||
original = _record(team_id="team-a")
|
||||
logger.log_queue = [original]
|
||||
interleaved = _record(team_id="team-interleaved")
|
||||
|
||||
async def _post_appending_mid_flight(**kwargs):
|
||||
logger.log_queue.append(interleaved)
|
||||
raise HTTPStatusError('e', request=_response(500).request, response=_response(500))
|
||||
|
||||
logger.async_client.post = AsyncMock(side_effect=_post_appending_mid_flight)
|
||||
|
||||
await logger.async_send_batch()
|
||||
|
||||
assert logger.log_queue == [original, interleaved]
|
||||
|
||||
|
||||
class TestErrorPolicy:
|
||||
@pytest.mark.asyncio
|
||||
async def test_4xx_drops_batch(self):
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record(), _record(team_id="team-b")]
|
||||
logger.async_client.post = AsyncMock(return_value=_response(400, text="bad request"))
|
||||
|
||||
await logger.async_send_batch()
|
||||
|
||||
assert logger.log_queue == []
|
||||
assert logger.async_client.post.await_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_403_drops_batch_and_names_permanent_credential_failure(self):
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record()]
|
||||
logger.async_client.post = _raises(403)
|
||||
|
||||
with patch("litellm.integrations.newrelic.newrelic_metrics.verbose_logger") as mock_logger:
|
||||
await logger.async_send_batch()
|
||||
|
||||
assert logger.log_queue == []
|
||||
warning_text = " ".join(str(arg) for call in mock_logger.warning.call_args_list for arg in call.args)
|
||||
assert "permanent credential failure" in warning_text
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_5xx_requeues_batch(self):
|
||||
records = [_record(), _record(team_id="team-b")]
|
||||
logger = _make_logger()
|
||||
logger.log_queue = list(records)
|
||||
logger.async_client.post = _raises(500)
|
||||
|
||||
await logger.async_send_batch()
|
||||
|
||||
assert logger.log_queue == records
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_network_error_requeues_batch(self):
|
||||
records = [_record()]
|
||||
logger = _make_logger()
|
||||
logger.log_queue = list(records)
|
||||
logger.async_client.post = AsyncMock(side_effect=ConnectionError("boom"))
|
||||
|
||||
await logger.async_send_batch()
|
||||
|
||||
assert logger.log_queue == records
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_requeue_is_capped_dropping_oldest(self):
|
||||
logger = _make_logger()
|
||||
logger.max_queue_size = 3
|
||||
oldest = _record(team_id="oldest")
|
||||
rest = [_record(team_id=f"team-{i}") for i in range(3)]
|
||||
logger.log_queue = [oldest, *rest]
|
||||
logger.async_client.post = _raises(500)
|
||||
|
||||
await logger.async_send_batch()
|
||||
|
||||
assert logger.log_queue == rest
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_requeued_records_are_resent_with_new_records(self):
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record()]
|
||||
logger.async_client.post = _raises(500)
|
||||
|
||||
await logger.async_send_batch()
|
||||
logger.log_queue.append(_record(team_id="team-b"))
|
||||
logger.async_client.post = AsyncMock(return_value=_response(202))
|
||||
|
||||
await logger.async_send_batch()
|
||||
|
||||
sent = logger.async_client.post.await_args.kwargs
|
||||
body = json.loads(gzip.decompress(sent["data"]).decode("utf-8"))
|
||||
team_ids = {m["attributes"]["team_id"] for m in body[0]["metrics"]}
|
||||
assert team_ids == {"team-a", "team-b"}
|
||||
assert logger.log_queue == []
|
||||
|
||||
|
||||
class TestStopFlag:
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_ends_periodic_flush_loop(self):
|
||||
logger = _make_logger()
|
||||
logger.flush_interval = 0.01
|
||||
logger.flush_queue = AsyncMock()
|
||||
|
||||
task = asyncio.create_task(logger.periodic_flush())
|
||||
await asyncio.sleep(0.05)
|
||||
assert not task.done()
|
||||
|
||||
logger.stop()
|
||||
await asyncio.wait_for(task, timeout=1.0)
|
||||
|
||||
assert task.done()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stopped_logger_exits_after_one_final_drain(self):
|
||||
logger = _make_logger()
|
||||
logger.flush_interval = 0.01
|
||||
logger._final_drain = AsyncMock()
|
||||
logger._stopped = True
|
||||
|
||||
await asyncio.wait_for(logger.periodic_flush(), timeout=1.0)
|
||||
|
||||
logger._final_drain.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_eviction_drains_queued_records(self):
|
||||
"""Eviction must post what is already queued, not silently discard it."""
|
||||
from litellm.litellm_core_utils.specialty_caches.dynamic_logging_cache import (
|
||||
DynamicLoggingCache,
|
||||
)
|
||||
|
||||
cache = DynamicLoggingCache()
|
||||
logger = _make_logger()
|
||||
logger.log_queue = [_record(), _record(team_id="team-b")]
|
||||
logger.async_client.post = AsyncMock(return_value=_response(202))
|
||||
credentials = {"newrelic_api_key": "test-key", "newrelic_region": None}
|
||||
cache.set_cache(credentials=credentials, service_name="newrelic", logging_obj=logger)
|
||||
|
||||
key = cache.get_cache_key(args={**credentials, "service_name": "newrelic"})
|
||||
cache.cache._remove_key(key)
|
||||
for _ in range(10):
|
||||
await asyncio.sleep(0)
|
||||
|
||||
logger.async_client.post.assert_awaited_once()
|
||||
body = json.loads(gzip.decompress(logger.async_client.post.await_args.kwargs["data"]).decode("utf-8"))
|
||||
team_ids = {m["attributes"]["team_id"] for m in body[0]["metrics"]}
|
||||
assert team_ids == {"team-a", "team-b"}
|
||||
assert logger.log_queue == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dynamic_logging_cache_eviction_calls_stop(self):
|
||||
from litellm.litellm_core_utils.specialty_caches.dynamic_logging_cache import (
|
||||
DynamicLoggingCache,
|
||||
)
|
||||
|
||||
cache = DynamicLoggingCache()
|
||||
logger = _make_logger()
|
||||
credentials = {"newrelic_api_key": "test-key", "newrelic_region": None}
|
||||
cache.set_cache(credentials=credentials, service_name="newrelic", logging_obj=logger)
|
||||
|
||||
key = cache.get_cache_key(args={**credentials, "service_name": "newrelic"})
|
||||
cache.cache._remove_key(key)
|
||||
|
||||
assert logger._stopped is True
|
||||
assert cache.get_cache(credentials=credentials, service_name="newrelic") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_append_after_eviction_drain_self_flushes():
|
||||
"""An in-flight callback holding an evicted (stopped) logger still delivers
|
||||
its record: with no periodic loop left, the append itself drains."""
|
||||
logger = _make_logger()
|
||||
with patch.object(
|
||||
logger.async_client, "post", new=AsyncMock(return_value=_response(202))
|
||||
) as mock_post:
|
||||
logger.stop()
|
||||
await logger.async_log_success_event(
|
||||
{"standard_logging_object": _standard_logging_object()}, None, None, None
|
||||
)
|
||||
assert mock_post.await_count >= 1, "record appended after stop() must be flushed, not stranded"
|
||||
assert logger.log_queue == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_final_drain_retries_transient_failure_then_delivers():
|
||||
"""A transient 5xx during the eviction drain must not strand the last
|
||||
batch: the final drain retries on its own (no periodic loop is left)."""
|
||||
logger = _make_logger()
|
||||
err = _response(500)
|
||||
responses = [HTTPStatusError('e', request=err.request, response=err), HTTPStatusError('e', request=err.request, response=err), _response(202)]
|
||||
post_mock = AsyncMock(side_effect=responses)
|
||||
with patch.object(logger, "async_client") as client, patch("asyncio.sleep", new=AsyncMock()):
|
||||
client.post = post_mock
|
||||
await logger._log_async_event(standard_logging_object=_standard_logging_object())
|
||||
await logger._final_drain()
|
||||
assert post_mock.await_count == 3
|
||||
assert logger.log_queue == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_final_drain_drops_after_bounded_passes_under_lock():
|
||||
"""A permanently failing destination is retried across bounded passes, then
|
||||
the remainder is dropped under flush_lock and logged, never stranded. A
|
||||
second drain over the now-empty queue is a no-op."""
|
||||
logger = _make_logger()
|
||||
post_mock = _raises(500)
|
||||
with patch.object(logger, "async_client") as client, patch("asyncio.sleep", new=AsyncMock()):
|
||||
client.post = post_mock
|
||||
await logger._log_async_event(standard_logging_object=_standard_logging_object())
|
||||
await logger._final_drain()
|
||||
after_first = post_mock.await_count
|
||||
await logger._final_drain()
|
||||
assert after_first >= 1, "the failing destination was retried before the drop"
|
||||
assert post_mock.await_count == after_first, "second drain over an empty queue is a no-op"
|
||||
assert logger.log_queue == [], "exhausted retries end in a logged drop, not a stranded queue"
|
||||
|
||||
|
||||
def test_attribute_values_bounded_against_payload_bombs():
|
||||
"""A caller-controlled high-entropy model string is truncated in metric
|
||||
attributes so one record cannot inflate the shared batch past the Metric
|
||||
API payload cap and take out other users' metrics."""
|
||||
record = _record(model="m" * 5000)
|
||||
metrics = _bucket_metrics((record,))
|
||||
for metric in metrics:
|
||||
assert len(metric["attributes"]["model"]) == 255
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_idle_gap_does_not_inflate_next_window():
|
||||
"""Empty flush cycles advance the window start, so a burst after idling
|
||||
reports an interval close to the flush cadence, not the whole idle gap."""
|
||||
logger = _make_logger()
|
||||
logger.last_flush_time = 100.0
|
||||
with patch.object(logger, "async_client") as client:
|
||||
client.post = AsyncMock(return_value=_response(202))
|
||||
await logger.flush_queue()
|
||||
assert logger.last_flush_time > 100.0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mid_drain_append_delivered_against_healthy_destination():
|
||||
"""A record a callback appends while a drain is running is picked up by a
|
||||
later pass and delivered when the destination is healthy; nothing stranded."""
|
||||
logger = _make_logger()
|
||||
logger.stop()
|
||||
late_record = _record(model="late-model")
|
||||
injected = {"done": False}
|
||||
posted = []
|
||||
|
||||
async def _capture(url, headers=None, content=None, **kw):
|
||||
posted.append(content)
|
||||
if not injected["done"]:
|
||||
injected["done"] = True
|
||||
logger.log_queue.append(late_record)
|
||||
return _response(202)
|
||||
|
||||
with patch.object(logger, "async_client") as client, patch("asyncio.sleep", new=AsyncMock()):
|
||||
client.post = _capture
|
||||
logger.log_queue.append(_record(model="first"))
|
||||
await logger._drain_with_retry()
|
||||
assert logger.log_queue == [], "the mid-drain append was drained too, nothing stranded"
|
||||
assert len(posted) >= 2, "both the original and the mid-drain record were sent"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_drain_attempts_every_chunk_not_just_the_head_under_failure():
|
||||
"""Regression: with more than batch_size records queued on a stopped logger
|
||||
and a persistently failing destination, every record must be attempted before
|
||||
the bounded terminal drop. The periodic path stops at the first failing chunk,
|
||||
so a drain that reused it would drop the un-sent tail (records past the head
|
||||
chunk) as if it had tried them, silently undercounting the team's usage."""
|
||||
logger = _make_logger()
|
||||
logger.stop()
|
||||
logger.batch_size = 2
|
||||
logger.log_queue = [_record(model=f"m{i}") for i in range(5)]
|
||||
sent_models = []
|
||||
|
||||
async def _capture_then_fail(url, data=None, headers=None, **kw):
|
||||
body = json.loads(gzip.decompress(data).decode("utf-8"))
|
||||
sent_models.extend(
|
||||
m["attributes"]["model"] for m in body[0]["metrics"] if m["name"] == NEWRELIC_METRIC_REQUESTS
|
||||
)
|
||||
resp = _response(503)
|
||||
raise HTTPStatusError("err", request=resp.request, response=resp)
|
||||
|
||||
with patch("asyncio.sleep", new=AsyncMock()):
|
||||
logger.async_client.post = _capture_then_fail
|
||||
await logger._drain_with_retry()
|
||||
|
||||
assert set(sent_models) == {"m0", "m1", "m2", "m3", "m4"}, "every chunk, including the tail, was attempted"
|
||||
assert logger.log_queue == [], "the exhausted batch is dropped after bounded passes, nothing stranded"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_drain_delivers_the_tail_once_the_destination_recovers():
|
||||
"""The tail beyond the head chunk must be delivered, not stranded, once a
|
||||
transiently failing destination recovers within the drain's passes."""
|
||||
logger = _make_logger()
|
||||
logger.stop()
|
||||
logger.batch_size = 2
|
||||
logger.log_queue = [_record(model=f"m{i}") for i in range(5)]
|
||||
delivered_models = []
|
||||
posts = {"n": 0}
|
||||
|
||||
async def _fail_first_pass_then_recover(url, data=None, headers=None, **kw):
|
||||
posts["n"] += 1
|
||||
if posts["n"] <= 3: # the first pass's three chunks all fail
|
||||
resp = _response(503)
|
||||
raise HTTPStatusError("err", request=resp.request, response=resp)
|
||||
body = json.loads(gzip.decompress(data).decode("utf-8"))
|
||||
delivered_models.extend(
|
||||
m["attributes"]["model"] for m in body[0]["metrics"] if m["name"] == NEWRELIC_METRIC_REQUESTS
|
||||
)
|
||||
return _response(202)
|
||||
|
||||
with patch("asyncio.sleep", new=AsyncMock()):
|
||||
logger.async_client.post = _fail_first_pass_then_recover
|
||||
await logger._drain_with_retry()
|
||||
|
||||
assert set(delivered_models) == {"m0", "m1", "m2", "m3", "m4"}, "all chunks delivered after recovery"
|
||||
assert logger.log_queue == [], "nothing left stranded once the destination recovered"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_terminal_drop_leaves_untried_late_arrival_for_next_drain():
|
||||
"""Against a permanently failing destination, the terminal drop clears only
|
||||
the records this drain actually tried; a record a callback appends during the
|
||||
final pass, after that pass's snapshot, is left in the queue for its own
|
||||
serialized drain, never wiped un-tried."""
|
||||
logger = _make_logger()
|
||||
logger.stop()
|
||||
from litellm.types.integrations.newrelic import NEWRELIC_METRICS_MAX_DRAIN_PASSES
|
||||
|
||||
late_record = _record(model="late-arrival")
|
||||
posts = {"n": 0}
|
||||
|
||||
async def _fail_and_append_on_final_pass(url, data=None, headers=None, **kw):
|
||||
posts["n"] += 1
|
||||
# One record means one post per pass, so the final pass's post is the
|
||||
# Nth; append then, after the drain has already snapshotted the queue.
|
||||
if posts["n"] == NEWRELIC_METRICS_MAX_DRAIN_PASSES:
|
||||
logger.log_queue.append(late_record)
|
||||
resp = _response(503)
|
||||
raise HTTPStatusError("err", request=resp.request, response=resp)
|
||||
|
||||
with patch("asyncio.sleep", new=AsyncMock()):
|
||||
logger.async_client.post = _fail_and_append_on_final_pass
|
||||
logger.log_queue.append(_record(model="doomed"))
|
||||
await logger._drain_with_retry()
|
||||
assert logger.log_queue == [late_record], "the un-tried late arrival is left for its own drain, not dropped"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_record_appended_on_an_early_pass_is_not_dropped_short_of_the_retry_budget():
|
||||
"""A record a callback appends during an early drain pass entered the queue
|
||||
after this drain's snapshot, so it has not seen the full retry budget. The
|
||||
terminal drop must clear only records queued when the drain began, leaving
|
||||
the early-pass arrival for its own serialized drain instead of dropping it
|
||||
after fewer than the configured attempts."""
|
||||
logger = _make_logger()
|
||||
logger.stop()
|
||||
early_record = _record(model="early-pass-arrival")
|
||||
posts = {"n": 0}
|
||||
|
||||
async def _fail_and_append_on_first_pass(url, data=None, headers=None, **kw):
|
||||
posts["n"] += 1
|
||||
# One record queued at start means the first pass's post is the 1st;
|
||||
# append during it, before this drain's later passes.
|
||||
if posts["n"] == 1:
|
||||
logger.log_queue.append(early_record)
|
||||
resp = _response(503)
|
||||
raise HTTPStatusError("err", request=resp.request, response=resp)
|
||||
|
||||
with patch("asyncio.sleep", new=AsyncMock()):
|
||||
logger.async_client.post = _fail_and_append_on_first_pass
|
||||
logger.log_queue.append(_record(model="doomed"))
|
||||
await logger._drain_with_retry()
|
||||
assert logger.log_queue == [early_record], "the early-pass arrival is left for its own drain, not dropped short"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_post_stop_drains_are_serialized():
|
||||
"""A callback that appends to a stopped logger and starts its own drain must
|
||||
queue behind an already-running drain, not race it: otherwise one drain's
|
||||
terminal clear could wipe a record the other is still responsible for.
|
||||
Proven by holding the first drain inside its flush and asserting the second
|
||||
has not entered its own flush until the first releases."""
|
||||
logger = _make_logger()
|
||||
logger._stopped = True # stopped without scheduling a background drain
|
||||
logger.log_queue.append(_record(model="r1"))
|
||||
entered = []
|
||||
release = asyncio.Event()
|
||||
|
||||
async def blocking_flush():
|
||||
entered.append(len(entered) + 1)
|
||||
if len(entered) == 1:
|
||||
await release.wait()
|
||||
logger.log_queue.clear()
|
||||
|
||||
logger._drain_flush_once = blocking_flush
|
||||
t1 = asyncio.create_task(logger._drain_with_retry())
|
||||
await asyncio.sleep(0.02) # let t1 acquire the drain lock and enter flush
|
||||
assert entered == [1], f"first drain did not enter flush: {entered}"
|
||||
t2 = asyncio.create_task(logger._drain_with_retry())
|
||||
await asyncio.sleep(0.02) # t2 must block on the drain lock, not enter flush
|
||||
assert entered == [1], f"second drain raced the first: {entered}"
|
||||
release.set()
|
||||
await asyncio.gather(t1, t2)
|
||||
assert logger.log_queue == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_raised_403_is_dropped_not_requeued():
|
||||
"""AsyncHTTPHandler.post raises HTTPStatusError on 4xx, so a 403 (permanent
|
||||
bad key) arrives as an exception, not a response. It must be dropped, never
|
||||
requeued, or a revoked key retries forever."""
|
||||
logger = _make_logger()
|
||||
logger.log_queue.append(_record())
|
||||
logger.async_client.post = _raises(403)
|
||||
await logger.async_send_batch()
|
||||
assert logger.log_queue == [], "a permanent 403 must drop, not requeue"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_raised_500_is_requeued():
|
||||
"""A raised 5xx is transient and must be requeued for retry."""
|
||||
logger = _make_logger()
|
||||
record = _record()
|
||||
logger.log_queue.append(record)
|
||||
logger.async_client.post = _raises(503)
|
||||
await logger.async_send_batch()
|
||||
assert logger.log_queue == [record], "a transient 5xx must requeue"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status", [429, 408])
|
||||
async def test_transient_4xx_is_requeued_not_dropped(status):
|
||||
"""The Metric API returns 429 when it throttles (and 408 on a request
|
||||
timeout); both are transient and expect a retry, so the batch must be
|
||||
requeued rather than permanently dropped like a 400/403."""
|
||||
logger = _make_logger()
|
||||
record = _record()
|
||||
logger.log_queue.append(record)
|
||||
logger.async_client.post = _raises(status)
|
||||
await logger.async_send_batch()
|
||||
assert logger.log_queue == [record], f"a transient {status} must requeue, not drop"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status", [200, 201, 204])
|
||||
async def test_any_2xx_is_treated_as_delivered_not_requeued(status):
|
||||
"""The Metric API answers 202, but any 2xx means the destination accepted the
|
||||
batch. Treating a non-202 2xx as a failure would re-queue and re-send data
|
||||
New Relic already stored, duplicating the team's metrics until the cap drops."""
|
||||
logger = _make_logger()
|
||||
logger.log_queue.append(_record())
|
||||
logger.async_client.post = AsyncMock(return_value=_response(status))
|
||||
await logger.async_send_batch()
|
||||
assert logger.log_queue == [], f"a {status} success must drop, not requeue and duplicate"
|
||||
|
|
@ -0,0 +1,274 @@
|
|||
"""
|
||||
Tests for team-scoped New Relic metrics callback support.
|
||||
|
||||
Verifies that NewRelicMetricsLogger is instantiated with per-team credentials
|
||||
(newrelic_api_key, newrelic_region) with no environment fallback, and that
|
||||
NewRelicHandler correctly resolves and caches per-team loggers.
|
||||
"""
|
||||
|
||||
import copy
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from litellm.integrations.newrelic.newrelic_metrics import NewRelicMetricsLogger
|
||||
from litellm.integrations.newrelic.newrelic_team_handler import NewRelicHandler
|
||||
from litellm.litellm_core_utils.initialize_dynamic_callback_params import (
|
||||
TRUSTED_CALLBACK_VARS_FIELD,
|
||||
)
|
||||
from litellm.litellm_core_utils.specialty_caches.dynamic_logging_cache import (
|
||||
DynamicLoggingCache,
|
||||
)
|
||||
from litellm.types.integrations.newrelic import NEWRELIC_METRIC_ENDPOINT_BY_REGION
|
||||
from litellm.types.utils import StandardCallbackDynamicParams
|
||||
|
||||
US_ENDPOINT = NEWRELIC_METRIC_ENDPOINT_BY_REGION["us"]
|
||||
EU_ENDPOINT = NEWRELIC_METRIC_ENDPOINT_BY_REGION["eu"]
|
||||
|
||||
|
||||
class TestNewRelicMetricsLoggerCredentialKwargs:
|
||||
"""The logger takes credentials by injection only; env vars never leak in."""
|
||||
|
||||
def test_init_with_explicit_credentials(self):
|
||||
with patch("asyncio.create_task"):
|
||||
logger = NewRelicMetricsLogger(newrelic_api_key="team_key", newrelic_region="eu")
|
||||
|
||||
assert logger.newrelic_api_key == "team_key"
|
||||
assert logger.metric_api_url == EU_ENDPOINT
|
||||
|
||||
def test_init_defaults_to_us_region(self):
|
||||
with patch("asyncio.create_task"):
|
||||
logger = NewRelicMetricsLogger(newrelic_api_key="team_key")
|
||||
|
||||
assert logger.metric_api_url == US_ENDPOINT
|
||||
|
||||
def test_unknown_region_falls_back_to_us(self):
|
||||
with patch("asyncio.create_task"):
|
||||
logger = NewRelicMetricsLogger(newrelic_api_key="team_key", newrelic_region="mars")
|
||||
|
||||
assert logger.metric_api_url == US_ENDPOINT
|
||||
|
||||
def test_region_is_case_insensitive(self):
|
||||
with patch("asyncio.create_task"):
|
||||
logger = NewRelicMetricsLogger(newrelic_api_key="team_key", newrelic_region="EU")
|
||||
|
||||
assert logger.metric_api_url == EU_ENDPOINT
|
||||
|
||||
def test_init_raises_without_api_key(self):
|
||||
with pytest.raises(ValueError, match="newrelic_api_key"):
|
||||
with patch("asyncio.create_task"):
|
||||
NewRelicMetricsLogger(newrelic_api_key="")
|
||||
|
||||
def test_init_never_falls_back_to_env_license_key(self, monkeypatch):
|
||||
"""A missing team key must fail, never silently reuse the operator's key."""
|
||||
monkeypatch.setenv("NEW_RELIC_LICENSE_KEY", "operator-license-key")
|
||||
|
||||
with pytest.raises(ValueError, match="newrelic_api_key"):
|
||||
with patch("asyncio.create_task"):
|
||||
NewRelicMetricsLogger(newrelic_api_key="")
|
||||
|
||||
|
||||
class TestNewRelicHandler:
|
||||
"""The handler resolves the correct logger per team."""
|
||||
|
||||
def test_creates_team_logger_with_dynamic_credentials(self):
|
||||
cache = DynamicLoggingCache()
|
||||
params = StandardCallbackDynamicParams(newrelic_api_key="team_a_key", newrelic_region="eu")
|
||||
|
||||
with patch("asyncio.create_task"):
|
||||
result = NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=params,
|
||||
in_memory_dynamic_logger_cache=cache,
|
||||
)
|
||||
|
||||
assert result.newrelic_api_key == "team_a_key"
|
||||
assert result.metric_api_url == EU_ENDPOINT
|
||||
|
||||
def test_caches_team_logger(self):
|
||||
cache = DynamicLoggingCache()
|
||||
params = StandardCallbackDynamicParams(newrelic_api_key="team_b_key")
|
||||
|
||||
with patch("asyncio.create_task"):
|
||||
result1 = NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=params,
|
||||
in_memory_dynamic_logger_cache=cache,
|
||||
)
|
||||
result2 = NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=params,
|
||||
in_memory_dynamic_logger_cache=cache,
|
||||
)
|
||||
|
||||
assert result1 is result2
|
||||
|
||||
def test_different_teams_get_different_loggers(self):
|
||||
cache = DynamicLoggingCache()
|
||||
params_a = StandardCallbackDynamicParams(newrelic_api_key="team_a_key")
|
||||
params_b = StandardCallbackDynamicParams(newrelic_api_key="team_b_key")
|
||||
|
||||
with patch("asyncio.create_task"):
|
||||
result_a = NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=params_a,
|
||||
in_memory_dynamic_logger_cache=cache,
|
||||
)
|
||||
result_b = NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=params_b,
|
||||
in_memory_dynamic_logger_cache=cache,
|
||||
)
|
||||
|
||||
assert result_a is not result_b
|
||||
assert result_a.newrelic_api_key == "team_a_key"
|
||||
assert result_b.newrelic_api_key == "team_b_key"
|
||||
|
||||
def test_region_is_part_of_cache_key(self):
|
||||
"""Same key, different region must not share a logger (different endpoints)."""
|
||||
cache = DynamicLoggingCache()
|
||||
|
||||
with patch("asyncio.create_task"):
|
||||
result_us = NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=StandardCallbackDynamicParams(newrelic_api_key="key"),
|
||||
in_memory_dynamic_logger_cache=cache,
|
||||
)
|
||||
result_eu = NewRelicHandler.get_newrelic_logger_for_request(
|
||||
standard_callback_dynamic_params=StandardCallbackDynamicParams(
|
||||
newrelic_api_key="key", newrelic_region="eu"
|
||||
),
|
||||
in_memory_dynamic_logger_cache=cache,
|
||||
)
|
||||
|
||||
assert result_us is not result_eu
|
||||
assert result_us.metric_api_url == US_ENDPOINT
|
||||
assert result_eu.metric_api_url == EU_ENDPOINT
|
||||
|
||||
def test_request_blocked_callback_params_includes_newrelic(self):
|
||||
from litellm.litellm_core_utils.initialize_dynamic_callback_params import (
|
||||
_request_blocked_callback_params,
|
||||
)
|
||||
|
||||
assert "newrelic_api_key" in _request_blocked_callback_params
|
||||
assert "newrelic_region" in _request_blocked_callback_params
|
||||
|
||||
|
||||
class TestDynamicCredentialDetection:
|
||||
def test_no_credentials(self):
|
||||
params = StandardCallbackDynamicParams()
|
||||
assert NewRelicHandler._dynamic_newrelic_credentials_are_passed(params) is False
|
||||
|
||||
def test_region_only_is_not_credentials(self):
|
||||
params = StandardCallbackDynamicParams(newrelic_region="eu")
|
||||
assert NewRelicHandler._dynamic_newrelic_credentials_are_passed(params) is False
|
||||
|
||||
def test_api_key_is_credentials(self):
|
||||
params = StandardCallbackDynamicParams(newrelic_api_key="key")
|
||||
assert NewRelicHandler._dynamic_newrelic_credentials_are_passed(params) is True
|
||||
|
||||
|
||||
class TestStandardCallbackDynamicParamsIncludesNewRelic:
|
||||
def test_newrelic_params_in_annotations(self):
|
||||
annotations = StandardCallbackDynamicParams.__annotations__
|
||||
assert "newrelic_api_key" in annotations
|
||||
assert "newrelic_region" in annotations
|
||||
|
||||
|
||||
def _build_logging_obj(kwargs: dict, *, with_newrelic_callback: bool = True):
|
||||
from litellm.litellm_core_utils.litellm_logging import Logging
|
||||
|
||||
with patch("asyncio.create_task"):
|
||||
return Logging(
|
||||
model="gpt-4",
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
stream=False,
|
||||
call_type="completion",
|
||||
start_time="2026-01-01",
|
||||
litellm_call_id="test-call-id",
|
||||
function_id="test-func",
|
||||
dynamic_success_callbacks=["newrelic"] if with_newrelic_callback else None,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _metrics_loggers(logging_obj) -> list[NewRelicMetricsLogger]:
|
||||
return [cb for cb in (logging_obj.dynamic_success_callbacks or []) if isinstance(cb, NewRelicMetricsLogger)]
|
||||
|
||||
|
||||
class TestTeamCallbackFlowPassesNewRelicCredentials:
|
||||
"""
|
||||
newrelic_* credentials reach NewRelicHandler only from the proxy-stamped trusted
|
||||
field. Anything the caller put in the request body must not, or a caller could
|
||||
pair its own newrelic_region with the team's ingest key.
|
||||
"""
|
||||
|
||||
def test_trusted_callback_vars_reach_newrelic_handler(self):
|
||||
logging_obj = _build_logging_obj(
|
||||
{
|
||||
TRUSTED_CALLBACK_VARS_FIELD: {"newrelic_api_key": "team-nr-key-123", "newrelic_region": "eu"},
|
||||
"model": "gpt-4",
|
||||
"litellm_params": {"metadata": {}},
|
||||
}
|
||||
)
|
||||
|
||||
metrics_loggers = _metrics_loggers(logging_obj)
|
||||
assert len(metrics_loggers) == 1, "NewRelicMetricsLogger should be initialized from team callback_vars"
|
||||
assert metrics_loggers[0].newrelic_api_key == "team-nr-key-123"
|
||||
assert metrics_loggers[0].metric_api_url == EU_ENDPOINT
|
||||
|
||||
def test_trace_logger_still_dispatched_alongside_metrics(self):
|
||||
"""The metrics logger must not displace the trace logger for the same name."""
|
||||
logging_obj = _build_logging_obj(
|
||||
{
|
||||
TRUSTED_CALLBACK_VARS_FIELD: {"newrelic_api_key": "team-nr-key-123"},
|
||||
"model": "gpt-4",
|
||||
"litellm_params": {"metadata": {}},
|
||||
}
|
||||
)
|
||||
|
||||
non_metrics = [
|
||||
cb for cb in (logging_obj.dynamic_success_callbacks or []) if not isinstance(cb, NewRelicMetricsLogger)
|
||||
]
|
||||
assert len(non_metrics) == 1, "trace logger (OTel v2 or legacy agent) must remain in the dynamic list"
|
||||
assert len(_metrics_loggers(logging_obj)) == 1
|
||||
async_non_metrics = [
|
||||
cb
|
||||
for cb in (logging_obj.dynamic_async_success_callbacks or [])
|
||||
if not isinstance(cb, NewRelicMetricsLogger)
|
||||
]
|
||||
assert len(async_non_metrics) == 1
|
||||
|
||||
def test_request_kwargs_newrelic_params_are_ignored(self):
|
||||
logging_obj = _build_logging_obj(
|
||||
{
|
||||
"newrelic_api_key": "caller-nr-key",
|
||||
"newrelic_region": "eu",
|
||||
"model": "gpt-4",
|
||||
"litellm_params": {"metadata": {}},
|
||||
}
|
||||
)
|
||||
|
||||
assert _metrics_loggers(logging_obj) == []
|
||||
|
||||
def test_logging_object_stays_deepcopyable(self):
|
||||
logging_obj = _build_logging_obj(
|
||||
{
|
||||
TRUSTED_CALLBACK_VARS_FIELD: {"newrelic_api_key": "team-nr-key-123"},
|
||||
"model": "gpt-4",
|
||||
"litellm_params": {"metadata": {}},
|
||||
},
|
||||
with_newrelic_callback=False,
|
||||
)
|
||||
|
||||
assert copy.deepcopy(logging_obj)._trusted_callback_vars == logging_obj._trusted_callback_vars
|
||||
|
||||
def test_caller_cannot_redirect_team_credentials(self):
|
||||
"""The exfil shape: caller's newrelic_region paired with the team's key."""
|
||||
logging_obj = _build_logging_obj(
|
||||
{
|
||||
TRUSTED_CALLBACK_VARS_FIELD: {"newrelic_api_key": "team-nr-key-123"},
|
||||
"newrelic_region": "eu",
|
||||
"model": "gpt-4",
|
||||
"litellm_params": {"metadata": {}},
|
||||
}
|
||||
)
|
||||
|
||||
metrics_loggers = _metrics_loggers(logging_obj)
|
||||
assert len(metrics_loggers) == 1
|
||||
assert metrics_loggers[0].newrelic_api_key == "team-nr-key-123"
|
||||
assert metrics_loggers[0].metric_api_url == US_ENDPOINT
|
||||
|
|
@ -357,6 +357,92 @@ def test_release_without_eviction_keeps_provider_alive(monkeypatch):
|
|||
cache.release(None) # default-route release is a no-op
|
||||
|
||||
|
||||
# --- per-request service.name routing from trusted key/team config --- #
|
||||
|
||||
|
||||
def test_tenant_service_name_precedence_and_blanks():
|
||||
from litellm.integrations.otel.plumbing.routing import tenant_service_name
|
||||
|
||||
assert tenant_service_name({"otel_service_name": "team-svc"}) == "team-svc"
|
||||
assert tenant_service_name({"otel_service_name_override": "override", "otel_service_name": "base"}) == "override"
|
||||
assert tenant_service_name({"otel_service_name": " "}) is None
|
||||
assert tenant_service_name({"logging_setting": "x"}) is None
|
||||
assert tenant_service_name(None) is None
|
||||
|
||||
|
||||
def test_key_override_survives_team_metadata_merge():
|
||||
from litellm.integrations.otel.plumbing.routing import tenant_service_name
|
||||
|
||||
# Request setup merges team metadata over key metadata (last writer wins),
|
||||
# so a key keeps its own destination via ``otel_service_name_override``,
|
||||
# which a team defining only ``otel_service_name`` never touches.
|
||||
merged = {"otel_service_name_override": "key-svc"}
|
||||
merged.update({"otel_service_name": "team-svc"})
|
||||
assert tenant_service_name(merged) == "key-svc"
|
||||
|
||||
|
||||
def test_provider_cached_per_service_name():
|
||||
cache = _cache("otel")
|
||||
default = NoOpTracer()
|
||||
routed = cache.route_for(default, None, {"otel_service_name": "payments-gateway"})
|
||||
assert routed.tracer is not default
|
||||
assert routed.detached is False # stays parented into the request trace
|
||||
assert routed.provider is not None
|
||||
assert routed.provider.resource.attributes["service.name"] == "payments-gateway"
|
||||
cache.route_for(default, None, {"otel_service_name": "payments-gateway"})
|
||||
assert len(cache._providers) == 1
|
||||
cache.route_for(default, None, {"otel_service_name": "search-gateway"})
|
||||
assert len(cache._providers) == 2
|
||||
for provider in cache._providers.values():
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def test_service_name_routed_span_carries_team_service_name(monkeypatch):
|
||||
# The artifact the exporter receives: the finished span's Resource must
|
||||
# carry the team's service.name, not the env-configured default.
|
||||
monkeypatch.setenv("OTEL_SERVICE_NAME", "proxy-default")
|
||||
cache = _cache("otel")
|
||||
default = NoOpTracer()
|
||||
route = cache.route_for(default, None, {"otel_service_name": "payments-gateway"})
|
||||
with route.tracer.start_as_current_span("chat gpt-4o-mini") as span:
|
||||
pass
|
||||
assert span.resource.attributes["service.name"] == "payments-gateway"
|
||||
cache.release(route.provider)
|
||||
|
||||
unrouted = cache.route_for(default, None, {"logging_setting": "x"})
|
||||
assert unrouted.tracer is default # env fallback: no scoped provider built
|
||||
|
||||
|
||||
def test_client_dynamic_params_cannot_choose_service_name():
|
||||
# ``StandardCallbackDynamicParams`` is populated from client-supplied
|
||||
# request metadata; the service name may only come from server-set
|
||||
# key/team config (the ``auth_metadata`` argument).
|
||||
cache = _cache("otel")
|
||||
default = NoOpTracer()
|
||||
assert cache.route_for(default, {"otel_service_name": "attacker"}).tracer is default
|
||||
assert cache.route_for(default, {"otel_service_name_override": "attacker"}).tracer is default
|
||||
assert cache._providers == {}
|
||||
|
||||
|
||||
def test_service_name_override_leaves_exporters_untouched():
|
||||
cache = _cache(
|
||||
"otel",
|
||||
exporters=[
|
||||
ExporterSpec(
|
||||
kind="otlp_http",
|
||||
endpoint="http://collector:4318",
|
||||
headers="x=base-collector",
|
||||
owner=None,
|
||||
),
|
||||
],
|
||||
)
|
||||
cfg = cache._routed_config({}, {}, None, "payments-gateway")
|
||||
assert cfg.service_name == "payments-gateway"
|
||||
(spec,) = cfg.exporters
|
||||
assert spec.headers == "x=base-collector"
|
||||
assert spec.endpoint == "http://collector:4318"
|
||||
|
||||
|
||||
# --- New Relic: per-team api-key header + fixed-table region endpoint --- #
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@ import pytest
|
|||
|
||||
from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import (
|
||||
StandardBuiltInToolCostTracking,
|
||||
get_web_search_requests,
|
||||
)
|
||||
from litellm.litellm_core_utils.llm_cost_calc.utils import get_web_search_requests
|
||||
from litellm.types.utils import ModelResponse, ServerToolUse, Usage
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1002,6 +1002,17 @@ def test_an_exception_without_a_status_is_still_a_connection_error(quiet_excepti
|
|||
)
|
||||
|
||||
|
||||
def test_an_unmapped_exception_with_no_model_or_provider_is_a_connection_error(quiet_exception_mapping):
|
||||
with pytest.raises(litellm.APIConnectionError) as raised:
|
||||
exception_type(
|
||||
model=None,
|
||||
original_exception=ValueError("boom"),
|
||||
custom_llm_provider=None,
|
||||
)
|
||||
|
||||
assert "boom" in raised.value.message
|
||||
|
||||
|
||||
CONTEXT_WINDOW_MESSAGE = "This model's maximum context length is 4096 tokens."
|
||||
CONTENT_POLICY_MESSAGE = (
|
||||
'{"error": {"type": "invalid_request_error", "code": "content_policy_violation"}}'
|
||||
|
|
|
|||
|
|
@ -2957,3 +2957,65 @@ async def test_log_messages_routes_async_logging_through_bounded_worker():
|
|||
logging_obj.success_handler.assert_not_called()
|
||||
# the bare create_task path must no longer be used for success logging
|
||||
mock_create_task.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_provider_config_path_captures_transcription_usage():
|
||||
"""A transcription.completed event with usage from the provider transform must
|
||||
land in the logged messages so realtime cost calculation can bill it."""
|
||||
from typing import Final
|
||||
|
||||
from litellm.types.realtime import RealtimeInputAudioTranscriptionUsage, RealtimeResponseTypedDict
|
||||
|
||||
client_ws: Final = MagicMock()
|
||||
client_ws.send_text = AsyncMock()
|
||||
backend_ws: Final = MagicMock()
|
||||
backend_ws.send = AsyncMock()
|
||||
logging_obj: Final = MagicMock()
|
||||
|
||||
usage: Final[RealtimeInputAudioTranscriptionUsage] = {
|
||||
"type": "tokens",
|
||||
"input_tokens": 50,
|
||||
"output_tokens": 6,
|
||||
"total_tokens": 56,
|
||||
"input_token_details": {"text_tokens": 0, "audio_tokens": 50},
|
||||
}
|
||||
transform_output: Final[RealtimeResponseTypedDict] = {
|
||||
"response": {
|
||||
"type": "conversation.item.input_audio_transcription.completed",
|
||||
"event_id": "event_1",
|
||||
"transcript": "ahoy",
|
||||
"item_id": "item_1",
|
||||
"content_index": 0,
|
||||
"usage": usage,
|
||||
},
|
||||
"current_output_item_id": None,
|
||||
"current_response_id": None,
|
||||
"current_delta_chunks": None,
|
||||
"current_conversation_id": None,
|
||||
"current_item_chunks": None,
|
||||
"current_delta_type": None,
|
||||
"session_configuration_request": None,
|
||||
}
|
||||
provider_config: Final = MagicMock()
|
||||
provider_config.transform_realtime_request = MagicMock(return_value=())
|
||||
provider_config.transform_realtime_response = MagicMock(return_value=transform_output)
|
||||
|
||||
streaming: Final = RealTimeStreaming(
|
||||
client_ws,
|
||||
backend_ws,
|
||||
logging_obj,
|
||||
provider_config=provider_config,
|
||||
model="gemini-3.5-transcribe-live",
|
||||
)
|
||||
|
||||
await streaming._handle_provider_config_message("{}")
|
||||
|
||||
usage_events: Final = tuple(
|
||||
message
|
||||
for message in streaming.messages
|
||||
if isinstance(message, dict)
|
||||
and message.get("type") == "conversation.item.input_audio_transcription.completed"
|
||||
and message.get("usage") == usage
|
||||
)
|
||||
assert len(usage_events) == 1
|
||||
|
|
|
|||
|
|
@ -17,7 +17,12 @@ from litellm.anthropic_interface import messages
|
|||
from litellm.integrations.custom_logger import CustomLogger
|
||||
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
|
||||
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
|
||||
from litellm.types.utils import Delta, ModelResponse, StreamingChoices
|
||||
from litellm.types.utils import (
|
||||
Delta,
|
||||
ModelResponse,
|
||||
StandardLoggingPayloadErrorInformation,
|
||||
StreamingChoices,
|
||||
)
|
||||
|
||||
|
||||
def test_anthropic_experimental_pass_through_messages_handler():
|
||||
|
|
@ -1292,7 +1297,7 @@ class TestMessagesStreamingSuccessLogging:
|
|||
class _FailureCapture(CustomLogger):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.error_information: List[Dict[str, Any]] = []
|
||||
self.error_information: list[StandardLoggingPayloadErrorInformation] = []
|
||||
|
||||
async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
|
||||
payload = kwargs.get("standard_logging_object") or {}
|
||||
|
|
|
|||
|
|
@ -8,10 +8,8 @@ See https://github.com/BerriAI/litellm/issues/26153.
|
|||
|
||||
import pytest
|
||||
|
||||
from litellm.llms.anthropic.cost_calculation import (
|
||||
get_cost_for_anthropic_web_search,
|
||||
get_web_search_requests,
|
||||
)
|
||||
from litellm.litellm_core_utils.llm_cost_calc.utils import get_web_search_requests
|
||||
from litellm.llms.anthropic.cost_calculation import get_cost_for_anthropic_web_search
|
||||
from litellm.types.utils import ModelInfo, ServerToolUse
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import pytest
|
|||
|
||||
import litellm
|
||||
from litellm.llms.bedrock.base_aws_llm import Boto3CredentialsInfo
|
||||
from litellm.llms.bedrock.rerank.handler import BedrockRerankHandler
|
||||
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
|
||||
|
||||
# Mock response for Bedrock rerank
|
||||
|
|
@ -402,6 +403,66 @@ def test_bedrock_rerank_extra_headers_and_headers_merge():
|
|||
pytest.fail(f"Failed to merge and forward headers: {str(e)}")
|
||||
|
||||
|
||||
def test_bedrock_rerank_forwarded_headers_excluded_from_sigv4_signature():
|
||||
"""
|
||||
A forwarded header like x-forwarded-for can be rewritten between LiteLLM
|
||||
signing the request and AWS receiving it (e.g. by an intermediate load
|
||||
balancer), which invalidates the signature if that header was part of
|
||||
the signed set. It must still reach Bedrock, just unsigned.
|
||||
"""
|
||||
handler = BedrockRerankHandler()
|
||||
|
||||
prepared_request = handler._prepare_request(
|
||||
model="cohere.rerank-v3-5:0",
|
||||
api_base=None,
|
||||
extra_headers={"x-forwarded-for": "203.0.113.5"},
|
||||
data={"query": test_query, "documents": test_documents},
|
||||
optional_params={
|
||||
"aws_access_key_id": "test-access-key",
|
||||
"aws_secret_access_key": "test-secret-key",
|
||||
"aws_region_name": "us-east-1",
|
||||
},
|
||||
)
|
||||
|
||||
headers = prepared_request["prepped"].headers
|
||||
signed_headers = headers["Authorization"].split("SignedHeaders=")[1].split(",")[0].split(";")
|
||||
|
||||
assert "x-forwarded-for" not in signed_headers, (
|
||||
f"x-forwarded-for must not be part of the SigV4 signature, got SignedHeaders={signed_headers}"
|
||||
)
|
||||
assert headers["x-forwarded-for"] == "203.0.113.5", "forwarded header must still reach Bedrock, unsigned"
|
||||
|
||||
|
||||
def test_bedrock_rerank_signs_with_sigv4_even_when_bedrock_api_key_is_set(monkeypatch):
|
||||
"""
|
||||
Bedrock API keys are only valid for Bedrock and Bedrock Runtime actions, not for
|
||||
Agents for Amazon Bedrock Runtime ones. Rerank is served by bedrock-agent-runtime,
|
||||
so it has to keep signing with SigV4 even when AWS_BEARER_TOKEN_BEDROCK is set.
|
||||
"""
|
||||
monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "test-bedrock-api-key")
|
||||
|
||||
handler = BedrockRerankHandler()
|
||||
|
||||
prepared_request = handler._prepare_request(
|
||||
model="cohere.rerank-v3-5:0",
|
||||
api_base=None,
|
||||
extra_headers=None,
|
||||
data={"query": test_query, "documents": test_documents},
|
||||
optional_params={
|
||||
"aws_access_key_id": "test-access-key",
|
||||
"aws_secret_access_key": "test-secret-key",
|
||||
"aws_region_name": "us-east-1",
|
||||
},
|
||||
)
|
||||
|
||||
assert prepared_request["endpoint_url"].startswith("https://bedrock-agent-runtime.")
|
||||
|
||||
authorization = prepared_request["prepped"].headers["Authorization"]
|
||||
assert authorization.startswith("AWS4-HMAC-SHA256"), (
|
||||
f"rerank must sign with SigV4, got Authorization={authorization[:30]}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bedrock_rerank_records_llm_api_duration():
|
||||
"""The bedrock rerank handler must feed httpx timing into the logging obj, so the
|
||||
|
|
|
|||
|
|
@ -0,0 +1,248 @@
|
|||
import base64
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
|
||||
import litellm
|
||||
from litellm.llms.gemini.audio_transcription.transformation import (
|
||||
GeminiAudioTranscriptionConfig,
|
||||
)
|
||||
from litellm.llms.gemini.common_utils import GeminiError
|
||||
from litellm.types.utils import LlmProviders
|
||||
from litellm.utils import ProviderConfigManager
|
||||
|
||||
AUDIO_BYTES = b"RIFF....WAVEfmt fake-wav-bytes"
|
||||
|
||||
COMPLETED_RESPONSE = {
|
||||
"id": "v1_abc123",
|
||||
"status": "completed",
|
||||
"usage": {
|
||||
"total_tokens": 200,
|
||||
"total_input_tokens": 200,
|
||||
"input_tokens_by_modality": [
|
||||
{"modality": "text", "tokens": 1},
|
||||
{"modality": "audio", "tokens": 199},
|
||||
],
|
||||
"total_output_tokens": 0,
|
||||
},
|
||||
"steps": [
|
||||
{
|
||||
"type": "model_generation",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Hello world.",
|
||||
"annotations": [
|
||||
{
|
||||
"type": "word_info",
|
||||
"text": "Hello",
|
||||
"speaker": "spk:0",
|
||||
"start_offset": "0.100s",
|
||||
"end_offset": "0.400s",
|
||||
},
|
||||
{
|
||||
"type": "word_info",
|
||||
"text": "world.",
|
||||
"speaker": "spk:1",
|
||||
"start_offset": "0.500s",
|
||||
"end_offset": "0.900s",
|
||||
},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def make_response(payload):
|
||||
return httpx.Response(200, json=payload, request=httpx.Request("POST", "https://example.test"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config():
|
||||
return GeminiAudioTranscriptionConfig()
|
||||
|
||||
|
||||
def test_provider_config_manager_returns_gemini_config():
|
||||
provider_config = ProviderConfigManager.get_provider_audio_transcription_config(
|
||||
model="gemini-3.5-transcribe", provider=LlmProviders.GEMINI
|
||||
)
|
||||
assert isinstance(provider_config, GeminiAudioTranscriptionConfig)
|
||||
|
||||
|
||||
class TestValidateEnvironment:
|
||||
def test_sets_api_key_and_revision_headers(self, config):
|
||||
headers = config.validate_environment(
|
||||
headers={},
|
||||
model="gemini-3.5-transcribe",
|
||||
messages=[],
|
||||
optional_params={},
|
||||
litellm_params={},
|
||||
api_key="test-key",
|
||||
)
|
||||
assert headers["x-goog-api-key"] == "test-key"
|
||||
assert headers["Api-Revision"] == "2026-05-20"
|
||||
assert headers["Content-Type"] == "application/json"
|
||||
|
||||
def test_missing_api_key_raises(self, config, monkeypatch):
|
||||
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
|
||||
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||
with pytest.raises(GeminiError) as excinfo:
|
||||
config.validate_environment(
|
||||
headers={},
|
||||
model="gemini-3.5-transcribe",
|
||||
messages=[],
|
||||
optional_params={},
|
||||
litellm_params={},
|
||||
)
|
||||
assert excinfo.value.status_code == 401
|
||||
|
||||
|
||||
class TestGetCompleteUrl:
|
||||
def test_defaults_to_interactions_endpoint(self, config):
|
||||
url = config.get_complete_url(
|
||||
api_base=None,
|
||||
api_key=None,
|
||||
model="gemini-3.5-transcribe",
|
||||
optional_params={},
|
||||
litellm_params={},
|
||||
)
|
||||
assert url == "https://generativelanguage.googleapis.com/v1beta/interactions"
|
||||
|
||||
def test_api_base_override(self, config):
|
||||
url = config.get_complete_url(
|
||||
api_base="http://localhost:8080",
|
||||
api_key=None,
|
||||
model="gemini-3.5-transcribe",
|
||||
optional_params={},
|
||||
litellm_params={},
|
||||
)
|
||||
assert url == "http://localhost:8080/v1beta/interactions"
|
||||
|
||||
|
||||
class TestTransformRequest:
|
||||
def test_builds_json_interaction_request(self, config):
|
||||
request_data = config.transform_audio_transcription_request(
|
||||
model="gemini/gemini-3.5-transcribe",
|
||||
audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"),
|
||||
optional_params={},
|
||||
litellm_params={},
|
||||
)
|
||||
assert request_data.files is None
|
||||
assert json.loads(json.dumps(request_data.data)) == {
|
||||
"model": "gemini-3.5-transcribe",
|
||||
"input": [
|
||||
{
|
||||
"type": "audio",
|
||||
"data": base64.b64encode(AUDIO_BYTES).decode("utf-8"),
|
||||
"mime_type": "audio/wav",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
def test_language_maps_to_bcp47_language_codes(self, config):
|
||||
request_data = config.transform_audio_transcription_request(
|
||||
model="gemini-3.5-transcribe",
|
||||
audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"),
|
||||
optional_params={"language": "en"},
|
||||
litellm_params={},
|
||||
)
|
||||
transcription_config = request_data.data["generation_config"]["transcription_config"]
|
||||
assert json.loads(json.dumps(transcription_config)) == {"language_codes": ["en-US"]}
|
||||
|
||||
def test_word_timestamp_granularity_maps_to_verbatim_diarization_mode(self, config):
|
||||
request_data = config.transform_audio_transcription_request(
|
||||
model="gemini-3.5-transcribe",
|
||||
audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"),
|
||||
optional_params={"timestamp_granularities": ["word"]},
|
||||
litellm_params={},
|
||||
)
|
||||
transcription_config = request_data.data["generation_config"]["transcription_config"]
|
||||
assert json.loads(json.dumps(transcription_config)) == {
|
||||
"mode": {
|
||||
"type": "verbatim",
|
||||
"timestamp_granularities": ["word"],
|
||||
"diarization_mode": "speaker",
|
||||
}
|
||||
}
|
||||
|
||||
def test_segment_granularity_sends_no_mode(self, config):
|
||||
request_data = config.transform_audio_transcription_request(
|
||||
model="gemini-3.5-transcribe",
|
||||
audio_file=("sample.wav", AUDIO_BYTES, "audio/wav"),
|
||||
optional_params={"timestamp_granularities": ["segment"]},
|
||||
litellm_params={},
|
||||
)
|
||||
assert "generation_config" not in request_data.data
|
||||
|
||||
|
||||
class TestTransformResponse:
|
||||
def test_completed_interaction_maps_to_transcription_response(self, config):
|
||||
response = config.transform_audio_transcription_response(make_response(COMPLETED_RESPONSE))
|
||||
assert response.text == "Hello world."
|
||||
assert response["task"] == "transcribe"
|
||||
assert response["words"] == [
|
||||
{"word": "Hello", "start": 0.1, "end": 0.4, "speaker": "spk:0"},
|
||||
{"word": "world.", "start": 0.5, "end": 0.9, "speaker": "spk:1"},
|
||||
]
|
||||
assert response["duration"] == 0.9
|
||||
assert response.usage.input_tokens == 200
|
||||
assert response.usage.output_tokens == 0
|
||||
assert response.usage.total_tokens == 200
|
||||
assert response.usage.input_token_details.audio_tokens == 199
|
||||
assert response.usage.input_token_details.text_tokens == 1
|
||||
|
||||
def test_non_completed_status_raises(self, config):
|
||||
with pytest.raises(GeminiError, match="did not complete"):
|
||||
config.transform_audio_transcription_response(
|
||||
make_response({**COMPLETED_RESPONSE, "status": "in_progress"})
|
||||
)
|
||||
|
||||
def test_non_json_response_raises(self, config):
|
||||
raw = httpx.Response(200, text="<html>oops</html>", request=httpx.Request("POST", "https://example.test"))
|
||||
with pytest.raises(GeminiError, match="non-JSON"):
|
||||
config.transform_audio_transcription_response(raw)
|
||||
|
||||
def test_word_without_offsets_survives(self, config):
|
||||
payload = json.loads(json.dumps(COMPLETED_RESPONSE))
|
||||
payload["steps"][0]["content"][0]["annotations"] = [{"type": "word_info", "text": "Hello"}]
|
||||
response = config.transform_audio_transcription_response(make_response(payload))
|
||||
assert response["words"] == [{"word": "Hello"}]
|
||||
assert response.get("duration") is None
|
||||
|
||||
|
||||
class TestCostRegression:
|
||||
@pytest.fixture
|
||||
def local_cost_map(self, monkeypatch):
|
||||
monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
|
||||
monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))
|
||||
|
||||
def test_registry_entries(self, local_cost_map):
|
||||
batch_entry = litellm.model_cost["gemini/gemini-3.5-transcribe"]
|
||||
assert batch_entry["mode"] == "audio_transcription"
|
||||
assert batch_entry["input_cost_per_audio_token"] == 2e-06
|
||||
assert batch_entry["input_cost_per_token"] == 2e-06
|
||||
assert batch_entry["output_cost_per_token"] == 1.2e-05
|
||||
assert batch_entry["supported_endpoints"] == ["/v1/audio/transcriptions"]
|
||||
|
||||
live_entry = litellm.model_cost["gemini/gemini-3.5-transcribe-live"]
|
||||
assert live_entry["mode"] == "audio_transcription"
|
||||
assert live_entry["input_cost_per_audio_token"] == 3.5e-06
|
||||
assert live_entry["input_cost_per_token"] == 3.5e-06
|
||||
assert live_entry["output_cost_per_token"] == 2.1e-05
|
||||
assert live_entry["supported_endpoints"] == ["/v1/realtime"]
|
||||
|
||||
def test_completion_cost_bills_provider_reported_tokens(self, config, local_cost_map):
|
||||
payload = json.loads(json.dumps(COMPLETED_RESPONSE))
|
||||
payload["usage"]["total_output_tokens"] = 10
|
||||
payload["usage"]["total_tokens"] = 210
|
||||
response = config.transform_audio_transcription_response(make_response(payload))
|
||||
cost = litellm.completion_cost(
|
||||
completion_response=response,
|
||||
model="gemini/gemini-3.5-transcribe",
|
||||
call_type="transcription",
|
||||
)
|
||||
assert cost == pytest.approx(199 * 2e-06 + 1 * 2e-06 + 10 * 1.2e-05)
|
||||
|
|
@ -1864,3 +1864,258 @@ def test_map_openai_params_drops_stock_voice_case_insensitively():
|
|||
|
||||
passthrough = cfg.map_openai_params(optional_params={}, non_default_params={"voice": "Kore"})
|
||||
assert passthrough["generationConfig"]["speechConfig"]["voiceConfig"]["prebuiltVoiceConfig"]["voiceName"] == "Kore"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=False)
|
||||
def patch_gemini_transcribe_live_cost_map_entry(monkeypatch):
|
||||
"""Inject the gemini-3.5-transcribe-live registry entry locally.
|
||||
|
||||
litellm.model_cost is fetched from main branch at import time, so in CI
|
||||
the entry may not exist yet. Also stamp supported_output_modalities on a
|
||||
chat model to prove mode, not output modalities, drives the discriminator.
|
||||
"""
|
||||
for m in ["gemini-3.5-transcribe-live", "gemini/gemini-3.5-transcribe-live"]:
|
||||
entry = dict(litellm.model_cost.get(m, {}))
|
||||
entry["mode"] = "audio_transcription"
|
||||
monkeypatch.setitem(litellm.model_cost, m, entry)
|
||||
chat_entry = dict(litellm.model_cost.get("gemini-2.5-flash", {}))
|
||||
chat_entry["supported_output_modalities"] = ["text"]
|
||||
monkeypatch.setitem(litellm.model_cost, "gemini-2.5-flash", chat_entry)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["gemini-3.5-transcribe-live", "gemini/gemini-3.5-transcribe-live"])
|
||||
def test_gemini_transcribe_live_eager_setup_uses_text_modality(model, patch_gemini_transcribe_live_cost_map_entry):
|
||||
"""Regression: the hardcoded AUDIO eager setup closes transcribe-live sessions with 1007."""
|
||||
config = GeminiRealtimeConfig()
|
||||
|
||||
setup = json.loads(config.session_configuration_request(model))["setup"]
|
||||
|
||||
assert setup["generationConfig"]["responseModalities"] == ["TEXT"]
|
||||
|
||||
|
||||
def test_gemini_transcribe_live_session_update_defaults_to_text_modality(
|
||||
patch_gemini_transcribe_live_cost_map_entry,
|
||||
):
|
||||
config = GeminiRealtimeConfig()
|
||||
session_update = {
|
||||
"type": "session.update",
|
||||
"session": {"instructions": "Transcribe the audio."},
|
||||
}
|
||||
|
||||
messages = config.transform_realtime_request(
|
||||
json.dumps(session_update),
|
||||
"gemini-3.5-transcribe-live",
|
||||
session_configuration_request=None,
|
||||
)
|
||||
|
||||
setup = json.loads(messages[0])["setup"]
|
||||
assert setup["generationConfig"]["responseModalities"] == ["TEXT"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("modalities", [["audio"], ["audio", "text"]])
|
||||
def test_gemini_transcribe_live_coerces_audio_modality_to_text(modalities, patch_gemini_transcribe_live_cost_map_entry):
|
||||
config = GeminiRealtimeConfig()
|
||||
session_update = {
|
||||
"type": "session.update",
|
||||
"session": {"modalities": modalities},
|
||||
}
|
||||
|
||||
messages = config.transform_realtime_request(
|
||||
json.dumps(session_update),
|
||||
"gemini-3.5-transcribe-live",
|
||||
session_configuration_request=None,
|
||||
)
|
||||
|
||||
setup = json.loads(messages[0])["setup"]
|
||||
assert setup["generationConfig"]["responseModalities"] == ["TEXT"]
|
||||
|
||||
|
||||
def test_gemini_chat_model_with_text_output_modalities_keeps_audio_eager_setup(
|
||||
patch_gemini_transcribe_live_cost_map_entry,
|
||||
):
|
||||
"""Chat entries also declare supported_output_modalities ["text"]; they must keep AUDIO."""
|
||||
config = GeminiRealtimeConfig()
|
||||
|
||||
setup = json.loads(config.session_configuration_request("gemini-2.5-flash"))["setup"]
|
||||
|
||||
assert setup["generationConfig"]["responseModalities"] == ["AUDIO"]
|
||||
|
||||
|
||||
def test_generation_complete_without_prior_delta_keeps_turn_usage(patch_gemini_audio_cost_map_entries):
|
||||
from typing import Final
|
||||
|
||||
from litellm.types.llms.gemini import BidiGenerateContentServerMessage
|
||||
from litellm.types.realtime import RealtimeResponseTransformInput
|
||||
|
||||
config: Final = GeminiRealtimeConfig()
|
||||
turn_end_frame: Final[BidiGenerateContentServerMessage] = {
|
||||
"serverContent": {"generationComplete": True, "turnComplete": True},
|
||||
"usageMetadata": {
|
||||
"promptTokenCount": 200,
|
||||
"totalTokenCount": 200,
|
||||
"promptTokensDetails": [
|
||||
{"modality": "AUDIO", "tokenCount": 199},
|
||||
{"modality": "TEXT", "tokenCount": 1},
|
||||
],
|
||||
},
|
||||
}
|
||||
transform_input: Final[RealtimeResponseTransformInput] = {
|
||||
"session_configuration_request": None,
|
||||
"current_output_item_id": None,
|
||||
"current_response_id": None,
|
||||
"current_conversation_id": None,
|
||||
"current_delta_chunks": None,
|
||||
"current_item_chunks": None,
|
||||
"current_delta_type": None,
|
||||
}
|
||||
|
||||
result: Final = config.transform_realtime_response(
|
||||
json.dumps(turn_end_frame),
|
||||
"gemini-3.5-transcribe-live",
|
||||
MagicMock(),
|
||||
realtime_response_transform_input=transform_input,
|
||||
)
|
||||
|
||||
done_events: Final = tuple(event for event in result["response"] if event["type"] == "response.done")
|
||||
assert len(done_events) == 1
|
||||
assert done_events[0]["response"]["usage"]["input_tokens"] == 200
|
||||
|
||||
|
||||
def test_bare_generation_complete_without_prior_delta_is_dropped(patch_gemini_audio_cost_map_entries):
|
||||
from typing import Final
|
||||
|
||||
from litellm.types.llms.gemini import BidiGenerateContentServerMessage
|
||||
from litellm.types.realtime import RealtimeResponseTransformInput
|
||||
|
||||
config: Final = GeminiRealtimeConfig()
|
||||
bare_frame: Final[BidiGenerateContentServerMessage] = {"serverContent": {"generationComplete": True}}
|
||||
transform_input: Final[RealtimeResponseTransformInput] = {
|
||||
"session_configuration_request": None,
|
||||
"current_output_item_id": None,
|
||||
"current_response_id": None,
|
||||
"current_conversation_id": None,
|
||||
"current_delta_chunks": None,
|
||||
"current_item_chunks": None,
|
||||
"current_delta_type": None,
|
||||
}
|
||||
|
||||
result: Final = config.transform_realtime_response(
|
||||
json.dumps(bare_frame),
|
||||
"gemini-3.5-transcribe-live",
|
||||
MagicMock(),
|
||||
realtime_response_transform_input=transform_input,
|
||||
)
|
||||
|
||||
assert result["response"] == []
|
||||
|
||||
|
||||
def _input_audio_append_message(raw_byte_count: int) -> str:
|
||||
import base64
|
||||
|
||||
return json.dumps(
|
||||
{"type": "input_audio_buffer.append", "audio": base64.b64encode(b"\x00" * raw_byte_count).decode()}
|
||||
)
|
||||
|
||||
|
||||
def test_transcribe_live_completed_event_carries_estimated_usage(patch_gemini_transcribe_live_cost_map_entry):
|
||||
"""Gemini Live sends no usageMetadata for transcribe sessions, so LiteLLM bills
|
||||
from streamed audio duration at Google's published estimate (25 audio tok/sec in,
|
||||
175 text tok/min out): 96000 pcm16 bytes = 2s at 24kHz -> 50 in / 6 out."""
|
||||
from typing import Final
|
||||
|
||||
from litellm.types.llms.gemini import BidiGenerateContentServerMessage
|
||||
from litellm.types.realtime import RealtimeInputAudioTranscriptionUsage, RealtimeResponseTransformInput
|
||||
|
||||
config: Final = GeminiRealtimeConfig()
|
||||
config.transform_realtime_request(_input_audio_append_message(96000), "gemini-3.5-transcribe-live")
|
||||
|
||||
transcript_frame: Final[BidiGenerateContentServerMessage] = {
|
||||
"serverContent": {"inputTranscription": {"text": "ahoy there"}}
|
||||
}
|
||||
transform_input: Final[RealtimeResponseTransformInput] = {
|
||||
"session_configuration_request": None,
|
||||
"current_output_item_id": None,
|
||||
"current_response_id": None,
|
||||
"current_conversation_id": None,
|
||||
"current_delta_chunks": None,
|
||||
"current_item_chunks": None,
|
||||
"current_delta_type": None,
|
||||
}
|
||||
|
||||
result: Final = config.transform_realtime_response(
|
||||
json.dumps(transcript_frame),
|
||||
"gemini-3.5-transcribe-live",
|
||||
MagicMock(),
|
||||
realtime_response_transform_input=transform_input,
|
||||
)
|
||||
|
||||
completed: Final = tuple(
|
||||
event
|
||||
for event in result["response"]
|
||||
if event["type"] == "conversation.item.input_audio_transcription.completed"
|
||||
)
|
||||
assert len(completed) == 1
|
||||
assert completed[0]["transcript"] == "ahoy there"
|
||||
expected_usage: Final[RealtimeInputAudioTranscriptionUsage] = {
|
||||
"type": "tokens",
|
||||
"input_tokens": 50,
|
||||
"output_tokens": 6,
|
||||
"total_tokens": 56,
|
||||
"input_token_details": {"text_tokens": 0, "audio_tokens": 50},
|
||||
}
|
||||
assert completed[0]["usage"] == expected_usage
|
||||
|
||||
second: Final = config.transform_realtime_response(
|
||||
json.dumps(transcript_frame),
|
||||
"gemini-3.5-transcribe-live",
|
||||
MagicMock(),
|
||||
realtime_response_transform_input=transform_input,
|
||||
)
|
||||
second_completed: Final = tuple(
|
||||
event
|
||||
for event in second["response"]
|
||||
if event["type"] == "conversation.item.input_audio_transcription.completed"
|
||||
)
|
||||
assert len(second_completed) == 1
|
||||
assert "usage" not in second_completed[0]
|
||||
|
||||
|
||||
def test_non_transcription_live_model_completed_event_has_no_usage(patch_gemini_audio_cost_map_entries):
|
||||
"""Conversational Live models get their audio tokens from usageMetadata via
|
||||
response.done; attaching estimated usage to their transcription events would
|
||||
double-bill, so the estimate is gated to audio_transcription-mode models."""
|
||||
from typing import Final
|
||||
|
||||
from litellm.types.llms.gemini import BidiGenerateContentServerMessage
|
||||
from litellm.types.realtime import RealtimeResponseTransformInput
|
||||
|
||||
config: Final = GeminiRealtimeConfig()
|
||||
config.transform_realtime_request(_input_audio_append_message(96000), "gemini-3.1-flash-live-preview")
|
||||
|
||||
transcript_frame: Final[BidiGenerateContentServerMessage] = {
|
||||
"serverContent": {"inputTranscription": {"text": "ahoy there"}}
|
||||
}
|
||||
transform_input: Final[RealtimeResponseTransformInput] = {
|
||||
"session_configuration_request": None,
|
||||
"current_output_item_id": None,
|
||||
"current_response_id": None,
|
||||
"current_conversation_id": None,
|
||||
"current_delta_chunks": None,
|
||||
"current_item_chunks": None,
|
||||
"current_delta_type": None,
|
||||
}
|
||||
|
||||
result: Final = config.transform_realtime_response(
|
||||
json.dumps(transcript_frame),
|
||||
"gemini-3.1-flash-live-preview",
|
||||
MagicMock(),
|
||||
realtime_response_transform_input=transform_input,
|
||||
)
|
||||
|
||||
completed: Final = tuple(
|
||||
event
|
||||
for event in result["response"]
|
||||
if event["type"] == "conversation.item.input_audio_transcription.completed"
|
||||
)
|
||||
assert len(completed) == 1
|
||||
assert "usage" not in completed[0]
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ through the consumer; and no path leaks the upstream token in a repr.
|
|||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from pydantic import SecretStr
|
||||
|
||||
from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import (
|
||||
|
|
@ -188,6 +189,31 @@ def test_resolve_strips_optional_bearer_scheme_before_detection():
|
|||
assert prefixed.upstream_authorization.get_secret_value() == bare.upstream_authorization.get_secret_value()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("token_type", ("bearer", "BEARER", "beArEr"))
|
||||
def test_resolve_canonicalizes_case_insensitive_bearer_token_type(token_type: str):
|
||||
keys = envelope_keys_from_master_key(_MASTER_KEY)
|
||||
grant = UpstreamTokenGrant(access_token=SecretStr(_ACCESS_TOKEN), token_type=token_type, expires_in=600)
|
||||
sealed = mint_envelope(_IDENTITY, grant, keys, _NOW)
|
||||
assert isinstance(sealed, SealedEnvelope)
|
||||
|
||||
result = resolve_bridge_envelope(sealed.token.get_secret_value(), keys, _NOW, _SERVER_ID)
|
||||
|
||||
assert isinstance(result, BridgeEnvelopeAdmitted)
|
||||
assert result.upstream_authorization.get_secret_value() == f"Bearer {_ACCESS_TOKEN}"
|
||||
|
||||
|
||||
def test_resolve_preserves_non_bearer_token_type():
|
||||
keys = envelope_keys_from_master_key(_MASTER_KEY)
|
||||
grant = UpstreamTokenGrant(access_token=SecretStr(_ACCESS_TOKEN), token_type="DPoP", expires_in=600)
|
||||
sealed = mint_envelope(_IDENTITY, grant, keys, _NOW)
|
||||
assert isinstance(sealed, SealedEnvelope)
|
||||
|
||||
result = resolve_bridge_envelope(sealed.token.get_secret_value(), keys, _NOW, _SERVER_ID)
|
||||
|
||||
assert isinstance(result, BridgeEnvelopeAdmitted)
|
||||
assert result.upstream_authorization.get_secret_value() == f"DPoP {_ACCESS_TOKEN}"
|
||||
|
||||
|
||||
def test_resolve_expired_envelope_is_invalid_not_admitted():
|
||||
keys = envelope_keys_from_master_key(_MASTER_KEY)
|
||||
token = _sealed_token(keys, now=_NOW)
|
||||
|
|
|
|||
|
|
@ -1,91 +1,120 @@
|
|||
import jwt
|
||||
import pytest
|
||||
|
||||
from litellm.proxy.management_endpoints.ui_sso import MicrosoftSSOHandler
|
||||
from litellm.proxy.management_endpoints.types import get_litellm_user_role
|
||||
from litellm.proxy._types import LitellmUserRoles
|
||||
from litellm.proxy.management_endpoints.ui_sso import MicrosoftSSOHandler
|
||||
|
||||
|
||||
def _id_token(**claims) -> str:
|
||||
"""Build a signed id_token carrying the given claims."""
|
||||
payload = {
|
||||
"sub": "user123",
|
||||
"email": "user@company.com",
|
||||
"aud": "litellm-app",
|
||||
"iss": "https://login.microsoftonline.com/tenant-id/v2.0",
|
||||
"exp": 9999999999,
|
||||
**claims,
|
||||
}
|
||||
return jwt.encode(payload, "secret", algorithm="HS256")
|
||||
|
||||
|
||||
def test_extracts_proxy_admin_role_from_jwt():
|
||||
"""Ensure supported app roles like 'proxy_admin' are extracted from the id_token."""
|
||||
payload = {
|
||||
"sub": "user123",
|
||||
"email": "admin@company.com",
|
||||
"app_roles": ["proxy_admin"],
|
||||
"aud": "litellm-app",
|
||||
"iss": "https://login.microsoftonline.com/tenant-id/v2.0",
|
||||
"exp": 9999999999,
|
||||
}
|
||||
token = _id_token(app_roles=["proxy_admin"])
|
||||
|
||||
token = jwt.encode(payload, "secret", algorithm="HS256")
|
||||
roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)
|
||||
|
||||
assert roles == ["proxy_admin"]
|
||||
|
||||
|
||||
def test_maps_internal_user_role():
|
||||
"""Ensure internal_user role is correctly mapped to LitellmUserRoles."""
|
||||
payload = {
|
||||
"sub": "user456",
|
||||
"email": "user@company.com",
|
||||
"app_roles": ["internal_user"],
|
||||
"aud": "litellm-app",
|
||||
"iss": "https://login.microsoftonline.com/tenant-id/v2.0",
|
||||
"exp": 9999999999,
|
||||
}
|
||||
def test_extracts_app_roles_from_roles_claim():
|
||||
"""Entra emits app role values in the `roles` claim; both spellings are read."""
|
||||
token = _id_token(roles=["internal_user"])
|
||||
|
||||
token = jwt.encode(payload, "secret", algorithm="HS256")
|
||||
roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)
|
||||
|
||||
# Map to LitellmUserRoles
|
||||
chosen = None
|
||||
for r in roles:
|
||||
mapped = get_litellm_user_role(r)
|
||||
if mapped is not None:
|
||||
chosen = mapped
|
||||
break
|
||||
|
||||
assert chosen == LitellmUserRoles.INTERNAL_USER
|
||||
assert roles == ["internal_user"]
|
||||
|
||||
|
||||
def test_maps_proxy_admin_viewer_role():
|
||||
"""Ensure proxy_admin_viewer role is correctly mapped."""
|
||||
payload = {
|
||||
"sub": "user789",
|
||||
"email": "viewer@company.com",
|
||||
"app_roles": ["proxy_admin_viewer"],
|
||||
"aud": "litellm-app",
|
||||
"iss": "https://login.microsoftonline.com/tenant-id/v2.0",
|
||||
"exp": 9999999999,
|
||||
}
|
||||
|
||||
token = jwt.encode(payload, "secret", algorithm="HS256")
|
||||
roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)
|
||||
|
||||
chosen = None
|
||||
for r in roles:
|
||||
mapped = get_litellm_user_role(r)
|
||||
if mapped is not None:
|
||||
chosen = mapped
|
||||
break
|
||||
|
||||
assert chosen == LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY
|
||||
@pytest.mark.parametrize(
|
||||
"app_roles, expected",
|
||||
[
|
||||
(["proxy_admin"], LitellmUserRoles.PROXY_ADMIN),
|
||||
(["proxy_admin_viewer"], LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY),
|
||||
(["internal_user"], LitellmUserRoles.INTERNAL_USER),
|
||||
(["internal_user_viewer"], LitellmUserRoles.INTERNAL_USER_VIEW_ONLY),
|
||||
# Case-insensitive, matching get_litellm_user_role.
|
||||
(["PROXY_ADMIN_VIEWER"], LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY),
|
||||
# Roles outside the privilege hierarchy still resolve.
|
||||
(["org_admin"], LitellmUserRoles.ORG_ADMIN),
|
||||
],
|
||||
)
|
||||
def test_maps_single_app_role(app_roles, expected):
|
||||
"""A lone app role maps to its LitellmUserRoles equivalent."""
|
||||
assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == expected
|
||||
|
||||
|
||||
def test_defaults_to_internal_user_viewer_when_no_role():
|
||||
"""Ensure default role is internal_user_viewer when no app role is present."""
|
||||
payload = {
|
||||
"sub": "user_no_role",
|
||||
"email": "noRole@company.com",
|
||||
"aud": "litellm-app",
|
||||
"iss": "https://login.microsoftonline.com/tenant-id/v2.0",
|
||||
"exp": 9999999999,
|
||||
}
|
||||
@pytest.mark.parametrize(
|
||||
"app_roles",
|
||||
[
|
||||
["internal_user", "proxy_admin_viewer"],
|
||||
["proxy_admin_viewer", "internal_user"],
|
||||
],
|
||||
)
|
||||
def test_highest_privilege_role_wins_regardless_of_claim_order(app_roles):
|
||||
"""
|
||||
A user in one group mapped to `internal_user` and another mapped to
|
||||
`proxy_admin_viewer` gets the higher privilege role either way.
|
||||
|
||||
Entra does not guarantee the ordering of the `roles` claim, so the resolved
|
||||
role must not depend on it.
|
||||
"""
|
||||
assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == (LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"app_roles",
|
||||
[
|
||||
["internal_user", "proxy_admin_viewer", "proxy_admin"],
|
||||
["proxy_admin", "proxy_admin_viewer", "internal_user"],
|
||||
["proxy_admin_viewer", "internal_user", "proxy_admin"],
|
||||
],
|
||||
)
|
||||
def test_proxy_admin_beats_every_other_role(app_roles):
|
||||
"""proxy_admin outranks every other role in the hierarchy, in any claim order."""
|
||||
assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == LitellmUserRoles.PROXY_ADMIN
|
||||
|
||||
|
||||
def test_unrecognised_app_roles_are_ignored():
|
||||
"""App roles that are not LitellmUserRoles values do not shadow ones that are."""
|
||||
app_roles = ["Some.Custom.Role", "msiam_access", "internal_user"]
|
||||
|
||||
assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == LitellmUserRoles.INTERNAL_USER
|
||||
|
||||
|
||||
@pytest.mark.parametrize("app_roles", [None, [], ["msiam_access"], ["User"]])
|
||||
def test_returns_none_when_no_role_resolves(app_roles):
|
||||
"""
|
||||
Returning None lets the caller keep the user's stored role or apply
|
||||
default_internal_user_params, rather than forcing a role.
|
||||
"""
|
||||
assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) is None
|
||||
|
||||
|
||||
def test_no_role_claim_yields_no_app_roles():
|
||||
"""An id_token with no role claim produces no app roles, and so no role."""
|
||||
token = _id_token()
|
||||
|
||||
token = jwt.encode(payload, "secret", algorithm="HS256")
|
||||
roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)
|
||||
|
||||
assert roles == []
|
||||
assert MicrosoftSSOHandler.get_user_role_from_app_roles(roles) is None
|
||||
|
||||
# Default role would be internal_user_viewer
|
||||
default_role = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY
|
||||
assert default_role.value == "internal_user_viewer"
|
||||
|
||||
def test_end_to_end_from_id_token_to_role():
|
||||
"""The id_token -> role path resolves the highest privilege role."""
|
||||
token = _id_token(roles=["internal_user", "proxy_admin_viewer"])
|
||||
|
||||
roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)
|
||||
|
||||
assert MicrosoftSSOHandler.get_user_role_from_app_roles(roles) == LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import asyncio
|
||||
import collections
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import timezone
|
||||
|
|
@ -96,6 +97,7 @@ def _reconstruct_ui_where_from_sql(sql_query, params):
|
|||
msg = re.search(r"error_message' LIKE \$(\d+)", cond)
|
||||
sess = re.fullmatch(r"session_id LIKE \$(\d+)", cond)
|
||||
status = re.fullmatch(r"status = \$(\d+)", cond)
|
||||
api_key_not_in = re.fullmatch(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", cond)
|
||||
if gte:
|
||||
date_bounds["gte"] = _iso(params[int(gte.group(1)) - 1])
|
||||
elif lte:
|
||||
|
|
@ -104,10 +106,19 @@ def _reconstruct_ui_where_from_sql(sql_query, params):
|
|||
where["OR"] = where.get("OR", []) + [{"multi_team": True}]
|
||||
elif "status = 'success'" in cond:
|
||||
where["OR"] = where.get("OR", []) + [{"status": "success"}]
|
||||
elif cond == "LOWER(cache_hit) = 'true'":
|
||||
where["cache_hit"] = "hit"
|
||||
elif cond == "(cache_hit IS NULL OR LOWER(cache_hit) != 'true')":
|
||||
where["cache_hit"] = "miss"
|
||||
elif sess:
|
||||
where["session_id"] = {"contains": str(params[int(sess.group(1)) - 1]).strip("%")}
|
||||
elif status:
|
||||
where["status"] = {"equals": params[int(status.group(1)) - 1]}
|
||||
elif api_key_not_in:
|
||||
where["api_key_not_in"] = [
|
||||
params[int(api_key_not_in.group(1)) - 1],
|
||||
params[int(api_key_not_in.group(2)) - 1],
|
||||
]
|
||||
elif alias:
|
||||
metadata_conds.append(
|
||||
{
|
||||
|
|
@ -196,6 +207,7 @@ def make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup_fn=No
|
|||
return MockPrismaClient()
|
||||
|
||||
|
||||
from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
|
||||
from litellm.proxy._types import (
|
||||
LitellmUserRoles,
|
||||
Member,
|
||||
|
|
@ -1256,6 +1268,140 @@ async def test_ui_view_spend_logs_with_team_id(client, monkeypatch):
|
|||
app.dependency_overrides.pop(ps.user_api_key_auth, None)
|
||||
|
||||
|
||||
_HEALTH_CHECK_HASHED_API_KEY = hashlib.sha256(LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME.encode()).hexdigest()
|
||||
|
||||
|
||||
def _spend_logs_with_health_check_rows():
|
||||
now = datetime.datetime.now(timezone.utc).isoformat()
|
||||
return [
|
||||
{
|
||||
"id": "log1",
|
||||
"request_id": "req1",
|
||||
"api_key": "sk-test-key",
|
||||
"user": "test_user_1",
|
||||
"team_id": None,
|
||||
"spend": 0.05,
|
||||
"startTime": now,
|
||||
"model": "gpt-4",
|
||||
},
|
||||
{
|
||||
"id": "log2",
|
||||
"request_id": "req2",
|
||||
"api_key": _HEALTH_CHECK_HASHED_API_KEY,
|
||||
"user": None,
|
||||
"team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
|
||||
"spend": 0.0,
|
||||
"startTime": now,
|
||||
"model": "gpt-4",
|
||||
},
|
||||
{
|
||||
"id": "log3",
|
||||
"request_id": "req3",
|
||||
"api_key": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
|
||||
"user": None,
|
||||
"team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
|
||||
"spend": 0.0,
|
||||
"startTime": now,
|
||||
"model": "gpt-4",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ui_view_spend_logs_exclude_internal_health_checks(client, monkeypatch):
|
||||
mock_spend_logs = _spend_logs_with_health_check_rows()
|
||||
|
||||
def filter_health_checks(where):
|
||||
excluded = where.get("api_key_not_in")
|
||||
if excluded is None:
|
||||
return mock_spend_logs
|
||||
return [log for log in mock_spend_logs if log["api_key"] not in excluded]
|
||||
|
||||
observed_queries = []
|
||||
|
||||
def observe_query(sql_query, params):
|
||||
if 'FROM "LiteLLM_SpendLogs"' in sql_query:
|
||||
observed_queries.append((sql_query, params))
|
||||
|
||||
monkeypatch.setattr(
|
||||
"litellm.proxy.proxy_server.prisma_client",
|
||||
make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query),
|
||||
)
|
||||
app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
|
||||
user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
|
||||
)
|
||||
|
||||
try:
|
||||
start_date, end_date = _default_date_range()
|
||||
response = client.get(
|
||||
"/spend/logs/ui",
|
||||
params={
|
||||
"exclude_internal_health_checks": "true",
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
},
|
||||
headers={"Authorization": "Bearer sk-test"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert [row["request_id"] for row in data["data"]] == ["req1"]
|
||||
|
||||
page_sql, page_params = next((sql, params) for sql, params in observed_queries if "ORDER BY" in sql)
|
||||
not_in = re.search(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", page_sql)
|
||||
assert not_in is not None
|
||||
assert LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME not in page_sql
|
||||
assert _HEALTH_CHECK_HASHED_API_KEY not in page_sql
|
||||
assert {
|
||||
page_params[int(not_in.group(1)) - 1],
|
||||
page_params[int(not_in.group(2)) - 1],
|
||||
} == {LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, _HEALTH_CHECK_HASHED_API_KEY}
|
||||
finally:
|
||||
app.dependency_overrides.pop(ps.user_api_key_auth, None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ui_view_spend_logs_includes_internal_health_checks_by_default(client, monkeypatch):
|
||||
mock_spend_logs = _spend_logs_with_health_check_rows()
|
||||
|
||||
def filter_health_checks(where):
|
||||
excluded = where.get("api_key_not_in")
|
||||
if excluded is None:
|
||||
return mock_spend_logs
|
||||
return [log for log in mock_spend_logs if log["api_key"] not in excluded]
|
||||
|
||||
observed_queries = []
|
||||
|
||||
def observe_query(sql_query, params):
|
||||
if 'FROM "LiteLLM_SpendLogs"' in sql_query:
|
||||
observed_queries.append((sql_query, params))
|
||||
|
||||
monkeypatch.setattr(
|
||||
"litellm.proxy.proxy_server.prisma_client",
|
||||
make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query),
|
||||
)
|
||||
app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
|
||||
user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
|
||||
)
|
||||
|
||||
try:
|
||||
start_date, end_date = _default_date_range()
|
||||
response = client.get(
|
||||
"/spend/logs/ui",
|
||||
params={"start_date": start_date, "end_date": end_date},
|
||||
headers={"Authorization": "Bearer sk-test"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 3
|
||||
assert [row["request_id"] for row in data["data"]] == ["req1", "req2", "req3"]
|
||||
assert all("NOT IN" not in sql for sql, _ in observed_queries)
|
||||
finally:
|
||||
app.dependency_overrides.pop(ps.user_api_key_auth, None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ui_view_spend_logs_internal_user_scoped_without_user_id(
|
||||
client, monkeypatch
|
||||
|
|
@ -2302,6 +2448,96 @@ async def test_ui_view_spend_logs_with_status(client, monkeypatch):
|
|||
app.dependency_overrides.pop(ps.user_api_key_auth, None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ui_view_spend_logs_with_cache_hit_filter(client, monkeypatch):
|
||||
base = {
|
||||
"api_key": "sk-test-key",
|
||||
"user": "test_user_1",
|
||||
"team_id": "team1",
|
||||
"spend": 0.05,
|
||||
"startTime": datetime.datetime.now(timezone.utc).isoformat(),
|
||||
"model": "gpt-4",
|
||||
"status": "success",
|
||||
}
|
||||
mock_spend_logs = [
|
||||
{**base, "id": "log1", "request_id": "req-hit", "cache_hit": "True"},
|
||||
{**base, "id": "log2", "request_id": "req-miss", "cache_hit": "False"},
|
||||
{**base, "id": "log3", "request_id": "req-legacy", "cache_hit": "None"},
|
||||
{**base, "id": "log4", "request_id": "req-null", "cache_hit": None},
|
||||
]
|
||||
|
||||
def filter_by_cache(where):
|
||||
cache_filter = where.get("cache_hit")
|
||||
if cache_filter == "hit":
|
||||
return [log for log in mock_spend_logs if str(log["cache_hit"]).lower() == "true"]
|
||||
if cache_filter == "miss":
|
||||
return [log for log in mock_spend_logs if str(log["cache_hit"]).lower() != "true"]
|
||||
return mock_spend_logs
|
||||
|
||||
monkeypatch.setattr(
|
||||
"litellm.proxy.proxy_server.prisma_client",
|
||||
make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_cache),
|
||||
)
|
||||
|
||||
start_date, end_date = _default_date_range()
|
||||
|
||||
app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
|
||||
user_role=LitellmUserRoles.PROXY_ADMIN
|
||||
)
|
||||
try:
|
||||
response = client.get(
|
||||
"/spend/logs/ui",
|
||||
params={
|
||||
"cache_hit_filter": "hit",
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
},
|
||||
headers={"Authorization": "Bearer sk-test"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert [row["request_id"] for row in data["data"]] == ["req-hit"]
|
||||
|
||||
response = client.get(
|
||||
"/spend/logs/ui",
|
||||
params={
|
||||
"cache_hit_filter": "miss",
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
},
|
||||
headers={"Authorization": "Bearer sk-test"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 3
|
||||
assert [row["request_id"] for row in data["data"]] == ["req-miss", "req-legacy", "req-null"]
|
||||
|
||||
response = client.get(
|
||||
"/spend/logs/ui",
|
||||
params={
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
},
|
||||
headers={"Authorization": "Bearer sk-test"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["total"] == 4
|
||||
|
||||
response = client.get(
|
||||
"/spend/logs/ui",
|
||||
params={
|
||||
"cache_hit_filter": "invalid",
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
},
|
||||
headers={"Authorization": "Bearer sk-test"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
finally:
|
||||
app.dependency_overrides.pop(ps.user_api_key_auth, None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ui_view_spend_logs_with_model(client, monkeypatch):
|
||||
mock_spend_logs = [
|
||||
|
|
|
|||
|
|
@ -1124,7 +1124,7 @@ def test_reservation_uses_most_expensive_deployment_in_group():
|
|||
],
|
||||
ids=["litellm_params", "model_info"],
|
||||
)
|
||||
def test_free_deployment_of_tiered_model_reserves_nothing(deployment_overrides):
|
||||
def test_free_deployment_of_tiered_model_reserves_nothing(deployment_overrides: dict[str, dict[str, int]]):
|
||||
"""A deployment priced at 0 on a model whose published entry carries a tier table
|
||||
must not be estimated against that table. Spend tracking bills such a deployment at
|
||||
its own rates, so reserving the published tier rate consumed, and rejected requests
|
||||
|
|
@ -1223,6 +1223,46 @@ def test_deployment_declaring_own_tier_table_keeps_it():
|
|||
assert estimated is not None and estimated > 0
|
||||
|
||||
|
||||
def test_input_only_tier_reserves_the_models_own_output_rate():
|
||||
"""A tier table that prices only input is billed with the model's own output rates,
|
||||
so reserving the tier's absent output rate as 0 would leave every completion
|
||||
unreserved and let a budgeted caller run past their limit."""
|
||||
output_tokens = 500
|
||||
router = Router(
|
||||
model_list=[
|
||||
{
|
||||
"model_name": "input-tiered",
|
||||
"litellm_params": {
|
||||
"model": "dashscope/qwen-plus-latest",
|
||||
"api_key": "sk-fake",
|
||||
"input_cost_per_token": 1e-06,
|
||||
"output_cost_per_token": 5e-06,
|
||||
"tiered_pricing": [{"range": [0, 32000], "input_cost_per_token": 2e-06}],
|
||||
},
|
||||
}
|
||||
]
|
||||
)
|
||||
request_body = {
|
||||
"model": "input-tiered",
|
||||
"messages": [{"role": "user", "content": "hello " * 100}],
|
||||
"max_tokens": output_tokens,
|
||||
}
|
||||
|
||||
input_cost = estimate_request_input_cost(
|
||||
request_body=request_body,
|
||||
route="/chat/completions",
|
||||
llm_router=router,
|
||||
)
|
||||
estimated = estimate_request_max_cost(
|
||||
request_body=request_body,
|
||||
route="/chat/completions",
|
||||
llm_router=router,
|
||||
)
|
||||
|
||||
assert input_cost is not None and input_cost > 0
|
||||
assert estimated == pytest.approx(input_cost + (output_tokens * 5e-06))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_should_clamp_reservation_to_model_ceiling_when_caller_overrequests(
|
||||
spend_counter_state,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import json
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
from litellm.proxy._lazy_features import LazyFeature
|
||||
from litellm.proxy._lazy_openapi_snapshot import _normalize_operation_ids
|
||||
from litellm.proxy._lazy_openapi_snapshot import SnapshotResult, _normalize_operation_ids, main
|
||||
|
||||
|
||||
def test_generate_snapshot_uses_shared_operation_id_reservations(monkeypatch):
|
||||
|
|
@ -61,7 +62,7 @@ def test_generate_snapshot_uses_shared_operation_id_reservations(monkeypatch):
|
|||
monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy_server_module)
|
||||
monkeypatch.setattr("fastapi.openapi.utils.get_openapi", fake_get_openapi)
|
||||
|
||||
fragments = _lazy_openapi_snapshot.generate_snapshot()
|
||||
fragments = _lazy_openapi_snapshot.generate_snapshot().fragments
|
||||
|
||||
assert fragments["feature-a"]["paths"]["/feature-a/items"]["get"]["operationId"] == "shared_operation_id_get"
|
||||
assert fragments["feature-b"]["paths"]["/feature-b/items"]["get"]["operationId"] == "shared_operation_id_get_2"
|
||||
|
|
@ -106,7 +107,7 @@ def test_generate_snapshot_registers_transitively_imported_modules(monkeypatch):
|
|||
monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy_server_module)
|
||||
monkeypatch.setattr("fastapi.openapi.utils.get_openapi", fake_get_openapi)
|
||||
|
||||
fragments = _lazy_openapi_snapshot.generate_snapshot()
|
||||
fragments = _lazy_openapi_snapshot.generate_snapshot().fragments
|
||||
|
||||
assert fragments["transitive"]["paths"]["/transitive/items"]["get"]["tags"] == ["transitive"]
|
||||
assert "/v1/{param}/deep/leaf" in fragments["transitive"]["paths"]
|
||||
|
|
@ -144,3 +145,66 @@ def test_normalize_operation_ids_preserves_custom_ids():
|
|||
operations = paths["/proxy/{endpoint}"]
|
||||
assert operations["get"]["operationId"] == "custom_operation"
|
||||
assert operations["post"]["operationId"] == "custom_operation"
|
||||
|
||||
|
||||
def test_generate_snapshot_reports_features_whose_import_fails(monkeypatch):
|
||||
from litellm.proxy import _lazy_openapi_snapshot
|
||||
|
||||
fake_app = SimpleNamespace(title="LiteLLM test", version="0.0.0", routes=[])
|
||||
|
||||
fake_module = ModuleType("fake_importable_feature")
|
||||
monkeypatch.setitem(sys.modules, "fake_importable_feature", fake_module)
|
||||
|
||||
def register_fn(app, module):
|
||||
app.routes.append(SimpleNamespace(path="/importable/items"))
|
||||
|
||||
fake_lazy_features_module = ModuleType("litellm.proxy._lazy_features")
|
||||
fake_lazy_features_module.LAZY_FEATURES = [
|
||||
LazyFeature(
|
||||
name="importable",
|
||||
module_path="fake_importable_feature",
|
||||
path_prefixes=("/importable",),
|
||||
register_fn=register_fn,
|
||||
),
|
||||
LazyFeature(
|
||||
name="broken",
|
||||
module_path="litellm.proxy.this_module_does_not_exist",
|
||||
path_prefixes=("/broken",),
|
||||
),
|
||||
]
|
||||
monkeypatch.setitem(sys.modules, "litellm.proxy._lazy_features", fake_lazy_features_module)
|
||||
|
||||
def fake_get_openapi(title, version, routes):
|
||||
return {"paths": {route.path: {"get": {"operationId": "importable_get"}} for route in routes}}
|
||||
|
||||
fake_proxy_server_module = ModuleType("litellm.proxy.proxy_server")
|
||||
fake_proxy_server_module.app = fake_app
|
||||
fake_proxy_server_module.ensure_unique_openapi_operation_ids = lambda schema, reserved_operation_ids: schema
|
||||
monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_proxy_server_module)
|
||||
monkeypatch.setattr("fastapi.openapi.utils.get_openapi", fake_get_openapi)
|
||||
|
||||
result = _lazy_openapi_snapshot.generate_snapshot()
|
||||
|
||||
assert result.skipped == ("broken",)
|
||||
assert sorted(result.fragments) == ["importable"]
|
||||
|
||||
|
||||
def test_main_refuses_to_write_a_snapshot_missing_skipped_features(tmp_path, capsys):
|
||||
snapshot_file = tmp_path / "snapshot.json"
|
||||
result = SnapshotResult(fragments={"importable": {"paths": {}, "components": {"schemas": {}}}}, skipped=("broken",))
|
||||
|
||||
assert main(snapshot_file, generate=lambda: result) == 1
|
||||
assert not snapshot_file.exists()
|
||||
assert "broken" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_main_writes_sorted_snapshot_when_every_feature_loads(tmp_path):
|
||||
snapshot_file = tmp_path / "snapshot.json"
|
||||
fragments = {
|
||||
"zeta": {"paths": {"/z": {}}, "components": {"schemas": {}}},
|
||||
"alpha": {"paths": {}, "components": {"schemas": {}}},
|
||||
}
|
||||
|
||||
assert main(snapshot_file, generate=lambda: SnapshotResult(fragments=fragments, skipped=())) == 0
|
||||
assert json.loads(snapshot_file.read_text()) == fragments
|
||||
assert snapshot_file.read_text() == json.dumps(fragments, indent=2, sort_keys=True) + "\n"
|
||||
|
|
|
|||
|
|
@ -234,6 +234,40 @@ async def test_add_litellm_data_to_request_parses_string_metadata():
|
|||
assert updated_data["metadata"]["generation_name"] == "gen123"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_key_otel_service_name_outranks_team_metadata_merge():
|
||||
from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
|
||||
|
||||
request_mock = MagicMock(spec=Request)
|
||||
request_mock.url = MagicMock()
|
||||
request_mock.url.path = "/v1/chat/completions"
|
||||
request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions"
|
||||
request_mock.method = "POST"
|
||||
request_mock.query_params = {}
|
||||
request_mock.headers = {"Content-Type": "application/json"}
|
||||
request_mock.client = MagicMock()
|
||||
request_mock.client.host = "127.0.0.1"
|
||||
|
||||
user_api_key_dict = UserAPIKeyAuth(
|
||||
api_key="hashed-key",
|
||||
metadata={"otel_service_name": "key-svc"},
|
||||
team_metadata={"otel_service_name": "team-svc", "other_setting": "team-val"},
|
||||
)
|
||||
|
||||
updated_data = await add_litellm_data_to_request(
|
||||
data={"model": "gpt-3.5-turbo"},
|
||||
request=request_mock,
|
||||
user_api_key_dict=user_api_key_dict,
|
||||
proxy_config=MagicMock(),
|
||||
general_settings={},
|
||||
version="test-version",
|
||||
)
|
||||
|
||||
auth_metadata = updated_data["metadata"]["user_api_key_auth_metadata"]
|
||||
assert auth_metadata["otel_service_name"] == "key-svc"
|
||||
assert auth_metadata["other_setting"] == "team-val"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stamped_auth_object_reflects_header_derived_identity():
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -343,6 +343,31 @@ def test_transcription_cost_uses_token_pricing(_local_model_cost_map):
|
|||
assert pytest.approx(cost, rel=1e-6) == expected_cost
|
||||
|
||||
|
||||
def test_transcription_token_pricing_is_provider_aware(_local_model_cost_map):
|
||||
"""Regression: the token-priced transcription path hardcoded provider openai,
|
||||
so gemini transcription models raised "This model isn't mapped yet"."""
|
||||
from litellm import completion_cost
|
||||
|
||||
usage = Usage(
|
||||
prompt_tokens=200,
|
||||
completion_tokens=10,
|
||||
total_tokens=210,
|
||||
prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1, audio_tokens=199),
|
||||
)
|
||||
response = TranscriptionResponse(text="demo text")
|
||||
response.usage = usage
|
||||
|
||||
cost = completion_cost(
|
||||
completion_response=response,
|
||||
model="gemini/gemini-3.5-transcribe",
|
||||
custom_llm_provider="gemini",
|
||||
call_type="atranscription",
|
||||
)
|
||||
|
||||
expected_cost = (199 * 2e-06) + (1 * 2e-06) + (10 * 1.2e-05)
|
||||
assert pytest.approx(cost, rel=1e-6) == expected_cost
|
||||
|
||||
|
||||
def test_transcription_cost_falls_back_to_duration(_local_model_cost_map):
|
||||
from litellm import completion_cost
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
# UI container — Next.js static export served by nginx.
|
||||
|
||||
ARG UI_BUILD_IMAGE=node:24.19-alpine3.24@sha256:d32cdf619f63fe0471182d08996dd516c6275bb5fd31ae06e55a570bd9e1ad43
|
||||
ARG NGINX_VERSION=1.27-alpine
|
||||
ARG NGINX_VERSION=1.31-alpine
|
||||
|
||||
# ---------- builder ----------
|
||||
FROM ${UI_BUILD_IMAGE} AS builder
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
|
|
@ -151,15 +151,18 @@ describe("AutoRouterBenchmarksTab", () => {
|
|||
mockAutoRouters();
|
||||
});
|
||||
|
||||
it("leads with total estimated savings, before the three session-shape metrics", () => {
|
||||
it("leads with total estimated savings, before the four session-shape metrics", () => {
|
||||
mockHook({ data: response([group(), group({ router_name: "gpt-auto" })]) });
|
||||
renderTab();
|
||||
|
||||
const labels = screen
|
||||
.getAllByText(/Total estimated savings|Avg turns per session|Avg session length|Avg tokens per session/)
|
||||
.getAllByText(
|
||||
/Total estimated savings|Avg saved per session|Avg turns per session|Avg session length|Avg tokens per session/,
|
||||
)
|
||||
.map((node) => node.textContent);
|
||||
expect(labels).toEqual([
|
||||
"Total estimated savings",
|
||||
"Avg saved per session",
|
||||
"Avg turns per session",
|
||||
"Avg session length",
|
||||
"Avg tokens per session",
|
||||
|
|
@ -181,13 +184,35 @@ describe("AutoRouterBenchmarksTab", () => {
|
|||
expect(screen.getByText("5.3M")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("pairs the savings with the session count it was earned over", () => {
|
||||
it("pairs the savings with the session count it was earned over, in its own tile", () => {
|
||||
mockHook({ data: response([group(), group({ router_name: "gpt-auto" })]) });
|
||||
renderTab();
|
||||
|
||||
expect(screen.getByText("Avg saved per session")).toBeInTheDocument();
|
||||
expect(screen.getByText("$23.13")).toBeInTheDocument();
|
||||
expect(screen.getByText("across 94 sessions")).toBeInTheDocument();
|
||||
const tile = screen.getByText("Avg saved per session").closest('[data-slot="card"]');
|
||||
if (!tile) throw new Error("expected avg saved per session to render as a metric tile");
|
||||
|
||||
expect(within(tile).getByText("$23.13")).toBeInTheDocument();
|
||||
expect(within(tile).getByText("· 94 sessions")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("exposes each spend row as a term and its value, not as loose text", () => {
|
||||
mockHook({ data: response([group()]) });
|
||||
renderTab();
|
||||
|
||||
const terms = screen.getAllByRole("term").map((node) => node.textContent);
|
||||
const values = screen.getAllByRole("definition").map((node) => node.textContent);
|
||||
expect(terms).toEqual(["Actual auto-router spend", "Estimated spend at highest-tier model"]);
|
||||
expect(values).toEqual(["$359.86", "$2,534.45"]);
|
||||
});
|
||||
|
||||
it("lets both hero columns shrink below their content so a large total cannot clip", () => {
|
||||
const huge = totals({ saved_spend: 123_456_789_012.34 });
|
||||
mockHook({ data: response([group(huge)], huge) });
|
||||
renderTab();
|
||||
|
||||
const figure = screen.getByText("$123,456,789,012.34");
|
||||
const grid = figure.closest('[data-slot="card"]')?.firstElementChild;
|
||||
expect(grid).toHaveClass("md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]");
|
||||
});
|
||||
|
||||
it("shows a cost increase as a positive delta rather than a saving", () => {
|
||||
|
|
@ -315,7 +340,7 @@ describe("AutoRouterBenchmarksTab", () => {
|
|||
|
||||
expect(screen.getByText("Total estimated savings")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("$0.00")).toHaveLength(4);
|
||||
expect(screen.getByText("across 0 sessions")).toBeInTheDocument();
|
||||
expect(screen.getByText("· 0 sessions")).toBeInTheDocument();
|
||||
expect(screen.getByText("0s")).toBeInTheDocument();
|
||||
expect(screen.getByText(/turns measured/)).toBeInTheDocument();
|
||||
expect(screen.getAllByText("0.0%").length).toBeGreaterThan(0);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import AdvancedDatePicker from "@/components/shared/advanced_date_picker";
|
|||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
|
|
@ -39,51 +40,51 @@ const Message: React.FC<{ children: React.ReactNode }> = ({ children }) => (
|
|||
<p className="py-8 text-center text-sm text-muted-foreground">{children}</p>
|
||||
);
|
||||
|
||||
const Metric: React.FC<{ label: string; value: string }> = ({ label, value }) => (
|
||||
const Metric: React.FC<{ label: string; value: string; hint?: string }> = ({ label, value, hint }) => (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm font-normal text-muted-foreground">{label}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex flex-wrap items-baseline gap-2">
|
||||
<p className="text-3xl font-semibold text-foreground">{value}</p>
|
||||
{hint && <p className="text-sm text-muted-foreground">{hint}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
const SpendRow: React.FC<{ label: string; value: string }> = ({ label, value }) => (
|
||||
<dl className="flex items-baseline justify-between gap-6 py-3">
|
||||
<dt className="text-sm text-muted-foreground">{label}</dt>
|
||||
<dd className="text-base font-semibold tabular-nums text-foreground">{value}</dd>
|
||||
</dl>
|
||||
);
|
||||
|
||||
const HeroCard: React.FC<{ view: BenchmarkView }> = ({ view }) => {
|
||||
const stats = view.stats;
|
||||
const cheaper = stats.saved_spend >= 0;
|
||||
return (
|
||||
<Card className="overflow-hidden py-0">
|
||||
<div className="grid md:grid-cols-[1fr_1fr]">
|
||||
<div className="flex flex-col justify-center gap-3 p-6">
|
||||
<p className="text-sm text-muted-foreground">Total estimated savings</p>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<p className="text-5xl font-semibold tracking-tight text-foreground">{usd(stats.saved_spend)}</p>
|
||||
<div className="grid md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<div className="flex flex-col items-center justify-center gap-2 p-6">
|
||||
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Total estimated savings
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center justify-center gap-3">
|
||||
<p className="text-6xl font-semibold tracking-tight text-foreground">{usd(stats.saved_spend)}</p>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={cheaper ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive"}
|
||||
className={`h-6 px-2.5 text-sm ${cheaper ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive"}`}
|
||||
>
|
||||
{stats.saved_spend !== 0 && (cheaper ? "-" : "+")}
|
||||
{Math.abs(stats.saved_pct).toFixed(0)}%
|
||||
</Badge>
|
||||
</div>
|
||||
<dl className="divide-y text-sm">
|
||||
<div className="flex items-baseline justify-between gap-6 py-3">
|
||||
<dt className="text-muted-foreground">Actual auto-router spend</dt>
|
||||
<dd className="font-medium tabular-nums text-foreground">{usd(stats.spend)}</dd>
|
||||
</div>
|
||||
<div className="flex items-baseline justify-between gap-6 py-3">
|
||||
<dt className="text-muted-foreground">Estimated spend at highest-tier model</dt>
|
||||
<dd className="font-medium tabular-nums text-foreground">{usd(stats.baseline_spend)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center justify-center gap-2 border-t p-6 md:border-t-0 md:border-l">
|
||||
<p className="text-[11px] uppercase tracking-wide text-muted-foreground">Avg saved per session</p>
|
||||
<p className="text-5xl font-semibold tracking-tight text-foreground">{usd(stats.saved_per_session)}</p>
|
||||
<p className="text-sm text-muted-foreground">across {stats.sessions.toLocaleString()} sessions</p>
|
||||
<div className="flex flex-col justify-center border-t p-6 md:border-t-0 md:border-l">
|
||||
<SpendRow label="Actual auto-router spend" value={usd(stats.spend)} />
|
||||
<Separator />
|
||||
<SpendRow label="Estimated spend at highest-tier model" value={usd(stats.baseline_spend)} />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
|
@ -239,7 +240,12 @@ const BenchmarksBody: React.FC<BenchmarksBodyProps> = ({ isPending, error, data,
|
|||
|
||||
<TierTurnsChart view={view} autoRouters={autoRouters} />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Metric
|
||||
label="Avg saved per session"
|
||||
value={usd(stats.saved_per_session)}
|
||||
hint={`· ${stats.sessions.toLocaleString()} sessions`}
|
||||
/>
|
||||
<Metric label="Avg turns per session" value={stats.avg_turns_per_session.toFixed(1)} />
|
||||
<Metric label="Avg session length" value={durationLabel(stats.avg_session_seconds)} />
|
||||
<Metric label="Avg tokens per session" value={formatNumberWithCommas(stats.avg_tokens_per_session, 1, true)} />
|
||||
|
|
|
|||
|
|
@ -107,6 +107,33 @@ const mockDeploymentsPage = () => {
|
|||
modelInfoCall.mockResolvedValue(pageOf(DEPLOYMENTS));
|
||||
};
|
||||
|
||||
// Oldest-first, as the proxy returns them, and two more than the ten-row first page holds.
|
||||
const BULK_ROUTER_NAMES = [
|
||||
"router-01-oldest",
|
||||
...Array.from({ length: 10 }, (_, i) => `router-${i + 2}`),
|
||||
"router-12-newest",
|
||||
];
|
||||
|
||||
const A_FULL_PAGE_AND_TWO_MORE = Array.from({ length: 12 }, (_, index) => ({
|
||||
model_name: BULK_ROUTER_NAMES[index],
|
||||
litellm_params: {
|
||||
model: "auto_router/complexity_router",
|
||||
complexity_router_config: { tiers: {}, classifier_type: "heuristic" },
|
||||
},
|
||||
model_info: {
|
||||
id: `bulk-${index + 1}`,
|
||||
db_model: true,
|
||||
created_at: `2026-08-${String(index + 1).padStart(2, "0")}T00:00:00.000000+00:00`,
|
||||
},
|
||||
}));
|
||||
|
||||
/** Row order as rendered, header row dropped. */
|
||||
const routerNamesInOrder = () =>
|
||||
screen
|
||||
.getAllByRole("row")
|
||||
.slice(1)
|
||||
.map((row) => row.querySelector("span.text-sm.font-medium")?.textContent ?? "");
|
||||
|
||||
const renderPanel = (canModify = true) =>
|
||||
renderWithProviders(
|
||||
<AutoRoutersPanel
|
||||
|
|
@ -257,4 +284,32 @@ describe("AutoRoutersPanel", () => {
|
|||
await screen.findByText("config-router");
|
||||
expect(screen.queryByTestId("auto-router-actions-auto-4")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// /v2/model/info returns an unordered model_list, and created_at is absent on config routers
|
||||
// and on non-enterprise proxies, so both halves of the order have to be pinned here.
|
||||
it("orders newest first, then the undated routers by name", async () => {
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText("tri-tier-router");
|
||||
|
||||
expect(routerNamesInOrder()).toEqual([
|
||||
"tri-tier-router", // 2026-07-28
|
||||
"support-router", // 2026-07-27
|
||||
"adaptive-router", // undated, sorts after every dated row, then by name
|
||||
"config-router",
|
||||
]);
|
||||
});
|
||||
|
||||
// The reported bug: the newest router was rendered last, so it landed on page 2 and read
|
||||
// as never created.
|
||||
it("puts a just-created router on the first page of a list longer than one page", async () => {
|
||||
modelInfoCall.mockResolvedValue(pageOf(A_FULL_PAGE_AND_TWO_MORE));
|
||||
|
||||
renderPanel();
|
||||
|
||||
expect(await screen.findByRole("button", { name: "router-12-newest" })).toBeInTheDocument();
|
||||
// Page one holds the ten newest, so the two oldest are the ones pushed off it.
|
||||
expect(screen.queryByRole("button", { name: "router-01-oldest" })).not.toBeInTheDocument();
|
||||
expect(routerNamesInOrder()[0]).toBe("router-12-newest");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { SortingState } from "@tanstack/react-table";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { DataTable } from "@/components/shared/DataTable";
|
||||
import { AutoRouterIcon } from "@/components/shared/table_cells";
|
||||
|
|
@ -19,6 +19,11 @@ interface AutoRoutersTableProps {
|
|||
|
||||
const PAGE_SIZE_OPTIONS = [10, 25, 50];
|
||||
|
||||
const DEFAULT_SORTING: SortingState = [
|
||||
{ id: "createdAt", desc: true },
|
||||
{ id: "name", desc: false },
|
||||
];
|
||||
|
||||
function EmptyState({ canModify }: { canModify: boolean }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-1 py-6">
|
||||
|
|
@ -42,8 +47,6 @@ export function AutoRoutersTable({
|
|||
onRouterClick,
|
||||
onDeleteClick,
|
||||
}: AutoRoutersTableProps) {
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
|
||||
const columns = useMemo(
|
||||
() => getAutoRoutersTableColumns({ canModify, onRouterClick, onDeleteClick }),
|
||||
[canModify, onRouterClick, onDeleteClick],
|
||||
|
|
@ -55,8 +58,7 @@ export function AutoRoutersTable({
|
|||
columns={columns}
|
||||
getRowId={(router) => router.id}
|
||||
sortingMode="client"
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
defaultSorting={DEFAULT_SORTING}
|
||||
paginationMode="client"
|
||||
pageSizeOptions={PAGE_SIZE_OPTIONS}
|
||||
isLoading={isLoading}
|
||||
|
|
|
|||
|
|
@ -155,6 +155,7 @@ export const getAutoRoutersTableColumns = ({
|
|||
size: 150,
|
||||
enableSorting: true,
|
||||
sortingFn: "datetime",
|
||||
sortUndefined: "last",
|
||||
cell: ({ row }) => <DateCell value={row.original.createdAt} precision="date" />,
|
||||
},
|
||||
...(canModify
|
||||
|
|
|
|||
|
|
@ -30,7 +30,8 @@ export interface AutoRouterRow {
|
|||
editBlockedReason: EditBlockedReason | null;
|
||||
targets: string[];
|
||||
defaultModel: string | null;
|
||||
createdAt: string | null;
|
||||
/** `undefined`, not `null`: the table's `sortUndefined` pin only matches `undefined` */
|
||||
createdAt: string | undefined;
|
||||
deployment: AutoRouterDeployment;
|
||||
}
|
||||
|
||||
|
|
@ -113,7 +114,7 @@ export const toAutoRouterRow = (
|
|||
canEdit: canEdit && mayActOnRow,
|
||||
canDelete: canDelete && mayActOnRow,
|
||||
editBlockedReason,
|
||||
createdAt: info.created_at ?? null,
|
||||
createdAt: info.created_at ?? undefined,
|
||||
defaultModel: (params[strategy.defaultModelKey] as string | null | undefined) ?? null,
|
||||
deployment,
|
||||
...PRESENTERS[strategy.kind](asRecord(params[strategy.configKey])),
|
||||
|
|
|
|||
|
|
@ -1,13 +1,16 @@
|
|||
{
|
||||
"anthropic_family": {
|
||||
"label": "Anthropic Family",
|
||||
"description": "Routes across the Claude model family: Haiku for simple queries, Sonnet for medium, Opus for complex and reasoning-heavy requests.",
|
||||
"description": "Routes across the Claude model family: Haiku for simple queries, Sonnet for medium, Opus for complex, Opus at high thinking for reasoning.",
|
||||
"complexity_router_config": {
|
||||
"tiers": {
|
||||
"SIMPLE": ["claude-haiku-4-5"],
|
||||
"MEDIUM": ["claude-sonnet-5"],
|
||||
"COMPLEX": ["claude-opus-5"],
|
||||
"REASONING": ["claude-fable-5"]
|
||||
"REASONING": ["claude-opus-5"]
|
||||
},
|
||||
"tier_model_configs": {
|
||||
"REASONING": [{ "model_name": "claude-opus-5", "litellm_params": { "reasoning_effort": "high" } }]
|
||||
},
|
||||
"classifier_type": "heuristic",
|
||||
"escalation_keywords": ["LITELLM ESCALATE"],
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import {
|
|||
CLASSIFICATION_RUBRIC_KEYS,
|
||||
ClassificationRubric,
|
||||
effectiveTierLabel,
|
||||
heuristicScoringRole,
|
||||
usesLlmClassifier,
|
||||
DEFAULT_HEURISTIC_FIRST_MAX_TIER,
|
||||
HEURISTIC_FIRST_MAX_TIER_KEYS,
|
||||
|
|
@ -502,7 +503,7 @@ const ClassificationMethodConfig: React.FC<ClassificationMethodConfigProps> = ({
|
|||
</div>
|
||||
)}
|
||||
|
||||
{value.classifier_type === "heuristic" && (
|
||||
{heuristicScoringRole(value) !== "never" && (
|
||||
<div className="mt-4">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<strong className="font-semibold">Custom Technical Keywords</strong>
|
||||
|
|
|
|||
|
|
@ -1012,3 +1012,47 @@ describe("ComplexityRouterConfig per-model effort filtering", () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComplexityRouterConfig custom technical keywords", () => {
|
||||
const openClassificationPanel = (value: ComplexityRouterConfigValue) => {
|
||||
renderWithProviders(<ComplexityRouterConfig modelInfo={mockModelInfo} value={value} onChange={vi.fn()} />);
|
||||
fireEvent.click(screen.getByText("Advanced: Classification Method"));
|
||||
};
|
||||
|
||||
const llmConfig = { model: "gpt-3.5-turbo", timeout_ms: 3000 };
|
||||
|
||||
it.each([
|
||||
["heuristic", { ...defaultValue, classifier_type: "heuristic" as const }],
|
||||
[
|
||||
"heuristic_first",
|
||||
{
|
||||
...defaultValue,
|
||||
classifier_type: "heuristic_first" as const,
|
||||
heuristic_first_max_tier: "SIMPLE",
|
||||
classifier_llm_config: llmConfig,
|
||||
},
|
||||
],
|
||||
[
|
||||
"llm falling back to the scorer",
|
||||
{
|
||||
...defaultValue,
|
||||
classifier_type: "llm" as const,
|
||||
classifier_llm_config: llmConfig,
|
||||
classifier_fallback: "heuristic" as const,
|
||||
},
|
||||
],
|
||||
])("offers the keywords on a router whose scorer runs: %s", (_label, value) => {
|
||||
openClassificationPanel(value);
|
||||
expect(screen.getByText("Custom Technical Keywords")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides the keywords when the scorer never runs, so they cannot imply an effect they have none", () => {
|
||||
openClassificationPanel({
|
||||
...defaultValue,
|
||||
classifier_type: "llm",
|
||||
classifier_llm_config: llmConfig,
|
||||
classifier_fallback: "default_model",
|
||||
});
|
||||
expect(screen.queryByText("Custom Technical Keywords")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -592,6 +592,28 @@ describe("AddAutoRouterTab", () => {
|
|||
});
|
||||
});
|
||||
|
||||
// Every step between the bundled JSON and the payload drops these params silently.
|
||||
it("carries a preset's per-tier reasoning effort through to the create payload", async () => {
|
||||
const user = userEvent.setup();
|
||||
mockFetchAvailableModels.mockResolvedValue(ALL_FAMILY_MODELS);
|
||||
|
||||
renderWithProviders(<Harness />);
|
||||
await waitForPresetEnabled("Anthropic Family");
|
||||
await selectTemplate("Anthropic Family");
|
||||
|
||||
await user.type(screen.getByPlaceholderText(/smart_router/i), "anthropic-router");
|
||||
await user.click(screen.getByRole("button", { name: /add auto router/i }));
|
||||
|
||||
await waitFor(() => expect(handleAddAutoRouterSubmit).toHaveBeenCalled());
|
||||
expect(vi.mocked(handleAddAutoRouterSubmit).mock.calls.at(-1)?.[0]).toMatchObject({
|
||||
complexity_router_config: {
|
||||
tier_model_configs: {
|
||||
REASONING: [{ model_name: "claude-opus-5", litellm_params: { reasoning_effort: "high" } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Bugbot-found bug: submitBlockedReason disables the button for this, but Form's onFinish
|
||||
// (wired to the same handler as the button) fires whenever the form itself is submitted,
|
||||
// independent of the button's own disabled state. Without submitRecommendedRouter re-checking
|
||||
|
|
|
|||
|
|
@ -459,6 +459,64 @@ describe("teamInfoCall", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("uiSpendLogsCall exclude_internal_health_checks serialization", () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
const mockOkFetch = () => {
|
||||
const mockFetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({ data: [], total: 0, page: 1, page_size: 50, total_pages: 0 }),
|
||||
} as any);
|
||||
global.fetch = mockFetch as any;
|
||||
return mockFetch;
|
||||
};
|
||||
|
||||
const callWith = (params: Parameters<typeof Networking.uiSpendLogsCall>[0]["params"]) =>
|
||||
Networking.uiSpendLogsCall({
|
||||
accessToken: "token",
|
||||
start_date: "2026-01-01 00:00:00",
|
||||
end_date: "2026-01-02 00:00:00",
|
||||
params,
|
||||
});
|
||||
|
||||
const lastUrl = (mockFetch: ReturnType<typeof vi.fn>) => {
|
||||
const [url] = mockFetch.mock.calls.at(-1) ?? [];
|
||||
return new URL(url as string, "http://example.com");
|
||||
};
|
||||
|
||||
it("appends exclude_internal_health_checks=true when the toggle is on", async () => {
|
||||
const mockFetch = mockOkFetch();
|
||||
|
||||
await callWith({ exclude_internal_health_checks: true });
|
||||
|
||||
expect(lastUrl(mockFetch).searchParams.get("exclude_internal_health_checks")).toBe("true");
|
||||
});
|
||||
|
||||
it("omits exclude_internal_health_checks when the toggle is off", async () => {
|
||||
const mockFetch = mockOkFetch();
|
||||
|
||||
await callWith({ exclude_internal_health_checks: false });
|
||||
|
||||
expect(lastUrl(mockFetch).searchParams.has("exclude_internal_health_checks")).toBe(false);
|
||||
});
|
||||
|
||||
it("omits exclude_internal_health_checks when the param is absent", async () => {
|
||||
const mockFetch = mockOkFetch();
|
||||
|
||||
await callWith({});
|
||||
|
||||
expect(lastUrl(mockFetch).searchParams.has("exclude_internal_health_checks")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sessionSpendLogsCall", () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
|
|
|
|||
|
|
@ -2002,6 +2002,7 @@ interface UiSpendLogsParams {
|
|||
user_id?: string;
|
||||
end_user?: string;
|
||||
status_filter?: string;
|
||||
cache_hit_filter?: string;
|
||||
/** Filter by model name (e.g. "gpt-4") */
|
||||
model?: string;
|
||||
/** Filter by model ID (litellm model deployment id) */
|
||||
|
|
@ -2013,6 +2014,7 @@ interface UiSpendLogsParams {
|
|||
sort_order?: "asc" | "desc";
|
||||
min_spend?: number;
|
||||
max_spend?: number;
|
||||
exclude_internal_health_checks?: boolean;
|
||||
}
|
||||
|
||||
interface UiSpendLogsCallOptions {
|
||||
|
|
@ -2047,6 +2049,8 @@ export const uiSpendLogsCall = async ({
|
|||
if (value == null) continue;
|
||||
if (key === "min_spend" || key === "max_spend") {
|
||||
queryParams.append(key, value.toString());
|
||||
} else if (typeof value === "boolean") {
|
||||
if (value) queryParams.append(key, "true");
|
||||
} else if (typeof value === "string" && value !== "") {
|
||||
queryParams.append(key, String(value));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ interface LogsTableToolbarProps {
|
|||
onSelectedTimeIntervalChange: (value: { value: number; unit: string }) => void;
|
||||
isLiveTail: boolean;
|
||||
onIsLiveTailChange: (value: boolean) => void;
|
||||
excludeInternalHealthChecks: boolean;
|
||||
onExcludeInternalHealthChecksChange: (value: boolean) => void;
|
||||
onResetToFirstPage: () => void;
|
||||
onResetFilters: () => void;
|
||||
}
|
||||
|
|
@ -38,6 +40,8 @@ export function LogsTableToolbar({
|
|||
onSelectedTimeIntervalChange,
|
||||
isLiveTail,
|
||||
onIsLiveTailChange,
|
||||
excludeInternalHealthChecks,
|
||||
onExcludeInternalHealthChecksChange,
|
||||
onResetToFirstPage,
|
||||
onResetFilters,
|
||||
}: LogsTableToolbarProps) {
|
||||
|
|
@ -125,6 +129,15 @@ export function LogsTableToolbar({
|
|||
<Switch checked={isLiveTail} onCheckedChange={onIsLiveTailChange} aria-label="Live Tail" />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">Hide Health Checks</span>
|
||||
<Switch
|
||||
checked={excludeInternalHealthChecks}
|
||||
onCheckedChange={onExcludeInternalHealthChecksChange}
|
||||
aria-label="Hide Health Checks"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button variant="outline" size="sm" onClick={onResetFilters}>
|
||||
Reset Filters
|
||||
</Button>
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ describe("RequestLogsFilters", () => {
|
|||
for (const label of [
|
||||
"Team ID",
|
||||
"Status",
|
||||
"Cache",
|
||||
"Key Alias",
|
||||
"User ID",
|
||||
"End User",
|
||||
|
|
@ -259,4 +260,37 @@ describe("RequestLogsFilters", () => {
|
|||
|
||||
expect(await screen.findByText(label)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", "All Requests"],
|
||||
["hit", "Cache Hit"],
|
||||
["miss", "Cache Miss"],
|
||||
])("shows the human label on the Cache trigger for %s", async (cacheState, label) => {
|
||||
renderFilters(cacheState === "" ? {} : { [LOG_FILTER_IDS.CACHE_STATUS]: cacheState });
|
||||
|
||||
expect(await screen.findByText(label)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Cache Hit", "hit"],
|
||||
["Cache Miss", "miss"],
|
||||
])("selecting %s sets the cache filter to %s", async (label, expected) => {
|
||||
const user = userEvent.setup();
|
||||
const { set } = renderFilters();
|
||||
|
||||
await user.click(await screen.findByText("All Requests"));
|
||||
await user.click(await screen.findByRole("option", { name: label }));
|
||||
|
||||
expect(set).toHaveBeenCalledWith(LOG_FILTER_IDS.CACHE_STATUS, expected);
|
||||
});
|
||||
|
||||
it("selecting All Requests clears the cache filter", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { set } = renderFilters({ [LOG_FILTER_IDS.CACHE_STATUS]: "hit" });
|
||||
|
||||
await user.click(await screen.findByText("Cache Hit"));
|
||||
await user.click(await screen.findByRole("option", { name: "All Requests" }));
|
||||
|
||||
expect(set).toHaveBeenCalledWith(LOG_FILTER_IDS.CACHE_STATUS, undefined);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -31,6 +31,12 @@ const STATUS_FILTER_ITEMS = [
|
|||
{ value: "success", label: "Success" },
|
||||
{ value: "failure", label: "Failure" },
|
||||
] as const;
|
||||
|
||||
const CACHE_FILTER_ITEMS = [
|
||||
{ value: ALL_VALUE, label: "All Requests" },
|
||||
{ value: "hit", label: "Cache Hit" },
|
||||
{ value: "miss", label: "Cache Miss" },
|
||||
] as const;
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
const asString = (value: unknown): string => (typeof value === "string" ? value : "");
|
||||
|
|
@ -328,6 +334,27 @@ export function RequestLogsFilters({ get, set, teams, logsWindow }: RequestLogsF
|
|||
</Select>
|
||||
</DataTableFilterField>
|
||||
|
||||
<DataTableFilterField label="Cache">
|
||||
<Select
|
||||
items={CACHE_FILTER_ITEMS}
|
||||
value={valueOf(LOG_FILTER_IDS.CACHE_STATUS) === "" ? ALL_VALUE : valueOf(LOG_FILTER_IDS.CACHE_STATUS)}
|
||||
onValueChange={(next) =>
|
||||
set(LOG_FILTER_IDS.CACHE_STATUS, next === null || next === ALL_VALUE ? undefined : next)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="All Requests" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CACHE_FILTER_ITEMS.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>
|
||||
{item.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</DataTableFilterField>
|
||||
|
||||
<KeyAliasFilterField
|
||||
value={valueOf(LOG_FILTER_IDS.KEY_ALIAS)}
|
||||
onChange={setter(LOG_FILTER_IDS.KEY_ALIAS)}
|
||||
|
|
|
|||
|
|
@ -434,6 +434,44 @@ describe("RequestLogsPanel", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("hide health checks", () => {
|
||||
const toggle = () => screen.getByRole("switch", { name: "Hide Health Checks" });
|
||||
|
||||
it("defaults to showing health checks and refetches without them from page 1 when toggled on", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
|
||||
await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());
|
||||
expect(lastCall()?.params?.exclude_internal_health_checks).toBe(false);
|
||||
expect(toggle()).not.toBeChecked();
|
||||
|
||||
await user.click(toggle());
|
||||
|
||||
await waitFor(() => expect(lastCall()?.params?.exclude_internal_health_checks).toBe(true));
|
||||
expect(lastCall()?.page).toBe(1);
|
||||
expect(toggle()).toBeChecked();
|
||||
expect(sessionStorage.getItem("excludeInternalHealthChecks")).toBe("true");
|
||||
});
|
||||
|
||||
it("restores the persisted toggle from sessionStorage", async () => {
|
||||
sessionStorage.setItem("excludeInternalHealthChecks", "true");
|
||||
renderPanel();
|
||||
|
||||
await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());
|
||||
expect(lastCall()?.params?.exclude_internal_health_checks).toBe(true);
|
||||
expect(toggle()).toBeChecked();
|
||||
});
|
||||
|
||||
it("falls back to showing health checks when the persisted value is malformed", async () => {
|
||||
sessionStorage.setItem("excludeInternalHealthChecks", "{not json");
|
||||
renderPanel();
|
||||
|
||||
await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());
|
||||
expect(lastCall()?.params?.exclude_internal_health_checks).toBe(false);
|
||||
expect(toggle()).not.toBeChecked();
|
||||
});
|
||||
});
|
||||
|
||||
describe("live tail", () => {
|
||||
it("shows the auto-refresh banner on the first page and hides it once stopped", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
|
|
|||
|
|
@ -72,6 +72,14 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,
|
|||
sessionStorage.setItem("isLiveTail", JSON.stringify(isLiveTail));
|
||||
}, [isLiveTail]);
|
||||
|
||||
const [excludeInternalHealthChecks, setExcludeInternalHealthChecks] = useState<boolean>(
|
||||
() => sessionStorage.getItem("excludeInternalHealthChecks") === "true",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
sessionStorage.setItem("excludeInternalHealthChecks", JSON.stringify(excludeInternalHealthChecks));
|
||||
}, [excludeInternalHealthChecks]);
|
||||
|
||||
const { logsQuery, filteredLogs, allTeams } = useLogFilterLogic({
|
||||
accessToken,
|
||||
token,
|
||||
|
|
@ -80,6 +88,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,
|
|||
columnFilters,
|
||||
activeTab: isActive ? "request logs" : "inactive",
|
||||
isLiveTail,
|
||||
excludeInternalHealthChecks,
|
||||
startTime,
|
||||
endTime,
|
||||
pagination,
|
||||
|
|
@ -219,6 +228,14 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,
|
|||
setPagination((previous) => ({ ...previous, pageIndex: 0 }));
|
||||
}, []);
|
||||
|
||||
const handleExcludeInternalHealthChecksChange = useCallback(
|
||||
(value: boolean) => {
|
||||
setExcludeInternalHealthChecks(value);
|
||||
resetToFirstPage();
|
||||
},
|
||||
[resetToFirstPage],
|
||||
);
|
||||
|
||||
const handleResetFilters = useCallback(() => {
|
||||
setColumnFilters([]);
|
||||
setStartTime(moment().subtract(24, "hours").format("YYYY-MM-DDTHH:mm"));
|
||||
|
|
@ -313,6 +330,8 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,
|
|||
onSelectedTimeIntervalChange={setSelectedTimeInterval}
|
||||
isLiveTail={isLiveTail}
|
||||
onIsLiveTailChange={setIsLiveTail}
|
||||
excludeInternalHealthChecks={excludeInternalHealthChecks}
|
||||
onExcludeInternalHealthChecksChange={handleExcludeInternalHealthChecksChange}
|
||||
onResetToFirstPage={resetToFirstPage}
|
||||
onResetFilters={handleResetFilters}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ const defaultProps = {
|
|||
columnFilters: [] as ColumnFiltersState,
|
||||
activeTab: "request logs",
|
||||
isLiveTail: false,
|
||||
excludeInternalHealthChecks: false,
|
||||
startTime: "2025-01-01T00:00:00",
|
||||
endTime: "2025-01-01T23:59:59",
|
||||
pagination: FIRST_PAGE,
|
||||
|
|
@ -82,6 +83,8 @@ describe("useLogFilterLogic", () => {
|
|||
{ id: LOG_FILTER_IDS.SESSION_ID, value: "sess-1", param: "session_id" },
|
||||
{ id: LOG_FILTER_IDS.END_USER, value: "end-user-1", param: "end_user" },
|
||||
{ id: LOG_FILTER_IDS.STATUS, value: "failure", param: "status_filter" },
|
||||
{ id: LOG_FILTER_IDS.CACHE_STATUS, value: "hit", param: "cache_hit_filter" },
|
||||
{ id: LOG_FILTER_IDS.CACHE_STATUS, value: "miss", param: "cache_hit_filter" },
|
||||
{ id: LOG_FILTER_IDS.MODEL_ID, value: "model-uuid-1", param: "model_id" },
|
||||
{ id: LOG_FILTER_IDS.PUBLIC_MODEL_OR_SEARCH_TOOL, value: "gpt-4o", param: "model" },
|
||||
{ id: LOG_FILTER_IDS.KEY_ALIAS, value: "alias-1", param: "key_alias" },
|
||||
|
|
@ -152,6 +155,7 @@ describe("useLogFilterLogic", () => {
|
|||
["pagination", { pagination: { pageIndex: 1, pageSize: 50 } }],
|
||||
["startTime", { startTime: "2025-02-02T00:00:00" }],
|
||||
["columnFilters", { columnFilters: [{ id: LOG_FILTER_IDS.TEAM_ID, value: "team-2" }] }],
|
||||
["excludeInternalHealthChecks", { excludeInternalHealthChecks: true }],
|
||||
])("refetches when %s changes", async (_label, nextProps) => {
|
||||
const { rerender } = renderHook((props: HookOverrides) => useLogFilterLogic({ ...defaultProps, ...props }), {
|
||||
wrapper,
|
||||
|
|
@ -164,6 +168,22 @@ describe("useLogFilterLogic", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("hide health checks toggle", () => {
|
||||
it("passes exclude_internal_health_checks when the toggle is on", async () => {
|
||||
renderFilterHook({ excludeInternalHealthChecks: true });
|
||||
|
||||
await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());
|
||||
expect(lastCallParams()?.params).toMatchObject({ exclude_internal_health_checks: true });
|
||||
});
|
||||
|
||||
it("passes exclude_internal_health_checks as false when the toggle is off", async () => {
|
||||
renderFilterHook();
|
||||
|
||||
await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());
|
||||
expect(lastCallParams()?.params).toMatchObject({ exclude_internal_health_checks: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("query enablement", () => {
|
||||
it("does not query when the request logs tab is inactive", async () => {
|
||||
renderFilterHook({ activeTab: "audit logs" });
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ export interface PaginatedResponse {
|
|||
export const LOG_FILTER_IDS = {
|
||||
TEAM_ID: "team_id",
|
||||
STATUS: "status",
|
||||
CACHE_STATUS: "cache_hit",
|
||||
KEY_ALIAS: "key_alias",
|
||||
END_USER: "end_user",
|
||||
ERROR_CODE: "error_code",
|
||||
|
|
@ -35,6 +36,7 @@ export const LOG_FILTER_IDS = {
|
|||
export const LOG_FILTER_LABELS: Record<string, string> = {
|
||||
[LOG_FILTER_IDS.TEAM_ID]: "Team ID",
|
||||
[LOG_FILTER_IDS.STATUS]: "Status",
|
||||
[LOG_FILTER_IDS.CACHE_STATUS]: "Cache",
|
||||
[LOG_FILTER_IDS.KEY_ALIAS]: "Key Alias",
|
||||
[LOG_FILTER_IDS.USER_ID]: "User ID",
|
||||
[LOG_FILTER_IDS.END_USER]: "End User",
|
||||
|
|
@ -101,6 +103,7 @@ export function useLogFilterLogic({
|
|||
columnFilters,
|
||||
activeTab,
|
||||
isLiveTail,
|
||||
excludeInternalHealthChecks,
|
||||
startTime,
|
||||
endTime,
|
||||
pagination,
|
||||
|
|
@ -114,6 +117,7 @@ export function useLogFilterLogic({
|
|||
columnFilters: ColumnFiltersState;
|
||||
activeTab: string;
|
||||
isLiveTail: boolean;
|
||||
excludeInternalHealthChecks: boolean;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
pagination: PaginationState;
|
||||
|
|
@ -137,6 +141,7 @@ export function useLogFilterLogic({
|
|||
columnFilters,
|
||||
sortBy,
|
||||
sortOrder,
|
||||
excludeInternalHealthChecks,
|
||||
],
|
||||
queryFn: async () => {
|
||||
if (!accessToken || !token || !userRole || !userID) {
|
||||
|
|
@ -167,6 +172,7 @@ export function useLogFilterLogic({
|
|||
user_id: userIdFilter,
|
||||
end_user: getFilterValue(columnFilters, LOG_FILTER_IDS.END_USER),
|
||||
status_filter: getFilterValue(columnFilters, LOG_FILTER_IDS.STATUS),
|
||||
cache_hit_filter: getFilterValue(columnFilters, LOG_FILTER_IDS.CACHE_STATUS),
|
||||
model_id: getFilterValue(columnFilters, LOG_FILTER_IDS.MODEL_ID),
|
||||
model: getFilterValue(columnFilters, LOG_FILTER_IDS.PUBLIC_MODEL_OR_SEARCH_TOOL),
|
||||
key_alias: getFilterValue(columnFilters, LOG_FILTER_IDS.KEY_ALIAS),
|
||||
|
|
@ -174,6 +180,7 @@ export function useLogFilterLogic({
|
|||
error_message: getFilterValue(columnFilters, LOG_FILTER_IDS.ERROR_MESSAGE),
|
||||
sort_by: sortBy,
|
||||
sort_order: sortOrder,
|
||||
exclude_internal_health_checks: excludeInternalHealthChecks,
|
||||
},
|
||||
});
|
||||
},
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
buildPresetPrefill,
|
||||
buildModelAvailability,
|
||||
deploymentRefsFromModelInfo,
|
||||
normalizeModelName,
|
||||
} from "./autorouter_presets";
|
||||
import { DEFAULT_MATCH_THRESHOLD } from "@/components/add_model/SemanticKeywordMatching";
|
||||
import { DEFAULT_ESCALATION_KEYWORDS } from "@/components/add_model/EscalationKeywords";
|
||||
|
|
@ -28,6 +29,29 @@ describe("autorouter_presets", () => {
|
|||
}
|
||||
});
|
||||
|
||||
// buildPresetPrefill resolves every model reference through normalizeModelName, so two spellings
|
||||
// of the same model in one tier (e.g. "claude-sonnet-4-5" and "claude-sonnet-4.5") collapse to one
|
||||
// key. For tier_model_configs that silently drops one model's litellm_params; catch it in the
|
||||
// bundled data itself, since nothing else validates preset authoring.
|
||||
it("never spells the same model two ways within a single tier", () => {
|
||||
for (const preset of getAllPresets()) {
|
||||
const { tiers, tier_model_configs: configs } = preset.complexity_router_config;
|
||||
for (const tier of Object.keys(tiers) as (keyof typeof tiers)[]) {
|
||||
const fromTierList = tiers[tier] ?? [];
|
||||
const fromConfigs = (configs?.[tier] ?? []).map((entry) => entry.model_name);
|
||||
const names = new Set([...fromTierList, ...fromConfigs]);
|
||||
const byNormalized = new Map<string, string[]>();
|
||||
for (const name of names) {
|
||||
const key = normalizeModelName(name);
|
||||
byNormalized.set(key, [...(byNormalized.get(key) ?? []), name]);
|
||||
}
|
||||
for (const spellings of byNormalized.values()) {
|
||||
expect(new Set(spellings).size, `${preset.key}.${tier}: ${spellings.join(", ")}`).toBe(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves a preset by its stable JSON key, not its display label", () => {
|
||||
expect(getPresetByKey("anthropic_family")?.label).toBe("Anthropic Family");
|
||||
expect(getPresetByKey("does_not_exist")).toBeUndefined();
|
||||
|
|
@ -75,6 +99,36 @@ describe("autorouter_presets", () => {
|
|||
);
|
||||
});
|
||||
|
||||
// Opus serves both tiers, so the effort is all that separates them and losing it fails silently.
|
||||
it("pins the anthropic preset's reasoning tier to Opus at high thinking", () => {
|
||||
const config = getPresetByKey("anthropic_family")!.complexity_router_config;
|
||||
expect(config.tiers.COMPLEX).toEqual(["claude-opus-5"]);
|
||||
expect(config.tiers.REASONING).toEqual(["claude-opus-5"]);
|
||||
expect(config.tier_model_configs).toEqual({
|
||||
REASONING: [{ model_name: "claude-opus-5", litellm_params: { reasoning_effort: "high" } }],
|
||||
});
|
||||
});
|
||||
|
||||
// serializeTierModelConfigs filters on the tier's models, so a stray name drops silently.
|
||||
it("never names a model in tier_model_configs that its own tier does not hold", () => {
|
||||
for (const preset of getAllPresets()) {
|
||||
const { tiers, tier_model_configs: configs } = preset.complexity_router_config;
|
||||
for (const [tier, entries] of Object.entries(configs ?? {})) {
|
||||
for (const entry of entries) {
|
||||
expect(tiers[tier as keyof typeof tiers] ?? [], `${preset.key}.${tier}`).toContain(entry.model_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("prefills the anthropic preset's effort through to tier_model_params", () => {
|
||||
const preset = getPresetByKey("anthropic_family")!;
|
||||
const prefill = buildPresetPrefill(preset.complexity_router_config, groupsOnly(getRequiredModelsInPreset(preset)));
|
||||
expect(prefill.complexityRouterConfig.tier_model_params).toEqual({
|
||||
REASONING: { "claude-opus-5": { reasoning_effort: "high" } },
|
||||
});
|
||||
});
|
||||
|
||||
it("pins the gemini preset to concrete model ids, never Google's hot-swapping -latest aliases", () => {
|
||||
const gemini = getPresetByKey("gemini_family")!;
|
||||
const config = gemini.complexity_router_config;
|
||||
|
|
@ -544,5 +598,73 @@ describe("autorouter_presets", () => {
|
|||
const prefill = buildPresetPrefill(config, groupsOnly(["claude-sonnet-4.5"]));
|
||||
expect(prefill.complexityRouterConfig.tiers.SIMPLE).toEqual(["claude-sonnet-4.5"]);
|
||||
});
|
||||
|
||||
it("prefills the per-model litellm_params a preset carries in tier_model_configs", () => {
|
||||
const config = {
|
||||
tiers: { SIMPLE: ["gpt-5-nano"], MEDIUM: [], COMPLEX: [], REASONING: ["o3"] },
|
||||
tier_model_configs: {
|
||||
REASONING: [{ model_name: "o3", litellm_params: { reasoning_effort: "high" } }],
|
||||
},
|
||||
classifier_type: "heuristic" as const,
|
||||
session_affinity: false,
|
||||
deployment_affinity: true,
|
||||
};
|
||||
const prefill = buildPresetPrefill(config, groupsOnly(["gpt-5-nano", "o3"]));
|
||||
expect(prefill.complexityRouterConfig.tier_model_params).toEqual({
|
||||
REASONING: { o3: { reasoning_effort: "high" } },
|
||||
});
|
||||
});
|
||||
|
||||
// The params key on the preset's own spelling while the tier entry gets rewritten to the
|
||||
// caller's. Leaving the key alone names a model the tier no longer holds, and
|
||||
// serializeTierModelConfigs then drops the params on submit without saying so.
|
||||
it("rewrites a param key to the same registered spelling its tier entry was rewritten to", () => {
|
||||
const config = {
|
||||
tiers: { SIMPLE: [], MEDIUM: [], COMPLEX: [], REASONING: ["claude-sonnet-4-5"] },
|
||||
tier_model_configs: {
|
||||
REASONING: [{ model_name: "claude-sonnet-4-5", litellm_params: { reasoning_effort: "high" } }],
|
||||
},
|
||||
classifier_type: "heuristic" as const,
|
||||
session_affinity: false,
|
||||
deployment_affinity: true,
|
||||
};
|
||||
const prefill = buildPresetPrefill(config, groupsOnly(["claude-sonnet-4.5"]));
|
||||
expect(prefill.complexityRouterConfig.tier_model_params).toEqual({
|
||||
REASONING: { "claude-sonnet-4.5": { reasoning_effort: "high" } },
|
||||
});
|
||||
});
|
||||
|
||||
// Two spellings of one model in a tier collapse to a single registered key, and one model can
|
||||
// only hold one param set downstream. Merging keeps whatever only one spelling set instead of
|
||||
// dropping that spelling's params wholesale.
|
||||
it("merges rather than drops params when two spellings resolve to the same registered model", () => {
|
||||
const config = {
|
||||
tiers: { SIMPLE: [], MEDIUM: [], COMPLEX: [], REASONING: ["claude-sonnet-4-5", "claude-sonnet-4.5"] },
|
||||
tier_model_configs: {
|
||||
REASONING: [
|
||||
{ model_name: "claude-sonnet-4-5", litellm_params: { reasoning_effort: "high", temperature: 0.2 } },
|
||||
{ model_name: "claude-sonnet-4.5", litellm_params: { reasoning_effort: "low" } },
|
||||
],
|
||||
},
|
||||
classifier_type: "heuristic" as const,
|
||||
};
|
||||
const prefill = buildPresetPrefill(config, groupsOnly(["claude-sonnet-4.5"]));
|
||||
// temperature survives from the spelling that would otherwise have been overwritten;
|
||||
// reasoning_effort, set by both, resolves last-wins.
|
||||
expect(prefill.complexityRouterConfig.tier_model_params).toEqual({
|
||||
REASONING: { "claude-sonnet-4.5": { reasoning_effort: "low", temperature: 0.2 } },
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves tier_model_params undefined for a preset that carries no per-model params", () => {
|
||||
const config = {
|
||||
tiers: { SIMPLE: ["gpt-5-nano"], MEDIUM: [], COMPLEX: [], REASONING: [] },
|
||||
classifier_type: "heuristic" as const,
|
||||
session_affinity: false,
|
||||
deployment_affinity: true,
|
||||
};
|
||||
const prefill = buildPresetPrefill(config, groupsOnly(["gpt-5-nano"]));
|
||||
expect(prefill.complexityRouterConfig.tier_model_params).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -12,6 +12,11 @@ import {
|
|||
} from "@/components/add_model/ComplexityRouterConfig";
|
||||
import { KeywordTierRule } from "@/components/add_model/KeywordTierRules";
|
||||
import { hydrateKeywordTierRules } from "@/components/add_model/complexity_router_keywords";
|
||||
import {
|
||||
TierModelParams,
|
||||
TierModelParamsByTier,
|
||||
hydrateTierModelParams,
|
||||
} from "@/components/add_model/complexity_router_tiers";
|
||||
import { DEFAULT_ESCALATION_KEYWORDS } from "@/components/add_model/EscalationKeywords";
|
||||
import { DEFAULT_MATCH_THRESHOLD } from "@/components/add_model/SemanticKeywordMatching";
|
||||
import presetsRaw from "@/autorouter_presets.json";
|
||||
|
|
@ -54,7 +59,7 @@ export const getRequiredModels = (
|
|||
// differing only in that separator. Canonicalizing on "-" (the presets' own convention) lets both
|
||||
// spellings match without doing anything looser - two DIFFERENT model names never collide here,
|
||||
// only the punctuation within one version number does.
|
||||
const normalizeModelName = (model: string): string => model.replace(/(\d)\.(\d)/g, "$1-$2");
|
||||
export const normalizeModelName = (model: string): string => model.replace(/(\d)\.(\d)/g, "$1-$2");
|
||||
|
||||
export interface DeploymentModelRef {
|
||||
modelGroup: string;
|
||||
|
|
@ -244,6 +249,25 @@ export const buildPresetPrefill = (
|
|||
): PresetPrefill => {
|
||||
const resolve = (model: string): string => resolveAvailableModel(model, availability) ?? model;
|
||||
const resolveTier = (models: string[]): string[] => models.map(resolve);
|
||||
// Params key on the model name the preset spells while every tier entry is rewritten to the
|
||||
// caller's registered spelling, so the keys have to be rewritten the same way. Otherwise
|
||||
// serializeTierModelConfigs drops them for naming a model the tier no longer holds.
|
||||
//
|
||||
// Two spellings in one tier can resolve to the same registered model, and one model holds one
|
||||
// param set here and in the payload, so a collision has to collapse. Merge rather than replace:
|
||||
// params only one spelling set still survive, and a key both set resolves last-wins, matching
|
||||
// how hydrateTierModelParams already collapses two entries spelled identically.
|
||||
const resolveParamKeys = (params: TierModelParamsByTier | undefined): TierModelParamsByTier | undefined =>
|
||||
params &&
|
||||
Object.fromEntries(
|
||||
Object.entries(params).map(([tier, byModel]) => [
|
||||
tier,
|
||||
Object.entries(byModel).reduce<Record<string, TierModelParams>>((byResolved, [model, litellmParams]) => {
|
||||
const resolved = resolve(model);
|
||||
return { ...byResolved, [resolved]: { ...byResolved[resolved], ...litellmParams } };
|
||||
}, {}),
|
||||
]),
|
||||
);
|
||||
|
||||
return {
|
||||
complexityRouterConfig: {
|
||||
|
|
@ -253,6 +277,7 @@ export const buildPresetPrefill = (
|
|||
COMPLEX: resolveTier(config.tiers.COMPLEX),
|
||||
REASONING: resolveTier(config.tiers.REASONING),
|
||||
},
|
||||
tier_model_params: resolveParamKeys(hydrateTierModelParams(config.tiers, config.tier_model_configs)),
|
||||
tier_labels: hydrateTierLabels(config.tier_labels),
|
||||
classifier_type: config.classifier_type,
|
||||
classifier_llm_config: config.classifier_llm_config && {
|
||||
|
|
|
|||
2950
ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
2950
ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
File diff suppressed because it is too large
Load diff
Loading…
Add table
Reference in a new issue