mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-23 22:07:29 +00:00
fix(proxy): type the tokenize body and keep caller fields request-owned
This commit is contained in:
parent
d25ca0079e
commit
2141be88c4
21 changed files with 983 additions and 12 deletions
1
.github/workflows/test-unit.yml
vendored
1
.github/workflows/test-unit.yml
vendored
|
|
@ -558,6 +558,7 @@ jobs:
|
|||
tests/unit/proxy/rag_endpoints
|
||||
tests/unit/proxy/rerank_endpoints
|
||||
tests/unit/proxy/realtime_endpoints
|
||||
tests/unit/proxy/tokenize_endpoints
|
||||
tests/unit/proxy/ui_crud_endpoints
|
||||
tests/unit/proxy/config_resolvers
|
||||
tests/unit/proxy/utils
|
||||
|
|
|
|||
|
|
@ -68,6 +68,8 @@ GATEWAY_PATH_PREFIXES: tuple[str, ...] = (
|
|||
"/extraction",
|
||||
"/v1/ocr",
|
||||
"/ocr",
|
||||
"/v1/tokenize",
|
||||
"/tokenize",
|
||||
"/v1/rag/",
|
||||
"/rag/",
|
||||
"/v1/video",
|
||||
|
|
|
|||
|
|
@ -39175,6 +39175,42 @@
|
|||
"title": "PinnedMCPTool",
|
||||
"type": "object"
|
||||
},
|
||||
"ProxyTokenizeRequest": {
|
||||
"additionalProperties": true,
|
||||
"properties": {
|
||||
"add_special_tokens": {
|
||||
"title": "Add Special Tokens",
|
||||
"type": "boolean"
|
||||
},
|
||||
"include": {
|
||||
"items": {
|
||||
"enum": [
|
||||
"token_ids",
|
||||
"tokens"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"title": "Include",
|
||||
"type": "array",
|
||||
"uniqueItems": true
|
||||
},
|
||||
"model": {
|
||||
"minLength": 1,
|
||||
"title": "Model",
|
||||
"type": "string"
|
||||
},
|
||||
"prompt": {
|
||||
"title": "Prompt",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"model",
|
||||
"prompt"
|
||||
],
|
||||
"title": "ProxyTokenizeRequest",
|
||||
"type": "object"
|
||||
},
|
||||
"RegisterGuardrailRequest": {
|
||||
"description": "Request body for POST /guardrails/register. Follows Generic Guardrail API config.",
|
||||
"properties": {
|
||||
|
|
@ -39253,6 +39289,53 @@
|
|||
"title": "RegisterGuardrailResponse",
|
||||
"type": "object"
|
||||
},
|
||||
"TokenizeResponse": {
|
||||
"properties": {
|
||||
"count": {
|
||||
"minimum": 0.0,
|
||||
"title": "Count",
|
||||
"type": "integer"
|
||||
},
|
||||
"model": {
|
||||
"title": "Model",
|
||||
"type": "string"
|
||||
},
|
||||
"token_ids": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "integer"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Token Ids"
|
||||
},
|
||||
"tokens": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Tokens"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"model",
|
||||
"count"
|
||||
],
|
||||
"title": "TokenizeResponse",
|
||||
"type": "object"
|
||||
},
|
||||
"ValidationError": {
|
||||
"properties": {
|
||||
"ctx": {
|
||||
|
|
@ -40495,6 +40578,53 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
"/tokenize": {
|
||||
"post": {
|
||||
"description": "Tokenize raw text and return its count with explicitly requested representations.",
|
||||
"operationId": "tokenize_tokenize_post",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProxyTokenizeRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/TokenizeResponse"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
},
|
||||
"422": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Validation Error"
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"APIKeyHeader": []
|
||||
}
|
||||
],
|
||||
"summary": "Tokenize",
|
||||
"tags": [
|
||||
"mcp_discoverable"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v1/mcp/server/register": {
|
||||
"post": {
|
||||
"description": "Submit a new MCP server for admin review (non-admin users). Mirrors POST /guardrails/register.",
|
||||
|
|
|
|||
|
|
@ -382,6 +382,8 @@ class LiteLLMRoutes(enum.Enum):
|
|||
# OCR
|
||||
"/ocr",
|
||||
"/v1/ocr",
|
||||
"/tokenize",
|
||||
"/v1/tokenize",
|
||||
# containers API
|
||||
"/containers",
|
||||
"/v1/containers",
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ _MANAGED_MODEL_ROUTES: Final = frozenset(
|
|||
"systemone",
|
||||
"extraction",
|
||||
"ocr",
|
||||
"tokenize",
|
||||
),
|
||||
)
|
||||
) | frozenset(
|
||||
|
|
|
|||
|
|
@ -96,6 +96,8 @@ _UNBILLED_ROUTES: Final[frozenset[str]] = frozenset(
|
|||
"/models",
|
||||
"/v1/models",
|
||||
"/utils/token_counter",
|
||||
"/tokenize",
|
||||
"/v1/tokenize",
|
||||
"/utils/transform_request",
|
||||
"/responses/input_tokens",
|
||||
"/v1/responses/input_tokens",
|
||||
|
|
|
|||
|
|
@ -32,6 +32,10 @@ from starlette.types import Receive, Scope, Send
|
|||
from typing_extensions import Never
|
||||
|
||||
import litellm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from litellm.tokenize.routing import TokenizeAdmissionContext
|
||||
|
||||
from litellm._logging import redact_internal_details_from_client_message, verbose_proxy_logger
|
||||
from litellm._uuid import uuid
|
||||
from litellm.anthropic_interface.exceptions import AnthropicErrorSseFrame, anthropic_error_sse_frame
|
||||
|
|
@ -190,6 +194,7 @@ ProxyRouteType: TypeAlias = Literal[
|
|||
"avector_store_file_update",
|
||||
"avector_store_file_delete",
|
||||
"aocr",
|
||||
"atokenize",
|
||||
"asearch",
|
||||
"adecisions",
|
||||
"asystemone",
|
||||
|
|
@ -274,6 +279,8 @@ from litellm.types.utils import (
|
|||
Usage,
|
||||
)
|
||||
|
||||
_TOKENIZE_ROUTE_DATA_ADAPTER: Final = TypeAdapter(dict[str, object])
|
||||
|
||||
# Datadog streaming spans are a no-op when ddtrace is not enabled, but the
|
||||
# ``with tracer.trace(...)`` context manager still allocates a NullSpan and
|
||||
# runs __enter__/__exit__ for every streamed chunk. Resolve once at import so
|
||||
|
|
@ -1981,9 +1988,15 @@ def _content_text(fields: Mapping[str, object]) -> str:
|
|||
|
||||
|
||||
class ProxyBaseLLMRequestProcessing:
|
||||
def __init__(self, data: dict, served_model: str | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
data: dict, # mutable-ok: existing request handlers mutate this compatibility payload
|
||||
served_model: str | None = None,
|
||||
tokenize_admission_context: "TokenizeAdmissionContext | None" = None,
|
||||
):
|
||||
self.data = data
|
||||
self.served_model = served_model
|
||||
self.tokenize_admission_context = tokenize_admission_context
|
||||
self._tags_before_guardrails: frozenset[str] | None = None
|
||||
self.route_type: str | None = None
|
||||
|
||||
|
|
@ -2216,6 +2229,7 @@ class ProxyBaseLLMRequestProcessing:
|
|||
"avector_store_file_update",
|
||||
"avector_store_file_delete",
|
||||
"aocr",
|
||||
"atokenize",
|
||||
"asearch",
|
||||
"adecisions",
|
||||
"asystemone",
|
||||
|
|
@ -2927,7 +2941,16 @@ class ProxyBaseLLMRequestProcessing:
|
|||
### ROUTE THE REQUEST ###
|
||||
# Do not change this - it should be a constant time fetch - ALWAYS
|
||||
llm_call: Final = await route_request(
|
||||
data=self.data,
|
||||
data=(
|
||||
{
|
||||
**_TOKENIZE_ROUTE_DATA_ADAPTER.validate_python(
|
||||
self.data # pyright: ignore[reportUnknownMemberType] # TypeAdapter validates payload
|
||||
),
|
||||
"_tokenize_context": self.tokenize_admission_context,
|
||||
}
|
||||
if route_type == "atokenize" and self.tokenize_admission_context is not None
|
||||
else self.data
|
||||
),
|
||||
route_type=route_type,
|
||||
llm_router=llm_router,
|
||||
user_model=user_model,
|
||||
|
|
|
|||
|
|
@ -908,6 +908,7 @@ from litellm.proxy.spend_tracking.spend_management_endpoints import (
|
|||
router as spend_management_router,
|
||||
)
|
||||
from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
|
||||
from litellm.proxy.tokenize_endpoints.endpoints import router as tokenize_router
|
||||
from litellm.proxy.tracing_runtime import manage_tracing
|
||||
from litellm.proxy.types_utils.utils import get_instance_fn
|
||||
from litellm.proxy.ui_crud_endpoints.latest_release_endpoints import (
|
||||
|
|
@ -21532,6 +21533,7 @@ app.include_router(public_endpoints_router)
|
|||
app.include_router(public_v1_router)
|
||||
app.include_router(rerank_router)
|
||||
app.include_router(ocr_router)
|
||||
app.include_router(tokenize_router)
|
||||
app.include_router(rag_router)
|
||||
app.include_router(video_router)
|
||||
app.include_router(container_router)
|
||||
|
|
|
|||
|
|
@ -155,6 +155,7 @@ ROUTE_ENDPOINT_MAPPING: Final = {
|
|||
"acancel_responses": "/responses/{response_id}/cancel",
|
||||
"acompact_responses": "/responses/compact",
|
||||
"aocr": "/ocr",
|
||||
"atokenize": "/tokenize",
|
||||
"asearch": "/search",
|
||||
"adecisions": "/decisions",
|
||||
"asystemone": "/systemone",
|
||||
|
|
@ -246,6 +247,7 @@ REQUIRED_PRESENT_BODY_PARAMS_BY_ROUTE: Final[Mapping[str, tuple[str, ...]]] = Ma
|
|||
"anthropic_messages": ("messages", "max_tokens"),
|
||||
"agenerate_content": ("contents",),
|
||||
"aocr": ("document",),
|
||||
"atokenize": ("prompt",),
|
||||
"avector_store_search": ("query",),
|
||||
"avector_store_file_create": ("file_id",),
|
||||
"avector_store_file_update": ("attributes",),
|
||||
|
|
@ -618,6 +620,7 @@ RouteType = Literal[
|
|||
"avector_store_file_update",
|
||||
"avector_store_file_delete",
|
||||
"aocr",
|
||||
"atokenize",
|
||||
"asearch",
|
||||
"adecisions",
|
||||
"asystemone",
|
||||
|
|
|
|||
0
litellm/proxy/tokenize_endpoints/__init__.py
Normal file
0
litellm/proxy/tokenize_endpoints/__init__.py
Normal file
91
litellm/proxy/tokenize_endpoints/endpoints.py
Normal file
91
litellm/proxy/tokenize_endpoints/endpoints.py
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
from collections.abc import Mapping
|
||||
from typing import Annotated, Final
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from pydantic import BaseModel, ConfigDict, model_validator
|
||||
|
||||
from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth
|
||||
from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing
|
||||
from litellm.tokenize.routing import TokenizeAdmissionContext
|
||||
from litellm.types.tokenize import TokenizeRequest, TokenizeResponse
|
||||
|
||||
router: Final = APIRouter()
|
||||
|
||||
|
||||
class ProxyTokenizeRequest(TokenizeRequest):
|
||||
model_config = ConfigDict(frozen=True, extra="allow", strict=True)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def reserved_fields(self) -> "ProxyTokenizeRequest":
|
||||
if any(name.startswith("_tokenize_") for name in self.model_extra or {}):
|
||||
raise ValueError("_tokenize_ fields are reserved")
|
||||
return self
|
||||
|
||||
|
||||
class _ProxySettings(BaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
general_settings: Mapping[str, object]
|
||||
user_model: str | None
|
||||
user_api_base: str | None
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/tokenize",
|
||||
dependencies=[Depends(user_api_key_auth)],
|
||||
response_model=TokenizeResponse,
|
||||
tags=["tokenize"],
|
||||
)
|
||||
@router.post(
|
||||
"/tokenize",
|
||||
dependencies=[Depends(user_api_key_auth)],
|
||||
response_model=TokenizeResponse,
|
||||
tags=["tokenize"],
|
||||
)
|
||||
async def tokenize(
|
||||
body: ProxyTokenizeRequest,
|
||||
request: Request,
|
||||
fastapi_response: Response,
|
||||
user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
|
||||
) -> object:
|
||||
"""Tokenize raw text and return its count with explicitly requested representations."""
|
||||
from litellm.proxy import proxy_server
|
||||
from litellm.proxy.proxy_server import (
|
||||
llm_router,
|
||||
proxy_config,
|
||||
proxy_logging_obj,
|
||||
user_request_timeout,
|
||||
version,
|
||||
)
|
||||
|
||||
settings: Final = _ProxySettings.model_validate(vars(proxy_server))
|
||||
processor: Final = ProxyBaseLLMRequestProcessing(
|
||||
data=body.model_dump(exclude_unset=True),
|
||||
tokenize_admission_context=TokenizeAdmissionContext(),
|
||||
)
|
||||
try:
|
||||
return await processor.base_process_llm_request(
|
||||
request=request,
|
||||
fastapi_response=fastapi_response,
|
||||
user_api_key_dict=user_api_key_dict,
|
||||
route_type="atokenize",
|
||||
proxy_logging_obj=proxy_logging_obj,
|
||||
llm_router=llm_router,
|
||||
general_settings=dict(settings.general_settings),
|
||||
proxy_config=proxy_config,
|
||||
select_data_generator=None,
|
||||
model=None,
|
||||
user_model=settings.user_model,
|
||||
user_temperature=None,
|
||||
user_request_timeout=user_request_timeout,
|
||||
user_max_tokens=None,
|
||||
user_api_base=settings.user_api_base,
|
||||
version=version,
|
||||
)
|
||||
except Exception as error: # noqa: BLE001 # normalize all provider and routing failures at the HTTP boundary
|
||||
raise await processor.handle_llm_api_exception(
|
||||
e=error,
|
||||
user_api_key_dict=user_api_key_dict,
|
||||
proxy_logging_obj=proxy_logging_obj,
|
||||
version=version,
|
||||
)
|
||||
|
|
@ -28,6 +28,8 @@ _PROJECTED_FIELDS: Final = frozenset(
|
|||
_OPERATIONAL_FIELDS: Final = frozenset(
|
||||
{
|
||||
"client",
|
||||
"client_side_timeout",
|
||||
"headers",
|
||||
"shared_session",
|
||||
"request_timeout",
|
||||
"max_retries",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Tokenization
|
||||
|
||||
LiteLLM tokenization is available through the SDK and Router. It supports provider-backed tokenization.
|
||||
LiteLLM tokenization is available through the SDK, Router, and proxy HTTP routes. It supports provider-backed tokenization.
|
||||
|
||||
## SDK
|
||||
|
||||
|
|
@ -30,6 +30,21 @@ Request both representations with `include=["token_ids", "tokens"]`. A requested
|
|||
|
||||
`add_special_tokens` is optional and must be a boolean when supplied. Omitting it lets the provider decide.
|
||||
|
||||
## Proxy
|
||||
|
||||
Send a request to either `/tokenize` or `/v1/tokenize`:
|
||||
|
||||
```bash
|
||||
curl http://localhost:4000/tokenize \
|
||||
-H 'Authorization: Bearer sk-...' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"tokenizer","prompt":"Hello, world","include":["token_ids"]}'
|
||||
```
|
||||
|
||||
The proxy resolves the model deployment and applies its configured provider. Client credentials and provider options remain subject to the proxy's existing authorization policy.
|
||||
|
||||
This endpoint does not change `token_counter`, `count_tokens`, or other legacy token-count APIs.
|
||||
|
||||
## Other token APIs
|
||||
|
||||
Tokenization is separate from the legacy `token_counter`, `encode`, and `decode` APIs. Those APIs retain their existing behavior and defaults.
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ from litellm.rust_bridge.host.routes.tokenize import body_params
|
|||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TokenizeAdmissionContext:
|
||||
authorized_fields: frozenset[str] = frozenset()
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
|
@ -30,13 +30,13 @@ def source_for(request: Mapping[str, object], name: str) -> str:
|
|||
context: Final = request.get("_tokenize_context")
|
||||
if context is None:
|
||||
return "deployment"
|
||||
if isinstance(context, TokenizeAdmissionContext):
|
||||
return "request"
|
||||
names: Final = (
|
||||
tuple(field for field in ("api_base", "base_url") if request.get(field) is not None)
|
||||
if name == "api_base"
|
||||
else (name,)
|
||||
)
|
||||
if isinstance(context, TokenizeAdmissionContext):
|
||||
return "deployment" if all(field in context.authorized_fields for field in names) else "request"
|
||||
if isinstance(context, TokenizeRoutingContext):
|
||||
return "deployment" if all(field in context.trusted_fields for field in names) else "request"
|
||||
raise ValueError("invalid tokenization context")
|
||||
|
|
@ -55,17 +55,13 @@ def deployment_kwargs(
|
|||
caller_fields: frozenset[str],
|
||||
) -> Mapping[str, object]:
|
||||
validate_internal_fields(request)
|
||||
admission: Final = request.get("_tokenize_context")
|
||||
authorized: Final = (
|
||||
admission.authorized_fields if isinstance(admission, TokenizeAdmissionContext) else frozenset[str]()
|
||||
)
|
||||
provider_params: Final = body_params(deployment)
|
||||
return MappingProxyType(
|
||||
{
|
||||
**{name: value for name, value in deployment.items() if name not in provider_params},
|
||||
**{name: value for name, value in request.items() if name not in provider_params or name in caller_fields},
|
||||
"_tokenize_context": TokenizeRoutingContext(
|
||||
trusted_fields=(frozenset(deployment) | frozenset(request)).difference(caller_fields) | authorized,
|
||||
trusted_fields=(frozenset(deployment) | frozenset(request)).difference(caller_fields),
|
||||
deployment_params=MappingProxyType(dict(provider_params)),
|
||||
),
|
||||
}
|
||||
|
|
|
|||
71
tests/integration/_support/tokenize_hook_probe.py
Normal file
71
tests/integration/_support/tokenize_hook_probe.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from typing import Final
|
||||
|
||||
import httpx
|
||||
|
||||
from litellm.integrations.custom_logger import CustomLogger
|
||||
from litellm.proxy._types import UserAPIKeyAuth
|
||||
from litellm.types.tokenize import TokenizeResponse
|
||||
|
||||
|
||||
async def _record(
|
||||
stage: str,
|
||||
data: Mapping[str, object],
|
||||
user_api_key_dict: UserAPIKeyAuth,
|
||||
response: TokenizeResponse | None = None,
|
||||
call_type: str | None = None,
|
||||
) -> None:
|
||||
metadata: Final = data.get("metadata")
|
||||
body: Final = {
|
||||
"stage": stage,
|
||||
"call_id": data.get("litellm_call_id"),
|
||||
"call_type": call_type or data.get("call_type"),
|
||||
"prompt": data.get("prompt"),
|
||||
"user_id": user_api_key_dict.user_id,
|
||||
"user": data.get("user"),
|
||||
"metadata": (
|
||||
{"request_marker": metadata.get("request_marker")}
|
||||
if isinstance(metadata, Mapping)
|
||||
else None
|
||||
),
|
||||
"count": response.count if response is not None else None,
|
||||
"model": response.model if response is not None else None,
|
||||
"token_ids": response.token_ids if response is not None else None,
|
||||
"tokens": response.tokens if response is not None else None,
|
||||
"hidden_params": dict(response._hidden_params) if response is not None else None,
|
||||
}
|
||||
async with httpx.AsyncClient(trust_env=False, timeout=2) as client:
|
||||
probe_response: Final = await client.post(os.environ["TOKENIZE_HOOK_PROBE_URL"], json=body)
|
||||
probe_response.raise_for_status()
|
||||
|
||||
|
||||
class TokenizeHookProbe(CustomLogger):
|
||||
async def async_pre_call_hook(
|
||||
self,
|
||||
user_api_key_dict: UserAPIKeyAuth,
|
||||
cache: object,
|
||||
data: dict[str, object],
|
||||
call_type: str,
|
||||
) -> dict[str, object] | None:
|
||||
if call_type != "atokenize":
|
||||
return None
|
||||
rewritten: Final = {**data, "prompt": "rewritten by tokenization hook"}
|
||||
await _record("pre", rewritten, user_api_key_dict, call_type=call_type)
|
||||
return rewritten
|
||||
|
||||
async def async_post_call_success_hook(
|
||||
self,
|
||||
data: dict[str, object],
|
||||
user_api_key_dict: UserAPIKeyAuth,
|
||||
response: object,
|
||||
) -> object | None:
|
||||
if not isinstance(response, TokenizeResponse):
|
||||
return None
|
||||
await _record("post", data, user_api_key_dict, response)
|
||||
return response.model_copy(update={"model": "hook-replaced-model", "count": 777})
|
||||
|
||||
|
||||
probe: Final = TokenizeHookProbe()
|
||||
212
tests/integration/providers/test_tokenize_wire.py
Normal file
212
tests/integration/providers/test_tokenize_wire.py
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
import json
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import yaml
|
||||
from integration._support.client import Gateway, object_value
|
||||
from integration._support.process import OwnedState, owned_proxy
|
||||
from integration._support.wire import Reply, Request, wire_server
|
||||
|
||||
|
||||
def _tokenizer(request: Request) -> Reply:
|
||||
assert (request.method, request.target) == ("POST", "/tokenize")
|
||||
assert request.headers["authorization"] == "Bearer deployment-token"
|
||||
body: Final = json.loads(request.body)
|
||||
assert body["model"] == "acme/model"
|
||||
assert body["prompt"] == "Hello world"
|
||||
return Reply(body=json.dumps({"count": 2, "tokens": [101, 102], "max_model_len": 4096}).encode())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/tokenize", "/v1/tokenize"])
|
||||
def test_tokenization_routes_model_alias_with_inference_auth(tmp_path: Path, path: str) -> None:
|
||||
with (
|
||||
wire_server(_tokenizer) as wire,
|
||||
httpx.Client(base_url="http://127.0.0.1:1", trust_env=False) as base_client,
|
||||
):
|
||||
base_gateway: Final = Gateway(base_client, "sk-integration-tokenize", wire.url)
|
||||
with (
|
||||
owned_proxy(base_gateway, tmp_path, {"STORE_MODEL_IN_DB": "False"}, state=OwnedState.PRIVATE) as gateway,
|
||||
gateway.scenario() as scenario,
|
||||
):
|
||||
model: Final = scenario.model(
|
||||
model="hosted_vllm/acme/model",
|
||||
api_base=wire.url,
|
||||
api_key="deployment-token",
|
||||
)
|
||||
denied_key: Final = scenario.key(models=["another-model"])
|
||||
denied: Final = gateway.request("POST", path, {"model": model, "prompt": "Hello world"}, key=denied_key)
|
||||
assert denied.status_code in (401, 403), denied.text
|
||||
assert wire.drain() == ()
|
||||
allowed_key: Final = scenario.key(models=[model])
|
||||
invalid: Final = gateway.request(
|
||||
"POST",
|
||||
path,
|
||||
{"model": model, "prompt": "Hello world", "unsupported_option": True},
|
||||
key=allowed_key,
|
||||
)
|
||||
assert invalid.status_code == 400, invalid.text
|
||||
assert wire.drain() == ()
|
||||
response: Final = gateway.request(
|
||||
"POST",
|
||||
path,
|
||||
{"model": model, "prompt": "Hello world", "include": []},
|
||||
key=allowed_key,
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
payload: Final = response.json()
|
||||
assert payload["model"] == "acme/model"
|
||||
assert payload["count"] == 2
|
||||
assert payload["token_ids"] is None
|
||||
assert payload["tokens"] is None
|
||||
assert float(response.headers["x-litellm-response-cost"]) == 0
|
||||
assert response.headers["x-litellm-rust"] == "true"
|
||||
assert len(wire.drain()) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/tokenize", "/v1/tokenize"])
|
||||
@pytest.mark.parametrize(
|
||||
("include", "has_token_ids"),
|
||||
[([], False), (["token_ids"], True)],
|
||||
ids=["count-only", "token-ids"],
|
||||
)
|
||||
def test_tokenization_http_hooks_rewrite_and_replace_once(
|
||||
tmp_path: Path,
|
||||
path: str,
|
||||
include: list[str],
|
||||
has_token_ids: bool,
|
||||
) -> None:
|
||||
config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
|
||||
config["litellm_settings"]["callbacks"] = ["integration._support.tokenize_hook_probe.probe"]
|
||||
config_path: Final = tmp_path / "tokenize-hooks.yaml"
|
||||
config_path.write_text(yaml.safe_dump(config))
|
||||
|
||||
def tokenize_upstream(request: Request) -> Reply:
|
||||
assert (request.method, request.target) == ("POST", "/tokenize")
|
||||
assert request.headers["authorization"] == "Bearer deployment-token"
|
||||
body: Final = json.loads(request.body)
|
||||
assert body["model"] == "acme/model"
|
||||
assert body["prompt"] == "rewritten by tokenization hook"
|
||||
return Reply(body=json.dumps({"count": 3, "tokens": [101, 102, 103], "max_model_len": 4096}).encode())
|
||||
|
||||
marker: Final = f"tokenize-hook-{'-'.join(include) or 'count-only'}"
|
||||
with (
|
||||
wire_server(tokenize_upstream) as upstream,
|
||||
wire_server(lambda _: Reply()) as hook_sink,
|
||||
httpx.Client(base_url="http://127.0.0.1:1", trust_env=False) as base_client,
|
||||
):
|
||||
base_gateway: Final = Gateway(base_client, "sk-integration-tokenize", upstream.url)
|
||||
with (
|
||||
owned_proxy(
|
||||
base_gateway,
|
||||
tmp_path,
|
||||
{"TOKENIZE_HOOK_PROBE_URL": hook_sink.url, "STORE_MODEL_IN_DB": "False"},
|
||||
config=config_path,
|
||||
state=OwnedState.PRIVATE,
|
||||
) as proxy,
|
||||
proxy.scenario() as scenario,
|
||||
):
|
||||
model: Final = scenario.model(
|
||||
model="hosted_vllm/acme/model",
|
||||
api_base=upstream.url,
|
||||
api_key="deployment-token",
|
||||
)
|
||||
key: Final = scenario.key(models=[model], user_id="tokenize-hook-user")
|
||||
response: Final = proxy.request(
|
||||
"POST",
|
||||
path,
|
||||
{
|
||||
"model": model,
|
||||
"prompt": "original prompt",
|
||||
"include": include,
|
||||
"user": "tokenize-hook-user",
|
||||
"metadata": {"request_marker": marker},
|
||||
},
|
||||
key=key,
|
||||
headers={"x-request-id": marker},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
assert int(response.headers["content-length"]) == len(response.content)
|
||||
payload: Final = object_value(response.json())
|
||||
assert payload["model"] == "hook-replaced-model"
|
||||
assert payload["count"] == 777
|
||||
assert float(response.headers["x-litellm-response-cost"]) == 0
|
||||
assert response.headers["x-litellm-rust"] == "true"
|
||||
events: Final = tuple(json.loads(request.body) for request in hook_sink.drain())
|
||||
assert tuple(event["stage"] for event in events) == ("pre", "post")
|
||||
assert events[0]["call_id"]
|
||||
assert events[0]["call_id"] == events[1]["call_id"]
|
||||
assert events[0]["call_type"] == "atokenize"
|
||||
assert events[0]["prompt"] == "rewritten by tokenization hook"
|
||||
assert events[1]["call_id"] == response.headers["x-litellm-call-id"]
|
||||
assert events[1]["user_id"] == "tokenize-hook-user"
|
||||
assert events[1]["user"] == "tokenize-hook-user"
|
||||
assert marker in json.dumps(events[1]["metadata"])
|
||||
assert payload["token_ids"] == events[1]["token_ids"]
|
||||
assert payload["tokens"] == events[1]["tokens"]
|
||||
assert events[1]["count"] == 3
|
||||
assert events[1]["model"] == "acme/model"
|
||||
assert events[1]["hidden_params"]["x-litellm-rust"] is True
|
||||
assert events[1]["hidden_params"]["response_cost"] == 0
|
||||
if not has_token_ids:
|
||||
assert events[1]["token_ids"] is None
|
||||
assert events[1]["tokens"] is None
|
||||
else:
|
||||
assert events[1]["token_ids"] is not None
|
||||
assert events[1]["tokens"] is None
|
||||
recorded: Final = upstream.drain()
|
||||
assert len(recorded) == 1
|
||||
assert int(recorded[0].headers["content-length"]) == len(recorded[0].body)
|
||||
|
||||
|
||||
def test_tokenization_proxy_rejects_caller_resources_with_deployment_credentials(tmp_path: Path) -> None:
|
||||
config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
|
||||
|
||||
def watsonx_upstream(request: Request) -> Reply:
|
||||
assert request.method == "POST"
|
||||
assert request.target.startswith("/ml/v1/text/tokenization?")
|
||||
body: Final = json.loads(request.body)
|
||||
assert body["project_id"] == "deployment-project"
|
||||
return Reply(body=json.dumps({"result": {"token_count": 2, "tokens": ["Hello", " world"]}}).encode())
|
||||
|
||||
with (
|
||||
wire_server(watsonx_upstream) as upstream,
|
||||
httpx.Client(base_url="http://127.0.0.1:1", trust_env=False) as base_client,
|
||||
):
|
||||
config["model_list"] = [
|
||||
{
|
||||
"model_name": "watsonx-tokenize",
|
||||
"litellm_params": {
|
||||
"model": "watsonx/ibm/granite-3-8b-instruct",
|
||||
"api_base": upstream.url,
|
||||
"token": "deployment-token",
|
||||
"project_id": "deployment-project",
|
||||
"api_version": "2023-05-29",
|
||||
"configurable_clientside_auth_params": ["project_id", "api_version"],
|
||||
},
|
||||
}
|
||||
]
|
||||
config_path: Final = tmp_path / "tokenize-auth.yaml"
|
||||
config_path.write_text(yaml.safe_dump(config))
|
||||
base_gateway: Final = Gateway(base_client, "sk-integration-tokenize", upstream.url)
|
||||
with owned_proxy(
|
||||
base_gateway,
|
||||
tmp_path,
|
||||
{"STORE_MODEL_IN_DB": "False"},
|
||||
config=config_path,
|
||||
state=OwnedState.PRIVATE,
|
||||
) as proxy:
|
||||
rejected: Final = tuple(
|
||||
proxy.request("POST", "/tokenize", {"model": "watsonx-tokenize", "prompt": "Hello world", field: value})
|
||||
for field, value in (("project_id", "caller-project"), ("api_version", "2025-01-01"))
|
||||
)
|
||||
assert [response.status_code for response in rejected] == [400, 400], [r.text for r in rejected]
|
||||
assert upstream.drain() == ()
|
||||
accepted: Final = proxy.request(
|
||||
"POST",
|
||||
"/tokenize",
|
||||
{"model": "watsonx-tokenize", "prompt": "Hello world", "metadata": {"source": "web"}},
|
||||
)
|
||||
assert accepted.status_code == 200, accepted.text
|
||||
assert len(upstream.drain()) == 1
|
||||
|
|
@ -357,6 +357,10 @@ async def test_unknown_invocation_target_leaves_billing_unset(monkeypatch: pytes
|
|||
("/v1/agents", "POST", False),
|
||||
("/v1/chat/completions", "POST", True),
|
||||
("/v1/chat/completions", "DELETE", False),
|
||||
("/tokenize", "POST", True),
|
||||
("/v1/tokenize", "POST", True),
|
||||
("/tokenize", "GET", False),
|
||||
("/v1/tokenize", "DELETE", False),
|
||||
("/openai/deployments/model/chat/completions", "POST", True),
|
||||
("/engines/openai/model/chat/completions", "POST", True),
|
||||
("/openai/deployments/openai/model/images/generations", "POST", True),
|
||||
|
|
@ -390,6 +394,8 @@ def test_managed_route_scope_excludes_provider_resources(route: str, method: str
|
|||
"route,body,settings,cli_model,path_model,expected",
|
||||
[
|
||||
("/v1/chat/completions", {"model": "body"}, {"completion_model": "default"}, "cli", "path", "default"),
|
||||
("/tokenize", {"model": "body"}, {"completion_model": "default"}, "cli", None, "default"),
|
||||
("/v1/tokenize", {"model": "body"}, {}, "cli", None, "cli"),
|
||||
("/v1/moderations", {"model": "body"}, {"moderation_model": "default"}, "cli", None, "cli"),
|
||||
("/v1/audio/speech", {"model": "body"}, {"completion_model": "ignored"}, None, None, "body"),
|
||||
("/openai/deployments/path/embeddings", {"model": "body"}, {}, None, "path", "path"),
|
||||
|
|
|
|||
|
|
@ -66,12 +66,12 @@ if _REPO_ROOT not in sys.path:
|
|||
|
||||
from backend.routes.allowlist import BACKEND_MOUNT_PATHS
|
||||
from gateway.routes.allowlist import GATEWAY_MOUNT_PATHS
|
||||
from litellm.integrations.prometheus_metrics_endpoint import make_metrics_asgi_app
|
||||
from litellm.proxy import tracing_endpoints
|
||||
from litellm.proxy._lazy_features import LazyFeature, attach_lazy_features
|
||||
from litellm.proxy.auth.authorization_dependencies import get_log_team_lookup
|
||||
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
|
||||
from litellm.proxy.proxy_server import app
|
||||
from litellm.integrations.prometheus_metrics_endpoint import make_metrics_asgi_app
|
||||
from tests.test_litellm_rust.support.child_interpreter import run_child_interpreter
|
||||
|
||||
for _key, _previous in _PRE_EXISTING_ENV.items():
|
||||
|
|
@ -291,6 +291,12 @@ def test_gateway_plus_backend_covers_full_app():
|
|||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ("/tokenize", "/v1/tokenize"))
|
||||
def test_gateway_keeps_tokenization_routes(path: str) -> None:
|
||||
route: Final = next(route for route in app.router.routes if getattr(route, "path", None) == path)
|
||||
assert _is_gateway_route(route)
|
||||
|
||||
|
||||
def test_backend_mount_paths_defined():
|
||||
"""BACKEND_MOUNT_PATHS constant must exist and be a frozenset."""
|
||||
assert isinstance(BACKEND_MOUNT_PATHS, frozenset), \
|
||||
|
|
|
|||
0
tests/unit/proxy/tokenize_endpoints/__init__.py
Normal file
0
tests/unit/proxy/tokenize_endpoints/__init__.py
Normal file
276
tests/unit/proxy/tokenize_endpoints/test_contract.py
Normal file
276
tests/unit/proxy/tokenize_endpoints/test_contract.py
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
from typing import Final, Literal, TypedDict
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import TypeAdapter, ValidationError
|
||||
from typing_extensions import ReadOnly
|
||||
|
||||
from litellm.cost_calculator import response_cost_calculator
|
||||
from litellm.proxy._types import ProxyException
|
||||
from litellm.proxy.auth.route_checks import RouteChecks
|
||||
from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth
|
||||
from litellm.proxy.route_llm_request import ProxyMissingRequiredParamError, raise_if_required_body_param_missing
|
||||
from litellm.proxy.tokenize_endpoints.endpoints import router
|
||||
from litellm.tokenize.routing import TokenizeAdmissionContext, deployment_kwargs, deployment_params, source_for
|
||||
from litellm.types.tokenize import TokenizeRequest, TokenizeResponse
|
||||
|
||||
|
||||
class _LocatedError(TypedDict):
|
||||
loc: ReadOnly[tuple[str | int, ...]]
|
||||
|
||||
|
||||
_VALIDATION_ERRORS: Final = TypeAdapter(dict[str, tuple[_LocatedError, ...]])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["/tokenize", "/v1/tokenize"])
|
||||
def test_tokenization_uses_inference_authorization_without_generation_billing(route: str) -> None:
|
||||
assert RouteChecks.is_llm_api_route(route)
|
||||
assert RouteChecks.is_unbilled_route(route)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("call_type", ["tokenize", "atokenize"])
|
||||
def test_tokenization_count_is_not_billed_as_generated_tokens(call_type: Literal["tokenize", "atokenize"]) -> None:
|
||||
response: Final = TokenizeResponse(model="acme/model", count=1000, token_ids=[1])
|
||||
assert (
|
||||
response_cost_calculator(
|
||||
response_object=response,
|
||||
model=response.model,
|
||||
custom_llm_provider="hosted_vllm",
|
||||
call_type=call_type,
|
||||
optional_params={},
|
||||
)
|
||||
== 0
|
||||
)
|
||||
|
||||
|
||||
def test_missing_prompt_fails_before_routing() -> None:
|
||||
with pytest.raises(ProxyMissingRequiredParamError):
|
||||
raise_if_required_body_param_missing(route_type="atokenize", data={"model": "tokenizer"}, llm_router=None)
|
||||
|
||||
|
||||
def test_empty_prompt_is_valid() -> None:
|
||||
request: Final = TokenizeRequest(model="tokenizer", prompt="")
|
||||
assert request.prompt == ""
|
||||
assert request.include is None
|
||||
assert request.model_dump(mode="json", exclude_unset=True) == {"model": "tokenizer", "prompt": ""}
|
||||
assert request.add_special_tokens is None
|
||||
|
||||
|
||||
def test_tokenize_request_schema_matches_runtime_contract() -> None:
|
||||
schema: Final = TokenizeRequest.model_json_schema()
|
||||
assert schema["properties"]["include"]["type"] == "array"
|
||||
assert schema["properties"]["include"]["uniqueItems"] is True
|
||||
assert "anyOf" not in schema["properties"]["include"]
|
||||
assert "include" not in schema["required"]
|
||||
assert schema["properties"]["add_special_tokens"]["type"] == "boolean"
|
||||
assert "default" not in schema["properties"]["add_special_tokens"]
|
||||
assert "add_special_tokens" not in schema["required"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("include", "expected"),
|
||||
[
|
||||
([], ()),
|
||||
(["token_ids"], ("token_ids",)),
|
||||
(["tokens"], ("tokens",)),
|
||||
(["token_ids", "tokens"], ("token_ids", "tokens")),
|
||||
],
|
||||
ids=["count-only", "token-ids", "tokens", "both"],
|
||||
)
|
||||
def test_tokenize_request_normalizes_include_arrays_and_serializes_them(
|
||||
include: list[str], expected: tuple[str, ...]
|
||||
) -> None:
|
||||
request: Final = TokenizeRequest.model_validate({"model": "tokenizer", "prompt": "", "include": include})
|
||||
assert request.include == expected
|
||||
assert request.model_dump(mode="json")["include"] == include
|
||||
|
||||
|
||||
def test_tokenize_request_rejects_unknown_fields_as_extra_forbidden() -> None:
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
TokenizeRequest.model_validate({"model": "tokenizer", "prompt": "", "unsupported_option": True})
|
||||
assert caught.value.errors()[0]["type"] == "extra_forbidden"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"include",
|
||||
[None, "token_ids", ["unknown"], ["tokens", "tokens"], ["token_ids", None]],
|
||||
ids=["null", "scalar", "unknown-entry", "duplicate", "null-entry"],
|
||||
)
|
||||
def test_include_accepts_only_unique_supported_representations(include: object) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
TokenizeRequest.model_validate({"model": "tokenizer", "prompt": "", "include": include})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("add_special_tokens", [None, 1, "true"], ids=["null", "integer", "string"])
|
||||
def test_explicit_add_special_tokens_requires_boolean(add_special_tokens: object) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
TokenizeRequest.model_validate({"model": "tokenizer", "prompt": "", "add_special_tokens": add_special_tokens})
|
||||
|
||||
|
||||
def test_provider_validation_receives_optional_options_without_callback_objects() -> None:
|
||||
from litellm.rust_bridge.host.routes.tokenize import body_params
|
||||
|
||||
assert body_params(
|
||||
{
|
||||
"model": "hosted_vllm/acme/model",
|
||||
"prompt": "hello",
|
||||
"metadata": {"opaque": object()},
|
||||
"timeout": 5,
|
||||
"extra_headers": {"x-user": "test"},
|
||||
"headers": {"x-forwarded": "client"},
|
||||
"client_side_timeout": True,
|
||||
"unknown_option": True,
|
||||
"api_version": "2024-03-13",
|
||||
"include": ["token_ids"],
|
||||
"add_special_tokens": False,
|
||||
}
|
||||
) == {"unknown_option": True, "api_version": "2024-03-13"}
|
||||
|
||||
|
||||
def test_provider_validation_keeps_optional_params_but_drops_callback_metadata() -> None:
|
||||
from litellm.rust_bridge.host.routes.tokenize import body_params
|
||||
|
||||
assert body_params(
|
||||
{
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 128,
|
||||
"user": "proxy-user",
|
||||
"metadata": {"opaque": object()},
|
||||
"include": ["token_ids"],
|
||||
"add_special_tokens": False,
|
||||
"_tokenize_context": object(),
|
||||
}
|
||||
) == {"temperature": 0.7, "max_tokens": 128}
|
||||
|
||||
|
||||
def test_router_deployment_defaults_are_separate_from_request_provenance() -> None:
|
||||
from litellm.rust_bridge.host.routes.tokenize import body_params
|
||||
|
||||
deployment: Final = {
|
||||
"model": "hosted_vllm/acme/model",
|
||||
"api_base": "http://deployment",
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 128,
|
||||
"extra_body": {"deployment_option": True},
|
||||
"add_special_tokens": False,
|
||||
}
|
||||
effective_request: Final = {
|
||||
**deployment,
|
||||
"base_url": "http://deployment",
|
||||
}
|
||||
routed: Final = deployment_kwargs(
|
||||
deployment,
|
||||
effective_request,
|
||||
caller_fields=frozenset({"model", "base_url"}),
|
||||
)
|
||||
assert "temperature" not in routed
|
||||
assert "max_tokens" not in routed
|
||||
assert "extra_body" not in routed
|
||||
assert routed["add_special_tokens"] is False
|
||||
assert "add_special_tokens" not in body_params(routed)
|
||||
assert deployment_params(routed) == {
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 128,
|
||||
"extra_body": {"deployment_option": True},
|
||||
}
|
||||
assert source_for(routed, "add_special_tokens") == "deployment"
|
||||
assert source_for(routed, "api_base") == "request"
|
||||
|
||||
|
||||
def test_router_keeps_caller_option_request_sourced_when_equal_to_default() -> None:
|
||||
deployment: Final = {"model": "hosted_vllm/acme/model", "temperature": 0.7}
|
||||
request: Final = {"model": "hosted_vllm/acme/model", "temperature": 0.7}
|
||||
routed: Final = deployment_kwargs(
|
||||
deployment,
|
||||
request,
|
||||
caller_fields=frozenset({"model", "temperature"}),
|
||||
)
|
||||
assert routed["temperature"] == deployment["temperature"]
|
||||
assert source_for(routed, "temperature") == "request"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
app: Final = FastAPI()
|
||||
app.include_router(router)
|
||||
app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth()
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
b"null",
|
||||
b"[]",
|
||||
b'"hello"',
|
||||
b'{"model":"tokenizer"}',
|
||||
b'{"prompt":"hello"}',
|
||||
b'{"model":"tokenizer","prompt":[]}',
|
||||
b'{"model":3,"prompt":"hello"}',
|
||||
b'{"model":"","prompt":""}',
|
||||
b'{"model":"tokenizer","prompt":"hello","include":null}',
|
||||
b'{"model":"tokenizer","prompt":"hello","include":["unsupported"]}',
|
||||
b'{"model":"tokenizer","prompt":"hello","include":["tokens","tokens"]}',
|
||||
b'{"model":"tokenizer","prompt":"hello","add_special_tokens":null}',
|
||||
b'{"model":"tokenizer","prompt":"hello","_tokenize_context":{}}',
|
||||
b'{"model":"tokenizer","prompt":"hello","_tokenize_trusted":true}',
|
||||
],
|
||||
ids=[
|
||||
"null",
|
||||
"array",
|
||||
"string",
|
||||
"missing-prompt",
|
||||
"missing-model",
|
||||
"prompt-array",
|
||||
"model-number",
|
||||
"empty-model",
|
||||
"include-null",
|
||||
"include-unknown",
|
||||
"include-duplicate",
|
||||
"special-tokens-null",
|
||||
"forged-tokenize-context",
|
||||
"reserved-internal-field",
|
||||
],
|
||||
)
|
||||
def test_malformed_tokenize_body_returns_client_error(client: TestClient, body: bytes) -> None:
|
||||
response: Final = client.post("/tokenize", content=body, headers={"content-type": "application/json"})
|
||||
assert response.status_code == 422
|
||||
assert all(error["loc"][0] == "body" for error in _VALIDATION_ERRORS.validate_json(response.content)["detail"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["/tokenize", "/v1/tokenize"])
|
||||
@pytest.mark.parametrize(
|
||||
"extra",
|
||||
[{}, {"metadata": {"source": "web", "nested": [{"backend": "local"}]}}],
|
||||
ids=["minimal", "metadata-with-reserved-looking-keys"],
|
||||
)
|
||||
def test_valid_body_reaches_proxy_model_routing(client: TestClient, route: str, extra: dict[str, object]) -> None:
|
||||
with pytest.raises(ProxyException) as caught:
|
||||
client.post(route, json={"model": "unconfigured-tokenizer", "prompt": "Hello", **extra})
|
||||
assert caught.value.code == "400"
|
||||
assert caught.value.message == (
|
||||
"/tokenize: Invalid model name passed in model=unconfigured-tokenizer. "
|
||||
"Call `/v1/models` to view available models for your key."
|
||||
)
|
||||
|
||||
|
||||
def test_proxy_caller_fields_stay_request_sourced_even_when_deployment_allows_them() -> None:
|
||||
admitted: Final = {
|
||||
"model": "hosted_vllm/acme/model",
|
||||
"api_base": "http://caller",
|
||||
"_tokenize_context": TokenizeAdmissionContext(),
|
||||
}
|
||||
assert source_for(admitted, "api_base") == "request"
|
||||
routed: Final = deployment_kwargs(
|
||||
{
|
||||
"model": "hosted_vllm/acme/model",
|
||||
"api_base": "http://deployment",
|
||||
"api_key": "deployment-key",
|
||||
"configurable_clientside_auth_params": ["api_base"],
|
||||
},
|
||||
admitted,
|
||||
caller_fields=frozenset(admitted),
|
||||
)
|
||||
assert source_for(routed, "api_base") == "request"
|
||||
assert source_for(routed, "api_key") == "deployment"
|
||||
130
ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
130
ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
|
|
@ -17922,6 +17922,26 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/tokenize": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Tokenize
|
||||
* @description Tokenize raw text and return its count with explicitly requested representations.
|
||||
*/
|
||||
post: operations["tokenize_tokenize_post"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/toolset/{toolset_name}/mcp": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -22439,6 +22459,26 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/v1/tokenize": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Tokenize
|
||||
* @description Tokenize raw text and return its count with explicitly requested representations.
|
||||
*/
|
||||
post: operations["tokenize_v1_tokenize_post"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/v1/tool/list": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -41926,6 +41966,19 @@ export interface components {
|
|||
*/
|
||||
user: string | null;
|
||||
};
|
||||
/** ProxyTokenizeRequest */
|
||||
ProxyTokenizeRequest: {
|
||||
/** Add Special Tokens */
|
||||
add_special_tokens?: boolean;
|
||||
/** Include */
|
||||
include?: ("token_ids" | "tokens")[];
|
||||
/** Model */
|
||||
model: string;
|
||||
/** Prompt */
|
||||
prompt: string;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/** PublicModelHubInfo */
|
||||
PublicModelHubInfo: {
|
||||
/** Custom Docs Description */
|
||||
|
|
@ -47167,6 +47220,17 @@ export interface components {
|
|||
/** Total Tokens */
|
||||
total_tokens: number;
|
||||
};
|
||||
/** TokenizeResponse */
|
||||
TokenizeResponse: {
|
||||
/** Count */
|
||||
count: number;
|
||||
/** Model */
|
||||
model: string;
|
||||
/** Token Ids */
|
||||
token_ids?: number[] | null;
|
||||
/** Tokens */
|
||||
tokens?: string[] | null;
|
||||
};
|
||||
/**
|
||||
* ToolChoiceAllowedParam
|
||||
* @description Constrains the tools available to the model to a pre-defined set.
|
||||
|
|
@ -74917,6 +74981,39 @@ export interface operations {
|
|||
};
|
||||
};
|
||||
};
|
||||
tokenize_tokenize_post: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["ProxyTokenizeRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description Successful Response */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["TokenizeResponse"];
|
||||
};
|
||||
};
|
||||
/** @description Validation Error */
|
||||
422: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["HTTPValidationError"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
toolset_mcp_route_toolset__toolset_name__mcp_get: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -81900,6 +81997,39 @@ export interface operations {
|
|||
};
|
||||
};
|
||||
};
|
||||
tokenize_v1_tokenize_post: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["ProxyTokenizeRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description Successful Response */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["TokenizeResponse"];
|
||||
};
|
||||
};
|
||||
/** @description Validation Error */
|
||||
422: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["HTTPValidationError"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
list_tools_v1_tool_list_get: {
|
||||
parameters: {
|
||||
query?: {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue