From 0d801eed1621dfd5a9c0f8b0eb46fc6e7e84b1f3 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Mon, 16 Nov 2026 03:19:07 -0500 Subject: [PATCH 01/14] Add workload identity federation credentials WorkloadIdentityCredentials and AsyncWorkloadIdentityCredentials exchange an identity provider's JWT for a short-lived Baseten access token under a trust rule (RFC 8693 token exchange at POST /v1/auth/token), cache it, and replace it before it expires. The management and inference clients accept them, or any AccessTokenSource, as `credentials` in place of `api_key`, send the token only to their own API host, and resend a request whose token is refused when the source can drop it. The token cache and the resend-on-refusal auth move from the sandbox package into baseten.client._token_auth, which the sandbox token source now uses too. Refusal also covers a 401 whose WWW-Authenticate names error="invalid_token", and the refresh margin is capped at half a token's lifetime. Co-Authored-By: Claude Opus 5.5 --- README.md | 17 + baseten/client/__init__.py | 27 ++ baseten/client/_inference.py | 60 +++- baseten/client/_management.py | 68 +++- baseten/client/_token_auth.py | 417 +++++++++++++++++++++++ baseten/client/_workload_identity.py | 339 +++++++++++++++++++ baseten/sandbox/_auth.py | 216 +++--------- tests/client/test_token_auth.py | 200 +++++++++++ tests/client/test_workload_identity.py | 448 +++++++++++++++++++++++++ tests/sandbox/test_auth.py | 27 +- 10 files changed, 1628 insertions(+), 191 deletions(-) create mode 100644 baseten/client/_token_auth.py create mode 100644 baseten/client/_workload_identity.py create mode 100644 tests/client/test_token_auth.py create mode 100644 tests/client/test_workload_identity.py diff --git a/README.md b/README.md index d2699eb..03d3c17 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,23 @@ async with AsyncManagementClient(api_key="my-api-key") as client: print(model.name) ``` +### Authenticating with workload identity federation + +Instead of an API key, a workload can exchange its identity provider's token (for example a projected Kubernetes service account token) for a short-lived Baseten access token under a trust rule. The credentials exchange on first use, cache the access token, and replace it before it expires: + +```python +from baseten.client import ManagementClient, WorkloadIdentityCredentials + +credentials = WorkloadIdentityCredentials( + trust_rule_id="my-trust-rule-id", + identity_token_file="/var/run/secrets/tokens/baseten", +) +with ManagementClient(credentials=credentials) as client: + ... +``` + +`AsyncWorkloadIdentityCredentials` is the same for async clients. + ## Sandboxes `baseten.sandbox` creates and works with sandboxes. HTTP/2 is used when the `h2` package is installed, which is strongly recommended: diff --git a/baseten/client/__init__.py b/baseten/client/__init__.py index a866705..d11d643 100644 --- a/baseten/client/__init__.py +++ b/baseten/client/__init__.py @@ -5,6 +5,9 @@ for the inference API. :class:`SandboxClient` and :class:`AsyncSandboxClient` reach one sandbox's execution API directly; the higher-level surface lives in :mod:`baseten.sandbox`. + +To authenticate without an API key, pass :class:`WorkloadIdentityCredentials` +or :class:`AsyncWorkloadIdentityCredentials` as a client's ``credentials``. """ from baseten.client._inference import ( @@ -22,15 +25,39 @@ SandboxClient, SandboxClientOptions, ) +from baseten.client._token_auth import ( + AccessToken, + AccessTokenInvalidator, + AccessTokenSource, + AsyncAccessTokenSource, +) +from baseten.client._workload_identity import ( + AsyncIdentityTokenProvider, + AsyncWorkloadIdentityCredentials, + IdentityTokenProvider, + InvalidGrantError, + WorkloadIdentityCredentials, + WorkloadIdentityError, +) __all__ = [ + "AccessToken", + "AccessTokenInvalidator", + "AccessTokenSource", + "AsyncAccessTokenSource", + "AsyncIdentityTokenProvider", "AsyncInferenceClient", "AsyncManagementClient", "AsyncSandboxClient", + "AsyncWorkloadIdentityCredentials", + "IdentityTokenProvider", "InferenceClient", "InferenceClientOptions", + "InvalidGrantError", "ManagementClient", "ManagementClientOptions", "SandboxClient", "SandboxClientOptions", + "WorkloadIdentityCredentials", + "WorkloadIdentityError", ] diff --git a/baseten/client/_inference.py b/baseten/client/_inference.py index 4f87a2b..2bc5768 100644 --- a/baseten/client/_inference.py +++ b/baseten/client/_inference.py @@ -7,6 +7,13 @@ import httpx import baseten.client.inferenceapi +from baseten.client._token_auth import ( + AccessTokenSource, + AsyncAccessTokenSource, + async_credentials_auth, + check_client_auth, + credentials_auth, +) from baseten.client._user_agent import with_user_agent @@ -18,8 +25,8 @@ class InferenceClientOptions: was constructed with. """ - api_key: str - """API key for authentication.""" + api_key: str | None + """API key for authentication, or ``None`` when *credentials* is set.""" headers: Mapping[str, str] | None = None """Additional headers to send on every request.""" @@ -37,6 +44,9 @@ class InferenceClientOptions: """Explicit base URL override. When set, *model_id*, *chain_id*, and *environment* are ignored.""" + credentials: AccessTokenSource | AsyncAccessTokenSource | None = None + """Source of short-lived access tokens, used in place of *api_key*.""" + @property def base_url(self) -> str: """The resolved base URL for the inference API.""" @@ -88,7 +98,8 @@ def default_base_url( def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: AccessTokenSource | None = None, headers: Mapping[str, str] | None = None, model_id: str | None = None, chain_id: str | None = None, @@ -100,7 +111,14 @@ def __init__( """Create a new synchronous inference client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Source of short-lived access tokens in place of an + API key, such as :class:`WorkloadIdentityCredentials`. A token + is fetched for every request, so a long-lived client picks up + refreshed tokens. It is sent only to this client's API host, + and a request whose token Baseten refuses is sent again with a + new one when the source can drop the refused token. headers: Additional headers to send on every request. model_id: Model ID. Mutually exclusive with *chain_id*. chain_id: Chain ID. Mutually exclusive with *model_id*. @@ -115,6 +133,7 @@ def __init__( client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = InferenceClientOptions( api_key=api_key, headers=headers, @@ -122,17 +141,24 @@ def __init__( chain_id=chain_id, environment=environment, base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else credentials_auth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.Client( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -146,7 +172,7 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.inferenceapi.ApiClient(self._http_client) + self._api = baseten.client.inferenceapi.ApiClient(self._http_client, auth=auth) @property def options(self) -> InferenceClientOptions: @@ -205,7 +231,8 @@ def default_base_url( def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: AsyncAccessTokenSource | None = None, headers: Mapping[str, str] | None = None, model_id: str | None = None, chain_id: str | None = None, @@ -217,7 +244,10 @@ def __init__( """Create a new asynchronous inference client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Source of short-lived access tokens, as for + :class:`InferenceClient`. headers: Additional headers to send on every request. model_id: Model ID. Mutually exclusive with *chain_id*. chain_id: Chain ID. Mutually exclusive with *model_id*. @@ -232,6 +262,7 @@ def __init__( client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = InferenceClientOptions( api_key=api_key, headers=headers, @@ -239,17 +270,24 @@ def __init__( chain_id=chain_id, environment=environment, base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else async_credentials_auth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.AsyncClient( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -263,7 +301,9 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.inferenceapi.AsyncApiClient(self._http_client) + self._api = baseten.client.inferenceapi.AsyncApiClient( + self._http_client, auth=auth + ) @property def options(self) -> InferenceClientOptions: diff --git a/baseten/client/_management.py b/baseten/client/_management.py index 85dcda2..27994be 100644 --- a/baseten/client/_management.py +++ b/baseten/client/_management.py @@ -7,6 +7,13 @@ import httpx import baseten.client.managementapi +from baseten.client._token_auth import ( + AccessTokenSource, + AsyncAccessTokenSource, + async_credentials_auth, + check_client_auth, + credentials_auth, +) from baseten.client._user_agent import with_user_agent @@ -18,8 +25,8 @@ class ManagementClientOptions: was constructed with. """ - api_key: str - """API key for authentication.""" + api_key: str | None + """API key for authentication, or ``None`` when *credentials* is set.""" headers: Mapping[str, str] | None = None """Additional headers to send on every request.""" @@ -27,6 +34,9 @@ class ManagementClientOptions: base_url_override: str | None = None """Explicit base URL override, or ``None`` to use the default.""" + credentials: AccessTokenSource | AsyncAccessTokenSource | None = None + """Source of short-lived access tokens, used in place of *api_key*.""" + @property def base_url(self) -> str: """The resolved base URL for the management API.""" @@ -50,7 +60,8 @@ def default_base_url(cls) -> str: def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: AccessTokenSource | None = None, headers: Mapping[str, str] | None = None, base_url_override: str | None = None, http_client_override: httpx.Client | None = None, @@ -59,7 +70,14 @@ def __init__( """Create a new synchronous management client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Source of short-lived access tokens in place of an + API key, such as :class:`WorkloadIdentityCredentials`. A token + is fetched for every request, so a long-lived client picks up + refreshed tokens. It is sent only to this client's API host, + and a request whose token Baseten refuses is sent again with a + new one when the source can drop the refused token. headers: Additional headers to send on every request. base_url_override: Override the default base URL. When ``None``, :meth:`default_base_url` is used. @@ -71,19 +89,29 @@ def __init__( client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = ManagementClientOptions( - api_key=api_key, headers=headers, base_url_override=base_url_override + api_key=api_key, + headers=headers, + base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else credentials_auth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.Client( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -97,7 +125,7 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.managementapi.ApiClient(self._http_client) + self._api = baseten.client.managementapi.ApiClient(self._http_client, auth=auth) @property def options(self) -> ManagementClientOptions: @@ -145,7 +173,8 @@ def default_base_url(cls) -> str: def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: AsyncAccessTokenSource | None = None, headers: Mapping[str, str] | None = None, base_url_override: str | None = None, http_client_override: httpx.AsyncClient | None = None, @@ -154,7 +183,10 @@ def __init__( """Create a new asynchronous management client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Source of short-lived access tokens, as for + :class:`ManagementClient`. headers: Additional headers to send on every request. base_url_override: Override the default base URL. When ``None``, :meth:`default_base_url` is used. @@ -166,19 +198,29 @@ def __init__( client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = ManagementClientOptions( - api_key=api_key, headers=headers, base_url_override=base_url_override + api_key=api_key, + headers=headers, + base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else async_credentials_auth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.AsyncClient( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -192,7 +234,9 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.managementapi.AsyncApiClient(self._http_client) + self._api = baseten.client.managementapi.AsyncApiClient( + self._http_client, auth=auth + ) @property def options(self) -> ManagementClientOptions: diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py new file mode 100644 index 0000000..602a624 --- /dev/null +++ b/baseten/client/_token_auth.py @@ -0,0 +1,417 @@ +"""What every short-lived Baseten token needs. + +A cache that mints a new token shortly before the current one expires, and an +:class:`httpx.Auth` that sends a request again with a new token when the server +refuses the current one. +""" + +from __future__ import annotations + +import asyncio +import inspect +import threading +import time +from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapping +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from typing import Protocol, runtime_checkable + +import httpx + + +@dataclass(frozen=True) +class AccessToken: + """A short-lived Baseten access token, sent as ``Authorization: Bearer``.""" + + token: str + """The bearer token.""" + + expires_at: datetime + """When the token expires.""" + + +@runtime_checkable +class AccessTokenSource(Protocol): + """Supplies a current access token. + + A client configured with one calls it before every request, so the source + decides when to refresh. + """ + + def access_token(self) -> AccessToken: + """Return a current access token.""" + ... + + +@runtime_checkable +class AsyncAccessTokenSource(Protocol): + """Async form of :class:`AccessTokenSource`.""" + + async def access_token(self) -> AccessToken: + """Return a current access token.""" + ... + + +@runtime_checkable +class AccessTokenInvalidator(Protocol): + """Implemented by an access token source that caches tokens. + + When Baseten refuses a token before it expires, for example because it was + revoked, a client drops it with :meth:`invalidate_access_token`, asks the + source for a new one, and sends the request again. Clients resend only for + sources that implement this. + """ + + def invalidate_access_token(self, token: str) -> None: + """Drop *token* if it is still the cached one.""" + ... + + +def _utc_now() -> datetime: + return datetime.now(UTC) + + +@dataclass(frozen=True) +class _CachedToken: + token: AccessToken + refresh_at: datetime + + +def _cached( + token: AccessToken, *, minted_at: datetime, refresh_before: timedelta +) -> _CachedToken: + """Cache *token* until *refresh_before* its expiry, capped at half its lifetime. + + The cap keeps a token whose lifetime is shorter than the margin from being + minted again on every call. + """ + lifetime = max(token.expires_at - minted_at, timedelta(0)) + return _CachedToken( + token=token, + refresh_at=token.expires_at - min(refresh_before, lifetime / 2), + ) + + +class TokenCache: + """Holds one token and mints a new one when it is due for refresh. + + Safe for use from several threads. Concurrent callers on a cold cache share + one mint. *mint* must bound its own duration, since every waiting caller + waits on it. + """ + + def __init__( + self, + *, + mint: Callable[[], AccessToken], + refresh_before: timedelta, + now: Callable[[], datetime] = _utc_now, + ) -> None: + """Create an empty cache; the first mint happens on first use.""" + self._mint = mint + self._refresh_before = refresh_before + self._now = now + self._lock = threading.Lock() + self._current: _CachedToken | None = None + + def token(self) -> AccessToken: + """Return the cached token, minting one when none is cached or it is due.""" + # Held across the mint, so a burst on a cold cache sends one mint. A + # caller that waited on a failed mint then makes one of its own. + with self._lock: + current = self._current + if current is not None and self._now() < current.refresh_at: + return current.token + minted_at = self._now() + token = self._mint() + self._current = _cached( + token, minted_at=minted_at, refresh_before=self._refresh_before + ) + # Returned even if already due, so a skewed clock cannot make every + # call mint. + return token + + def invalidate(self, token: str) -> None: + """Drop *token* if it is still the cached one.""" + with self._lock: + # Compared by value, so a refusal of an older token never discards + # a newer one another caller already minted. + if self._current is not None and self._current.token.token == token: + self._current = None + + +class AsyncTokenCache: + """Async form of :class:`TokenCache`. + + The shared mint runs as its own task, so one caller being cancelled does + not cancel the mint the others wait on. + """ + + def __init__( + self, + *, + mint: Callable[[], Awaitable[AccessToken]], + refresh_before: timedelta, + now: Callable[[], datetime] = _utc_now, + ) -> None: + """Create an empty cache; the first mint happens on first use.""" + self._mint = mint + self._refresh_before = refresh_before + self._now = now + self._current: _CachedToken | None = None + self._minting: asyncio.Task[_CachedToken] | None = None + + async def token(self) -> AccessToken: + """Return the cached token, as :meth:`TokenCache.token` does.""" + while True: + current = self._current + if current is not None and self._now() < current.refresh_at: + return current.token + started = self._minting is None + if self._minting is None: + self._minting = asyncio.create_task(self._run_mint()) + # Retrieved here so a failure no caller is left to see is not + # reported as never retrieved. + self._minting.add_done_callback( + lambda task: task.cancelled() or task.exception() + ) + try: + minted = await asyncio.shield(self._minting) + except Exception: + # Another caller's failed mint gets one more try of this + # caller's own; the failed one already left the cache. + if started: + raise + continue + # A token this caller just minted is used even if already due, so + # a skewed clock cannot loop here forever. + if started or self._now() < minted.refresh_at: + return minted.token + if self._current is minted: + self._current = None + + def invalidate(self, token: str) -> None: + """Drop *token* if it is still the cached one.""" + # Compared by value, so a refusal of an older token never discards a + # newer one another caller already minted. + if self._current is not None and self._current.token.token == token: + self._current = None + + async def _run_mint(self) -> _CachedToken: + try: + minted_at = self._now() + token = await self._mint() + self._current = _cached( + token, minted_at=minted_at, refresh_before=self._refresh_before + ) + return self._current + finally: + self._minting = None + + +# A few resends cover a new token being invalidated in the same event as the +# old one. Past that, the refusal is returned, since tokens that keep getting +# refused point at something a new token cannot fix. +_MAX_RESENDS = 2 + +# Revocation refuses every token issued before a cutoff, the time of the +# revoking event rounded up to the next whole second. A token minted right +# after the event can fall before the cutoff and be refused too, so after the +# first resend, each one waits this long to be minted past it. A module +# variable so tests can shorten it. +_resend_delay_sec = 1.0 + + +class TokenAuth(httpx.Auth): + """Authenticates requests with ``Authorization: Bearer`` from *get_token*. + + *get_token* is called with ``None``, or with the token the server just + refused, and returns the token to send, or ``None`` to send no + Authorization. When the server refuses the token (see + :func:`is_token_refused`) and the body can be sent again, the request is + resent with a new token, at most twice. + """ + + def __init__( + self, + get_token: Callable[[str | None], str | None], + *, + resend_refused: bool = True, + origin: str | None = None, + ) -> None: + """Create the auth. + + Args: + get_token: Returns the token for a request. + resend_refused: Whether to resend a request whose token was refused. + origin: When set, only requests to this URL's host and port that + carry no Authorization of their own are authenticated, so a + token never reaches another host through a shared HTTP client. + """ + self._get_token = get_token + self._resend_refused = resend_refused + self._origin = None if origin is None else httpx.URL(origin) + + def sync_auth_flow( + self, request: httpx.Request + ) -> Generator[httpx.Request, httpx.Response, None]: + """Send the request, again with a new token if its token was refused.""" + if not _applies_to(request, self._origin): + yield request + return + resend = self._resend_refused and _is_replayable(request) + refused: str | None = None + for attempt in range(_MAX_RESENDS + 1): + token = self._get_token(refused) + _set_authorization(request, token) + response = yield request + if token is None or not resend or not is_token_refused(response): + return + if attempt == _MAX_RESENDS: + return + refused = token + if attempt > 0: + time.sleep(_resend_delay_sec) + + +class AsyncTokenAuth(httpx.Auth): + """Async form of :class:`TokenAuth`.""" + + def __init__( + self, + get_token: Callable[[str | None], Awaitable[str | None]], + *, + resend_refused: bool = True, + origin: str | None = None, + ) -> None: + """Create the auth, as :class:`TokenAuth` does.""" + self._get_token = get_token + self._resend_refused = resend_refused + self._origin = None if origin is None else httpx.URL(origin) + + async def async_auth_flow( + self, request: httpx.Request + ) -> AsyncGenerator[httpx.Request, httpx.Response]: + """Send the request, again with a new token if its token was refused.""" + if not _applies_to(request, self._origin): + yield request + return + resend = self._resend_refused and _is_replayable(request) + refused: str | None = None + for attempt in range(_MAX_RESENDS + 1): + token = await self._get_token(refused) + _set_authorization(request, token) + response = yield request + if token is None or not resend or not is_token_refused(response): + return + if attempt == _MAX_RESENDS: + return + refused = token + if attempt > 0: + await asyncio.sleep(_resend_delay_sec) + + +def is_token_refused(response: httpx.Response) -> bool: + """Report whether the server refused a request's token before its expiry. + + For example after it was revoked. The request was refused before any work + was done, so sending it again with a new token is safe even when it has + side effects. + """ + if response.status_code != 401: + return False + # Sandboxes, and the control plane for sandbox tokens, send this header. + if response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED": + return True + # The RFC 6750 response to a refused access token. + return any( + 'error="invalid_token"' in challenge + for challenge in response.headers.get_list("www-authenticate") + ) + + +def _applies_to(request: httpx.Request, origin: httpx.URL | None) -> bool: + if origin is None: + return True + return ( + request.url.host == origin.host + and request.url.port == origin.port + and "Authorization" not in request.headers + ) + + +def _is_replayable(request: httpx.Request) -> bool: + """Report whether a request's body can be sent again.""" + # A stream body can be read only once, so a request carrying one is never + # sent again. The SDK itself never sends one; only raw API calls can. + return isinstance(request.stream, httpx.ByteStream) + + +def _set_authorization(request: httpx.Request, token: str | None) -> None: + if token is not None: + request.headers["Authorization"] = f"Bearer {token}" + + +def check_client_auth( + *, + api_key: str | None, + credentials: object | None, + headers: Mapping[str, str] | None, +) -> None: + """Check that a client is given exactly one way to authenticate.""" + if api_key is not None and credentials is not None: + raise ValueError("api_key and credentials are mutually exclusive") + if api_key is None and credentials is None: + raise ValueError("one of api_key or credentials is required") + if credentials is not None and any( + key.lower() == "authorization" for key in headers or {} + ): + raise ValueError("headers must not set Authorization when credentials is set") + + +def credentials_auth(credentials: AccessTokenSource, *, origin: str) -> TokenAuth: + """Build the auth that sends *credentials*' token to *origin* only.""" + if inspect.iscoroutinefunction(credentials.access_token): + raise TypeError( + "credentials.access_token is async; use the client's async form" + ) + invalidator = ( + credentials if isinstance(credentials, AccessTokenInvalidator) else None + ) + + def get_token(refused: str | None) -> str: + if refused is not None and invalidator is not None: + invalidator.invalidate_access_token(refused) + return _non_empty(credentials.access_token()) + + # Without a way to drop the refused token, the source would return it + # again, so the request is sent once. + return TokenAuth(get_token, resend_refused=invalidator is not None, origin=origin) + + +def async_credentials_auth( + credentials: AsyncAccessTokenSource, *, origin: str +) -> AsyncTokenAuth: + """Async form of :func:`credentials_auth`.""" + if not inspect.iscoroutinefunction(credentials.access_token): + raise TypeError( + "credentials.access_token must be async; use the client's sync form" + ) + invalidator = ( + credentials if isinstance(credentials, AccessTokenInvalidator) else None + ) + + async def get_token(refused: str | None) -> str: + if refused is not None and invalidator is not None: + invalidator.invalidate_access_token(refused) + return _non_empty(await credentials.access_token()) + + return AsyncTokenAuth( + get_token, resend_refused=invalidator is not None, origin=origin + ) + + +def _non_empty(token: AccessToken) -> str: + if token.token == "": + raise ValueError("the access token source returned an empty token") + return token.token diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py new file mode 100644 index 0000000..94a91b7 --- /dev/null +++ b/baseten/client/_workload_identity.py @@ -0,0 +1,339 @@ +from __future__ import annotations + +import asyncio +import os +from collections.abc import Awaitable, Callable +from datetime import datetime, timedelta +from pathlib import Path +from typing import TypeAlias + +import httpx + +from baseten.client._token_auth import ( + AccessToken, + AsyncTokenCache, + TokenCache, + _utc_now, +) +from baseten.client._user_agent import with_user_agent + +# The exchange takes an RFC 8693 request naming the trust rule as its audience. +_TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" +_JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" + +_DEFAULT_BASE_URL = "https://api.baseten.co" + +IdentityTokenProvider: TypeAlias = Callable[[], str] +"""Returns the identity provider's JWT. Called on every exchange.""" + +AsyncIdentityTokenProvider: TypeAlias = Callable[[], Awaitable[str]] +"""Async form of :data:`IdentityTokenProvider`.""" + + +class WorkloadIdentityError(Exception): + """A workload identity token exchange failed.""" + + +class InvalidGrantError(WorkloadIdentityError): + """Baseten refused the identity token under the trust rule. + + The server gives no reason: the trust rule may not exist, may not match the + identity token's issuer or claims, or the identity token may be expired or + have the wrong audience. + """ + + +class _Exchange: + """The parts of an exchange shared by the sync and async credentials.""" + + def __init__( + self, + *, + trust_rule_id: str, + identity_token_file: str | os.PathLike[str] | None, + has_identity_token: bool, + base_url_override: str | None, + refresh_before_expiry: timedelta, + exchange_timeout_sec: float, + ) -> None: + if (identity_token_file is None) == (not has_identity_token): + raise ValueError( + "exactly one of identity_token_file and identity_token is required" + ) + if trust_rule_id == "": + raise ValueError("trust_rule_id is required") + if refresh_before_expiry < timedelta(0): + raise ValueError("refresh_before_expiry must not be negative") + if exchange_timeout_sec <= 0: + raise ValueError("exchange_timeout_sec must be positive") + self.trust_rule_id = trust_rule_id + self.identity_token_file = ( + None if identity_token_file is None else Path(identity_token_file) + ) + base_url = (base_url_override or _DEFAULT_BASE_URL).rstrip("/") + self.url = f"{base_url}/v1/auth/token" + self.timeout = httpx.Timeout(exchange_timeout_sec) + self.headers = with_user_agent({"Accept": "application/json"}) + + def read_identity_token_file(self) -> str: + assert self.identity_token_file is not None + # Re-read on every exchange, since such files are rotated in place. + token = self.identity_token_file.read_text().strip() + if token == "": + raise WorkloadIdentityError( + f"identity token file {self.identity_token_file} is empty" + ) + return token + + def body(self, identity_token: str) -> dict[str, str]: + token = identity_token.strip() + if token == "": + raise WorkloadIdentityError( + "the identity token provider returned an empty token" + ) + return { + "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE, + "subject_token": token, + "subject_token_type": _JWT_TOKEN_TYPE, + "audience": self.trust_rule_id, + } + + def parse(self, response: httpx.Response, *, issued_at: datetime) -> AccessToken: + try: + body = response.json() + except ValueError: + raise WorkloadIdentityError( + f"workload identity token exchange: HTTP {response.status_code} " + f"with a non-JSON response: {_truncate(response.text)}" + ) from None + if not isinstance(body, dict): + raise WorkloadIdentityError( + f"workload identity token exchange: HTTP {response.status_code} " + f"with an unexpected response: {_truncate(response.text)}" + ) + if response.status_code != 200: + if body.get("error") == "invalid_grant": + raise InvalidGrantError( + "workload identity token exchange refused for trust rule " + f"{self.trust_rule_id}: invalid_grant (the trust rule may not " + "exist or may not match the identity token's issuer, " + "audience, or claims, or the identity token may have expired)" + ) + raise WorkloadIdentityError( + f"workload identity token exchange: HTTP {response.status_code}: " + f"{_truncate(response.text)}" + ) + access_token = body.get("access_token") + if not isinstance(access_token, str) or access_token == "": + raise WorkloadIdentityError( + "workload identity token exchange: the response carried no access_token" + ) + token_type = body.get("token_type") + if not isinstance(token_type, str) or token_type.lower() != "bearer": + raise WorkloadIdentityError( + "workload identity token exchange: unsupported token_type " + f"{token_type!r}" + ) + expires_in = body.get("expires_in") + if ( + not isinstance(expires_in, int) + or isinstance(expires_in, bool) + or expires_in <= 0 + ): + raise WorkloadIdentityError( + f"workload identity token exchange: invalid expires_in {expires_in!r}" + ) + return AccessToken( + token=access_token, expires_at=issued_at + timedelta(seconds=expires_in) + ) + + +class WorkloadIdentityCredentials: + """Exchanges an identity provider's JWT for a Baseten access token. + + OIDC workload identity federation: the identity token is exchanged under a + Baseten trust rule on first use, the access token is cached in memory and + replaced shortly before it expires. Safe for use from several threads; + concurrent callers share one exchange. Pass to a client as ``credentials`` + in place of an API key. Everything is passed explicitly; no environment + variables are read. + """ + + def __init__( + self, + *, + trust_rule_id: str, + identity_token_file: str | os.PathLike[str] | None = None, + identity_token: IdentityTokenProvider | None = None, + base_url_override: str | None = None, + refresh_before_expiry: timedelta = timedelta(minutes=5), + exchange_timeout_sec: float = 10.0, + http_client_override: httpx.Client | None = None, + ) -> None: + """Validate the options. Baseten is not contacted until first use. + + Args: + trust_rule_id: The Baseten trust rule the identity token is + exchanged under. + identity_token_file: A file holding the identity provider's JWT, + such as a projected Kubernetes service account token. Re-read + on every exchange, since such files are rotated in place. + Exactly one of *identity_token_file* and *identity_token* is + required. + identity_token: Returns the identity provider's JWT. Called on + every exchange. + base_url_override: Management API base URL the exchange is sent + to. ``None`` uses ``https://api.baseten.co``. + refresh_before_expiry: How long before expiry the access token is + replaced, capped at half the token's lifetime so a short-lived + token is still reused. + exchange_timeout_sec: Bounds each phase of one exchange, which + every caller waiting for a token shares. + http_client_override: HTTP client to send the exchange with. + ``None`` uses a new one per exchange. + """ + self._exchange = _Exchange( + trust_rule_id=trust_rule_id, + identity_token_file=identity_token_file, + has_identity_token=identity_token is not None, + base_url_override=base_url_override, + refresh_before_expiry=refresh_before_expiry, + exchange_timeout_sec=exchange_timeout_sec, + ) + self._identity_token = identity_token + self._http_client = http_client_override + # Replaced in tests. + self._now: Callable[[], datetime] = _utc_now + self._cache = TokenCache( + mint=self._exchange_token, + refresh_before=refresh_before_expiry, + now=lambda: self._now(), + ) + + def access_token(self) -> AccessToken: + """Return a current access token, exchanging for a new one when due.""" + return self._cache.token() + + def invalidate_access_token(self, token: str) -> None: + """Drop *token* if it is still cached, so the next call exchanges again.""" + self._cache.invalidate(token) + + def _exchange_token(self) -> AccessToken: + if self._identity_token is not None: + identity_token = self._identity_token() + else: + identity_token = self._exchange.read_identity_token_file() + body = self._exchange.body(identity_token) + # Taken before sending, so the computed expiry errs early. + issued_at = self._now() + try: + if self._http_client is not None: + response = self._post(self._http_client, body) + else: + with httpx.Client() as http_client: + response = self._post(http_client, body) + except httpx.HTTPError as e: + raise WorkloadIdentityError(f"workload identity token exchange: {e}") from e + return self._exchange.parse(response, issued_at=issued_at) + + def _post(self, http_client: httpx.Client, body: dict[str, str]) -> httpx.Response: + return http_client.post( + self._exchange.url, + json=body, + headers=self._exchange.headers, + timeout=self._exchange.timeout, + ) + + +class AsyncWorkloadIdentityCredentials: + """Async form of :class:`WorkloadIdentityCredentials`. + + Concurrent tasks share one exchange, and one task being cancelled does not + cancel the exchange the others wait on. + """ + + def __init__( + self, + *, + trust_rule_id: str, + identity_token_file: str | os.PathLike[str] | None = None, + identity_token: AsyncIdentityTokenProvider | None = None, + base_url_override: str | None = None, + refresh_before_expiry: timedelta = timedelta(minutes=5), + exchange_timeout_sec: float = 10.0, + http_client_override: httpx.AsyncClient | None = None, + ) -> None: + """Validate the options, as :class:`WorkloadIdentityCredentials` does. + + Here *exchange_timeout_sec* bounds the whole exchange, including + *identity_token*. + """ + self._exchange = _Exchange( + trust_rule_id=trust_rule_id, + identity_token_file=identity_token_file, + has_identity_token=identity_token is not None, + base_url_override=base_url_override, + refresh_before_expiry=refresh_before_expiry, + exchange_timeout_sec=exchange_timeout_sec, + ) + self._identity_token = identity_token + self._http_client = http_client_override + self._exchange_timeout_sec = exchange_timeout_sec + # Replaced in tests. + self._now: Callable[[], datetime] = _utc_now + self._cache = AsyncTokenCache( + mint=self._exchange_token, + refresh_before=refresh_before_expiry, + now=lambda: self._now(), + ) + + async def access_token(self) -> AccessToken: + """Return a current access token, exchanging for a new one when due.""" + return await self._cache.token() + + def invalidate_access_token(self, token: str) -> None: + """Drop *token* if it is still cached, so the next call exchanges again.""" + self._cache.invalidate(token) + + async def _exchange_token(self) -> AccessToken: + try: + async with asyncio.timeout(self._exchange_timeout_sec): + return await self._exchange_once() + except TimeoutError as e: + raise WorkloadIdentityError( + "workload identity token exchange timed out after " + f"{self._exchange_timeout_sec}s" + ) from e + + async def _exchange_once(self) -> AccessToken: + if self._identity_token is not None: + identity_token = await self._identity_token() + else: + identity_token = self._exchange.read_identity_token_file() + body = self._exchange.body(identity_token) + # Taken before sending, so the computed expiry errs early. + issued_at = self._now() + try: + if self._http_client is not None: + response = await self._post(self._http_client, body) + else: + async with httpx.AsyncClient() as http_client: + response = await self._post(http_client, body) + except httpx.HTTPError as e: + raise WorkloadIdentityError(f"workload identity token exchange: {e}") from e + return self._exchange.parse(response, issued_at=issued_at) + + async def _post( + self, http_client: httpx.AsyncClient, body: dict[str, str] + ) -> httpx.Response: + return await http_client.post( + self._exchange.url, + json=body, + headers=self._exchange.headers, + timeout=self._exchange.timeout, + ) + + +def _truncate(text: str, max_len: int = 512) -> str: + text = text.strip() + return text if len(text) <= max_len else text[:max_len] + "..." diff --git a/baseten/sandbox/_auth.py b/baseten/sandbox/_auth.py index 740bcdf..93e870e 100644 --- a/baseten/sandbox/_auth.py +++ b/baseten/sandbox/_auth.py @@ -1,16 +1,13 @@ from __future__ import annotations -import asyncio -import threading -import time -from collections.abc import AsyncGenerator, Awaitable, Callable, Generator +from collections.abc import Awaitable, Callable from dataclasses import dataclass -from datetime import UTC, datetime, timedelta +from datetime import timedelta from typing import TypeAlias -import httpx - +import baseten.client._token_auth import baseten.client.managementapi +from baseten.client._token_auth import AccessToken, AsyncTokenCache, TokenCache @dataclass(kw_only=True) @@ -40,21 +37,10 @@ class SandboxTokenProviderContext: """Async form of :data:`SandboxTokenProvider`.""" # Refresh this long before the token's stated expiry, to allow for clock skew -# between this machine and the server, and for time spent in flight. +# between this machine and the server, and for time spent in flight. Capped at +# half the token's lifetime. _TOKEN_EXPIRY_LEEWAY = timedelta(seconds=60) -# A few resends cover a new token being invalidated in the same event as the -# old one. Past that, the rejection is returned, since tokens that keep getting -# rejected point at something a new token cannot fix. -_TOKEN_INVALIDATION_MAX_RETRIES = 2 - -# Revocation rejects every token issued before a cutoff, the time of the -# revoking event rounded up to the next whole second. A token minted right -# after the event can fall before the cutoff and be rejected too, so after the -# first resend, each one waits this long to be minted past it. A module -# variable so tests can shorten it. -_token_revoked_retry_delay = 1.0 - TOKEN_MINT_TIMEOUT = 30.0 """Seconds that one token exchange may take. @@ -62,17 +48,9 @@ class SandboxTokenProviderContext: from holding up every later caller. """ - -@dataclass(frozen=True) -class _MintedToken: - """A token minted from an API key, with its expiry.""" - - token: str - expires_at: datetime - - def fresh(self) -> bool: - """Report whether the token is far enough from expiry to use.""" - return datetime.now(UTC) < self.expires_at - _TOKEN_EXPIRY_LEEWAY +_SANDBOX_TOKEN_REQUEST = baseten.client.managementapi.CreateTokenRequest( + scopes=["sandboxes"] +) class TokenSource: @@ -95,44 +73,38 @@ def __init__( if token_provider is not None and api_key != "": raise ValueError("api_key must be empty when token_provider is set") self._provider = token_provider - self._mint_api = mint_api if api_key != "" else None - self._lock = threading.Lock() - self._cached: _MintedToken | None = None + self._cache = ( + TokenCache( + mint=lambda: _access_token( + mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST) + ), + refresh_before=_TOKEN_EXPIRY_LEEWAY, + ) + if api_key != "" + else None + ) def token(self, revoked_token: str | None = None) -> str | None: """Return the token for a request. - ``None`` means no Authorization is sent, which is the advanced opt-out - of an empty API key with no token provider. + ``revoked_token`` is the token the previous attempt was refused with, + if any. ``None`` means no Authorization is sent, which is the advanced + opt-out of an empty API key with no token provider. """ if self._provider is not None: return self._provider( SandboxTokenProviderContext(revoked_token=revoked_token) ) - if self._mint_api is None: + if self._cache is None: return None - # Held across the mint, so a burst on a cold cache sends one exchange. - with self._lock: - cached = self._cached - if cached is not None and cached.fresh(): - return cached.token - minted = self._mint_api.post_token( - request=baseten.client.managementapi.CreateTokenRequest( - scopes=["sandboxes"] - ) - ) - self._cached = _MintedToken( - token=minted.token, expires_at=minted.expires_at - ) - return minted.token + if revoked_token is not None: + self.invalidate(revoked_token) + return self._cache.token().token def invalidate(self, token: str) -> None: """Drop a token the server rejected, so the next request gets a new one.""" - with self._lock: - # Compared by value, so a rejection of an older token never - # discards a newer one another request already minted. - if self._cached is not None and self._cached.token == token: - self._cached = None + if self._cache is not None: + self._cache.invalidate(token) class AsyncTokenSource: @@ -149,9 +121,17 @@ def __init__( if token_provider is not None and api_key != "": raise ValueError("api_key must be empty when token_provider is set") self._provider = token_provider - self._mint_api = mint_api if api_key != "" else None - self._cached: _MintedToken | None = None - self._minting: asyncio.Task[_MintedToken] | None = None + + async def mint() -> AccessToken: + return _access_token( + await mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST) + ) + + self._cache = ( + AsyncTokenCache(mint=mint, refresh_before=_TOKEN_EXPIRY_LEEWAY) + if api_key != "" + else None + ) async def token(self, revoked_token: str | None = None) -> str | None: """Return the token for a request, as :meth:`TokenSource.token` does.""" @@ -159,125 +139,35 @@ async def token(self, revoked_token: str | None = None) -> str | None: return await self._provider( SandboxTokenProviderContext(revoked_token=revoked_token) ) - if self._mint_api is None: + if self._cache is None: return None - cached = self._cached - if cached is not None and cached.fresh(): - return cached.token - # Every caller shares one mint, so a burst on a cold cache sends one - # exchange. Shielded, since one caller being cancelled must not cancel - # the mint the others are waiting on. - if self._minting is None: - self._minting = asyncio.create_task(self._mint(self._mint_api)) - # Retrieved here so a failure no caller is left to see is not - # reported as never retrieved. - self._minting.add_done_callback( - lambda task: task.cancelled() or task.exception() - ) - minted = await asyncio.shield(self._minting) - return minted.token + if revoked_token is not None: + await self.invalidate(revoked_token) + return (await self._cache.token()).token async def invalidate(self, token: str) -> None: """Drop a token the server rejected, so the next request gets a new one.""" - # Compared by value, so a rejection of an older token never discards a - # newer one another request already minted. - if self._cached is not None and self._cached.token == token: - self._cached = None - - async def _mint( - self, mint_api: baseten.client.managementapi.AsyncApiClient - ) -> _MintedToken: - """Exchange the API key for a token and cache it.""" - try: - minted = await mint_api.post_token( - request=baseten.client.managementapi.CreateTokenRequest( - scopes=["sandboxes"] - ) - ) - self._cached = _MintedToken( - token=minted.token, expires_at=minted.expires_at - ) - return self._cached - finally: - self._minting = None + if self._cache is not None: + self._cache.invalidate(token) -class TokenAuth(httpx.Auth): +class TokenAuth(baseten.client._token_auth.TokenAuth): """Authenticates every request with a token from a :class:`TokenSource`.""" def __init__(self, tokens: TokenSource) -> None: """Create the auth.""" + super().__init__(tokens.token) self.tokens = tokens - def sync_auth_flow( - self, request: httpx.Request - ) -> Generator[httpx.Request, httpx.Response, None]: - """Send the request, again with a new token if its token was revoked.""" - replayable = _is_replayable(request) - revoked_token: str | None = None - for retry in range(_TOKEN_INVALIDATION_MAX_RETRIES + 1): - token = self.tokens.token(revoked_token) - _set_authorization(request, token) - response = yield request - if token is None or not replayable or not _is_token_revoked(response): - return - if retry == _TOKEN_INVALIDATION_MAX_RETRIES: - return - self.tokens.invalidate(token) - revoked_token = token - if retry > 0: - time.sleep(_token_revoked_retry_delay) - - -class AsyncTokenAuth(httpx.Auth): + +class AsyncTokenAuth(baseten.client._token_auth.AsyncTokenAuth): """Authenticates every request with a token from an :class:`AsyncTokenSource`.""" def __init__(self, tokens: AsyncTokenSource) -> None: """Create the auth.""" + super().__init__(tokens.token) self.tokens = tokens - async def async_auth_flow( - self, request: httpx.Request - ) -> AsyncGenerator[httpx.Request, httpx.Response]: - """Send the request, again with a new token if its token was revoked.""" - replayable = _is_replayable(request) - revoked_token: str | None = None - for retry in range(_TOKEN_INVALIDATION_MAX_RETRIES + 1): - token = await self.tokens.token(revoked_token) - _set_authorization(request, token) - response = yield request - if token is None or not replayable or not _is_token_revoked(response): - return - if retry == _TOKEN_INVALIDATION_MAX_RETRIES: - return - await self.tokens.invalidate(token) - revoked_token = token - if retry > 0: - await asyncio.sleep(_token_revoked_retry_delay) - - -def _is_replayable(request: httpx.Request) -> bool: - """Report whether a request's body can be sent again.""" - # A stream body can be read only once, so a request carrying one is never - # sent again. The SDK itself never sends one; only raw API calls can. - return isinstance(request.stream, httpx.ByteStream) - - -def _set_authorization(request: httpx.Request, token: str | None) -> None: - """Set the request's bearer token, or leave Authorization unset for ``None``.""" - if token is not None: - request.headers["Authorization"] = f"Bearer {token}" - - -def _is_token_revoked(response: httpx.Response) -> bool: - """Report whether the server rejected a request's token as revoked. - - The request was rejected before any work was done, so sending it again - with a new token is safe even when it has side effects. - """ - # Both the control plane and sandboxes send this header, while their - # bodies differ. - return ( - response.status_code == 401 - and response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED" - ) + +def _access_token(minted: baseten.client.managementapi.Token) -> AccessToken: + return AccessToken(token=minted.token, expires_at=minted.expires_at) diff --git a/tests/client/test_token_auth.py b/tests/client/test_token_auth.py new file mode 100644 index 0000000..66fa5fa --- /dev/null +++ b/tests/client/test_token_auth.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import asyncio +import threading +from datetime import UTC, datetime, timedelta + +import httpx +import pytest + +from baseten.client import AccessToken +from baseten.client._token_auth import ( + AsyncTokenCache, + TokenCache, + is_token_refused, +) + + +class _Clock: + def __init__(self) -> None: + self.now = datetime(2026, 1, 1, tzinfo=UTC) + + def __call__(self) -> datetime: + return self.now + + +class _Mints: + """Issues ``token-`` valid for *lifetime* from the clock's time.""" + + def __init__(self, clock: _Clock, lifetime: timedelta) -> None: + self.clock = clock + self.lifetime = lifetime + self.count = 0 + self.failures = 0 + + def mint(self) -> AccessToken: + self.count += 1 + if self.failures > 0: + self.failures -= 1 + raise RuntimeError("mint failed") + return AccessToken( + token=f"token-{self.count}", expires_at=self.clock() + self.lifetime + ) + + async def mint_async(self) -> AccessToken: + return self.mint() + + +def _cache( + lifetime: timedelta, refresh_before: timedelta +) -> tuple[TokenCache, _Clock, _Mints]: + clock = _Clock() + mints = _Mints(clock, lifetime) + cache = TokenCache(mint=mints.mint, refresh_before=refresh_before, now=clock) + return cache, clock, mints + + +class TestTokenCache: + def test_refreshes_before_expiry(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + assert cache.token().token == "token-1" + clock.now += timedelta(minutes=54, seconds=59) + assert cache.token().token == "token-1" + clock.now += timedelta(seconds=1) + assert cache.token().token == "token-2" + assert mints.count == 2 + + def test_refresh_capped_at_half_lifetime(self) -> None: + # Without the cap, a five-minute margin on a one-minute token would + # mint on every call. + cache, clock, mints = _cache(timedelta(minutes=1), timedelta(minutes=5)) + cache.token() + clock.now += timedelta(seconds=29) + cache.token() + assert mints.count == 1 + clock.now += timedelta(seconds=1) + cache.token() + assert mints.count == 2 + + def test_returns_just_minted_token_even_if_due(self) -> None: + cache, _, mints = _cache(timedelta(0), timedelta(minutes=1)) + assert cache.token().token == "token-1" + assert cache.token().token == "token-2" + assert mints.count == 2 + + def test_invalidate_keeps_newer_token(self) -> None: + cache, _, _ = _cache(timedelta(hours=1), timedelta(minutes=1)) + cache.token() + cache.invalidate("token-0") + assert cache.token().token == "token-1" + cache.invalidate("token-1") + assert cache.token().token == "token-2" + + def test_failed_mint_is_not_cached(self) -> None: + cache, _, mints = _cache(timedelta(hours=1), timedelta(minutes=1)) + mints.failures = 1 + with pytest.raises(RuntimeError): + cache.token() + assert cache.token().token == "token-2" + + def test_waiter_on_failed_mint_tries_its_own(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + mints.failures = 1 + release = threading.Event() + first_minting = threading.Event() + + def mint() -> AccessToken: + first_minting.set() + release.wait() + return mints.mint() + + cache = TokenCache(mint=mint, refresh_before=timedelta(minutes=1), now=clock) + errors: list[BaseException] = [] + results: list[str] = [] + + def first() -> None: + try: + cache.token() + except RuntimeError as e: + errors.append(e) + + first_thread = threading.Thread(target=first) + first_thread.start() + first_minting.wait() + waiter = threading.Thread(target=lambda: results.append(cache.token().token)) + waiter.start() + release.set() + first_thread.join() + waiter.join() + assert len(errors) == 1 + assert results == ["token-2"] + + +class TestAsyncTokenCache: + @pytest.mark.asyncio + async def test_refreshes_and_caps(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(minutes=1)) + cache = AsyncTokenCache( + mint=mints.mint_async, refresh_before=timedelta(minutes=5), now=clock + ) + assert (await cache.token()).token == "token-1" + clock.now += timedelta(seconds=29) + assert (await cache.token()).token == "token-1" + clock.now += timedelta(seconds=1) + assert (await cache.token()).token == "token-2" + + @pytest.mark.asyncio + async def test_shares_one_mint_and_waiter_retries_after_failure(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + release = asyncio.Event() + + async def mint() -> AccessToken: + await release.wait() + return mints.mint() + + cache = AsyncTokenCache( + mint=mint, refresh_before=timedelta(minutes=1), now=clock + ) + mints.failures = 1 + first = asyncio.create_task(cache.token()) + waiters = [asyncio.create_task(cache.token()) for _ in range(3)] + await asyncio.sleep(0) + release.set() + with pytest.raises(RuntimeError): + await first + assert [(await w).token for w in waiters] == ["token-2"] * 3 + assert mints.count == 2 + + @pytest.mark.asyncio + async def test_invalidate_keeps_newer_token(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + cache = AsyncTokenCache( + mint=mints.mint_async, refresh_before=timedelta(minutes=1), now=clock + ) + await cache.token() + cache.invalidate("token-0") + assert (await cache.token()).token == "token-1" + cache.invalidate("token-1") + assert (await cache.token()).token == "token-2" + + +@pytest.mark.parametrize( + ("status", "headers", "refused"), + [ + (401, {"x-blaxel-error-code": "TOKEN_REVOKED"}, True), + ( + 401, + {"WWW-Authenticate": 'Bearer realm="baseten", error="invalid_token"'}, + True, + ), + (401, {}, False), + (401, {"WWW-Authenticate": 'Bearer realm="baseten"'}, False), + (403, {"WWW-Authenticate": 'Bearer error="invalid_token"'}, False), + ], +) +def test_is_token_refused(status: int, headers: dict[str, str], refused: bool) -> None: + assert is_token_refused(httpx.Response(status, headers=headers)) is refused diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py new file mode 100644 index 0000000..cbaf5d5 --- /dev/null +++ b/tests/client/test_workload_identity.py @@ -0,0 +1,448 @@ +from __future__ import annotations + +import asyncio +import json +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import httpx +import pytest + +import baseten.client._token_auth +import baseten.client.managementapi +from baseten.client import ( + AccessToken, + AsyncInferenceClient, + AsyncManagementClient, + AsyncWorkloadIdentityCredentials, + InferenceClient, + InvalidGrantError, + ManagementClient, + WorkloadIdentityCredentials, + WorkloadIdentityError, +) + +_BASE_URL = "https://api.test" +_ORG = { + "org_id": "o", + "created_at": "2026-01-01T00:00:00Z", + "allow_personal_api_keys": True, + "allow_service_account_api_keys": True, +} + + +@pytest.fixture(autouse=True) +def no_resend_delay(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(baseten.client._token_auth, "_resend_delay_sec", 0.0) + + +class _Server: + """Stands in for ``POST /v1/auth/token``, issuing ``access-``. + + Other requests record their Authorization and get *respond*'s response. + """ + + def __init__(self, *, expires_in: int = 3600) -> None: + self.expires_in = expires_in + self.assertions: list[str] = [] + self.exchange_response: Callable[[], httpx.Response] | None = None + self.respond: Callable[[httpx.Request], httpx.Response] = lambda request: ( + httpx.Response(200, json=_ORG) + ) + self.authorizations: list[str | None] = [] + + def handle(self, request: httpx.Request) -> httpx.Response: + if request.url.path != "/v1/auth/token": + self.authorizations.append(request.headers.get("Authorization")) + return self.respond(request) + assert request.method == "POST" + assert request.headers["Content-Type"] == "application/json" + assert "Authorization" not in request.headers + body = json.loads(request.content) + assert body.keys() == { + "grant_type", + "subject_token", + "subject_token_type", + "audience", + } + assert body["grant_type"] == "urn:ietf:params:oauth:grant-type:token-exchange" + assert body["subject_token_type"] == "urn:ietf:params:oauth:token-type:jwt" + assert body["audience"] == "rule-1" + self.assertions.append(body["subject_token"]) + if self.exchange_response is not None: + return self.exchange_response() + return httpx.Response( + 200, + json={ + "access_token": f"access-{len(self.assertions)}", + "token_type": "Bearer", + "expires_in": self.expires_in, + }, + ) + + async def handle_async(self, request: httpx.Request) -> httpx.Response: + return self.handle(request) + + def credentials(self, **kwargs) -> WorkloadIdentityCredentials: + kwargs.setdefault("trust_rule_id", "rule-1") + if "identity_token_file" not in kwargs: + kwargs.setdefault("identity_token", lambda: "idp-jwt") + return WorkloadIdentityCredentials( + base_url_override=_BASE_URL, + http_client_override=httpx.Client( + transport=httpx.MockTransport(self.handle) + ), + **kwargs, + ) + + def async_credentials(self, **kwargs) -> AsyncWorkloadIdentityCredentials: + kwargs.setdefault("trust_rule_id", "rule-1") + + async def identity_token() -> str: + return "idp-jwt" + + if "identity_token_file" not in kwargs: + kwargs.setdefault("identity_token", identity_token) + return AsyncWorkloadIdentityCredentials( + base_url_override=_BASE_URL, + http_client_override=httpx.AsyncClient( + transport=httpx.MockTransport(self.handle_async) + ), + **kwargs, + ) + + +class _Clock: + def __init__(self) -> None: + self.now = datetime.now(UTC) + + def __call__(self) -> datetime: + return self.now + + +def _with_clock(credentials): + clock = _Clock() + credentials._now = clock + return clock + + +def _error_response(status: int, body: str) -> Callable[[], httpx.Response]: + return lambda: httpx.Response(status, text=body) + + +class TestWorkloadIdentityCredentials: + def test_exchanges_and_caches(self) -> None: + server = _Server() + credentials = server.credentials() + before = datetime.now(UTC) + token = credentials.access_token() + assert token.token == "access-1" + assert token.expires_at >= before + timedelta(hours=1) + assert credentials.access_token().token == "access-1" + assert server.assertions == ["idp-jwt"] + + def test_refreshes_within_leeway(self) -> None: + server = _Server(expires_in=600) + credentials = server.credentials(refresh_before_expiry=timedelta(minutes=1)) + clock = _with_clock(credentials) + credentials.access_token() + clock.now += timedelta(minutes=8, seconds=59) + assert credentials.access_token().token == "access-1" + clock.now += timedelta(seconds=1) + assert credentials.access_token().token == "access-2" + + def test_leeway_capped_at_half_lifetime(self) -> None: + # The default five-minute leeway exceeds the lifetime; without the cap + # every call would exchange. + server = _Server(expires_in=60) + credentials = server.credentials() + clock = _with_clock(credentials) + credentials.access_token() + clock.now += timedelta(seconds=29) + credentials.access_token() + assert len(server.assertions) == 1 + clock.now += timedelta(seconds=1) + credentials.access_token() + assert len(server.assertions) == 2 + + def test_rereads_token_file_on_every_exchange(self, tmp_path: Path) -> None: + server = _Server(expires_in=600) + path = tmp_path / "token" + path.write_text("jwt-one\n") + credentials = server.credentials(identity_token_file=path) + clock = _with_clock(credentials) + credentials.access_token() + path.write_text("jwt-two") + clock.now += timedelta(minutes=10) + credentials.access_token() + assert server.assertions == ["jwt-one", "jwt-two"] + + def test_missing_token_file(self, tmp_path: Path) -> None: + server = _Server() + credentials = server.credentials(identity_token_file=tmp_path / "missing") + with pytest.raises(FileNotFoundError): + credentials.access_token() + assert server.assertions == [] + + def test_empty_token_file(self, tmp_path: Path) -> None: + path = tmp_path / "token" + path.write_text("\n") + credentials = _Server().credentials(identity_token_file=path) + with pytest.raises(WorkloadIdentityError, match="is empty"): + credentials.access_token() + + def test_invalid_grant_is_explained_and_not_cached(self) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response( + 400, json={"error": "invalid_grant"} + ) + credentials = server.credentials() + with pytest.raises(InvalidGrantError, match="rule-1"): + credentials.access_token() + with pytest.raises(InvalidGrantError): + credentials.access_token() + assert len(server.assertions) == 2 + + def test_non_json_response(self) -> None: + server = _Server() + server.exchange_response = _error_response(502, "bad gateway") + with pytest.raises( + WorkloadIdentityError, + match="HTTP 502 with a non-JSON response.*bad gateway", + ): + server.credentials().access_token() + + def test_other_error_status(self) -> None: + server = _Server() + server.exchange_response = _error_response(429, '{"error":"rate_limited"}') + with pytest.raises(WorkloadIdentityError, match="HTTP 429") as exc_info: + server.credentials().access_token() + assert not isinstance(exc_info.value, InvalidGrantError) + + @pytest.mark.parametrize( + "body", + [ + {"token_type": "Bearer", "expires_in": 60}, + {"access_token": "a", "token_type": "MAC", "expires_in": 60}, + {"access_token": "a", "token_type": "Bearer"}, + ], + ) + def test_malformed_success(self, body: dict[str, object]) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response(200, json=body) + with pytest.raises(WorkloadIdentityError): + server.credentials().access_token() + + @pytest.mark.parametrize( + "kwargs", + [ + {"trust_rule_id": "r"}, + {"trust_rule_id": "r", "identity_token_file": "/f", "identity_token": str}, + {"trust_rule_id": "", "identity_token": str}, + { + "trust_rule_id": "r", + "identity_token": str, + "refresh_before_expiry": timedelta(seconds=-1), + }, + ], + ) + def test_validates_options(self, kwargs: dict[str, object]) -> None: + with pytest.raises(ValueError): + WorkloadIdentityCredentials(**kwargs) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + + +class TestAsyncWorkloadIdentityCredentials: + @pytest.mark.asyncio + async def test_concurrent_callers_share_one_exchange(self) -> None: + server = _Server() + release = asyncio.Event() + + async def handle(request: httpx.Request) -> httpx.Response: + await release.wait() + return server.handle(request) + + credentials = AsyncWorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=server.async_credentials()._identity_token, + base_url_override=_BASE_URL, + http_client_override=httpx.AsyncClient( + transport=httpx.MockTransport(handle) + ), + ) + tasks = [asyncio.create_task(credentials.access_token()) for _ in range(32)] + await asyncio.sleep(0) + release.set() + tokens = await asyncio.gather(*tasks) + assert {token.token for token in tokens} == {"access-1"} + assert len(server.assertions) == 1 + + @pytest.mark.asyncio + async def test_cancelled_waiter_does_not_cancel_exchange(self) -> None: + server = _Server() + release = asyncio.Event() + + async def identity_token() -> str: + await release.wait() + return "idp-jwt" + + credentials = server.async_credentials(identity_token=identity_token) + cancelled = asyncio.create_task(credentials.access_token()) + waiting = asyncio.create_task(credentials.access_token()) + await asyncio.sleep(0) + cancelled.cancel() + release.set() + assert (await waiting).token == "access-1" + with pytest.raises(asyncio.CancelledError): + await cancelled + + @pytest.mark.asyncio + async def test_exchange_timeout(self) -> None: + async def identity_token() -> str: + await asyncio.Event().wait() + return "never" + + credentials = _Server().async_credentials( + identity_token=identity_token, exchange_timeout_sec=0.01 + ) + with pytest.raises(WorkloadIdentityError, match="timed out"): + await credentials.access_token() + + @pytest.mark.asyncio + async def test_rereads_token_file(self, tmp_path: Path) -> None: + server = _Server(expires_in=600) + path = tmp_path / "token" + path.write_text("jwt-one") + credentials = server.async_credentials(identity_token_file=path) + clock = _with_clock(credentials) + await credentials.access_token() + path.write_text("jwt-two") + clock.now += timedelta(minutes=10) + await credentials.access_token() + assert server.assertions == ["jwt-one", "jwt-two"] + + +def _management(server: _Server, credentials) -> ManagementClient: + client = ManagementClient(credentials=credentials, base_url_override=_BASE_URL) + client.http_client._transport = httpx.MockTransport(server.handle) # type: ignore[attr-defined] + return client + + +class TestClientsWithCredentials: + def test_send_the_current_token(self) -> None: + server = _Server(expires_in=600) + credentials = server.credentials() + clock = _with_clock(credentials) + management = _management(server, credentials) + management.api.get_organizations_me() + clock.now += timedelta(hours=1) + management.api.get_organizations_me() + inference = InferenceClient( + credentials=credentials, base_url_override=_BASE_URL + ) + inference.http_client._transport = httpx.MockTransport(server.handle) # type: ignore[attr-defined] + inference.http_client.get("/anything") + assert server.authorizations == [ + "Bearer access-1", + "Bearer access-2", + "Bearer access-2", + ] + + @pytest.mark.asyncio + async def test_async_clients_send_the_current_token(self) -> None: + server = _Server() + credentials = server.async_credentials() + management = AsyncManagementClient( + credentials=credentials, base_url_override=_BASE_URL + ) + management.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] + await management.api.get_organizations_me() + inference = AsyncInferenceClient( + credentials=credentials, base_url_override=_BASE_URL + ) + inference.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] + await inference.http_client.get("/anything") + assert server.authorizations == ["Bearer access-1", "Bearer access-1"] + + def test_resends_refused_token(self) -> None: + server = _Server() + server.respond = _refuse_access_1 + management = _management(server, server.credentials()) + management.api.get_organizations_me() + assert server.authorizations == ["Bearer access-1", "Bearer access-2"] + + @pytest.mark.asyncio + async def test_async_resends_refused_token(self) -> None: + server = _Server() + server.respond = _refuse_access_1 + management = AsyncManagementClient( + credentials=server.async_credentials(), base_url_override=_BASE_URL + ) + management.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] + await management.api.get_organizations_me() + assert server.authorizations == ["Bearer access-1", "Bearer access-2"] + + def test_sends_once_for_source_without_invalidation(self) -> None: + class Source: + def access_token(self) -> AccessToken: + return AccessToken( + token="access-1", expires_at=datetime.now(UTC) + timedelta(hours=1) + ) + + server = _Server() + server.respond = _refuse_access_1 + management = _management(server, Source()) + with pytest.raises(baseten.client.managementapi.ResponseError): + management.api.get_organizations_me() + assert server.authorizations == ["Bearer access-1"] + + def test_leaves_other_hosts_alone(self) -> None: + server = _Server() + management = _management(server, server.credentials()) + management.http_client.put("https://storage.test/presigned") + management.http_client.get( + "/explicit", headers={"Authorization": "Bearer mine"} + ) + assert server.authorizations == [None, "Bearer mine"] + assert server.assertions == [] + + def test_redirect_to_other_host_drops_token(self) -> None: + server = _Server() + server.respond = lambda request: ( + httpx.Response(302, headers={"Location": "https://sub.api.test/landing"}) + if request.url.path == "/start" + else httpx.Response(200) + ) + management = _management(server, server.credentials()) + management.http_client.get("/start", follow_redirects=True) + assert server.authorizations == ["Bearer access-1", None] + + def test_validates_auth_options(self) -> None: + credentials = _Server().credentials() + with pytest.raises(ValueError, match="mutually exclusive"): + ManagementClient(api_key="k", credentials=credentials) + with pytest.raises(ValueError, match="mutually exclusive"): + ManagementClient(api_key="", credentials=credentials) + with pytest.raises(ValueError, match="required"): + ManagementClient() + for name in ["Authorization", "authorization"]: + with pytest.raises(ValueError, match="Authorization"): + ManagementClient(credentials=credentials, headers={name: "Bearer x"}) + with pytest.raises(ValueError, match="mutually exclusive"): + InferenceClient(api_key="k", credentials=credentials, model_id="m") + InferenceClient(credentials=credentials, model_id="m").close() + with pytest.raises(TypeError, match="async"): + AsyncManagementClient(credentials=credentials) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="async"): + ManagementClient(credentials=_Server().async_credentials()) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + + +def _refuse_access_1(request: httpx.Request) -> httpx.Response: + if request.headers.get("Authorization") == "Bearer access-1": + return httpx.Response( + 401, + headers={ + "WWW-Authenticate": 'Bearer realm="baseten", error="invalid_token"' + }, + ) + return httpx.Response(200, json=_ORG) diff --git a/tests/sandbox/test_auth.py b/tests/sandbox/test_auth.py index 3969b56..fa5b8f5 100644 --- a/tests/sandbox/test_auth.py +++ b/tests/sandbox/test_auth.py @@ -9,8 +9,8 @@ import httpx import pytest +import baseten.client._token_auth import baseten.client.managementapi -import baseten.sandbox._auth from baseten.sandbox import SandboxTokenProviderContext from baseten.sandbox._auth import ( AsyncTokenAuth, @@ -26,7 +26,7 @@ def _revoked(request: httpx.Request | None = None) -> httpx.Response: @pytest.fixture(autouse=True) def no_revoked_retry_delay(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(baseten.sandbox._auth, "_token_revoked_retry_delay", 0.0) + monkeypatch.setattr(baseten.client._token_auth, "_resend_delay_sec", 0.0) class _Server: @@ -89,8 +89,9 @@ def test_mints_with_api_key_and_reuses_token(self) -> None: assert server.mints[0].headers["Authorization"] == "Bearer key" assert json.loads(server.mints[0].content) == {"scopes": ["sandboxes"]} - def test_refreshes_within_a_minute_of_expiry(self) -> None: - server = _Server(expires_in=timedelta(seconds=30)) + def test_refreshes_at_expiry(self) -> None: + # Refresh timing within the lifetime is covered by the token cache tests. + server = _Server(expires_in=timedelta(0)) tokens = server.tokens() assert tokens.token() == "token-1" assert tokens.token() == "token-2" @@ -226,6 +227,18 @@ def test_resends_with_new_token_after_revocation(self) -> None: "Bearer token-2", ] + def test_resends_with_new_token_after_invalid_token(self) -> None: + server = _Server() + server.respond = lambda request: ( + httpx.Response( + 401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'} + ) + if len(server.requests) == 1 + else httpx.Response(200) + ) + assert _get(server, server.tokens()).status_code == 200 + assert server.authorizations == ["Bearer token-1", "Bearer token-2"] + def test_tells_caching_provider_which_token_was_revoked(self) -> None: server = _Server() server.respond = lambda request: ( @@ -245,14 +258,16 @@ def test_returns_revocation_after_two_resends( ) -> None: delays: list[float] = [] monkeypatch.setattr( - baseten.sandbox._auth.time, "sleep", lambda seconds: delays.append(seconds) + baseten.client._token_auth.time, + "sleep", + lambda seconds: delays.append(seconds), ) server = _Server(respond=_revoked) response = _get(server, server.tokens()) assert response.status_code == 401 assert len(server.requests) == 3 # Only the second resend waits, to be minted past the revocation. - assert delays == [baseten.sandbox._auth._token_revoked_retry_delay] + assert delays == [baseten.client._token_auth._resend_delay_sec] def test_does_not_resend_other_401(self) -> None: server = _Server(respond=lambda request: httpx.Response(401)) From 86025e83f8aa28571b51db27ee7334391fd8b0df Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Tue, 17 Nov 2026 01:43:08 -0500 Subject: [PATCH 02/14] Send credentials tokens once and pass options to Credentials The management and inference clients fetch a token from their credentials and send each request once; a 401 is returned to the caller as is, since on inference it can come from the model itself. Sandbox requests keep their resend on a refused token, and the shared auth now drops the refused token itself, even when the request cannot be sent again. The credentials protocol is now Credentials / AsyncCredentials, named after the client option, with one access_token method taking AccessTokenOptions so fields can be added without breaking implementations. The separate invalidation protocol is gone. The refresh margin is refresh_leeway everywhere. A refused exchange raises the management API's ResponseError with the full body; an invalid_grant refusal adds a note naming the trust rule and the possible causes. The exchange never follows redirects, since its body carries the identity token. The sandbox clients accept credentials directly, mutually exclusive with api_key and token_provider, and mint sandbox tokens with them. The workload identity usage moves from the README into the credentials docstring, matching how other client options are documented. Co-Authored-By: Claude Opus 5.5 --- README.md | 17 -- baseten/client/__init__.py | 16 +- baseten/client/_inference.py | 27 ++- baseten/client/_management.py | 27 ++- baseten/client/_token_auth.py | 229 ++++++++++++------------- baseten/client/_workload_identity.py | 202 ++++++++++------------ baseten/sandbox/_auth.py | 81 +++++---- baseten/sandbox/_client.py | 124 +++++++++---- tests/client/test_token_auth.py | 12 +- tests/client/test_workload_identity.py | 150 +++++++++------- tests/sandbox/test_auth.py | 20 +-- tests/sandbox/test_client.py | 65 +++++++ 12 files changed, 530 insertions(+), 440 deletions(-) diff --git a/README.md b/README.md index 03d3c17..d2699eb 100644 --- a/README.md +++ b/README.md @@ -34,23 +34,6 @@ async with AsyncManagementClient(api_key="my-api-key") as client: print(model.name) ``` -### Authenticating with workload identity federation - -Instead of an API key, a workload can exchange its identity provider's token (for example a projected Kubernetes service account token) for a short-lived Baseten access token under a trust rule. The credentials exchange on first use, cache the access token, and replace it before it expires: - -```python -from baseten.client import ManagementClient, WorkloadIdentityCredentials - -credentials = WorkloadIdentityCredentials( - trust_rule_id="my-trust-rule-id", - identity_token_file="/var/run/secrets/tokens/baseten", -) -with ManagementClient(credentials=credentials) as client: - ... -``` - -`AsyncWorkloadIdentityCredentials` is the same for async clients. - ## Sandboxes `baseten.sandbox` creates and works with sandboxes. HTTP/2 is used when the `h2` package is installed, which is strongly recommended: diff --git a/baseten/client/__init__.py b/baseten/client/__init__.py index d11d643..cd7135d 100644 --- a/baseten/client/__init__.py +++ b/baseten/client/__init__.py @@ -27,37 +27,33 @@ ) from baseten.client._token_auth import ( AccessToken, - AccessTokenInvalidator, - AccessTokenSource, - AsyncAccessTokenSource, + AccessTokenOptions, + AsyncCredentials, + Credentials, ) from baseten.client._workload_identity import ( AsyncIdentityTokenProvider, AsyncWorkloadIdentityCredentials, IdentityTokenProvider, - InvalidGrantError, WorkloadIdentityCredentials, - WorkloadIdentityError, ) __all__ = [ "AccessToken", - "AccessTokenInvalidator", - "AccessTokenSource", - "AsyncAccessTokenSource", + "AccessTokenOptions", + "AsyncCredentials", "AsyncIdentityTokenProvider", "AsyncInferenceClient", "AsyncManagementClient", "AsyncSandboxClient", "AsyncWorkloadIdentityCredentials", + "Credentials", "IdentityTokenProvider", "InferenceClient", "InferenceClientOptions", - "InvalidGrantError", "ManagementClient", "ManagementClientOptions", "SandboxClient", "SandboxClientOptions", "WorkloadIdentityCredentials", - "WorkloadIdentityError", ] diff --git a/baseten/client/_inference.py b/baseten/client/_inference.py index 2bc5768..0f0185e 100644 --- a/baseten/client/_inference.py +++ b/baseten/client/_inference.py @@ -8,11 +8,11 @@ import baseten.client.inferenceapi from baseten.client._token_auth import ( - AccessTokenSource, - AsyncAccessTokenSource, - async_credentials_auth, + AsyncCredentials, + AsyncCredentialsAuth, + Credentials, + CredentialsAuth, check_client_auth, - credentials_auth, ) from baseten.client._user_agent import with_user_agent @@ -44,8 +44,8 @@ class InferenceClientOptions: """Explicit base URL override. When set, *model_id*, *chain_id*, and *environment* are ignored.""" - credentials: AccessTokenSource | AsyncAccessTokenSource | None = None - """Source of short-lived access tokens, used in place of *api_key*.""" + credentials: Credentials | AsyncCredentials | None = None + """Supplies short-lived access tokens, used in place of *api_key*.""" @property def base_url(self) -> str: @@ -99,7 +99,7 @@ def __init__( self, *, api_key: str | None = None, - credentials: AccessTokenSource | None = None, + credentials: Credentials | None = None, headers: Mapping[str, str] | None = None, model_id: str | None = None, chain_id: str | None = None, @@ -113,12 +113,11 @@ def __init__( Args: api_key: API key for authentication. Exactly one of *api_key* and *credentials* is required. - credentials: Source of short-lived access tokens in place of an + credentials: Supplies short-lived access tokens in place of an API key, such as :class:`WorkloadIdentityCredentials`. A token is fetched for every request, so a long-lived client picks up refreshed tokens. It is sent only to this client's API host, - and a request whose token Baseten refuses is sent again with a - new one when the source can drop the refused token. + and each request is sent once. headers: Additional headers to send on every request. model_id: Model ID. Mutually exclusive with *chain_id*. chain_id: Chain ID. Mutually exclusive with *model_id*. @@ -146,7 +145,7 @@ def __init__( auth = ( None if credentials is None - else credentials_auth(credentials, origin=self._options.base_url) + else CredentialsAuth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} @@ -232,7 +231,7 @@ def __init__( self, *, api_key: str | None = None, - credentials: AsyncAccessTokenSource | None = None, + credentials: AsyncCredentials | None = None, headers: Mapping[str, str] | None = None, model_id: str | None = None, chain_id: str | None = None, @@ -246,7 +245,7 @@ def __init__( Args: api_key: API key for authentication. Exactly one of *api_key* and *credentials* is required. - credentials: Source of short-lived access tokens, as for + credentials: Supplies short-lived access tokens, as for :class:`InferenceClient`. headers: Additional headers to send on every request. model_id: Model ID. Mutually exclusive with *chain_id*. @@ -275,7 +274,7 @@ def __init__( auth = ( None if credentials is None - else async_credentials_auth(credentials, origin=self._options.base_url) + else AsyncCredentialsAuth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} diff --git a/baseten/client/_management.py b/baseten/client/_management.py index 27994be..3aff3a5 100644 --- a/baseten/client/_management.py +++ b/baseten/client/_management.py @@ -8,11 +8,11 @@ import baseten.client.managementapi from baseten.client._token_auth import ( - AccessTokenSource, - AsyncAccessTokenSource, - async_credentials_auth, + AsyncCredentials, + AsyncCredentialsAuth, + Credentials, + CredentialsAuth, check_client_auth, - credentials_auth, ) from baseten.client._user_agent import with_user_agent @@ -34,8 +34,8 @@ class ManagementClientOptions: base_url_override: str | None = None """Explicit base URL override, or ``None`` to use the default.""" - credentials: AccessTokenSource | AsyncAccessTokenSource | None = None - """Source of short-lived access tokens, used in place of *api_key*.""" + credentials: Credentials | AsyncCredentials | None = None + """Supplies short-lived access tokens, used in place of *api_key*.""" @property def base_url(self) -> str: @@ -61,7 +61,7 @@ def __init__( self, *, api_key: str | None = None, - credentials: AccessTokenSource | None = None, + credentials: Credentials | None = None, headers: Mapping[str, str] | None = None, base_url_override: str | None = None, http_client_override: httpx.Client | None = None, @@ -72,12 +72,11 @@ def __init__( Args: api_key: API key for authentication. Exactly one of *api_key* and *credentials* is required. - credentials: Source of short-lived access tokens in place of an + credentials: Supplies short-lived access tokens in place of an API key, such as :class:`WorkloadIdentityCredentials`. A token is fetched for every request, so a long-lived client picks up refreshed tokens. It is sent only to this client's API host, - and a request whose token Baseten refuses is sent again with a - new one when the source can drop the refused token. + and each request is sent once. headers: Additional headers to send on every request. base_url_override: Override the default base URL. When ``None``, :meth:`default_base_url` is used. @@ -99,7 +98,7 @@ def __init__( auth = ( None if credentials is None - else credentials_auth(credentials, origin=self._options.base_url) + else CredentialsAuth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} @@ -174,7 +173,7 @@ def __init__( self, *, api_key: str | None = None, - credentials: AsyncAccessTokenSource | None = None, + credentials: AsyncCredentials | None = None, headers: Mapping[str, str] | None = None, base_url_override: str | None = None, http_client_override: httpx.AsyncClient | None = None, @@ -185,7 +184,7 @@ def __init__( Args: api_key: API key for authentication. Exactly one of *api_key* and *credentials* is required. - credentials: Source of short-lived access tokens, as for + credentials: Supplies short-lived access tokens, as for :class:`ManagementClient`. headers: Additional headers to send on every request. base_url_override: Override the default base URL. When ``None``, @@ -208,7 +207,7 @@ def __init__( auth = ( None if credentials is None - else async_credentials_auth(credentials, origin=self._options.base_url) + else AsyncCredentialsAuth(credentials, origin=self._options.base_url) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py index 602a624..c776500 100644 --- a/baseten/client/_token_auth.py +++ b/baseten/client/_token_auth.py @@ -1,8 +1,8 @@ """What every short-lived Baseten token needs. -A cache that mints a new token shortly before the current one expires, and an -:class:`httpx.Auth` that sends a request again with a new token when the server -refuses the current one. +A cache that mints a new token shortly before the current one expires, an +:class:`httpx.Auth` that sends a token from :class:`Credentials`, and one that +sends a request again with a new token when the server refuses the current one. """ from __future__ import annotations @@ -14,7 +14,7 @@ from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapping from dataclasses import dataclass from datetime import UTC, datetime, timedelta -from typing import Protocol, runtime_checkable +from typing import Protocol import httpx @@ -30,40 +30,31 @@ class AccessToken: """When the token expires.""" -@runtime_checkable -class AccessTokenSource(Protocol): - """Supplies a current access token. +@dataclass(frozen=True) +class AccessTokenOptions: + """What :class:`Credentials` are told about the token they are asked for. - A client configured with one calls it before every request, so the source - decides when to refresh. + Has no fields yet; it lets fields be added without breaking implementations. """ - def access_token(self) -> AccessToken: - """Return a current access token.""" - ... +class Credentials(Protocol): + """Supplies a current Baseten access token. -@runtime_checkable -class AsyncAccessTokenSource(Protocol): - """Async form of :class:`AccessTokenSource`.""" + A client given one as ``credentials`` calls it before every request, so + the credentials decide when to refresh. + """ - async def access_token(self) -> AccessToken: + def access_token(self, options: AccessTokenOptions) -> AccessToken: """Return a current access token.""" ... -@runtime_checkable -class AccessTokenInvalidator(Protocol): - """Implemented by an access token source that caches tokens. +class AsyncCredentials(Protocol): + """Async form of :class:`Credentials`.""" - When Baseten refuses a token before it expires, for example because it was - revoked, a client drops it with :meth:`invalidate_access_token`, asks the - source for a new one, and sends the request again. Clients resend only for - sources that implement this. - """ - - def invalidate_access_token(self, token: str) -> None: - """Drop *token* if it is still the cached one.""" + async def access_token(self, options: AccessTokenOptions) -> AccessToken: + """Return a current access token.""" ... @@ -78,17 +69,17 @@ class _CachedToken: def _cached( - token: AccessToken, *, minted_at: datetime, refresh_before: timedelta + token: AccessToken, *, minted_at: datetime, refresh_leeway: timedelta ) -> _CachedToken: - """Cache *token* until *refresh_before* its expiry, capped at half its lifetime. + """Cache *token* until *refresh_leeway* before expiry, capped at half its lifetime. - The cap keeps a token whose lifetime is shorter than the margin from being + The cap keeps a token whose lifetime is shorter than the leeway from being minted again on every call. """ lifetime = max(token.expires_at - minted_at, timedelta(0)) return _CachedToken( token=token, - refresh_at=token.expires_at - min(refresh_before, lifetime / 2), + refresh_at=token.expires_at - min(refresh_leeway, lifetime / 2), ) @@ -104,12 +95,12 @@ def __init__( self, *, mint: Callable[[], AccessToken], - refresh_before: timedelta, + refresh_leeway: timedelta, now: Callable[[], datetime] = _utc_now, ) -> None: """Create an empty cache; the first mint happens on first use.""" self._mint = mint - self._refresh_before = refresh_before + self._refresh_leeway = refresh_leeway self._now = now self._lock = threading.Lock() self._current: _CachedToken | None = None @@ -125,7 +116,7 @@ def token(self) -> AccessToken: minted_at = self._now() token = self._mint() self._current = _cached( - token, minted_at=minted_at, refresh_before=self._refresh_before + token, minted_at=minted_at, refresh_leeway=self._refresh_leeway ) # Returned even if already due, so a skewed clock cannot make every # call mint. @@ -151,12 +142,12 @@ def __init__( self, *, mint: Callable[[], Awaitable[AccessToken]], - refresh_before: timedelta, + refresh_leeway: timedelta, now: Callable[[], datetime] = _utc_now, ) -> None: """Create an empty cache; the first mint happens on first use.""" self._mint = mint - self._refresh_before = refresh_before + self._refresh_leeway = refresh_leeway self._now = now self._current: _CachedToken | None = None self._minting: asyncio.Task[_CachedToken] | None = None @@ -202,7 +193,7 @@ async def _run_mint(self) -> _CachedToken: minted_at = self._now() token = await self._mint() self._current = _cached( - token, minted_at=minted_at, refresh_before=self._refresh_before + token, minted_at=minted_at, refresh_leeway=self._refresh_leeway ) return self._current finally: @@ -228,46 +219,35 @@ class TokenAuth(httpx.Auth): *get_token* is called with ``None``, or with the token the server just refused, and returns the token to send, or ``None`` to send no Authorization. When the server refuses the token (see - :func:`is_token_refused`) and the body can be sent again, the request is - resent with a new token, at most twice. + :func:`is_token_refused`), it is passed to *invalidate*, and the request + is sent again with a new token when its body can be, at most twice. """ def __init__( self, get_token: Callable[[str | None], str | None], - *, - resend_refused: bool = True, - origin: str | None = None, + invalidate: Callable[[str], None], ) -> None: - """Create the auth. - - Args: - get_token: Returns the token for a request. - resend_refused: Whether to resend a request whose token was refused. - origin: When set, only requests to this URL's host and port that - carry no Authorization of their own are authenticated, so a - token never reaches another host through a shared HTTP client. - """ + """Create the auth.""" self._get_token = get_token - self._resend_refused = resend_refused - self._origin = None if origin is None else httpx.URL(origin) + self._invalidate = invalidate def sync_auth_flow( self, request: httpx.Request ) -> Generator[httpx.Request, httpx.Response, None]: """Send the request, again with a new token if its token was refused.""" - if not _applies_to(request, self._origin): - yield request - return - resend = self._resend_refused and _is_replayable(request) + replayable = _is_replayable(request) refused: str | None = None for attempt in range(_MAX_RESENDS + 1): token = self._get_token(refused) _set_authorization(request, token) response = yield request - if token is None or not resend or not is_token_refused(response): + if token is None or not is_token_refused(response): return - if attempt == _MAX_RESENDS: + # Dropped even when the request is not sent again, so later + # requests do not reuse it. + self._invalidate(token) + if not replayable or attempt == _MAX_RESENDS: return refused = token if attempt > 0: @@ -280,31 +260,26 @@ class AsyncTokenAuth(httpx.Auth): def __init__( self, get_token: Callable[[str | None], Awaitable[str | None]], - *, - resend_refused: bool = True, - origin: str | None = None, + invalidate: Callable[[str], None], ) -> None: """Create the auth, as :class:`TokenAuth` does.""" self._get_token = get_token - self._resend_refused = resend_refused - self._origin = None if origin is None else httpx.URL(origin) + self._invalidate = invalidate async def async_auth_flow( self, request: httpx.Request ) -> AsyncGenerator[httpx.Request, httpx.Response]: """Send the request, again with a new token if its token was refused.""" - if not _applies_to(request, self._origin): - yield request - return - resend = self._resend_refused and _is_replayable(request) + replayable = _is_replayable(request) refused: str | None = None for attempt in range(_MAX_RESENDS + 1): token = await self._get_token(refused) _set_authorization(request, token) response = yield request - if token is None or not resend or not is_token_refused(response): + if token is None or not is_token_refused(response): return - if attempt == _MAX_RESENDS: + self._invalidate(token) + if not replayable or attempt == _MAX_RESENDS: return refused = token if attempt > 0: @@ -330,9 +305,63 @@ def is_token_refused(response: httpx.Response) -> bool: ) -def _applies_to(request: httpx.Request, origin: httpx.URL | None) -> bool: - if origin is None: - return True +class CredentialsAuth(httpx.Auth): + """Sends a token from :class:`Credentials` on each request to one origin. + + A token is fetched for every request, so a long-lived client picks up + refreshed tokens. Each request is sent once; a refusal is returned to the + caller as is. + """ + + def __init__(self, credentials: Credentials, *, origin: str) -> None: + """Create the auth. + + Args: + credentials: Supplies the token. + origin: Only requests to this URL's host and port that carry no + Authorization of their own are authenticated, so a token never + reaches another host through a shared HTTP client. + """ + if inspect.iscoroutinefunction(credentials.access_token): + raise TypeError( + "credentials.access_token is async; use the client's async form" + ) + self._credentials = credentials + self._origin = httpx.URL(origin) + + def sync_auth_flow( + self, request: httpx.Request + ) -> Generator[httpx.Request, httpx.Response, None]: + """Send the request with the current token.""" + if _applies_to(request, self._origin): + token = self._credentials.access_token(AccessTokenOptions()) + _set_authorization(request, _non_empty(token)) + yield request + + +class AsyncCredentialsAuth(httpx.Auth): + """Async form of :class:`CredentialsAuth`.""" + + def __init__(self, credentials: AsyncCredentials, *, origin: str) -> None: + """Create the auth, as :class:`CredentialsAuth` does.""" + if not inspect.iscoroutinefunction(credentials.access_token): + raise TypeError( + "credentials.access_token must be async; use the client's sync form" + ) + self._credentials = credentials + self._origin = httpx.URL(origin) + + async def async_auth_flow( + self, request: httpx.Request + ) -> AsyncGenerator[httpx.Request, httpx.Response]: + """Send the request with the current token.""" + if _applies_to(request, self._origin): + token = await self._credentials.access_token(AccessTokenOptions()) + _set_authorization(request, _non_empty(token)) + yield request + + +def _applies_to(request: httpx.Request, origin: httpx.URL) -> bool: return ( request.url.host == origin.host and request.url.port == origin.port @@ -352,6 +381,12 @@ def _set_authorization(request: httpx.Request, token: str | None) -> None: request.headers["Authorization"] = f"Bearer {token}" +def _non_empty(token: AccessToken) -> str: + if token.token == "": + raise ValueError("the credentials returned an empty access token") + return token.token + + def check_client_auth( *, api_key: str | None, @@ -367,51 +402,3 @@ def check_client_auth( key.lower() == "authorization" for key in headers or {} ): raise ValueError("headers must not set Authorization when credentials is set") - - -def credentials_auth(credentials: AccessTokenSource, *, origin: str) -> TokenAuth: - """Build the auth that sends *credentials*' token to *origin* only.""" - if inspect.iscoroutinefunction(credentials.access_token): - raise TypeError( - "credentials.access_token is async; use the client's async form" - ) - invalidator = ( - credentials if isinstance(credentials, AccessTokenInvalidator) else None - ) - - def get_token(refused: str | None) -> str: - if refused is not None and invalidator is not None: - invalidator.invalidate_access_token(refused) - return _non_empty(credentials.access_token()) - - # Without a way to drop the refused token, the source would return it - # again, so the request is sent once. - return TokenAuth(get_token, resend_refused=invalidator is not None, origin=origin) - - -def async_credentials_auth( - credentials: AsyncAccessTokenSource, *, origin: str -) -> AsyncTokenAuth: - """Async form of :func:`credentials_auth`.""" - if not inspect.iscoroutinefunction(credentials.access_token): - raise TypeError( - "credentials.access_token must be async; use the client's sync form" - ) - invalidator = ( - credentials if isinstance(credentials, AccessTokenInvalidator) else None - ) - - async def get_token(refused: str | None) -> str: - if refused is not None and invalidator is not None: - invalidator.invalidate_access_token(refused) - return _non_empty(await credentials.access_token()) - - return AsyncTokenAuth( - get_token, resend_refused=invalidator is not None, origin=origin - ) - - -def _non_empty(token: AccessToken) -> str: - if token.token == "": - raise ValueError("the access token source returned an empty token") - return token.token diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 94a91b7..07d9d0e 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -5,17 +5,19 @@ from collections.abc import Awaitable, Callable from datetime import datetime, timedelta from pathlib import Path -from typing import TypeAlias +from typing import Any, TypeAlias import httpx from baseten.client._token_auth import ( AccessToken, + AccessTokenOptions, AsyncTokenCache, TokenCache, _utc_now, ) from baseten.client._user_agent import with_user_agent +from baseten.client.managementapi import ResponseError # The exchange takes an RFC 8693 request naming the trust rule as its audience. _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" @@ -30,19 +32,6 @@ """Async form of :data:`IdentityTokenProvider`.""" -class WorkloadIdentityError(Exception): - """A workload identity token exchange failed.""" - - -class InvalidGrantError(WorkloadIdentityError): - """Baseten refused the identity token under the trust rule. - - The server gives no reason: the trust rule may not exist, may not match the - identity token's issuer or claims, or the identity token may be expired or - have the wrong audience. - """ - - class _Exchange: """The parts of an exchange shared by the sync and async credentials.""" @@ -53,7 +42,7 @@ def __init__( identity_token_file: str | os.PathLike[str] | None, has_identity_token: bool, base_url_override: str | None, - refresh_before_expiry: timedelta, + refresh_leeway: timedelta, exchange_timeout_sec: float, ) -> None: if (identity_token_file is None) == (not has_identity_token): @@ -62,8 +51,8 @@ def __init__( ) if trust_rule_id == "": raise ValueError("trust_rule_id is required") - if refresh_before_expiry < timedelta(0): - raise ValueError("refresh_before_expiry must not be negative") + if refresh_leeway < timedelta(0): + raise ValueError("refresh_leeway must not be negative") if exchange_timeout_sec <= 0: raise ValueError("exchange_timeout_sec must be positive") self.trust_rule_id = trust_rule_id @@ -80,17 +69,13 @@ def read_identity_token_file(self) -> str: # Re-read on every exchange, since such files are rotated in place. token = self.identity_token_file.read_text().strip() if token == "": - raise WorkloadIdentityError( - f"identity token file {self.identity_token_file} is empty" - ) + raise ValueError(f"identity token file {self.identity_token_file} is empty") return token def body(self, identity_token: str) -> dict[str, str]: token = identity_token.strip() if token == "": - raise WorkloadIdentityError( - "the identity token provider returned an empty token" - ) + raise ValueError("the identity token provider returned an empty token") return { "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE, "subject_token": token, @@ -98,39 +83,46 @@ def body(self, identity_token: str) -> dict[str, str]: "audience": self.trust_rule_id, } + def post_kwargs(self, body: dict[str, str]) -> dict[str, Any]: + return { + "url": self.url, + "json": body, + "headers": self.headers, + "timeout": self.timeout, + # The body carries the identity token, so it is never sent on to + # wherever a redirect points, even with a client that follows them. + "follow_redirects": False, + } + def parse(self, response: httpx.Response, *, issued_at: datetime) -> AccessToken: + if response.status_code != 200: + error = ResponseError(status_code=response.status_code, body=response.text) + if _oauth_error(response) == "invalid_grant": + # The server sends every refusal as the same invalid_grant, so + # the note covers each possible cause. + error.add_note( + "workload identity token exchange refused for trust rule " + f"{self.trust_rule_id} (the trust rule may not exist or may " + "not match the identity token's issuer, audience, or claims, " + "or the identity token may have expired)" + ) + raise error try: body = response.json() except ValueError: - raise WorkloadIdentityError( - f"workload identity token exchange: HTTP {response.status_code} " - f"with a non-JSON response: {_truncate(response.text)}" + raise ValueError( + "workload identity token exchange: the response is not JSON" ) from None if not isinstance(body, dict): - raise WorkloadIdentityError( - f"workload identity token exchange: HTTP {response.status_code} " - f"with an unexpected response: {_truncate(response.text)}" - ) - if response.status_code != 200: - if body.get("error") == "invalid_grant": - raise InvalidGrantError( - "workload identity token exchange refused for trust rule " - f"{self.trust_rule_id}: invalid_grant (the trust rule may not " - "exist or may not match the identity token's issuer, " - "audience, or claims, or the identity token may have expired)" - ) - raise WorkloadIdentityError( - f"workload identity token exchange: HTTP {response.status_code}: " - f"{_truncate(response.text)}" - ) + body = {} access_token = body.get("access_token") if not isinstance(access_token, str) or access_token == "": - raise WorkloadIdentityError( + raise ValueError( "workload identity token exchange: the response carried no access_token" ) token_type = body.get("token_type") if not isinstance(token_type, str) or token_type.lower() != "bearer": - raise WorkloadIdentityError( + raise ValueError( "workload identity token exchange: unsupported token_type " f"{token_type!r}" ) @@ -140,7 +132,7 @@ def parse(self, response: httpx.Response, *, issued_at: datetime) -> AccessToken or isinstance(expires_in, bool) or expires_in <= 0 ): - raise WorkloadIdentityError( + raise ValueError( f"workload identity token exchange: invalid expires_in {expires_in!r}" ) return AccessToken( @@ -148,15 +140,36 @@ def parse(self, response: httpx.Response, *, issued_at: datetime) -> AccessToken ) +def _oauth_error(response: httpx.Response) -> object: + try: + body = response.json() + except ValueError: + return None + return body.get("error") if isinstance(body, dict) else None + + class WorkloadIdentityCredentials: - """Exchanges an identity provider's JWT for a Baseten access token. - - OIDC workload identity federation: the identity token is exchanged under a - Baseten trust rule on first use, the access token is cached in memory and - replaced shortly before it expires. Safe for use from several threads; - concurrent callers share one exchange. Pass to a client as ``credentials`` - in place of an API key. Everything is passed explicitly; no environment - variables are read. + """Exchanges an identity provider's JWT for Baseten access tokens. + + OIDC workload identity federation: instead of an API key, a workload + exchanges its identity provider's token (for example a projected + Kubernetes service account token) for a short-lived Baseten access token + under a trust rule. Pass the credentials to a client as ``credentials``:: + + from baseten.client import ManagementClient, WorkloadIdentityCredentials + + credentials = WorkloadIdentityCredentials( + trust_rule_id="my-trust-rule-id", + identity_token_file="/var/run/secrets/tokens/baseten", + ) + with ManagementClient(credentials=credentials) as client: + print(client.api.get_organizations_me().org_id) + + The exchange happens on first use; the access token is cached in memory + and replaced shortly before it expires. Safe for use from several threads; + concurrent callers share one exchange. Everything is passed explicitly; no + environment variables are read. A refused exchange raises + :class:`baseten.client.managementapi.ResponseError`. """ def __init__( @@ -166,7 +179,7 @@ def __init__( identity_token_file: str | os.PathLike[str] | None = None, identity_token: IdentityTokenProvider | None = None, base_url_override: str | None = None, - refresh_before_expiry: timedelta = timedelta(minutes=5), + refresh_leeway: timedelta = timedelta(minutes=5), exchange_timeout_sec: float = 10.0, http_client_override: httpx.Client | None = None, ) -> None: @@ -184,7 +197,7 @@ def __init__( every exchange. base_url_override: Management API base URL the exchange is sent to. ``None`` uses ``https://api.baseten.co``. - refresh_before_expiry: How long before expiry the access token is + refresh_leeway: How long before expiry the access token is replaced, capped at half the token's lifetime so a short-lived token is still reused. exchange_timeout_sec: Bounds each phase of one exchange, which @@ -197,7 +210,7 @@ def __init__( identity_token_file=identity_token_file, has_identity_token=identity_token is not None, base_url_override=base_url_override, - refresh_before_expiry=refresh_before_expiry, + refresh_leeway=refresh_leeway, exchange_timeout_sec=exchange_timeout_sec, ) self._identity_token = identity_token @@ -206,47 +219,32 @@ def __init__( self._now: Callable[[], datetime] = _utc_now self._cache = TokenCache( mint=self._exchange_token, - refresh_before=refresh_before_expiry, + refresh_leeway=refresh_leeway, now=lambda: self._now(), ) - def access_token(self) -> AccessToken: + def access_token(self, options: AccessTokenOptions) -> AccessToken: """Return a current access token, exchanging for a new one when due.""" return self._cache.token() - def invalidate_access_token(self, token: str) -> None: - """Drop *token* if it is still cached, so the next call exchanges again.""" - self._cache.invalidate(token) - def _exchange_token(self) -> AccessToken: if self._identity_token is not None: identity_token = self._identity_token() else: identity_token = self._exchange.read_identity_token_file() - body = self._exchange.body(identity_token) + post_kwargs = self._exchange.post_kwargs(self._exchange.body(identity_token)) # Taken before sending, so the computed expiry errs early. issued_at = self._now() - try: - if self._http_client is not None: - response = self._post(self._http_client, body) - else: - with httpx.Client() as http_client: - response = self._post(http_client, body) - except httpx.HTTPError as e: - raise WorkloadIdentityError(f"workload identity token exchange: {e}") from e + if self._http_client is not None: + response = self._http_client.post(**post_kwargs) + else: + with httpx.Client() as http_client: + response = http_client.post(**post_kwargs) return self._exchange.parse(response, issued_at=issued_at) - def _post(self, http_client: httpx.Client, body: dict[str, str]) -> httpx.Response: - return http_client.post( - self._exchange.url, - json=body, - headers=self._exchange.headers, - timeout=self._exchange.timeout, - ) - class AsyncWorkloadIdentityCredentials: - """Async form of :class:`WorkloadIdentityCredentials`. + """Async form of :class:`WorkloadIdentityCredentials`, for async clients. Concurrent tasks share one exchange, and one task being cancelled does not cancel the exchange the others wait on. @@ -259,7 +257,7 @@ def __init__( identity_token_file: str | os.PathLike[str] | None = None, identity_token: AsyncIdentityTokenProvider | None = None, base_url_override: str | None = None, - refresh_before_expiry: timedelta = timedelta(minutes=5), + refresh_leeway: timedelta = timedelta(minutes=5), exchange_timeout_sec: float = 10.0, http_client_override: httpx.AsyncClient | None = None, ) -> None: @@ -273,7 +271,7 @@ def __init__( identity_token_file=identity_token_file, has_identity_token=identity_token is not None, base_url_override=base_url_override, - refresh_before_expiry=refresh_before_expiry, + refresh_leeway=refresh_leeway, exchange_timeout_sec=exchange_timeout_sec, ) self._identity_token = identity_token @@ -283,24 +281,20 @@ def __init__( self._now: Callable[[], datetime] = _utc_now self._cache = AsyncTokenCache( mint=self._exchange_token, - refresh_before=refresh_before_expiry, + refresh_leeway=refresh_leeway, now=lambda: self._now(), ) - async def access_token(self) -> AccessToken: + async def access_token(self, options: AccessTokenOptions) -> AccessToken: """Return a current access token, exchanging for a new one when due.""" return await self._cache.token() - def invalidate_access_token(self, token: str) -> None: - """Drop *token* if it is still cached, so the next call exchanges again.""" - self._cache.invalidate(token) - async def _exchange_token(self) -> AccessToken: try: async with asyncio.timeout(self._exchange_timeout_sec): return await self._exchange_once() except TimeoutError as e: - raise WorkloadIdentityError( + raise TimeoutError( "workload identity token exchange timed out after " f"{self._exchange_timeout_sec}s" ) from e @@ -310,30 +304,12 @@ async def _exchange_once(self) -> AccessToken: identity_token = await self._identity_token() else: identity_token = self._exchange.read_identity_token_file() - body = self._exchange.body(identity_token) + post_kwargs = self._exchange.post_kwargs(self._exchange.body(identity_token)) # Taken before sending, so the computed expiry errs early. issued_at = self._now() - try: - if self._http_client is not None: - response = await self._post(self._http_client, body) - else: - async with httpx.AsyncClient() as http_client: - response = await self._post(http_client, body) - except httpx.HTTPError as e: - raise WorkloadIdentityError(f"workload identity token exchange: {e}") from e + if self._http_client is not None: + response = await self._http_client.post(**post_kwargs) + else: + async with httpx.AsyncClient() as http_client: + response = await http_client.post(**post_kwargs) return self._exchange.parse(response, issued_at=issued_at) - - async def _post( - self, http_client: httpx.AsyncClient, body: dict[str, str] - ) -> httpx.Response: - return await http_client.post( - self._exchange.url, - json=body, - headers=self._exchange.headers, - timeout=self._exchange.timeout, - ) - - -def _truncate(text: str, max_len: int = 512) -> str: - text = text.strip() - return text if len(text) <= max_len else text[:max_len] + "..." diff --git a/baseten/sandbox/_auth.py b/baseten/sandbox/_auth.py index 93e870e..03d25b7 100644 --- a/baseten/sandbox/_auth.py +++ b/baseten/sandbox/_auth.py @@ -56,40 +56,36 @@ class SandboxTokenProviderContext: class TokenSource: """Where each request's bearer token comes from. - Either a caller's token provider, or a token minted from an API key and - cached until shortly before it expires. The API key is exchanged for a - token because the sandbox APIs do not accept API keys directly. Should that - change, only this class changes. + Either a caller's token provider, or a token minted through *mint_api* and + cached until shortly before it expires. *mint_api* authenticates with an + API key or credentials, which are exchanged for a token because the + sandbox APIs do not accept them directly. Should that change, only this + class changes. """ def __init__( self, *, - api_key: str, token_provider: SandboxTokenProvider | None, - mint_api: baseten.client.managementapi.ApiClient, + mint_api: baseten.client.managementapi.ApiClient | None, ) -> None: - """Create a token source. ``mint_api`` authenticates with the API key.""" - if token_provider is not None and api_key != "": - raise ValueError("api_key must be empty when token_provider is set") + """Create a token source. + + With neither *token_provider* nor *mint_api*, no Authorization is + sent, which is the advanced opt-out of an empty API key. + """ self._provider = token_provider self._cache = ( - TokenCache( - mint=lambda: _access_token( - mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST) - ), - refresh_before=_TOKEN_EXPIRY_LEEWAY, - ) - if api_key != "" - else None + None + if token_provider is not None or mint_api is None + else _token_cache(mint_api) ) def token(self, revoked_token: str | None = None) -> str | None: - """Return the token for a request. + """Return the token for a request, or ``None`` to send no Authorization. ``revoked_token`` is the token the previous attempt was refused with, - if any. ``None`` means no Authorization is sent, which is the advanced - opt-out of an empty API key with no token provider. + if any. """ if self._provider is not None: return self._provider( @@ -97,8 +93,6 @@ def token(self, revoked_token: str | None = None) -> str | None: ) if self._cache is None: return None - if revoked_token is not None: - self.invalidate(revoked_token) return self._cache.token().token def invalidate(self, token: str) -> None: @@ -113,24 +107,15 @@ class AsyncTokenSource: def __init__( self, *, - api_key: str, token_provider: AsyncSandboxTokenProvider | None, - mint_api: baseten.client.managementapi.AsyncApiClient, + mint_api: baseten.client.managementapi.AsyncApiClient | None, ) -> None: - """Create a token source. ``mint_api`` authenticates with the API key.""" - if token_provider is not None and api_key != "": - raise ValueError("api_key must be empty when token_provider is set") + """Create a token source, as :class:`TokenSource` does.""" self._provider = token_provider - - async def mint() -> AccessToken: - return _access_token( - await mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST) - ) - self._cache = ( - AsyncTokenCache(mint=mint, refresh_before=_TOKEN_EXPIRY_LEEWAY) - if api_key != "" - else None + None + if token_provider is not None or mint_api is None + else _async_token_cache(mint_api) ) async def token(self, revoked_token: str | None = None) -> str | None: @@ -141,11 +126,9 @@ async def token(self, revoked_token: str | None = None) -> str | None: ) if self._cache is None: return None - if revoked_token is not None: - await self.invalidate(revoked_token) return (await self._cache.token()).token - async def invalidate(self, token: str) -> None: + def invalidate(self, token: str) -> None: """Drop a token the server rejected, so the next request gets a new one.""" if self._cache is not None: self._cache.invalidate(token) @@ -156,7 +139,7 @@ class TokenAuth(baseten.client._token_auth.TokenAuth): def __init__(self, tokens: TokenSource) -> None: """Create the auth.""" - super().__init__(tokens.token) + super().__init__(tokens.token, tokens.invalidate) self.tokens = tokens @@ -165,9 +148,25 @@ class AsyncTokenAuth(baseten.client._token_auth.AsyncTokenAuth): def __init__(self, tokens: AsyncTokenSource) -> None: """Create the auth.""" - super().__init__(tokens.token) + super().__init__(tokens.token, tokens.invalidate) self.tokens = tokens +def _token_cache(mint_api: baseten.client.managementapi.ApiClient) -> TokenCache: + return TokenCache( + mint=lambda: _access_token(mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST)), + refresh_leeway=_TOKEN_EXPIRY_LEEWAY, + ) + + +def _async_token_cache( + mint_api: baseten.client.managementapi.AsyncApiClient, +) -> AsyncTokenCache: + async def mint() -> AccessToken: + return _access_token(await mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST)) + + return AsyncTokenCache(mint=mint, refresh_leeway=_TOKEN_EXPIRY_LEEWAY) + + def _access_token(minted: baseten.client.managementapi.Token) -> AccessToken: return AccessToken(token=minted.token, expires_at=minted.expires_at) diff --git a/baseten/sandbox/_client.py b/baseten/sandbox/_client.py index f8bdbc4..607b629 100644 --- a/baseten/sandbox/_client.py +++ b/baseten/sandbox/_client.py @@ -17,6 +17,13 @@ import baseten.client import baseten.client.managementapi import baseten.client.sandboxapi +from baseten.client._token_auth import ( + AsyncCredentials, + AsyncCredentialsAuth, + Credentials, + CredentialsAuth, + check_client_auth, +) from baseten.client._user_agent import with_user_agent from baseten.sandbox._auth import ( TOKEN_MINT_TIMEOUT, @@ -83,8 +90,8 @@ class SandboxClientOptions: was constructed with. """ - api_key: str - """API key for authentication.""" + api_key: str | None = None + """API key for authentication, or ``None`` when another way is set.""" team_id: str | None = None """Team to act in, or ``None`` for the caller's only team.""" @@ -92,6 +99,9 @@ class SandboxClientOptions: token_provider: SandboxTokenProvider | AsyncSandboxTokenProvider | None = None """Provider of each request's bearer token, in place of the API key.""" + credentials: Credentials | AsyncCredentials | None = None + """Supplies short-lived access tokens, used in place of *api_key*.""" + base_url_override: str | None = None """Explicit base URL override, or ``None`` to use the default.""" @@ -153,9 +163,10 @@ class SandboxClient: def __init__( self, *, - api_key: str, + api_key: str | None = None, team_id: str | None = None, token_provider: SandboxTokenProvider | None = None, + credentials: Credentials | None = None, base_url_override: str | None = None, headers: Mapping[str, str] | None = None, retry: SandboxRetryOptions | None = None, @@ -167,13 +178,17 @@ def __init__( """Create a new sandbox client. Args: - api_key: API key for authentication. Empty, together with - *token_provider*, is the advanced opt-out of API key - authentication. + api_key: API key for authentication. Exactly one of *api_key*, + *credentials*, and *token_provider* is required. Empty, on its + own, is the advanced opt-out of sending Authorization. team_id: Team to act in. ``None`` uses the caller's only team, and is an error for callers in more than one team. token_provider: Returns the bearer token for each request, instead - of one derived from the API key, which must then be empty. + of one derived from an API key or credentials. + credentials: Supplies short-lived access tokens in place of an + API key, such as + :class:`~baseten.client.WorkloadIdentityCredentials`. Sandbox + tokens are requested with them. base_url_override: Override the management API's base URL, which defaults to ``https://api.baseten.co``. headers: Additional headers to send on every request. @@ -203,10 +218,17 @@ def __init__( threads end once the sandbox is no longer referenced. """ self._executor = executor + _check_auth( + api_key=api_key, + credentials=credentials, + token_provider=token_provider, + headers=headers, + ) self._options = SandboxClientOptions( api_key=api_key, team_id=team_id, token_provider=token_provider, + credentials=credentials, base_url_override=base_url_override, headers=headers, retry=retry, @@ -229,16 +251,22 @@ def __init__( else close_http_client_on_close ) self._request_headers = with_user_agent(headers or {}) - mint_api = baseten.client.managementapi.ApiClient( - self._http_client, - base_url=self._options.base_url, - headers={**self._request_headers, "Authorization": f"Bearer {api_key}"}, - timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), - ) - self._auth = TokenAuth( - TokenSource( - api_key=api_key, token_provider=token_provider, mint_api=mint_api + mint_api = None + if api_key or credentials is not None: + mint_headers = dict(self._request_headers) + if api_key: + mint_headers["Authorization"] = f"Bearer {api_key}" + mint_api = baseten.client.managementapi.ApiClient( + self._http_client, + base_url=self._options.base_url, + auth=None + if credentials is None + else CredentialsAuth(credentials, origin=self._options.base_url), + headers=mint_headers, + timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), ) + self._auth = TokenAuth( + TokenSource(token_provider=token_provider, mint_api=mint_api) ) self._raw_api = baseten.client.managementapi.ApiClient( self._http_client, @@ -562,9 +590,10 @@ class AsyncSandboxClient: def __init__( self, *, - api_key: str, + api_key: str | None = None, team_id: str | None = None, token_provider: AsyncSandboxTokenProvider | None = None, + credentials: AsyncCredentials | None = None, base_url_override: str | None = None, headers: Mapping[str, str] | None = None, retry: SandboxRetryOptions | None = None, @@ -575,13 +604,17 @@ def __init__( """Create a new async sandbox client. Args: - api_key: API key for authentication. Empty, together with - *token_provider*, is the advanced opt-out of API key - authentication. + api_key: API key for authentication. Exactly one of *api_key*, + *credentials*, and *token_provider* is required. Empty, on its + own, is the advanced opt-out of sending Authorization. team_id: Team to act in. ``None`` uses the caller's only team, and is an error for callers in more than one team. token_provider: Returns the bearer token for each request, instead - of one derived from the API key, which must then be empty. + of one derived from an API key or credentials. + credentials: Supplies short-lived access tokens in place of an + API key, such as + :class:`~baseten.client.AsyncWorkloadIdentityCredentials`. Sandbox + tokens are requested with them. base_url_override: Override the management API's base URL, which defaults to ``https://api.baseten.co``. headers: Additional headers to send on every request. @@ -603,10 +636,17 @@ def __init__( client is created internally, ``False`` when *http_client_override* is provided. """ + _check_auth( + api_key=api_key, + credentials=credentials, + token_provider=token_provider, + headers=headers, + ) self._options = SandboxClientOptions( api_key=api_key, team_id=team_id, token_provider=token_provider, + credentials=credentials, base_url_override=base_url_override, headers=headers, retry=retry, @@ -629,16 +669,22 @@ def __init__( else close_http_client_on_close ) self._request_headers = with_user_agent(headers or {}) - mint_api = baseten.client.managementapi.AsyncApiClient( - self._http_client, - base_url=self._options.base_url, - headers={**self._request_headers, "Authorization": f"Bearer {api_key}"}, - timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), - ) - self._auth = AsyncTokenAuth( - AsyncTokenSource( - api_key=api_key, token_provider=token_provider, mint_api=mint_api + mint_api = None + if api_key or credentials is not None: + mint_headers = dict(self._request_headers) + if api_key: + mint_headers["Authorization"] = f"Bearer {api_key}" + mint_api = baseten.client.managementapi.AsyncApiClient( + self._http_client, + base_url=self._options.base_url, + auth=None + if credentials is None + else AsyncCredentialsAuth(credentials, origin=self._options.base_url), + headers=mint_headers, + timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), ) + self._auth = AsyncTokenAuth( + AsyncTokenSource(token_provider=token_provider, mint_api=mint_api) ) self._raw_api = baseten.client.managementapi.AsyncApiClient( self._http_client, @@ -888,3 +934,21 @@ def _use_http2(http2: bool | None) -> bool: 'http2=True requires the h2 package, installed with "httpx[http2]"' ) return available + + +def _check_auth( + *, + api_key: str | None, + credentials: object | None, + token_provider: object | None, + headers: Mapping[str, str] | None, +) -> None: + """Check that a client is given exactly one way to authenticate.""" + if sum((bool(api_key), credentials is not None, token_provider is not None)) > 1: + raise ValueError( + "only one of api_key, credentials, and token_provider may be set" + ) + if api_key is None and credentials is None and token_provider is None: + raise ValueError("one of api_key, credentials, or token_provider is required") + if credentials is not None: + check_client_auth(api_key=None, credentials=credentials, headers=headers) diff --git a/tests/client/test_token_auth.py b/tests/client/test_token_auth.py index 66fa5fa..35fe63e 100644 --- a/tests/client/test_token_auth.py +++ b/tests/client/test_token_auth.py @@ -46,11 +46,11 @@ async def mint_async(self) -> AccessToken: def _cache( - lifetime: timedelta, refresh_before: timedelta + lifetime: timedelta, refresh_leeway: timedelta ) -> tuple[TokenCache, _Clock, _Mints]: clock = _Clock() mints = _Mints(clock, lifetime) - cache = TokenCache(mint=mints.mint, refresh_before=refresh_before, now=clock) + cache = TokenCache(mint=mints.mint, refresh_leeway=refresh_leeway, now=clock) return cache, clock, mints @@ -109,7 +109,7 @@ def mint() -> AccessToken: release.wait() return mints.mint() - cache = TokenCache(mint=mint, refresh_before=timedelta(minutes=1), now=clock) + cache = TokenCache(mint=mint, refresh_leeway=timedelta(minutes=1), now=clock) errors: list[BaseException] = [] results: list[str] = [] @@ -137,7 +137,7 @@ async def test_refreshes_and_caps(self) -> None: clock = _Clock() mints = _Mints(clock, timedelta(minutes=1)) cache = AsyncTokenCache( - mint=mints.mint_async, refresh_before=timedelta(minutes=5), now=clock + mint=mints.mint_async, refresh_leeway=timedelta(minutes=5), now=clock ) assert (await cache.token()).token == "token-1" clock.now += timedelta(seconds=29) @@ -156,7 +156,7 @@ async def mint() -> AccessToken: return mints.mint() cache = AsyncTokenCache( - mint=mint, refresh_before=timedelta(minutes=1), now=clock + mint=mint, refresh_leeway=timedelta(minutes=1), now=clock ) mints.failures = 1 first = asyncio.create_task(cache.token()) @@ -173,7 +173,7 @@ async def test_invalidate_keeps_newer_token(self) -> None: clock = _Clock() mints = _Mints(clock, timedelta(hours=1)) cache = AsyncTokenCache( - mint=mints.mint_async, refresh_before=timedelta(minutes=1), now=clock + mint=mints.mint_async, refresh_leeway=timedelta(minutes=1), now=clock ) await cache.token() cache.invalidate("token-0") diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index cbaf5d5..8afcc8e 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -9,19 +9,17 @@ import httpx import pytest -import baseten.client._token_auth -import baseten.client.managementapi from baseten.client import ( AccessToken, + AccessTokenOptions, AsyncInferenceClient, AsyncManagementClient, AsyncWorkloadIdentityCredentials, InferenceClient, - InvalidGrantError, ManagementClient, WorkloadIdentityCredentials, - WorkloadIdentityError, ) +from baseten.client.managementapi import ResponseError _BASE_URL = "https://api.test" _ORG = { @@ -30,11 +28,7 @@ "allow_personal_api_keys": True, "allow_service_account_api_keys": True, } - - -@pytest.fixture(autouse=True) -def no_resend_delay(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(baseten.client._token_auth, "_resend_delay_sec", 0.0) +_OPTIONS = AccessTokenOptions() class _Server: @@ -136,21 +130,21 @@ def test_exchanges_and_caches(self) -> None: server = _Server() credentials = server.credentials() before = datetime.now(UTC) - token = credentials.access_token() + token = credentials.access_token(_OPTIONS) assert token.token == "access-1" assert token.expires_at >= before + timedelta(hours=1) - assert credentials.access_token().token == "access-1" + assert credentials.access_token(_OPTIONS).token == "access-1" assert server.assertions == ["idp-jwt"] def test_refreshes_within_leeway(self) -> None: server = _Server(expires_in=600) - credentials = server.credentials(refresh_before_expiry=timedelta(minutes=1)) + credentials = server.credentials(refresh_leeway=timedelta(minutes=1)) clock = _with_clock(credentials) - credentials.access_token() + credentials.access_token(_OPTIONS) clock.now += timedelta(minutes=8, seconds=59) - assert credentials.access_token().token == "access-1" + assert credentials.access_token(_OPTIONS).token == "access-1" clock.now += timedelta(seconds=1) - assert credentials.access_token().token == "access-2" + assert credentials.access_token(_OPTIONS).token == "access-2" def test_leeway_capped_at_half_lifetime(self) -> None: # The default five-minute leeway exceeds the lifetime; without the cap @@ -158,12 +152,12 @@ def test_leeway_capped_at_half_lifetime(self) -> None: server = _Server(expires_in=60) credentials = server.credentials() clock = _with_clock(credentials) - credentials.access_token() + credentials.access_token(_OPTIONS) clock.now += timedelta(seconds=29) - credentials.access_token() + credentials.access_token(_OPTIONS) assert len(server.assertions) == 1 clock.now += timedelta(seconds=1) - credentials.access_token() + credentials.access_token(_OPTIONS) assert len(server.assertions) == 2 def test_rereads_token_file_on_every_exchange(self, tmp_path: Path) -> None: @@ -172,25 +166,25 @@ def test_rereads_token_file_on_every_exchange(self, tmp_path: Path) -> None: path.write_text("jwt-one\n") credentials = server.credentials(identity_token_file=path) clock = _with_clock(credentials) - credentials.access_token() + credentials.access_token(_OPTIONS) path.write_text("jwt-two") clock.now += timedelta(minutes=10) - credentials.access_token() + credentials.access_token(_OPTIONS) assert server.assertions == ["jwt-one", "jwt-two"] def test_missing_token_file(self, tmp_path: Path) -> None: server = _Server() credentials = server.credentials(identity_token_file=tmp_path / "missing") with pytest.raises(FileNotFoundError): - credentials.access_token() + credentials.access_token(_OPTIONS) assert server.assertions == [] def test_empty_token_file(self, tmp_path: Path) -> None: path = tmp_path / "token" path.write_text("\n") credentials = _Server().credentials(identity_token_file=path) - with pytest.raises(WorkloadIdentityError, match="is empty"): - credentials.access_token() + with pytest.raises(ValueError, match="is empty"): + credentials.access_token(_OPTIONS) def test_invalid_grant_is_explained_and_not_cached(self) -> None: server = _Server() @@ -198,27 +192,49 @@ def test_invalid_grant_is_explained_and_not_cached(self) -> None: 400, json={"error": "invalid_grant"} ) credentials = server.credentials() - with pytest.raises(InvalidGrantError, match="rule-1"): - credentials.access_token() - with pytest.raises(InvalidGrantError): - credentials.access_token() + with pytest.raises(ResponseError) as exc_info: + credentials.access_token(_OPTIONS) + assert exc_info.value.status_code == 400 + assert exc_info.value.body == '{"error":"invalid_grant"}' + (note,) = exc_info.value.__notes__ + assert "trust rule rule-1" in note + assert "may have expired" in note + with pytest.raises(ResponseError): + credentials.access_token(_OPTIONS) assert len(server.assertions) == 2 - def test_non_json_response(self) -> None: + def test_non_json_error_keeps_whole_body(self) -> None: + body = "" + "x" * 2000 + "" server = _Server() - server.exchange_response = _error_response(502, "bad gateway") - with pytest.raises( - WorkloadIdentityError, - match="HTTP 502 with a non-JSON response.*bad gateway", - ): - server.credentials().access_token() + server.exchange_response = _error_response(502, body) + with pytest.raises(ResponseError) as exc_info: + server.credentials().access_token(_OPTIONS) + assert (exc_info.value.status_code, exc_info.value.body) == (502, body) + assert not hasattr(exc_info.value, "__notes__") def test_other_error_status(self) -> None: server = _Server() server.exchange_response = _error_response(429, '{"error":"rate_limited"}') - with pytest.raises(WorkloadIdentityError, match="HTTP 429") as exc_info: - server.credentials().access_token() - assert not isinstance(exc_info.value, InvalidGrantError) + with pytest.raises(ResponseError, match="HTTP 429") as exc_info: + server.credentials().access_token(_OPTIONS) + assert not hasattr(exc_info.value, "__notes__") + + def test_does_not_follow_redirects(self) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response( + 307, headers={"Location": "https://elsewhere.test/v1/auth/token"} + ) + credentials = WorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=lambda: "idp-jwt", + base_url_override=_BASE_URL, + http_client_override=httpx.Client( + transport=httpx.MockTransport(server.handle), follow_redirects=True + ), + ) + with pytest.raises(ResponseError, match="HTTP 307"): + credentials.access_token(_OPTIONS) + assert server.assertions == ["idp-jwt"] @pytest.mark.parametrize( "body", @@ -231,8 +247,8 @@ def test_other_error_status(self) -> None: def test_malformed_success(self, body: dict[str, object]) -> None: server = _Server() server.exchange_response = lambda: httpx.Response(200, json=body) - with pytest.raises(WorkloadIdentityError): - server.credentials().access_token() + with pytest.raises(ValueError): + server.credentials().access_token(_OPTIONS) @pytest.mark.parametrize( "kwargs", @@ -243,7 +259,7 @@ def test_malformed_success(self, body: dict[str, object]) -> None: { "trust_rule_id": "r", "identity_token": str, - "refresh_before_expiry": timedelta(seconds=-1), + "refresh_leeway": timedelta(seconds=-1), }, ], ) @@ -270,7 +286,9 @@ async def handle(request: httpx.Request) -> httpx.Response: transport=httpx.MockTransport(handle) ), ) - tasks = [asyncio.create_task(credentials.access_token()) for _ in range(32)] + tasks = [ + asyncio.create_task(credentials.access_token(_OPTIONS)) for _ in range(32) + ] await asyncio.sleep(0) release.set() tokens = await asyncio.gather(*tasks) @@ -287,8 +305,8 @@ async def identity_token() -> str: return "idp-jwt" credentials = server.async_credentials(identity_token=identity_token) - cancelled = asyncio.create_task(credentials.access_token()) - waiting = asyncio.create_task(credentials.access_token()) + cancelled = asyncio.create_task(credentials.access_token(_OPTIONS)) + waiting = asyncio.create_task(credentials.access_token(_OPTIONS)) await asyncio.sleep(0) cancelled.cancel() release.set() @@ -305,8 +323,8 @@ async def identity_token() -> str: credentials = _Server().async_credentials( identity_token=identity_token, exchange_timeout_sec=0.01 ) - with pytest.raises(WorkloadIdentityError, match="timed out"): - await credentials.access_token() + with pytest.raises(TimeoutError, match="timed out"): + await credentials.access_token(_OPTIONS) @pytest.mark.asyncio async def test_rereads_token_file(self, tmp_path: Path) -> None: @@ -315,10 +333,10 @@ async def test_rereads_token_file(self, tmp_path: Path) -> None: path.write_text("jwt-one") credentials = server.async_credentials(identity_token_file=path) clock = _with_clock(credentials) - await credentials.access_token() + await credentials.access_token(_OPTIONS) path.write_text("jwt-two") clock.now += timedelta(minutes=10) - await credentials.access_token() + await credentials.access_token(_OPTIONS) assert server.assertions == ["jwt-one", "jwt-two"] @@ -364,37 +382,41 @@ async def test_async_clients_send_the_current_token(self) -> None: await inference.http_client.get("/anything") assert server.authorizations == ["Bearer access-1", "Bearer access-1"] - def test_resends_refused_token(self) -> None: + def test_returns_refusal_without_resending(self) -> None: + # A 401 can come from the model itself, so it is the caller's to see. server = _Server() server.respond = _refuse_access_1 management = _management(server, server.credentials()) - management.api.get_organizations_me() - assert server.authorizations == ["Bearer access-1", "Bearer access-2"] + with pytest.raises(ResponseError, match="HTTP 401"): + management.api.get_organizations_me() + assert server.authorizations == ["Bearer access-1"] @pytest.mark.asyncio - async def test_async_resends_refused_token(self) -> None: + async def test_async_returns_refusal_without_resending(self) -> None: server = _Server() server.respond = _refuse_access_1 - management = AsyncManagementClient( + inference = AsyncInferenceClient( credentials=server.async_credentials(), base_url_override=_BASE_URL ) - management.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] - await management.api.get_organizations_me() - assert server.authorizations == ["Bearer access-1", "Bearer access-2"] + inference.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] + response = await inference.http_client.get("/predict") + assert response.status_code == 401 + assert server.authorizations == ["Bearer access-1"] + + def test_accepts_own_credentials(self) -> None: + seen: list[AccessTokenOptions] = [] - def test_sends_once_for_source_without_invalidation(self) -> None: - class Source: - def access_token(self) -> AccessToken: + class Own: + def access_token(self, options: AccessTokenOptions) -> AccessToken: + seen.append(options) return AccessToken( - token="access-1", expires_at=datetime.now(UTC) + timedelta(hours=1) + token="own", expires_at=datetime.now(UTC) + timedelta(hours=1) ) server = _Server() - server.respond = _refuse_access_1 - management = _management(server, Source()) - with pytest.raises(baseten.client.managementapi.ResponseError): - management.api.get_organizations_me() - assert server.authorizations == ["Bearer access-1"] + _management(server, Own()).api.get_organizations_me() + assert server.authorizations == ["Bearer own"] + assert seen == [AccessTokenOptions()] def test_leaves_other_hosts_alone(self) -> None: server = _Server() diff --git a/tests/sandbox/test_auth.py b/tests/sandbox/test_auth.py index fa5b8f5..6fe96f5 100644 --- a/tests/sandbox/test_auth.py +++ b/tests/sandbox/test_auth.py @@ -69,13 +69,14 @@ def handle(self, request: httpx.Request) -> httpx.Response: def tokens(self, *, api_key: str = "key", provider=None) -> TokenSource: return TokenSource( - api_key=api_key, token_provider=provider, mint_api=baseten.client.managementapi.ApiClient( httpx.Client(transport=httpx.MockTransport(self.handle)), base_url="https://api.test", headers={"Authorization": f"Bearer {api_key}"}, - ), + ) + if api_key + else None, ) @@ -148,10 +149,6 @@ def provider(context: SandboxTokenProviderContext) -> str: assert tokens.token(revoked_token="provided-1") == "provided-2" assert [context.revoked_token for context in contexts] == [None, "provided-1"] - def test_rejects_api_key_alongside_provider(self) -> None: - with pytest.raises(ValueError, match="api_key must be empty"): - _Server().tokens(provider=lambda context: "token") - def test_no_token_for_empty_api_key_without_provider(self) -> None: server = _Server() assert server.tokens(api_key="").token() is None @@ -274,16 +271,18 @@ def test_does_not_resend_other_401(self) -> None: assert _get(server, server.tokens()).status_code == 401 assert len(server.requests) == 1 - def test_does_not_resend_stream_body(self) -> None: + def test_does_not_resend_stream_body_but_drops_its_token(self) -> None: server = _Server(respond=_revoked) + tokens = server.tokens() with httpx.Client(transport=httpx.MockTransport(server.handle)) as client: response = client.post( "https://sbx.test/upload", content=iter([b"chunk"]), - auth=TokenAuth(server.tokens()), + auth=TokenAuth(tokens), ) assert response.status_code == 401 assert len(server.requests) == 1 + assert tokens.token() == "token-2" def test_sends_no_authorization_without_token(self) -> None: server = _Server() @@ -350,11 +349,12 @@ async def handle(request: httpx.Request) -> httpx.Response: return server.handle(request) return AsyncTokenSource( - api_key=api_key, token_provider=provider, mint_api=baseten.client.managementapi.AsyncApiClient( httpx.AsyncClient(transport=httpx.MockTransport(handle)), base_url="https://api.test", headers={"Authorization": f"Bearer {api_key}"}, - ), + ) + if api_key + else None, ) diff --git a/tests/sandbox/test_client.py b/tests/sandbox/test_client.py index 2cceea0..d3e233f 100644 --- a/tests/sandbox/test_client.py +++ b/tests/sandbox/test_client.py @@ -10,6 +10,7 @@ import pytest import baseten.sandbox._client +from baseten.client import AccessToken, AccessTokenOptions from baseten.sandbox import ( AsyncSandboxClient, SandboxAPIError, @@ -34,6 +35,7 @@ def __init__(self) -> None: self.requests: list[httpx.Request] = [] self.authorizations: list[str | None] = [] self.mints = 0 + self.mint_authorizations: list[str | None] = [] self.routes: dict[ tuple[str, str], Callable[[httpx.Request], httpx.Response] ] = {} @@ -67,6 +69,7 @@ def route( def handle(self, request: httpx.Request) -> httpx.Response: if request.url.path == "/v1/token": self.mints += 1 + self.mint_authorizations.append(request.headers.get("Authorization")) return httpx.Response( 200, json={ @@ -102,6 +105,18 @@ async def handle(request: httpx.Request) -> httpx.Response: ) +class _Credentials: + def access_token(self, options: AccessTokenOptions) -> AccessToken: + return AccessToken( + token="access-token", expires_at=datetime.now(UTC) + timedelta(hours=1) + ) + + +class _AsyncCredentials: + async def access_token(self, options: AccessTokenOptions) -> AccessToken: + return _Credentials().access_token(options) + + def _record(name: str = "sbx", **fields: Any) -> dict[str, Any]: return { "name": name, @@ -378,6 +393,37 @@ def test_deletes_and_returns_record(self) -> None: ) assert api.client().delete(name="sbx").status == "DELETING" + def test_mints_sandbox_token_with_credentials(self) -> None: + api = _Api() + api.route("GET", "/v1/sandboxes/instances/sbx", _record()) + client = SandboxClient( + credentials=_Credentials(), + base_url_override="https://api.test", + http_client_override=httpx.Client( + transport=httpx.MockTransport(api.handle) + ), + ) + client.get(name="sbx") + assert api.mint_authorizations == ["Bearer access-token"] + assert api.authorizations == ["Bearer token-1"] + + def test_validates_auth_options(self) -> None: + def provider(context: object) -> str: + return "t" + + with pytest.raises(ValueError, match="only one of"): + SandboxClient(api_key="key", credentials=_Credentials()) + with pytest.raises(ValueError, match="only one of"): + SandboxClient(api_key="key", token_provider=provider) + with pytest.raises(ValueError, match="only one of"): + SandboxClient(credentials=_Credentials(), token_provider=provider) + with pytest.raises(ValueError, match="required"): + SandboxClient() + with pytest.raises(ValueError, match="Authorization"): + SandboxClient( + credentials=_Credentials(), headers={"authorization": "Bearer x"} + ) + def test_closes_only_its_own_http_client(self) -> None: own = SandboxClient(api_key="key", http2=False) own.close() @@ -436,6 +482,25 @@ async def test_converts_error_responses(self) -> None: await api.async_client().delete(name="sbx") assert info.value.code == "NOT_FOUND" + @pytest.mark.asyncio + async def test_mints_sandbox_token_with_credentials(self) -> None: + api = _Api() + api.route("GET", "/v1/sandboxes/instances/sbx", _record()) + + async def handle(request: httpx.Request) -> httpx.Response: + return api.handle(request) + + client = AsyncSandboxClient( + credentials=_AsyncCredentials(), + base_url_override="https://api.test", + http_client_override=httpx.AsyncClient( + transport=httpx.MockTransport(handle) + ), + ) + await client.get(name="sbx") + assert api.mint_authorizations == ["Bearer access-token"] + assert api.authorizations == ["Bearer token-1"] + @pytest.mark.asyncio async def test_closes_only_its_own_http_client(self) -> None: own = AsyncSandboxClient(api_key="key", http2=False) From 965c65cda036e8f2b1dfbeebb937b3017ae5bca7 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Tue, 17 Nov 2026 01:44:49 -0500 Subject: [PATCH 03/14] Resend sandbox requests only on TOKEN_REVOKED, as before Co-Authored-By: Claude Opus 5.5 --- baseten/client/_token_auth.py | 11 +++-------- tests/client/test_token_auth.py | 8 ++------ tests/sandbox/test_auth.py | 14 +++++--------- 3 files changed, 10 insertions(+), 23 deletions(-) diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py index c776500..27af43a 100644 --- a/baseten/client/_token_auth.py +++ b/baseten/client/_token_auth.py @@ -293,15 +293,10 @@ def is_token_refused(response: httpx.Response) -> bool: was done, so sending it again with a new token is safe even when it has side effects. """ - if response.status_code != 401: - return False # Sandboxes, and the control plane for sandbox tokens, send this header. - if response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED": - return True - # The RFC 6750 response to a refused access token. - return any( - 'error="invalid_token"' in challenge - for challenge in response.headers.get_list("www-authenticate") + return ( + response.status_code == 401 + and response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED" ) diff --git a/tests/client/test_token_auth.py b/tests/client/test_token_auth.py index 35fe63e..7745ab8 100644 --- a/tests/client/test_token_auth.py +++ b/tests/client/test_token_auth.py @@ -186,14 +186,10 @@ async def test_invalidate_keeps_newer_token(self) -> None: ("status", "headers", "refused"), [ (401, {"x-blaxel-error-code": "TOKEN_REVOKED"}, True), - ( - 401, - {"WWW-Authenticate": 'Bearer realm="baseten", error="invalid_token"'}, - True, - ), + (401, {"WWW-Authenticate": 'Bearer error="invalid_token"'}, False), (401, {}, False), (401, {"WWW-Authenticate": 'Bearer realm="baseten"'}, False), - (403, {"WWW-Authenticate": 'Bearer error="invalid_token"'}, False), + (403, {"x-blaxel-error-code": "TOKEN_REVOKED"}, False), ], ) def test_is_token_refused(status: int, headers: dict[str, str], refused: bool) -> None: diff --git a/tests/sandbox/test_auth.py b/tests/sandbox/test_auth.py index 6fe96f5..1c46002 100644 --- a/tests/sandbox/test_auth.py +++ b/tests/sandbox/test_auth.py @@ -224,17 +224,13 @@ def test_resends_with_new_token_after_revocation(self) -> None: "Bearer token-2", ] - def test_resends_with_new_token_after_invalid_token(self) -> None: + def test_does_not_resend_after_invalid_token_challenge(self) -> None: server = _Server() - server.respond = lambda request: ( - httpx.Response( - 401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'} - ) - if len(server.requests) == 1 - else httpx.Response(200) + server.respond = lambda request: httpx.Response( + 401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'} ) - assert _get(server, server.tokens()).status_code == 200 - assert server.authorizations == ["Bearer token-1", "Bearer token-2"] + assert _get(server, server.tokens()).status_code == 401 + assert server.authorizations == ["Bearer token-1"] def test_tells_caching_provider_which_token_was_revoked(self) -> None: server = _Server() From c81661839e0f449b4be6e435931681c42a64bc50 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Tue, 17 Nov 2026 01:53:49 -0500 Subject: [PATCH 04/14] Share failed-mint retries, fall back to the previous token, and tighten credentials The token caches now give a caller that joined a failed mint one more try, shared with the others that joined it, instead of one full mint per waiter in turn. When a refresh fails, the replaced token is used while still unexpired. Access tokens are left out of reprs, the credentials origin check compares the scheme, and a client given both credentials and an HTTP client override sends the token to that client's base URL. The exchange timeout is a timedelta like the other durations, the async credentials read the token file off the event loop, and blank trust rule IDs and empty token file paths are refused. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_inference.py | 23 ++- baseten/client/_management.py | 23 ++- baseten/client/_token_auth.py | 212 +++++++++++++++++++------ baseten/client/_workload_identity.py | 49 +++--- tests/client/test_token_auth.py | 139 ++++++++++++++++ tests/client/test_workload_identity.py | 87 +++++++++- 6 files changed, 456 insertions(+), 77 deletions(-) diff --git a/baseten/client/_inference.py b/baseten/client/_inference.py index 0f0185e..9976bd2 100644 --- a/baseten/client/_inference.py +++ b/baseten/client/_inference.py @@ -13,6 +13,7 @@ Credentials, CredentialsAuth, check_client_auth, + credentials_origin, ) from baseten.client._user_agent import with_user_agent @@ -127,6 +128,10 @@ def __init__( http_client_override: Pre-configured httpx client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when @@ -145,7 +150,12 @@ def __init__( auth = ( None if credentials is None - else CredentialsAuth(credentials, origin=self._options.base_url) + else CredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} @@ -256,6 +266,10 @@ def __init__( http_client_override: Pre-configured httpx async client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when @@ -274,7 +288,12 @@ def __init__( auth = ( None if credentials is None - else AsyncCredentialsAuth(credentials, origin=self._options.base_url) + else AsyncCredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} diff --git a/baseten/client/_management.py b/baseten/client/_management.py index 3aff3a5..4e70910 100644 --- a/baseten/client/_management.py +++ b/baseten/client/_management.py @@ -13,6 +13,7 @@ Credentials, CredentialsAuth, check_client_auth, + credentials_origin, ) from baseten.client._user_agent import with_user_agent @@ -83,6 +84,10 @@ def __init__( http_client_override: Pre-configured httpx client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when @@ -98,7 +103,12 @@ def __init__( auth = ( None if credentials is None - else CredentialsAuth(credentials, origin=self._options.base_url) + else CredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} @@ -192,6 +202,10 @@ def __init__( http_client_override: Pre-configured httpx async client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when @@ -207,7 +221,12 @@ def __init__( auth = ( None if credentials is None - else AsyncCredentialsAuth(credentials, origin=self._options.base_url) + else AsyncCredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py index 27af43a..cee77f0 100644 --- a/baseten/client/_token_auth.py +++ b/baseten/client/_token_auth.py @@ -12,7 +12,7 @@ import threading import time from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta from typing import Protocol @@ -23,8 +23,8 @@ class AccessToken: """A short-lived Baseten access token, sent as ``Authorization: Bearer``.""" - token: str - """The bearer token.""" + token: str = field(repr=False) + """The bearer token, left out of the repr so logging it does not leak it.""" expires_at: datetime """When the token expires.""" @@ -83,12 +83,21 @@ def _cached( ) +class _Mint: + """One call to a :class:`TokenCache`'s mint; its result is set before *done*.""" + + def __init__(self) -> None: + self.done = threading.Event() + self.result: _CachedToken | None = None + self.error: BaseException | None = None + + class TokenCache: """Holds one token and mints a new one when it is due for refresh. - Safe for use from several threads. Concurrent callers on a cold cache share - one mint. *mint* must bound its own duration, since every waiting caller - waits on it. + Safe for use from several threads. Concurrent callers share one mint, + which runs on the thread of the caller that started it. *mint* must bound + its own duration, since every waiting caller waits on it. """ def __init__( @@ -103,33 +112,96 @@ def __init__( self._refresh_leeway = refresh_leeway self._now = now self._lock = threading.Lock() - self._current: _CachedToken | None = None + self._current: _Mint | None = None + # The token last dropped for being due for refresh. Still valid until + # it expires, so it stands in when the refresh fails. + self._previous: AccessToken | None = None def token(self) -> AccessToken: """Return the cached token, minting one when none is cached or it is due.""" - # Held across the mint, so a burst on a cold cache sends one mint. A - # caller that waited on a failed mint then makes one of its own. - with self._lock: - current = self._current - if current is not None and self._now() < current.refresh_at: - return current.token - minted_at = self._now() - token = self._mint() - self._current = _cached( - token, minted_at=minted_at, refresh_leeway=self._refresh_leeway - ) - # Returned even if already due, so a skewed clock cannot make every - # call mint. - return token + joined_failure = False + while True: + with self._lock: + mint = self._current + started = mint is None + if mint is None: + mint = _Mint() + self._current = mint + if started: + self._run_mint(mint) + else: + mint.done.wait() + if mint.error is not None: + # Interrupted rather than failed, so the starter's own + # exception is not raised on another thread. + if not started and not isinstance(mint.error, Exception): + continue + # Another caller's failed mint gets one more try, which may + # be this caller's own or one shared with other such callers; + # the failed one already left the cache. + if not started and not joined_failure: + joined_failure = True + continue + fallback = self._fallback() + if fallback is not None: + return fallback + raise mint.error + assert mint.result is not None + # A token this caller just minted is used even if already due, so + # a skewed clock cannot loop here forever. + if started or self._now() < mint.result.refresh_at: + return mint.result.token + with self._lock: + if self._current is mint: + self._current = None + self._previous = mint.result.token def invalidate(self, token: str) -> None: """Drop *token* if it is still the cached one.""" with self._lock: + if self._previous is not None and self._previous.token == token: + self._previous = None + current = self._current # Compared by value, so a refusal of an older token never discards - # a newer one another caller already minted. - if self._current is not None and self._current.token.token == token: + # a newer one another caller already minted. One still minting is + # newer than any token a caller could have sent. + if ( + current is not None + and current.result is not None + and current.result.token.token == token + ): self._current = None + def _fallback(self) -> AccessToken | None: + # A refresh that fails while the replaced token is still valid falls + # back to it, so a brief outage of the minting endpoint does not fail + # requests the old token can still serve. + with self._lock: + previous = self._previous + if previous is not None and self._now() < previous.expires_at: + return previous + return None + + def _run_mint(self, mint: _Mint) -> None: + """Run *mint*, keeping a ``KeyboardInterrupt`` or the like propagating.""" + try: + minted_at = self._now() + mint.result = _cached( + self._mint(), minted_at=minted_at, refresh_leeway=self._refresh_leeway + ) + with self._lock: + self._previous = None + except BaseException as e: + mint.error = e + # Not cached, so the next caller tries again. + with self._lock: + if self._current is mint: + self._current = None + if not isinstance(e, Exception): + raise + finally: + mint.done.set() + class AsyncTokenCache: """Async form of :class:`TokenCache`. @@ -149,55 +221,73 @@ def __init__( self._mint = mint self._refresh_leeway = refresh_leeway self._now = now - self._current: _CachedToken | None = None - self._minting: asyncio.Task[_CachedToken] | None = None + self._current: asyncio.Task[_CachedToken] | None = None + # As in TokenCache. + self._previous: AccessToken | None = None async def token(self) -> AccessToken: """Return the cached token, as :meth:`TokenCache.token` does.""" + joined_failure = False while True: - current = self._current - if current is not None and self._now() < current.refresh_at: - return current.token - started = self._minting is None - if self._minting is None: - self._minting = asyncio.create_task(self._run_mint()) + task = self._current + started = task is None + if task is None: + task = asyncio.create_task(self._run_mint()) # Retrieved here so a failure no caller is left to see is not # reported as never retrieved. - self._minting.add_done_callback( - lambda task: task.cancelled() or task.exception() - ) + task.add_done_callback(lambda t: t.cancelled() or t.exception()) + self._current = task try: - minted = await asyncio.shield(self._minting) + minted = await asyncio.shield(task) except Exception: - # Another caller's failed mint gets one more try of this - # caller's own; the failed one already left the cache. - if started: - raise - continue + # As in TokenCache: at most one more try after joining + # another caller's failed mint. + if not started and not joined_failure: + joined_failure = True + continue + previous = self._previous + if previous is not None and self._now() < previous.expires_at: + return previous + raise # A token this caller just minted is used even if already due, so # a skewed clock cannot loop here forever. if started or self._now() < minted.refresh_at: return minted.token - if self._current is minted: + if self._current is task: self._current = None + self._previous = minted.token def invalidate(self, token: str) -> None: """Drop *token* if it is still the cached one.""" + if self._previous is not None and self._previous.token == token: + self._previous = None + current = self._current # Compared by value, so a refusal of an older token never discards a # newer one another caller already minted. - if self._current is not None and self._current.token.token == token: + if ( + current is not None + and current.done() + and not current.cancelled() + and current.exception() is None + and current.result().token.token == token + ): self._current = None async def _run_mint(self) -> _CachedToken: try: minted_at = self._now() - token = await self._mint() - self._current = _cached( - token, minted_at=minted_at, refresh_leeway=self._refresh_leeway + minted = _cached( + await self._mint(), + minted_at=minted_at, + refresh_leeway=self._refresh_leeway, ) - return self._current - finally: - self._minting = None + except BaseException: + # Not cached, so the next caller tries again. + if self._current is asyncio.current_task(): + self._current = None + raise + self._previous = None + return minted # A few resends cover a new token being invalidated in the same event as the @@ -313,9 +403,9 @@ def __init__(self, credentials: Credentials, *, origin: str) -> None: Args: credentials: Supplies the token. - origin: Only requests to this URL's host and port that carry no - Authorization of their own are authenticated, so a token never - reaches another host through a shared HTTP client. + origin: Only requests to this URL's scheme, host and port that + carry no Authorization of their own are authenticated, so a + token never reaches another host through a shared HTTP client. """ if inspect.iscoroutinefunction(credentials.access_token): raise TypeError( @@ -356,9 +446,27 @@ async def async_auth_flow( yield request +def credentials_origin( + http_client_override: httpx.Client | httpx.AsyncClient | None, + base_url: Callable[[], str], +) -> str: + """Return the origin a client's credentials are sent to. + + The API client sends its requests to *http_client_override*'s base URL + when it has one, so that is where the token must go; *base_url* is + called only otherwise, since an inference client given an override may + have no model or chain to compute one from. + """ + if http_client_override is not None and http_client_override.base_url.host: + return str(http_client_override.base_url) + return base_url() + + def _applies_to(request: httpx.Request, origin: httpx.URL) -> bool: + # Scheme too, so a token meant for https is never sent in the clear. return ( - request.url.host == origin.host + request.url.scheme == origin.scheme + and request.url.host == origin.host and request.url.port == origin.port and "Authorization" not in request.headers ) diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 07d9d0e..90c2f53 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -9,6 +9,7 @@ import httpx +from baseten.client._management import ManagementClient from baseten.client._token_auth import ( AccessToken, AccessTokenOptions, @@ -23,8 +24,6 @@ _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" _JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" -_DEFAULT_BASE_URL = "https://api.baseten.co" - IdentityTokenProvider: TypeAlias = Callable[[], str] """Returns the identity provider's JWT. Called on every exchange.""" @@ -43,25 +42,30 @@ def __init__( has_identity_token: bool, base_url_override: str | None, refresh_leeway: timedelta, - exchange_timeout_sec: float, + exchange_timeout: timedelta, ) -> None: if (identity_token_file is None) == (not has_identity_token): raise ValueError( "exactly one of identity_token_file and identity_token is required" ) - if trust_rule_id == "": + if identity_token_file is not None and os.fspath(identity_token_file) == "": + raise ValueError("identity_token_file must not be empty") + if trust_rule_id.strip() == "": raise ValueError("trust_rule_id is required") if refresh_leeway < timedelta(0): raise ValueError("refresh_leeway must not be negative") - if exchange_timeout_sec <= 0: - raise ValueError("exchange_timeout_sec must be positive") + if exchange_timeout <= timedelta(0): + raise ValueError("exchange_timeout must be positive") self.trust_rule_id = trust_rule_id self.identity_token_file = ( None if identity_token_file is None else Path(identity_token_file) ) - base_url = (base_url_override or _DEFAULT_BASE_URL).rstrip("/") + base_url = (base_url_override or ManagementClient.default_base_url()).rstrip( + "/" + ) self.url = f"{base_url}/v1/auth/token" - self.timeout = httpx.Timeout(exchange_timeout_sec) + self.timeout_sec = exchange_timeout.total_seconds() + self.timeout = httpx.Timeout(self.timeout_sec) self.headers = with_user_agent({"Accept": "application/json"}) def read_identity_token_file(self) -> str: @@ -180,7 +184,7 @@ def __init__( identity_token: IdentityTokenProvider | None = None, base_url_override: str | None = None, refresh_leeway: timedelta = timedelta(minutes=5), - exchange_timeout_sec: float = 10.0, + exchange_timeout: timedelta = timedelta(seconds=10), http_client_override: httpx.Client | None = None, ) -> None: """Validate the options. Baseten is not contacted until first use. @@ -196,11 +200,14 @@ def __init__( identity_token: Returns the identity provider's JWT. Called on every exchange. base_url_override: Management API base URL the exchange is sent - to. ``None`` uses ``https://api.baseten.co``. + to. ``None`` uses :meth:`ManagementClient.default_base_url`. + Must point at the same Baseten environment as the clients + given these credentials, since a token is accepted only by + the environment that issued it. refresh_leeway: How long before expiry the access token is replaced, capped at half the token's lifetime so a short-lived token is still reused. - exchange_timeout_sec: Bounds each phase of one exchange, which + exchange_timeout: Bounds each phase of one exchange, which every caller waiting for a token shares. http_client_override: HTTP client to send the exchange with. ``None`` uses a new one per exchange. @@ -211,7 +218,7 @@ def __init__( has_identity_token=identity_token is not None, base_url_override=base_url_override, refresh_leeway=refresh_leeway, - exchange_timeout_sec=exchange_timeout_sec, + exchange_timeout=exchange_timeout, ) self._identity_token = identity_token self._http_client = http_client_override @@ -258,13 +265,13 @@ def __init__( identity_token: AsyncIdentityTokenProvider | None = None, base_url_override: str | None = None, refresh_leeway: timedelta = timedelta(minutes=5), - exchange_timeout_sec: float = 10.0, + exchange_timeout: timedelta = timedelta(seconds=10), http_client_override: httpx.AsyncClient | None = None, ) -> None: """Validate the options, as :class:`WorkloadIdentityCredentials` does. - Here *exchange_timeout_sec* bounds the whole exchange, including - *identity_token*. + Here *exchange_timeout* bounds the whole exchange, including + *identity_token* and reading *identity_token_file*. """ self._exchange = _Exchange( trust_rule_id=trust_rule_id, @@ -272,11 +279,10 @@ def __init__( has_identity_token=identity_token is not None, base_url_override=base_url_override, refresh_leeway=refresh_leeway, - exchange_timeout_sec=exchange_timeout_sec, + exchange_timeout=exchange_timeout, ) self._identity_token = identity_token self._http_client = http_client_override - self._exchange_timeout_sec = exchange_timeout_sec # Replaced in tests. self._now: Callable[[], datetime] = _utc_now self._cache = AsyncTokenCache( @@ -291,19 +297,22 @@ async def access_token(self, options: AccessTokenOptions) -> AccessToken: async def _exchange_token(self) -> AccessToken: try: - async with asyncio.timeout(self._exchange_timeout_sec): + async with asyncio.timeout(self._exchange.timeout_sec): return await self._exchange_once() except TimeoutError as e: raise TimeoutError( "workload identity token exchange timed out after " - f"{self._exchange_timeout_sec}s" + f"{self._exchange.timeout_sec}s" ) from e async def _exchange_once(self) -> AccessToken: if self._identity_token is not None: identity_token = await self._identity_token() else: - identity_token = self._exchange.read_identity_token_file() + # Off the event loop, since the file system can be slow. + identity_token = await asyncio.to_thread( + self._exchange.read_identity_token_file + ) post_kwargs = self._exchange.post_kwargs(self._exchange.body(identity_token)) # Taken before sending, so the computed expiry errs early. issued_at = self._now() diff --git a/tests/client/test_token_auth.py b/tests/client/test_token_auth.py index 7745ab8..19d6def 100644 --- a/tests/client/test_token_auth.py +++ b/tests/client/test_token_auth.py @@ -2,6 +2,7 @@ import asyncio import threading +import time from datetime import UTC, datetime, timedelta import httpx @@ -11,9 +12,15 @@ from baseten.client._token_auth import ( AsyncTokenCache, TokenCache, + _applies_to, + _cached, is_token_refused, ) +# How long each mint in the concurrency tests takes, long enough for every +# caller to be waiting on the first one. +_SLOW_MINT_SEC = 0.2 + class _Clock: def __init__(self) -> None: @@ -130,6 +137,71 @@ def first() -> None: assert len(errors) == 1 assert results == ["token-2"] + def test_concurrent_callers_on_failing_mint_share_one_retry(self) -> None: + calls = 0 + + def mint() -> AccessToken: + nonlocal calls + calls += 1 + time.sleep(_SLOW_MINT_SEC) + raise RuntimeError("mint failed") + + cache = TokenCache(mint=mint, refresh_leeway=timedelta(minutes=1)) + errors: list[BaseException] = [] + + def call() -> None: + try: + cache.token() + except RuntimeError as e: + errors.append(e) + + threads = [threading.Thread(target=call) for _ in range(8)] + started = time.monotonic() + for thread in threads: + thread.start() + for thread in threads: + thread.join() + elapsed = time.monotonic() - started + assert len(errors) == 8 + # One failed mint, then one retry shared by everyone who joined it, + # rather than one mint per caller in turn. + assert calls == 2 + assert elapsed < 3 * _SLOW_MINT_SEC + + def test_failed_refresh_falls_back_to_previous_token(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + assert cache.token().token == "token-1" + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-1" + assert cache.token().token == "token-3" + # The successful mint dropped the fallback. + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-3" + + def test_no_fallback_once_previous_expired(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + cache.token() + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-1" + clock.now += timedelta(minutes=4) + mints.failures = 1 + with pytest.raises(RuntimeError): + cache.token() + + def test_invalidate_clears_previous_token(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + cache.token() + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-1" + cache.invalidate("token-1") + mints.failures = 1 + with pytest.raises(RuntimeError): + cache.token() + class TestAsyncTokenCache: @pytest.mark.asyncio @@ -181,6 +253,73 @@ async def test_invalidate_keeps_newer_token(self) -> None: cache.invalidate("token-1") assert (await cache.token()).token == "token-2" + @pytest.mark.asyncio + async def test_concurrent_callers_on_failing_mint_share_one_retry(self) -> None: + calls = 0 + + async def mint() -> AccessToken: + nonlocal calls + calls += 1 + await asyncio.sleep(_SLOW_MINT_SEC) + raise RuntimeError("mint failed") + + cache = AsyncTokenCache(mint=mint, refresh_leeway=timedelta(minutes=1)) + started = time.monotonic() + results = await asyncio.gather( + *(cache.token() for _ in range(8)), return_exceptions=True + ) + elapsed = time.monotonic() - started + assert all(isinstance(result, RuntimeError) for result in results) + assert calls == 2 + assert elapsed < 3 * _SLOW_MINT_SEC + + @pytest.mark.asyncio + async def test_failed_refresh_falls_back_to_previous_token(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + cache = AsyncTokenCache( + mint=mints.mint_async, refresh_leeway=timedelta(minutes=5), now=clock + ) + await cache.token() + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert (await cache.token()).token == "token-1" + cache.invalidate("token-1") + mints.failures = 1 + with pytest.raises(RuntimeError): + await cache.token() + assert (await cache.token()).token == "token-4" + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert (await cache.token()).token == "token-4" + clock.now += timedelta(minutes=4) + mints.failures = 1 + with pytest.raises(RuntimeError): + await cache.token() + + +@pytest.mark.parametrize( + ("url", "applies"), + [ + ("https://api.test/x", True), + ("http://api.test/x", False), + ("https://api.test:8443/x", False), + ("https://other.test/x", False), + ], +) +def test_applies_only_to_origin(url: str, applies: bool) -> None: + origin = httpx.URL("https://api.test") + assert _applies_to(httpx.Request("GET", url), origin) is applies + + +def test_access_token_repr_hides_token() -> None: + token = AccessToken( + token="secret-bearer", expires_at=datetime(2026, 1, 1, tzinfo=UTC) + ) + assert "secret-bearer" not in repr(token) + cached = _cached(token, minted_at=token.expires_at, refresh_leeway=timedelta(0)) + assert "secret-bearer" not in repr(cached) + @pytest.mark.parametrize( ("status", "headers", "refused"), diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index 8afcc8e..6690415 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -2,6 +2,7 @@ import asyncio import json +import socket from collections.abc import Callable from datetime import UTC, datetime, timedelta from pathlib import Path @@ -236,6 +237,21 @@ def test_does_not_follow_redirects(self) -> None: credentials.access_token(_OPTIONS) assert server.assertions == ["idp-jwt"] + def test_exchange_timeout(self) -> None: + # Accepts the connection but never answers it. + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen() + host, port = listener.getsockname() + credentials = WorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=lambda: "idp-jwt", + base_url_override=f"http://{host}:{port}", + exchange_timeout=timedelta(milliseconds=100), + ) + with pytest.raises(httpx.TimeoutException): + credentials.access_token(_OPTIONS) + @pytest.mark.parametrize( "body", [ @@ -256,6 +272,13 @@ def test_malformed_success(self, body: dict[str, object]) -> None: {"trust_rule_id": "r"}, {"trust_rule_id": "r", "identity_token_file": "/f", "identity_token": str}, {"trust_rule_id": "", "identity_token": str}, + {"trust_rule_id": " ", "identity_token": str}, + {"trust_rule_id": "r", "identity_token_file": ""}, + { + "trust_rule_id": "r", + "identity_token": str, + "exchange_timeout": timedelta(0), + }, { "trust_rule_id": "r", "identity_token": str, @@ -321,11 +344,44 @@ async def identity_token() -> str: return "never" credentials = _Server().async_credentials( - identity_token=identity_token, exchange_timeout_sec=0.01 + identity_token=identity_token, + exchange_timeout=timedelta(milliseconds=10), ) with pytest.raises(TimeoutError, match="timed out"): await credentials.access_token(_OPTIONS) + @pytest.mark.asyncio + async def test_invalid_grant_is_explained(self) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response( + 400, json={"error": "invalid_grant"} + ) + with pytest.raises(ResponseError) as exc_info: + await server.async_credentials().access_token(_OPTIONS) + assert exc_info.value.status_code == 400 + (note,) = exc_info.value.__notes__ + assert "trust rule rule-1" in note + + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("response", "match"), + [ + (httpx.Response(200, text=""), "not JSON"), + (httpx.Response(200, json=["a"]), "no access_token"), + ( + httpx.Response(200, json={"access_token": "a", "token_type": "Bearer"}), + "expires_in", + ), + ], + ) + async def test_malformed_success( + self, response: httpx.Response, match: str + ) -> None: + server = _Server() + server.exchange_response = lambda: response + with pytest.raises(ValueError, match=match): + await server.async_credentials().access_token(_OPTIONS) + @pytest.mark.asyncio async def test_rereads_token_file(self, tmp_path: Path) -> None: server = _Server(expires_in=600) @@ -439,6 +495,35 @@ def test_redirect_to_other_host_drops_token(self) -> None: management.http_client.get("/start", follow_redirects=True) assert server.authorizations == ["Bearer access-1", None] + def test_management_with_http_client_override(self) -> None: + server = _Server() + http_client = httpx.Client( + base_url=_BASE_URL, transport=httpx.MockTransport(server.handle) + ) + # No base_url_override: the token goes where the override sends + # requests, not to the default base URL. + management = ManagementClient( + credentials=server.credentials(), http_client_override=http_client + ) + management.api.get_organizations_me() + # Only the API client authenticates; the HTTP client is the caller's. + management.http_client.get("/direct") + assert server.authorizations == ["Bearer access-1", None] + + def test_inference_with_http_client_override(self) -> None: + server = _Server() + server.respond = lambda request: httpx.Response(202) + http_client = httpx.Client( + base_url="https://model-x.api.test", + transport=httpx.MockTransport(server.handle), + ) + # Neither model_id nor chain_id, which only the default URL needs. + inference = InferenceClient( + credentials=server.credentials(), http_client_override=http_client + ) + inference.api.wake(env_name="production") + assert server.authorizations == ["Bearer access-1"] + def test_validates_auth_options(self) -> None: credentials = _Server().credentials() with pytest.raises(ValueError, match="mutually exclusive"): From 23c0d442db42847b2f69c3312f7edeb288127640 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Wed, 18 Nov 2026 14:36:37 -0500 Subject: [PATCH 05/14] Replace an access token Baseten refused, and move the sandbox resend back to sandbox A 401 with WWW-Authenticate: Bearer realm="baseten", error="invalid_token" comes only from Baseten's auth layer, so the client passes that token as refused_token on the next access_token call and the workload identity credentials drop it. The refused request is not sent again. TokenAuth, AsyncTokenAuth and is_token_refused had only the sandbox client left as a caller, so they move into the sandbox package. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_token_auth.py | 173 ++++++++----------------- baseten/client/_workload_identity.py | 4 + baseten/sandbox/_auth.py | 105 +++++++++++++-- tests/client/test_token_auth.py | 15 --- tests/client/test_workload_identity.py | 56 +++++--- tests/sandbox/test_auth.py | 22 +++- 6 files changed, 208 insertions(+), 167 deletions(-) diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py index cee77f0..729366a 100644 --- a/baseten/client/_token_auth.py +++ b/baseten/client/_token_auth.py @@ -1,8 +1,7 @@ """What every short-lived Baseten token needs. -A cache that mints a new token shortly before the current one expires, an -:class:`httpx.Auth` that sends a token from :class:`Credentials`, and one that -sends a request again with a new token when the server refuses the current one. +A cache that mints a new token shortly before the current one expires, and an +:class:`httpx.Auth` that sends a token from :class:`Credentials`. """ from __future__ import annotations @@ -10,7 +9,6 @@ import asyncio import inspect import threading -import time from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapping from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta @@ -32,9 +30,12 @@ class AccessToken: @dataclass(frozen=True) class AccessTokenOptions: - """What :class:`Credentials` are told about the token they are asked for. + """What :class:`Credentials` are told about the token they are asked for.""" - Has no fields yet; it lets fields be added without breaking implementations. + refused_token: str | None = field(default=None, repr=False) + """A token Baseten refused before its stated expiry. + + Credentials that cache tokens must not return it again. """ @@ -290,112 +291,13 @@ async def _run_mint(self) -> _CachedToken: return minted -# A few resends cover a new token being invalidated in the same event as the -# old one. Past that, the refusal is returned, since tokens that keep getting -# refused point at something a new token cannot fix. -_MAX_RESENDS = 2 - -# Revocation refuses every token issued before a cutoff, the time of the -# revoking event rounded up to the next whole second. A token minted right -# after the event can fall before the cutoff and be refused too, so after the -# first resend, each one waits this long to be minted past it. A module -# variable so tests can shorten it. -_resend_delay_sec = 1.0 - - -class TokenAuth(httpx.Auth): - """Authenticates requests with ``Authorization: Bearer`` from *get_token*. - - *get_token* is called with ``None``, or with the token the server just - refused, and returns the token to send, or ``None`` to send no - Authorization. When the server refuses the token (see - :func:`is_token_refused`), it is passed to *invalidate*, and the request - is sent again with a new token when its body can be, at most twice. - """ - - def __init__( - self, - get_token: Callable[[str | None], str | None], - invalidate: Callable[[str], None], - ) -> None: - """Create the auth.""" - self._get_token = get_token - self._invalidate = invalidate - - def sync_auth_flow( - self, request: httpx.Request - ) -> Generator[httpx.Request, httpx.Response, None]: - """Send the request, again with a new token if its token was refused.""" - replayable = _is_replayable(request) - refused: str | None = None - for attempt in range(_MAX_RESENDS + 1): - token = self._get_token(refused) - _set_authorization(request, token) - response = yield request - if token is None or not is_token_refused(response): - return - # Dropped even when the request is not sent again, so later - # requests do not reuse it. - self._invalidate(token) - if not replayable or attempt == _MAX_RESENDS: - return - refused = token - if attempt > 0: - time.sleep(_resend_delay_sec) - - -class AsyncTokenAuth(httpx.Auth): - """Async form of :class:`TokenAuth`.""" - - def __init__( - self, - get_token: Callable[[str | None], Awaitable[str | None]], - invalidate: Callable[[str], None], - ) -> None: - """Create the auth, as :class:`TokenAuth` does.""" - self._get_token = get_token - self._invalidate = invalidate - - async def async_auth_flow( - self, request: httpx.Request - ) -> AsyncGenerator[httpx.Request, httpx.Response]: - """Send the request, again with a new token if its token was refused.""" - replayable = _is_replayable(request) - refused: str | None = None - for attempt in range(_MAX_RESENDS + 1): - token = await self._get_token(refused) - _set_authorization(request, token) - response = yield request - if token is None or not is_token_refused(response): - return - self._invalidate(token) - if not replayable or attempt == _MAX_RESENDS: - return - refused = token - if attempt > 0: - await asyncio.sleep(_resend_delay_sec) - - -def is_token_refused(response: httpx.Response) -> bool: - """Report whether the server refused a request's token before its expiry. - - For example after it was revoked. The request was refused before any work - was done, so sending it again with a new token is safe even when it has - side effects. - """ - # Sandboxes, and the control plane for sandbox tokens, send this header. - return ( - response.status_code == 401 - and response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED" - ) - - class CredentialsAuth(httpx.Auth): """Sends a token from :class:`Credentials` on each request to one origin. A token is fetched for every request, so a long-lived client picks up refreshed tokens. Each request is sent once; a refusal is returned to the - caller as is. + caller as is, and when Baseten refused the token, the next request asks + the credentials for a new one. """ def __init__(self, credentials: Credentials, *, origin: str) -> None: @@ -413,15 +315,26 @@ def __init__(self, credentials: Credentials, *, origin: str) -> None: ) self._credentials = credentials self._origin = httpx.URL(origin) + # The last token Baseten refused, passed to the next access_token call + # so the credentials replace it. + self._refused: str | None = None def sync_auth_flow( self, request: httpx.Request ) -> Generator[httpx.Request, httpx.Response, None]: """Send the request with the current token.""" - if _applies_to(request, self._origin): - token = self._credentials.access_token(AccessTokenOptions()) - _set_authorization(request, _non_empty(token)) - yield request + if not _applies_to(request, self._origin): + yield request + return + options = AccessTokenOptions(refused_token=self._refused) + self._refused = None + token = _non_empty(self._credentials.access_token(options)) + _set_authorization(request, token) + response = yield request + # The request is not sent again, since it may have side effects; only + # the next request gets a new token. + if refused_by_baseten(response): + self._refused = token class AsyncCredentialsAuth(httpx.Auth): @@ -435,15 +348,38 @@ def __init__(self, credentials: AsyncCredentials, *, origin: str) -> None: ) self._credentials = credentials self._origin = httpx.URL(origin) + self._refused: str | None = None async def async_auth_flow( self, request: httpx.Request ) -> AsyncGenerator[httpx.Request, httpx.Response]: """Send the request with the current token.""" - if _applies_to(request, self._origin): - token = await self._credentials.access_token(AccessTokenOptions()) - _set_authorization(request, _non_empty(token)) - yield request + if not _applies_to(request, self._origin): + yield request + return + options = AccessTokenOptions(refused_token=self._refused) + self._refused = None + token = _non_empty(await self._credentials.access_token(options)) + _set_authorization(request, token) + response = yield request + if refused_by_baseten(response): + self._refused = token + + +def refused_by_baseten(response: httpx.Response) -> bool: + """Report whether Baseten's auth layer refused the request's access token. + + It signals that with this challenge. A model's own error response cannot + carry it, since its headers are not forwarded. + """ + if response.status_code != 401: + return False + return any( + challenge.startswith("Bearer ") + and 'realm="baseten"' in challenge + and 'error="invalid_token"' in challenge + for challenge in response.headers.get_list("WWW-Authenticate") + ) def credentials_origin( @@ -472,13 +408,6 @@ def _applies_to(request: httpx.Request, origin: httpx.URL) -> bool: ) -def _is_replayable(request: httpx.Request) -> bool: - """Report whether a request's body can be sent again.""" - # A stream body can be read only once, so a request carrying one is never - # sent again. The SDK itself never sends one; only raw API calls can. - return isinstance(request.stream, httpx.ByteStream) - - def _set_authorization(request: httpx.Request, token: str | None) -> None: if token is not None: request.headers["Authorization"] = f"Bearer {token}" diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 90c2f53..13ab6b2 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -232,6 +232,8 @@ def __init__( def access_token(self, options: AccessTokenOptions) -> AccessToken: """Return a current access token, exchanging for a new one when due.""" + if options.refused_token is not None: + self._cache.invalidate(options.refused_token) return self._cache.token() def _exchange_token(self) -> AccessToken: @@ -293,6 +295,8 @@ def __init__( async def access_token(self, options: AccessTokenOptions) -> AccessToken: """Return a current access token, exchanging for a new one when due.""" + if options.refused_token is not None: + self._cache.invalidate(options.refused_token) return await self._cache.token() async def _exchange_token(self) -> AccessToken: diff --git a/baseten/sandbox/_auth.py b/baseten/sandbox/_auth.py index 03d25b7..96d05fc 100644 --- a/baseten/sandbox/_auth.py +++ b/baseten/sandbox/_auth.py @@ -1,13 +1,21 @@ from __future__ import annotations -from collections.abc import Awaitable, Callable +import asyncio +import time +from collections.abc import AsyncGenerator, Awaitable, Callable, Generator from dataclasses import dataclass from datetime import timedelta from typing import TypeAlias -import baseten.client._token_auth +import httpx + import baseten.client.managementapi -from baseten.client._token_auth import AccessToken, AsyncTokenCache, TokenCache +from baseten.client._token_auth import ( + AccessToken, + AsyncTokenCache, + TokenCache, + _set_authorization, +) @dataclass(kw_only=True) @@ -41,6 +49,18 @@ class SandboxTokenProviderContext: # half the token's lifetime. _TOKEN_EXPIRY_LEEWAY = timedelta(seconds=60) +# A few retries cover a new token being invalidated in the same event as the +# old one. Past that, the rejection is returned, since tokens that keep getting +# rejected point at something a new token cannot fix. +_TOKEN_INVALIDATION_MAX_RETRIES = 2 + +# Revocation rejects every token issued before a cutoff, the time of the +# revoking event rounded up to the next whole second. A token minted right +# after the event can fall before the cutoff and be rejected too, so after the +# first resend, each one waits this long to be minted past it. A module +# variable so tests can shorten it. +_token_revoked_retry_delay_sec = 1.0 + TOKEN_MINT_TIMEOUT = 30.0 """Seconds that one token exchange may take. @@ -134,23 +154,88 @@ def invalidate(self, token: str) -> None: self._cache.invalidate(token) -class TokenAuth(baseten.client._token_auth.TokenAuth): - """Authenticates every request with a token from a :class:`TokenSource`.""" +class TokenAuth(httpx.Auth): + """Authenticates every request with a token from a :class:`TokenSource`. + + When the server rejects the token as revoked (see :func:`is_token_revoked`), + the request is sent again with a new one when its body can be, at most + twice. + """ def __init__(self, tokens: TokenSource) -> None: """Create the auth.""" - super().__init__(tokens.token, tokens.invalidate) self.tokens = tokens - -class AsyncTokenAuth(baseten.client._token_auth.AsyncTokenAuth): - """Authenticates every request with a token from an :class:`AsyncTokenSource`.""" + def sync_auth_flow( + self, request: httpx.Request + ) -> Generator[httpx.Request, httpx.Response, None]: + """Send the request, again with a new token if its token was revoked.""" + replayable = _is_replayable(request) + revoked: str | None = None + for retry in range(_TOKEN_INVALIDATION_MAX_RETRIES + 1): + token = self.tokens.token(revoked) + _set_authorization(request, token) + response = yield request + if token is None or not is_token_revoked(response): + return + # Dropped even when the request is not sent again, so later + # requests do not reuse it. + self.tokens.invalidate(token) + if not replayable or retry == _TOKEN_INVALIDATION_MAX_RETRIES: + return + revoked = token + if retry > 0: + time.sleep(_token_revoked_retry_delay_sec) + + +class AsyncTokenAuth(httpx.Auth): + """Async form of :class:`TokenAuth`.""" def __init__(self, tokens: AsyncTokenSource) -> None: """Create the auth.""" - super().__init__(tokens.token, tokens.invalidate) self.tokens = tokens + async def async_auth_flow( + self, request: httpx.Request + ) -> AsyncGenerator[httpx.Request, httpx.Response]: + """Send the request, again with a new token if its token was revoked.""" + replayable = _is_replayable(request) + revoked: str | None = None + for retry in range(_TOKEN_INVALIDATION_MAX_RETRIES + 1): + token = await self.tokens.token(revoked) + _set_authorization(request, token) + response = yield request + if token is None or not is_token_revoked(response): + return + self.tokens.invalidate(token) + if not replayable or retry == _TOKEN_INVALIDATION_MAX_RETRIES: + return + revoked = token + if retry > 0: + await asyncio.sleep(_token_revoked_retry_delay_sec) + + +def is_token_revoked(response: httpx.Response) -> bool: + """Report whether the server rejected a request's token as revoked. + + It can do so before the token's stated expiry, for example after a role + change. The request was rejected before any work was done, so sending it + again with a new token is safe even when it has side effects. + """ + # Both the control plane and sandboxes send this header, while their + # bodies differ. + return ( + response.status_code == 401 + and response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED" + ) + + +def _is_replayable(request: httpx.Request) -> bool: + """Report whether a request's body can be sent again.""" + # A stream body can be read only once, so a request carrying one is never + # sent again. The SDK itself never sends one; only raw API calls can. + return isinstance(request.stream, httpx.ByteStream) + def _token_cache(mint_api: baseten.client.managementapi.ApiClient) -> TokenCache: return TokenCache( diff --git a/tests/client/test_token_auth.py b/tests/client/test_token_auth.py index 19d6def..330f29b 100644 --- a/tests/client/test_token_auth.py +++ b/tests/client/test_token_auth.py @@ -14,7 +14,6 @@ TokenCache, _applies_to, _cached, - is_token_refused, ) # How long each mint in the concurrency tests takes, long enough for every @@ -319,17 +318,3 @@ def test_access_token_repr_hides_token() -> None: assert "secret-bearer" not in repr(token) cached = _cached(token, minted_at=token.expires_at, refresh_leeway=timedelta(0)) assert "secret-bearer" not in repr(cached) - - -@pytest.mark.parametrize( - ("status", "headers", "refused"), - [ - (401, {"x-blaxel-error-code": "TOKEN_REVOKED"}, True), - (401, {"WWW-Authenticate": 'Bearer error="invalid_token"'}, False), - (401, {}, False), - (401, {"WWW-Authenticate": 'Bearer realm="baseten"'}, False), - (403, {"x-blaxel-error-code": "TOKEN_REVOKED"}, False), - ], -) -def test_is_token_refused(status: int, headers: dict[str, str], refused: bool) -> None: - assert is_token_refused(httpx.Response(status, headers=headers)) is refused diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index 6690415..1f7ddf6 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -438,26 +438,44 @@ async def test_async_clients_send_the_current_token(self) -> None: await inference.http_client.get("/anything") assert server.authorizations == ["Bearer access-1", "Bearer access-1"] - def test_returns_refusal_without_resending(self) -> None: - # A 401 can come from the model itself, so it is the caller's to see. + @pytest.mark.parametrize( + ("challenge", "second"), + [ + ('Bearer realm="baseten", error="invalid_token"', "Bearer access-2"), + ('Bearer realm="model", error="invalid_token"', "Bearer access-1"), + ('Bearer realm="baseten"', "Bearer access-1"), + (None, "Bearer access-1"), + ], + ids=[ + "baseten_refusal", + "other_realm", + "authentication_required", + "no_challenge", + ], + ) + def test_sends_each_request_once(self, challenge: str | None, second: str) -> None: + # Only a refusal from Baseten's auth layer makes the next request use a + # new token; the refused request itself is the caller's to see. server = _Server() - server.respond = _refuse_access_1 + server.respond = _refuse_once(challenge) management = _management(server, server.credentials()) with pytest.raises(ResponseError, match="HTTP 401"): management.api.get_organizations_me() - assert server.authorizations == ["Bearer access-1"] + management.api.get_organizations_me() + assert server.authorizations == ["Bearer access-1", second] @pytest.mark.asyncio - async def test_async_returns_refusal_without_resending(self) -> None: + async def test_async_replaces_token_baseten_refused(self) -> None: server = _Server() - server.respond = _refuse_access_1 + server.respond = _refuse_once('Bearer realm="baseten", error="invalid_token"') inference = AsyncInferenceClient( credentials=server.async_credentials(), base_url_override=_BASE_URL ) inference.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] response = await inference.http_client.get("/predict") assert response.status_code == 401 - assert server.authorizations == ["Bearer access-1"] + await inference.http_client.get("/predict") + assert server.authorizations == ["Bearer access-1", "Bearer access-2"] def test_accepts_own_credentials(self) -> None: seen: list[AccessTokenOptions] = [] @@ -544,12 +562,18 @@ def test_validates_auth_options(self) -> None: ManagementClient(credentials=_Server().async_credentials()) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] -def _refuse_access_1(request: httpx.Request) -> httpx.Response: - if request.headers.get("Authorization") == "Bearer access-1": - return httpx.Response( - 401, - headers={ - "WWW-Authenticate": 'Bearer realm="baseten", error="invalid_token"' - }, - ) - return httpx.Response(200, json=_ORG) +def _refuse_once( + challenge: str | None, +) -> Callable[[httpx.Request], httpx.Response]: + """Answer the first request with a 401 carrying *challenge*, then succeed.""" + calls = 0 + + def respond(request: httpx.Request) -> httpx.Response: + nonlocal calls + calls += 1 + if calls == 1: + headers = {} if challenge is None else {"WWW-Authenticate": challenge} + return httpx.Response(401, headers=headers) + return httpx.Response(200, json=_ORG) + + return respond diff --git a/tests/sandbox/test_auth.py b/tests/sandbox/test_auth.py index 1c46002..db1e3a0 100644 --- a/tests/sandbox/test_auth.py +++ b/tests/sandbox/test_auth.py @@ -9,14 +9,15 @@ import httpx import pytest -import baseten.client._token_auth import baseten.client.managementapi +import baseten.sandbox._auth from baseten.sandbox import SandboxTokenProviderContext from baseten.sandbox._auth import ( AsyncTokenAuth, AsyncTokenSource, TokenAuth, TokenSource, + is_token_revoked, ) @@ -26,7 +27,7 @@ def _revoked(request: httpx.Request | None = None) -> httpx.Response: @pytest.fixture(autouse=True) def no_revoked_retry_delay(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(baseten.client._token_auth, "_resend_delay_sec", 0.0) + monkeypatch.setattr(baseten.sandbox._auth, "_token_revoked_retry_delay_sec", 0.0) class _Server: @@ -251,7 +252,7 @@ def test_returns_revocation_after_two_resends( ) -> None: delays: list[float] = [] monkeypatch.setattr( - baseten.client._token_auth.time, + baseten.sandbox._auth.time, "sleep", lambda seconds: delays.append(seconds), ) @@ -260,7 +261,7 @@ def test_returns_revocation_after_two_resends( assert response.status_code == 401 assert len(server.requests) == 3 # Only the second resend waits, to be minted past the revocation. - assert delays == [baseten.client._token_auth._resend_delay_sec] + assert delays == [baseten.sandbox._auth._token_revoked_retry_delay_sec] def test_does_not_resend_other_401(self) -> None: server = _Server(respond=lambda request: httpx.Response(401)) @@ -354,3 +355,16 @@ async def handle(request: httpx.Request) -> httpx.Response: if api_key else None, ) + + +@pytest.mark.parametrize( + ("status", "headers", "revoked"), + [ + (401, {"x-blaxel-error-code": "TOKEN_REVOKED"}, True), + (401, {"WWW-Authenticate": 'Bearer error="invalid_token"'}, False), + (401, {}, False), + (403, {"x-blaxel-error-code": "TOKEN_REVOKED"}, False), + ], +) +def test_is_token_revoked(status: int, headers: dict[str, str], revoked: bool) -> None: + assert is_token_revoked(httpx.Response(status, headers=headers)) is revoked From fcf13635d405dd7952114cf53da091bb7d60b9be Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Wed, 18 Nov 2026 23:02:08 -0500 Subject: [PATCH 06/14] Regenerate the API clients from the production spec The production management spec now documents POST /v1/auth/token, so the workload identity exchange builds its body from the generated TokenExchangeRequest. The exchange keeps its own request so it can refuse redirects, which the generated client leaves to the HTTP client. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_workload_identity.py | 20 +- baseten/client/managementapi/__init__.py | 170 +- baseten/client/managementapi/_client.py | 1136 +++- baseten/client/managementapi/_models.py | 2392 ++++++++- baseten/client/modelconfig/__init__.py | 4 + baseten/client/modelconfig/_models.py | 54 +- scripts/apigen/specs/config.schema.json | 124 +- scripts/apigen/specs/management.json | 6264 ++++++++++++++++++---- 8 files changed, 8632 insertions(+), 1532 deletions(-) diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 13ab6b2..f8cfeee 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -18,7 +18,7 @@ _utc_now, ) from baseten.client._user_agent import with_user_agent -from baseten.client.managementapi import ResponseError +from baseten.client.managementapi import ResponseError, TokenExchangeRequest # The exchange takes an RFC 8693 request naming the trust rule as its audience. _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" @@ -76,21 +76,21 @@ def read_identity_token_file(self) -> str: raise ValueError(f"identity token file {self.identity_token_file} is empty") return token - def body(self, identity_token: str) -> dict[str, str]: + def body(self, identity_token: str) -> TokenExchangeRequest: token = identity_token.strip() if token == "": raise ValueError("the identity token provider returned an empty token") - return { - "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE, - "subject_token": token, - "subject_token_type": _JWT_TOKEN_TYPE, - "audience": self.trust_rule_id, - } + return TokenExchangeRequest( + grant_type=_TOKEN_EXCHANGE_GRANT_TYPE, + subject_token=token, + subject_token_type=_JWT_TOKEN_TYPE, + audience=self.trust_rule_id, + ) - def post_kwargs(self, body: dict[str, str]) -> dict[str, Any]: + def post_kwargs(self, body: TokenExchangeRequest) -> dict[str, Any]: return { "url": self.url, - "json": body, + "json": body.model_dump(mode="json", exclude_unset=True), "headers": self.headers, "timeout": self.timeout, # The body carries the identity token, so it is never sent on to diff --git a/baseten/client/managementapi/__init__.py b/baseten/client/managementapi/__init__.py index bfadfa4..02d5265 100644 --- a/baseten/client/managementapi/__init__.py +++ b/baseten/client/managementapi/__init__.py @@ -12,6 +12,9 @@ from ._client import ApiClient, AsyncApiClient, ResponseError from ._models import ( + AccessTokenLifetimeSeconds, + AccessTrustRule, + AccessTrustRules, ActivateResponse, ActiveJobAtSubmit, APIKey, @@ -19,6 +22,7 @@ APIKeyOwner, APIKeys, APIKeyTombstone, + AuditFieldChange, AuditLogActor, AuditLogEntry, AuditLogEventApiKeyCreated, @@ -51,6 +55,9 @@ AuditLogEventGridMachineUserCreated, AuditLogEventGridMachineUserDeleted, AuditLogEventGridMachineUserUpdated, + AuditLogEventIdentityProviderCreated, + AuditLogEventIdentityProviderDeleted, + AuditLogEventIdentityProviderUpdated, AuditLogEventModelDeleted, AuditLogEventModelDeployed, AuditLogEventModelDeploymentActivated, @@ -63,6 +70,8 @@ AuditLogEventModelDeploymentRetried, AuditLogEventModelPromotionControlAction, AuditLogEventModelRenamed, + AuditLogEventOrganizationApiKeySettingsUpdated, + AuditLogEventPredefinedIdentityProviderConfig, AuditLogEventPromotionSettingsOverride, AuditLogEventProviderConnectionCreated, AuditLogEventProviderConnectionDeleted, @@ -72,10 +81,17 @@ AuditLogEventRequireGroupBasedAdminsEnabled, AuditLogEventSecretDeleted, AuditLogEventSecretUpdated, + AuditLogEventServiceAccountCreated, + AuditLogEventServiceAccountDeleted, + AuditLogEventServiceAccountPresetPermissions, + AuditLogEventServiceAccountUpdated, AuditLogEventSshCertificateSigned, AuditLogEventTelemetryExportCreated, AuditLogEventTelemetryExportDeleted, AuditLogEventTelemetryExportUpdated, + AuditLogEventTrustRuleCreated, + AuditLogEventTrustRuleDeleted, + AuditLogEventTrustRuleUpdated, AuditLogEventUserInvited, AuditLogEventUserJoinedOrganization, AuditLogEventUserRemoved, @@ -135,6 +151,7 @@ CostPerMillionInputTokens1, CostPerMillionOutputTokens, CostPerMillionOutputTokens1, + CreateAccessTrustRuleRequest, CreateApiKeyForGroupRequest, CreateApiKeyForGroupResponse, CreateAPIKeyRequest, @@ -152,6 +169,7 @@ CreateGridTokenRequest, CreateGroupHierarchy, CreateGroupRequest, + CreateIdentityProviderRequest, CreateJobWeightConfig, CreateLibraryListingRequest, CreateLibraryListingVersionRequest, @@ -165,6 +183,7 @@ CreateLoopsTrainerRequest, CreateModelDeploymentRequest, CreateModelRequest, + CreatePredefinedIdentityProviderConfig, CreateSandboxParams, CreateSandboxPreviewParams, CreateSandboxPreviewRequest, @@ -173,6 +192,7 @@ CreateSandboxRequest, CreateSandboxVolumeParams, CreateSandboxVolumeRequest, + CreateServiceAccountRequest, CreateTokenRequest, CreateTrainingJob, CreateTrainingJobAccelerator, @@ -198,8 +218,12 @@ DeactivateResponse, DedicatedItem, DedicatedUsage, + DeletedAccessTrustRule, + DeletedIdentityProvider, + DeletedServiceAccount, DeleteImageParams, DeleteImageTagParams, + DeleteLoopsRunResponse, DeleteSandboxParams, DeleteSandboxPreviewParams, DeleteSandboxPreviewTokenParams, @@ -224,10 +248,16 @@ DeploymentPatchOpPythonRequirement, DeploymentPatchPoint, DeploymentPatchPointWithHash, + DeploymentReplica, + DeploymentReplicas, Deployments, DeploymentTombstone, Description, Description1, + Description2, + Description3, + Description4, + Description5, DisplayName, DisplayName1, DockerAuth, @@ -271,6 +301,8 @@ GatewayKeyInfo, GcpOidcDockerAuth, GcpServiceAccountJsonDockerAuth, + GetAccessIdentityProvidersParams, + GetAccessTrustRulesParams, GetApiKeysParams, GetAuditLogsParams, GetAuthCodesResponse, @@ -285,7 +317,6 @@ GetDeploymentPatchesStateResponse, GetExploreMetadataParams, GetGatewayEventsParams, - GetGridClassifiersParams, GetGridConnectionsParams, GetGridMachineUsersParams, GetGridRouteClassifiersParams, @@ -323,10 +354,12 @@ GetModelsDeploymentsLogsParams, GetModelsDeploymentsMetricsParams, GetModelsDeploymentsParams, + GetModelsDeploymentsReplicasParams, GetModelsDeploymentsStartupsParams, GetModelsDeploymentsStartupsSummaryParams, GetModelsEnvironmentsLogsParams, GetModelsEnvironmentsMetricsParams, + GetModelsEnvironmentsReplicasParams, GetModelsEnvironmentsStartupsParams, GetModelsEnvironmentsStartupsSummaryParams, GetModelsParams, @@ -336,6 +369,7 @@ GetSandboxParams, GetSandboxPreviewParams, GetSandboxVolumeParams, + GetServiceAccountsParams, GetTeamsLoopsRunsParams, GetTeamsLoopsSamplersParams, GetTeamsModelsParams, @@ -359,12 +393,11 @@ GetVolumesSyncsParams, GetVolumesVersionsParams, GitInfo, - GridClassifier, - GridClassifiersResponse, GridConnection, GridConnectionBedrockAccessKeysAuth, GridConnectionBedrockApiKeyAuth, GridConnectionConfigAnthropic, + GridConnectionConfigAzure, GridConnectionConfigBedrock, GridConnectionConfigOpenAI, GridConnectionConfigVertex, @@ -379,12 +412,12 @@ GridMachineUsersResponse, GridMachineUserTombstone, GridRoute, + GridRouteAlias, GridRouteClassifier, GridRouteClassifiersResponse, - GridRouteRef, + GridRouteMetadata, GridRoutesResponse, GridRouteTargetBasetenModelAPI, - GridRouteTargetClassifier, GridRouteTargetConnection, GridRouteTargetIntelligent, GridRouteTombstone, @@ -402,6 +435,8 @@ GroupHierarchy, GroupMetadata, GroupsResponse, + IdentityProvider, + IdentityProviders, InferenceVolumeByStatusDatapoint, InProgressPromotion, InstanceType, @@ -410,6 +445,7 @@ InstanceTypeWithPrice, InteractiveSession, InteractiveSessionConfig, + IssuerUrl, KeysForGroupResponse, LibraryListing, LibraryListingMetadata, @@ -458,6 +494,7 @@ LoopsCheckpointFilesResponse, LoopsCheckpointS3Source, LoopsCheckpointSourceResponse, + LoopsCheckpointTombstone, LoopsCheckpointVolumeSource, LoopsDebugArchiveFilesResponse, LoopsDeployment, @@ -474,6 +511,7 @@ LoopsSession, LoopsUsage, LoopsUserConfig, + MaxAccessTokenLifetimeSeconds, MaxScaleDownRate, MaxScaleDownRate1, MaxSeqLen, @@ -502,9 +540,15 @@ Name1, Name2, Name3, + Name4, Name5, Name6, - Name7, + Name8, + Name9, + Name10, + Name12, + Name13, + Name14, NumReplicas, OneTimeAutoscalingSchedule, OneTimeAutoscalingScheduleUpsert, @@ -520,6 +564,9 @@ PatchVolumeRequest, PatchVolumeResponse, PendingJobAheadAtSubmit, + PredefinedIdentityProvider, + PredefinedIdentityProviderConfig, + PredefinedIdentityProviders, PrepareModelUploadRequest, PrepareModelUploadResponse, Primary, @@ -584,6 +631,11 @@ SecretReference, Secrets, SecretTombstone, + ServiceAccount, + ServiceAccountPresetPermissions, + ServiceAccountPresetPermissionsRequest, + ServiceAccounts, + SetLoopsCheckpointTtlRequest, SetVolumeTagRequest, SetVolumeTagResponse, SignalPromotionResponse, @@ -627,17 +679,26 @@ TeamId5, TeamId6, TeamId7, + TeamId8, Teams, TeamTrainingGpuCapacityItem, TerminateReplicaResponse, Token, + TokenExchangeRequest, + TokenExchangeResponse, ToolCallUsageBucket, ToolCallUsageResponse, Total, + Total2, + Total3, TrafficRoutingRule, TrafficRoutingRuleUpsert, TrafficRoutingTarget, TrafficRoutingTargetUpsert, + TrainingBDNConfig, + TrainingBDNConfigResponse, + TrainingBDNMount, + TrainingBDNMountResponse, TrainingGpuCapacityItem, TrainingItem, TrainingJob, @@ -652,7 +713,9 @@ TrainingUsage, TrainingWeightAuth, TrussUserEnv, + TtlSeconds, TTSBenchmarkMetrics, + UpdateAccessTrustRuleRequest, UpdateAutoscalingScheduleSettings, UpdateAutoscalingSettings, UpdateAutoscalingSettingsResponse, @@ -678,10 +741,12 @@ UpdateGridUserSettingsRequest, UpdateGroupMetadata, UpdateGroupRequest, + UpdateIdentityProviderRequest, UpdateLibraryListingRequest, UpdateLibraryListingVersionRequest, UpdateModelPromotionSettings, UpdateModelRequest, + UpdateOrganizationRequest, UpdatePromotionSettings, UpdateRequestBackpressureSettings, UpdateRollingDeployConfig, @@ -691,19 +756,21 @@ UpdateSandboxRequest, UpdateSandboxVolumeParams, UpdateSandboxVolumeRequest, + UpdateServiceAccountRequest, UpdateTrafficRoutingSettings, UpdateTrainingJobRequest, UpdateTrainingJobResponse, UpsertGridConnectionBedrockAccessKeysAuth, UpsertGridConnectionBedrockApiKeyAuth, UpsertGridConnectionConfigAnthropic, + UpsertGridConnectionConfigAzure, UpsertGridConnectionConfigBedrock, UpsertGridConnectionConfigOpenAI, UpsertGridConnectionConfigVertex, UpsertGridConnectionConfigXAI, UpsertGridRouteTargetBasetenModelAPI, - UpsertGridRouteTargetClassifier, UpsertGridRouteTargetConnection, + UpsertGridRouteTargetIntelligent, UpsertSecretRequest, UpsertTrainingProject, UpsertTrainingProjectRequest, @@ -716,6 +783,10 @@ ValidateLoopsCheckpointRequest, ValidateLoopsCheckpointResponse, Value, + Verification, + VerifyAccessTrustRuleRequest, + VerifyIdentityProviderRequest, + VerifyPredefinedIdentityProviderConfig, VertexTargetConfig, Volume, VolumeSync, @@ -746,10 +817,14 @@ "APIKeyTombstone", "APIKeys", "AWSCredentials", + "AccessTokenLifetimeSeconds", + "AccessTrustRule", + "AccessTrustRules", "ActivateResponse", "ActiveJobAtSubmit", "ApiClient", "AsyncApiClient", + "AuditFieldChange", "AuditLogActor", "AuditLogEntry", "AuditLogEventApiKeyCreated", @@ -782,6 +857,9 @@ "AuditLogEventGridMachineUserCreated", "AuditLogEventGridMachineUserDeleted", "AuditLogEventGridMachineUserUpdated", + "AuditLogEventIdentityProviderCreated", + "AuditLogEventIdentityProviderDeleted", + "AuditLogEventIdentityProviderUpdated", "AuditLogEventModelDeleted", "AuditLogEventModelDeployed", "AuditLogEventModelDeploymentActivated", @@ -794,6 +872,8 @@ "AuditLogEventModelDeploymentRetried", "AuditLogEventModelPromotionControlAction", "AuditLogEventModelRenamed", + "AuditLogEventOrganizationApiKeySettingsUpdated", + "AuditLogEventPredefinedIdentityProviderConfig", "AuditLogEventPromotionSettingsOverride", "AuditLogEventProviderConnectionCreated", "AuditLogEventProviderConnectionDeleted", @@ -803,10 +883,17 @@ "AuditLogEventRequireGroupBasedAdminsEnabled", "AuditLogEventSecretDeleted", "AuditLogEventSecretUpdated", + "AuditLogEventServiceAccountCreated", + "AuditLogEventServiceAccountDeleted", + "AuditLogEventServiceAccountPresetPermissions", + "AuditLogEventServiceAccountUpdated", "AuditLogEventSshCertificateSigned", "AuditLogEventTelemetryExportCreated", "AuditLogEventTelemetryExportDeleted", "AuditLogEventTelemetryExportUpdated", + "AuditLogEventTrustRuleCreated", + "AuditLogEventTrustRuleDeleted", + "AuditLogEventTrustRuleUpdated", "AuditLogEventUserInvited", "AuditLogEventUserJoinedOrganization", "AuditLogEventUserRemoved", @@ -866,6 +953,7 @@ "CostPerMillionOutputTokens", "CostPerMillionOutputTokens1", "CreateAPIKeyRequest", + "CreateAccessTrustRuleRequest", "CreateApiKeyForGroupRequest", "CreateApiKeyForGroupResponse", "CreateChainEnvironmentRequest", @@ -880,6 +968,7 @@ "CreateGridTokenRequest", "CreateGroupHierarchy", "CreateGroupRequest", + "CreateIdentityProviderRequest", "CreateJobWeightConfig", "CreateLLMModelRequest", "CreateLLMModelVersionRequest", @@ -893,6 +982,7 @@ "CreateLoopsTrainerRequest", "CreateModelDeploymentRequest", "CreateModelRequest", + "CreatePredefinedIdentityProviderConfig", "CreateSandboxParams", "CreateSandboxPreviewParams", "CreateSandboxPreviewRequest", @@ -901,6 +991,7 @@ "CreateSandboxRequest", "CreateSandboxVolumeParams", "CreateSandboxVolumeRequest", + "CreateServiceAccountRequest", "CreateTokenRequest", "CreateTrainingJob", "CreateTrainingJobAccelerator", @@ -930,6 +1021,7 @@ "DedicatedUsage", "DeleteImageParams", "DeleteImageTagParams", + "DeleteLoopsRunResponse", "DeleteSandboxParams", "DeleteSandboxPreviewParams", "DeleteSandboxPreviewTokenParams", @@ -940,6 +1032,9 @@ "DeleteVolumeTagResponse", "DeleteVolumeVersionRequest", "DeleteVolumeVersionResponse", + "DeletedAccessTrustRule", + "DeletedIdentityProvider", + "DeletedServiceAccount", "DeployLoopsCheckpointRequest", "DeployLoopsCheckpointResponse", "Deployment", @@ -954,10 +1049,16 @@ "DeploymentPatchOpPythonRequirement", "DeploymentPatchPoint", "DeploymentPatchPointWithHash", + "DeploymentReplica", + "DeploymentReplicas", "DeploymentTombstone", "Deployments", "Description", "Description1", + "Description2", + "Description3", + "Description4", + "Description5", "DisplayName", "DisplayName1", "DockerAuth", @@ -1001,6 +1102,8 @@ "GatewayKeyInfo", "GcpOidcDockerAuth", "GcpServiceAccountJsonDockerAuth", + "GetAccessIdentityProvidersParams", + "GetAccessTrustRulesParams", "GetApiKeysParams", "GetAuditLogsParams", "GetAuthCodesResponse", @@ -1015,7 +1118,6 @@ "GetDeploymentPatchesStateResponse", "GetExploreMetadataParams", "GetGatewayEventsParams", - "GetGridClassifiersParams", "GetGridConnectionsParams", "GetGridMachineUsersParams", "GetGridRouteClassifiersParams", @@ -1053,10 +1155,12 @@ "GetModelsDeploymentsLogsParams", "GetModelsDeploymentsMetricsParams", "GetModelsDeploymentsParams", + "GetModelsDeploymentsReplicasParams", "GetModelsDeploymentsStartupsParams", "GetModelsDeploymentsStartupsSummaryParams", "GetModelsEnvironmentsLogsParams", "GetModelsEnvironmentsMetricsParams", + "GetModelsEnvironmentsReplicasParams", "GetModelsEnvironmentsStartupsParams", "GetModelsEnvironmentsStartupsSummaryParams", "GetModelsParams", @@ -1066,6 +1170,7 @@ "GetSandboxParams", "GetSandboxPreviewParams", "GetSandboxVolumeParams", + "GetServiceAccountsParams", "GetTeamsLoopsRunsParams", "GetTeamsLoopsSamplersParams", "GetTeamsModelsParams", @@ -1089,12 +1194,11 @@ "GetVolumesSyncsParams", "GetVolumesVersionsParams", "GitInfo", - "GridClassifier", - "GridClassifiersResponse", "GridConnection", "GridConnectionBedrockAccessKeysAuth", "GridConnectionBedrockApiKeyAuth", "GridConnectionConfigAnthropic", + "GridConnectionConfigAzure", "GridConnectionConfigBedrock", "GridConnectionConfigOpenAI", "GridConnectionConfigVertex", @@ -1109,11 +1213,11 @@ "GridMachineUserTombstone", "GridMachineUsersResponse", "GridRoute", + "GridRouteAlias", "GridRouteClassifier", "GridRouteClassifiersResponse", - "GridRouteRef", + "GridRouteMetadata", "GridRouteTargetBasetenModelAPI", - "GridRouteTargetClassifier", "GridRouteTargetConnection", "GridRouteTargetIntelligent", "GridRouteTombstone", @@ -1132,6 +1236,8 @@ "GroupHierarchy", "GroupMetadata", "GroupsResponse", + "IdentityProvider", + "IdentityProviders", "InProgressPromotion", "InferenceVolumeByStatusDatapoint", "InstanceType", @@ -1140,6 +1246,7 @@ "InstanceTypes", "InteractiveSession", "InteractiveSessionConfig", + "IssuerUrl", "KeysForGroupResponse", "LLMBenchmarkMetrics", "LLMModelHandle", @@ -1188,6 +1295,7 @@ "LoopsCheckpointFilesResponse", "LoopsCheckpointS3Source", "LoopsCheckpointSourceResponse", + "LoopsCheckpointTombstone", "LoopsCheckpointVolumeSource", "LoopsDebugArchiveFilesResponse", "LoopsDeployment", @@ -1204,6 +1312,7 @@ "LoopsSession", "LoopsUsage", "LoopsUserConfig", + "MaxAccessTokenLifetimeSeconds", "MaxScaleDownRate", "MaxScaleDownRate1", "MaxSeqLen", @@ -1232,9 +1341,15 @@ "Name1", "Name2", "Name3", + "Name4", "Name5", "Name6", - "Name7", + "Name8", + "Name9", + "Name10", + "Name12", + "Name13", + "Name14", "NumReplicas", "OneTimeAutoscalingSchedule", "OneTimeAutoscalingScheduleUpsert", @@ -1250,6 +1365,9 @@ "PatchVolumeRequest", "PatchVolumeResponse", "PendingJobAheadAtSubmit", + "PredefinedIdentityProvider", + "PredefinedIdentityProviderConfig", + "PredefinedIdentityProviders", "PrepareModelUploadRequest", "PrepareModelUploadResponse", "Primary", @@ -1315,6 +1433,11 @@ "SecretReference", "SecretTombstone", "Secrets", + "ServiceAccount", + "ServiceAccountPresetPermissions", + "ServiceAccountPresetPermissionsRequest", + "ServiceAccounts", + "SetLoopsCheckpointTtlRequest", "SetVolumeTagRequest", "SetVolumeTagResponse", "SignSSHCertificateRequest", @@ -1359,17 +1482,26 @@ "TeamId5", "TeamId6", "TeamId7", + "TeamId8", "TeamTrainingGpuCapacityItem", "Teams", "TerminateReplicaResponse", "Token", + "TokenExchangeRequest", + "TokenExchangeResponse", "ToolCallUsageBucket", "ToolCallUsageResponse", "Total", + "Total2", + "Total3", "TrafficRoutingRule", "TrafficRoutingRuleUpsert", "TrafficRoutingTarget", "TrafficRoutingTargetUpsert", + "TrainingBDNConfig", + "TrainingBDNConfigResponse", + "TrainingBDNMount", + "TrainingBDNMountResponse", "TrainingGpuCapacityItem", "TrainingItem", "TrainingJob", @@ -1384,6 +1516,8 @@ "TrainingUsage", "TrainingWeightAuth", "TrussUserEnv", + "TtlSeconds", + "UpdateAccessTrustRuleRequest", "UpdateAutoscalingScheduleSettings", "UpdateAutoscalingSettings", "UpdateAutoscalingSettingsResponse", @@ -1409,10 +1543,12 @@ "UpdateGridUserSettingsRequest", "UpdateGroupMetadata", "UpdateGroupRequest", + "UpdateIdentityProviderRequest", "UpdateLibraryListingRequest", "UpdateLibraryListingVersionRequest", "UpdateModelPromotionSettings", "UpdateModelRequest", + "UpdateOrganizationRequest", "UpdatePromotionSettings", "UpdateRequestBackpressureSettings", "UpdateRollingDeployConfig", @@ -1422,19 +1558,21 @@ "UpdateSandboxRequest", "UpdateSandboxVolumeParams", "UpdateSandboxVolumeRequest", + "UpdateServiceAccountRequest", "UpdateTrafficRoutingSettings", "UpdateTrainingJobRequest", "UpdateTrainingJobResponse", "UpsertGridConnectionBedrockAccessKeysAuth", "UpsertGridConnectionBedrockApiKeyAuth", "UpsertGridConnectionConfigAnthropic", + "UpsertGridConnectionConfigAzure", "UpsertGridConnectionConfigBedrock", "UpsertGridConnectionConfigOpenAI", "UpsertGridConnectionConfigVertex", "UpsertGridConnectionConfigXAI", "UpsertGridRouteTargetBasetenModelAPI", - "UpsertGridRouteTargetClassifier", "UpsertGridRouteTargetConnection", + "UpsertGridRouteTargetIntelligent", "UpsertSecretRequest", "UpsertTrainingProject", "UpsertTrainingProjectRequest", @@ -1447,6 +1585,10 @@ "ValidateLoopsCheckpointRequest", "ValidateLoopsCheckpointResponse", "Value", + "Verification", + "VerifyAccessTrustRuleRequest", + "VerifyIdentityProviderRequest", + "VerifyPredefinedIdentityProviderConfig", "VertexTargetConfig", "Volume", "VolumeSync", diff --git a/baseten/client/managementapi/_client.py b/baseten/client/managementapi/_client.py index 145cd1e..f757c3d 100644 --- a/baseten/client/managementapi/_client.py +++ b/baseten/client/managementapi/_client.py @@ -11,6 +11,8 @@ from pydantic import BaseModel from ._models import ( + AccessTrustRule, + AccessTrustRules, ActivateResponse, APIKey, APIKeys, @@ -25,6 +27,7 @@ ChainTombstone, CleanupImagesParams, CleanupSandboxImagesResponse, + CreateAccessTrustRuleRequest, CreateApiKeyForGroupRequest, CreateApiKeyForGroupResponse, CreateAPIKeyRequest, @@ -41,6 +44,7 @@ CreateGridRouteRequest, CreateGridTokenRequest, CreateGroupRequest, + CreateIdentityProviderRequest, CreateLibraryListingRequest, CreateLibraryListingVersionRequest, CreateLLMModelRequest, @@ -61,6 +65,7 @@ CreateSandboxRequest, CreateSandboxVolumeParams, CreateSandboxVolumeRequest, + CreateServiceAccountRequest, CreateTokenRequest, CreateTrainingJobRequest, CreateTrainingJobResponse, @@ -71,8 +76,12 @@ DeactivateLoopsRunResponse, DeactivateLoopsSamplerResponse, DeactivateResponse, + DeletedAccessTrustRule, + DeletedIdentityProvider, + DeletedServiceAccount, DeleteImageParams, DeleteImageTagParams, + DeleteLoopsRunResponse, DeleteSandboxParams, DeleteSandboxPreviewParams, DeleteSandboxPreviewTokenParams, @@ -87,6 +96,8 @@ DeployLoopsCheckpointResponse, Deployment, DeploymentConfigResponse, + DeploymentReplica, + DeploymentReplicas, Deployments, DeploymentTombstone, DownloadDeploymentResponse, @@ -102,6 +113,8 @@ ExploreMetadataResponse, GatewayEventsResponse, GatewayKeyInfo, + GetAccessIdentityProvidersParams, + GetAccessTrustRulesParams, GetApiKeysParams, GetAuditLogsParams, GetAuthCodesResponse, @@ -116,7 +129,6 @@ GetDeploymentPatchesStateResponse, GetExploreMetadataParams, GetGatewayEventsParams, - GetGridClassifiersParams, GetGridConnectionsParams, GetGridMachineUsersParams, GetGridRouteClassifiersParams, @@ -154,10 +166,12 @@ GetModelsDeploymentsLogsParams, GetModelsDeploymentsMetricsParams, GetModelsDeploymentsParams, + GetModelsDeploymentsReplicasParams, GetModelsDeploymentsStartupsParams, GetModelsDeploymentsStartupsSummaryParams, GetModelsEnvironmentsLogsParams, GetModelsEnvironmentsMetricsParams, + GetModelsEnvironmentsReplicasParams, GetModelsEnvironmentsStartupsParams, GetModelsEnvironmentsStartupsSummaryParams, GetModelsParams, @@ -167,6 +181,7 @@ GetSandboxParams, GetSandboxPreviewParams, GetSandboxVolumeParams, + GetServiceAccountsParams, GetTeamsLoopsRunsParams, GetTeamsLoopsSamplersParams, GetTeamsModelsParams, @@ -189,8 +204,6 @@ GetVolumesParams, GetVolumesSyncsParams, GetVolumesVersionsParams, - GridClassifier, - GridClassifiersResponse, GridConnection, GridConnectionsResponse, GridConnectionTombstone, @@ -209,6 +222,8 @@ GridToken, Group, GroupsResponse, + IdentityProvider, + IdentityProviders, InstanceTypePrices, InstanceTypes, KeysForGroupResponse, @@ -242,8 +257,10 @@ ListVolumesResponse, ListVolumeVersionsResponse, LLMModelHandle, + LoopsCheckpoint, LoopsCheckpointFilesResponse, LoopsCheckpointSourceResponse, + LoopsCheckpointTombstone, LoopsDebugArchiveFilesResponse, Model, ModelAPI, @@ -261,6 +278,7 @@ PatchTeamTrainingGpuCapacityResponse, PatchVolumeRequest, PatchVolumeResponse, + PredefinedIdentityProviders, PrepareModelUploadRequest, PrepareModelUploadResponse, PromoteRequest, @@ -290,6 +308,9 @@ Secret, Secrets, SecretTombstone, + ServiceAccount, + ServiceAccounts, + SetLoopsCheckpointTtlRequest, SetVolumeTagRequest, SetVolumeTagResponse, SignalPromotionResponse, @@ -305,9 +326,12 @@ Teams, TerminateReplicaResponse, Token, + TokenExchangeRequest, + TokenExchangeResponse, ToolCallUsageResponse, TrainingJobTombstone, TrainingProjectTombstone, + UpdateAccessTrustRuleRequest, UpdateAutoscalingSettings, UpdateAutoscalingSettingsResponse, UpdateChainEnvironmentRequest, @@ -326,9 +350,11 @@ UpdateGridTeamSettingsRequest, UpdateGridUserSettingsRequest, UpdateGroupRequest, + UpdateIdentityProviderRequest, UpdateLibraryListingRequest, UpdateLibraryListingVersionRequest, UpdateModelRequest, + UpdateOrganizationRequest, UpdateRequestBackpressureSettings, UpdateSandboxParams, UpdateSandboxPreviewParams, @@ -336,6 +362,7 @@ UpdateSandboxRequest, UpdateSandboxVolumeParams, UpdateSandboxVolumeRequest, + UpdateServiceAccountRequest, UpdateTrainingJobRequest, UpdateTrainingJobResponse, UpsertSecretRequest, @@ -346,6 +373,9 @@ UsersResponse, ValidateLoopsCheckpointRequest, ValidateLoopsCheckpointResponse, + Verification, + VerifyAccessTrustRuleRequest, + VerifyIdentityProviderRequest, Volume, VolumeSync, VolumeSyncs, @@ -513,6 +543,40 @@ def create_sandbox_volume( ), ) + def delete_access_identity_providers( + self, *, identity_provider_id: str + ) -> DeletedIdentityProvider: + """Deletes an identity provider""" + return self._do_json( + DeletedIdentityProvider, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def delete_access_trust_rules( + self, *, trust_rule_id: str + ) -> DeletedAccessTrustRule: + """Deletes a trust rule""" + return self._do_json( + DeletedAccessTrustRule, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_api_keys(self, *, api_key_prefix: str) -> APIKeyTombstone: """Deletes an API key by prefix""" return self._do_json( @@ -711,6 +775,38 @@ def delete_library_listings_versions( ), ) + def delete_loops_checkpoints( + self, *, checkpoint_id: str + ) -> LoopsCheckpointTombstone: + """Deletes a Loops checkpoint""" + return self._do_json( + LoopsCheckpointTombstone, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/checkpoints/{}", + path_args=[checkpoint_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def delete_loops_runs(self, *, run_id: str) -> DeleteLoopsRunResponse: + """Deletes a Loops run""" + return self._do_json( + DeleteLoopsRunResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/runs/{}", + path_args=[run_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_models(self, *, model_id: str) -> ModelTombstone: """Deletes a model by ID""" return self._do_json( @@ -777,6 +873,23 @@ def delete_models_environments( ), ) + def delete_models_environments_replicas( + self, *, model_id: str, env_name: str, replica_id: str + ) -> TerminateReplicaResponse: + """Terminates a replica in an environment""" + return self._do_json( + TerminateReplicaResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_sandbox( self, *, sandbox_name: str, params: DeleteSandboxParams | None = None ) -> Sandbox: @@ -868,6 +981,23 @@ def delete_secrets(self, *, secret_name: str) -> SecretTombstone: ), ) + def delete_service_accounts( + self, *, service_account_id: str + ) -> DeletedServiceAccount: + """Deletes a service account""" + return self._do_json( + DeletedServiceAccount, + _ApiRequest( + method="DELETE", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_teams_secrets( self, *, team_id: str, secret_name: str ) -> SecretTombstone: @@ -980,6 +1110,89 @@ def delete_volumes_versions( ), ) + def get_access_identity_providers( + self, *, params: GetAccessIdentityProvidersParams | None = None + ) -> IdentityProviders: + """Lists identity providers""" + return self._do_json( + IdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_identity_providers_identity_provider_id( + self, *, identity_provider_id: str + ) -> IdentityProvider: + """Gets an identity provider""" + return self._do_json( + IdentityProvider, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_predefined_identity_providers(self) -> PredefinedIdentityProviders: + """Lists predefined identity providers""" + return self._do_json( + PredefinedIdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/predefined_identity_providers", + path_args=[], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_trust_rules( + self, *, params: GetAccessTrustRulesParams | None = None + ) -> AccessTrustRules: + """Lists trust rules""" + return self._do_json( + AccessTrustRules, + _ApiRequest( + method="GET", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_trust_rules_trust_rule_id( + self, *, trust_rule_id: str + ) -> AccessTrustRule: + """Gets a trust rule""" + return self._do_json( + AccessTrustRule, + _ApiRequest( + method="GET", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_api_keys(self, *, params: GetApiKeysParams | None = None) -> APIKeys: """Lists API keys (metadata only, no plain text keys)""" return self._do_json( @@ -1382,40 +1595,6 @@ def get_gateway_groups_group_id(self, *, group_id: str) -> Group: ), ) - def get_grid_classifiers( - self, *, params: GetGridClassifiersParams | None = None - ) -> GridClassifiersResponse: - """Lists classifiers available for intelligent routes""" - return self._do_json( - GridClassifiersResponse, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - def get_grid_classifiers_classifier_id( - self, *, classifier_id: str - ) -> GridClassifier: - """Gets a classifier available for intelligent routes""" - return self._do_json( - GridClassifier, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers/{}", - path_args=[classifier_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def get_grid_connections( self, *, params: GetGridConnectionsParams | None = None ) -> GridConnectionsResponse: @@ -2268,6 +2447,44 @@ def get_models_deployments_production(self, *, model_id: str) -> Deployment: ), ) + def get_models_deployments_replicas( + self, + *, + model_id: str, + deployment_id: str, + params: GetModelsDeploymentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for a deployment""" + return self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas", + path_args=[model_id, deployment_id], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_models_deployments_replicas_replica_id( + self, *, model_id: str, deployment_id: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in a deployment""" + return self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas/{}", + path_args=[model_id, deployment_id, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_models_deployments_startups( self, *, @@ -2384,6 +2601,44 @@ def get_models_environments_metrics( ), ) + def get_models_environments_replicas( + self, + *, + model_id: str, + env_name: str, + params: GetModelsEnvironmentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for an environment""" + return self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas", + path_args=[model_id, env_name], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_models_environments_replicas_replica_id( + self, *, model_id: str, env_name: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in an environment""" + return self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_models_environments_startups( self, *, @@ -2590,6 +2845,40 @@ def get_secrets(self) -> Secrets: ), ) + def get_service_accounts( + self, *, params: GetServiceAccountsParams | None = None + ) -> ServiceAccounts: + """Lists service accounts""" + return self._do_json( + ServiceAccounts, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_service_accounts_service_account_id( + self, *, service_account_id: str + ) -> ServiceAccount: + """Gets a service account""" + return self._do_json( + ServiceAccount, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_teams(self, *, params: GetTeamsParams | None = None) -> Teams: """Lists all teams""" return self._do_json( @@ -3249,6 +3538,40 @@ def list_sandboxes( ), ) + def patch_access_identity_providers( + self, *, identity_provider_id: str, request: UpdateIdentityProviderRequest + ) -> IdentityProvider: + """Updates an identity provider""" + return self._do_json( + IdentityProvider, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def patch_access_trust_rules( + self, *, trust_rule_id: str, request: UpdateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Updates a trust rule""" + return self._do_json( + AccessTrustRule, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def patch_chains_environments( self, *, chain_id: str, env_name: str, request: UpdateChainEnvironmentRequest ) -> UpdateChainEnvironmentResponse: @@ -3599,6 +3922,40 @@ def patch_models_environments( ), ) + def patch_organizations_me( + self, *, request: UpdateOrganizationRequest + ) -> OrganizationInfo: + """Updates the authenticated organization""" + return self._do_json( + OrganizationInfo, + _ApiRequest( + method="PATCH", + path_fmt="/v1/organizations/me", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def patch_service_accounts( + self, *, service_account_id: str, request: UpdateServiceAccountRequest + ) -> ServiceAccount: + """Updates a service account""" + return self._do_json( + ServiceAccount, + _ApiRequest( + method="PATCH", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def patch_teams_environment_groups( self, *, team_id: str, env_name: str, request: UpdateEnvironmentGroupRequest ) -> EnvironmentGroup: @@ -3619,7 +3976,7 @@ def patch_teams_environment_groups( def patch_training_capacity( self, *, request: PatchTeamTrainingGpuCapacityRequest ) -> PatchTeamTrainingGpuCapacityResponse: - """Sets a team's training GPU capacity""" + """Sets a team's training GPU quota""" return self._do_json( PatchTeamTrainingGpuCapacityResponse, _ApiRequest( @@ -3693,6 +4050,74 @@ def patch_volumes( ), ) + def post_access_identity_providers( + self, *, request: CreateIdentityProviderRequest + ) -> IdentityProvider: + """Adds an identity provider""" + return self._do_json( + IdentityProvider, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def post_access_identity_providers_verify( + self, *, request: VerifyIdentityProviderRequest + ) -> Verification: + """Checks an identity provider before adding it""" + return self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def post_access_trust_rules( + self, *, request: CreateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Creates a trust rule""" + return self._do_json( + AccessTrustRule, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def post_access_trust_rules_verify( + self, *, request: VerifyAccessTrustRuleRequest + ) -> Verification: + """Checks a trust rule's condition and audience""" + return self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: """Creates an API key""" return self._do_json( @@ -3708,6 +4133,23 @@ def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: ), ) + def post_auth_token( + self, *, request: TokenExchangeRequest + ) -> TokenExchangeResponse: + """Exchanges an identity provider's JWT for an access token""" + return self._do_json( + TokenExchangeResponse, + _ApiRequest( + method="POST", + path_fmt="/v1/auth/token", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def post_chains_deployments_deactivate( self, *, chain_id: str, chain_deployment_id: str ) -> DeactivateResponse: @@ -4640,6 +5082,23 @@ def post_secrets(self, *, request: UpsertSecretRequest) -> Secret: ), ) + def post_service_accounts( + self, *, request: CreateServiceAccountRequest + ) -> ServiceAccount: + """Creates a service account""" + return self._do_json( + ServiceAccount, + _ApiRequest( + method="POST", + path_fmt="/v1/service_accounts", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def post_teams_api_keys( self, *, team_id: str, request: CreateAPIKeyRequest ) -> APIKey: @@ -5061,6 +5520,23 @@ def push_image( ), ) + def put_loops_checkpoints_ttl( + self, *, checkpoint_id: str, request: SetLoopsCheckpointTtlRequest + ) -> LoopsCheckpoint: + """Sets a Loops checkpoint's TTL""" + return self._do_json( + LoopsCheckpoint, + _ApiRequest( + method="PUT", + path_fmt="/v1/loops/checkpoints/{}/ttl", + path_args=[checkpoint_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def update_sandbox( self, *, @@ -5335,6 +5811,40 @@ async def create_sandbox_volume( ), ) + async def delete_access_identity_providers( + self, *, identity_provider_id: str + ) -> DeletedIdentityProvider: + """Deletes an identity provider""" + return await self._do_json( + DeletedIdentityProvider, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_access_trust_rules( + self, *, trust_rule_id: str + ) -> DeletedAccessTrustRule: + """Deletes a trust rule""" + return await self._do_json( + DeletedAccessTrustRule, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_api_keys(self, *, api_key_prefix: str) -> APIKeyTombstone: """Deletes an API key by prefix""" return await self._do_json( @@ -5535,6 +6045,38 @@ async def delete_library_listings_versions( ), ) + async def delete_loops_checkpoints( + self, *, checkpoint_id: str + ) -> LoopsCheckpointTombstone: + """Deletes a Loops checkpoint""" + return await self._do_json( + LoopsCheckpointTombstone, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/checkpoints/{}", + path_args=[checkpoint_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_loops_runs(self, *, run_id: str) -> DeleteLoopsRunResponse: + """Deletes a Loops run""" + return await self._do_json( + DeleteLoopsRunResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/runs/{}", + path_args=[run_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_models(self, *, model_id: str) -> ModelTombstone: """Deletes a model by ID""" return await self._do_json( @@ -5601,6 +6143,23 @@ async def delete_models_environments( ), ) + async def delete_models_environments_replicas( + self, *, model_id: str, env_name: str, replica_id: str + ) -> TerminateReplicaResponse: + """Terminates a replica in an environment""" + return await self._do_json( + TerminateReplicaResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_sandbox( self, *, sandbox_name: str, params: DeleteSandboxParams | None = None ) -> Sandbox: @@ -5692,6 +6251,23 @@ async def delete_secrets(self, *, secret_name: str) -> SecretTombstone: ), ) + async def delete_service_accounts( + self, *, service_account_id: str + ) -> DeletedServiceAccount: + """Deletes a service account""" + return await self._do_json( + DeletedServiceAccount, + _ApiRequest( + method="DELETE", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_teams_secrets( self, *, team_id: str, secret_name: str ) -> SecretTombstone: @@ -5750,54 +6326,139 @@ async def delete_volumes( return await self._do_json( DeleteVolumeResponse, _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}", - path_args=[volume_namespace, volume_name], - body=request, + method="DELETE", + path_fmt="/v1/volumes/{}/{}", + path_args=[volume_namespace, volume_name], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_volumes_tags( + self, + *, + volume_namespace: str, + volume_name: str, + volume_tag: str, + request: DeleteVolumeTagRequest, + ) -> DeleteVolumeTagResponse: + """Deletes a volume tag""" + return await self._do_json( + DeleteVolumeTagResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/volumes/{}/{}/tags/{}", + path_args=[volume_namespace, volume_name, volume_tag], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_volumes_versions( + self, + *, + volume_namespace: str, + volume_name: str, + volume_version: str, + request: DeleteVolumeVersionRequest, + ) -> DeleteVolumeVersionResponse: + """Deletes one version of a volume""" + return await self._do_json( + DeleteVolumeVersionResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/volumes/{}/{}/versions/{}", + path_args=[volume_namespace, volume_name, volume_version], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_access_identity_providers( + self, *, params: GetAccessIdentityProvidersParams | None = None + ) -> IdentityProviders: + """Lists identity providers""" + return await self._do_json( + IdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_access_identity_providers_identity_provider_id( + self, *, identity_provider_id: str + ) -> IdentityProvider: + """Gets an identity provider""" + return await self._do_json( + IdentityProvider, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_access_predefined_identity_providers( + self, + ) -> PredefinedIdentityProviders: + """Lists predefined identity providers""" + return await self._do_json( + PredefinedIdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/predefined_identity_providers", + path_args=[], + body=None, query=None, success_codes=[200], error_codes=None, ), ) - async def delete_volumes_tags( - self, - *, - volume_namespace: str, - volume_name: str, - volume_tag: str, - request: DeleteVolumeTagRequest, - ) -> DeleteVolumeTagResponse: - """Deletes a volume tag""" + async def get_access_trust_rules( + self, *, params: GetAccessTrustRulesParams | None = None + ) -> AccessTrustRules: + """Lists trust rules""" return await self._do_json( - DeleteVolumeTagResponse, + AccessTrustRules, _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}/tags/{}", - path_args=[volume_namespace, volume_name, volume_tag], - body=request, - query=None, + method="GET", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=None, + query=params, success_codes=[200], error_codes=None, ), ) - async def delete_volumes_versions( - self, - *, - volume_namespace: str, - volume_name: str, - volume_version: str, - request: DeleteVolumeVersionRequest, - ) -> DeleteVolumeVersionResponse: - """Deletes one version of a volume""" + async def get_access_trust_rules_trust_rule_id( + self, *, trust_rule_id: str + ) -> AccessTrustRule: + """Gets a trust rule""" return await self._do_json( - DeleteVolumeVersionResponse, + AccessTrustRule, _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}/versions/{}", - path_args=[volume_namespace, volume_name, volume_version], - body=request, + method="GET", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, query=None, success_codes=[200], error_codes=None, @@ -6210,40 +6871,6 @@ async def get_gateway_groups_group_id(self, *, group_id: str) -> Group: ), ) - async def get_grid_classifiers( - self, *, params: GetGridClassifiersParams | None = None - ) -> GridClassifiersResponse: - """Lists classifiers available for intelligent routes""" - return await self._do_json( - GridClassifiersResponse, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_grid_classifiers_classifier_id( - self, *, classifier_id: str - ) -> GridClassifier: - """Gets a classifier available for intelligent routes""" - return await self._do_json( - GridClassifier, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers/{}", - path_args=[classifier_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def get_grid_connections( self, *, params: GetGridConnectionsParams | None = None ) -> GridConnectionsResponse: @@ -7096,6 +7723,44 @@ async def get_models_deployments_production(self, *, model_id: str) -> Deploymen ), ) + async def get_models_deployments_replicas( + self, + *, + model_id: str, + deployment_id: str, + params: GetModelsDeploymentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for a deployment""" + return await self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas", + path_args=[model_id, deployment_id], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_models_deployments_replicas_replica_id( + self, *, model_id: str, deployment_id: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in a deployment""" + return await self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas/{}", + path_args=[model_id, deployment_id, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def get_models_deployments_startups( self, *, @@ -7212,6 +7877,44 @@ async def get_models_environments_metrics( ), ) + async def get_models_environments_replicas( + self, + *, + model_id: str, + env_name: str, + params: GetModelsEnvironmentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for an environment""" + return await self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas", + path_args=[model_id, env_name], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_models_environments_replicas_replica_id( + self, *, model_id: str, env_name: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in an environment""" + return await self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def get_models_environments_startups( self, *, @@ -7418,6 +8121,40 @@ async def get_secrets(self) -> Secrets: ), ) + async def get_service_accounts( + self, *, params: GetServiceAccountsParams | None = None + ) -> ServiceAccounts: + """Lists service accounts""" + return await self._do_json( + ServiceAccounts, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_service_accounts_service_account_id( + self, *, service_account_id: str + ) -> ServiceAccount: + """Gets a service account""" + return await self._do_json( + ServiceAccount, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def get_teams(self, *, params: GetTeamsParams | None = None) -> Teams: """Lists all teams""" return await self._do_json( @@ -8079,6 +8816,40 @@ async def list_sandboxes( ), ) + async def patch_access_identity_providers( + self, *, identity_provider_id: str, request: UpdateIdentityProviderRequest + ) -> IdentityProvider: + """Updates an identity provider""" + return await self._do_json( + IdentityProvider, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def patch_access_trust_rules( + self, *, trust_rule_id: str, request: UpdateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Updates a trust rule""" + return await self._do_json( + AccessTrustRule, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def patch_chains_environments( self, *, chain_id: str, env_name: str, request: UpdateChainEnvironmentRequest ) -> UpdateChainEnvironmentResponse: @@ -8431,6 +9202,40 @@ async def patch_models_environments( ), ) + async def patch_organizations_me( + self, *, request: UpdateOrganizationRequest + ) -> OrganizationInfo: + """Updates the authenticated organization""" + return await self._do_json( + OrganizationInfo, + _ApiRequest( + method="PATCH", + path_fmt="/v1/organizations/me", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def patch_service_accounts( + self, *, service_account_id: str, request: UpdateServiceAccountRequest + ) -> ServiceAccount: + """Updates a service account""" + return await self._do_json( + ServiceAccount, + _ApiRequest( + method="PATCH", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def patch_teams_environment_groups( self, *, team_id: str, env_name: str, request: UpdateEnvironmentGroupRequest ) -> EnvironmentGroup: @@ -8451,7 +9256,7 @@ async def patch_teams_environment_groups( async def patch_training_capacity( self, *, request: PatchTeamTrainingGpuCapacityRequest ) -> PatchTeamTrainingGpuCapacityResponse: - """Sets a team's training GPU capacity""" + """Sets a team's training GPU quota""" return await self._do_json( PatchTeamTrainingGpuCapacityResponse, _ApiRequest( @@ -8525,6 +9330,74 @@ async def patch_volumes( ), ) + async def post_access_identity_providers( + self, *, request: CreateIdentityProviderRequest + ) -> IdentityProvider: + """Adds an identity provider""" + return await self._do_json( + IdentityProvider, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def post_access_identity_providers_verify( + self, *, request: VerifyIdentityProviderRequest + ) -> Verification: + """Checks an identity provider before adding it""" + return await self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def post_access_trust_rules( + self, *, request: CreateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Creates a trust rule""" + return await self._do_json( + AccessTrustRule, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def post_access_trust_rules_verify( + self, *, request: VerifyAccessTrustRuleRequest + ) -> Verification: + """Checks a trust rule's condition and audience""" + return await self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: """Creates an API key""" return await self._do_json( @@ -8540,6 +9413,23 @@ async def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: ), ) + async def post_auth_token( + self, *, request: TokenExchangeRequest + ) -> TokenExchangeResponse: + """Exchanges an identity provider's JWT for an access token""" + return await self._do_json( + TokenExchangeResponse, + _ApiRequest( + method="POST", + path_fmt="/v1/auth/token", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def post_chains_deployments_deactivate( self, *, chain_id: str, chain_deployment_id: str ) -> DeactivateResponse: @@ -9480,6 +10370,23 @@ async def post_secrets(self, *, request: UpsertSecretRequest) -> Secret: ), ) + async def post_service_accounts( + self, *, request: CreateServiceAccountRequest + ) -> ServiceAccount: + """Creates a service account""" + return await self._do_json( + ServiceAccount, + _ApiRequest( + method="POST", + path_fmt="/v1/service_accounts", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def post_teams_api_keys( self, *, team_id: str, request: CreateAPIKeyRequest ) -> APIKey: @@ -9905,6 +10812,23 @@ async def push_image( ), ) + async def put_loops_checkpoints_ttl( + self, *, checkpoint_id: str, request: SetLoopsCheckpointTtlRequest + ) -> LoopsCheckpoint: + """Sets a Loops checkpoint's TTL""" + return await self._do_json( + LoopsCheckpoint, + _ApiRequest( + method="PUT", + path_fmt="/v1/loops/checkpoints/{}/ttl", + path_args=[checkpoint_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def update_sandbox( self, *, diff --git a/baseten/client/managementapi/_models.py b/baseten/client/managementapi/_models.py index b5f378f..53b2707 100644 --- a/baseten/client/managementapi/_models.py +++ b/baseten/client/managementapi/_models.py @@ -828,6 +828,111 @@ class GetUsersParams(BaseModel): ] = None +class Name1(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Only the account with this name, ignoring case", + min_length=1, + title="Name", + ), + ] = None + + +class GetServiceAccountsParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + name: Annotated[ + Name1 | None, + Field( + description="Only the account with this name, ignoring case", title="Name" + ), + ] = None + team_id: Annotated[ + str | None, Field(description="Only this team's accounts", title="Team Id") + ] = None + disabled: Annotated[ + bool | None, + Field(description="Only disabled or enabled accounts", title="Disabled"), + ] = None + + +class Name2(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Only the provider with this name, ignoring case", + min_length=1, + title="Name", + ), + ] = None + + +class Name3(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Only the rule with this name, ignoring case", + min_length=1, + title="Name", + ), + ] = None + + +class GetAccessTrustRulesParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + name: Annotated[ + Name3 | None, + Field(description="Only the rule with this name, ignoring case", title="Name"), + ] = None + identity_provider_id: Annotated[ + str | None, + Field(description="Only this provider's rules", title="Identity Provider Id"), + ] = None + service_account_id: Annotated[ + str | None, + Field( + description="Only rules for this service account", + title="Service Account Id", + ), + ] = None + team_id: Annotated[ + str | None, + Field( + description="Only rules for this team's service accounts", title="Team Id" + ), + ] = None + + class Limit6(RootModel[int]): root: Annotated[ int | None, @@ -949,7 +1054,7 @@ class GetGridRoutesParams(BaseModel): name: Annotated[ str | None, Field( - description="Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", + description="Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", title="Name", ), ] = None @@ -1066,25 +1171,6 @@ class GetGridConnectionsParams(BaseModel): ] = None -class GetGridClassifiersParams(BaseModel): - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor returned by a previous page. Omit to fetch the first page.", - title="Cursor", - ), - ] = None - limit: Annotated[ - int, - Field( - description="Maximum number of items to return.", - ge=1, - le=1000, - title="Limit", - ), - ] = 100 - - class GetGridRouteClassifiersParams(BaseModel): cursor: Annotated[ str | None, @@ -3329,9 +3415,21 @@ class PrepareModelUploadResponse(BaseModel): ] = None +class AuditFieldChange(BaseModel): + old: Annotated[Any, Field(description="The value before the update.", title="Old")] + new: Annotated[Any, Field(description="The value after the update.", title="New")] + + class AuditLogActor(BaseModel): type: Annotated[ - Literal["USER", "API_KEY", "BASETEN_USER", "BASETEN_SYSTEM", "TOMBSTONE_USER"] + Literal[ + "USER", + "API_KEY", + "BASETEN_USER", + "BASETEN_SYSTEM", + "TOMBSTONE_USER", + "SERVICE_ACCOUNT", + ] | str, Field( description="Kind of actor that performed the action.", @@ -3359,6 +3457,27 @@ class AuditLogActor(BaseModel): title="Api Key Name", ), ] = None + service_account_id: Annotated[ + str | None, + Field( + description="ID of the acting service account, when the actor is a service account.", + title="Service Account Id", + ), + ] = None + service_account_name: Annotated[ + str | None, + Field( + description="Current name of the acting service account, when the actor is a service account.", + title="Service Account Name", + ), + ] = None + trust_rule_id: Annotated[ + str | None, + Field( + description="ID of the trust rule the acting workload identity federation token was exchanged through, when the actor is a service account.", + title="Trust Rule Id", + ), + ] = None class AuditLogEventApiKeyCreated(BaseModel): @@ -3370,6 +3489,7 @@ class AuditLogEventApiKeyCreated(BaseModel): "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", + "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -3396,6 +3516,7 @@ class AuditLogEventApiKeyDeleted(BaseModel): "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", + "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -3411,7 +3532,7 @@ class AuditLogEventApiKeyDeleted(BaseModel): ), ] prefix: Annotated[str, Field(title="Prefix")] - revocation_reason: Literal["INACTIVITY"] | str | None = None + revocation_reason: Literal["INACTIVITY", "CREDENTIAL_EXPOSURE"] | str | None = None class AuditLogEventApiKeyLifetimeLimitsUpdated(BaseModel): @@ -3810,6 +3931,29 @@ class AuditLogEventGridMachineUserUpdated(BaseModel): team_name: Annotated[str, Field(title="Team Name")] +class AuditLogEventIdentityProviderDeleted(BaseModel): + event_type: Annotated[ + Literal["IDENTITY_PROVIDER_DELETED"], Field(title="Event Type") + ] + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + name: Annotated[str, Field(title="Name")] + + +class AuditLogEventIdentityProviderUpdated(BaseModel): + event_type: Annotated[ + Literal["IDENTITY_PROVIDER_UPDATED"], Field(title="Event Type") + ] + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + name: Annotated[str, Field(title="Name")] + changes: Annotated[ + dict[str, AuditFieldChange], + Field( + description="The fields the update changed, keyed by field name.", + title="Changes", + ), + ] + + class AuditLogEventModelDeleted(BaseModel): event_type: Annotated[Literal["MODEL_DELETED"], Field(title="Event Type")] model_id: Annotated[str, Field(title="Model Id")] @@ -3888,6 +4032,41 @@ class AuditLogEventModelRenamed(BaseModel): previous_name: Annotated[str | None, Field(title="Previous Name")] +class AuditLogEventOrganizationApiKeySettingsUpdated(BaseModel): + event_type: Annotated[ + Literal["ORGANIZATION_API_KEY_SETTINGS_UPDATED"], Field(title="Event Type") + ] + organization_id: Annotated[str, Field(title="Organization Id")] + previous_allow_personal_api_keys: Annotated[ + bool, Field(title="Previous Allow Personal Api Keys") + ] + new_allow_personal_api_keys: Annotated[ + bool, Field(title="New Allow Personal Api Keys") + ] + previous_allow_service_account_api_keys: Annotated[ + bool, Field(title="Previous Allow Service Account Api Keys") + ] + new_allow_service_account_api_keys: Annotated[ + bool, Field(title="New Allow Service Account Api Keys") + ] + + +class AuditLogEventPredefinedIdentityProviderConfig(BaseModel): + kind: Annotated[ + str, + Field( + description="Which predefined provider, for example `AWS_EKS`.", + title="Kind", + ), + ] + issuer_url: Annotated[ + str, + Field( + description="The `iss` claim of the provider's tokens.", title="Issuer Url" + ), + ] + + class AuditLogEventPromotionSettingsOverride(BaseModel): redeploy_on_promotion: Annotated[bool | None, Field(title="Redeploy On Promotion")] rolling_deploy: Annotated[bool | None, Field(title="Rolling Deploy")] @@ -3968,6 +4147,56 @@ class AuditLogEventSecretUpdated(BaseModel): secret_name: Annotated[str, Field(title="Secret Name")] +class AuditLogEventServiceAccountDeleted(BaseModel): + event_type: Annotated[Literal["SERVICE_ACCOUNT_DELETED"], Field(title="Event Type")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + name: Annotated[str, Field(title="Name")] + + +class AuditLogEventServiceAccountPresetPermissions(BaseModel): + api_key_type: Annotated[ + str, + Field( + description="The API key type whose permissions the account has, as API key events record it.", + title="Api Key Type", + ), + ] + model_ids: Annotated[ + list[str], + Field( + description="Models the access is limited to; empty for all.", + title="Model Ids", + ), + ] + environment_names: Annotated[ + list[str], + Field( + description="Environments the access is limited to, or may also manage; empty for none.", + title="Environment Names", + ), + ] + model_api_slugs: Annotated[ + list[str], + Field( + description="Model APIs the access is limited to; empty for all.", + title="Model Api Slugs", + ), + ] + + +class AuditLogEventServiceAccountUpdated(BaseModel): + event_type: Annotated[Literal["SERVICE_ACCOUNT_UPDATED"], Field(title="Event Type")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + name: Annotated[str, Field(title="Name")] + changes: Annotated[ + dict[str, AuditFieldChange], + Field( + description="The fields the update changed, keyed by field name.", + title="Changes", + ), + ] + + class AuditLogEventSshCertificateSigned(BaseModel): event_type: Annotated[Literal["SSH_CERTIFICATE_SIGNED"], Field(title="Event Type")] workload_type: Annotated[str, Field(title="Workload Type")] @@ -4007,6 +4236,57 @@ class AuditLogEventTelemetryExportUpdated(BaseModel): enabled: Annotated[bool | None, Field(title="Enabled")] +class AuditLogEventTrustRuleCreated(BaseModel): + event_type: Annotated[Literal["TRUST_RULE_CREATED"], Field(title="Event Type")] + trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] + name: Annotated[str, Field(title="Name")] + description: Annotated[ + str | None, + Field( + description="Null when the rule was created without one.", + title="Description", + ), + ] = None + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + condition: Annotated[ + str, + Field( + description="The CEL expression a token's claims must satisfy.", + title="Condition", + ), + ] + audience: Annotated[ + str, Field(description="The `aud` claim a token must carry.", title="Audience") + ] + max_access_token_lifetime_seconds: Annotated[ + int, + Field( + description="The longest lifetime, in seconds, of an access token the rule issues.", + title="Max Access Token Lifetime Seconds", + ), + ] + + +class AuditLogEventTrustRuleDeleted(BaseModel): + event_type: Annotated[Literal["TRUST_RULE_DELETED"], Field(title="Event Type")] + trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] + name: Annotated[str, Field(title="Name")] + + +class AuditLogEventTrustRuleUpdated(BaseModel): + event_type: Annotated[Literal["TRUST_RULE_UPDATED"], Field(title="Event Type")] + trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] + name: Annotated[str, Field(title="Name")] + changes: Annotated[ + dict[str, AuditFieldChange], + Field( + description="The fields the update changed, keyed by field name.", + title="Changes", + ), + ] + + class AuditLogEventUserInvited(BaseModel): event_type: Annotated[Literal["USER_INVITED"], Field(title="Event Type")] invited_user_email: Annotated[str, Field(title="Invited User Email")] @@ -4261,7 +4541,7 @@ class ModelTombstone(BaseModel): ] -class Name1(RootModel[str]): +class Name4(RootModel[str]): root: Annotated[ str | None, Field( @@ -4279,7 +4559,7 @@ class UpdateModelRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name1 | None, + Name4 | None, Field( description="New name for the model, unique within its team. Renaming does not change the model ID, endpoints, or deployments. Pushes that still use the old model_name create another model or target a model that now uses that name, so update config.yaml after renaming.", examples=["my-model"], @@ -4300,7 +4580,7 @@ class DeploymentTombstone(BaseModel): ] -class Name2(RootModel[str]): +class Name5(RootModel[str]): root: Annotated[ str | None, Field( @@ -4318,7 +4598,7 @@ class UpdateDeploymentRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name2 | None, + Name5 | None, Field( description="New name for the deployment, unique among the model's deployments. Only alphanumeric characters, hyphens, underscores, and periods are allowed.", examples=["my-deployment"], @@ -4885,45 +5165,108 @@ class StartupSummary(BaseModel): ] -class TerminateReplicaResponse(BaseModel): - success: Annotated[ - bool, - Field( - description="Whether the replica was successfully terminated", - title="Success", - ), - ] = True - - -class SignSSHCertificateRequest(BaseModel): - public_key: Annotated[ +class DeploymentReplica(BaseModel): + id: Annotated[ str, Field( - description="The user's SSH public key (e.g., 'ssh-ed25519 AAAA... user@host').", - title="Public Key", + description="Pod-name suffix used for replica lookup and termination, usually five characters.", + title="Id", ), ] - replica_id: Annotated[ - str | None, - Field( - description="The replica to connect to. Required for training jobs (e.g. '0'). Optional for inference (server picks a running replica if omitted).", - title="Replica Id", - ), - ] = None - - -class SignSSHCertificateResponse(BaseModel): - ssh_certificate: Annotated[ + deployment_id: Annotated[ + str, Field(description="ID of the replica's deployment.", title="Deployment Id") + ] + deployment_name: Annotated[ str, + Field(description="Name of the replica's deployment.", title="Deployment Name"), + ] + status: Annotated[ + Literal[ + "STARTING", "ACTIVE", "UNHEALTHY", "TERMINATING", "TERMINATED", "UNKNOWN" + ] + | str, Field( - description="The signed SSH certificate in OpenSSH format.", - title="Ssh Certificate", + description="Current replica lifecycle status.", + title="DeploymentReplicaStatusV1", ), ] - jwt: Annotated[ - str, + created_at: Annotated[ + AwareDatetime, Field( - description="Signed JWT (ES256) for SSH proxy authorization.", title="Jwt" + description="Replica creation time in ISO 8601 format.", title="Created At" + ), + ] + terminated_at: Annotated[ + AwareDatetime | None, + Field( + description="Observed termination completion time in ISO 8601 format, or null if unavailable.", + title="Terminated At", + ), + ] + age_seconds: Annotated[ + float, + Field( + description="Age in seconds since creation, frozen at termination.", + title="Age Seconds", + ), + ] + restart_count: Annotated[ + int | None, + Field( + description="Model container lifetime restart count, or null if unavailable.", + title="Restart Count", + ), + ] + + +class DeploymentReplicas(BaseModel): + items: Annotated[ + list[DeploymentReplica], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + +class TerminateReplicaResponse(BaseModel): + success: Annotated[ + bool, + Field( + description="Whether the replica was successfully terminated", + title="Success", + ), + ] = True + + +class SignSSHCertificateRequest(BaseModel): + public_key: Annotated[ + str, + Field( + description="The user's SSH public key (e.g., 'ssh-ed25519 AAAA... user@host').", + title="Public Key", + ), + ] + replica_id: Annotated[ + str | None, + Field( + description="The replica to connect to. Required for training jobs (e.g. '0'). Optional for inference (server picks a running replica if omitted).", + title="Replica Id", + ), + ] = None + + +class SignSSHCertificateResponse(BaseModel): + ssh_certificate: Annotated[ + str, + Field( + description="The signed SSH certificate in OpenSSH format.", + title="Ssh Certificate", + ), + ] + jwt: Annotated[ + str, + Field( + description="Signed JWT (ES256) for SSH proxy authorization.", title="Jwt" ), ] proxy_address: Annotated[ @@ -5688,6 +6031,25 @@ class UpsertTrainingProjectRequest(BaseModel): ] +class TrainingBDNMountResponse(BaseModel): + source: Annotated[str, Field(title="Source")] + path: Annotated[str, Field(title="Path")] + include: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns selecting files to mount; empty includes all files.", + title="Include", + ), + ] = None + exclude: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns excluding files from the mount; exclusions win.", + title="Exclude", + ), + ] = None + + class TrainingProjectSummary(BaseModel): id: Annotated[ str, Field(description="Unique identifier of the training project.", title="Id") @@ -5843,6 +6205,28 @@ class SecretReference(BaseModel): ] +class TrainingBDNMount(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + source: Annotated[str, Field(title="Source")] + path: Annotated[str, Field(title="Path")] + include: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns selecting files to mount; empty includes all files.", + title="Include", + ), + ] = None + exclude: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns excluding files from the mount; exclusions win.", + title="Exclude", + ), + ] = None + + class TrainingWeightAuth(BaseModel): auth_method: Annotated[ Literal[ @@ -6552,7 +6936,7 @@ class LoopsSampler(BaseModel): ] = None -class Name3(RootModel[str]): +class Name6(RootModel[str]): root: Annotated[ str | None, Field( @@ -6588,7 +6972,7 @@ class CreateLoopsRunRequest(BaseModel): Field(description="Base model ID (e.g. 'Qwen/Qwen3-8B').", title="Base Model"), ] name: Annotated[ - Name3 | None, + Name6 | None, Field( description="Optional display name for the run. Defaults to the base model name when omitted.", title="Name", @@ -6657,10 +7041,22 @@ class CreateLoopsRunRequest(BaseModel): base_checkpoint: Annotated[ str | None, Field( - description="Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + description="Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", title="Base Checkpoint", ), ] = None + base_checkpoint_auth: Annotated[ + TrainingWeightAuth | None, + Field( + description="Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + examples=[ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint", + } + ], + ), + ] = None sampler_num_replicas: Annotated[ SamplerNumReplicas | None, Field( @@ -6682,6 +7078,25 @@ class DeactivateLoopsRunResponse(BaseModel): user: Annotated[User, Field(description="The user who owns the Loops run.")] +class LoopsLoRAConfig(BaseModel): + config_version: Annotated[ + str, Field(description="The config version, like v1.", title="Config Version") + ] + targets: Annotated[ + list[str], + Field( + description="The module names the LoRA adapter targets.", title="Targets" + ), + ] + expert_layout: Annotated[ + Literal["per_expert", "shared_outer", "shared_adapter"] | str | None, + Field( + description="How routed-expert LoRA weights are laid out. Null when no experts are targeted.", + title="Expert Layout", + ), + ] = None + + class CreateLoopsTrainerRequest(BaseModel): session_id: Annotated[ str, @@ -6695,7 +7110,7 @@ class CreateLoopsTrainerRequest(BaseModel): Field(description="Base model ID (e.g. 'Qwen/Qwen3-8B').", title="Base Model"), ] name: Annotated[ - Name3 | None, + Name6 | None, Field( description="Optional display name for the run. Defaults to the base model name when omitted.", title="Name", @@ -6764,10 +7179,22 @@ class CreateLoopsTrainerRequest(BaseModel): base_checkpoint: Annotated[ str | None, Field( - description="Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + description="Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", title="Base Checkpoint", ), ] = None + base_checkpoint_auth: Annotated[ + TrainingWeightAuth | None, + Field( + description="Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + examples=[ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint", + } + ], + ), + ] = None scope: Annotated[ Literal["default", "serverless", "dedicated"] | str, Field( @@ -6882,25 +7309,6 @@ class GetLoopsSamplerResponse(BaseModel): sampler: Annotated[LoopsSampler, Field(description="The Loops sampler.")] -class LoopsLoRAConfig(BaseModel): - config_version: Annotated[ - str, Field(description="The config version, like v1.", title="Config Version") - ] - targets: Annotated[ - list[str], - Field( - description="The module names the LoRA adapter targets.", title="Targets" - ), - ] - expert_layout: Annotated[ - Literal["per_expert", "shared_outer", "shared_adapter"] | str | None, - Field( - description="How routed-expert LoRA weights are laid out. Null when no experts are targeted.", - title="Expert Layout", - ), - ] = None - - class ValidateLoopsCheckpointRequest(BaseModel): checkpoint_path: Annotated[ str, @@ -6968,6 +7376,34 @@ class DeployLoopsCheckpointResponse(BaseModel): ] +class LoopsCheckpointTombstone(BaseModel): + id: Annotated[str, Field(description="The deleted checkpoint ID.", title="Id")] + run_id: Annotated[ + str, + Field( + description="The ID of the run that produced the checkpoint.", + title="Run Id", + ), + ] + checkpoint_id: Annotated[ + str, + Field( + description="The name the checkpoint was saved under.", + title="Checkpoint Id", + ), + ] + target: Annotated[ + Literal["sampler", "trainer"] | str, + Field( + description="Whether the checkpoint was loadable by the sampler or by the run.", + title="TrainerCheckpointTarget", + ), + ] + path: Annotated[ + str, Field(description="The checkpoint's bt:// path.", title="Path") + ] + + class LoopsCheckpointFilesResponse(BaseModel): presigned_urls: Annotated[ list[CheckpointFile], @@ -7029,6 +7465,28 @@ class LoopsCheckpointSourceResponse(BaseModel): ] +class TtlSeconds(RootModel[int]): + root: Annotated[ + int, + Field( + description="Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", + ge=3600, + le=315360000, + title="Ttl Seconds", + ), + ] + + +class SetLoopsCheckpointTtlRequest(BaseModel): + ttl_seconds: Annotated[ + TtlSeconds | None, + Field( + description="Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", + title="Ttl Seconds", + ), + ] + + class LoopsDeploymentStatus(BaseModel): name: Annotated[ Literal[ @@ -7221,14 +7679,14 @@ class TeamTrainingGpuCapacityItem(BaseModel): baseline: Annotated[ int, Field( - description="Baseline GPU allocation for the team. 0 if not configured.", + description="Configured minimum GPU allocation for the team. Not enforced. 0 if not configured.", title="Baseline", ), ] limit: Annotated[ int, Field( - description="Maximum concurrent GPUs of this type for this team", + description="The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", title="Limit", ), ] @@ -7242,7 +7700,7 @@ class TeamTrainingGpuCapacityItem(BaseModel): dedicated_usage_count: Annotated[ int, Field( - description="Portion of usage_count from standard (non-spot) jobs.", + description="Portion of usage_count from on-demand (non-spot) jobs.", title="Dedicated Usage Count", ), ] = 0 @@ -7265,17 +7723,31 @@ class TrainingGpuCapacityItem(BaseModel): baseline: Annotated[ int, Field( - description="Baseline GPU allocation; jobs below this threshold are expected to run immediately. 0 if not configured.", + description="Configured minimum GPU allocation (`min_gpus`). 0 if not configured. Use `on_demand_quota` for the quota applied to on-demand jobs.", title="Baseline", ), ] limit: Annotated[ int, Field( - description="Maximum concurrent GPUs of this type for this org", + description="Configured maximum GPU allocation (`max_gpus`). Use `on_demand_quota` and `spot_quota` for the quotas applied to jobs.", title="Limit", ), ] + on_demand_quota: Annotated[ + int, + Field( + description="GPU quota for this type for on-demand (non-spot) jobs: the most GPUs they can use at once.", + title="On Demand Quota", + ), + ] + spot_quota: Annotated[ + int | None, + Field( + description="GPU quota for this type for spot jobs. Spot shares this quota with on-demand jobs: spot can use up to the quota minus on-demand GPUs in use. Null if spot is not enabled for the organization.", + title="Spot Quota", + ), + ] = None usage_count: Annotated[ int, Field( @@ -7286,14 +7758,14 @@ class TrainingGpuCapacityItem(BaseModel): dedicated_usage_count: Annotated[ int, Field( - description="Portion of usage_count from standard (non-spot) jobs, which run against the baseline.", + description="Portion of usage_count from on-demand (non-spot) jobs.", title="Dedicated Usage Count", ), ] = 0 spot_usage_count: Annotated[ int, Field( - description="Portion of usage_count from spot jobs, which burst into the peak and may push usage above the limit.", + description="Portion of usage_count from spot jobs.", title="Spot Usage Count", ), ] = 0 @@ -7303,17 +7775,24 @@ class GetTrainingGpuCapacityResponse(BaseModel): gpu_capacities: Annotated[ list[TrainingGpuCapacityItem], Field( - description="Org-level GPU capacity limits and current usage per GPU type", + description="Organization GPU quotas and current usage per GPU type", title="Gpu Capacities", ), ] team_gpu_capacities: Annotated[ list[TeamTrainingGpuCapacityItem] | None, Field( - description="Per-team GPU capacity limits and current usage per GPU type", + description="Per-team GPU quotas and current usage per GPU type", title="Team Gpu Capacities", ), ] = None + spot_enabled: Annotated[ + bool, + Field( + description="Whether the organization can submit spot training jobs.", + title="Spot Enabled", + ), + ] = False class PatchTeamTrainingGpuCapacityRequest(BaseModel): @@ -7327,7 +7806,7 @@ class PatchTeamTrainingGpuCapacityRequest(BaseModel): max_gpus: Annotated[ int, Field( - description="Max concurrent GPUs of this type the team may use", + description="The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", examples=[8, 16, 32], title="Max Gpus", ), @@ -7336,8 +7815,7 @@ class PatchTeamTrainingGpuCapacityRequest(BaseModel): class PatchTeamTrainingGpuCapacityResponse(BaseModel): team_gpu_capacity: Annotated[ - TeamTrainingGpuCapacityItem, - Field(description="The updated per-team GPU capacity limit"), + TeamTrainingGpuCapacityItem, Field(description="The updated per-team GPU quota") ] @@ -8390,7 +8868,7 @@ class Subtotal5(RootModel[str]): root: Annotated[ str, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), @@ -8515,6 +8993,20 @@ class ModelApiItem(BaseModel): float | Subtotal10, Field(description="Subtotal cost in dollars for this model", title="Subtotal"), ] + team_id: Annotated[ + str | None, + Field( + description="Team ID for multi-team organizations; otherwise null", + title="Team Id", + ), + ] = None + team_name: Annotated[ + str | None, + Field( + description="Team name, including historical teams; null if unavailable", + title="Team Name", + ), + ] = None input_tokens: Annotated[ int, Field(description="Total input tokens for this model", title="Input Tokens"), @@ -8543,18 +9035,32 @@ class Subtotal11(RootModel[str]): root: Annotated[ str, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), ] +class Total2(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="Usage charges in dollars after applying credits, floored at zero", + pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", + title="Total", + ), + ] + + class ModelApisUsage(BaseModel): subtotal: Annotated[ float | Subtotal11, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", title="Subtotal", ), ] @@ -8563,11 +9069,18 @@ class ModelApisUsage(BaseModel): Field(description="Credits applied in dollars", title="Credits Used"), ] total: Annotated[ - float | Total, Field(description="Total cost in dollars", title="Total") + float | Total2, + Field( + description="Usage charges in dollars after applying credits, floored at zero", + title="Total", + ), ] breakdown: Annotated[ list[ModelApiItem] | None, - Field(description="Per-model usage breakdown", title="Breakdown"), + Field( + description="Per-model usage breakdown, split by team for multi-team organizations", + title="Breakdown", + ), ] = None @@ -8592,13 +9105,27 @@ class Subtotal13(RootModel[str]): root: Annotated[ str, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), ] +class Total3(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="Total cost in dollars", + pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", + title="Total", + ), + ] + + class ToolCallUsageBucket(BaseModel): date: Annotated[ date_aliased, @@ -8701,17 +9228,796 @@ class OrganizationInfo(BaseModel): description="AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" ), ] = None - - -class GatewayEventTokens(BaseModel): - inputTokens: Annotated[ - int, Field(description="Cached and uncached input tokens.", title="Inputtokens") - ] - outputTokens: Annotated[ - int, Field(description="Output tokens.", title="Outputtokens") + allow_personal_api_keys: Annotated[ + bool, + Field( + description="Whether members can create new personal API keys. Existing keys keep working.", + title="Allow Personal Api Keys", + ), ] - cachedInputTokens: Annotated[ - int, Field(description="Cached input tokens.", title="Cachedinputtokens") + allow_service_account_api_keys: Annotated[ + bool, + Field( + description="Whether new team and organization API keys can be created. Existing keys keep working.", + title="Allow Service Account Api Keys", + ), + ] + + +class UpdateOrganizationRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + allow_personal_api_keys: Annotated[ + bool | None, + Field( + description="Whether members can create new personal API keys. Null is not accepted.", + title="Allow Personal Api Keys", + ), + ] = None + allow_service_account_api_keys: Annotated[ + bool | None, + Field( + description="Whether new team and organization API keys can be created. Null is not accepted.", + title="Allow Service Account Api Keys", + ), + ] = None + + +class ServiceAccountPresetPermissionsRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[ + Literal[ + "WORKSPACE_MANAGE_ALL", + "WORKSPACE_INVOKE", + "WORKSPACE_EXPORT_METRICS", + "WORKSPACE_MANAGE_API_KEYS", + "WORKSPACE_INVOKE_MODEL_APIS", + ] + | str, + Field( + description="What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + examples=["WORKSPACE_MANAGE_ALL"], + title="ServiceAccountPresetTypeV1", + ), + ] + model_ids: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + examples=[["abcd1234"]], + title="Model Ids", + ), + ] = None + environment_names: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + examples=[["production"]], + title="Environment Names", + ), + ] = None + model_api_slugs: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + examples=[["my-model-api"]], + title="Model Api Slugs", + ), + ] = None + + +class Description(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Optional description, up to 1,024 characters", + max_length=1024, + title="Description", + ), + ] = None + + +class TeamId4(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="The team that owns the account. Omit for an organization account. Can't be changed.", + min_length=1, + title="Team Id", + ), + ] = None + + +class CreateServiceAccountRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + str, + Field( + description="Name, unique in the organization. Can be changed later.", + examples=["ci-deployer"], + max_length=255, + min_length=1, + title="Name", + ), + ] + description: Annotated[ + Description | None, + Field( + description="Optional description, up to 1,024 characters", + title="Description", + ), + ] = None + team_id: Annotated[ + TeamId4 | None, + Field( + description="The team that owns the account. Omit for an organization account. Can't be changed.", + title="Team Id", + ), + ] = None + preset_permissions: Annotated[ + ServiceAccountPresetPermissionsRequest, + Field( + description="What the service account may do. Can be changed later. Temporary; may be removed once fine-grained access control is available." + ), + ] + + +class DeletedServiceAccount(BaseModel): + id: Annotated[ + str, Field(description="ID of the deleted service account", title="Id") + ] + deleted: Annotated[bool, Field(description="Always true", title="Deleted")] + + +class Name8(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Name, unique in the organization", + max_length=255, + min_length=1, + title="Name", + ), + ] = None + + +class Description1(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Description, up to 1,024 characters; null clears it", + max_length=1024, + title="Description", + ), + ] = None + + +class UpdateServiceAccountRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name8 | None, + Field(description="Name, unique in the organization", title="Name"), + ] = None + description: Annotated[ + Description1 | None, + Field( + description="Description, up to 1,024 characters; null clears it", + title="Description", + ), + ] = None + disabled: Annotated[ + bool | None, + Field( + description="Disable the account to stop it being used, or enable it again", + title="Disabled", + ), + ] = None + preset_permissions: Annotated[ + ServiceAccountPresetPermissionsRequest | None, + Field( + description="Replaces the account's access as a whole. Temporary; may be removed once fine-grained access control is available." + ), + ] = None + + +class PredefinedIdentityProvider(BaseModel): + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Pass as `kind` when adding the provider", + title="PredefinedIdentityProviderKindV1", + ), + ] + name: Annotated[str, Field(description="Display name", title="Name")] + issuer_url: Annotated[ + str | None, + Field( + description="The `iss` claim its tokens carry. Null when each account, tenant, or cluster has its own issuer, which you pass as `issuer_url` when adding the provider.", + title="Issuer Url", + ), + ] = None + issuer_url_example: Annotated[ + str | None, + Field( + description="An example of the `issuer_url` to pass. Null when the issuer is fixed.", + title="Issuer Url Example", + ), + ] = None + + +class PredefinedIdentityProviders(BaseModel): + items: Annotated[ + list[PredefinedIdentityProvider], + Field(description="Identity providers Baseten supports", title="Items"), + ] + + +class IssuerUrl(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + max_length=1024, + title="Issuer Url", + ), + ] = None + + +class PredefinedIdentityProviderConfig(BaseModel): + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Which predefined provider. Can't be changed.", + title="PredefinedIdentityProviderKindV1", + ), + ] + issuer_url: Annotated[ + IssuerUrl | None, + Field( + description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + title="Issuer Url", + ), + ] = None + + +class CreatePredefinedIdentityProviderConfig(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Which predefined provider. Can't be changed.", + title="PredefinedIdentityProviderKindV1", + ), + ] + issuer_url: Annotated[ + IssuerUrl | None, + Field( + description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + title="Issuer Url", + ), + ] = None + + +class Name9(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", + max_length=255, + min_length=1, + title="Name", + ), + ] = None + + +class Description2(RootModel[str]): + root: Annotated[ + str | None, + Field(description="Optional description", max_length=1024, title="Description"), + ] = None + + +class CreateIdentityProviderRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name9 | None, + Field( + description="Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", + title="Name", + ), + ] = None + description: Annotated[ + Description2 | None, + Field(description="Optional description", title="Description"), + ] = None + predefined: Annotated[ + CreatePredefinedIdentityProviderConfig, + Field(description="The predefined provider to add"), + ] + + +class VerifyPredefinedIdentityProviderConfig(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Which predefined provider", + title="PredefinedIdentityProviderKindV1", + ), + ] + issuer_url: Annotated[ + str | None, + Field( + description="The issuer to check, for AWS IAM, Amazon EKS, Azure managed identity, and Azure Kubernetes Service, in the format the predefined identity providers endpoint shows", + title="Issuer Url", + ), + ] = None + + +class VerifyIdentityProviderRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + predefined: Annotated[ + VerifyPredefinedIdentityProviderConfig, + Field( + description="The predefined provider to check, as you'd pass it when adding it" + ), + ] + + +class Verification(BaseModel): + valid: Annotated[ + bool, Field(description="Whether the input passes every check", title="Valid") + ] + error: Annotated[ + str | None, + Field( + description="Why the input fails, as creating it would report. Null when it's valid.", + title="Error", + ), + ] = None + + +class DeletedIdentityProvider(BaseModel): + id: Annotated[ + str, Field(description="ID of the deleted identity provider", title="Id") + ] + deleted: Annotated[bool, Field(description="Always true", title="Deleted")] + + +class Name10(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Name, unique in the organization", + max_length=255, + min_length=1, + title="Name", + ), + ] = None + + +class Description3(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Description; null clears it", + max_length=1024, + title="Description", + ), + ] = None + + +class UpdateIdentityProviderRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name10 | None, + Field(description="Name, unique in the organization", title="Name"), + ] = None + description: Annotated[ + Description3 | None, + Field(description="Description; null clears it", title="Description"), + ] = None + + +class AccessTrustRule(BaseModel): + id: Annotated[ + str, + Field( + description="Trust rule ID. Workloads pass it when they exchange a token.", + title="Id", + ), + ] + name: Annotated[ + str, Field(description="Name, unique in the organization", title="Name") + ] + description: Annotated[ + str | None, Field(description="Description", title="Description") + ] = None + identity_provider_id: Annotated[ + str, + Field( + description="The identity provider whose tokens it accepts", + title="Identity Provider Id", + ), + ] + identity_provider_name: Annotated[ + str, + Field( + description="Name of the identity provider", title="Identity Provider Name" + ), + ] + service_account_id: Annotated[ + str, + Field( + description="The service account its tokens act as", + title="Service Account Id", + ), + ] + service_account_name: Annotated[ + str, + Field(description="Name of the service account", title="Service Account Name"), + ] + team_id: Annotated[ + str | None, + Field( + description="The service account's team. Null for an organization service account.", + title="Team Id", + ), + ] = None + team_name: Annotated[ + str | None, + Field( + description="Name of the service account's team. Null for an organization service account.", + title="Team Name", + ), + ] = None + condition: Annotated[ + str, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + examples=[ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + title="Condition", + ), + ] + audience: Annotated[ + str, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + title="Audience", + ), + ] + max_access_token_lifetime_seconds: Annotated[ + int, + Field( + description="Longest lifetime of a token the rule issues, in seconds", + title="Max Access Token Lifetime Seconds", + ), + ] + last_used_at: Annotated[ + AwareDatetime | None, + Field( + description="Last time a request authenticated with a token the rule issued, to within an hour. Null until the first.", + title="Last Used At", + ), + ] = None + created_by: Annotated[ + str, + Field(description="ID of the user who created the rule", title="Created By"), + ] + created_at: Annotated[ + AwareDatetime, + Field(description="Time the rule was created", title="Created At"), + ] + updated_at: Annotated[ + AwareDatetime, + Field(description="Time the rule was last updated", title="Updated At"), + ] + + +class AccessTrustRules(BaseModel): + items: Annotated[ + list[AccessTrustRule], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + +class CreateAccessTrustRuleRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + str, + Field( + description="Name, unique in the organization. Can be changed later.", + max_length=255, + min_length=1, + title="Name", + ), + ] + description: Annotated[ + str | None, Field(description="Optional description", title="Description") + ] = None + identity_provider_id: Annotated[ + str, + Field( + description="Whose tokens the rule accepts. Can't be changed.", + title="Identity Provider Id", + ), + ] + service_account_id: Annotated[ + str, + Field( + description="The service account its tokens act as. Can be changed later.", + title="Service Account Id", + ), + ] + condition: Annotated[ + str, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters. Can be changed later.", + examples=[ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + title="Condition", + ), + ] + audience: Annotated[ + str, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters. Can be changed later.", + title="Audience", + ), + ] + max_access_token_lifetime_seconds: Annotated[ + int, + Field( + description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Can be changed later.", + ge=60, + le=3600, + title="Max Access Token Lifetime Seconds", + ), + ] = 3600 + + +class VerifyAccessTrustRuleRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + identity_provider_id: Annotated[ + str, + Field( + description="The identity provider the rule is for, which decides the claims it must pin", + title="Identity Provider Id", + ), + ] + condition: Annotated[ + str, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + examples=[ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + title="Condition", + ), + ] + audience: Annotated[ + str, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + title="Audience", + ), + ] + + +class DeletedAccessTrustRule(BaseModel): + id: Annotated[str, Field(description="ID of the deleted trust rule", title="Id")] + deleted: Annotated[bool, Field(description="Always true", title="Deleted")] + + +class MaxAccessTokenLifetimeSeconds(RootModel[int]): + root: Annotated[ + int | None, + Field( + description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", + ge=60, + le=3600, + title="Max Access Token Lifetime Seconds", + ), + ] = None + + +class UpdateAccessTrustRuleRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name10 | None, + Field(description="Name, unique in the organization", title="Name"), + ] = None + description: Annotated[ + str | None, + Field(description="Description; null clears it", title="Description"), + ] = None + condition: Annotated[ + str | None, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + title="Condition", + ), + ] = None + audience: Annotated[ + str | None, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + title="Audience", + ), + ] = None + max_access_token_lifetime_seconds: Annotated[ + MaxAccessTokenLifetimeSeconds | None, + Field( + description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", + title="Max Access Token Lifetime Seconds", + ), + ] = None + service_account_id: Annotated[ + str | None, + Field( + description="Moves the rule to another service account. Tokens already issued keep the old account until they expire.", + title="Service Account Id", + ), + ] = None + + +class AccessTokenLifetimeSeconds(RootModel[int]): + root: Annotated[ + int | None, + Field( + description="Lifetime of the access token, in seconds. At most the rule's maximum.", + ge=1, + title="Access Token Lifetime Seconds", + ), + ] = None + + +class TokenExchangeRequest(BaseModel): + grant_type: Annotated[ + str, + Field( + description="Always `urn:ietf:params:oauth:grant-type:token-exchange`", + examples=["urn:ietf:params:oauth:grant-type:token-exchange"], + title="Grant Type", + ), + ] + subject_token: Annotated[ + str, + Field( + description="The identity provider's JWT", + examples=[""], + max_length=16384, + title="Subject Token", + ), + ] + subject_token_type: Annotated[ + str, + Field( + description="`urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`", + examples=["urn:ietf:params:oauth:token-type:jwt"], + title="Subject Token Type", + ), + ] + audience: Annotated[ + str, + Field( + description="ID of the trust rule to check the JWT against", + examples=["abcd1234"], + max_length=64, + title="Audience", + ), + ] + requested_token_type: Annotated[ + str | None, + Field( + description="Optional; only `urn:ietf:params:oauth:token-type:access_token` is issued", + title="Requested Token Type", + ), + ] = None + access_token_lifetime_seconds: Annotated[ + AccessTokenLifetimeSeconds | None, + Field( + description="Lifetime of the access token, in seconds. At most the rule's maximum.", + title="Access Token Lifetime Seconds", + ), + ] = None + + +class TokenExchangeResponse(BaseModel): + access_token: Annotated[ + str, Field(description="Send as `Authorization: Bearer`", title="Access Token") + ] + issued_token_type: Annotated[ + str, + Field( + description="Always `urn:ietf:params:oauth:token-type:access_token`", + title="Issued Token Type", + ), + ] + token_type: Annotated[str, Field(description="Always `Bearer`", title="Token Type")] + expires_in: Annotated[ + int, + Field(description="Seconds until the access token expires", title="Expires In"), + ] + + +class GatewayEventTokens(BaseModel): + inputTokens: Annotated[ + int, Field(description="Cached and uncached input tokens.", title="Inputtokens") + ] + outputTokens: Annotated[ + int, Field(description="Output tokens.", title="Outputtokens") + ] + cachedInputTokens: Annotated[ + int, Field(description="Cached input tokens.", title="Cachedinputtokens") ] @@ -8787,7 +10093,7 @@ class ExploreMetadataAPIFormats(BaseModel): ] = False -class TeamId4(RootModel[str]): +class TeamId5(RootModel[str]): root: Annotated[ str | None, Field( @@ -8801,7 +10107,7 @@ class TeamId4(RootModel[str]): class CreateGridTokenRequest(BaseModel): team_id: Annotated[ - TeamId4 | None, + TeamId5 | None, Field( description="ID of the team. When omitted, the team you belong to; required when you belong to several.", examples=["abc1234"], @@ -8843,21 +10149,19 @@ class GridToken(BaseModel): ] -class GridClassifier(BaseModel): - id: Annotated[ +class GridRouteAlias(BaseModel): + name: Annotated[ str, Field( - description="Stable classifier identifier.", - examples=["general-v1"], - title="Id", + description="Name to send in the inference request's `model` field instead of the route's `name`.", + title="Name", ), ] - name: Annotated[ - str, + kind: Annotated[ + Literal["CLAUDE_DESKTOP", "ALIAS"] | str, Field( - description="Display name of the classifier.", - examples=["General"], - title="Name", + description="Purpose of the alias. CLAUDE_DESKTOP is for Claude Code desktop, which rejects model names without a `claude` substring. ALIAS is any other name the team's clients send for the route.", + title="GridRouteAliasKindV1", ), ] @@ -8867,16 +10171,16 @@ class GridRouteClassifier(BaseModel): str, Field( description="Stable route classifier identifier.", - examples=["general-v1"], + examples=["abc1234"], title="Id", ), ] - name: Annotated[ + display_name: Annotated[ str, Field( description="Display name of the route classifier.", examples=["General"], - title="Name", + title="Display Name", ), ] supported_tradeoffs: Annotated[ @@ -8886,23 +10190,12 @@ class GridRouteClassifier(BaseModel): title="Supported Tradeoffs", ), ] - decidable_models: Annotated[ + decidable_canonical_model_ids: Annotated[ list[str], Field( - description="Model identities the route classifier picks from.", + description="Canonical model ids the route classifier picks from.", examples=[["zai-org/GLM-5.3", "anthropic/claude-opus-5-5"]], - title="Decidable Models", - ), - ] - - -class GridRouteRef(BaseModel): - id: Annotated[str, Field(description="Stable route identifier.", title="Id")] - slug: Annotated[ - str, - Field( - description="Name of the route to send in the inference request's model field.", - title="Slug", + title="Decidable Canonical Model Ids", ), ] @@ -8913,31 +10206,8 @@ class GridRouteTargetBasetenModelAPI(BaseModel): Field(description="Target kind for a Baseten Model API.", title="Type"), ] model: Annotated[ - str, - Field(description="Name of the target Model API.", min_length=1, title="Model"), - ] - - -class GridRouteTargetClassifier(BaseModel): - type: Annotated[ - Literal["CLASSIFIER"], - Field(description="Target kind for a classifier-based route.", title="Type"), - ] - classifier: Annotated[ - GridClassifier | None, - Field( - description="Classifier that picks a route for each request. Null for routers created before classifiers could be selected." - ), - ] - default_route: Annotated[ - GridRouteRef, Field(description="Route used when the classifier picks none.") - ] - allowed_routes: Annotated[ - list[GridRouteRef], - Field( - description="Routes the classifier may pick, in creation order.", - title="Allowed Routes", - ), + str, + Field(description="Name of the target Model API.", min_length=1, title="Model"), ] @@ -8998,70 +10268,64 @@ class UpsertGridRouteTargetBasetenModelAPI(BaseModel): ] -class UpsertGridRouteTargetClassifier(BaseModel): +class UpsertGridRouteTargetConnection(BaseModel): model_config = ConfigDict( extra="forbid", ) type: Annotated[ - Literal["CLASSIFIER"], - Field(description="Target kind for a classifier-based route.", title="Type"), - ] - classifier_id: Annotated[ - str, + Literal["CONNECTION"], Field( - description="ID of the classifier that picks a route for each request.", - examples=["general-v1"], - min_length=1, - title="Classifier Id", + description="Target kind for a provider reached through a team connection.", + title="Type", ), ] - allowed_route_ids: Annotated[ - list[str], + model: Annotated[ + str, Field( - description="IDs of the routes the classifier may pick. All must belong to the route's team and must not be routers themselves.", - examples=[["abc1234", "def5678"]], - title="Allowed Route Ids", + description="Model name sent to the provider.", min_length=1, title="Model" ), ] - default_route_id: Annotated[ + connection_id: Annotated[ str, Field( - description="ID of the allowed route used when the classifier picks none.", + description="Identifier of a connection owned by the route's team. Its provider serves the route.", examples=["abc1234"], - title="Default Route Id", + min_length=1, + title="Connection Id", ), ] -class UpsertGridRouteTargetConnection(BaseModel): +class UpsertGridRouteTargetIntelligent(BaseModel): model_config = ConfigDict( extra="forbid", ) type: Annotated[ - Literal["CONNECTION"], + Literal["INTELLIGENT"], Field( - description="Target kind for a provider reached through a team connection.", + description="Target kind for an intelligent route: Baseten picks the model per request.", title="Type", ), ] - model: Annotated[ + route_classifier_id: Annotated[ str, Field( - description="Model name sent to the provider.", min_length=1, title="Model" + description="Identifier of the route classifier that picks the model. List them with GET /v1/grid/route_classifiers.", + examples=["abc1234"], + min_length=1, + title="Route Classifier Id", ), ] - connection_id: Annotated[ - str, + tradeoff: Annotated[ + Literal["cost", "balanced", "intelligence"] | str, Field( - description="Identifier of a connection owned by the route's team. Its provider serves the route.", - examples=["abc1234"], - min_length=1, - title="Connection Id", + description="How the classifier weighs cost against quality. Must be one of the classifier's supported tradeoffs.", + title="GridRouteTradeoffV1", ), ] -class TeamId5(RootModel[str]): +class TeamId6(RootModel[str]): root: Annotated[ str | None, Field( @@ -9077,7 +10341,7 @@ class DisplayName(RootModel[str]): root: Annotated[ str | None, Field( - description="Display label. Omit to use the route name; null is not accepted.", + description="Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", examples=["Assistant"], max_length=255, min_length=1, @@ -9086,7 +10350,7 @@ class DisplayName(RootModel[str]): ] = None -class Description(RootModel[str]): +class Description4(RootModel[str]): root: Annotated[ str | None, Field( @@ -9103,7 +10367,7 @@ class CreateGridRouteRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId5 | None, + TeamId6 | None, Field( description="Identifier of the team that owns the route.", examples=["abc1234"], @@ -9113,7 +10377,7 @@ class CreateGridRouteRequest(BaseModel): display_name: Annotated[ DisplayName | None, Field( - description="Display label. Omit to use the route name; null is not accepted.", + description="Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", examples=["Assistant"], title="Display Name", ), @@ -9122,9 +10386,9 @@ class CreateGridRouteRequest(BaseModel): Annotated[ UpsertGridRouteTargetBasetenModelAPI | UpsertGridRouteTargetConnection - | UpsertGridRouteTargetClassifier, + | UpsertGridRouteTargetIntelligent, Field( - description="Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team.", + description="Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team. INTELLIGENT targets need at least one of the route classifier's models, and one of its fallback models, servable by the team.", discriminator="type", examples=[{"model": "zai-org/GLM-5.3", "type": "BASETEN_MODEL_API"}], title="Target", @@ -9134,7 +10398,7 @@ class CreateGridRouteRequest(BaseModel): Field(union_mode="left_to_right"), ] description: Annotated[ - Description | None, + Description4 | None, Field( description="Short description of the route. Omit for no description; null is not accepted.", examples=["Assistant for code review and debugging."], @@ -9181,6 +10445,7 @@ class GridRouteUsageResult(BaseModel): "VERTEX", "OPENAI_COMPATIBLE", "BEDROCK", + "AZURE", ] | str | None, @@ -9188,11 +10453,18 @@ class GridRouteUsageResult(BaseModel): description="Provider that served the requests. Null when not grouping by PROVIDER." ), ] = None - intelligent_route: Annotated[ + intelligent_route_id: Annotated[ + str | None, + Field( + description="ID of the intelligent route, as `id` in GET /v1/grid/routes. Null when not grouping by INTELLIGENT_ROUTE.", + title="Intelligent Route Id", + ), + ] = None + intelligent_route_display_name: Annotated[ str | None, Field( - description="Name of the intelligent route, as in `GET /v1/grid/routes`. Null when not grouping by INTELLIGENT_ROUTE.", - title="Intelligent Route", + description="Display name of the intelligent route. Null when `intelligent_route_id` is null or the route cannot be resolved.", + title="Intelligent Route Display Name", ), ] = None harness: Annotated[ @@ -9201,6 +10473,20 @@ class GridRouteUsageResult(BaseModel): description="Coding harness. Null when not grouping by HARNESS, when no harness was recorded (including usage from before harness tracking), or when the recorded harness is not recognized by this API version." ), ] = None + api_key_prefix: Annotated[ + str | None, + Field( + description="Prefix of the API key that made the requests, matching `GET /v1/api_keys`. Null when not grouping by API_KEY, for usage without an API key, and for usage recorded before API key tracking.", + title="Api Key Prefix", + ), + ] = None + api_key_name: Annotated[ + str | None, + Field( + description="Name of the API key. Null when `api_key_prefix` is null or the key has no name.", + title="Api Key Name", + ), + ] = None cost_usd: Annotated[ str, Field( @@ -9249,7 +10535,7 @@ class GridRouteTombstone(BaseModel): name: Annotated[str, Field(description="Name of the deleted route.", title="Name")] -class Description1(RootModel[str]): +class Description5(RootModel[str]): root: Annotated[ str | None, Field( @@ -9279,7 +10565,7 @@ class UpdateGridRouteRequest(BaseModel): extra="forbid", ) description: Annotated[ - Description1 | None, + Description5 | None, Field( description="New description. Omit to keep the current description; use an empty string to clear it. Null is not accepted.", examples=["Assistant for code review and debugging."], @@ -9294,16 +10580,6 @@ class UpdateGridRouteRequest(BaseModel): title="Display Name", ), ] = None - target: Annotated[ - UpsertGridRouteTargetBasetenModelAPI - | UpsertGridRouteTargetConnection - | UpsertGridRouteTargetClassifier - | None, - Field( - description="Complete new target configuration. Omit to keep the current configuration; null is not accepted. Only the CLASSIFIER configuration of a router route is mutable.", - title="Target", - ), - ] = None class GridTeamSpendLimitSetting(BaseModel): @@ -9518,6 +10794,34 @@ class GridConnectionConfigAnthropic(BaseModel): ] +class GridConnectionConfigAzure(BaseModel): + provider: Annotated[ + Literal["AZURE"], + Field(description="Provider kind for Microsoft Azure.", title="Provider"), + ] + secret_id: Annotated[ + str, + Field( + description="Identifier of the team secret holding the provider API key.", + title="Secret Id", + ), + ] + secret_name: Annotated[ + str, + Field( + description="Name of the team secret holding the provider API key.", + title="Secret Name", + ), + ] + resource_name: Annotated[ + str, + Field( + description="Name of the Azure AI Foundry or Azure OpenAI resource.", + title="Resource Name", + ), + ] + + class GridConnectionConfigBedrock(BaseModel): provider: Annotated[ Literal["BEDROCK"], @@ -9652,7 +10956,8 @@ class GridConnection(BaseModel): | GridConnectionConfigOpenAI | GridConnectionConfigXAI | GridConnectionConfigVertex - | GridConnectionConfigBedrock, + | GridConnectionConfigBedrock + | GridConnectionConfigAzure, Field( description="Provider the connection authenticates with, and the team secret holding its API key.", discriminator="provider", @@ -9725,6 +11030,37 @@ class UpsertGridConnectionConfigAnthropic(BaseModel): ] +class UpsertGridConnectionConfigAzure(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + provider: Annotated[ + Literal["AZURE"], + Field( + description="Provider kind for Microsoft Azure. Route targets name a deployment, which must be named after its Azure model. Claude models (`claude-*`) use the Anthropic Messages API, and other models use the OpenAI-compatible APIs.", + title="Provider", + ), + ] + secret_name: Annotated[ + str, + Field( + description="Name of an existing secret, owned by the same team, that holds the provider API key.", + examples=["anthropic-key"], + min_length=1, + title="Secret Name", + ), + ] + resource_name: Annotated[ + str, + Field( + description="Name of the Azure AI Foundry or Azure OpenAI resource, the subdomain of `.openai.azure.com`.", + examples=["my-foundry-resource"], + min_length=1, + title="Resource Name", + ), + ] + + class UpsertGridConnectionConfigBedrock(BaseModel): model_config = ConfigDict( extra="forbid", @@ -9843,7 +11179,7 @@ class UpsertGridConnectionConfigXAI(BaseModel): ] -class TeamId6(RootModel[str]): +class TeamId7(RootModel[str]): root: Annotated[ str | None, Field( @@ -9860,7 +11196,7 @@ class CreateGridConnectionRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId6 | None, + TeamId7 | None, Field( description="Identifier of the team that owns the connection.", examples=["abc1234"], @@ -9873,7 +11209,8 @@ class CreateGridConnectionRequest(BaseModel): | UpsertGridConnectionConfigOpenAI | UpsertGridConnectionConfigXAI | UpsertGridConnectionConfigVertex - | UpsertGridConnectionConfigBedrock, + | UpsertGridConnectionConfigBedrock + | UpsertGridConnectionConfigAzure, Field( description="Provider the connection authenticates with, and the team secret holding its API key.", discriminator="provider", @@ -9903,7 +11240,8 @@ class UpdateGridConnectionRequest(BaseModel): | UpsertGridConnectionConfigOpenAI | UpsertGridConnectionConfigXAI | UpsertGridConnectionConfigVertex - | UpsertGridConnectionConfigBedrock, + | UpsertGridConnectionConfigBedrock + | UpsertGridConnectionConfigAzure, Field( description="Complete new connection configuration, replacing the current one. The provider must match the connection and is immutable.", discriminator="provider", @@ -9916,15 +11254,6 @@ class UpdateGridConnectionRequest(BaseModel): ] -class GridClassifiersResponse(BaseModel): - items: Annotated[ - list[GridClassifier], Field(description="Items in this page.", title="Items") - ] - pagination: Annotated[ - PaginationResponse, Field(description="Pagination metadata for the page.") - ] - - class GridRouteClassifiersResponse(BaseModel): items: Annotated[ list[GridRouteClassifier], @@ -9985,7 +11314,7 @@ class GridMachineUsersResponse(BaseModel): ] -class Name5(RootModel[str]): +class Name12(RootModel[str]): root: Annotated[ str | None, Field( @@ -10003,7 +11332,7 @@ class CreateGridMachineUserAPIKeyRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name5 | None, + Name12 | None, Field( description="Name of the API key: lowercase letters, numbers, and hyphens, at most 255 characters, and unique among the machine user's active keys. Defaults to a name derived from the machine user's.", examples=["production"], @@ -10012,7 +11341,7 @@ class CreateGridMachineUserAPIKeyRequest(BaseModel): ] = None -class TeamId7(RootModel[str]): +class TeamId8(RootModel[str]): root: Annotated[ str | None, Field( @@ -10029,7 +11358,7 @@ class CreateGridMachineUserRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId7 | None, + TeamId8 | None, Field( description="Identifier of the team that owns the machine user. Defaults to your only team, if you belong to exactly one.", examples=["abc1234"], @@ -10107,7 +11436,7 @@ class GridMachineUserTombstone(BaseModel): ] -class Name6(RootModel[str]): +class Name13(RootModel[str]): root: Annotated[ str | None, Field( @@ -10124,7 +11453,7 @@ class UpdateGridMachineUserRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name6 | None, + Name13 | None, Field( description="Name of the machine user, unique within its team. At most 255 characters. Omit to keep it.", title="Name", @@ -10390,7 +11719,7 @@ class EffectiveRateLimit(BaseModel): ] -class Name7(RootModel[str]): +class Name14(RootModel[str]): root: Annotated[ str | None, Field( @@ -10404,7 +11733,7 @@ class Name7(RootModel[str]): class GroupMetadata(BaseModel): name: Annotated[ - Name7 | None, + Name14 | None, Field( description="Optional display name for the group.", examples=["Acme prod"], @@ -10508,7 +11837,7 @@ class CreateGroupHierarchy(BaseModel): class UpdateGroupMetadata(BaseModel): name: Annotated[ - Name7 | None, + Name14 | None, Field( description="Optional display name for the group.", examples=["Acme prod"], @@ -11369,6 +12698,7 @@ class GetAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY", ] | str ] @@ -11482,6 +12812,7 @@ class GetModelsAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY", ] | str ] @@ -11725,6 +13056,43 @@ class GetModelsDeploymentsStartupsParams(BaseModel): ] = None +class GetModelsDeploymentsReplicasParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + statuses: Annotated[ + list[ + Literal[ + "STARTING", + "ACTIVE", + "UNHEALTHY", + "TERMINATING", + "TERMINATED", + "UNKNOWN", + ] + | str + ] + | None, + Field( + description="Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + title="Statuses", + ), + ] = None + + class GetModelsEnvironmentsLogsParams(BaseModel): start_epoch_millis: Annotated[ int | None, @@ -11908,6 +13276,43 @@ class GetModelsEnvironmentsStartupsParams(BaseModel): ] = None +class GetModelsEnvironmentsReplicasParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + statuses: Annotated[ + list[ + Literal[ + "STARTING", + "ACTIVE", + "UNHEALTHY", + "TERMINATING", + "TERMINATED", + "UNKNOWN", + ] + | str + ] + | None, + Field( + description="Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + title="Statuses", + ), + ] = None + + class GetChainsAuditLogsParams(BaseModel): cursor: Annotated[ str | None, @@ -11961,6 +13366,7 @@ class GetChainsAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY", ] | str ] @@ -12301,6 +13707,13 @@ class GetModelApisMetricsParams(BaseModel): title="Metrics", ), ] = None + team_ids: Annotated[ + list[str] | None, + Field( + description="Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", + title="Team Ids", + ), + ] = None class GetBillingModelApisParams(BaseModel): @@ -12410,6 +13823,46 @@ class GetBillingToolCallUsageParams(BaseModel): ] = None +class GetAccessIdentityProvidersParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + name: Annotated[ + Name2 | None, + Field( + description="Only the provider with this name, ignoring case", title="Name" + ), + ] = None + predefined_kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str + | None, + Field(description="Only this predefined provider's issuers"), + ] = None + + class GetGridRoutesUsageParams(BaseModel): cursor: Annotated[ str | None, @@ -12450,12 +13903,20 @@ class GetGridRoutesUsageParams(BaseModel): ] = None group_by: Annotated[ list[ - Literal["USER", "TEAM", "MODEL", "PROVIDER", "INTELLIGENT_ROUTE", "HARNESS"] + Literal[ + "USER", + "TEAM", + "MODEL", + "PROVIDER", + "INTELLIGENT_ROUTE", + "HARNESS", + "API_KEY", + ] | str ] | None, Field( - description="Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", + description="Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", title="Group By", ), ] = None @@ -12483,6 +13944,7 @@ class GetGridRoutesUsageParams(BaseModel): "VERTEX", "OPENAI_COMPATIBLE", "BEDROCK", + "AZURE", ] | str ] @@ -12499,6 +13961,13 @@ class GetGridRoutesUsageParams(BaseModel): title="Harnesses", ), ] = None + api_key_prefixes: Annotated[ + list[str] | None, + Field( + description="Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", + title="Api Key Prefixes", + ), + ] = None class GetSandboxMetricsParams(BaseModel): @@ -12970,6 +14439,27 @@ class AuditLogEventEnvironmentUpdated(BaseModel): previous_settings: AuditLogEventEnvironmentSettings | None +class AuditLogEventIdentityProviderCreated(BaseModel): + event_type: Annotated[ + Literal["IDENTITY_PROVIDER_CREATED"], Field(title="Event Type") + ] + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + name: Annotated[str, Field(title="Name")] + description: Annotated[ + str | None, + Field( + description="Null when the provider was added without one.", + title="Description", + ), + ] = None + predefined: Annotated[ + AuditLogEventPredefinedIdentityProviderConfig, + Field( + description="The provider's settings, as the identity provider resource returns them." + ), + ] + + class AuditLogEventModelDeployed(BaseModel): event_type: Annotated[Literal["MODEL_DEPLOYED"], Field(title="Event Type")] model_id: Annotated[str, Field(title="Model Id")] @@ -13062,10 +14552,31 @@ class AuditLogEventModelPromotionControlAction(BaseModel): ] | str, Field( - description="User-initiated promotion control signal recorded on a promotion-control event.", - title="AuditLogPromotionControlActionV1", + description="User-initiated promotion control signal recorded on a promotion-control event.", + title="AuditLogPromotionControlActionV1", + ), + ] + + +class AuditLogEventServiceAccountCreated(BaseModel): + event_type: Annotated[Literal["SERVICE_ACCOUNT_CREATED"], Field(title="Event Type")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + name: Annotated[str, Field(title="Name")] + description: Annotated[ + str | None, + Field( + description="Null when the account was created without one.", + title="Description", + ), + ] = None + owner_team_id: Annotated[ + str | None, + Field( + description="The team that owns the account. Null for an organization account.", + title="Owner Team Id", ), - ] + ] = None + preset_permissions: AuditLogEventServiceAccountPresetPermissions class Deployment(BaseModel): @@ -13158,6 +14669,13 @@ class Deployment(BaseModel): description="Effective request backpressure settings for the deployment." ), ] + failure_reason: Annotated[ + str | None, + Field( + description="Why the deployment failed. Set only when the status is DEPLOY_FAILED; null otherwise.", + title="Failure Reason", + ), + ] = None class CreatedModelDeployment(BaseModel): @@ -13542,10 +15060,10 @@ class TrafficRoutingRuleUpsert(BaseModel): sampling_mode: Annotated[ Literal["RANDOM", "USER_SESSION"] | str, Field( - description="How requests are picked for shadowing", + description="How requests are picked for shadowing. Defaults to USER_SESSION.", title="TrafficRoutingRuleShadowSamplingModeV1", ), - ] + ] = "USER_SESSION" propagate_client_cancellation: Annotated[ bool, Field( @@ -13915,7 +15433,14 @@ class UpdateChainletEnvironmentInstanceTypeResponse(BaseModel): ] +class TrainingBDNConfigResponse(BaseModel): + mounts: Annotated[list[TrainingBDNMountResponse] | None, Field(title="Mounts")] = ( + None + ) + + class TrainingJob(BaseModel): + bdn: TrainingBDNConfigResponse | None = None id: Annotated[ str, Field(description="Unique identifier of the training job.", title="Id") ] @@ -14226,6 +15751,15 @@ class RegistrySecretDockerAuth(BaseModel): ] +class TrainingBDNConfig(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + mounts: Annotated[ + list[TrainingBDNMount] | None, Field(max_length=32, title="Mounts") + ] = None + + class CreateTrainingJobResponse(BaseModel): training_job: Annotated[TrainingJob, Field(description="The created training job.")] @@ -14266,35 +15800,63 @@ class TrainingJobMetrics(BaseModel): gpu_memory_usage_bytes: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + description="A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Memory Usage Bytes", ), ] gpu_utilization: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + description="A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Utilization", ), ] + gpu_temperature_celsius: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Temperature Celsius", + ), + ] + gpu_power_usage_watts: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Power Usage Watts", + ), + ] + gpu_tensor_core_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Tensor Core Utilization", + ), + ] + gpu_memory_bandwidth_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Memory Bandwidth Utilization", + ), + ] cpu_usage: Annotated[ list[TrainingJobMetric], Field( - description="The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + description="The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Usage", ), ] cpu_memory_usage_bytes: Annotated[ list[TrainingJobMetric], Field( - description="The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + description="The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Memory Usage Bytes", ), ] ephemeral_storage: Annotated[ StorageMetrics, Field( - description="The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + description="The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." ), ] @@ -14310,35 +15872,63 @@ class GetTrainingJobMetricsResponse(BaseModel): gpu_memory_usage_bytes: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + description="A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Memory Usage Bytes", ), ] gpu_utilization: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + description="A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Utilization", ), ] + gpu_temperature_celsius: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Temperature Celsius", + ), + ] + gpu_power_usage_watts: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Power Usage Watts", + ), + ] + gpu_tensor_core_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Tensor Core Utilization", + ), + ] + gpu_memory_bandwidth_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Memory Bandwidth Utilization", + ), + ] cpu_usage: Annotated[ list[TrainingJobMetric], Field( - description="The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + description="The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Usage", ), ] cpu_memory_usage_bytes: Annotated[ list[TrainingJobMetric], Field( - description="The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + description="The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Memory Usage Bytes", ), ] ephemeral_storage: Annotated[ StorageMetrics, Field( - description="The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + description="The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." ), ] training_job: Annotated[TrainingJob, Field(description="The training job.")] @@ -14444,12 +16034,6 @@ class CreateLoopsRunResponse(BaseModel): run: LoopsRun -class GetLoopsRunResponse(BaseModel): - run: Annotated[ - LoopsRun, Field(description="The Loops run with its associated sampler.") - ] - - class LoopsCheckpoint(BaseModel): checkpoint_id: Annotated[ str, Field(description="The ID of the checkpoint.", title="Checkpoint Id") @@ -14507,6 +16091,30 @@ class LoopsCheckpoint(BaseModel): title="TrainerCheckpointTarget", ), ] + expires_at: Annotated[ + AwareDatetime | None, + Field( + description="When the checkpoint expires and is deleted, set from the TTL it was saved with. Null means it's kept until you delete it. A checkpoint that's still in use when it expires, for example deployed, is deleted once it's released.", + title="Expires At", + ), + ] + + +class DeleteLoopsRunResponse(BaseModel): + id: Annotated[str, Field(description="The deleted Loops run ID.", title="Id")] + kept_checkpoints: Annotated[ + list[LoopsCheckpoint], + Field( + description="The run's checkpoints that were not deleted because something still uses them, such as a deployment. They stay usable until that stops.", + title="Kept Checkpoints", + ), + ] + + +class GetLoopsRunResponse(BaseModel): + run: Annotated[ + LoopsRun, Field(description="The Loops run with its associated sampler.") + ] class ListLoopsCheckpointsResponse(BaseModel): @@ -15351,7 +16959,7 @@ class DedicatedUsage(BaseModel): subtotal: Annotated[ float | Subtotal5, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", title="Subtotal", ), ] @@ -15428,7 +17036,7 @@ class TrainingUsage(BaseModel): subtotal: Annotated[ float | Subtotal13, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", title="Subtotal", ), ] @@ -15437,7 +17045,7 @@ class TrainingUsage(BaseModel): Field(description="Credits applied in dollars", title="Credits Used"), ] total: Annotated[ - float | Total, Field(description="Total cost in dollars", title="Total") + float | Total3, Field(description="Total cost in dollars", title="Total") ] minutes: Annotated[int, Field(description="Total minutes used", title="Minutes")] breakdown: Annotated[ @@ -15446,6 +17054,137 @@ class TrainingUsage(BaseModel): ] = None +class ServiceAccountPresetPermissions(BaseModel): + type: Annotated[ + Literal[ + "WORKSPACE_MANAGE_ALL", + "WORKSPACE_INVOKE", + "WORKSPACE_EXPORT_METRICS", + "WORKSPACE_MANAGE_API_KEYS", + "WORKSPACE_INVOKE_MODEL_APIS", + ] + | str, + Field( + description="What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + examples=["WORKSPACE_MANAGE_ALL"], + title="ServiceAccountPresetTypeV1", + ), + ] + model_ids: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + examples=[["abcd1234"]], + title="Model Ids", + ), + ] = None + environment_names: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + examples=[["production"]], + title="Environment Names", + ), + ] = None + model_api_slugs: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + examples=[["my-model-api"]], + title="Model Api Slugs", + ), + ] = None + + +class ServiceAccount(BaseModel): + id: Annotated[str, Field(description="Service account ID", title="Id")] + name: Annotated[ + str, Field(description="Name, unique in the organization", title="Name") + ] + description: Annotated[ + str | None, Field(description="Description", title="Description") + ] = None + team_id: Annotated[ + str | None, + Field( + description="The team that owns the account. Null for an organization account.", + title="Team Id", + ), + ] = None + preset_permissions: Annotated[ + ServiceAccountPresetPermissions, + Field( + description="What the service account may do. Temporary; may be removed once fine-grained access control is available." + ), + ] + disabled: Annotated[ + bool, + Field( + description="Whether the account is disabled. A disabled account can't be used.", + title="Disabled", + ), + ] + last_used_at: Annotated[ + AwareDatetime | None, + Field( + description="Last time a request authenticated as this account, to within an hour. Null until the first.", + title="Last Used At", + ), + ] = None + created_at: Annotated[ + AwareDatetime, + Field(description="Time the account was created", title="Created At"), + ] + updated_at: Annotated[ + AwareDatetime, + Field(description="Time the account was last updated", title="Updated At"), + ] + + +class ServiceAccounts(BaseModel): + items: Annotated[ + list[ServiceAccount], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + +class IdentityProvider(BaseModel): + id: Annotated[str, Field(description="Identity provider ID", title="Id")] + name: Annotated[ + str, Field(description="Name, unique in the organization", title="Name") + ] + description: Annotated[ + str | None, Field(description="Description", title="Description") + ] = None + predefined: Annotated[ + PredefinedIdentityProviderConfig, + Field(description="Settings of the predefined provider"), + ] + created_by: Annotated[ + str, + Field(description="ID of the user who added the provider", title="Created By"), + ] + created_at: Annotated[ + AwareDatetime, + Field(description="Time the provider was added", title="Created At"), + ] + updated_at: Annotated[ + AwareDatetime, + Field(description="Time the provider was last updated", title="Updated At"), + ] + + +class IdentityProviders(BaseModel): + items: Annotated[ + list[IdentityProvider], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + class ExploreCost(BaseModel): input: Annotated[ float | None, @@ -15554,28 +17293,111 @@ class ExploreMetadataResponse(BaseModel): ] +class GridRouteMetadata(BaseModel): + slug: Annotated[ + str | None, + Field( + description="Metadata slug, e.g. 'anthropic/claude-opus-4'; null for rows without one.", + title="Slug", + ), + ] + display_name: Annotated[ + str | None, + Field(description="Model display name, when available.", title="Display Name"), + ] + release_date: Annotated[ + date_aliased | None, + Field( + description="Model release date. Month-only source dates use the first day of that month.", + title="Release Date", + ), + ] + provider: Annotated[ + str | None, + Field( + description="Provider key derived from the slug prefix, e.g. 'anthropic'; null for unprefixed slugs.", + title="Provider", + ), + ] + context_window: Annotated[ + int | None, + Field(description="Total context window in tokens.", title="Context Window"), + ] + max_output_tokens: Annotated[ + int | None, + Field( + description="Maximum output tokens per response.", title="Max Output Tokens" + ), + ] + input_modalities: Annotated[ + list[str], + Field(description="Accepted input modalities.", title="Input Modalities"), + ] + tools: Annotated[ + bool | None, + Field(description="Whether the model supports tool calling.", title="Tools"), + ] + reasoning_effort_levels: Annotated[ + list[str] | None, + Field( + description="Reasoning effort levels the model supports.", + title="Reasoning Effort Levels", + ), + ] + parallel_tool_calls: Annotated[ + bool | None, + Field( + description="Whether the model supports parallel tool calls.", + title="Parallel Tool Calls", + ), + ] + supported_api_formats: Annotated[ + ExploreMetadataAPIFormats | None, + Field(description="API formats the model supports."), + ] + cost: Annotated[ + ExploreCost | None, + Field(description="Provider list prices in USD per 1M tokens, when available."), + ] + api_formats: Annotated[ + list[Literal["messages", "responses", "chat_completions"] | str], + Field( + description="API formats the route supports, most preferred first: `chat_completions`, `messages`, `responses` for a BASETEN_MODEL_API target and `messages`, `responses`, `chat_completions` for any other target, keeping only the formats the route supports. Never empty.", + min_length=1, + title="Api Formats", + ), + ] + + class GridRoute(BaseModel): id: Annotated[str, Field(description="Stable route identifier.", title="Id")] name: Annotated[ str, Field( - description="Name to send in the inference request's model field.", + description="Name to send in the inference request's `model` field. Unique within the team; immutable.", title="Name", ), ] - team_id: Annotated[ - str, Field(description="Identifier of the owning team.", title="Team Id") - ] - team_name: Annotated[ - str, Field(description="Name of the owning team.", title="Team Name") - ] display_name: Annotated[ str, Field( - description="Display label, defaulting to the route name.", + description="Display label, defaulting to the route's name.", title="Display Name", ), ] + aliases: Annotated[ + list[GridRouteAlias] | None, + Field( + description="The route's other names, one per purpose. Empty for routes created before aliases existed.", + title="Aliases", + ), + ] = None + team_id: Annotated[ + str, Field(description="Identifier of the owning team.", title="Team Id") + ] + team_name: Annotated[ + str, Field(description="Name of the owning team.", title="Team Name") + ] description: Annotated[ str, Field( @@ -15587,7 +17409,6 @@ class GridRoute(BaseModel): Annotated[ GridRouteTargetBasetenModelAPI | GridRouteTargetConnection - | GridRouteTargetClassifier | GridRouteTargetIntelligent, Field( description="Configured upstream target.", @@ -15599,9 +17420,9 @@ class GridRoute(BaseModel): Field(union_mode="left_to_right"), ] metadata: Annotated[ - ExploreMetadata | None, + GridRouteMetadata | None, Field( - description="Resolved model metadata; for a router, the envelope of its allowed routes' metadata. Null when nothing is linked." + description="Resolved model metadata; for an intelligent route, the envelope of its servable models' metadata. Null when nothing is linked or the metadata has no supported API formats." ), ] invoke_url: Annotated[ @@ -16367,6 +18188,16 @@ class AuditLogEntry(BaseModel): "TELEMETRY_EXPORT_CREATED", "TELEMETRY_EXPORT_UPDATED", "TELEMETRY_EXPORT_DELETED", + "SERVICE_ACCOUNT_CREATED", + "SERVICE_ACCOUNT_UPDATED", + "SERVICE_ACCOUNT_DELETED", + "IDENTITY_PROVIDER_CREATED", + "IDENTITY_PROVIDER_UPDATED", + "IDENTITY_PROVIDER_DELETED", + "TRUST_RULE_CREATED", + "TRUST_RULE_UPDATED", + "TRUST_RULE_DELETED", + "ORGANIZATION_API_KEY_SETTINGS_UPDATED", ] | str, Field( @@ -16401,6 +18232,7 @@ class AuditLogEntry(BaseModel): | AuditLogEventApiKeyCreated | AuditLogEventApiKeyDeleted | AuditLogEventApiKeyLifetimeLimitsUpdated + | AuditLogEventOrganizationApiKeySettingsUpdated | AuditLogEventGatewayEndpointCreated | AuditLogEventGatewayEndpointUpdated | AuditLogEventGatewayEndpointDeleted @@ -16434,7 +18266,16 @@ class AuditLogEntry(BaseModel): | AuditLogEventVolumeUpdated | AuditLogEventTelemetryExportCreated | AuditLogEventTelemetryExportUpdated - | AuditLogEventTelemetryExportDeleted, + | AuditLogEventTelemetryExportDeleted + | AuditLogEventServiceAccountCreated + | AuditLogEventServiceAccountUpdated + | AuditLogEventServiceAccountDeleted + | AuditLogEventIdentityProviderCreated + | AuditLogEventIdentityProviderUpdated + | AuditLogEventIdentityProviderDeleted + | AuditLogEventTrustRuleCreated + | AuditLogEventTrustRuleUpdated + | AuditLogEventTrustRuleDeleted, Field( description="Structured details of the action, discriminated by `event_type`.", discriminator="event_type", @@ -17480,6 +19321,7 @@ class CreateTrainingJobImage(BaseModel): class CreateTrainingJob(BaseModel): + bdn: TrainingBDNConfig | None = None image: Annotated[ CreateTrainingJobImage, Field(examples=[{"base_image": "hello-world", "docker_auth": None}]), diff --git a/baseten/client/modelconfig/__init__.py b/baseten/client/modelconfig/__init__.py index 3215dcf..672e898 100644 --- a/baseten/client/modelconfig/__init__.py +++ b/baseten/client/modelconfig/__init__.py @@ -17,6 +17,8 @@ BDNConfig, BDNHotload, BDNVolumeMount, + BEIConfiguration, + BEIModelConfiguration, Build, CheckpointList, CheckpointRepository, @@ -74,6 +76,8 @@ "BDNConfig", "BDNHotload", "BDNVolumeMount", + "BEIConfiguration", + "BEIModelConfiguration", "BaseImage", "Build", "CheckpointList", diff --git a/baseten/client/modelconfig/_models.py b/baseten/client/modelconfig/_models.py index 64ca410..05b942a 100644 --- a/baseten/client/modelconfig/_models.py +++ b/baseten/client/modelconfig/_models.py @@ -71,6 +71,25 @@ class BDNVolumeMount(BaseModel): ] = None +class BEIModelConfiguration(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + checkpoint: Annotated[ + str, + Field( + description="Hugging Face repository to download through weights, or an absolute path to manually mounted weights.", + min_length=1, + title="Checkpoint", + ), + ] + revision: Annotated[str | None, Field(title="Revision")] = None + served_model_name: Annotated[str | None, Field(title="Served Model Name")] = None + quantization: Annotated[ + Literal["none", "fp8", "mxfp8", "nvfp4"] | str, Field(title="Quantization") + ] = "none" + + class DockerServer(BaseModel): model_config = ConfigDict( extra="allow", @@ -85,7 +104,7 @@ class DockerServer(BaseModel): server_port: Annotated[ int, Field( - description="The port where the server runs. Port 8080 is reserved by Baseten's internal reverse proxy and cannot be used.", + description="The port where the server runs. Port 8080 is reserved when Truss installs its internal reverse proxy; no_build deployments can use 8080.", title="Server Port", ), ] @@ -234,14 +253,14 @@ class HealthChecks(BaseModel): restart_threshold_seconds: Annotated[ int | None, Field( - description="The time in seconds after which an unhealthy instance is restarted. Defaults to platform-determined value when not set.", + description="The time in seconds after which an unhealthy instance is restarted. With trt_llm, defaults to 60 and must be <= 60. Otherwise defaults to platform-determined value when not set.", title="Restart Threshold Seconds", ), ] = None stop_traffic_threshold_seconds: Annotated[ int | None, Field( - description="The time in seconds after which traffic is stopped to an unhealthy instance. Defaults to platform-determined value when not set.", + description="The time in seconds after which traffic is stopped to an unhealthy instance. With trt_llm, defaults to 30 and must be <= 30. Otherwise defaults to platform-determined value when not set.", title="Stop Traffic Threshold Seconds", ), ] = None @@ -318,7 +337,7 @@ class Resources(BaseModel): accelerator: Annotated[ str | None, Field( - description="The GPU type for your instance. To request multiple GPUs, use the ':' operator (e.g. L4:4).", + description="The accelerator type for your instance. To request multiple accelerators, use the ':' operator (e.g. L4:4).", examples=["A100", "T4:2", "H100:8"], ), ] = None @@ -590,6 +609,17 @@ class BDNConfig(BaseModel): ] = None +class BEIConfiguration(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + backend: Annotated[Literal["nvidia", "tpu"] | str, Field(title="Backend")] + version_override: Annotated[str | None, Field(title="Version Override")] = None + configuration: Annotated[ + list[BEIModelConfiguration], Field(min_length=1, title="Configuration") + ] + + class BISLLM(BaseModel): model_config = ConfigDict( extra="allow", @@ -908,7 +938,8 @@ class WeightsAuth(BaseModel): ), ] = None auth_method: Annotated[ - Literal["CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", "AWS_ASSUME_ROLE"] | str, + Literal["CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", "HF_OIDC", "AWS_ASSUME_ROLE"] + | str, Field( description="Authentication method for downloading weights from the source.", title="WeightsAuthMethod", @@ -921,6 +952,13 @@ class WeightsAuth(BaseModel): title="Auth Secret Name", ), ] = None + hf_oidc_resource: Annotated[ + str | None, + Field( + description="Hugging Face repository (namespace/name) or username for OIDC token exchange.", + title="Hf Oidc Resource", + ), + ] = None class WeightsSource(BaseModel): @@ -1136,6 +1174,12 @@ class ModelConfig(BaseModel): TRTLLMConfigurationV1 | TRTLLMConfigurationV2 | None, Field(description="TensorRT-LLM configuration for optimized LLM inference."), ] = None + bei: Annotated[ + BEIConfiguration | None, + Field( + description="BEIv3 encoder serving without an engine-build job. Hugging Face checkpoints use runtime weights mounts. Requires explicit restart and stop-traffic health thresholds of 1–60 seconds." + ), + ] = None training_checkpoints: Annotated[ CheckpointList | None, Field(description="Configuration for deploying from training checkpoints."), diff --git a/scripts/apigen/specs/config.schema.json b/scripts/apigen/specs/config.schema.json index b9fbb1d..dc08074 100644 --- a/scripts/apigen/specs/config.schema.json +++ b/scripts/apigen/specs/config.schema.json @@ -167,6 +167,96 @@ "title": "BDNVolumeMount", "type": "object" }, + "BEIConfiguration": { + "additionalProperties": true, + "properties": { + "backend": { + "enum": [ + "nvidia", + "tpu" + ], + "title": "Backend", + "type": "string" + }, + "version_override": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Version Override" + }, + "configuration": { + "items": { + "$ref": "#/$defs/BEIModelConfiguration" + }, + "minItems": 1, + "title": "Configuration", + "type": "array" + } + }, + "required": [ + "backend", + "configuration" + ], + "title": "BEIConfiguration", + "type": "object" + }, + "BEIModelConfiguration": { + "additionalProperties": true, + "properties": { + "checkpoint": { + "description": "Hugging Face repository to download through weights, or an absolute path to manually mounted weights.", + "minLength": 1, + "title": "Checkpoint", + "type": "string" + }, + "revision": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Revision" + }, + "served_model_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Served Model Name" + }, + "quantization": { + "default": "none", + "enum": [ + "none", + "fp8", + "mxfp8", + "nvfp4" + ], + "title": "Quantization", + "type": "string" + } + }, + "required": [ + "checkpoint" + ], + "title": "BEIModelConfiguration", + "type": "object" + }, "BISLLM": { "additionalProperties": true, "description": "Configuration options for BIS LLM deployments.", @@ -519,7 +609,7 @@ "title": "Start Command" }, "server_port": { - "description": "The port where the server runs. Port 8080 is reserved by Baseten's internal reverse proxy and cannot be used.", + "description": "The port where the server runs. Port 8080 is reserved when Truss installs its internal reverse proxy; no_build deployments can use 8080.", "title": "Server Port", "type": "integer" }, @@ -783,7 +873,7 @@ } ], "default": null, - "description": "The time in seconds after which an unhealthy instance is restarted. Defaults to platform-determined value when not set.", + "description": "The time in seconds after which an unhealthy instance is restarted. With trt_llm, defaults to 60 and must be <= 60. Otherwise defaults to platform-determined value when not set.", "title": "Restart Threshold Seconds" }, "stop_traffic_threshold_seconds": { @@ -796,7 +886,7 @@ } ], "default": null, - "description": "The time in seconds after which traffic is stopped to an unhealthy instance. Defaults to platform-determined value when not set.", + "description": "The time in seconds after which traffic is stopped to an unhealthy instance. With trt_llm, defaults to 30 and must be <= 30. Otherwise defaults to platform-determined value when not set.", "title": "Stop Traffic Threshold Seconds" }, "startup_threshold_seconds": { @@ -1059,7 +1149,7 @@ }, "accelerator": { "$ref": "#/$defs/AcceleratorSpec", - "description": "The GPU type for your instance. To request multiple GPUs, use the ':' operator (e.g. L4:4).", + "description": "The accelerator type for your instance. To request multiple accelerators, use the ':' operator (e.g. L4:4).", "examples": [ "A100", "T4:2", @@ -2157,6 +2247,19 @@ "default": null, "description": "Baseten secret name containing credentials for accessing the source.", "title": "Auth Secret Name" + }, + "hf_oidc_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Hugging Face repository (namespace/name) or username for OIDC token exchange.", + "title": "Hf Oidc Resource" } }, "required": [ @@ -2171,6 +2274,7 @@ "CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", + "HF_OIDC", "AWS_ASSUME_ROLE" ], "title": "WeightsAuthMethod", @@ -2482,6 +2586,18 @@ "default": null, "description": "TensorRT-LLM configuration for optimized LLM inference." }, + "bei": { + "anyOf": [ + { + "$ref": "#/$defs/BEIConfiguration" + }, + { + "type": "null" + } + ], + "default": null, + "description": "BEIv3 encoder serving without an engine-build job. Hugging Face checkpoints use runtime weights mounts. Requires explicit restart and stop-traffic health thresholds of 1\u201360 seconds." + }, "training_checkpoints": { "anyOf": [ { diff --git a/scripts/apigen/specs/management.json b/scripts/apigen/specs/management.json index e859282..977a7ce 100644 --- a/scripts/apigen/specs/management.json +++ b/scripts/apigen/specs/management.json @@ -1494,7 +1494,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/audit_logs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'direction': 'DESC', 'search': None, 'start_epoch_millis': None, 'end_epoch_millis': None}\n)\n\nprint(response.text)" } ], - "description": "Returns audit-log entries across the workspace, newest first, covering models, chains, and workspace-level actions. Use the filters to narrow by event type, actor, resource, environment, source, or time window, and the cursor to page. In workspaces with multiple teams, only organization admins can read the workspace audit log.", + "description": "Returns audit-log entries across the workspace, newest first, covering models, chains, and workspace-level actions. Use the filters to narrow by event type, actor, resource, environment, source, or time window, and the cursor to page. Requires a personal API key; team API keys can't read the workspace audit log. In workspaces with multiple teams, only organization admins can read the workspace audit log.", "parameters": [ { "name": "cursor", @@ -3831,6 +3831,88 @@ } ] }, + "/v1/models/{model_id}/deployments/{deployment_id}/replicas": { + "get": { + "summary": "Lists replicas for a deployment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + } + ], + "description": "Includes terminated replicas and lifecycle information without metrics. Replicas are ordered by creation time, oldest first, with replica ID as a tie-breaker. For subsequent pages, pass pagination.cursor as cursor with unchanged filters. Cursors expire after one hour. Replica status may change between requests.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "statuses", + "in": "query", + "required": false, + "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + "schema": { + "items": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1" + }, + "title": "Statuses", + "type": "array" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicasV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/model_id" + }, + { + "$ref": "#/components/parameters/deployment_id" + } + ] + }, "/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}": { "delete": { "summary": "Terminates a replica in a deployment", @@ -3844,7 +3926,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Terminates a deployment replica and returns the termination status.", + "description": "Terminates a deployment replica and returns the termination status. Returns 404 if no replica matches the replica ID. Returns 400 without requesting termination if multiple replicas match the replica ID.", "responses": { "200": { "description": "", @@ -3868,7 +3950,33 @@ { "$ref": "#/components/parameters/replica_id" } - ] + ], + "get": { + "summary": "Gets a replica in a deployment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Returns lifecycle information without metrics, including for terminated replicas. Returns 404 if the replica does not exist in the specified deployment. Returns 400 if multiple replicas match the replica ID.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicaV1" + } + } + } + } + } + } }, "/v1/models/{model_id}/deployments/{deployment_id}/ssh/sign": { "post": { @@ -4980,6 +5088,153 @@ } ] }, + "/v1/models/{model_id}/environments/{env_name}/replicas": { + "get": { + "summary": "Lists replicas for an environment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + } + ], + "description": "Includes retained terminated replicas from deployments active in the preceding hour. Orders replicas oldest first, with replica ID breaking ties. Pass pagination.cursor with unchanged filters for subsequent pages. Cursors pin deployment membership and expire after one hour.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "statuses", + "in": "query", + "required": false, + "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + "schema": { + "items": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1" + }, + "title": "Statuses", + "type": "array" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicasV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/model_id" + }, + { + "$ref": "#/components/parameters/env_name" + } + ] + }, + "/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}": { + "delete": { + "summary": "Terminates a replica in an environment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Requests replica termination in the environment's current deployment. Returns 404 if the environment has no current deployment or no replica matches the replica ID. Returns 400 without requesting termination if multiple replicas in the current deployment match the replica ID.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TerminateReplicaResponseV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/model_id" + }, + { + "$ref": "#/components/parameters/env_name" + }, + { + "$ref": "#/components/parameters/replica_id" + } + ], + "get": { + "summary": "Gets a replica in an environment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Searches deployments active in the environment during the preceding hour. Includes retained terminated replicas. Returns 404 if the replica is outside this scope. Returns 400 if multiple replicas match the replica ID.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicaV1" + } + } + } + } + } + } + }, "/v1/chains": { "get": { "summary": "Gets all chains", @@ -6116,11 +6371,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/training_projects/{training_project_id}/jobs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"training_job\": {\n \"image\": {\n \"base_image\": \"hello-world\",\n \"docker_auth\": null\n },\n \"compute\": {\n \"node_count\": 1,\n \"cpu_count\": 1,\n \"memory\": \"2Gi\",\n \"accelerator\": {\n \"accelerator\": \"H100\",\n \"count\": 2\n },\n \"availability_model\": \"spot\"\n },\n \"runtime\": {\n \"start_commands\": [\n \"python main.py\"\n ],\n \"environment_variables\": {\n \"API_KEY\": \"your_api_key_here\",\n \"PATH\": \"/usr/bin\"\n },\n \"enable_cache\": true,\n \"cache_config\": {\n \"enable_legacy_hf_mount\": true,\n \"enabled\": true,\n \"mount_base_path\": \"/root/.cache\",\n \"persistent_home\": false,\n \"require_cache_affinity\": true\n },\n \"checkpointing_config\": {\n \"enabled\": true,\n \"checkpoint_path\": \"/mnt/ckpts\",\n \"volume_size_gib\": 10\n },\n \"load_checkpoint_config\": null\n },\n \"name\": \"gpt-oss-job\",\n \"truss_user_env\": null,\n \"interactive_session\": null,\n \"weights\": [\n {\n \"allow_patterns\": null,\n \"auth\": null,\n \"auth_secret_name\": null,\n \"ignore_patterns\": null,\n \"mount_location\": \"/app/models/base\",\n \"source\": \"hf://meta-llama/Llama-3-8B@main\"\n }\n ],\n \"enable_baseten_workdir\": false,\n \"priority\": 0\n }\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/training_projects/{training_project_id}/jobs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"training_job\": {\n \"bdn\": {},\n \"image\": {\n \"base_image\": \"hello-world\",\n \"docker_auth\": null\n },\n \"compute\": {\n \"node_count\": 1,\n \"cpu_count\": 1,\n \"memory\": \"2Gi\",\n \"accelerator\": {\n \"accelerator\": \"H100\",\n \"count\": 2\n },\n \"availability_model\": \"spot\"\n },\n \"runtime\": {\n \"start_commands\": [\n \"python main.py\"\n ],\n \"environment_variables\": {\n \"API_KEY\": \"your_api_key_here\",\n \"PATH\": \"/usr/bin\"\n },\n \"enable_cache\": true,\n \"cache_config\": {\n \"enable_legacy_hf_mount\": true,\n \"enabled\": true,\n \"mount_base_path\": \"/root/.cache\",\n \"persistent_home\": false,\n \"require_cache_affinity\": true\n },\n \"checkpointing_config\": {\n \"enabled\": true,\n \"checkpoint_path\": \"/mnt/ckpts\",\n \"volume_size_gib\": 10\n },\n \"load_checkpoint_config\": null\n },\n \"name\": \"gpt-oss-job\",\n \"truss_user_env\": null,\n \"interactive_session\": null,\n \"weights\": [\n {\n \"allow_patterns\": null,\n \"auth\": null,\n \"auth_secret_name\": null,\n \"ignore_patterns\": null,\n \"mount_location\": \"/app/models/base\",\n \"source\": \"hf://meta-llama/Llama-3-8B@main\"\n }\n ],\n \"enable_baseten_workdir\": false,\n \"priority\": 0\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training_projects/{training_project_id}/jobs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'training_job': {'image': {'base_image': 'hello-world', 'docker_auth': None}, 'compute': {'node_count': 1, 'cpu_count': 1, 'memory': '2Gi', 'accelerator': {'accelerator': 'H100', 'count': 2}, 'availability_model': 'spot'}, 'runtime': {'start_commands': ['python main.py'], 'environment_variables': {'API_KEY': 'your_api_key_here', 'PATH': '/usr/bin'}, 'enable_cache': True, 'cache_config': {'enable_legacy_hf_mount': True, 'enabled': True, 'mount_base_path': '/root/.cache', 'persistent_home': False, 'require_cache_affinity': True}, 'checkpointing_config': {'enabled': True, 'checkpoint_path': '/mnt/ckpts', 'volume_size_gib': 10}, 'load_checkpoint_config': None}, 'name': 'gpt-oss-job', 'truss_user_env': None, 'interactive_session': None, 'weights': [{'allow_patterns': None, 'auth': None, 'auth_secret_name': None, 'ignore_patterns': None, 'mount_location': '/app/models/base', 'source': 'hf://meta-llama/Llama-3-8B@main'}], 'enable_baseten_workdir': False, 'priority': 0}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training_projects/{training_project_id}/jobs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'training_job': {'bdn': {}, 'image': {'base_image': 'hello-world', 'docker_auth': None}, 'compute': {'node_count': 1, 'cpu_count': 1, 'memory': '2Gi', 'accelerator': {'accelerator': 'H100', 'count': 2}, 'availability_model': 'spot'}, 'runtime': {'start_commands': ['python main.py'], 'environment_variables': {'API_KEY': 'your_api_key_here', 'PATH': '/usr/bin'}, 'enable_cache': True, 'cache_config': {'enable_legacy_hf_mount': True, 'enabled': True, 'mount_base_path': '/root/.cache', 'persistent_home': False, 'require_cache_affinity': True}, 'checkpointing_config': {'enabled': True, 'checkpoint_path': '/mnt/ckpts', 'volume_size_gib': 10}, 'load_checkpoint_config': None}, 'name': 'gpt-oss-job', 'truss_user_env': None, 'interactive_session': None, 'weights': [{'allow_patterns': None, 'auth': None, 'auth_secret_name': None, 'ignore_patterns': None, 'mount_location': '/app/models/base', 'source': 'hf://meta-llama/Llama-3-8B@main'}], 'enable_baseten_workdir': False, 'priority': 0}}\n)\n\nprint(response.text)" } ], "description": "Creates a training job with the specified configuration.", @@ -7305,11 +7560,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"sampler_num_replicas\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"sampler_num_replicas\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" } ], "description": "Creates a Loops run with an associated sampler in the given session.", @@ -7371,6 +7626,37 @@ ] }, "/v1/loops/runs/{run_id}": { + "delete": { + "summary": "Deletes a Loops run", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/loops/runs/{run_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs/{run_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes a Loops run by ID, deactivating it first if it is active, and deletes its checkpoints. Checkpoints still in use, such as deployed ones, are kept and listed in the response; they stay usable until that use stops. Deletion is permanent, and storage for some checkpoints is reclaimed later.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteLoopsRunResponseV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/run_id" + } + ], "get": { "summary": "Gets a Loops run", "x-codeSamples": [ @@ -7396,12 +7682,7 @@ } } } - }, - "parameters": [ - { - "$ref": "#/components/parameters/run_id" - } - ] + } }, "/v1/loops/trainers": { "post": { @@ -7409,11 +7690,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"scope\": \"default\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"scope\": \"default\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'scope': 'default'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'scope': 'default'}\n)\n\nprint(response.text)" } ], "description": "Creates a trainer-only Loops run in the given session, without a sampler. To sample from it, create a sampler with POST /v1/loops/samplers and pass this run's ID as run_id to pair the two. List and read the trainer through the /v1/loops/runs endpoints.", @@ -7784,6 +8065,39 @@ } } }, + "/v1/loops/checkpoints/{checkpoint_id}": { + "delete": { + "summary": "Deletes a Loops checkpoint", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes a Loops checkpoint by ID and returns its tombstone. The checkpoint disappears from listings and can't be loaded, sampled, or deployed. Deletion is permanent, and storage for some checkpoints is reclaimed later. A checkpoint that is deployed, read by an unfinished LoRA merge, served by an active sampler, or the start of an active run can't be deleted, and the error says which. Deleting an already-deleted checkpoint returns the same tombstone.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoopsCheckpointTombstoneV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/checkpoint_id" + } + ] + }, "/v1/loops/checkpoints/{checkpoint_id}/files": { "get": { "summary": "Gets Loops checkpoint files", @@ -7876,6 +8190,49 @@ } ] }, + "/v1/loops/checkpoints/{checkpoint_id}/ttl": { + "put": { + "summary": "Sets a Loops checkpoint's TTL", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PUT \\\n--url https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}/ttl \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"ttl_seconds\": null\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}/ttl\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PUT\",\n url,\n headers=headers,\n json={'ttl_seconds': None}\n)\n\nprint(response.text)" + } + ], + "description": "Sets when a Loops checkpoint expires, counted from now, or removes its TTL so it's kept until you delete it. An expired checkpoint is deleted within 24 hours. If it's in use when it expires, it's deleted within 24 hours after it stops being used.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetLoopsCheckpointTtlRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoopsCheckpointV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/checkpoint_id" + } + ] + }, "/v1/loops/deployments": { "get": { "summary": "Lists Loops deployments", @@ -8115,7 +8472,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/deployments/{deployment_id}/logs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_epoch_millis': None, 'end_epoch_millis': None, 'direction': None, 'limit': None, 'min_level': None}\n)\n\nprint(response.text)" } ], - "description": "Fetches logs from the trainer pods of a Loops deployment. Visible to any member of the deployment's team.", + "description": "Fetches logs from the trainer pods of a Loops deployment. Visible to anyone with training access to the deployment's team.", "parameters": [ { "name": "start_epoch_millis", @@ -8383,11 +8740,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"sampler_num_replicas\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"sampler_num_replicas\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" } ], "description": "Creates a Loops run with an associated sampler in the given session; the run's infrastructure belongs to the given team.", @@ -8421,11 +8778,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"scope\": \"default\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"scope\": \"default\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'scope': 'default'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'scope': 'default'}\n)\n\nprint(response.text)" } ], "description": "Creates a trainer-only Loops run in the given session, without a sampler. To sample from it, create a sampler with POST /v1/loops/samplers and pass this run's ID as run_id to pair the two. List and read the trainer through the /v1/loops/runs endpoints.", @@ -8584,7 +8941,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training/capacity\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Returns GPU capacity limits (baseline and peak) and current usage for the organization.", + "description": "Returns on-demand and spot GPU quotas and current usage for the teams you can view, plus organization-wide totals when you have organization-level access.", "responses": { "200": { "description": "", @@ -8599,7 +8956,7 @@ } }, "patch": { - "summary": "Sets a team's training GPU capacity", + "summary": "Sets a team's training GPU quota", "x-codeSamples": [ { "lang": "bash", @@ -8610,7 +8967,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training/capacity\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'team_id': None, 'gpu_type': None, 'max_gpus': 8}\n)\n\nprint(response.text)" } ], - "description": "Sets the max concurrent GPUs of a given type a team may use. Creates the limit if one doesn't exist for this (team, gpu_type) pair, otherwise updates it in place. Org-admin only: this is a ceiling the org imposes on the team, not something the team manages for itself.", + "description": "Sets a team's GPU quota for a given type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota, and on-demand jobs can borrow past it from the organization's shared pool when one exists. Creates the quota if one doesn't exist for this (team, gpu_type) pair, otherwise updates it in place. Org-admin only: this is a quota the org imposes on the team, not something the team manages for itself.", "requestBody": { "content": { "application/json": { @@ -9170,7 +9527,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/model_apis/{model_api_name}/metrics\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'mode': 'CURRENT', 'start_epoch_millis': None, 'end_epoch_millis': None}\n)\n\nprint(response.text)" } ], - "description": "Gets the metrics for a Model API in the given time range.", + "description": "Gets the metrics for a Model API in the given time range for the teams you can manage, with each series labeled by team_id. Organization admins receive organization-wide metrics by default. For a Model API your lab organization lists, other organizations' consumption is included regardless of team_ids.", "parameters": [ { "name": "mode", @@ -9230,6 +9587,19 @@ "title": "Metrics", "type": "array" } + }, + { + "name": "team_ids", + "in": "query", + "required": false, + "description": "Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", + "schema": { + "items": { + "type": "string" + }, + "title": "Team Ids", + "type": "array" + } } ], "responses": { @@ -9937,7 +10307,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/billing/usage_summary\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" } ], - "description": "Returns billing usage within [start_date, end_date): the start date is inclusive and the end date is exclusive. Both dates are normalized to midnight UTC. Includes dedicated model serving, training, and model APIs usage. The date range must not exceed 31 days.", + "description": "Returns billing usage within [start_date, end_date): the start date is inclusive and the end date is exclusive. Both dates are normalized to midnight UTC. Includes dedicated model serving, training, and model APIs usage. For multi-team organizations, Model APIs usage is split by team. Historical usage without a recorded team is assigned to Default Team. Usage subtotals are before credits; credits are deducted only at the product summary level. The date range must not exceed 31 days.", "parameters": [ { "name": "start_date", @@ -10232,31 +10602,68 @@ } }, "x-stability": "unstable" + }, + "patch": { + "summary": "Updates the authenticated organization", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/organizations/me \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"allow_personal_api_keys\": null,\n \"allow_service_account_api_keys\": null\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/organizations/me\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'allow_personal_api_keys': None, 'allow_service_account_api_keys': None}\n)\n\nprint(response.text)" + } + ], + "description": "Updates settings of the organization of the user making the request. Only organization admins can call it. Omitted fields are unchanged.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOrganizationRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OrganizationInfoV1" + } + } + } + } + }, + "x-stability": "unstable" } }, - "/v1/gateway/events": { + "/v1/service_accounts": { "get": { - "summary": "Lists gateway events", + "summary": "Lists service accounts", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/gateway/events \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/service_accounts \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/gateway/events\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_time': None, 'end_time': None, 'limit': None, 'cursor': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'team_id': None, 'disabled': None}\n)\n\nprint(response.text)" } ], + "description": "Lists the service accounts you administer: every account for an organization admin, and your teams' accounts for a team admin. Workload identity federation tokens act as service accounts.", "parameters": [ { - "name": "start_time", + "name": "cursor", "in": "query", "required": false, - "description": "Inclusive start (ISO 8601, UTC). Required without a cursor.", + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", "schema": { "anyOf": [ { - "format": "date-time", "type": "string" }, { @@ -10264,18 +10671,31 @@ } ], "default": null, - "title": "Start Time" + "title": "Cursor" } }, { - "name": "end_time", + "name": "limit", "in": "query", "required": false, - "description": "Exclusive end (ISO 8601, UTC). Defaults to now.", + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "name", + "in": "query", + "required": false, + "description": "Only the account with this name, ignoring case", "schema": { "anyOf": [ { - "format": "date-time", + "minLength": 1, "type": "string" }, { @@ -10283,71 +10703,43 @@ } ], "default": null, - "title": "End Time" + "title": "Name" } }, { - "name": "limit", + "name": "team_id", "in": "query", "required": false, - "description": "Max events. Default 100, max 1000.", + "description": "Only this team's accounts", "schema": { "anyOf": [ { - "maximum": 1000, - "minimum": 1, - "type": "integer" + "type": "string" }, { "type": "null" } ], "default": null, - "title": "Limit" - } - }, - { - "name": "api_keys", - "in": "query", - "required": false, - "description": "Return only events for these API key prefixes, repeated once per prefix.", - "schema": { - "items": { - "type": "string" - }, - "title": "Api Keys", - "type": "array" + "title": "Team Id" } }, { - "name": "external_entity_ids", + "name": "disabled", "in": "query", "required": false, - "description": "Return only events for these external entity IDs, repeated once per ID.", - "schema": { - "items": { - "type": "string" - }, - "title": "External Entity Ids", - "type": "array" - } - }, - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Next-page cursor. Other parameters are ignored.", + "description": "Only disabled or enabled accounts", "schema": { "anyOf": [ { - "type": "string" + "type": "boolean" }, { "type": "null" } ], "default": null, - "title": "Cursor" + "title": "Disabled" } } ], @@ -10357,28 +10749,192 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayEventsResponseV1" + "$ref": "#/components/schemas/ServiceAccountsV1" } } } } + }, + "x-stability": "unstable" + }, + "post": { + "summary": "Creates a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/service_accounts \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"ci-deployer\",\n \"description\": \"GitHub Actions deploys from acme/models\",\n \"team_id\": \"abcd1234\",\n \"preset_permissions\": {\n \"type\": \"WORKSPACE_MANAGE_ALL\"\n }\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'ci-deployer', 'description': 'GitHub Actions deploys from acme/models', 'team_id': 'abcd1234', 'preset_permissions': {'type': 'WORKSPACE_MANAGE_ALL'}}\n)\n\nprint(response.text)" + } + ], + "description": "Creates a service account that workload identity federation tokens act as. It's enabled at once. Omit `team_id` for an organization account, which only an organization admin can create. A team admin can create accounts for their own team.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateServiceAccountRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/service_accounts/{service_account_id}": { + "delete": { + "summary": "Deletes a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes a disabled service account that no trust rule uses. Disable the account and delete its trust rules first.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/service_account_id" } + ], + "get": { + "summary": "Gets a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "patch": { + "summary": "Updates a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"disabled\": true\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'disabled': True}\n)\n\nprint(response.text)" + } + ], + "description": "Updates the fields you send. Set `disabled` to true to stop the account being used, and back to false to restore it. `preset_permissions` replaces the account's access as a whole. The owning team can't change.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateServiceAccountRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" } }, - "/v1/explore/metadata": { + "/v1/access/predefined_identity_providers": { "get": { - "summary": "Lists model metadata", + "summary": "Lists predefined identity providers", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/explore/metadata \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/predefined_identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/explore/metadata\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'provider': None, 'q': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/predefined_identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Lists all live model metadata rows, e.g. for model pickers.", + "description": "Lists the identity providers Baseten supports, with the issuer format for those where each account, tenant, or cluster has its own issuer.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PredefinedIdentityProvidersV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/access/identity_providers": { + "get": { + "summary": "Lists identity providers", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'predefined_kind': None}\n)\n\nprint(response.text)" + } + ], + "description": "Lists the organization's identity providers. Organization and team admins can list them.", "parameters": [ { "name": "cursor", @@ -10412,13 +10968,14 @@ } }, { - "name": "provider", + "name": "name", "in": "query", "required": false, - "description": "Filter to a provider by slug prefix, e.g. 'anthropic'. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Only the provider with this name, ignoring case", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -10426,25 +10983,24 @@ } ], "default": null, - "title": "Provider" + "title": "Name" } }, { - "name": "q", + "name": "predefined_kind", "in": "query", "required": false, - "description": "Case-insensitive substring search over metadata slugs. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Only this predefined provider's issuers", "schema": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1" }, { "type": "null" } ], - "default": null, - "title": "Q" + "default": null } } ], @@ -10454,34 +11010,32 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ExploreMetadataResponseV1" + "$ref": "#/components/schemas/IdentityProvidersV1" } } } } }, "x-stability": "unstable" - } - }, - "/v1/grid/token": { + }, "post": { - "summary": "Creates a Grid access token", + "summary": "Adds an identity provider", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/token \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"prod-eks\",\n \"predefined\": {\n \"kind\": \"AWS_EKS\",\n \"issuer_url\": \"https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE\"\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/token\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'prod-eks', 'predefined': {'kind': 'AWS_EKS', 'issuer_url': 'https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE'}}\n)\n\nprint(response.text)" } ], - "description": "Exchanges your Baseten credentials for a short-lived token that authenticates against the Grid gateway as you, in the given team. Tokens expire after four hours and cannot be renewed; request a new one when needed. Routes keys cannot create tokens.", + "description": "Adds an identity provider to the organization. For a provider with a per-customer issuer, the issuer must match the provider's format, and its signing keys are fetched before it's saved; a failure returns 422 with the reason. Each provider with a fixed issuer can be added once. Only organization admins can call this endpoint.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridTokenRequestV1" + "$ref": "#/components/schemas/CreateIdentityProviderRequestV1" } } }, @@ -10493,7 +11047,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTokenV1" + "$ref": "#/components/schemas/IdentityProviderV1" } } } @@ -10502,98 +11056,88 @@ "x-stability": "unstable" } }, - "/v1/grid/routes": { - "get": { - "summary": "Lists routes", + "/v1/access/identity_providers/verify": { + "post": { + "summary": "Checks an identity provider before adding it", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/identity_providers/verify \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"predefined\": {\n \"kind\": \"AWS_EKS\",\n \"issuer_url\": \"https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE\"\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'name': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/verify\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'predefined': {'kind': 'AWS_EKS', 'issuer_url': 'https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE'}}\n)\n\nprint(response.text)" } ], - "description": "Lists routes you can invoke, newest first, optionally filtered by exact name. Without `team_id`, routes from every team where you can invoke routes. With `for_harnesses`, exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", - "parameters": [ - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" + "description": "Runs the checks that adding the identity provider runs, without adding it: the issuer's format, that the organization doesn't have it yet, and, for a provider with a per-customer issuer, that its signing keys can be fetched. A failed check returns 200 with `valid` false and the reason. Only organization admins can call this endpoint.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifyIdentityProviderRequestV1" + } } }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerificationV1" + } + } } + } + }, + "x-stability": "unstable" + } + }, + "/v1/access/identity_providers/{identity_provider_id}": { + "delete": { + "summary": "Deletes an identity provider", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { - "name": "team_id", - "in": "query", - "required": false, - "description": "Limit routes to this team. Without it, routes from every team where you can invoke routes.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Removes the identity provider from the organization. Returns 409 while a trust rule uses it. Only organization admins can call this endpoint.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedIdentityProviderV1" } - ], - "default": null, - "title": "Team Id" + } } - }, + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/identity_provider_id" + } + ], + "get": { + "summary": "Gets an identity provider", + "x-codeSamples": [ { - "name": "for_harnesses", - "in": "query", - "required": false, - "description": "Set by harness setup and sync. Returns routes from exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", - "schema": { - "default": false, - "title": "For Harnesses", - "type": "boolean" - } + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { - "name": "name", - "in": "query", - "required": false, - "description": "Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Name" - } + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -10602,7 +11146,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRoutesResponseV1" + "$ref": "#/components/schemas/IdentityProviderV1" } } } @@ -10610,24 +11154,24 @@ }, "x-stability": "unstable" }, - "post": { - "summary": "Creates a route", + "patch": { + "summary": "Updates an identity provider", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"display_name\": \"Assistant\",\n \"target\": {\n \"model\": \"zai-org/GLM-5.3\",\n \"type\": \"BASETEN_MODEL_API\"\n },\n \"description\": \"Assistant for code review and debugging.\"\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"prod-eks\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'display_name': 'Assistant', 'target': {'model': 'zai-org/GLM-5.3', 'type': 'BASETEN_MODEL_API'}, 'description': 'Assistant for code review and debugging.'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'name': 'prod-eks'}\n)\n\nprint(response.text)" } ], - "description": "Creates and derives a name for the provided route configuration. CONNECTION targets reference a connection owned by the route's team; create the connection first.", + "description": "Updates the fields you send. The provider and issuer can't change. Only organization admins can call this endpoint.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridRouteRequestV1" + "$ref": "#/components/schemas/UpdateIdentityProviderRequestV1" } } }, @@ -10639,7 +11183,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/IdentityProviderV1" } } } @@ -10648,20 +11192,20 @@ "x-stability": "unstable" } }, - "/v1/grid/routes/usage": { + "/v1/access/trust_rules": { "get": { - "summary": "Gets daily Grid usage and estimated costs", + "summary": "Lists trust rules", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/usage \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/trust_rules \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/usage\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'identity_provider_id': None, 'service_account_id': None, 'team_id': None}\n)\n\nprint(response.text)" } ], - "description": "Buckets are UTC days, and days with no usage are included. Organization admins see all Grid usage in the organization. Team admins see usage in teams they manage. Other members, including viewers, see only usage from Routes keys they created, including keys that have since expired, been revoked, or been deleted. Usage can be filtered and grouped by the team it was metered in. Usage is metered every 15 minutes, so the current hour can lag. Model API costs use your prices at the time of each request and include tool calls. xAI costs are the charges xAI reports. OpenAI and Anthropic costs are estimated from Baseten's reference prices and may differ from your provider's bill. Vertex and OpenAI-compatible usage is not included. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges. Usage is retained for 92 days.", + "description": "Lists the trust rules you administer: every rule for an organization admin, and rules for your teams' service accounts for a team admin.", "parameters": [ { "name": "cursor", @@ -10685,23 +11229,24 @@ "name": "limit", "in": "query", "required": false, - "description": "Number of daily buckets to return. Defaults to 7; maximum 31.", + "description": "Maximum number of items to return.", "schema": { - "default": 7, - "maximum": 31, + "default": 100, + "maximum": 1000, "minimum": 1, "title": "Limit", "type": "integer" } }, { - "name": "team_id", + "name": "name", "in": "query", "required": false, - "description": "Limit usage to a team you can access. Organization admins can view all usage in the team, team admins can view usage in teams they manage, and other members can view only their own usage. Without a team, organization admins see all organization usage, team admins see their managed teams, and other members see their own usage.", + "description": "Only the rule with this name, ignoring case", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -10709,18 +11254,17 @@ } ], "default": null, - "title": "Team Id" + "title": "Name" } }, { - "name": "start_date", + "name": "identity_provider_id", "in": "query", "required": false, - "description": "Inclusive UTC calendar day at the start of the query range. Defaults to the previous UTC date, and is ignored when you pass a cursor.", + "description": "Only this provider's rules", "schema": { "anyOf": [ { - "format": "date", "type": "string" }, { @@ -10728,18 +11272,17 @@ } ], "default": null, - "title": "Start Date" + "title": "Identity Provider Id" } }, { - "name": "end_date", + "name": "service_account_id", "in": "query", "required": false, - "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included.", + "description": "Only rules for this service account", "schema": { "anyOf": [ { - "format": "date", "type": "string" }, { @@ -10747,82 +11290,111 @@ } ], "default": null, - "title": "End Date" + "title": "Service Account Id" } }, { - "name": "group_by", + "name": "team_id", "in": "query", "required": false, - "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", + "description": "Only rules for this team's service accounts", "schema": { - "items": { - "$ref": "#/components/schemas/GridRouteUsageDimensionV1" - }, - "title": "Group By", - "type": "array" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Team Id" } - }, - { - "name": "user_ids", - "in": "query", - "required": false, - "description": "Return only usage from Routes keys created by these user IDs, repeated once per ID.", - "schema": { - "items": { - "type": "string" - }, - "title": "User Ids", - "type": "array" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AccessTrustRulesV1" + } + } } + } + }, + "x-stability": "unstable" + }, + "post": { + "summary": "Creates a trust rule", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/trust_rules \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"models-main-deploy\",\n \"identity_provider_id\": \"abcd1234\",\n \"service_account_id\": \"wxyz5678\",\n \"condition\": \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\",\n \"audience\": \"https://api.baseten.co\"\n}'" }, { - "name": "models", - "in": "query", - "required": false, - "description": "Return only usage for these exact model names, repeated once per model.", - "schema": { - "items": { - "type": "string" - }, - "title": "Models", - "type": "array" + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'models-main-deploy', 'identity_provider_id': 'abcd1234', 'service_account_id': 'wxyz5678', 'condition': \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\", 'audience': 'https://api.baseten.co'}\n)\n\nprint(response.text)" + } + ], + "description": "Creates a rule that lets tokens from an identity provider act as a service account. Organization admins can create rules for any service account, team admins for their own team's. An organization API key manager key can't target organization accounts.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateAccessTrustRuleRequestV1" + } } }, - { - "name": "providers", - "in": "query", - "required": false, - "description": "Return only usage for these providers, repeated once per provider.", - "schema": { - "items": { - "$ref": "#/components/schemas/GridProviderV1" - }, - "title": "Providers", - "type": "array" + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AccessTrustRuleV1" + } + } } + } + }, + "x-stability": "unstable" + } + }, + "/v1/access/trust_rules/verify": { + "post": { + "summary": "Checks a trust rule's condition and audience", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/trust_rules/verify \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"identity_provider_id\": \"abcd1234\",\n \"condition\": \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\",\n \"audience\": \"https://api.baseten.co\"\n}'" }, { - "name": "harnesses", - "in": "query", - "required": false, - "description": "Return only usage for these harnesses, repeated once per harness. Omit to include all usage, including usage with no recorded harness.", - "schema": { - "items": { - "$ref": "#/components/schemas/GridRouteUsageHarnessV1" - }, - "title": "Harnesses", - "type": "array" - } + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/verify\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'identity_provider_id': 'abcd1234', 'condition': \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\", 'audience': 'https://api.baseten.co'}\n)\n\nprint(response.text)" } ], + "description": "Runs the checks that creating or updating a trust rule runs on its condition and audience, without saving anything: that the condition compiles and pins the claims the identity provider requires. A failed check returns 200 with `valid` false and the reason.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifyAccessTrustRuleRequestV1" + } + } + }, + "required": true + }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteUsageResponseV1" + "$ref": "#/components/schemas/VerificationV1" } } } @@ -10831,26 +11403,27 @@ "x-stability": "unstable" } }, - "/v1/grid/routes/{route_id}": { + "/v1/access/trust_rules/{trust_rule_id}": { "delete": { - "summary": "Deletes a route", + "summary": "Deletes a trust rule", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], + "description": "New exchanges through the rule fail at once; tokens already issued keep working until they expire.", "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteTombstoneV1" + "$ref": "#/components/schemas/DeletedAccessTrustRuleV1" } } } @@ -10860,19 +11433,19 @@ }, "parameters": [ { - "$ref": "#/components/parameters/route_id" + "$ref": "#/components/parameters/trust_rule_id" } ], "get": { - "summary": "Gets a route", + "summary": "Gets a trust rule", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -10881,7 +11454,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/AccessTrustRuleV1" } } } @@ -10890,23 +11463,23 @@ "x-stability": "unstable" }, "patch": { - "summary": "Updates a route", + "summary": "Updates a trust rule", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"description\": \"Assistant for code review and debugging.\",\n \"display_name\": \"Assistant\",\n \"target\": null\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"models-release-deploy\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'description': 'Assistant for code review and debugging.', 'display_name': 'Assistant', 'target': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'name': 'models-release-deploy'}\n)\n\nprint(response.text)" } ], - "description": "The route name, target type, and owning team are immutable.", + "description": "Updates the fields you send. Changes apply to new exchanges only. The identity provider can't change.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateGridRouteRequestV1" + "$ref": "#/components/schemas/UpdateAccessTrustRuleRequestV1" } } }, @@ -10918,7 +11491,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/AccessTrustRuleV1" } } } @@ -10927,30 +11500,64 @@ "x-stability": "unstable" } }, - "/v1/grid/team_settings": { + "/v1/auth/token": { + "post": { + "summary": "Exchanges an identity provider's JWT for an access token", + "security": [], + "description": "Exchanges a JWT from your identity provider for a short-lived Baseten access token, as described in RFC 8693. Send no API key: the JWT is the credential. Name the trust rule to check the JWT against as the `audience`, and send the access token as `Authorization: Bearer` on later requests. Errors follow RFC 6749 section 5.2: a 400 response with an `error` of `invalid_request`, `unsupported_grant_type`, or `invalid_grant`. A well-formed request that is refused always returns `invalid_grant`, whatever the reason.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenExchangeRequestV1" + } + }, + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/TokenExchangeRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenExchangeResponseV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/gateway/events": { "get": { - "summary": "Gets a team's Grid settings by team ID or your only team", + "summary": "Lists gateway events", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/gateway/events \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/gateway/events\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_time': None, 'end_time': None, 'limit': None, 'cursor': None}\n)\n\nprint(response.text)" } ], - "description": "Returns the settings that apply to the team, including the default models for each coding harness and the team's spend limits. Any member who can invoke the team's routes can read them. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", "parameters": [ { - "name": "team_id", + "name": "start_time", "in": "query", "required": false, - "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", + "description": "Inclusive start (ISO 8601, UTC). Required without a cursor.", "schema": { "anyOf": [ { - "minLength": 1, + "format": "date-time", "type": "string" }, { @@ -10958,79 +11565,121 @@ } ], "default": null, - "examples": [ - "abc1234" + "title": "Start Time" + } + }, + { + "name": "end_time", + "in": "query", + "required": false, + "description": "Exclusive end (ISO 8601, UTC). Defaults to now.", + "schema": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } ], - "title": "Team Id" + "default": null, + "title": "End Time" } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridTeamSettingsV1" + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Max events. Default 100, max 1000.", + "schema": { + "anyOf": [ + { + "maximum": 1000, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" } - } + ], + "default": null, + "title": "Limit" } - } - }, - "x-stability": "unstable" - }, - "patch": { - "summary": "Updates a team's Grid settings by team ID or your only team", - "x-codeSamples": [ + }, { - "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"harness_defaults\": null,\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" + "name": "api_keys", + "in": "query", + "required": false, + "description": "Return only events for these API key prefixes, repeated once per prefix.", + "schema": { + "items": { + "type": "string" + }, + "title": "Api Keys", + "type": "array" + } }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'harness_defaults': None, 'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" - } - ], - "description": "Changes only the fields in the request, all or nothing. Requires team admin, and organization admin to change the team-wide spend limit. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateGridTeamSettingsRequestV1" - } + "name": "external_entity_ids", + "in": "query", + "required": false, + "description": "Return only events for these external entity IDs, repeated once per ID.", + "schema": { + "items": { + "type": "string" + }, + "title": "External Entity Ids", + "type": "array" } }, - "required": true - }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Next-page cursor. Other parameters are ignored.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + } + ], "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamSettingsV1" + "$ref": "#/components/schemas/GatewayEventsResponseV1" } } } } - }, - "x-stability": "unstable" + } } }, - "/v1/grid/team_settings/users": { + "/v1/explore/metadata": { "get": { - "summary": "Lists members' Grid settings", + "summary": "Lists model metadata", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/explore/metadata \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/explore/metadata\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'provider': None, 'q': None}\n)\n\nprint(response.text)" } ], - "description": "Returns each member's settings in each team, including organization admins and Grid service accounts, one row per team membership. With `team_id`, one team, which requires team admin for it or organization admin; without it, every team you administer, which is none for members.", + "description": "Lists all live model metadata rows, e.g. for model pickers.", "parameters": [ { "name": "cursor", @@ -11064,14 +11713,13 @@ } }, { - "name": "team_id", + "name": "provider", "in": "query", "required": false, - "description": "Limit the list to this team. Without it, the members of every team you administer, one row per team.", + "description": "Filter to a provider by slug prefix, e.g. 'anthropic'. Preserved by the cursor; if repeated, must match the original filter.", "schema": { "anyOf": [ { - "minLength": 1, "type": "string" }, { @@ -11079,10 +11727,25 @@ } ], "default": null, - "examples": [ - "abc1234" + "title": "Provider" + } + }, + { + "name": "q", + "in": "query", + "required": false, + "description": "Case-insensitive substring search over metadata slugs. Preserved by the cursor; if repeated, must match the original filter.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], - "title": "Team Id" + "default": null, + "title": "Q" } } ], @@ -11092,7 +11755,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsListV1" + "$ref": "#/components/schemas/ExploreMetadataResponseV1" } } } @@ -11101,30 +11764,68 @@ "x-stability": "unstable" } }, - "/v1/grid/team_settings/users/{user_id}": { - "get": { - "summary": "Gets a user's Grid settings by team ID or your only team", + "/v1/grid/token": { + "post": { + "summary": "Creates a Grid access token", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/token \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/token\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Returns the user's spend limit for Baseten Grid in the team, their spend in the team this month, and whether that spend reached the limit. Members can read their own settings; team admins can read members' settings in teams they administer, and organization admins can read anyone's. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "description": "Exchanges your Baseten credentials for a short-lived token that authenticates against the Grid gateway as you, in the given team. Tokens expire after four hours and cannot be renewed; request a new one when needed. Routes keys cannot create tokens.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateGridTokenRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridTokenV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/routes": { + "get": { + "summary": "Lists routes", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'name': None}\n)\n\nprint(response.text)" + } + ], + "description": "Lists routes you can invoke, newest first, optionally filtered by exact name. Without `team_id`, routes from every team where you can invoke routes. With `for_harnesses`, exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", "parameters": [ { - "name": "team_id", + "name": "cursor", "in": "query", "required": false, - "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", "schema": { "anyOf": [ { - "minLength": 1, "type": "string" }, { @@ -11132,11 +11833,68 @@ } ], "default": null, - "examples": [ - "abc1234" + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "team_id", + "in": "query", + "required": false, + "description": "Limit routes to this team. Without it, routes from every team where you can invoke routes.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], + "default": null, "title": "Team Id" } + }, + { + "name": "for_harnesses", + "in": "query", + "required": false, + "description": "Set by harness setup and sync. Returns routes from exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", + "schema": { + "default": false, + "title": "For Harnesses", + "type": "boolean" + } + }, + { + "name": "name", + "in": "query", + "required": false, + "description": "Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Name" + } } ], "responses": { @@ -11145,7 +11903,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsV1" + "$ref": "#/components/schemas/GridRoutesResponseV1" } } } @@ -11153,29 +11911,24 @@ }, "x-stability": "unstable" }, - "parameters": [ - { - "$ref": "#/components/parameters/user_id" - } - ], - "patch": { - "summary": "Updates a user's Grid settings by team ID or your only team", + "post": { + "summary": "Creates a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"display_name\": \"Assistant\",\n \"target\": {\n \"model\": \"zai-org/GLM-5.3\",\n \"type\": \"BASETEN_MODEL_API\"\n },\n \"description\": \"Assistant for code review and debugging.\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'display_name': 'Assistant', 'target': {'model': 'zai-org/GLM-5.3', 'type': 'BASETEN_MODEL_API'}, 'description': 'Assistant for code review and debugging.'}\n)\n\nprint(response.text)" } ], - "description": "Changes only the fields in the request. Once the user's metered spend in the team in a month reaches the spend limit, requests with Routes keys they created in the team are rejected until the limit is raised or the next month starts. Spend is metered every 15 minutes and can lag, so a user can go over the limit. Requires team admin for the specified team or organization admin. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "description": "Creates and derives a name for the provided route configuration. CONNECTION targets reference a connection owned by the route's team; create the connection first. INTELLIGENT targets reference a route classifier from GET /v1/grid/route_classifiers.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateGridUserSettingsRequestV1" + "$ref": "#/components/schemas/CreateGridRouteRequestV1" } } }, @@ -11187,7 +11940,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11196,20 +11949,20 @@ "x-stability": "unstable" } }, - "/v1/grid/connections": { + "/v1/grid/routes/usage": { "get": { - "summary": "Lists connections", + "summary": "Gets daily Grid usage and estimated costs", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/usage \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/usage\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" } ], - "description": "Lists connections, newest first: the team's with `team_id`, else those of every team where you can invoke routes.", + "description": "Buckets are UTC days, and days with no usage are included. Organization admins see all Grid usage in the organization. Team admins see usage in teams they manage. Other members, including viewers, see only usage from Routes keys they created, including keys that have since expired, been revoked, or been deleted. Usage can be filtered and grouped by the team it was metered in. Usage is metered every 15 minutes, so the current hour can lag. Model API costs use your prices at the time of each request and include tool calls. xAI costs are the charges xAI reports. OpenAI and Anthropic costs are estimated from Baseten's reference prices and may differ from your provider's bill. Vertex and OpenAI-compatible usage is not included. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges. Usage is retained for 92 days.", "parameters": [ { "name": "cursor", @@ -11233,10 +11986,10 @@ "name": "limit", "in": "query", "required": false, - "description": "Maximum number of items to return.", + "description": "Number of daily buckets to return. Defaults to 7; maximum 31.", "schema": { - "default": 100, - "maximum": 1000, + "default": 7, + "maximum": 31, "minimum": 1, "title": "Limit", "type": "integer" @@ -11246,7 +11999,7 @@ "name": "team_id", "in": "query", "required": false, - "description": "Limit connections to this team. Without it, connections from every team where you can invoke routes.", + "description": "Limit usage to a team you can access. Organization admins can view all usage in the team, team admins can view usage in teams they manage, and other members can view only their own usage. Without a team, organization admins see all organization usage, team admins see their managed teams, and other members see their own usage.", "schema": { "anyOf": [ { @@ -11259,52 +12012,131 @@ "default": null, "title": "Team Id" } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridConnectionsResponseV1" + }, + { + "name": "start_date", + "in": "query", + "required": false, + "description": "Inclusive UTC calendar day at the start of the query range. Defaults to the previous UTC date, and is ignored when you pass a cursor.", + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" } - } + ], + "default": null, + "title": "Start Date" } - } - }, - "x-stability": "unstable" - }, - "post": { - "summary": "Creates a connection", - "x-codeSamples": [ + }, { - "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" + "name": "end_date", + "in": "query", + "required": false, + "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included.", + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "End Date" + } }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" - } - ], - "description": "Creates a connection from the team to an upstream provider.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateGridConnectionRequestV1" - } + "name": "group_by", + "in": "query", + "required": false, + "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridRouteUsageDimensionV1" + }, + "title": "Group By", + "type": "array" } }, - "required": true - }, + { + "name": "user_ids", + "in": "query", + "required": false, + "description": "Return only usage from Routes keys created by these user IDs, repeated once per ID.", + "schema": { + "items": { + "type": "string" + }, + "title": "User Ids", + "type": "array" + } + }, + { + "name": "models", + "in": "query", + "required": false, + "description": "Return only usage for these exact model names, repeated once per model.", + "schema": { + "items": { + "type": "string" + }, + "title": "Models", + "type": "array" + } + }, + { + "name": "providers", + "in": "query", + "required": false, + "description": "Return only usage for these providers, repeated once per provider.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridProviderV1" + }, + "title": "Providers", + "type": "array" + } + }, + { + "name": "harnesses", + "in": "query", + "required": false, + "description": "Return only usage for these harnesses, repeated once per harness. Omit to include all usage, including usage with no recorded harness.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridRouteUsageHarnessV1" + }, + "title": "Harnesses", + "type": "array" + } + }, + { + "name": "api_key_prefixes", + "in": "query", + "required": false, + "description": "Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", + "schema": { + "items": { + "type": "string" + }, + "title": "Api Key Prefixes", + "type": "array" + } + } + ], "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionV1" + "$ref": "#/components/schemas/GridRouteUsageResponseV1" } } } @@ -11313,27 +12145,26 @@ "x-stability": "unstable" } }, - "/v1/grid/connections/{connection_id}": { + "/v1/grid/routes/{route_id}": { "delete": { - "summary": "Deletes a connection", + "summary": "Deletes a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Deletes the connection. The team secret it points at is left in place.", "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionTombstoneV1" + "$ref": "#/components/schemas/GridRouteTombstoneV1" } } } @@ -11343,19 +12174,19 @@ }, "parameters": [ { - "$ref": "#/components/parameters/connection_id" + "$ref": "#/components/parameters/route_id" } ], "get": { - "summary": "Gets a connection", + "summary": "Gets a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -11364,7 +12195,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11373,23 +12204,23 @@ "x-stability": "unstable" }, "patch": { - "summary": "Updates a connection", + "summary": "Updates a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"description\": \"Assistant for code review and debugging.\",\n \"display_name\": \"Assistant\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'description': 'Assistant for code review and debugging.', 'display_name': 'Assistant'}\n)\n\nprint(response.text)" } ], - "description": "Updates the connection's fields. The provider and owning team are immutable; point the connection at a new team secret to change its API key, or rotate the key itself by updating the secret.", + "description": "The route name, target, and owning team are immutable.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateGridConnectionRequestV1" + "$ref": "#/components/schemas/UpdateGridRouteRequestV1" } } }, @@ -11401,7 +12232,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11410,29 +12241,30 @@ "x-stability": "unstable" } }, - "/v1/grid/classifiers": { + "/v1/grid/team_settings": { "get": { - "summary": "Lists classifiers available for intelligent routes", + "summary": "Gets a team's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Returns Baseten-managed classifiers available to your organization, ordered by identifier. Classifiers cannot be created or modified through this API.", + "description": "Returns the settings that apply to the team, including the default models for each coding harness and the team's spend limits. Any member who can invoke the team's routes can read them. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", "parameters": [ { - "name": "cursor", + "name": "team_id", "in": "query", "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -11440,20 +12272,10 @@ } ], "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" + "examples": [ + "abc1234" + ], + "title": "Team Id" } } ], @@ -11463,62 +12285,66 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridClassifiersResponseV1" + "$ref": "#/components/schemas/GridTeamSettingsV1" } } } } }, "x-stability": "unstable" - } - }, - "/v1/grid/classifiers/{classifier_id}": { - "get": { - "summary": "Gets a classifier available for intelligent routes", + }, + "patch": { + "summary": "Updates a team's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/classifiers/{classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"harness_defaults\": null,\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/classifiers/{classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'harness_defaults': None, 'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], + "description": "Changes only the fields in the request, all or nothing. Requires team admin, and organization admin to change the team-wide spend limit. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateGridTeamSettingsRequestV1" + } + } + }, + "required": true + }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridClassifierV1" + "$ref": "#/components/schemas/GridTeamSettingsV1" } } } } }, "x-stability": "unstable" - }, - "parameters": [ - { - "$ref": "#/components/parameters/classifier_id" - } - ] + } }, - "/v1/grid/route_classifiers": { + "/v1/grid/team_settings/users": { "get": { - "summary": "Lists route classifiers available for intelligent routes", + "summary": "Lists members' Grid settings", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Returns Baseten-managed route classifiers available to your organization, ordered by identifier. Route classifiers cannot be created or modified through this API.", + "description": "Returns each member's settings in each team, including organization admins and Grid service accounts, one row per team membership. With `team_id`, one team, which requires team admin for it or organization admin; without it, every team you administer, which is none for members.", "parameters": [ { "name": "cursor", @@ -11550,6 +12376,28 @@ "title": "Limit", "type": "integer" } + }, + { + "name": "team_id", + "in": "query", + "required": false, + "description": "Limit the list to this team. Without it, the members of every team you administer, one row per team.", + "schema": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "examples": [ + "abc1234" + ], + "title": "Team Id" + } } ], "responses": { @@ -11558,7 +12406,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteClassifiersResponseV1" + "$ref": "#/components/schemas/GridTeamUserSettingsListV1" } } } @@ -11567,17 +12415,42 @@ "x-stability": "unstable" } }, - "/v1/grid/route_classifiers/{route_classifier_id}": { + "/v1/grid/team_settings/users/{user_id}": { "get": { - "summary": "Gets a route classifier available for intelligent routes", + "summary": "Gets a user's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + } + ], + "description": "Returns the user's spend limit for Baseten Grid in the team, their spend in the team this month, and whether that spend reached the limit. Members can read their own settings; team admins can read members' settings in teams they administer, and organization admins can read anyone's. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "parameters": [ + { + "name": "team_id", + "in": "query", + "required": false, + "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", + "schema": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "examples": [ + "abc1234" + ], + "title": "Team Id" + } } ], "responses": { @@ -11586,7 +12459,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteClassifierV1" + "$ref": "#/components/schemas/GridTeamUserSettingsV1" } } } @@ -11596,24 +12469,61 @@ }, "parameters": [ { - "$ref": "#/components/parameters/route_classifier_id" + "$ref": "#/components/parameters/user_id" } - ] + ], + "patch": { + "summary": "Updates a user's Grid settings by team ID or your only team", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + } + ], + "description": "Changes only the fields in the request. Once the user's metered spend in the team in a month reaches the spend limit, requests with Routes keys they created in the team are rejected until the limit is raised or the next month starts. Spend is metered every 15 minutes and can lag, so a user can go over the limit. Requires team admin for the specified team or organization admin. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateGridUserSettingsRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridTeamUserSettingsV1" + } + } + } + } + }, + "x-stability": "unstable" + } }, - "/v1/grid/machine_users": { + "/v1/grid/connections": { "get": { - "summary": "Lists machine users", + "summary": "Lists connections", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" } ], - "description": "Lists machine users, newest first: the team's with `team_id`, which requires team admin for it, else those of every team you administer.", + "description": "Lists connections, newest first: the team's with `team_id`, else those of every team where you can invoke routes.", "parameters": [ { "name": "cursor", @@ -11650,7 +12560,7 @@ "name": "team_id", "in": "query", "required": false, - "description": "Limit machine users to this team. Without it, every team you administer.", + "description": "Limit connections to this team. Without it, connections from every team where you can invoke routes.", "schema": { "anyOf": [ { @@ -11671,7 +12581,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridMachineUsersResponseV1" + "$ref": "#/components/schemas/GridConnectionsResponseV1" } } } @@ -11680,23 +12590,23 @@ "x-stability": "unstable" }, "post": { - "summary": "Creates a machine user", + "summary": "Creates a connection", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"name\": \"night-shift\",\n \"api_key\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'name': 'night-shift', 'api_key': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" } ], - "description": "Creates a team-owned identity for an application, with its own Grid budget. Set `api_key` to also create its first API key, which the response returns only once. Set the machine user's spend limit with the user settings endpoint, using its `id` as the user ID. Requires team admin.", + "description": "Creates a connection from the team to an upstream provider.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridMachineUserRequestV1" + "$ref": "#/components/schemas/CreateGridConnectionRequestV1" } } }, @@ -11708,7 +12618,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreatedGridMachineUserV1" + "$ref": "#/components/schemas/GridConnectionV1" } } } @@ -11717,7 +12627,316 @@ "x-stability": "unstable" } }, - "/v1/grid/machine_users/{machine_user_id}": { + "/v1/grid/connections/{connection_id}": { + "delete": { + "summary": "Deletes a connection", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes the connection. The team secret it points at is left in place.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridConnectionTombstoneV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/connection_id" + } + ], + "get": { + "summary": "Gets a connection", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridConnectionV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "patch": { + "summary": "Updates a connection", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" + } + ], + "description": "Updates the connection's fields. The provider and owning team are immutable; point the connection at a new team secret to change its API key, or rotate the key itself by updating the secret.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateGridConnectionRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridConnectionV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/route_classifiers": { + "get": { + "summary": "Lists route classifiers available for intelligent routes", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + } + ], + "description": "Returns Baseten-managed route classifiers available to your organization, ordered by identifier. Route classifiers cannot be created or modified through this API.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridRouteClassifiersResponseV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/route_classifiers/{route_classifier_id}": { + "get": { + "summary": "Gets a route classifier available for intelligent routes", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridRouteClassifierV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/route_classifier_id" + } + ] + }, + "/v1/grid/machine_users": { + "get": { + "summary": "Lists machine users", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" + } + ], + "description": "Lists machine users, newest first: the team's with `team_id`, which requires team admin for it, else those of every team you administer.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "team_id", + "in": "query", + "required": false, + "description": "Limit machine users to this team. Without it, every team you administer.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Team Id" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridMachineUsersResponseV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "post": { + "summary": "Creates a machine user", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"name\": \"night-shift\",\n \"api_key\": null\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'name': 'night-shift', 'api_key': None}\n)\n\nprint(response.text)" + } + ], + "description": "Creates a team-owned identity for an application, with its own Grid budget. Set `api_key` to also create its first API key, which the response returns only once. Set the machine user's spend limit with the user settings endpoint, using its `id` as the user ID. Requires team admin.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateGridMachineUserRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedGridMachineUserV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/machine_users/{machine_user_id}": { "delete": { "summary": "Deletes a machine user", "x-codeSamples": [ @@ -18102,6 +19321,25 @@ "title": "PrepareModelUploadResponseV1", "type": "object" }, + "AuditFieldChangeV1": { + "description": "A field's value before and after an update.", + "properties": { + "old": { + "description": "The value before the update.", + "title": "Old" + }, + "new": { + "description": "The value after the update.", + "title": "New" + } + }, + "required": [ + "old", + "new" + ], + "title": "AuditFieldChangeV1", + "type": "object" + }, "AuditLogActorTypeV1": { "description": "Kind of actor that performed an audited action.", "enum": [ @@ -18109,7 +19347,8 @@ "API_KEY", "BASETEN_USER", "BASETEN_SYSTEM", - "TOMBSTONE_USER" + "TOMBSTONE_USER", + "SERVICE_ACCOUNT" ], "title": "AuditLogActorTypeV1", "type": "string" @@ -18159,6 +19398,45 @@ "default": null, "description": "Display name of the acting API key, when the actor is an API key.", "title": "Api Key Name" + }, + "service_account_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the acting service account, when the actor is a service account.", + "title": "Service Account Id" + }, + "service_account_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Current name of the acting service account, when the actor is a service account.", + "title": "Service Account Name" + }, + "trust_rule_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the trust rule the acting workload identity federation token was exchanged through, when the actor is a service account.", + "title": "Trust Rule Id" } }, "required": [ @@ -18170,7 +19448,8 @@ "AuditLogApiKeyRevocationReasonV1": { "description": "Reason an API key was revoked.", "enum": [ - "INACTIVITY" + "INACTIVITY", + "CREDENTIAL_EXPOSURE" ], "title": "AuditLogApiKeyRevocationReasonV1", "type": "string" @@ -18182,6 +19461,7 @@ "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", + "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -18238,6 +19518,9 @@ "GRID_MACHINE_USER_CREATED": "#/components/schemas/AuditLogEventGridMachineUserCreatedV1", "GRID_MACHINE_USER_DELETED": "#/components/schemas/AuditLogEventGridMachineUserDeletedV1", "GRID_MACHINE_USER_UPDATED": "#/components/schemas/AuditLogEventGridMachineUserUpdatedV1", + "IDENTITY_PROVIDER_CREATED": "#/components/schemas/AuditLogEventIdentityProviderCreatedV1", + "IDENTITY_PROVIDER_DELETED": "#/components/schemas/AuditLogEventIdentityProviderDeletedV1", + "IDENTITY_PROVIDER_UPDATED": "#/components/schemas/AuditLogEventIdentityProviderUpdatedV1", "MODEL_DELETED": "#/components/schemas/AuditLogEventModelDeletedV1", "MODEL_DEPLOYED": "#/components/schemas/AuditLogEventModelDeployedV1", "MODEL_DEPLOYMENT_ACTIVATED": "#/components/schemas/AuditLogEventModelDeploymentActivatedV1", @@ -18250,6 +19533,7 @@ "MODEL_DEPLOYMENT_RETRIED": "#/components/schemas/AuditLogEventModelDeploymentRetriedV1", "MODEL_PROMOTION_CONTROL_ACTION": "#/components/schemas/AuditLogEventModelPromotionControlActionV1", "MODEL_RENAMED": "#/components/schemas/AuditLogEventModelRenamedV1", + "ORGANIZATION_API_KEY_SETTINGS_UPDATED": "#/components/schemas/AuditLogEventOrganizationApiKeySettingsUpdatedV1", "PROVIDER_CONNECTION_CREATED": "#/components/schemas/AuditLogEventProviderConnectionCreatedV1", "PROVIDER_CONNECTION_DELETED": "#/components/schemas/AuditLogEventProviderConnectionDeletedV1", "PROVIDER_CONNECTION_UPDATED": "#/components/schemas/AuditLogEventProviderConnectionUpdatedV1", @@ -18257,10 +19541,16 @@ "REQUIRE_GROUP_BASED_ADMINS_ENABLED": "#/components/schemas/AuditLogEventRequireGroupBasedAdminsEnabledV1", "SECRET_DELETED": "#/components/schemas/AuditLogEventSecretDeletedV1", "SECRET_UPDATED": "#/components/schemas/AuditLogEventSecretUpdatedV1", + "SERVICE_ACCOUNT_CREATED": "#/components/schemas/AuditLogEventServiceAccountCreatedV1", + "SERVICE_ACCOUNT_DELETED": "#/components/schemas/AuditLogEventServiceAccountDeletedV1", + "SERVICE_ACCOUNT_UPDATED": "#/components/schemas/AuditLogEventServiceAccountUpdatedV1", "SSH_CERTIFICATE_SIGNED": "#/components/schemas/AuditLogEventSshCertificateSignedV1", "TELEMETRY_EXPORT_CREATED": "#/components/schemas/AuditLogEventTelemetryExportCreatedV1", "TELEMETRY_EXPORT_DELETED": "#/components/schemas/AuditLogEventTelemetryExportDeletedV1", "TELEMETRY_EXPORT_UPDATED": "#/components/schemas/AuditLogEventTelemetryExportUpdatedV1", + "TRUST_RULE_CREATED": "#/components/schemas/AuditLogEventTrustRuleCreatedV1", + "TRUST_RULE_DELETED": "#/components/schemas/AuditLogEventTrustRuleDeletedV1", + "TRUST_RULE_UPDATED": "#/components/schemas/AuditLogEventTrustRuleUpdatedV1", "USER_INVITED": "#/components/schemas/AuditLogEventUserInvitedV1", "USER_JOINED_ORGANIZATION": "#/components/schemas/AuditLogEventUserJoinedOrganizationV1", "USER_REMOVED": "#/components/schemas/AuditLogEventUserRemovedV1", @@ -18357,6 +19647,9 @@ { "$ref": "#/components/schemas/AuditLogEventApiKeyLifetimeLimitsUpdatedV1" }, + { + "$ref": "#/components/schemas/AuditLogEventOrganizationApiKeySettingsUpdatedV1" + }, { "$ref": "#/components/schemas/AuditLogEventGatewayEndpointCreatedV1" }, @@ -18458,6 +19751,33 @@ }, { "$ref": "#/components/schemas/AuditLogEventTelemetryExportDeletedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventServiceAccountCreatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventServiceAccountUpdatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventServiceAccountDeletedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventIdentityProviderCreatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventIdentityProviderUpdatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventIdentityProviderDeletedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventTrustRuleCreatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventTrustRuleUpdatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventTrustRuleDeletedV1" } ], "title": "Event Data" @@ -21022,6 +22342,108 @@ "title": "AuditLogEventGridMachineUserUpdatedV1", "type": "object" }, + "AuditLogEventIdentityProviderCreatedV1": { + "description": "An identity provider was added.", + "properties": { + "event_type": { + "const": "IDENTITY_PROVIDER_CREATED", + "title": "Event Type", + "type": "string" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Null when the provider was added without one.", + "title": "Description" + }, + "predefined": { + "$ref": "#/components/schemas/AuditLogEventPredefinedIdentityProviderConfigV1", + "description": "The provider's settings, as the identity provider resource returns them." + } + }, + "required": [ + "event_type", + "identity_provider_id", + "name", + "predefined" + ], + "title": "AuditLogEventIdentityProviderCreatedV1", + "type": "object" + }, + "AuditLogEventIdentityProviderDeletedV1": { + "description": "An identity provider was deleted.", + "properties": { + "event_type": { + "const": "IDENTITY_PROVIDER_DELETED", + "title": "Event Type", + "type": "string" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "event_type", + "identity_provider_id", + "name" + ], + "title": "AuditLogEventIdentityProviderDeletedV1", + "type": "object" + }, + "AuditLogEventIdentityProviderUpdatedV1": { + "description": "An identity provider was updated.", + "properties": { + "event_type": { + "const": "IDENTITY_PROVIDER_UPDATED", + "title": "Event Type", + "type": "string" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/components/schemas/AuditFieldChangeV1" + }, + "description": "The fields the update changed, keyed by field name.", + "title": "Changes", + "type": "object" + } + }, + "required": [ + "event_type", + "identity_provider_id", + "name", + "changes" + ], + "title": "AuditLogEventIdentityProviderUpdatedV1", + "type": "object" + }, "AuditLogEventModelDeletedV1": { "description": "A model was deleted.", "properties": { @@ -21789,6 +23211,67 @@ "title": "AuditLogEventModelRenamedV1", "type": "object" }, + "AuditLogEventOrganizationApiKeySettingsUpdatedV1": { + "description": "An administrator changed which classes of API key the organization allows creating.", + "properties": { + "event_type": { + "const": "ORGANIZATION_API_KEY_SETTINGS_UPDATED", + "title": "Event Type", + "type": "string" + }, + "organization_id": { + "title": "Organization Id", + "type": "string" + }, + "previous_allow_personal_api_keys": { + "title": "Previous Allow Personal Api Keys", + "type": "boolean" + }, + "new_allow_personal_api_keys": { + "title": "New Allow Personal Api Keys", + "type": "boolean" + }, + "previous_allow_service_account_api_keys": { + "title": "Previous Allow Service Account Api Keys", + "type": "boolean" + }, + "new_allow_service_account_api_keys": { + "title": "New Allow Service Account Api Keys", + "type": "boolean" + } + }, + "required": [ + "event_type", + "organization_id", + "previous_allow_personal_api_keys", + "new_allow_personal_api_keys", + "previous_allow_service_account_api_keys", + "new_allow_service_account_api_keys" + ], + "title": "AuditLogEventOrganizationApiKeySettingsUpdatedV1", + "type": "object" + }, + "AuditLogEventPredefinedIdentityProviderConfigV1": { + "description": "Settings of a predefined identity provider, as recorded on an identity provider event. Not\nitself an event payload.", + "properties": { + "kind": { + "description": "Which predefined provider, for example `AWS_EKS`.", + "title": "Kind", + "type": "string" + }, + "issuer_url": { + "description": "The `iss` claim of the provider's tokens.", + "title": "Issuer Url", + "type": "string" + } + }, + "required": [ + "kind", + "issuer_url" + ], + "title": "AuditLogEventPredefinedIdentityProviderConfigV1", + "type": "object" + }, "AuditLogEventPromotionSettingsOverrideV1": { "description": "Promotion settings overridden for one promotion. Null means the environment's value. Not\nitself a payload in the discriminated union.", "properties": { @@ -22112,6 +23595,162 @@ "title": "AuditLogEventSecretUpdatedV1", "type": "object" }, + "AuditLogEventServiceAccountCreatedV1": { + "description": "A service account was created.", + "properties": { + "event_type": { + "const": "SERVICE_ACCOUNT_CREATED", + "title": "Event Type", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Null when the account was created without one.", + "title": "Description" + }, + "owner_team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The team that owns the account. Null for an organization account.", + "title": "Owner Team Id" + }, + "preset_permissions": { + "$ref": "#/components/schemas/AuditLogEventServiceAccountPresetPermissionsV1" + } + }, + "required": [ + "event_type", + "service_account_id", + "name", + "preset_permissions" + ], + "title": "AuditLogEventServiceAccountCreatedV1", + "type": "object" + }, + "AuditLogEventServiceAccountDeletedV1": { + "description": "A service account was deleted.", + "properties": { + "event_type": { + "const": "SERVICE_ACCOUNT_DELETED", + "title": "Event Type", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "event_type", + "service_account_id", + "name" + ], + "title": "AuditLogEventServiceAccountDeletedV1", + "type": "object" + }, + "AuditLogEventServiceAccountPresetPermissionsV1": { + "description": "A service account's access, as recorded on a service account event. Not itself an event\npayload.", + "properties": { + "api_key_type": { + "description": "The API key type whose permissions the account has, as API key events record it.", + "title": "Api Key Type", + "type": "string" + }, + "model_ids": { + "description": "Models the access is limited to; empty for all.", + "items": { + "type": "string" + }, + "title": "Model Ids", + "type": "array" + }, + "environment_names": { + "description": "Environments the access is limited to, or may also manage; empty for none.", + "items": { + "type": "string" + }, + "title": "Environment Names", + "type": "array" + }, + "model_api_slugs": { + "description": "Model APIs the access is limited to; empty for all.", + "items": { + "type": "string" + }, + "title": "Model Api Slugs", + "type": "array" + } + }, + "required": [ + "api_key_type", + "model_ids", + "environment_names", + "model_api_slugs" + ], + "title": "AuditLogEventServiceAccountPresetPermissionsV1", + "type": "object" + }, + "AuditLogEventServiceAccountUpdatedV1": { + "description": "A service account was updated. Disabling or enabling it is a change to `disabled`.", + "properties": { + "event_type": { + "const": "SERVICE_ACCOUNT_UPDATED", + "title": "Event Type", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/components/schemas/AuditFieldChangeV1" + }, + "description": "The fields the update changed, keyed by field name.", + "title": "Changes", + "type": "object" + } + }, + "required": [ + "event_type", + "service_account_id", + "name", + "changes" + ], + "title": "AuditLogEventServiceAccountUpdatedV1", + "type": "object" + }, "AuditLogEventSshCertificateSignedV1": { "description": "An SSH certificate was signed for a workload.", "properties": { @@ -22234,6 +23873,131 @@ "title": "AuditLogEventTelemetryExportUpdatedV1", "type": "object" }, + "AuditLogEventTrustRuleCreatedV1": { + "description": "A trust rule was created.", + "properties": { + "event_type": { + "const": "TRUST_RULE_CREATED", + "title": "Event Type", + "type": "string" + }, + "trust_rule_id": { + "title": "Trust Rule Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Null when the rule was created without one.", + "title": "Description" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "condition": { + "description": "The CEL expression a token's claims must satisfy.", + "title": "Condition", + "type": "string" + }, + "audience": { + "description": "The `aud` claim a token must carry.", + "title": "Audience", + "type": "string" + }, + "max_access_token_lifetime_seconds": { + "description": "The longest lifetime, in seconds, of an access token the rule issues.", + "title": "Max Access Token Lifetime Seconds", + "type": "integer" + } + }, + "required": [ + "event_type", + "trust_rule_id", + "name", + "identity_provider_id", + "service_account_id", + "condition", + "audience", + "max_access_token_lifetime_seconds" + ], + "title": "AuditLogEventTrustRuleCreatedV1", + "type": "object" + }, + "AuditLogEventTrustRuleDeletedV1": { + "description": "A trust rule was deleted.", + "properties": { + "event_type": { + "const": "TRUST_RULE_DELETED", + "title": "Event Type", + "type": "string" + }, + "trust_rule_id": { + "title": "Trust Rule Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "event_type", + "trust_rule_id", + "name" + ], + "title": "AuditLogEventTrustRuleDeletedV1", + "type": "object" + }, + "AuditLogEventTrustRuleUpdatedV1": { + "description": "A trust rule was updated.", + "properties": { + "event_type": { + "const": "TRUST_RULE_UPDATED", + "title": "Event Type", + "type": "string" + }, + "trust_rule_id": { + "title": "Trust Rule Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/components/schemas/AuditFieldChangeV1" + }, + "description": "The fields the update changed, keyed by field name.", + "title": "Changes", + "type": "object" + } + }, + "required": [ + "event_type", + "trust_rule_id", + "name", + "changes" + ], + "title": "AuditLogEventTrustRuleUpdatedV1", + "type": "object" + }, "AuditLogEventTypeV1": { "description": "Type of action recorded by an audit-log entry.", "enum": [ @@ -22296,7 +24060,17 @@ "VOLUME_UPDATED", "TELEMETRY_EXPORT_CREATED", "TELEMETRY_EXPORT_UPDATED", - "TELEMETRY_EXPORT_DELETED" + "TELEMETRY_EXPORT_DELETED", + "SERVICE_ACCOUNT_CREATED", + "SERVICE_ACCOUNT_UPDATED", + "SERVICE_ACCOUNT_DELETED", + "IDENTITY_PROVIDER_CREATED", + "IDENTITY_PROVIDER_UPDATED", + "IDENTITY_PROVIDER_DELETED", + "TRUST_RULE_CREATED", + "TRUST_RULE_UPDATED", + "TRUST_RULE_DELETED", + "ORGANIZATION_API_KEY_SETTINGS_UPDATED" ], "title": "AuditLogEventTypeV1", "type": "string" @@ -22790,7 +24564,8 @@ "USER_MANAGEMENT", "DIRECTORY_GROUP_MANAGEMENT", "SSH", - "TELEMETRY_EXPORT" + "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY" ], "title": "AuditLogEventTypeGroupV1", "type": "string" @@ -23367,6 +25142,19 @@ "request_backpressure_settings": { "$ref": "#/components/schemas/RequestBackpressureSettingsV1", "description": "Effective request backpressure settings for the deployment." + }, + "failure_reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Why the deployment failed. Set only when the status is DEPLOY_FAILED; null otherwise.", + "title": "Failure Reason" } }, "required": [ @@ -25329,6 +27117,146 @@ "title": "GetStartupSummaryRequestV1", "type": "object" }, + "DeploymentReplicaStatusV1": { + "enum": [ + "STARTING", + "ACTIVE", + "UNHEALTHY", + "TERMINATING", + "TERMINATED", + "UNKNOWN" + ], + "title": "DeploymentReplicaStatusV1", + "type": "string" + }, + "DeploymentReplicaV1": { + "properties": { + "id": { + "description": "Pod-name suffix used for replica lookup and termination, usually five characters.", + "title": "Id", + "type": "string" + }, + "deployment_id": { + "description": "ID of the replica's deployment.", + "title": "Deployment Id", + "type": "string" + }, + "deployment_name": { + "description": "Name of the replica's deployment.", + "title": "Deployment Name", + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1", + "description": "Current replica lifecycle status." + }, + "created_at": { + "description": "Replica creation time in ISO 8601 format.", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "terminated_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Observed termination completion time in ISO 8601 format, or null if unavailable.", + "title": "Terminated At" + }, + "age_seconds": { + "description": "Age in seconds since creation, frozen at termination.", + "title": "Age Seconds", + "type": "number" + }, + "restart_count": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Model container lifetime restart count, or null if unavailable.", + "title": "Restart Count" + } + }, + "required": [ + "id", + "deployment_id", + "deployment_name", + "status", + "created_at", + "terminated_at", + "age_seconds", + "restart_count" + ], + "title": "DeploymentReplicaV1", + "type": "object" + }, + "DeploymentReplicasV1": { + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/DeploymentReplicaV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "DeploymentReplicasV1", + "type": "object" + }, + "DeploymentReplicasRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "statuses": { + "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + "items": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1" + }, + "title": "Statuses", + "type": "array" + } + }, + "title": "DeploymentReplicasRequestV1", + "type": "object" + }, "TerminateReplicaResponseV1": { "description": "The response to a request to terminate a replica in a deployment.", "properties": { @@ -26421,7 +28349,8 @@ }, "sampling_mode": { "$ref": "#/components/schemas/TrafficRoutingRuleShadowSamplingModeV1", - "description": "How requests are picked for shadowing" + "default": "USER_SESSION", + "description": "How requests are picked for shadowing. Defaults to USER_SESSION." }, "propagate_client_cancellation": { "description": "Whether a shadow request is cancelled when the original client disconnects", @@ -26434,7 +28363,6 @@ "targets", "percent_traffic", "expires_at", - "sampling_mode", "propagate_client_cancellation" ], "title": "TrafficRoutingRuleUpsertV1", @@ -27893,8 +29821,58 @@ "title": "CheckpointSyncStatus", "type": "string" }, + "TrainingBDNConfigResponseV1": { + "properties": { + "mounts": { + "items": { + "$ref": "#/components/schemas/TrainingBDNMountResponseV1" + }, + "title": "Mounts", + "type": "array" + } + }, + "title": "TrainingBDNConfigResponseV1", + "type": "object" + }, + "TrainingBDNMountResponseV1": { + "properties": { + "source": { + "title": "Source", + "type": "string" + }, + "path": { + "title": "Path", + "type": "string" + }, + "include": { + "description": "Relative glob patterns selecting files to mount; empty includes all files.", + "items": { + "type": "string" + }, + "title": "Include", + "type": "array" + }, + "exclude": { + "description": "Relative glob patterns excluding files from the mount; exclusions win.", + "items": { + "type": "string" + }, + "title": "Exclude", + "type": "array" + } + }, + "required": [ + "source", + "path" + ], + "title": "TrainingBDNMountResponseV1", + "type": "object" + }, "TrainingJobV1": { "properties": { + "bdn": { + "$ref": "#/components/schemas/TrainingBDNConfigResponseV1" + }, "id": { "description": "Unique identifier of the training job.", "title": "Id", @@ -28876,6 +30854,9 @@ "CreateTrainingJobV1": { "description": "Configuration for a training job.", "properties": { + "bdn": { + "$ref": "#/components/schemas/TrainingBDNConfigV1" + }, "image": { "$ref": "#/components/schemas/CreateTrainingJobImageV1", "examples": [ @@ -29352,6 +31333,58 @@ "title": "SecretReferenceV1", "type": "object" }, + "TrainingBDNConfigV1": { + "additionalProperties": false, + "description": "Read-only BDN mounts with the same reference semantics as inference.", + "properties": { + "mounts": { + "items": { + "$ref": "#/components/schemas/TrainingBDNMountV1" + }, + "maxItems": 32, + "title": "Mounts", + "type": "array" + } + }, + "title": "TrainingBDNConfigV1", + "type": "object" + }, + "TrainingBDNMountV1": { + "additionalProperties": false, + "description": "A requested read-only BDN dataset mount.", + "properties": { + "source": { + "title": "Source", + "type": "string" + }, + "path": { + "title": "Path", + "type": "string" + }, + "include": { + "description": "Relative glob patterns selecting files to mount; empty includes all files.", + "items": { + "type": "string" + }, + "title": "Include", + "type": "array" + }, + "exclude": { + "description": "Relative glob patterns excluding files from the mount; exclusions win.", + "items": { + "type": "string" + }, + "title": "Exclude", + "type": "array" + } + }, + "required": [ + "source", + "path" + ], + "title": "TrainingBDNMountV1", + "type": "object" + }, "TrainingWeightAuthV1": { "description": "Authentication configuration for a training weight source.", "properties": { @@ -29850,7 +31883,7 @@ }, "type": "array" }, - "description": "A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + "description": "A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Memory Usage Bytes", "type": "object" }, @@ -29861,12 +31894,56 @@ }, "type": "array" }, - "description": "A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + "description": "A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Utilization", "type": "object" }, + "gpu_temperature_celsius": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Temperature Celsius", + "type": "object" + }, + "gpu_power_usage_watts": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Power Usage Watts", + "type": "object" + }, + "gpu_tensor_core_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Tensor Core Utilization", + "type": "object" + }, + "gpu_memory_bandwidth_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Memory Bandwidth Utilization", + "type": "object" + }, "cpu_usage": { - "description": "The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + "description": "The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29874,7 +31951,7 @@ "type": "array" }, "cpu_memory_usage_bytes": { - "description": "The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + "description": "The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29883,12 +31960,16 @@ }, "ephemeral_storage": { "$ref": "#/components/schemas/StorageMetricsV1", - "description": "The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + "description": "The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." } }, "required": [ "gpu_memory_usage_bytes", "gpu_utilization", + "gpu_temperature_celsius", + "gpu_power_usage_watts", + "gpu_tensor_core_utilization", + "gpu_memory_bandwidth_utilization", "cpu_usage", "cpu_memory_usage_bytes", "ephemeral_storage" @@ -29926,7 +32007,7 @@ }, "type": "array" }, - "description": "A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + "description": "A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Memory Usage Bytes", "type": "object" }, @@ -29937,12 +32018,56 @@ }, "type": "array" }, - "description": "A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + "description": "A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Utilization", "type": "object" }, + "gpu_temperature_celsius": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Temperature Celsius", + "type": "object" + }, + "gpu_power_usage_watts": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Power Usage Watts", + "type": "object" + }, + "gpu_tensor_core_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Tensor Core Utilization", + "type": "object" + }, + "gpu_memory_bandwidth_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Memory Bandwidth Utilization", + "type": "object" + }, "cpu_usage": { - "description": "The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + "description": "The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29950,7 +32075,7 @@ "type": "array" }, "cpu_memory_usage_bytes": { - "description": "The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + "description": "The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29959,7 +32084,7 @@ }, "ephemeral_storage": { "$ref": "#/components/schemas/StorageMetricsV1", - "description": "The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + "description": "The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." }, "training_job": { "$ref": "#/components/schemas/TrainingJobV1", @@ -29988,6 +32113,10 @@ "required": [ "gpu_memory_usage_bytes", "gpu_utilization", + "gpu_temperature_celsius", + "gpu_power_usage_watts", + "gpu_tensor_core_utilization", + "gpu_memory_bandwidth_utilization", "cpu_usage", "cpu_memory_usage_bytes", "ephemeral_storage", @@ -31508,9 +33637,27 @@ } ], "default": null, - "description": "Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + "description": "Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", "title": "Base Checkpoint" }, + "base_checkpoint_auth": { + "anyOf": [ + { + "$ref": "#/components/schemas/TrainingWeightAuthV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + "examples": [ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint" + } + ] + }, "sampler_num_replicas": { "anyOf": [ { @@ -31571,6 +33718,198 @@ "title": "DeactivateLoopsRunResponseV1", "type": "object" }, + "LoopsCheckpointV1": { + "description": "A checkpoint saved by a Loops run.", + "properties": { + "checkpoint_id": { + "description": "The ID of the checkpoint.", + "title": "Checkpoint Id", + "type": "string" + }, + "created_at": { + "description": "The timestamp of the checkpoint in ISO 8601 format.", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "checkpoint_type": { + "description": "The type of checkpoint.", + "title": "Checkpoint Type", + "type": "string" + }, + "base_model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The base model of the checkpoint.", + "title": "Base Model" + }, + "lora_adapter_config": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "description": "The adapter config of the checkpoint.", + "title": "Lora Adapter Config" + }, + "size_bytes": { + "description": "The size of the checkpoint in bytes.", + "title": "Size Bytes", + "type": "integer" + }, + "sync_status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sync state of the checkpoint: SYNCING or COMPLETE.", + "title": "Sync Status" + }, + "id": { + "description": "The checkpoint ID.", + "title": "Id", + "type": "string" + }, + "lora_config": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoopsLoRAConfigV1" + }, + { + "type": "null" + } + ], + "description": "The immutable LoRA config used to save this checkpoint. Null means the checkpoint is unsupported and cannot be loaded." + }, + "run_id": { + "description": "The ID of the run that produced the checkpoint.", + "title": "Run Id", + "type": "string" + }, + "target": { + "$ref": "#/components/schemas/TrainerCheckpointTarget", + "description": "Whether this checkpoint is loadable by the sampler or by the run." + }, + "expires_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "When the checkpoint expires and is deleted, set from the TTL it was saved with. Null means it's kept until you delete it. A checkpoint that's still in use when it expires, for example deployed, is deleted once it's released.", + "title": "Expires At" + } + }, + "required": [ + "checkpoint_id", + "created_at", + "checkpoint_type", + "base_model", + "lora_adapter_config", + "size_bytes", + "id", + "lora_config", + "run_id", + "target", + "expires_at" + ], + "title": "LoopsCheckpointV1", + "type": "object" + }, + "LoopsLoRAConfigV1": { + "description": "A published LoRA config: which modules the adapter targets and how experts are laid out.", + "properties": { + "config_version": { + "description": "The config version, like v1.", + "title": "Config Version", + "type": "string" + }, + "targets": { + "description": "The module names the LoRA adapter targets.", + "items": { + "type": "string" + }, + "title": "Targets", + "type": "array" + }, + "expert_layout": { + "anyOf": [ + { + "enum": [ + "per_expert", + "shared_outer", + "shared_adapter" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "How routed-expert LoRA weights are laid out. Null when no experts are targeted.", + "title": "Expert Layout" + } + }, + "required": [ + "config_version", + "targets" + ], + "title": "LoopsLoRAConfigV1", + "type": "object" + }, + "TrainerCheckpointTarget": { + "description": "Whether a TrainerServerCheckpoint is loadable by the sampler or the trainer.\n\nSAMPLER checkpoints are consumed by the sampling server for inference;\nTRAINER checkpoints capture full trainer state for resuming training.\nMirrored in the bt:// URI as\n``bt://loops:/(sampler_weights|weights)/``.", + "enum": [ + "sampler", + "trainer" + ], + "title": "TrainerCheckpointTarget", + "type": "string" + }, + "DeleteLoopsRunResponseV1": { + "description": "A Loops run whose delete was accepted.", + "properties": { + "id": { + "description": "The deleted Loops run ID.", + "title": "Id", + "type": "string" + }, + "kept_checkpoints": { + "description": "The run's checkpoints that were not deleted because something still uses them, such as a deployment. They stay usable until that stops.", + "items": { + "$ref": "#/components/schemas/LoopsCheckpointV1" + }, + "title": "Kept Checkpoints", + "type": "array" + } + }, + "required": [ + "id", + "kept_checkpoints" + ], + "title": "DeleteLoopsRunResponseV1", + "type": "object" + }, "GetLoopsRunResponseV1": { "description": "Response for ``GET /v1/loops/runs/``.", "properties": { @@ -31730,9 +34069,27 @@ } ], "default": null, - "description": "Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + "description": "Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", "title": "Base Checkpoint" }, + "base_checkpoint_auth": { + "anyOf": [ + { + "$ref": "#/components/schemas/TrainingWeightAuthV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + "examples": [ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint" + } + ] + }, "scope": { "$ref": "#/components/schemas/LoopsPlacementScopeV1", "default": "default", @@ -31968,160 +34325,6 @@ "title": "GetLoopsSamplerResponseV1", "type": "object" }, - "LoopsCheckpointV1": { - "description": "A checkpoint saved by a Loops run.", - "properties": { - "checkpoint_id": { - "description": "The ID of the checkpoint.", - "title": "Checkpoint Id", - "type": "string" - }, - "created_at": { - "description": "The timestamp of the checkpoint in ISO 8601 format.", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "checkpoint_type": { - "description": "The type of checkpoint.", - "title": "Checkpoint Type", - "type": "string" - }, - "base_model": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The base model of the checkpoint.", - "title": "Base Model" - }, - "lora_adapter_config": { - "anyOf": [ - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "description": "The adapter config of the checkpoint.", - "title": "Lora Adapter Config" - }, - "size_bytes": { - "description": "The size of the checkpoint in bytes.", - "title": "Size Bytes", - "type": "integer" - }, - "sync_status": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Sync state of the checkpoint: SYNCING or COMPLETE.", - "title": "Sync Status" - }, - "id": { - "description": "The checkpoint ID.", - "title": "Id", - "type": "string" - }, - "lora_config": { - "anyOf": [ - { - "$ref": "#/components/schemas/LoopsLoRAConfigV1" - }, - { - "type": "null" - } - ], - "description": "The immutable LoRA config used to save this checkpoint. Null means the checkpoint is unsupported and cannot be loaded." - }, - "run_id": { - "description": "The ID of the run that produced the checkpoint.", - "title": "Run Id", - "type": "string" - }, - "target": { - "$ref": "#/components/schemas/TrainerCheckpointTarget", - "description": "Whether this checkpoint is loadable by the sampler or by the run." - } - }, - "required": [ - "checkpoint_id", - "created_at", - "checkpoint_type", - "base_model", - "lora_adapter_config", - "size_bytes", - "id", - "lora_config", - "run_id", - "target" - ], - "title": "LoopsCheckpointV1", - "type": "object" - }, - "LoopsLoRAConfigV1": { - "description": "A published LoRA config: which modules the adapter targets and how experts are laid out.", - "properties": { - "config_version": { - "description": "The config version, like v1.", - "title": "Config Version", - "type": "string" - }, - "targets": { - "description": "The module names the LoRA adapter targets.", - "items": { - "type": "string" - }, - "title": "Targets", - "type": "array" - }, - "expert_layout": { - "anyOf": [ - { - "enum": [ - "per_expert", - "shared_outer", - "shared_adapter" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "How routed-expert LoRA weights are laid out. Null when no experts are targeted.", - "title": "Expert Layout" - } - }, - "required": [ - "config_version", - "targets" - ], - "title": "LoopsLoRAConfigV1", - "type": "object" - }, - "TrainerCheckpointTarget": { - "description": "Whether a TrainerServerCheckpoint is loadable by the sampler or the trainer.\n\nSAMPLER checkpoints are consumed by the sampling server for inference;\nTRAINER checkpoints capture full trainer state for resuming training.\nMirrored in the bt:// URI as\n``bt://loops:/(sampler_weights|weights)/``.", - "enum": [ - "sampler", - "trainer" - ], - "title": "TrainerCheckpointTarget", - "type": "string" - }, "ListLoopsCheckpointsResponseV1": { "description": "Checkpoints matching the query filter.", "properties": { @@ -32293,6 +34496,44 @@ "title": "DeployLoopsCheckpointResponseV1", "type": "object" }, + "LoopsCheckpointTombstoneV1": { + "description": "A Loops checkpoint whose delete was accepted.", + "properties": { + "id": { + "description": "The deleted checkpoint ID.", + "title": "Id", + "type": "string" + }, + "run_id": { + "description": "The ID of the run that produced the checkpoint.", + "title": "Run Id", + "type": "string" + }, + "checkpoint_id": { + "description": "The name the checkpoint was saved under.", + "title": "Checkpoint Id", + "type": "string" + }, + "target": { + "$ref": "#/components/schemas/TrainerCheckpointTarget", + "description": "Whether the checkpoint was loadable by the sampler or by the run." + }, + "path": { + "description": "The checkpoint's bt:// path.", + "title": "Path", + "type": "string" + } + }, + "required": [ + "id", + "run_id", + "checkpoint_id", + "target", + "path" + ], + "title": "LoopsCheckpointTombstoneV1", + "type": "object" + }, "LoopsCheckpointFilesResponseV1": { "description": "Response with presigned URLs for files under a Loops checkpoint.", "properties": { @@ -32420,6 +34661,29 @@ "title": "LoopsCheckpointSourceResponseV1", "type": "object" }, + "SetLoopsCheckpointTtlRequestV1": { + "properties": { + "ttl_seconds": { + "anyOf": [ + { + "maximum": 315360000, + "minimum": 3600, + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", + "title": "Ttl Seconds" + } + }, + "required": [ + "ttl_seconds" + ], + "title": "SetLoopsCheckpointTtlRequestV1", + "type": "object" + }, "LoopsDeploymentStatusV1": { "description": "Latest deployment status for a Loops deployment.", "properties": { @@ -33118,12 +35382,12 @@ "type": "string" }, "baseline": { - "description": "Baseline GPU allocation for the team. 0 if not configured.", + "description": "Configured minimum GPU allocation for the team. Not enforced. 0 if not configured.", "title": "Baseline", "type": "integer" }, "limit": { - "description": "Maximum concurrent GPUs of this type for this team", + "description": "The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", "title": "Limit", "type": "integer" }, @@ -33134,7 +35398,7 @@ }, "dedicated_usage_count": { "default": 0, - "description": "Portion of usage_count from standard (non-spot) jobs.", + "description": "Portion of usage_count from on-demand (non-spot) jobs.", "title": "Dedicated Usage Count", "type": "integer" }, @@ -33165,15 +35429,33 @@ "type": "string" }, "baseline": { - "description": "Baseline GPU allocation; jobs below this threshold are expected to run immediately. 0 if not configured.", + "description": "Configured minimum GPU allocation (`min_gpus`). 0 if not configured. Use `on_demand_quota` for the quota applied to on-demand jobs.", "title": "Baseline", "type": "integer" }, "limit": { - "description": "Maximum concurrent GPUs of this type for this org", + "description": "Configured maximum GPU allocation (`max_gpus`). Use `on_demand_quota` and `spot_quota` for the quotas applied to jobs.", "title": "Limit", "type": "integer" }, + "on_demand_quota": { + "description": "GPU quota for this type for on-demand (non-spot) jobs: the most GPUs they can use at once.", + "title": "On Demand Quota", + "type": "integer" + }, + "spot_quota": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "GPU quota for this type for spot jobs. Spot shares this quota with on-demand jobs: spot can use up to the quota minus on-demand GPUs in use. Null if spot is not enabled for the organization.", + "title": "Spot Quota" + }, "usage_count": { "description": "GPUs currently in use by active training jobs", "title": "Usage Count", @@ -33181,13 +35463,13 @@ }, "dedicated_usage_count": { "default": 0, - "description": "Portion of usage_count from standard (non-spot) jobs, which run against the baseline.", + "description": "Portion of usage_count from on-demand (non-spot) jobs.", "title": "Dedicated Usage Count", "type": "integer" }, "spot_usage_count": { "default": 0, - "description": "Portion of usage_count from spot jobs, which burst into the peak and may push usage above the limit.", + "description": "Portion of usage_count from spot jobs.", "title": "Spot Usage Count", "type": "integer" } @@ -33196,6 +35478,7 @@ "gpu_type", "baseline", "limit", + "on_demand_quota", "usage_count" ], "title": "TrainingGpuCapacityItemV1", @@ -33205,7 +35488,7 @@ "description": "Response for the training GPU capacity endpoint.", "properties": { "gpu_capacities": { - "description": "Org-level GPU capacity limits and current usage per GPU type", + "description": "Organization GPU quotas and current usage per GPU type", "items": { "$ref": "#/components/schemas/TrainingGpuCapacityItemV1" }, @@ -33213,12 +35496,18 @@ "type": "array" }, "team_gpu_capacities": { - "description": "Per-team GPU capacity limits and current usage per GPU type", + "description": "Per-team GPU quotas and current usage per GPU type", "items": { "$ref": "#/components/schemas/TeamTrainingGpuCapacityItemV1" }, "title": "Team Gpu Capacities", "type": "array" + }, + "spot_enabled": { + "default": false, + "description": "Whether the organization can submit spot training jobs.", + "title": "Spot Enabled", + "type": "boolean" } }, "required": [ @@ -33228,7 +35517,7 @@ "type": "object" }, "PatchTeamTrainingGpuCapacityRequestV1": { - "description": "A request to set the GPU capacity ceiling for a (team, gpu_type) pair.\n\nCreates the limit if one doesn't already exist for this team and GPU type,\notherwise updates it in place.", + "description": "A request to set the GPU quota for a (team, gpu_type) pair.\n\nCreates the quota if one doesn't already exist for this team and GPU type,\notherwise updates it in place.", "properties": { "team_id": { "description": "Team identifier", @@ -33241,7 +35530,7 @@ "type": "string" }, "max_gpus": { - "description": "Max concurrent GPUs of this type the team may use", + "description": "The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", "examples": [ 8, 16, @@ -33260,11 +35549,11 @@ "type": "object" }, "PatchTeamTrainingGpuCapacityResponseV1": { - "description": "Response for setting a team's GPU capacity ceiling.", + "description": "Response for setting a team's GPU quota.", "properties": { "team_gpu_capacity": { "$ref": "#/components/schemas/TeamTrainingGpuCapacityItemV1", - "description": "The updated per-team GPU capacity limit" + "description": "The updated per-team GPU quota" } }, "required": [ @@ -34747,6 +37036,14 @@ }, "title": "Metrics", "type": "array" + }, + "team_ids": { + "description": "Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", + "items": { + "type": "string" + }, + "title": "Team Ids", + "type": "array" } }, "title": "GetModelAPIMetricsRequestV1", @@ -36885,7 +39182,7 @@ "type": "string" } ], - "description": "Subtotal cost in dollars after applying credits used", + "description": "Usage charges in dollars before applying credits", "title": "Subtotal" }, "credits_used": { @@ -37175,6 +39472,32 @@ "description": "Subtotal cost in dollars for this model", "title": "Subtotal" }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Team ID for multi-team organizations; otherwise null", + "title": "Team Id" + }, + "team_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Team name, including historical teams; null if unavailable", + "title": "Team Name" + }, "input_tokens": { "description": "Total input tokens for this model", "title": "Input Tokens", @@ -37221,7 +39544,7 @@ "type": "string" } ], - "description": "Subtotal cost in dollars after applying credits used", + "description": "Usage charges in dollars before applying credits", "title": "Subtotal" }, "credits_used": { @@ -37247,11 +39570,11 @@ "type": "string" } ], - "description": "Total cost in dollars", + "description": "Usage charges in dollars after applying credits, floored at zero", "title": "Total" }, "breakdown": { - "description": "Per-model usage breakdown", + "description": "Per-model usage breakdown, split by team for multi-team organizations", "items": { "$ref": "#/components/schemas/ModelApiItemV1" }, @@ -37332,7 +39655,7 @@ "type": "string" } ], - "description": "Subtotal cost in dollars after applying credits used", + "description": "Usage charges in dollars before applying credits", "title": "Subtotal" }, "credits_used": { @@ -37390,169 +39713,1730 @@ "dedicated_usage": { "anyOf": [ { - "$ref": "#/components/schemas/DedicatedUsageV1" + "$ref": "#/components/schemas/DedicatedUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dedicated model serving usage" + }, + "training_usage": { + "anyOf": [ + { + "$ref": "#/components/schemas/TrainingUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Training usage" + }, + "model_apis_usage": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelApisUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Model APIs usage" + }, + "loops_usage": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoopsUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Serverless Loops usage, billed per token. Loops usage on dedicated trainers and samplers is billed by the minute and is part of training usage." + } + }, + "title": "UsageSummaryV1", + "type": "object" + }, + "UsageSummaryRequestV1": { + "properties": { + "start_date": { + "description": "Inclusive start date (ISO 8601, normalized to midnight UTC). Earliest queryable: 2026-01-01.", + "format": "date-time", + "title": "Start Date", + "type": "string" + }, + "end_date": { + "description": "Exclusive end date (ISO 8601, normalized to midnight UTC). Date range cannot exceed 31 days.", + "format": "date-time", + "title": "End Date", + "type": "string" + } + }, + "required": [ + "start_date", + "end_date" + ], + "title": "UsageSummaryRequestV1", + "type": "object" + }, + "ToolCallUsageBucketV1": { + "description": "Server-side tool call usage for one day, provider, charge unit, and model.", + "properties": { + "date": { + "description": "UTC day the usage was recorded on.", + "format": "date", + "title": "Date", + "type": "string" + }, + "provider": { + "description": "Tool provider, such as exa or parallel.", + "title": "Provider", + "type": "string" + }, + "sku": { + "description": "Charge unit, as `/`. The unit is what the provider reported, or the tool name when it reported none. Its meaning varies by provider.", + "title": "Sku", + "type": "string" + }, + "model": { + "description": "Model that made the tool calls.", + "title": "Model", + "type": "string" + }, + "calls": { + "description": "Number of tool calls.", + "title": "Calls", + "type": "integer" + }, + "quantity": { + "description": "Billable quantity in the provider's sku unit, summed over the calls.", + "title": "Quantity", + "type": "number" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Team attributed to the usage. Null when not grouping by team or when historical team attribution is unavailable.", + "title": "Team Id" + } + }, + "required": [ + "date", + "provider", + "sku", + "model", + "calls", + "quantity" + ], + "title": "ToolCallUsageBucketV1", + "type": "object" + }, + "ToolCallUsageResponseV1": { + "description": "Daily server-side tool call usage, ordered by day, provider, sku, and model.", + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/ToolCallUsageBucketV1" + }, + "title": "Items", + "type": "array" + } + }, + "title": "ToolCallUsageResponseV1", + "type": "object" + }, + "ToolCallUsageDimensionV1": { + "enum": [ + "TEAM" + ], + "title": "ToolCallUsageDimensionV1", + "type": "string" + }, + "ToolCallUsageRequestV1": { + "properties": { + "start_date": { + "description": "Inclusive UTC calendar day at the start of the query range.", + "format": "date", + "title": "Start Date", + "type": "string" + }, + "end_date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included. The date range cannot exceed 90 days.", + "title": "End Date" + }, + "team_ids": { + "description": "Return only usage for these teams, repeated once per team. Defaults to all teams you can manage. An unauthorized team ID causes a 403 response.", + "items": { + "type": "string" + }, + "title": "Team Ids", + "type": "array" + }, + "group_by": { + "description": "Pass TEAM to split daily rows by team. Defaults to aggregating across teams.", + "items": { + "$ref": "#/components/schemas/ToolCallUsageDimensionV1" + }, + "title": "Group By", + "type": "array" + } + }, + "required": [ + "start_date" + ], + "title": "ToolCallUsageRequestV1", + "type": "object" + }, + "UserInfoV1": { + "description": "A Baseten user.", + "properties": { + "user_id": { + "description": "Unique identifier for the user", + "title": "User Id", + "type": "string" + }, + "email": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Email address of the user", + "title": "Email" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the user", + "title": "Name" + }, + "workspace_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the user's workspace", + "title": "Workspace Name" + } + }, + "required": [ + "user_id" + ], + "title": "UserInfoV1", + "type": "object" + }, + "UsersResponseV1": { + "description": "A page of users in the caller's workspace.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/UserInfoV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "UsersResponseV1", + "type": "object" + }, + "UsersRequestV1": { + "description": "Request parameters for listing users.", + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "email": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "When set, returns only users with this exact email, if any.", + "title": "Email" + } + }, + "title": "UsersRequestV1", + "type": "object" + }, + "AwsAssumeRoleV1": { + "description": "AWS AssumeRole trust-policy inputs for the organization.", + "properties": { + "baseten_role_arn": { + "description": "Baseten role ARN to allow in an IAM role's trust policy", + "title": "Baseten Role Arn", + "type": "string" + }, + "external_id": { + "description": "sts:ExternalId Baseten presents when assuming the role", + "title": "External Id", + "type": "string" + } + }, + "required": [ + "baseten_role_arn", + "external_id" + ], + "title": "AwsAssumeRoleV1", + "type": "object" + }, + "OrganizationInfoV1": { + "description": "The caller's organization.", + "properties": { + "org_id": { + "description": "Unique identifier for the organization", + "title": "Org Id", + "type": "string" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the organization", + "title": "Name" + }, + "created_at": { + "description": "Time the organization was created in ISO 8601 format", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "aws_assume_role": { + "anyOf": [ + { + "$ref": "#/components/schemas/AwsAssumeRoleV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" + }, + "allow_personal_api_keys": { + "description": "Whether members can create new personal API keys. Existing keys keep working.", + "title": "Allow Personal Api Keys", + "type": "boolean" + }, + "allow_service_account_api_keys": { + "description": "Whether new team and organization API keys can be created. Existing keys keep working.", + "title": "Allow Service Account Api Keys", + "type": "boolean" + } + }, + "required": [ + "org_id", + "created_at", + "allow_personal_api_keys", + "allow_service_account_api_keys" + ], + "title": "OrganizationInfoV1", + "type": "object" + }, + "UpdateOrganizationRequestV1": { + "additionalProperties": false, + "description": "Partial update of the caller's organization settings. Omitted fields are unchanged.", + "properties": { + "allow_personal_api_keys": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether members can create new personal API keys. Null is not accepted.", + "title": "Allow Personal Api Keys" + }, + "allow_service_account_api_keys": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether new team and organization API keys can be created. Null is not accepted.", + "title": "Allow Service Account Api Keys" + } + }, + "title": "UpdateOrganizationRequestV1", + "type": "object" + }, + "ServiceAccountPresetPermissionsV1": { + "description": "A service account's access: one of the access types API keys have.\n\nTemporary: mirrors API key access until fine-grained access control is available, and may be removed.", + "properties": { + "type": { + "$ref": "#/components/schemas/ServiceAccountPresetTypeV1", + "description": "What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + "examples": [ + "WORKSPACE_MANAGE_ALL" + ] + }, + "model_ids": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + "examples": [ + [ + "abcd1234" + ] + ], + "title": "Model Ids" + }, + "environment_names": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + "examples": [ + [ + "production" + ] + ], + "title": "Environment Names" + }, + "model_api_slugs": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + "examples": [ + [ + "my-model-api" + ] + ], + "title": "Model Api Slugs" + } + }, + "required": [ + "type" + ], + "title": "ServiceAccountPresetPermissionsV1", + "type": "object" + }, + "ServiceAccountPresetTypeV1": { + "description": "What a service account may do: the workspace API key categories, plus Model APIs.\n\nTemporary: mirrors API key access until fine-grained access control is available, and may be removed.", + "enum": [ + "WORKSPACE_MANAGE_ALL", + "WORKSPACE_INVOKE", + "WORKSPACE_EXPORT_METRICS", + "WORKSPACE_MANAGE_API_KEYS", + "WORKSPACE_INVOKE_MODEL_APIS" + ], + "title": "ServiceAccountPresetTypeV1", + "type": "string" + }, + "ServiceAccountV1": { + "description": "A named service account that workload identity federation tokens act as.", + "properties": { + "id": { + "description": "Service account ID", + "title": "Id", + "type": "string" + }, + "name": { + "description": "Name, unique in the organization", + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description", + "title": "Description" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The team that owns the account. Null for an organization account.", + "title": "Team Id" + }, + "preset_permissions": { + "$ref": "#/components/schemas/ServiceAccountPresetPermissionsV1", + "description": "What the service account may do. Temporary; may be removed once fine-grained access control is available." + }, + "disabled": { + "description": "Whether the account is disabled. A disabled account can't be used.", + "title": "Disabled", + "type": "boolean" + }, + "last_used_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Last time a request authenticated as this account, to within an hour. Null until the first.", + "title": "Last Used At" + }, + "created_at": { + "description": "Time the account was created", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "updated_at": { + "description": "Time the account was last updated", + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "id", + "name", + "preset_permissions", + "disabled", + "created_at", + "updated_at" + ], + "title": "ServiceAccountV1", + "type": "object" + }, + "ServiceAccountsV1": { + "description": "A page of service accounts.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/ServiceAccountV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "ServiceAccountsV1", + "type": "object" + }, + "ServiceAccountsRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only the account with this name, ignoring case", + "title": "Name" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only this team's accounts", + "title": "Team Id" + }, + "disabled": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only disabled or enabled accounts", + "title": "Disabled" + } + }, + "title": "ServiceAccountsRequestV1", + "type": "object" + }, + "ServiceAccountPresetPermissionsRequestV1": { + "additionalProperties": false, + "description": "A service account's access, as sent. Omit a list for no restriction; never send it empty.", + "properties": { + "type": { + "$ref": "#/components/schemas/ServiceAccountPresetTypeV1", + "description": "What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + "examples": [ + "WORKSPACE_MANAGE_ALL" + ] + }, + "model_ids": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + "examples": [ + [ + "abcd1234" + ] + ], + "title": "Model Ids" + }, + "environment_names": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + "examples": [ + [ + "production" + ] + ], + "title": "Environment Names" + }, + "model_api_slugs": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + "examples": [ + [ + "my-model-api" + ] + ], + "title": "Model Api Slugs" + } + }, + "required": [ + "type" + ], + "title": "ServiceAccountPresetPermissionsRequestV1", + "type": "object" + }, + "CreateServiceAccountRequestV1": { + "additionalProperties": false, + "description": "Request to create a service account.", + "properties": { + "name": { + "description": "Name, unique in the organization. Can be changed later.", + "examples": [ + "ci-deployer" + ], + "maxLength": 255, + "minLength": 1, + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional description, up to 1,024 characters", + "title": "Description" + }, + "team_id": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The team that owns the account. Omit for an organization account. Can't be changed.", + "title": "Team Id" + }, + "preset_permissions": { + "$ref": "#/components/schemas/ServiceAccountPresetPermissionsRequestV1", + "description": "What the service account may do. Can be changed later. Temporary; may be removed once fine-grained access control is available." + } + }, + "required": [ + "name", + "preset_permissions" + ], + "title": "CreateServiceAccountRequestV1", + "type": "object" + }, + "DeletedServiceAccountV1": { + "properties": { + "id": { + "description": "ID of the deleted service account", + "title": "Id", + "type": "string" + }, + "deleted": { + "description": "Always true", + "title": "Deleted", + "type": "boolean" + } + }, + "required": [ + "id", + "deleted" + ], + "title": "DeletedServiceAccountV1", + "type": "object" + }, + "UpdateServiceAccountRequestV1": { + "additionalProperties": false, + "description": "Request to update a service account. Only the fields sent change.", + "properties": { + "name": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name, unique in the organization", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description, up to 1,024 characters; null clears it", + "title": "Description", + "x-null-distinct": true + }, + "disabled": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Disable the account to stop it being used, or enable it again", + "title": "Disabled" + }, + "preset_permissions": { + "anyOf": [ + { + "$ref": "#/components/schemas/ServiceAccountPresetPermissionsRequestV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Replaces the account's access as a whole. Temporary; may be removed once fine-grained access control is available." + } + }, + "title": "UpdateServiceAccountRequestV1", + "type": "object" + }, + "PredefinedIdentityProviderKindV1": { + "description": "An identity provider Baseten supports.", + "enum": [ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS" + ], + "title": "PredefinedIdentityProviderKindV1", + "type": "string" + }, + "PredefinedIdentityProviderV1": { + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Pass as `kind` when adding the provider" + }, + "name": { + "description": "Display name", + "title": "Name", + "type": "string" + }, + "issuer_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The `iss` claim its tokens carry. Null when each account, tenant, or cluster has its own issuer, which you pass as `issuer_url` when adding the provider.", + "title": "Issuer Url" + }, + "issuer_url_example": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "An example of the `issuer_url` to pass. Null when the issuer is fixed.", + "title": "Issuer Url Example" + } + }, + "required": [ + "kind", + "name" + ], + "title": "PredefinedIdentityProviderV1", + "type": "object" + }, + "PredefinedIdentityProvidersV1": { + "properties": { + "items": { + "description": "Identity providers Baseten supports", + "items": { + "$ref": "#/components/schemas/PredefinedIdentityProviderV1" + }, + "title": "Items", + "type": "array" + } + }, + "required": [ + "items" + ], + "title": "PredefinedIdentityProvidersV1", + "type": "object" + }, + "IdentityProviderV1": { + "description": "An OIDC issuer whose tokens the organization accepts for workload identity federation.", + "properties": { + "id": { + "description": "Identity provider ID", + "title": "Id", + "type": "string" + }, + "name": { + "description": "Name, unique in the organization", + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description", + "title": "Description" + }, + "predefined": { + "$ref": "#/components/schemas/PredefinedIdentityProviderConfigV1", + "description": "Settings of the predefined provider" + }, + "created_by": { + "description": "ID of the user who added the provider", + "title": "Created By", + "type": "string" + }, + "created_at": { + "description": "Time the provider was added", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "updated_at": { + "description": "Time the provider was last updated", + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "id", + "name", + "predefined", + "created_by", + "created_at", + "updated_at" + ], + "title": "IdentityProviderV1", + "type": "object" + }, + "PredefinedIdentityProviderConfigV1": { + "description": "Settings of an identity provider that Baseten defines.", + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Which predefined provider. Can't be changed." + }, + "issuer_url": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + "title": "Issuer Url" + } + }, + "required": [ + "kind" + ], + "title": "PredefinedIdentityProviderConfigV1", + "type": "object" + }, + "IdentityProvidersV1": { + "description": "A page of identity providers.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/IdentityProviderV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "IdentityProvidersV1", + "type": "object" + }, + "IdentityProvidersRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only the provider with this name, ignoring case", + "title": "Name" + }, + "predefined_kind": { + "anyOf": [ + { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only this predefined provider's issuers" + } + }, + "title": "IdentityProvidersRequestV1", + "type": "object" + }, + "CreatePredefinedIdentityProviderConfigV1": { + "additionalProperties": false, + "description": "Settings of the predefined identity provider to add.", + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Which predefined provider. Can't be changed." + }, + "issuer_url": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + "title": "Issuer Url" + } + }, + "required": [ + "kind" + ], + "title": "CreatePredefinedIdentityProviderConfigV1", + "type": "object" + }, + "CreateIdentityProviderRequestV1": { + "additionalProperties": false, + "description": "Request to add an identity provider.", + "properties": { + "name": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional description", + "title": "Description" + }, + "predefined": { + "$ref": "#/components/schemas/CreatePredefinedIdentityProviderConfigV1", + "description": "The predefined provider to add" + } + }, + "required": [ + "predefined" + ], + "title": "CreateIdentityProviderRequestV1", + "type": "object" + }, + "VerifyPredefinedIdentityProviderConfigV1": { + "additionalProperties": false, + "description": "Settings of the predefined identity provider to check.", + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Which predefined provider" + }, + "issuer_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The issuer to check, for AWS IAM, Amazon EKS, Azure managed identity, and Azure Kubernetes Service, in the format the predefined identity providers endpoint shows", + "title": "Issuer Url" + } + }, + "required": [ + "kind" + ], + "title": "VerifyPredefinedIdentityProviderConfigV1", + "type": "object" + }, + "VerifyIdentityProviderRequestV1": { + "additionalProperties": false, + "description": "Request to check an identity provider before adding it.", + "properties": { + "predefined": { + "$ref": "#/components/schemas/VerifyPredefinedIdentityProviderConfigV1", + "description": "The predefined provider to check, as you'd pass it when adding it" + } + }, + "required": [ + "predefined" + ], + "title": "VerifyIdentityProviderRequestV1", + "type": "object" + }, + "VerificationV1": { + "description": "Whether a create request would pass the checks the server runs on it.", + "properties": { + "valid": { + "description": "Whether the input passes every check", + "title": "Valid", + "type": "boolean" + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Why the input fails, as creating it would report. Null when it's valid.", + "title": "Error" + } + }, + "required": [ + "valid" + ], + "title": "VerificationV1", + "type": "object" + }, + "DeletedIdentityProviderV1": { + "properties": { + "id": { + "description": "ID of the deleted identity provider", + "title": "Id", + "type": "string" + }, + "deleted": { + "description": "Always true", + "title": "Deleted", + "type": "boolean" + } + }, + "required": [ + "id", + "deleted" + ], + "title": "DeletedIdentityProviderV1", + "type": "object" + }, + "UpdateIdentityProviderRequestV1": { + "additionalProperties": false, + "description": "Request to update an identity provider. Only the fields sent change.", + "properties": { + "name": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name, unique in the organization", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description; null clears it", + "title": "Description", + "x-null-distinct": true + } + }, + "title": "UpdateIdentityProviderRequestV1", + "type": "object" + }, + "AccessTrustRuleV1": { + "description": "Which tokens from an identity provider may act as a service account.", + "properties": { + "id": { + "description": "Trust rule ID. Workloads pass it when they exchange a token.", + "title": "Id", + "type": "string" + }, + "name": { + "description": "Name, unique in the organization", + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description", + "title": "Description" + }, + "identity_provider_id": { + "description": "The identity provider whose tokens it accepts", + "title": "Identity Provider Id", + "type": "string" + }, + "identity_provider_name": { + "description": "Name of the identity provider", + "title": "Identity Provider Name", + "type": "string" + }, + "service_account_id": { + "description": "The service account its tokens act as", + "title": "Service Account Id", + "type": "string" + }, + "service_account_name": { + "description": "Name of the service account", + "title": "Service Account Name", + "type": "string" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The service account's team. Null for an organization service account.", + "title": "Team Id" + }, + "team_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the service account's team. Null for an organization service account.", + "title": "Team Name" + }, + "condition": { + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + "examples": [ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + "title": "Condition", + "type": "string" + }, + "audience": { + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + "title": "Audience", + "type": "string" + }, + "max_access_token_lifetime_seconds": { + "description": "Longest lifetime of a token the rule issues, in seconds", + "title": "Max Access Token Lifetime Seconds", + "type": "integer" + }, + "last_used_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Last time a request authenticated with a token the rule issued, to within an hour. Null until the first.", + "title": "Last Used At" + }, + "created_by": { + "description": "ID of the user who created the rule", + "title": "Created By", + "type": "string" + }, + "created_at": { + "description": "Time the rule was created", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "updated_at": { + "description": "Time the rule was last updated", + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "id", + "name", + "identity_provider_id", + "identity_provider_name", + "service_account_id", + "service_account_name", + "condition", + "audience", + "max_access_token_lifetime_seconds", + "created_by", + "created_at", + "updated_at" + ], + "title": "AccessTrustRuleV1", + "type": "object" + }, + "AccessTrustRulesV1": { + "description": "A page of trust rules.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/AccessTrustRuleV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "AccessTrustRulesV1", + "type": "object" + }, + "AccessTrustRulesRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Dedicated model serving usage" + "description": "Only the rule with this name, ignoring case", + "title": "Name" }, - "training_usage": { + "identity_provider_id": { "anyOf": [ { - "$ref": "#/components/schemas/TrainingUsageV1" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Training usage" + "description": "Only this provider's rules", + "title": "Identity Provider Id" }, - "model_apis_usage": { + "service_account_id": { "anyOf": [ { - "$ref": "#/components/schemas/ModelApisUsageV1" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Model APIs usage" + "description": "Only rules for this service account", + "title": "Service Account Id" }, - "loops_usage": { + "team_id": { "anyOf": [ { - "$ref": "#/components/schemas/LoopsUsageV1" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Serverless Loops usage, billed per token. Loops usage on dedicated trainers and samplers is billed by the minute and is part of training usage." + "description": "Only rules for this team's service accounts", + "title": "Team Id" } }, - "title": "UsageSummaryV1", + "title": "AccessTrustRulesRequestV1", "type": "object" }, - "UsageSummaryRequestV1": { + "CreateAccessTrustRuleRequestV1": { + "additionalProperties": false, + "description": "Request to create a trust rule.", "properties": { - "start_date": { - "description": "Inclusive start date (ISO 8601, normalized to midnight UTC). Earliest queryable: 2026-01-01.", - "format": "date-time", - "title": "Start Date", + "name": { + "description": "Name, unique in the organization. Can be changed later.", + "maxLength": 255, + "minLength": 1, + "title": "Name", "type": "string" }, - "end_date": { - "description": "Exclusive end date (ISO 8601, normalized to midnight UTC). Date range cannot exceed 31 days.", - "format": "date-time", - "title": "End Date", + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional description", + "title": "Description" + }, + "identity_provider_id": { + "description": "Whose tokens the rule accepts. Can't be changed.", + "title": "Identity Provider Id", + "type": "string" + }, + "service_account_id": { + "description": "The service account its tokens act as. Can be changed later.", + "title": "Service Account Id", + "type": "string" + }, + "condition": { + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters. Can be changed later.", + "examples": [ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + "title": "Condition", + "type": "string" + }, + "audience": { + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters. Can be changed later.", + "title": "Audience", "type": "string" + }, + "max_access_token_lifetime_seconds": { + "default": 3600, + "description": "Longest lifetime of a token the rule issues, 60 to 3600 seconds. Can be changed later.", + "maximum": 3600, + "minimum": 60, + "title": "Max Access Token Lifetime Seconds", + "type": "integer" } }, "required": [ - "start_date", - "end_date" + "name", + "identity_provider_id", + "service_account_id", + "condition", + "audience" ], - "title": "UsageSummaryRequestV1", + "title": "CreateAccessTrustRuleRequestV1", "type": "object" }, - "ToolCallUsageBucketV1": { - "description": "Server-side tool call usage for one day, provider, charge unit, and model.", + "VerifyAccessTrustRuleRequestV1": { + "additionalProperties": false, + "description": "Request to check a trust rule's condition and audience before saving them.", "properties": { - "date": { - "description": "UTC day the usage was recorded on.", - "format": "date", - "title": "Date", - "type": "string" - }, - "provider": { - "description": "Tool provider, such as exa or parallel.", - "title": "Provider", + "identity_provider_id": { + "description": "The identity provider the rule is for, which decides the claims it must pin", + "title": "Identity Provider Id", "type": "string" }, - "sku": { - "description": "Charge unit, as `/`. The unit is what the provider reported, or the tool name when it reported none. Its meaning varies by provider.", - "title": "Sku", + "condition": { + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + "examples": [ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + "title": "Condition", "type": "string" }, - "model": { - "description": "Model that made the tool calls.", - "title": "Model", + "audience": { + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + "title": "Audience", "type": "string" - }, - "calls": { - "description": "Number of tool calls.", - "title": "Calls", - "type": "integer" - }, - "quantity": { - "description": "Billable quantity in the provider's sku unit, summed over the calls.", - "title": "Quantity", - "type": "number" - }, - "team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Team attributed to the usage. Null when not grouping by team or when historical team attribution is unavailable.", - "title": "Team Id" } }, "required": [ - "date", - "provider", - "sku", - "model", - "calls", - "quantity" + "identity_provider_id", + "condition", + "audience" ], - "title": "ToolCallUsageBucketV1", + "title": "VerifyAccessTrustRuleRequestV1", "type": "object" }, - "ToolCallUsageResponseV1": { - "description": "Daily server-side tool call usage, ordered by day, provider, sku, and model.", + "DeletedAccessTrustRuleV1": { "properties": { - "items": { - "items": { - "$ref": "#/components/schemas/ToolCallUsageBucketV1" - }, - "title": "Items", - "type": "array" + "id": { + "description": "ID of the deleted trust rule", + "title": "Id", + "type": "string" + }, + "deleted": { + "description": "Always true", + "title": "Deleted", + "type": "boolean" } }, - "title": "ToolCallUsageResponseV1", - "type": "object" - }, - "ToolCallUsageDimensionV1": { - "enum": [ - "TEAM" + "required": [ + "id", + "deleted" ], - "title": "ToolCallUsageDimensionV1", - "type": "string" + "title": "DeletedAccessTrustRuleV1", + "type": "object" }, - "ToolCallUsageRequestV1": { + "UpdateAccessTrustRuleRequestV1": { + "additionalProperties": false, + "description": "Request to update a trust rule. Only the fields sent change.", "properties": { - "start_date": { - "description": "Inclusive UTC calendar day at the start of the query range.", - "format": "date", - "title": "Start Date", - "type": "string" - }, - "end_date": { + "name": { "anyOf": [ { - "format": "date", + "maxLength": 255, + "minLength": 1, "type": "string" }, { @@ -37560,41 +41444,10 @@ } ], "default": null, - "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included. The date range cannot exceed 90 days.", - "title": "End Date" - }, - "team_ids": { - "description": "Return only usage for these teams, repeated once per team. Defaults to all teams you can manage. An unauthorized team ID causes a 403 response.", - "items": { - "type": "string" - }, - "title": "Team Ids", - "type": "array" - }, - "group_by": { - "description": "Pass TEAM to split daily rows by team. Defaults to aggregating across teams.", - "items": { - "$ref": "#/components/schemas/ToolCallUsageDimensionV1" - }, - "title": "Group By", - "type": "array" - } - }, - "required": [ - "start_date" - ], - "title": "ToolCallUsageRequestV1", - "type": "object" - }, - "UserInfoV1": { - "description": "A Baseten user.", - "properties": { - "user_id": { - "description": "Unique identifier for the user", - "title": "User Id", - "type": "string" + "description": "Name, unique in the organization", + "title": "Name" }, - "email": { + "description": { "anyOf": [ { "type": "string" @@ -37604,10 +41457,11 @@ } ], "default": null, - "description": "Email address of the user", - "title": "Email" + "description": "Description; null clears it", + "title": "Description", + "x-null-distinct": true }, - "name": { + "condition": { "anyOf": [ { "type": "string" @@ -37617,10 +41471,10 @@ } ], "default": null, - "description": "Display name of the user", - "title": "Name" + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + "title": "Condition" }, - "workspace_name": { + "audience": { "anyOf": [ { "type": "string" @@ -37630,64 +41484,25 @@ } ], "default": null, - "description": "Name of the user's workspace", - "title": "Workspace Name" - } - }, - "required": [ - "user_id" - ], - "title": "UserInfoV1", - "type": "object" - }, - "UsersResponseV1": { - "description": "A page of users in the caller's workspace.", - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/UserInfoV1" - }, - "title": "Items", - "type": "array" + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + "title": "Audience" }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "UsersResponseV1", - "type": "object" - }, - "UsersRequestV1": { - "description": "Request parameters for listing users.", - "properties": { - "cursor": { + "max_access_token_lifetime_seconds": { "anyOf": [ { - "type": "string" + "maximum": 3600, + "minimum": 60, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" + "description": "Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", + "title": "Max Access Token Lifetime Seconds" }, - "email": { + "service_account_id": { "anyOf": [ { "type": "string" @@ -37697,43 +41512,51 @@ } ], "default": null, - "description": "When set, returns only users with this exact email, if any.", - "title": "Email" + "description": "Moves the rule to another service account. Tokens already issued keep the old account until they expire.", + "title": "Service Account Id" } }, - "title": "UsersRequestV1", + "title": "UpdateAccessTrustRuleRequestV1", "type": "object" }, - "AwsAssumeRoleV1": { - "description": "AWS AssumeRole trust-policy inputs for the organization.", + "TokenExchangeRequestV1": { + "description": "An RFC 8693 token exchange request naming the trust rule to check as its audience.", "properties": { - "baseten_role_arn": { - "description": "Baseten role ARN to allow in an IAM role's trust policy", - "title": "Baseten Role Arn", + "grant_type": { + "description": "Always `urn:ietf:params:oauth:grant-type:token-exchange`", + "examples": [ + "urn:ietf:params:oauth:grant-type:token-exchange" + ], + "title": "Grant Type", "type": "string" }, - "external_id": { - "description": "sts:ExternalId Baseten presents when assuming the role", - "title": "External Id", + "subject_token": { + "description": "The identity provider's JWT", + "examples": [ + "" + ], + "maxLength": 16384, + "title": "Subject Token", "type": "string" - } - }, - "required": [ - "baseten_role_arn", - "external_id" - ], - "title": "AwsAssumeRoleV1", - "type": "object" - }, - "OrganizationInfoV1": { - "description": "The caller's organization.", - "properties": { - "org_id": { - "description": "Unique identifier for the organization", - "title": "Org Id", + }, + "subject_token_type": { + "description": "`urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`", + "examples": [ + "urn:ietf:params:oauth:token-type:jwt" + ], + "title": "Subject Token Type", "type": "string" }, - "name": { + "audience": { + "description": "ID of the trust rule to check the JWT against", + "examples": [ + "abcd1234" + ], + "maxLength": 64, + "title": "Audience", + "type": "string" + }, + "requested_token_type": { "anyOf": [ { "type": "string" @@ -37743,33 +41566,63 @@ } ], "default": null, - "description": "Display name of the organization", - "title": "Name" - }, - "created_at": { - "description": "Time the organization was created in ISO 8601 format", - "format": "date-time", - "title": "Created At", - "type": "string" + "description": "Optional; only `urn:ietf:params:oauth:token-type:access_token` is issued", + "title": "Requested Token Type" }, - "aws_assume_role": { + "access_token_lifetime_seconds": { "anyOf": [ { - "$ref": "#/components/schemas/AwsAssumeRoleV1" + "minimum": 1, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" + "description": "Lifetime of the access token, in seconds. At most the rule's maximum.", + "title": "Access Token Lifetime Seconds" } }, "required": [ - "org_id", - "created_at" + "grant_type", + "subject_token", + "subject_token_type", + "audience" ], - "title": "OrganizationInfoV1", + "title": "TokenExchangeRequestV1", + "type": "object" + }, + "TokenExchangeResponseV1": { + "properties": { + "access_token": { + "description": "Send as `Authorization: Bearer`", + "title": "Access Token", + "type": "string" + }, + "issued_token_type": { + "description": "Always `urn:ietf:params:oauth:token-type:access_token`", + "title": "Issued Token Type", + "type": "string" + }, + "token_type": { + "description": "Always `Bearer`", + "title": "Token Type", + "type": "string" + }, + "expires_in": { + "description": "Seconds until the access token expires", + "title": "Expires In", + "type": "integer" + } + }, + "required": [ + "access_token", + "issued_token_type", + "token_type", + "expires_in" + ], + "title": "TokenExchangeResponseV1", "type": "object" }, "GatewayEventTokensV1": { @@ -38403,30 +42256,31 @@ "title": "GridTokenV1", "type": "object" }, - "GridClassifierV1": { + "GridRouteAliasKindV1": { + "enum": [ + "CLAUDE_DESKTOP", + "ALIAS" + ], + "title": "GridRouteAliasKindV1", + "type": "string" + }, + "GridRouteAliasV1": { "properties": { - "id": { - "description": "Stable classifier identifier.", - "examples": [ - "general-v1" - ], - "title": "Id", - "type": "string" - }, "name": { - "description": "Display name of the classifier.", - "examples": [ - "General" - ], + "description": "Name to send in the inference request's `model` field instead of the route's `name`.", "title": "Name", "type": "string" + }, + "kind": { + "$ref": "#/components/schemas/GridRouteAliasKindV1", + "description": "Purpose of the alias. CLAUDE_DESKTOP is for Claude Code desktop, which rejects model names without a `claude` substring. ALIAS is any other name the team's clients send for the route." } }, "required": [ - "id", - "name" + "name", + "kind" ], - "title": "GridClassifierV1", + "title": "GridRouteAliasV1", "type": "object" }, "GridRouteClassifierV1": { @@ -38434,17 +42288,17 @@ "id": { "description": "Stable route classifier identifier.", "examples": [ - "general-v1" + "abc1234" ], "title": "Id", "type": "string" }, - "name": { + "display_name": { "description": "Display name of the route classifier.", "examples": [ "General" ], - "title": "Name", + "title": "Display Name", "type": "string" }, "supported_tradeoffs": { @@ -38461,8 +42315,8 @@ "title": "Supported Tradeoffs", "type": "array" }, - "decidable_models": { - "description": "Model identities the route classifier picks from.", + "decidable_canonical_model_ids": { + "description": "Canonical model ids the route classifier picks from.", "examples": [ [ "zai-org/GLM-5.3", @@ -38472,37 +42326,195 @@ "items": { "type": "string" }, - "title": "Decidable Models", + "title": "Decidable Canonical Model Ids", "type": "array" } }, "required": [ "id", - "name", + "display_name", "supported_tradeoffs", - "decidable_models" + "decidable_canonical_model_ids" ], "title": "GridRouteClassifierV1", "type": "object" }, - "GridRouteRefV1": { + "GridRouteMetadataV1": { "properties": { - "id": { - "description": "Stable route identifier.", - "title": "Id", - "type": "string" - }, "slug": { - "description": "Name of the route to send in the inference request's model field.", - "title": "Slug", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Metadata slug, e.g. 'anthropic/claude-opus-4'; null for rows without one.", + "title": "Slug" + }, + "display_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Model display name, when available.", + "title": "Display Name" + }, + "release_date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Model release date. Month-only source dates use the first day of that month.", + "title": "Release Date" + }, + "provider": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Provider key derived from the slug prefix, e.g. 'anthropic'; null for unprefixed slugs.", + "title": "Provider" + }, + "context_window": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Total context window in tokens.", + "title": "Context Window" + }, + "max_output_tokens": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Maximum output tokens per response.", + "title": "Max Output Tokens" + }, + "input_modalities": { + "description": "Accepted input modalities.", + "items": { + "type": "string" + }, + "title": "Input Modalities", + "type": "array" + }, + "tools": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "Whether the model supports tool calling.", + "title": "Tools" + }, + "reasoning_effort_levels": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "description": "Reasoning effort levels the model supports.", + "title": "Reasoning Effort Levels" + }, + "parallel_tool_calls": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "Whether the model supports parallel tool calls.", + "title": "Parallel Tool Calls" + }, + "supported_api_formats": { + "anyOf": [ + { + "$ref": "#/components/schemas/ExploreMetadataAPIFormatsV1" + }, + { + "type": "null" + } + ], + "description": "API formats the model supports." + }, + "cost": { + "anyOf": [ + { + "$ref": "#/components/schemas/ExploreCostV1" + }, + { + "type": "null" + } + ], + "description": "Provider list prices in USD per 1M tokens, when available." + }, + "api_formats": { + "description": "API formats the route supports, most preferred first: `chat_completions`, `messages`, `responses` for a BASETEN_MODEL_API target and `messages`, `responses`, `chat_completions` for any other target, keeping only the formats the route supports. Never empty.", + "items": { + "enum": [ + "messages", + "responses", + "chat_completions" + ], + "title": "GridRouteAPIFormatV1", + "type": "string" + }, + "minItems": 1, + "title": "Api Formats", + "type": "array" } }, "required": [ - "id", - "slug" + "slug", + "display_name", + "release_date", + "provider", + "context_window", + "max_output_tokens", + "input_modalities", + "tools", + "reasoning_effort_levels", + "parallel_tool_calls", + "supported_api_formats", + "cost", + "api_formats" ], - "title": "GridRouteRefV1", + "title": "GridRouteMetadataV1", "type": "object" }, "GridRouteTargetBasetenModelAPIV1": { @@ -38527,47 +42539,6 @@ "title": "GridRouteTargetBasetenModelAPIV1", "type": "object" }, - "GridRouteTargetClassifierV1": { - "properties": { - "type": { - "const": "CLASSIFIER", - "description": "Target kind for a classifier-based route.", - "title": "Type", - "type": "string" - }, - "classifier": { - "anyOf": [ - { - "$ref": "#/components/schemas/GridClassifierV1" - }, - { - "type": "null" - } - ], - "description": "Classifier that picks a route for each request. Null for routers created before classifiers could be selected." - }, - "default_route": { - "$ref": "#/components/schemas/GridRouteRefV1", - "description": "Route used when the classifier picks none." - }, - "allowed_routes": { - "description": "Routes the classifier may pick, in creation order.", - "items": { - "$ref": "#/components/schemas/GridRouteRefV1" - }, - "title": "Allowed Routes", - "type": "array" - } - }, - "required": [ - "type", - "classifier", - "default_route", - "allowed_routes" - ], - "title": "GridRouteTargetClassifierV1", - "type": "object" - }, "GridRouteTargetConnectionV1": { "properties": { "type": { @@ -38635,10 +42606,23 @@ "type": "string" }, "name": { - "description": "Name to send in the inference request's model field.", + "description": "Name to send in the inference request's `model` field. Unique within the team; immutable.", "title": "Name", "type": "string" }, + "display_name": { + "description": "Display label, defaulting to the route's name.", + "title": "Display Name", + "type": "string" + }, + "aliases": { + "description": "The route's other names, one per purpose. Empty for routes created before aliases existed.", + "items": { + "$ref": "#/components/schemas/GridRouteAliasV1" + }, + "title": "Aliases", + "type": "array" + }, "team_id": { "description": "Identifier of the owning team.", "title": "Team Id", @@ -38649,11 +42633,6 @@ "title": "Team Name", "type": "string" }, - "display_name": { - "description": "Display label, defaulting to the route name.", - "title": "Display Name", - "type": "string" - }, "description": { "description": "Short description of the route, empty when unset.", "title": "Description", @@ -38664,7 +42643,6 @@ "discriminator": { "mapping": { "BASETEN_MODEL_API": "#/components/schemas/GridRouteTargetBasetenModelAPIV1", - "CLASSIFIER": "#/components/schemas/GridRouteTargetClassifierV1", "CONNECTION": "#/components/schemas/GridRouteTargetConnectionV1", "INTELLIGENT": "#/components/schemas/GridRouteTargetIntelligentV1" }, @@ -38677,9 +42655,6 @@ { "$ref": "#/components/schemas/GridRouteTargetConnectionV1" }, - { - "$ref": "#/components/schemas/GridRouteTargetClassifierV1" - }, { "$ref": "#/components/schemas/GridRouteTargetIntelligentV1" } @@ -38689,13 +42664,13 @@ "metadata": { "anyOf": [ { - "$ref": "#/components/schemas/ExploreMetadataV1" + "$ref": "#/components/schemas/GridRouteMetadataV1" }, { "type": "null" } ], - "description": "Resolved model metadata; for a router, the envelope of its allowed routes' metadata. Null when nothing is linked." + "description": "Resolved model metadata; for an intelligent route, the envelope of its servable models' metadata. Null when nothing is linked or the metadata has no supported API formats." }, "invoke_url": { "description": "Base URL for inference requests using this route.", @@ -38712,9 +42687,9 @@ "required": [ "id", "name", + "display_name", "team_id", "team_name", - "display_name", "description", "target", "metadata", @@ -38798,7 +42773,7 @@ } ], "default": null, - "description": "Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", "title": "Name" } }, @@ -38828,87 +42803,74 @@ "title": "UpsertGridRouteTargetBasetenModelAPIV1", "type": "object" }, - "UpsertGridRouteTargetClassifierV1": { + "UpsertGridRouteTargetConnectionV1": { "additionalProperties": false, "properties": { "type": { - "const": "CLASSIFIER", - "description": "Target kind for a classifier-based route.", + "const": "CONNECTION", + "description": "Target kind for a provider reached through a team connection.", "title": "Type", "type": "string" }, - "classifier_id": { - "description": "ID of the classifier that picks a route for each request.", - "examples": [ - "general-v1" - ], + "model": { + "description": "Model name sent to the provider.", "minLength": 1, - "title": "Classifier Id", + "title": "Model", "type": "string" }, - "allowed_route_ids": { - "description": "IDs of the routes the classifier may pick. All must belong to the route's team and must not be routers themselves.", - "examples": [ - [ - "abc1234", - "def5678" - ] - ], - "items": { - "type": "string" - }, - "title": "Allowed Route Ids", - "type": "array" - }, - "default_route_id": { - "description": "ID of the allowed route used when the classifier picks none.", + "connection_id": { + "description": "Identifier of a connection owned by the route's team. Its provider serves the route.", "examples": [ "abc1234" ], - "title": "Default Route Id", + "minLength": 1, + "title": "Connection Id", "type": "string" } }, "required": [ "type", - "classifier_id", - "allowed_route_ids", - "default_route_id" + "model", + "connection_id" ], - "title": "UpsertGridRouteTargetClassifierV1", + "title": "UpsertGridRouteTargetConnectionV1", "type": "object" }, - "UpsertGridRouteTargetConnectionV1": { + "UpsertGridRouteTargetIntelligentV1": { "additionalProperties": false, "properties": { "type": { - "const": "CONNECTION", - "description": "Target kind for a provider reached through a team connection.", + "const": "INTELLIGENT", + "description": "Target kind for an intelligent route: Baseten picks the model per request.", "title": "Type", "type": "string" }, - "model": { - "description": "Model name sent to the provider.", - "minLength": 1, - "title": "Model", - "type": "string" - }, - "connection_id": { - "description": "Identifier of a connection owned by the route's team. Its provider serves the route.", + "route_classifier_id": { + "description": "Identifier of the route classifier that picks the model. List them with GET /v1/grid/route_classifiers.", "examples": [ "abc1234" ], "minLength": 1, - "title": "Connection Id", + "title": "Route Classifier Id", + "type": "string" + }, + "tradeoff": { + "description": "How the classifier weighs cost against quality. Must be one of the classifier's supported tradeoffs.", + "enum": [ + "cost", + "balanced", + "intelligence" + ], + "title": "GridRouteTradeoffV1", "type": "string" } }, "required": [ "type", - "model", - "connection_id" + "route_classifier_id", + "tradeoff" ], - "title": "UpsertGridRouteTargetConnectionV1", + "title": "UpsertGridRouteTargetIntelligentV1", "type": "object" }, "CreateGridRouteRequestV1": { @@ -38943,19 +42905,19 @@ } ], "default": null, - "description": "Display label. Omit to use the route name; null is not accepted.", + "description": "Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", "examples": [ "Assistant" ], "title": "Display Name" }, "target": { - "description": "Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team.", + "description": "Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team. INTELLIGENT targets need at least one of the route classifier's models, and one of its fallback models, servable by the team.", "discriminator": { "mapping": { "BASETEN_MODEL_API": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1", - "CLASSIFIER": "#/components/schemas/UpsertGridRouteTargetClassifierV1", - "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1" + "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1", + "INTELLIGENT": "#/components/schemas/UpsertGridRouteTargetIntelligentV1" }, "propertyName": "type" }, @@ -38973,7 +42935,7 @@ "$ref": "#/components/schemas/UpsertGridRouteTargetConnectionV1" }, { - "$ref": "#/components/schemas/UpsertGridRouteTargetClassifierV1" + "$ref": "#/components/schemas/UpsertGridRouteTargetIntelligentV1" } ], "title": "Target" @@ -39011,7 +42973,8 @@ "XAI", "VERTEX", "OPENAI_COMPATIBLE", - "BEDROCK" + "BEDROCK", + "AZURE" ], "title": "GridProviderV1", "type": "string" @@ -39116,7 +43079,7 @@ "default": null, "description": "Provider that served the requests. Null when not grouping by PROVIDER." }, - "intelligent_route": { + "intelligent_route_id": { "anyOf": [ { "type": "string" @@ -39126,8 +43089,21 @@ } ], "default": null, - "description": "Name of the intelligent route, as in `GET /v1/grid/routes`. Null when not grouping by INTELLIGENT_ROUTE.", - "title": "Intelligent Route" + "description": "ID of the intelligent route, as `id` in GET /v1/grid/routes. Null when not grouping by INTELLIGENT_ROUTE.", + "title": "Intelligent Route Id" + }, + "intelligent_route_display_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the intelligent route. Null when `intelligent_route_id` is null or the route cannot be resolved.", + "title": "Intelligent Route Display Name" }, "harness": { "anyOf": [ @@ -39141,6 +43117,32 @@ "default": null, "description": "Coding harness. Null when not grouping by HARNESS, when no harness was recorded (including usage from before harness tracking), or when the recorded harness is not recognized by this API version." }, + "api_key_prefix": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Prefix of the API key that made the requests, matching `GET /v1/api_keys`. Null when not grouping by API_KEY, for usage without an API key, and for usage recorded before API key tracking.", + "title": "Api Key Prefix" + }, + "api_key_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the API key. Null when `api_key_prefix` is null or the key has no name.", + "title": "Api Key Name" + }, "cost_usd": { "description": "Estimated cost in USD, returned as an exact decimal string. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges.", "examples": [ @@ -39215,7 +43217,8 @@ "MODEL", "PROVIDER", "INTELLIGENT_ROUTE", - "HARNESS" + "HARNESS", + "API_KEY" ], "title": "GridRouteUsageDimensionV1", "type": "string" @@ -39285,7 +43288,7 @@ "title": "End Date" }, "group_by": { - "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", + "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", "items": { "$ref": "#/components/schemas/GridRouteUsageDimensionV1" }, @@ -39323,6 +43326,14 @@ }, "title": "Harnesses", "type": "array" + }, + "api_key_prefixes": { + "description": "Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", + "items": { + "type": "string" + }, + "title": "Api Key Prefixes", + "type": "array" } }, "title": "GridRouteUsageRequestV1", @@ -39386,37 +43397,6 @@ "Assistant" ], "title": "Display Name" - }, - "target": { - "anyOf": [ - { - "discriminator": { - "mapping": { - "BASETEN_MODEL_API": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1", - "CLASSIFIER": "#/components/schemas/UpsertGridRouteTargetClassifierV1", - "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1" - }, - "propertyName": "type" - }, - "oneOf": [ - { - "$ref": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1" - }, - { - "$ref": "#/components/schemas/UpsertGridRouteTargetConnectionV1" - }, - { - "$ref": "#/components/schemas/UpsertGridRouteTargetClassifierV1" - } - ] - }, - { - "type": "null" - } - ], - "description": "Complete new target configuration. Omit to keep the current configuration; null is not accepted. Only the CLASSIFIER configuration of a router route is mutable.", - "title": "Target", - "x-null-distinct": true } }, "title": "UpdateGridRouteRequestV1", @@ -40240,6 +44220,39 @@ "title": "GridConnectionConfigAnthropicV1", "type": "object" }, + "GridConnectionConfigAzureV1": { + "properties": { + "provider": { + "const": "AZURE", + "description": "Provider kind for Microsoft Azure.", + "title": "Provider", + "type": "string" + }, + "secret_id": { + "description": "Identifier of the team secret holding the provider API key.", + "title": "Secret Id", + "type": "string" + }, + "secret_name": { + "description": "Name of the team secret holding the provider API key.", + "title": "Secret Name", + "type": "string" + }, + "resource_name": { + "description": "Name of the Azure AI Foundry or Azure OpenAI resource.", + "title": "Resource Name", + "type": "string" + } + }, + "required": [ + "provider", + "secret_id", + "secret_name", + "resource_name" + ], + "title": "GridConnectionConfigAzureV1", + "type": "object" + }, "GridConnectionConfigBedrockV1": { "properties": { "provider": { @@ -40408,6 +44421,7 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/GridConnectionConfigAnthropicV1", + "AZURE": "#/components/schemas/GridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/GridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/GridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/GridConnectionConfigVertexV1", @@ -40430,6 +44444,9 @@ }, { "$ref": "#/components/schemas/GridConnectionConfigBedrockV1" + }, + { + "$ref": "#/components/schemas/GridConnectionConfigAzureV1" } ], "title": "Config" @@ -40578,6 +44595,42 @@ "title": "UpsertGridConnectionConfigAnthropicV1", "type": "object" }, + "UpsertGridConnectionConfigAzureV1": { + "additionalProperties": false, + "properties": { + "provider": { + "const": "AZURE", + "description": "Provider kind for Microsoft Azure. Route targets name a deployment, which must be named after its Azure model. Claude models (`claude-*`) use the Anthropic Messages API, and other models use the OpenAI-compatible APIs.", + "title": "Provider", + "type": "string" + }, + "secret_name": { + "description": "Name of an existing secret, owned by the same team, that holds the provider API key.", + "examples": [ + "anthropic-key" + ], + "minLength": 1, + "title": "Secret Name", + "type": "string" + }, + "resource_name": { + "description": "Name of the Azure AI Foundry or Azure OpenAI resource, the subdomain of `.openai.azure.com`.", + "examples": [ + "my-foundry-resource" + ], + "minLength": 1, + "title": "Resource Name", + "type": "string" + } + }, + "required": [ + "provider", + "secret_name", + "resource_name" + ], + "title": "UpsertGridConnectionConfigAzureV1", + "type": "object" + }, "UpsertGridConnectionConfigBedrockV1": { "additionalProperties": false, "properties": { @@ -40757,6 +44810,7 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/UpsertGridConnectionConfigAnthropicV1", + "AZURE": "#/components/schemas/UpsertGridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/UpsertGridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/UpsertGridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/UpsertGridConnectionConfigVertexV1", @@ -40785,6 +44839,9 @@ }, { "$ref": "#/components/schemas/UpsertGridConnectionConfigBedrockV1" + }, + { + "$ref": "#/components/schemas/UpsertGridConnectionConfigAzureV1" } ], "title": "Config" @@ -40818,6 +44875,7 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/UpsertGridConnectionConfigAnthropicV1", + "AZURE": "#/components/schemas/UpsertGridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/UpsertGridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/UpsertGridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/UpsertGridConnectionConfigVertexV1", @@ -40846,6 +44904,9 @@ }, { "$ref": "#/components/schemas/UpsertGridConnectionConfigBedrockV1" + }, + { + "$ref": "#/components/schemas/UpsertGridConnectionConfigAzureV1" } ], "title": "Config" @@ -40857,55 +44918,6 @@ "title": "UpdateGridConnectionRequestV1", "type": "object" }, - "GridClassifiersResponseV1": { - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/GridClassifierV1" - }, - "title": "Items", - "type": "array" - }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "GridClassifiersResponseV1", - "type": "object" - }, - "GridClassifiersRequestV1": { - "properties": { - "cursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - } - }, - "title": "GridClassifiersRequestV1", - "type": "object" - }, "GridRouteClassifiersResponseV1": { "properties": { "items": { @@ -44919,27 +48931,43 @@ "in": "path", "required": true }, - "route_id": { + "service_account_id": { "schema": { "type": "string" }, - "name": "route_id", + "name": "service_account_id", "in": "path", "required": true }, - "connection_id": { + "identity_provider_id": { "schema": { "type": "string" }, - "name": "connection_id", + "name": "identity_provider_id", "in": "path", "required": true }, - "classifier_id": { + "trust_rule_id": { "schema": { "type": "string" }, - "name": "classifier_id", + "name": "trust_rule_id", + "in": "path", + "required": true + }, + "route_id": { + "schema": { + "type": "string" + }, + "name": "route_id", + "in": "path", + "required": true + }, + "connection_id": { + "schema": { + "type": "string" + }, + "name": "connection_id", "in": "path", "required": true }, From 0713562b5272d1eb68f136ae0dafb43af94d6bdf Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Thu, 19 Nov 2026 15:51:53 -0500 Subject: [PATCH 07/14] Regenerate the API clients from the production spec Co-Authored-By: Claude Opus 5.5 --- baseten/client/managementapi/__init__.py | 170 +- baseten/client/managementapi/_client.py | 1136 +++- baseten/client/managementapi/_models.py | 2392 ++++++++- baseten/client/modelconfig/__init__.py | 4 + baseten/client/modelconfig/_models.py | 54 +- scripts/apigen/specs/config.schema.json | 124 +- scripts/apigen/specs/management.json | 6264 ++++++++++++++++++---- 7 files changed, 8622 insertions(+), 1522 deletions(-) diff --git a/baseten/client/managementapi/__init__.py b/baseten/client/managementapi/__init__.py index bfadfa4..02d5265 100644 --- a/baseten/client/managementapi/__init__.py +++ b/baseten/client/managementapi/__init__.py @@ -12,6 +12,9 @@ from ._client import ApiClient, AsyncApiClient, ResponseError from ._models import ( + AccessTokenLifetimeSeconds, + AccessTrustRule, + AccessTrustRules, ActivateResponse, ActiveJobAtSubmit, APIKey, @@ -19,6 +22,7 @@ APIKeyOwner, APIKeys, APIKeyTombstone, + AuditFieldChange, AuditLogActor, AuditLogEntry, AuditLogEventApiKeyCreated, @@ -51,6 +55,9 @@ AuditLogEventGridMachineUserCreated, AuditLogEventGridMachineUserDeleted, AuditLogEventGridMachineUserUpdated, + AuditLogEventIdentityProviderCreated, + AuditLogEventIdentityProviderDeleted, + AuditLogEventIdentityProviderUpdated, AuditLogEventModelDeleted, AuditLogEventModelDeployed, AuditLogEventModelDeploymentActivated, @@ -63,6 +70,8 @@ AuditLogEventModelDeploymentRetried, AuditLogEventModelPromotionControlAction, AuditLogEventModelRenamed, + AuditLogEventOrganizationApiKeySettingsUpdated, + AuditLogEventPredefinedIdentityProviderConfig, AuditLogEventPromotionSettingsOverride, AuditLogEventProviderConnectionCreated, AuditLogEventProviderConnectionDeleted, @@ -72,10 +81,17 @@ AuditLogEventRequireGroupBasedAdminsEnabled, AuditLogEventSecretDeleted, AuditLogEventSecretUpdated, + AuditLogEventServiceAccountCreated, + AuditLogEventServiceAccountDeleted, + AuditLogEventServiceAccountPresetPermissions, + AuditLogEventServiceAccountUpdated, AuditLogEventSshCertificateSigned, AuditLogEventTelemetryExportCreated, AuditLogEventTelemetryExportDeleted, AuditLogEventTelemetryExportUpdated, + AuditLogEventTrustRuleCreated, + AuditLogEventTrustRuleDeleted, + AuditLogEventTrustRuleUpdated, AuditLogEventUserInvited, AuditLogEventUserJoinedOrganization, AuditLogEventUserRemoved, @@ -135,6 +151,7 @@ CostPerMillionInputTokens1, CostPerMillionOutputTokens, CostPerMillionOutputTokens1, + CreateAccessTrustRuleRequest, CreateApiKeyForGroupRequest, CreateApiKeyForGroupResponse, CreateAPIKeyRequest, @@ -152,6 +169,7 @@ CreateGridTokenRequest, CreateGroupHierarchy, CreateGroupRequest, + CreateIdentityProviderRequest, CreateJobWeightConfig, CreateLibraryListingRequest, CreateLibraryListingVersionRequest, @@ -165,6 +183,7 @@ CreateLoopsTrainerRequest, CreateModelDeploymentRequest, CreateModelRequest, + CreatePredefinedIdentityProviderConfig, CreateSandboxParams, CreateSandboxPreviewParams, CreateSandboxPreviewRequest, @@ -173,6 +192,7 @@ CreateSandboxRequest, CreateSandboxVolumeParams, CreateSandboxVolumeRequest, + CreateServiceAccountRequest, CreateTokenRequest, CreateTrainingJob, CreateTrainingJobAccelerator, @@ -198,8 +218,12 @@ DeactivateResponse, DedicatedItem, DedicatedUsage, + DeletedAccessTrustRule, + DeletedIdentityProvider, + DeletedServiceAccount, DeleteImageParams, DeleteImageTagParams, + DeleteLoopsRunResponse, DeleteSandboxParams, DeleteSandboxPreviewParams, DeleteSandboxPreviewTokenParams, @@ -224,10 +248,16 @@ DeploymentPatchOpPythonRequirement, DeploymentPatchPoint, DeploymentPatchPointWithHash, + DeploymentReplica, + DeploymentReplicas, Deployments, DeploymentTombstone, Description, Description1, + Description2, + Description3, + Description4, + Description5, DisplayName, DisplayName1, DockerAuth, @@ -271,6 +301,8 @@ GatewayKeyInfo, GcpOidcDockerAuth, GcpServiceAccountJsonDockerAuth, + GetAccessIdentityProvidersParams, + GetAccessTrustRulesParams, GetApiKeysParams, GetAuditLogsParams, GetAuthCodesResponse, @@ -285,7 +317,6 @@ GetDeploymentPatchesStateResponse, GetExploreMetadataParams, GetGatewayEventsParams, - GetGridClassifiersParams, GetGridConnectionsParams, GetGridMachineUsersParams, GetGridRouteClassifiersParams, @@ -323,10 +354,12 @@ GetModelsDeploymentsLogsParams, GetModelsDeploymentsMetricsParams, GetModelsDeploymentsParams, + GetModelsDeploymentsReplicasParams, GetModelsDeploymentsStartupsParams, GetModelsDeploymentsStartupsSummaryParams, GetModelsEnvironmentsLogsParams, GetModelsEnvironmentsMetricsParams, + GetModelsEnvironmentsReplicasParams, GetModelsEnvironmentsStartupsParams, GetModelsEnvironmentsStartupsSummaryParams, GetModelsParams, @@ -336,6 +369,7 @@ GetSandboxParams, GetSandboxPreviewParams, GetSandboxVolumeParams, + GetServiceAccountsParams, GetTeamsLoopsRunsParams, GetTeamsLoopsSamplersParams, GetTeamsModelsParams, @@ -359,12 +393,11 @@ GetVolumesSyncsParams, GetVolumesVersionsParams, GitInfo, - GridClassifier, - GridClassifiersResponse, GridConnection, GridConnectionBedrockAccessKeysAuth, GridConnectionBedrockApiKeyAuth, GridConnectionConfigAnthropic, + GridConnectionConfigAzure, GridConnectionConfigBedrock, GridConnectionConfigOpenAI, GridConnectionConfigVertex, @@ -379,12 +412,12 @@ GridMachineUsersResponse, GridMachineUserTombstone, GridRoute, + GridRouteAlias, GridRouteClassifier, GridRouteClassifiersResponse, - GridRouteRef, + GridRouteMetadata, GridRoutesResponse, GridRouteTargetBasetenModelAPI, - GridRouteTargetClassifier, GridRouteTargetConnection, GridRouteTargetIntelligent, GridRouteTombstone, @@ -402,6 +435,8 @@ GroupHierarchy, GroupMetadata, GroupsResponse, + IdentityProvider, + IdentityProviders, InferenceVolumeByStatusDatapoint, InProgressPromotion, InstanceType, @@ -410,6 +445,7 @@ InstanceTypeWithPrice, InteractiveSession, InteractiveSessionConfig, + IssuerUrl, KeysForGroupResponse, LibraryListing, LibraryListingMetadata, @@ -458,6 +494,7 @@ LoopsCheckpointFilesResponse, LoopsCheckpointS3Source, LoopsCheckpointSourceResponse, + LoopsCheckpointTombstone, LoopsCheckpointVolumeSource, LoopsDebugArchiveFilesResponse, LoopsDeployment, @@ -474,6 +511,7 @@ LoopsSession, LoopsUsage, LoopsUserConfig, + MaxAccessTokenLifetimeSeconds, MaxScaleDownRate, MaxScaleDownRate1, MaxSeqLen, @@ -502,9 +540,15 @@ Name1, Name2, Name3, + Name4, Name5, Name6, - Name7, + Name8, + Name9, + Name10, + Name12, + Name13, + Name14, NumReplicas, OneTimeAutoscalingSchedule, OneTimeAutoscalingScheduleUpsert, @@ -520,6 +564,9 @@ PatchVolumeRequest, PatchVolumeResponse, PendingJobAheadAtSubmit, + PredefinedIdentityProvider, + PredefinedIdentityProviderConfig, + PredefinedIdentityProviders, PrepareModelUploadRequest, PrepareModelUploadResponse, Primary, @@ -584,6 +631,11 @@ SecretReference, Secrets, SecretTombstone, + ServiceAccount, + ServiceAccountPresetPermissions, + ServiceAccountPresetPermissionsRequest, + ServiceAccounts, + SetLoopsCheckpointTtlRequest, SetVolumeTagRequest, SetVolumeTagResponse, SignalPromotionResponse, @@ -627,17 +679,26 @@ TeamId5, TeamId6, TeamId7, + TeamId8, Teams, TeamTrainingGpuCapacityItem, TerminateReplicaResponse, Token, + TokenExchangeRequest, + TokenExchangeResponse, ToolCallUsageBucket, ToolCallUsageResponse, Total, + Total2, + Total3, TrafficRoutingRule, TrafficRoutingRuleUpsert, TrafficRoutingTarget, TrafficRoutingTargetUpsert, + TrainingBDNConfig, + TrainingBDNConfigResponse, + TrainingBDNMount, + TrainingBDNMountResponse, TrainingGpuCapacityItem, TrainingItem, TrainingJob, @@ -652,7 +713,9 @@ TrainingUsage, TrainingWeightAuth, TrussUserEnv, + TtlSeconds, TTSBenchmarkMetrics, + UpdateAccessTrustRuleRequest, UpdateAutoscalingScheduleSettings, UpdateAutoscalingSettings, UpdateAutoscalingSettingsResponse, @@ -678,10 +741,12 @@ UpdateGridUserSettingsRequest, UpdateGroupMetadata, UpdateGroupRequest, + UpdateIdentityProviderRequest, UpdateLibraryListingRequest, UpdateLibraryListingVersionRequest, UpdateModelPromotionSettings, UpdateModelRequest, + UpdateOrganizationRequest, UpdatePromotionSettings, UpdateRequestBackpressureSettings, UpdateRollingDeployConfig, @@ -691,19 +756,21 @@ UpdateSandboxRequest, UpdateSandboxVolumeParams, UpdateSandboxVolumeRequest, + UpdateServiceAccountRequest, UpdateTrafficRoutingSettings, UpdateTrainingJobRequest, UpdateTrainingJobResponse, UpsertGridConnectionBedrockAccessKeysAuth, UpsertGridConnectionBedrockApiKeyAuth, UpsertGridConnectionConfigAnthropic, + UpsertGridConnectionConfigAzure, UpsertGridConnectionConfigBedrock, UpsertGridConnectionConfigOpenAI, UpsertGridConnectionConfigVertex, UpsertGridConnectionConfigXAI, UpsertGridRouteTargetBasetenModelAPI, - UpsertGridRouteTargetClassifier, UpsertGridRouteTargetConnection, + UpsertGridRouteTargetIntelligent, UpsertSecretRequest, UpsertTrainingProject, UpsertTrainingProjectRequest, @@ -716,6 +783,10 @@ ValidateLoopsCheckpointRequest, ValidateLoopsCheckpointResponse, Value, + Verification, + VerifyAccessTrustRuleRequest, + VerifyIdentityProviderRequest, + VerifyPredefinedIdentityProviderConfig, VertexTargetConfig, Volume, VolumeSync, @@ -746,10 +817,14 @@ "APIKeyTombstone", "APIKeys", "AWSCredentials", + "AccessTokenLifetimeSeconds", + "AccessTrustRule", + "AccessTrustRules", "ActivateResponse", "ActiveJobAtSubmit", "ApiClient", "AsyncApiClient", + "AuditFieldChange", "AuditLogActor", "AuditLogEntry", "AuditLogEventApiKeyCreated", @@ -782,6 +857,9 @@ "AuditLogEventGridMachineUserCreated", "AuditLogEventGridMachineUserDeleted", "AuditLogEventGridMachineUserUpdated", + "AuditLogEventIdentityProviderCreated", + "AuditLogEventIdentityProviderDeleted", + "AuditLogEventIdentityProviderUpdated", "AuditLogEventModelDeleted", "AuditLogEventModelDeployed", "AuditLogEventModelDeploymentActivated", @@ -794,6 +872,8 @@ "AuditLogEventModelDeploymentRetried", "AuditLogEventModelPromotionControlAction", "AuditLogEventModelRenamed", + "AuditLogEventOrganizationApiKeySettingsUpdated", + "AuditLogEventPredefinedIdentityProviderConfig", "AuditLogEventPromotionSettingsOverride", "AuditLogEventProviderConnectionCreated", "AuditLogEventProviderConnectionDeleted", @@ -803,10 +883,17 @@ "AuditLogEventRequireGroupBasedAdminsEnabled", "AuditLogEventSecretDeleted", "AuditLogEventSecretUpdated", + "AuditLogEventServiceAccountCreated", + "AuditLogEventServiceAccountDeleted", + "AuditLogEventServiceAccountPresetPermissions", + "AuditLogEventServiceAccountUpdated", "AuditLogEventSshCertificateSigned", "AuditLogEventTelemetryExportCreated", "AuditLogEventTelemetryExportDeleted", "AuditLogEventTelemetryExportUpdated", + "AuditLogEventTrustRuleCreated", + "AuditLogEventTrustRuleDeleted", + "AuditLogEventTrustRuleUpdated", "AuditLogEventUserInvited", "AuditLogEventUserJoinedOrganization", "AuditLogEventUserRemoved", @@ -866,6 +953,7 @@ "CostPerMillionOutputTokens", "CostPerMillionOutputTokens1", "CreateAPIKeyRequest", + "CreateAccessTrustRuleRequest", "CreateApiKeyForGroupRequest", "CreateApiKeyForGroupResponse", "CreateChainEnvironmentRequest", @@ -880,6 +968,7 @@ "CreateGridTokenRequest", "CreateGroupHierarchy", "CreateGroupRequest", + "CreateIdentityProviderRequest", "CreateJobWeightConfig", "CreateLLMModelRequest", "CreateLLMModelVersionRequest", @@ -893,6 +982,7 @@ "CreateLoopsTrainerRequest", "CreateModelDeploymentRequest", "CreateModelRequest", + "CreatePredefinedIdentityProviderConfig", "CreateSandboxParams", "CreateSandboxPreviewParams", "CreateSandboxPreviewRequest", @@ -901,6 +991,7 @@ "CreateSandboxRequest", "CreateSandboxVolumeParams", "CreateSandboxVolumeRequest", + "CreateServiceAccountRequest", "CreateTokenRequest", "CreateTrainingJob", "CreateTrainingJobAccelerator", @@ -930,6 +1021,7 @@ "DedicatedUsage", "DeleteImageParams", "DeleteImageTagParams", + "DeleteLoopsRunResponse", "DeleteSandboxParams", "DeleteSandboxPreviewParams", "DeleteSandboxPreviewTokenParams", @@ -940,6 +1032,9 @@ "DeleteVolumeTagResponse", "DeleteVolumeVersionRequest", "DeleteVolumeVersionResponse", + "DeletedAccessTrustRule", + "DeletedIdentityProvider", + "DeletedServiceAccount", "DeployLoopsCheckpointRequest", "DeployLoopsCheckpointResponse", "Deployment", @@ -954,10 +1049,16 @@ "DeploymentPatchOpPythonRequirement", "DeploymentPatchPoint", "DeploymentPatchPointWithHash", + "DeploymentReplica", + "DeploymentReplicas", "DeploymentTombstone", "Deployments", "Description", "Description1", + "Description2", + "Description3", + "Description4", + "Description5", "DisplayName", "DisplayName1", "DockerAuth", @@ -1001,6 +1102,8 @@ "GatewayKeyInfo", "GcpOidcDockerAuth", "GcpServiceAccountJsonDockerAuth", + "GetAccessIdentityProvidersParams", + "GetAccessTrustRulesParams", "GetApiKeysParams", "GetAuditLogsParams", "GetAuthCodesResponse", @@ -1015,7 +1118,6 @@ "GetDeploymentPatchesStateResponse", "GetExploreMetadataParams", "GetGatewayEventsParams", - "GetGridClassifiersParams", "GetGridConnectionsParams", "GetGridMachineUsersParams", "GetGridRouteClassifiersParams", @@ -1053,10 +1155,12 @@ "GetModelsDeploymentsLogsParams", "GetModelsDeploymentsMetricsParams", "GetModelsDeploymentsParams", + "GetModelsDeploymentsReplicasParams", "GetModelsDeploymentsStartupsParams", "GetModelsDeploymentsStartupsSummaryParams", "GetModelsEnvironmentsLogsParams", "GetModelsEnvironmentsMetricsParams", + "GetModelsEnvironmentsReplicasParams", "GetModelsEnvironmentsStartupsParams", "GetModelsEnvironmentsStartupsSummaryParams", "GetModelsParams", @@ -1066,6 +1170,7 @@ "GetSandboxParams", "GetSandboxPreviewParams", "GetSandboxVolumeParams", + "GetServiceAccountsParams", "GetTeamsLoopsRunsParams", "GetTeamsLoopsSamplersParams", "GetTeamsModelsParams", @@ -1089,12 +1194,11 @@ "GetVolumesSyncsParams", "GetVolumesVersionsParams", "GitInfo", - "GridClassifier", - "GridClassifiersResponse", "GridConnection", "GridConnectionBedrockAccessKeysAuth", "GridConnectionBedrockApiKeyAuth", "GridConnectionConfigAnthropic", + "GridConnectionConfigAzure", "GridConnectionConfigBedrock", "GridConnectionConfigOpenAI", "GridConnectionConfigVertex", @@ -1109,11 +1213,11 @@ "GridMachineUserTombstone", "GridMachineUsersResponse", "GridRoute", + "GridRouteAlias", "GridRouteClassifier", "GridRouteClassifiersResponse", - "GridRouteRef", + "GridRouteMetadata", "GridRouteTargetBasetenModelAPI", - "GridRouteTargetClassifier", "GridRouteTargetConnection", "GridRouteTargetIntelligent", "GridRouteTombstone", @@ -1132,6 +1236,8 @@ "GroupHierarchy", "GroupMetadata", "GroupsResponse", + "IdentityProvider", + "IdentityProviders", "InProgressPromotion", "InferenceVolumeByStatusDatapoint", "InstanceType", @@ -1140,6 +1246,7 @@ "InstanceTypes", "InteractiveSession", "InteractiveSessionConfig", + "IssuerUrl", "KeysForGroupResponse", "LLMBenchmarkMetrics", "LLMModelHandle", @@ -1188,6 +1295,7 @@ "LoopsCheckpointFilesResponse", "LoopsCheckpointS3Source", "LoopsCheckpointSourceResponse", + "LoopsCheckpointTombstone", "LoopsCheckpointVolumeSource", "LoopsDebugArchiveFilesResponse", "LoopsDeployment", @@ -1204,6 +1312,7 @@ "LoopsSession", "LoopsUsage", "LoopsUserConfig", + "MaxAccessTokenLifetimeSeconds", "MaxScaleDownRate", "MaxScaleDownRate1", "MaxSeqLen", @@ -1232,9 +1341,15 @@ "Name1", "Name2", "Name3", + "Name4", "Name5", "Name6", - "Name7", + "Name8", + "Name9", + "Name10", + "Name12", + "Name13", + "Name14", "NumReplicas", "OneTimeAutoscalingSchedule", "OneTimeAutoscalingScheduleUpsert", @@ -1250,6 +1365,9 @@ "PatchVolumeRequest", "PatchVolumeResponse", "PendingJobAheadAtSubmit", + "PredefinedIdentityProvider", + "PredefinedIdentityProviderConfig", + "PredefinedIdentityProviders", "PrepareModelUploadRequest", "PrepareModelUploadResponse", "Primary", @@ -1315,6 +1433,11 @@ "SecretReference", "SecretTombstone", "Secrets", + "ServiceAccount", + "ServiceAccountPresetPermissions", + "ServiceAccountPresetPermissionsRequest", + "ServiceAccounts", + "SetLoopsCheckpointTtlRequest", "SetVolumeTagRequest", "SetVolumeTagResponse", "SignSSHCertificateRequest", @@ -1359,17 +1482,26 @@ "TeamId5", "TeamId6", "TeamId7", + "TeamId8", "TeamTrainingGpuCapacityItem", "Teams", "TerminateReplicaResponse", "Token", + "TokenExchangeRequest", + "TokenExchangeResponse", "ToolCallUsageBucket", "ToolCallUsageResponse", "Total", + "Total2", + "Total3", "TrafficRoutingRule", "TrafficRoutingRuleUpsert", "TrafficRoutingTarget", "TrafficRoutingTargetUpsert", + "TrainingBDNConfig", + "TrainingBDNConfigResponse", + "TrainingBDNMount", + "TrainingBDNMountResponse", "TrainingGpuCapacityItem", "TrainingItem", "TrainingJob", @@ -1384,6 +1516,8 @@ "TrainingUsage", "TrainingWeightAuth", "TrussUserEnv", + "TtlSeconds", + "UpdateAccessTrustRuleRequest", "UpdateAutoscalingScheduleSettings", "UpdateAutoscalingSettings", "UpdateAutoscalingSettingsResponse", @@ -1409,10 +1543,12 @@ "UpdateGridUserSettingsRequest", "UpdateGroupMetadata", "UpdateGroupRequest", + "UpdateIdentityProviderRequest", "UpdateLibraryListingRequest", "UpdateLibraryListingVersionRequest", "UpdateModelPromotionSettings", "UpdateModelRequest", + "UpdateOrganizationRequest", "UpdatePromotionSettings", "UpdateRequestBackpressureSettings", "UpdateRollingDeployConfig", @@ -1422,19 +1558,21 @@ "UpdateSandboxRequest", "UpdateSandboxVolumeParams", "UpdateSandboxVolumeRequest", + "UpdateServiceAccountRequest", "UpdateTrafficRoutingSettings", "UpdateTrainingJobRequest", "UpdateTrainingJobResponse", "UpsertGridConnectionBedrockAccessKeysAuth", "UpsertGridConnectionBedrockApiKeyAuth", "UpsertGridConnectionConfigAnthropic", + "UpsertGridConnectionConfigAzure", "UpsertGridConnectionConfigBedrock", "UpsertGridConnectionConfigOpenAI", "UpsertGridConnectionConfigVertex", "UpsertGridConnectionConfigXAI", "UpsertGridRouteTargetBasetenModelAPI", - "UpsertGridRouteTargetClassifier", "UpsertGridRouteTargetConnection", + "UpsertGridRouteTargetIntelligent", "UpsertSecretRequest", "UpsertTrainingProject", "UpsertTrainingProjectRequest", @@ -1447,6 +1585,10 @@ "ValidateLoopsCheckpointRequest", "ValidateLoopsCheckpointResponse", "Value", + "Verification", + "VerifyAccessTrustRuleRequest", + "VerifyIdentityProviderRequest", + "VerifyPredefinedIdentityProviderConfig", "VertexTargetConfig", "Volume", "VolumeSync", diff --git a/baseten/client/managementapi/_client.py b/baseten/client/managementapi/_client.py index 145cd1e..f757c3d 100644 --- a/baseten/client/managementapi/_client.py +++ b/baseten/client/managementapi/_client.py @@ -11,6 +11,8 @@ from pydantic import BaseModel from ._models import ( + AccessTrustRule, + AccessTrustRules, ActivateResponse, APIKey, APIKeys, @@ -25,6 +27,7 @@ ChainTombstone, CleanupImagesParams, CleanupSandboxImagesResponse, + CreateAccessTrustRuleRequest, CreateApiKeyForGroupRequest, CreateApiKeyForGroupResponse, CreateAPIKeyRequest, @@ -41,6 +44,7 @@ CreateGridRouteRequest, CreateGridTokenRequest, CreateGroupRequest, + CreateIdentityProviderRequest, CreateLibraryListingRequest, CreateLibraryListingVersionRequest, CreateLLMModelRequest, @@ -61,6 +65,7 @@ CreateSandboxRequest, CreateSandboxVolumeParams, CreateSandboxVolumeRequest, + CreateServiceAccountRequest, CreateTokenRequest, CreateTrainingJobRequest, CreateTrainingJobResponse, @@ -71,8 +76,12 @@ DeactivateLoopsRunResponse, DeactivateLoopsSamplerResponse, DeactivateResponse, + DeletedAccessTrustRule, + DeletedIdentityProvider, + DeletedServiceAccount, DeleteImageParams, DeleteImageTagParams, + DeleteLoopsRunResponse, DeleteSandboxParams, DeleteSandboxPreviewParams, DeleteSandboxPreviewTokenParams, @@ -87,6 +96,8 @@ DeployLoopsCheckpointResponse, Deployment, DeploymentConfigResponse, + DeploymentReplica, + DeploymentReplicas, Deployments, DeploymentTombstone, DownloadDeploymentResponse, @@ -102,6 +113,8 @@ ExploreMetadataResponse, GatewayEventsResponse, GatewayKeyInfo, + GetAccessIdentityProvidersParams, + GetAccessTrustRulesParams, GetApiKeysParams, GetAuditLogsParams, GetAuthCodesResponse, @@ -116,7 +129,6 @@ GetDeploymentPatchesStateResponse, GetExploreMetadataParams, GetGatewayEventsParams, - GetGridClassifiersParams, GetGridConnectionsParams, GetGridMachineUsersParams, GetGridRouteClassifiersParams, @@ -154,10 +166,12 @@ GetModelsDeploymentsLogsParams, GetModelsDeploymentsMetricsParams, GetModelsDeploymentsParams, + GetModelsDeploymentsReplicasParams, GetModelsDeploymentsStartupsParams, GetModelsDeploymentsStartupsSummaryParams, GetModelsEnvironmentsLogsParams, GetModelsEnvironmentsMetricsParams, + GetModelsEnvironmentsReplicasParams, GetModelsEnvironmentsStartupsParams, GetModelsEnvironmentsStartupsSummaryParams, GetModelsParams, @@ -167,6 +181,7 @@ GetSandboxParams, GetSandboxPreviewParams, GetSandboxVolumeParams, + GetServiceAccountsParams, GetTeamsLoopsRunsParams, GetTeamsLoopsSamplersParams, GetTeamsModelsParams, @@ -189,8 +204,6 @@ GetVolumesParams, GetVolumesSyncsParams, GetVolumesVersionsParams, - GridClassifier, - GridClassifiersResponse, GridConnection, GridConnectionsResponse, GridConnectionTombstone, @@ -209,6 +222,8 @@ GridToken, Group, GroupsResponse, + IdentityProvider, + IdentityProviders, InstanceTypePrices, InstanceTypes, KeysForGroupResponse, @@ -242,8 +257,10 @@ ListVolumesResponse, ListVolumeVersionsResponse, LLMModelHandle, + LoopsCheckpoint, LoopsCheckpointFilesResponse, LoopsCheckpointSourceResponse, + LoopsCheckpointTombstone, LoopsDebugArchiveFilesResponse, Model, ModelAPI, @@ -261,6 +278,7 @@ PatchTeamTrainingGpuCapacityResponse, PatchVolumeRequest, PatchVolumeResponse, + PredefinedIdentityProviders, PrepareModelUploadRequest, PrepareModelUploadResponse, PromoteRequest, @@ -290,6 +308,9 @@ Secret, Secrets, SecretTombstone, + ServiceAccount, + ServiceAccounts, + SetLoopsCheckpointTtlRequest, SetVolumeTagRequest, SetVolumeTagResponse, SignalPromotionResponse, @@ -305,9 +326,12 @@ Teams, TerminateReplicaResponse, Token, + TokenExchangeRequest, + TokenExchangeResponse, ToolCallUsageResponse, TrainingJobTombstone, TrainingProjectTombstone, + UpdateAccessTrustRuleRequest, UpdateAutoscalingSettings, UpdateAutoscalingSettingsResponse, UpdateChainEnvironmentRequest, @@ -326,9 +350,11 @@ UpdateGridTeamSettingsRequest, UpdateGridUserSettingsRequest, UpdateGroupRequest, + UpdateIdentityProviderRequest, UpdateLibraryListingRequest, UpdateLibraryListingVersionRequest, UpdateModelRequest, + UpdateOrganizationRequest, UpdateRequestBackpressureSettings, UpdateSandboxParams, UpdateSandboxPreviewParams, @@ -336,6 +362,7 @@ UpdateSandboxRequest, UpdateSandboxVolumeParams, UpdateSandboxVolumeRequest, + UpdateServiceAccountRequest, UpdateTrainingJobRequest, UpdateTrainingJobResponse, UpsertSecretRequest, @@ -346,6 +373,9 @@ UsersResponse, ValidateLoopsCheckpointRequest, ValidateLoopsCheckpointResponse, + Verification, + VerifyAccessTrustRuleRequest, + VerifyIdentityProviderRequest, Volume, VolumeSync, VolumeSyncs, @@ -513,6 +543,40 @@ def create_sandbox_volume( ), ) + def delete_access_identity_providers( + self, *, identity_provider_id: str + ) -> DeletedIdentityProvider: + """Deletes an identity provider""" + return self._do_json( + DeletedIdentityProvider, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def delete_access_trust_rules( + self, *, trust_rule_id: str + ) -> DeletedAccessTrustRule: + """Deletes a trust rule""" + return self._do_json( + DeletedAccessTrustRule, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_api_keys(self, *, api_key_prefix: str) -> APIKeyTombstone: """Deletes an API key by prefix""" return self._do_json( @@ -711,6 +775,38 @@ def delete_library_listings_versions( ), ) + def delete_loops_checkpoints( + self, *, checkpoint_id: str + ) -> LoopsCheckpointTombstone: + """Deletes a Loops checkpoint""" + return self._do_json( + LoopsCheckpointTombstone, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/checkpoints/{}", + path_args=[checkpoint_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def delete_loops_runs(self, *, run_id: str) -> DeleteLoopsRunResponse: + """Deletes a Loops run""" + return self._do_json( + DeleteLoopsRunResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/runs/{}", + path_args=[run_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_models(self, *, model_id: str) -> ModelTombstone: """Deletes a model by ID""" return self._do_json( @@ -777,6 +873,23 @@ def delete_models_environments( ), ) + def delete_models_environments_replicas( + self, *, model_id: str, env_name: str, replica_id: str + ) -> TerminateReplicaResponse: + """Terminates a replica in an environment""" + return self._do_json( + TerminateReplicaResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_sandbox( self, *, sandbox_name: str, params: DeleteSandboxParams | None = None ) -> Sandbox: @@ -868,6 +981,23 @@ def delete_secrets(self, *, secret_name: str) -> SecretTombstone: ), ) + def delete_service_accounts( + self, *, service_account_id: str + ) -> DeletedServiceAccount: + """Deletes a service account""" + return self._do_json( + DeletedServiceAccount, + _ApiRequest( + method="DELETE", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def delete_teams_secrets( self, *, team_id: str, secret_name: str ) -> SecretTombstone: @@ -980,6 +1110,89 @@ def delete_volumes_versions( ), ) + def get_access_identity_providers( + self, *, params: GetAccessIdentityProvidersParams | None = None + ) -> IdentityProviders: + """Lists identity providers""" + return self._do_json( + IdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_identity_providers_identity_provider_id( + self, *, identity_provider_id: str + ) -> IdentityProvider: + """Gets an identity provider""" + return self._do_json( + IdentityProvider, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_predefined_identity_providers(self) -> PredefinedIdentityProviders: + """Lists predefined identity providers""" + return self._do_json( + PredefinedIdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/predefined_identity_providers", + path_args=[], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_trust_rules( + self, *, params: GetAccessTrustRulesParams | None = None + ) -> AccessTrustRules: + """Lists trust rules""" + return self._do_json( + AccessTrustRules, + _ApiRequest( + method="GET", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_access_trust_rules_trust_rule_id( + self, *, trust_rule_id: str + ) -> AccessTrustRule: + """Gets a trust rule""" + return self._do_json( + AccessTrustRule, + _ApiRequest( + method="GET", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_api_keys(self, *, params: GetApiKeysParams | None = None) -> APIKeys: """Lists API keys (metadata only, no plain text keys)""" return self._do_json( @@ -1382,40 +1595,6 @@ def get_gateway_groups_group_id(self, *, group_id: str) -> Group: ), ) - def get_grid_classifiers( - self, *, params: GetGridClassifiersParams | None = None - ) -> GridClassifiersResponse: - """Lists classifiers available for intelligent routes""" - return self._do_json( - GridClassifiersResponse, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - def get_grid_classifiers_classifier_id( - self, *, classifier_id: str - ) -> GridClassifier: - """Gets a classifier available for intelligent routes""" - return self._do_json( - GridClassifier, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers/{}", - path_args=[classifier_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def get_grid_connections( self, *, params: GetGridConnectionsParams | None = None ) -> GridConnectionsResponse: @@ -2268,6 +2447,44 @@ def get_models_deployments_production(self, *, model_id: str) -> Deployment: ), ) + def get_models_deployments_replicas( + self, + *, + model_id: str, + deployment_id: str, + params: GetModelsDeploymentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for a deployment""" + return self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas", + path_args=[model_id, deployment_id], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_models_deployments_replicas_replica_id( + self, *, model_id: str, deployment_id: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in a deployment""" + return self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas/{}", + path_args=[model_id, deployment_id, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_models_deployments_startups( self, *, @@ -2384,6 +2601,44 @@ def get_models_environments_metrics( ), ) + def get_models_environments_replicas( + self, + *, + model_id: str, + env_name: str, + params: GetModelsEnvironmentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for an environment""" + return self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas", + path_args=[model_id, env_name], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_models_environments_replicas_replica_id( + self, *, model_id: str, env_name: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in an environment""" + return self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_models_environments_startups( self, *, @@ -2590,6 +2845,40 @@ def get_secrets(self) -> Secrets: ), ) + def get_service_accounts( + self, *, params: GetServiceAccountsParams | None = None + ) -> ServiceAccounts: + """Lists service accounts""" + return self._do_json( + ServiceAccounts, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_service_accounts_service_account_id( + self, *, service_account_id: str + ) -> ServiceAccount: + """Gets a service account""" + return self._do_json( + ServiceAccount, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_teams(self, *, params: GetTeamsParams | None = None) -> Teams: """Lists all teams""" return self._do_json( @@ -3249,6 +3538,40 @@ def list_sandboxes( ), ) + def patch_access_identity_providers( + self, *, identity_provider_id: str, request: UpdateIdentityProviderRequest + ) -> IdentityProvider: + """Updates an identity provider""" + return self._do_json( + IdentityProvider, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def patch_access_trust_rules( + self, *, trust_rule_id: str, request: UpdateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Updates a trust rule""" + return self._do_json( + AccessTrustRule, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def patch_chains_environments( self, *, chain_id: str, env_name: str, request: UpdateChainEnvironmentRequest ) -> UpdateChainEnvironmentResponse: @@ -3599,6 +3922,40 @@ def patch_models_environments( ), ) + def patch_organizations_me( + self, *, request: UpdateOrganizationRequest + ) -> OrganizationInfo: + """Updates the authenticated organization""" + return self._do_json( + OrganizationInfo, + _ApiRequest( + method="PATCH", + path_fmt="/v1/organizations/me", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def patch_service_accounts( + self, *, service_account_id: str, request: UpdateServiceAccountRequest + ) -> ServiceAccount: + """Updates a service account""" + return self._do_json( + ServiceAccount, + _ApiRequest( + method="PATCH", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def patch_teams_environment_groups( self, *, team_id: str, env_name: str, request: UpdateEnvironmentGroupRequest ) -> EnvironmentGroup: @@ -3619,7 +3976,7 @@ def patch_teams_environment_groups( def patch_training_capacity( self, *, request: PatchTeamTrainingGpuCapacityRequest ) -> PatchTeamTrainingGpuCapacityResponse: - """Sets a team's training GPU capacity""" + """Sets a team's training GPU quota""" return self._do_json( PatchTeamTrainingGpuCapacityResponse, _ApiRequest( @@ -3693,6 +4050,74 @@ def patch_volumes( ), ) + def post_access_identity_providers( + self, *, request: CreateIdentityProviderRequest + ) -> IdentityProvider: + """Adds an identity provider""" + return self._do_json( + IdentityProvider, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def post_access_identity_providers_verify( + self, *, request: VerifyIdentityProviderRequest + ) -> Verification: + """Checks an identity provider before adding it""" + return self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def post_access_trust_rules( + self, *, request: CreateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Creates a trust rule""" + return self._do_json( + AccessTrustRule, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + def post_access_trust_rules_verify( + self, *, request: VerifyAccessTrustRuleRequest + ) -> Verification: + """Checks a trust rule's condition and audience""" + return self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: """Creates an API key""" return self._do_json( @@ -3708,6 +4133,23 @@ def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: ), ) + def post_auth_token( + self, *, request: TokenExchangeRequest + ) -> TokenExchangeResponse: + """Exchanges an identity provider's JWT for an access token""" + return self._do_json( + TokenExchangeResponse, + _ApiRequest( + method="POST", + path_fmt="/v1/auth/token", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def post_chains_deployments_deactivate( self, *, chain_id: str, chain_deployment_id: str ) -> DeactivateResponse: @@ -4640,6 +5082,23 @@ def post_secrets(self, *, request: UpsertSecretRequest) -> Secret: ), ) + def post_service_accounts( + self, *, request: CreateServiceAccountRequest + ) -> ServiceAccount: + """Creates a service account""" + return self._do_json( + ServiceAccount, + _ApiRequest( + method="POST", + path_fmt="/v1/service_accounts", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def post_teams_api_keys( self, *, team_id: str, request: CreateAPIKeyRequest ) -> APIKey: @@ -5061,6 +5520,23 @@ def push_image( ), ) + def put_loops_checkpoints_ttl( + self, *, checkpoint_id: str, request: SetLoopsCheckpointTtlRequest + ) -> LoopsCheckpoint: + """Sets a Loops checkpoint's TTL""" + return self._do_json( + LoopsCheckpoint, + _ApiRequest( + method="PUT", + path_fmt="/v1/loops/checkpoints/{}/ttl", + path_args=[checkpoint_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def update_sandbox( self, *, @@ -5335,6 +5811,40 @@ async def create_sandbox_volume( ), ) + async def delete_access_identity_providers( + self, *, identity_provider_id: str + ) -> DeletedIdentityProvider: + """Deletes an identity provider""" + return await self._do_json( + DeletedIdentityProvider, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_access_trust_rules( + self, *, trust_rule_id: str + ) -> DeletedAccessTrustRule: + """Deletes a trust rule""" + return await self._do_json( + DeletedAccessTrustRule, + _ApiRequest( + method="DELETE", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_api_keys(self, *, api_key_prefix: str) -> APIKeyTombstone: """Deletes an API key by prefix""" return await self._do_json( @@ -5535,6 +6045,38 @@ async def delete_library_listings_versions( ), ) + async def delete_loops_checkpoints( + self, *, checkpoint_id: str + ) -> LoopsCheckpointTombstone: + """Deletes a Loops checkpoint""" + return await self._do_json( + LoopsCheckpointTombstone, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/checkpoints/{}", + path_args=[checkpoint_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_loops_runs(self, *, run_id: str) -> DeleteLoopsRunResponse: + """Deletes a Loops run""" + return await self._do_json( + DeleteLoopsRunResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/loops/runs/{}", + path_args=[run_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_models(self, *, model_id: str) -> ModelTombstone: """Deletes a model by ID""" return await self._do_json( @@ -5601,6 +6143,23 @@ async def delete_models_environments( ), ) + async def delete_models_environments_replicas( + self, *, model_id: str, env_name: str, replica_id: str + ) -> TerminateReplicaResponse: + """Terminates a replica in an environment""" + return await self._do_json( + TerminateReplicaResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_sandbox( self, *, sandbox_name: str, params: DeleteSandboxParams | None = None ) -> Sandbox: @@ -5692,6 +6251,23 @@ async def delete_secrets(self, *, secret_name: str) -> SecretTombstone: ), ) + async def delete_service_accounts( + self, *, service_account_id: str + ) -> DeletedServiceAccount: + """Deletes a service account""" + return await self._do_json( + DeletedServiceAccount, + _ApiRequest( + method="DELETE", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def delete_teams_secrets( self, *, team_id: str, secret_name: str ) -> SecretTombstone: @@ -5750,54 +6326,139 @@ async def delete_volumes( return await self._do_json( DeleteVolumeResponse, _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}", - path_args=[volume_namespace, volume_name], - body=request, + method="DELETE", + path_fmt="/v1/volumes/{}/{}", + path_args=[volume_namespace, volume_name], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_volumes_tags( + self, + *, + volume_namespace: str, + volume_name: str, + volume_tag: str, + request: DeleteVolumeTagRequest, + ) -> DeleteVolumeTagResponse: + """Deletes a volume tag""" + return await self._do_json( + DeleteVolumeTagResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/volumes/{}/{}/tags/{}", + path_args=[volume_namespace, volume_name, volume_tag], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def delete_volumes_versions( + self, + *, + volume_namespace: str, + volume_name: str, + volume_version: str, + request: DeleteVolumeVersionRequest, + ) -> DeleteVolumeVersionResponse: + """Deletes one version of a volume""" + return await self._do_json( + DeleteVolumeVersionResponse, + _ApiRequest( + method="DELETE", + path_fmt="/v1/volumes/{}/{}/versions/{}", + path_args=[volume_namespace, volume_name, volume_version], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_access_identity_providers( + self, *, params: GetAccessIdentityProvidersParams | None = None + ) -> IdentityProviders: + """Lists identity providers""" + return await self._do_json( + IdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_access_identity_providers_identity_provider_id( + self, *, identity_provider_id: str + ) -> IdentityProvider: + """Gets an identity provider""" + return await self._do_json( + IdentityProvider, + _ApiRequest( + method="GET", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_access_predefined_identity_providers( + self, + ) -> PredefinedIdentityProviders: + """Lists predefined identity providers""" + return await self._do_json( + PredefinedIdentityProviders, + _ApiRequest( + method="GET", + path_fmt="/v1/access/predefined_identity_providers", + path_args=[], + body=None, query=None, success_codes=[200], error_codes=None, ), ) - async def delete_volumes_tags( - self, - *, - volume_namespace: str, - volume_name: str, - volume_tag: str, - request: DeleteVolumeTagRequest, - ) -> DeleteVolumeTagResponse: - """Deletes a volume tag""" + async def get_access_trust_rules( + self, *, params: GetAccessTrustRulesParams | None = None + ) -> AccessTrustRules: + """Lists trust rules""" return await self._do_json( - DeleteVolumeTagResponse, + AccessTrustRules, _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}/tags/{}", - path_args=[volume_namespace, volume_name, volume_tag], - body=request, - query=None, + method="GET", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=None, + query=params, success_codes=[200], error_codes=None, ), ) - async def delete_volumes_versions( - self, - *, - volume_namespace: str, - volume_name: str, - volume_version: str, - request: DeleteVolumeVersionRequest, - ) -> DeleteVolumeVersionResponse: - """Deletes one version of a volume""" + async def get_access_trust_rules_trust_rule_id( + self, *, trust_rule_id: str + ) -> AccessTrustRule: + """Gets a trust rule""" return await self._do_json( - DeleteVolumeVersionResponse, + AccessTrustRule, _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}/versions/{}", - path_args=[volume_namespace, volume_name, volume_version], - body=request, + method="GET", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=None, query=None, success_codes=[200], error_codes=None, @@ -6210,40 +6871,6 @@ async def get_gateway_groups_group_id(self, *, group_id: str) -> Group: ), ) - async def get_grid_classifiers( - self, *, params: GetGridClassifiersParams | None = None - ) -> GridClassifiersResponse: - """Lists classifiers available for intelligent routes""" - return await self._do_json( - GridClassifiersResponse, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_grid_classifiers_classifier_id( - self, *, classifier_id: str - ) -> GridClassifier: - """Gets a classifier available for intelligent routes""" - return await self._do_json( - GridClassifier, - _ApiRequest( - method="GET", - path_fmt="/v1/grid/classifiers/{}", - path_args=[classifier_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def get_grid_connections( self, *, params: GetGridConnectionsParams | None = None ) -> GridConnectionsResponse: @@ -7096,6 +7723,44 @@ async def get_models_deployments_production(self, *, model_id: str) -> Deploymen ), ) + async def get_models_deployments_replicas( + self, + *, + model_id: str, + deployment_id: str, + params: GetModelsDeploymentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for a deployment""" + return await self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas", + path_args=[model_id, deployment_id], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_models_deployments_replicas_replica_id( + self, *, model_id: str, deployment_id: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in a deployment""" + return await self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/deployments/{}/replicas/{}", + path_args=[model_id, deployment_id, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def get_models_deployments_startups( self, *, @@ -7212,6 +7877,44 @@ async def get_models_environments_metrics( ), ) + async def get_models_environments_replicas( + self, + *, + model_id: str, + env_name: str, + params: GetModelsEnvironmentsReplicasParams | None = None, + ) -> DeploymentReplicas: + """Lists replicas for an environment""" + return await self._do_json( + DeploymentReplicas, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas", + path_args=[model_id, env_name], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_models_environments_replicas_replica_id( + self, *, model_id: str, env_name: str, replica_id: str + ) -> DeploymentReplica: + """Gets a replica in an environment""" + return await self._do_json( + DeploymentReplica, + _ApiRequest( + method="GET", + path_fmt="/v1/models/{}/environments/{}/replicas/{}", + path_args=[model_id, env_name, replica_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def get_models_environments_startups( self, *, @@ -7418,6 +8121,40 @@ async def get_secrets(self) -> Secrets: ), ) + async def get_service_accounts( + self, *, params: GetServiceAccountsParams | None = None + ) -> ServiceAccounts: + """Lists service accounts""" + return await self._do_json( + ServiceAccounts, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_service_accounts_service_account_id( + self, *, service_account_id: str + ) -> ServiceAccount: + """Gets a service account""" + return await self._do_json( + ServiceAccount, + _ApiRequest( + method="GET", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def get_teams(self, *, params: GetTeamsParams | None = None) -> Teams: """Lists all teams""" return await self._do_json( @@ -8079,6 +8816,40 @@ async def list_sandboxes( ), ) + async def patch_access_identity_providers( + self, *, identity_provider_id: str, request: UpdateIdentityProviderRequest + ) -> IdentityProvider: + """Updates an identity provider""" + return await self._do_json( + IdentityProvider, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/identity_providers/{}", + path_args=[identity_provider_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def patch_access_trust_rules( + self, *, trust_rule_id: str, request: UpdateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Updates a trust rule""" + return await self._do_json( + AccessTrustRule, + _ApiRequest( + method="PATCH", + path_fmt="/v1/access/trust_rules/{}", + path_args=[trust_rule_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def patch_chains_environments( self, *, chain_id: str, env_name: str, request: UpdateChainEnvironmentRequest ) -> UpdateChainEnvironmentResponse: @@ -8431,6 +9202,40 @@ async def patch_models_environments( ), ) + async def patch_organizations_me( + self, *, request: UpdateOrganizationRequest + ) -> OrganizationInfo: + """Updates the authenticated organization""" + return await self._do_json( + OrganizationInfo, + _ApiRequest( + method="PATCH", + path_fmt="/v1/organizations/me", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def patch_service_accounts( + self, *, service_account_id: str, request: UpdateServiceAccountRequest + ) -> ServiceAccount: + """Updates a service account""" + return await self._do_json( + ServiceAccount, + _ApiRequest( + method="PATCH", + path_fmt="/v1/service_accounts/{}", + path_args=[service_account_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def patch_teams_environment_groups( self, *, team_id: str, env_name: str, request: UpdateEnvironmentGroupRequest ) -> EnvironmentGroup: @@ -8451,7 +9256,7 @@ async def patch_teams_environment_groups( async def patch_training_capacity( self, *, request: PatchTeamTrainingGpuCapacityRequest ) -> PatchTeamTrainingGpuCapacityResponse: - """Sets a team's training GPU capacity""" + """Sets a team's training GPU quota""" return await self._do_json( PatchTeamTrainingGpuCapacityResponse, _ApiRequest( @@ -8525,6 +9330,74 @@ async def patch_volumes( ), ) + async def post_access_identity_providers( + self, *, request: CreateIdentityProviderRequest + ) -> IdentityProvider: + """Adds an identity provider""" + return await self._do_json( + IdentityProvider, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def post_access_identity_providers_verify( + self, *, request: VerifyIdentityProviderRequest + ) -> Verification: + """Checks an identity provider before adding it""" + return await self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/identity_providers/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def post_access_trust_rules( + self, *, request: CreateAccessTrustRuleRequest + ) -> AccessTrustRule: + """Creates a trust rule""" + return await self._do_json( + AccessTrustRule, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + + async def post_access_trust_rules_verify( + self, *, request: VerifyAccessTrustRuleRequest + ) -> Verification: + """Checks a trust rule's condition and audience""" + return await self._do_json( + Verification, + _ApiRequest( + method="POST", + path_fmt="/v1/access/trust_rules/verify", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: """Creates an API key""" return await self._do_json( @@ -8540,6 +9413,23 @@ async def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: ), ) + async def post_auth_token( + self, *, request: TokenExchangeRequest + ) -> TokenExchangeResponse: + """Exchanges an identity provider's JWT for an access token""" + return await self._do_json( + TokenExchangeResponse, + _ApiRequest( + method="POST", + path_fmt="/v1/auth/token", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def post_chains_deployments_deactivate( self, *, chain_id: str, chain_deployment_id: str ) -> DeactivateResponse: @@ -9480,6 +10370,23 @@ async def post_secrets(self, *, request: UpsertSecretRequest) -> Secret: ), ) + async def post_service_accounts( + self, *, request: CreateServiceAccountRequest + ) -> ServiceAccount: + """Creates a service account""" + return await self._do_json( + ServiceAccount, + _ApiRequest( + method="POST", + path_fmt="/v1/service_accounts", + path_args=[], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def post_teams_api_keys( self, *, team_id: str, request: CreateAPIKeyRequest ) -> APIKey: @@ -9905,6 +10812,23 @@ async def push_image( ), ) + async def put_loops_checkpoints_ttl( + self, *, checkpoint_id: str, request: SetLoopsCheckpointTtlRequest + ) -> LoopsCheckpoint: + """Sets a Loops checkpoint's TTL""" + return await self._do_json( + LoopsCheckpoint, + _ApiRequest( + method="PUT", + path_fmt="/v1/loops/checkpoints/{}/ttl", + path_args=[checkpoint_id], + body=request, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def update_sandbox( self, *, diff --git a/baseten/client/managementapi/_models.py b/baseten/client/managementapi/_models.py index b5f378f..53b2707 100644 --- a/baseten/client/managementapi/_models.py +++ b/baseten/client/managementapi/_models.py @@ -828,6 +828,111 @@ class GetUsersParams(BaseModel): ] = None +class Name1(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Only the account with this name, ignoring case", + min_length=1, + title="Name", + ), + ] = None + + +class GetServiceAccountsParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + name: Annotated[ + Name1 | None, + Field( + description="Only the account with this name, ignoring case", title="Name" + ), + ] = None + team_id: Annotated[ + str | None, Field(description="Only this team's accounts", title="Team Id") + ] = None + disabled: Annotated[ + bool | None, + Field(description="Only disabled or enabled accounts", title="Disabled"), + ] = None + + +class Name2(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Only the provider with this name, ignoring case", + min_length=1, + title="Name", + ), + ] = None + + +class Name3(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Only the rule with this name, ignoring case", + min_length=1, + title="Name", + ), + ] = None + + +class GetAccessTrustRulesParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + name: Annotated[ + Name3 | None, + Field(description="Only the rule with this name, ignoring case", title="Name"), + ] = None + identity_provider_id: Annotated[ + str | None, + Field(description="Only this provider's rules", title="Identity Provider Id"), + ] = None + service_account_id: Annotated[ + str | None, + Field( + description="Only rules for this service account", + title="Service Account Id", + ), + ] = None + team_id: Annotated[ + str | None, + Field( + description="Only rules for this team's service accounts", title="Team Id" + ), + ] = None + + class Limit6(RootModel[int]): root: Annotated[ int | None, @@ -949,7 +1054,7 @@ class GetGridRoutesParams(BaseModel): name: Annotated[ str | None, Field( - description="Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", + description="Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", title="Name", ), ] = None @@ -1066,25 +1171,6 @@ class GetGridConnectionsParams(BaseModel): ] = None -class GetGridClassifiersParams(BaseModel): - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor returned by a previous page. Omit to fetch the first page.", - title="Cursor", - ), - ] = None - limit: Annotated[ - int, - Field( - description="Maximum number of items to return.", - ge=1, - le=1000, - title="Limit", - ), - ] = 100 - - class GetGridRouteClassifiersParams(BaseModel): cursor: Annotated[ str | None, @@ -3329,9 +3415,21 @@ class PrepareModelUploadResponse(BaseModel): ] = None +class AuditFieldChange(BaseModel): + old: Annotated[Any, Field(description="The value before the update.", title="Old")] + new: Annotated[Any, Field(description="The value after the update.", title="New")] + + class AuditLogActor(BaseModel): type: Annotated[ - Literal["USER", "API_KEY", "BASETEN_USER", "BASETEN_SYSTEM", "TOMBSTONE_USER"] + Literal[ + "USER", + "API_KEY", + "BASETEN_USER", + "BASETEN_SYSTEM", + "TOMBSTONE_USER", + "SERVICE_ACCOUNT", + ] | str, Field( description="Kind of actor that performed the action.", @@ -3359,6 +3457,27 @@ class AuditLogActor(BaseModel): title="Api Key Name", ), ] = None + service_account_id: Annotated[ + str | None, + Field( + description="ID of the acting service account, when the actor is a service account.", + title="Service Account Id", + ), + ] = None + service_account_name: Annotated[ + str | None, + Field( + description="Current name of the acting service account, when the actor is a service account.", + title="Service Account Name", + ), + ] = None + trust_rule_id: Annotated[ + str | None, + Field( + description="ID of the trust rule the acting workload identity federation token was exchanged through, when the actor is a service account.", + title="Trust Rule Id", + ), + ] = None class AuditLogEventApiKeyCreated(BaseModel): @@ -3370,6 +3489,7 @@ class AuditLogEventApiKeyCreated(BaseModel): "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", + "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -3396,6 +3516,7 @@ class AuditLogEventApiKeyDeleted(BaseModel): "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", + "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -3411,7 +3532,7 @@ class AuditLogEventApiKeyDeleted(BaseModel): ), ] prefix: Annotated[str, Field(title="Prefix")] - revocation_reason: Literal["INACTIVITY"] | str | None = None + revocation_reason: Literal["INACTIVITY", "CREDENTIAL_EXPOSURE"] | str | None = None class AuditLogEventApiKeyLifetimeLimitsUpdated(BaseModel): @@ -3810,6 +3931,29 @@ class AuditLogEventGridMachineUserUpdated(BaseModel): team_name: Annotated[str, Field(title="Team Name")] +class AuditLogEventIdentityProviderDeleted(BaseModel): + event_type: Annotated[ + Literal["IDENTITY_PROVIDER_DELETED"], Field(title="Event Type") + ] + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + name: Annotated[str, Field(title="Name")] + + +class AuditLogEventIdentityProviderUpdated(BaseModel): + event_type: Annotated[ + Literal["IDENTITY_PROVIDER_UPDATED"], Field(title="Event Type") + ] + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + name: Annotated[str, Field(title="Name")] + changes: Annotated[ + dict[str, AuditFieldChange], + Field( + description="The fields the update changed, keyed by field name.", + title="Changes", + ), + ] + + class AuditLogEventModelDeleted(BaseModel): event_type: Annotated[Literal["MODEL_DELETED"], Field(title="Event Type")] model_id: Annotated[str, Field(title="Model Id")] @@ -3888,6 +4032,41 @@ class AuditLogEventModelRenamed(BaseModel): previous_name: Annotated[str | None, Field(title="Previous Name")] +class AuditLogEventOrganizationApiKeySettingsUpdated(BaseModel): + event_type: Annotated[ + Literal["ORGANIZATION_API_KEY_SETTINGS_UPDATED"], Field(title="Event Type") + ] + organization_id: Annotated[str, Field(title="Organization Id")] + previous_allow_personal_api_keys: Annotated[ + bool, Field(title="Previous Allow Personal Api Keys") + ] + new_allow_personal_api_keys: Annotated[ + bool, Field(title="New Allow Personal Api Keys") + ] + previous_allow_service_account_api_keys: Annotated[ + bool, Field(title="Previous Allow Service Account Api Keys") + ] + new_allow_service_account_api_keys: Annotated[ + bool, Field(title="New Allow Service Account Api Keys") + ] + + +class AuditLogEventPredefinedIdentityProviderConfig(BaseModel): + kind: Annotated[ + str, + Field( + description="Which predefined provider, for example `AWS_EKS`.", + title="Kind", + ), + ] + issuer_url: Annotated[ + str, + Field( + description="The `iss` claim of the provider's tokens.", title="Issuer Url" + ), + ] + + class AuditLogEventPromotionSettingsOverride(BaseModel): redeploy_on_promotion: Annotated[bool | None, Field(title="Redeploy On Promotion")] rolling_deploy: Annotated[bool | None, Field(title="Rolling Deploy")] @@ -3968,6 +4147,56 @@ class AuditLogEventSecretUpdated(BaseModel): secret_name: Annotated[str, Field(title="Secret Name")] +class AuditLogEventServiceAccountDeleted(BaseModel): + event_type: Annotated[Literal["SERVICE_ACCOUNT_DELETED"], Field(title="Event Type")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + name: Annotated[str, Field(title="Name")] + + +class AuditLogEventServiceAccountPresetPermissions(BaseModel): + api_key_type: Annotated[ + str, + Field( + description="The API key type whose permissions the account has, as API key events record it.", + title="Api Key Type", + ), + ] + model_ids: Annotated[ + list[str], + Field( + description="Models the access is limited to; empty for all.", + title="Model Ids", + ), + ] + environment_names: Annotated[ + list[str], + Field( + description="Environments the access is limited to, or may also manage; empty for none.", + title="Environment Names", + ), + ] + model_api_slugs: Annotated[ + list[str], + Field( + description="Model APIs the access is limited to; empty for all.", + title="Model Api Slugs", + ), + ] + + +class AuditLogEventServiceAccountUpdated(BaseModel): + event_type: Annotated[Literal["SERVICE_ACCOUNT_UPDATED"], Field(title="Event Type")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + name: Annotated[str, Field(title="Name")] + changes: Annotated[ + dict[str, AuditFieldChange], + Field( + description="The fields the update changed, keyed by field name.", + title="Changes", + ), + ] + + class AuditLogEventSshCertificateSigned(BaseModel): event_type: Annotated[Literal["SSH_CERTIFICATE_SIGNED"], Field(title="Event Type")] workload_type: Annotated[str, Field(title="Workload Type")] @@ -4007,6 +4236,57 @@ class AuditLogEventTelemetryExportUpdated(BaseModel): enabled: Annotated[bool | None, Field(title="Enabled")] +class AuditLogEventTrustRuleCreated(BaseModel): + event_type: Annotated[Literal["TRUST_RULE_CREATED"], Field(title="Event Type")] + trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] + name: Annotated[str, Field(title="Name")] + description: Annotated[ + str | None, + Field( + description="Null when the rule was created without one.", + title="Description", + ), + ] = None + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + condition: Annotated[ + str, + Field( + description="The CEL expression a token's claims must satisfy.", + title="Condition", + ), + ] + audience: Annotated[ + str, Field(description="The `aud` claim a token must carry.", title="Audience") + ] + max_access_token_lifetime_seconds: Annotated[ + int, + Field( + description="The longest lifetime, in seconds, of an access token the rule issues.", + title="Max Access Token Lifetime Seconds", + ), + ] + + +class AuditLogEventTrustRuleDeleted(BaseModel): + event_type: Annotated[Literal["TRUST_RULE_DELETED"], Field(title="Event Type")] + trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] + name: Annotated[str, Field(title="Name")] + + +class AuditLogEventTrustRuleUpdated(BaseModel): + event_type: Annotated[Literal["TRUST_RULE_UPDATED"], Field(title="Event Type")] + trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] + name: Annotated[str, Field(title="Name")] + changes: Annotated[ + dict[str, AuditFieldChange], + Field( + description="The fields the update changed, keyed by field name.", + title="Changes", + ), + ] + + class AuditLogEventUserInvited(BaseModel): event_type: Annotated[Literal["USER_INVITED"], Field(title="Event Type")] invited_user_email: Annotated[str, Field(title="Invited User Email")] @@ -4261,7 +4541,7 @@ class ModelTombstone(BaseModel): ] -class Name1(RootModel[str]): +class Name4(RootModel[str]): root: Annotated[ str | None, Field( @@ -4279,7 +4559,7 @@ class UpdateModelRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name1 | None, + Name4 | None, Field( description="New name for the model, unique within its team. Renaming does not change the model ID, endpoints, or deployments. Pushes that still use the old model_name create another model or target a model that now uses that name, so update config.yaml after renaming.", examples=["my-model"], @@ -4300,7 +4580,7 @@ class DeploymentTombstone(BaseModel): ] -class Name2(RootModel[str]): +class Name5(RootModel[str]): root: Annotated[ str | None, Field( @@ -4318,7 +4598,7 @@ class UpdateDeploymentRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name2 | None, + Name5 | None, Field( description="New name for the deployment, unique among the model's deployments. Only alphanumeric characters, hyphens, underscores, and periods are allowed.", examples=["my-deployment"], @@ -4885,45 +5165,108 @@ class StartupSummary(BaseModel): ] -class TerminateReplicaResponse(BaseModel): - success: Annotated[ - bool, - Field( - description="Whether the replica was successfully terminated", - title="Success", - ), - ] = True - - -class SignSSHCertificateRequest(BaseModel): - public_key: Annotated[ +class DeploymentReplica(BaseModel): + id: Annotated[ str, Field( - description="The user's SSH public key (e.g., 'ssh-ed25519 AAAA... user@host').", - title="Public Key", + description="Pod-name suffix used for replica lookup and termination, usually five characters.", + title="Id", ), ] - replica_id: Annotated[ - str | None, - Field( - description="The replica to connect to. Required for training jobs (e.g. '0'). Optional for inference (server picks a running replica if omitted).", - title="Replica Id", - ), - ] = None - - -class SignSSHCertificateResponse(BaseModel): - ssh_certificate: Annotated[ + deployment_id: Annotated[ + str, Field(description="ID of the replica's deployment.", title="Deployment Id") + ] + deployment_name: Annotated[ str, + Field(description="Name of the replica's deployment.", title="Deployment Name"), + ] + status: Annotated[ + Literal[ + "STARTING", "ACTIVE", "UNHEALTHY", "TERMINATING", "TERMINATED", "UNKNOWN" + ] + | str, Field( - description="The signed SSH certificate in OpenSSH format.", - title="Ssh Certificate", + description="Current replica lifecycle status.", + title="DeploymentReplicaStatusV1", ), ] - jwt: Annotated[ - str, + created_at: Annotated[ + AwareDatetime, Field( - description="Signed JWT (ES256) for SSH proxy authorization.", title="Jwt" + description="Replica creation time in ISO 8601 format.", title="Created At" + ), + ] + terminated_at: Annotated[ + AwareDatetime | None, + Field( + description="Observed termination completion time in ISO 8601 format, or null if unavailable.", + title="Terminated At", + ), + ] + age_seconds: Annotated[ + float, + Field( + description="Age in seconds since creation, frozen at termination.", + title="Age Seconds", + ), + ] + restart_count: Annotated[ + int | None, + Field( + description="Model container lifetime restart count, or null if unavailable.", + title="Restart Count", + ), + ] + + +class DeploymentReplicas(BaseModel): + items: Annotated[ + list[DeploymentReplica], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + +class TerminateReplicaResponse(BaseModel): + success: Annotated[ + bool, + Field( + description="Whether the replica was successfully terminated", + title="Success", + ), + ] = True + + +class SignSSHCertificateRequest(BaseModel): + public_key: Annotated[ + str, + Field( + description="The user's SSH public key (e.g., 'ssh-ed25519 AAAA... user@host').", + title="Public Key", + ), + ] + replica_id: Annotated[ + str | None, + Field( + description="The replica to connect to. Required for training jobs (e.g. '0'). Optional for inference (server picks a running replica if omitted).", + title="Replica Id", + ), + ] = None + + +class SignSSHCertificateResponse(BaseModel): + ssh_certificate: Annotated[ + str, + Field( + description="The signed SSH certificate in OpenSSH format.", + title="Ssh Certificate", + ), + ] + jwt: Annotated[ + str, + Field( + description="Signed JWT (ES256) for SSH proxy authorization.", title="Jwt" ), ] proxy_address: Annotated[ @@ -5688,6 +6031,25 @@ class UpsertTrainingProjectRequest(BaseModel): ] +class TrainingBDNMountResponse(BaseModel): + source: Annotated[str, Field(title="Source")] + path: Annotated[str, Field(title="Path")] + include: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns selecting files to mount; empty includes all files.", + title="Include", + ), + ] = None + exclude: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns excluding files from the mount; exclusions win.", + title="Exclude", + ), + ] = None + + class TrainingProjectSummary(BaseModel): id: Annotated[ str, Field(description="Unique identifier of the training project.", title="Id") @@ -5843,6 +6205,28 @@ class SecretReference(BaseModel): ] +class TrainingBDNMount(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + source: Annotated[str, Field(title="Source")] + path: Annotated[str, Field(title="Path")] + include: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns selecting files to mount; empty includes all files.", + title="Include", + ), + ] = None + exclude: Annotated[ + list[str] | None, + Field( + description="Relative glob patterns excluding files from the mount; exclusions win.", + title="Exclude", + ), + ] = None + + class TrainingWeightAuth(BaseModel): auth_method: Annotated[ Literal[ @@ -6552,7 +6936,7 @@ class LoopsSampler(BaseModel): ] = None -class Name3(RootModel[str]): +class Name6(RootModel[str]): root: Annotated[ str | None, Field( @@ -6588,7 +6972,7 @@ class CreateLoopsRunRequest(BaseModel): Field(description="Base model ID (e.g. 'Qwen/Qwen3-8B').", title="Base Model"), ] name: Annotated[ - Name3 | None, + Name6 | None, Field( description="Optional display name for the run. Defaults to the base model name when omitted.", title="Name", @@ -6657,10 +7041,22 @@ class CreateLoopsRunRequest(BaseModel): base_checkpoint: Annotated[ str | None, Field( - description="Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + description="Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", title="Base Checkpoint", ), ] = None + base_checkpoint_auth: Annotated[ + TrainingWeightAuth | None, + Field( + description="Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + examples=[ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint", + } + ], + ), + ] = None sampler_num_replicas: Annotated[ SamplerNumReplicas | None, Field( @@ -6682,6 +7078,25 @@ class DeactivateLoopsRunResponse(BaseModel): user: Annotated[User, Field(description="The user who owns the Loops run.")] +class LoopsLoRAConfig(BaseModel): + config_version: Annotated[ + str, Field(description="The config version, like v1.", title="Config Version") + ] + targets: Annotated[ + list[str], + Field( + description="The module names the LoRA adapter targets.", title="Targets" + ), + ] + expert_layout: Annotated[ + Literal["per_expert", "shared_outer", "shared_adapter"] | str | None, + Field( + description="How routed-expert LoRA weights are laid out. Null when no experts are targeted.", + title="Expert Layout", + ), + ] = None + + class CreateLoopsTrainerRequest(BaseModel): session_id: Annotated[ str, @@ -6695,7 +7110,7 @@ class CreateLoopsTrainerRequest(BaseModel): Field(description="Base model ID (e.g. 'Qwen/Qwen3-8B').", title="Base Model"), ] name: Annotated[ - Name3 | None, + Name6 | None, Field( description="Optional display name for the run. Defaults to the base model name when omitted.", title="Name", @@ -6764,10 +7179,22 @@ class CreateLoopsTrainerRequest(BaseModel): base_checkpoint: Annotated[ str | None, Field( - description="Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + description="Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", title="Base Checkpoint", ), ] = None + base_checkpoint_auth: Annotated[ + TrainingWeightAuth | None, + Field( + description="Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + examples=[ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint", + } + ], + ), + ] = None scope: Annotated[ Literal["default", "serverless", "dedicated"] | str, Field( @@ -6882,25 +7309,6 @@ class GetLoopsSamplerResponse(BaseModel): sampler: Annotated[LoopsSampler, Field(description="The Loops sampler.")] -class LoopsLoRAConfig(BaseModel): - config_version: Annotated[ - str, Field(description="The config version, like v1.", title="Config Version") - ] - targets: Annotated[ - list[str], - Field( - description="The module names the LoRA adapter targets.", title="Targets" - ), - ] - expert_layout: Annotated[ - Literal["per_expert", "shared_outer", "shared_adapter"] | str | None, - Field( - description="How routed-expert LoRA weights are laid out. Null when no experts are targeted.", - title="Expert Layout", - ), - ] = None - - class ValidateLoopsCheckpointRequest(BaseModel): checkpoint_path: Annotated[ str, @@ -6968,6 +7376,34 @@ class DeployLoopsCheckpointResponse(BaseModel): ] +class LoopsCheckpointTombstone(BaseModel): + id: Annotated[str, Field(description="The deleted checkpoint ID.", title="Id")] + run_id: Annotated[ + str, + Field( + description="The ID of the run that produced the checkpoint.", + title="Run Id", + ), + ] + checkpoint_id: Annotated[ + str, + Field( + description="The name the checkpoint was saved under.", + title="Checkpoint Id", + ), + ] + target: Annotated[ + Literal["sampler", "trainer"] | str, + Field( + description="Whether the checkpoint was loadable by the sampler or by the run.", + title="TrainerCheckpointTarget", + ), + ] + path: Annotated[ + str, Field(description="The checkpoint's bt:// path.", title="Path") + ] + + class LoopsCheckpointFilesResponse(BaseModel): presigned_urls: Annotated[ list[CheckpointFile], @@ -7029,6 +7465,28 @@ class LoopsCheckpointSourceResponse(BaseModel): ] +class TtlSeconds(RootModel[int]): + root: Annotated[ + int, + Field( + description="Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", + ge=3600, + le=315360000, + title="Ttl Seconds", + ), + ] + + +class SetLoopsCheckpointTtlRequest(BaseModel): + ttl_seconds: Annotated[ + TtlSeconds | None, + Field( + description="Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", + title="Ttl Seconds", + ), + ] + + class LoopsDeploymentStatus(BaseModel): name: Annotated[ Literal[ @@ -7221,14 +7679,14 @@ class TeamTrainingGpuCapacityItem(BaseModel): baseline: Annotated[ int, Field( - description="Baseline GPU allocation for the team. 0 if not configured.", + description="Configured minimum GPU allocation for the team. Not enforced. 0 if not configured.", title="Baseline", ), ] limit: Annotated[ int, Field( - description="Maximum concurrent GPUs of this type for this team", + description="The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", title="Limit", ), ] @@ -7242,7 +7700,7 @@ class TeamTrainingGpuCapacityItem(BaseModel): dedicated_usage_count: Annotated[ int, Field( - description="Portion of usage_count from standard (non-spot) jobs.", + description="Portion of usage_count from on-demand (non-spot) jobs.", title="Dedicated Usage Count", ), ] = 0 @@ -7265,17 +7723,31 @@ class TrainingGpuCapacityItem(BaseModel): baseline: Annotated[ int, Field( - description="Baseline GPU allocation; jobs below this threshold are expected to run immediately. 0 if not configured.", + description="Configured minimum GPU allocation (`min_gpus`). 0 if not configured. Use `on_demand_quota` for the quota applied to on-demand jobs.", title="Baseline", ), ] limit: Annotated[ int, Field( - description="Maximum concurrent GPUs of this type for this org", + description="Configured maximum GPU allocation (`max_gpus`). Use `on_demand_quota` and `spot_quota` for the quotas applied to jobs.", title="Limit", ), ] + on_demand_quota: Annotated[ + int, + Field( + description="GPU quota for this type for on-demand (non-spot) jobs: the most GPUs they can use at once.", + title="On Demand Quota", + ), + ] + spot_quota: Annotated[ + int | None, + Field( + description="GPU quota for this type for spot jobs. Spot shares this quota with on-demand jobs: spot can use up to the quota minus on-demand GPUs in use. Null if spot is not enabled for the organization.", + title="Spot Quota", + ), + ] = None usage_count: Annotated[ int, Field( @@ -7286,14 +7758,14 @@ class TrainingGpuCapacityItem(BaseModel): dedicated_usage_count: Annotated[ int, Field( - description="Portion of usage_count from standard (non-spot) jobs, which run against the baseline.", + description="Portion of usage_count from on-demand (non-spot) jobs.", title="Dedicated Usage Count", ), ] = 0 spot_usage_count: Annotated[ int, Field( - description="Portion of usage_count from spot jobs, which burst into the peak and may push usage above the limit.", + description="Portion of usage_count from spot jobs.", title="Spot Usage Count", ), ] = 0 @@ -7303,17 +7775,24 @@ class GetTrainingGpuCapacityResponse(BaseModel): gpu_capacities: Annotated[ list[TrainingGpuCapacityItem], Field( - description="Org-level GPU capacity limits and current usage per GPU type", + description="Organization GPU quotas and current usage per GPU type", title="Gpu Capacities", ), ] team_gpu_capacities: Annotated[ list[TeamTrainingGpuCapacityItem] | None, Field( - description="Per-team GPU capacity limits and current usage per GPU type", + description="Per-team GPU quotas and current usage per GPU type", title="Team Gpu Capacities", ), ] = None + spot_enabled: Annotated[ + bool, + Field( + description="Whether the organization can submit spot training jobs.", + title="Spot Enabled", + ), + ] = False class PatchTeamTrainingGpuCapacityRequest(BaseModel): @@ -7327,7 +7806,7 @@ class PatchTeamTrainingGpuCapacityRequest(BaseModel): max_gpus: Annotated[ int, Field( - description="Max concurrent GPUs of this type the team may use", + description="The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", examples=[8, 16, 32], title="Max Gpus", ), @@ -7336,8 +7815,7 @@ class PatchTeamTrainingGpuCapacityRequest(BaseModel): class PatchTeamTrainingGpuCapacityResponse(BaseModel): team_gpu_capacity: Annotated[ - TeamTrainingGpuCapacityItem, - Field(description="The updated per-team GPU capacity limit"), + TeamTrainingGpuCapacityItem, Field(description="The updated per-team GPU quota") ] @@ -8390,7 +8868,7 @@ class Subtotal5(RootModel[str]): root: Annotated[ str, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), @@ -8515,6 +8993,20 @@ class ModelApiItem(BaseModel): float | Subtotal10, Field(description="Subtotal cost in dollars for this model", title="Subtotal"), ] + team_id: Annotated[ + str | None, + Field( + description="Team ID for multi-team organizations; otherwise null", + title="Team Id", + ), + ] = None + team_name: Annotated[ + str | None, + Field( + description="Team name, including historical teams; null if unavailable", + title="Team Name", + ), + ] = None input_tokens: Annotated[ int, Field(description="Total input tokens for this model", title="Input Tokens"), @@ -8543,18 +9035,32 @@ class Subtotal11(RootModel[str]): root: Annotated[ str, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), ] +class Total2(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="Usage charges in dollars after applying credits, floored at zero", + pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", + title="Total", + ), + ] + + class ModelApisUsage(BaseModel): subtotal: Annotated[ float | Subtotal11, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", title="Subtotal", ), ] @@ -8563,11 +9069,18 @@ class ModelApisUsage(BaseModel): Field(description="Credits applied in dollars", title="Credits Used"), ] total: Annotated[ - float | Total, Field(description="Total cost in dollars", title="Total") + float | Total2, + Field( + description="Usage charges in dollars after applying credits, floored at zero", + title="Total", + ), ] breakdown: Annotated[ list[ModelApiItem] | None, - Field(description="Per-model usage breakdown", title="Breakdown"), + Field( + description="Per-model usage breakdown, split by team for multi-team organizations", + title="Breakdown", + ), ] = None @@ -8592,13 +9105,27 @@ class Subtotal13(RootModel[str]): root: Annotated[ str, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), ] +class Total3(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="Total cost in dollars", + pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", + title="Total", + ), + ] + + class ToolCallUsageBucket(BaseModel): date: Annotated[ date_aliased, @@ -8701,17 +9228,796 @@ class OrganizationInfo(BaseModel): description="AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" ), ] = None - - -class GatewayEventTokens(BaseModel): - inputTokens: Annotated[ - int, Field(description="Cached and uncached input tokens.", title="Inputtokens") - ] - outputTokens: Annotated[ - int, Field(description="Output tokens.", title="Outputtokens") + allow_personal_api_keys: Annotated[ + bool, + Field( + description="Whether members can create new personal API keys. Existing keys keep working.", + title="Allow Personal Api Keys", + ), ] - cachedInputTokens: Annotated[ - int, Field(description="Cached input tokens.", title="Cachedinputtokens") + allow_service_account_api_keys: Annotated[ + bool, + Field( + description="Whether new team and organization API keys can be created. Existing keys keep working.", + title="Allow Service Account Api Keys", + ), + ] + + +class UpdateOrganizationRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + allow_personal_api_keys: Annotated[ + bool | None, + Field( + description="Whether members can create new personal API keys. Null is not accepted.", + title="Allow Personal Api Keys", + ), + ] = None + allow_service_account_api_keys: Annotated[ + bool | None, + Field( + description="Whether new team and organization API keys can be created. Null is not accepted.", + title="Allow Service Account Api Keys", + ), + ] = None + + +class ServiceAccountPresetPermissionsRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[ + Literal[ + "WORKSPACE_MANAGE_ALL", + "WORKSPACE_INVOKE", + "WORKSPACE_EXPORT_METRICS", + "WORKSPACE_MANAGE_API_KEYS", + "WORKSPACE_INVOKE_MODEL_APIS", + ] + | str, + Field( + description="What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + examples=["WORKSPACE_MANAGE_ALL"], + title="ServiceAccountPresetTypeV1", + ), + ] + model_ids: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + examples=[["abcd1234"]], + title="Model Ids", + ), + ] = None + environment_names: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + examples=[["production"]], + title="Environment Names", + ), + ] = None + model_api_slugs: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + examples=[["my-model-api"]], + title="Model Api Slugs", + ), + ] = None + + +class Description(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Optional description, up to 1,024 characters", + max_length=1024, + title="Description", + ), + ] = None + + +class TeamId4(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="The team that owns the account. Omit for an organization account. Can't be changed.", + min_length=1, + title="Team Id", + ), + ] = None + + +class CreateServiceAccountRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + str, + Field( + description="Name, unique in the organization. Can be changed later.", + examples=["ci-deployer"], + max_length=255, + min_length=1, + title="Name", + ), + ] + description: Annotated[ + Description | None, + Field( + description="Optional description, up to 1,024 characters", + title="Description", + ), + ] = None + team_id: Annotated[ + TeamId4 | None, + Field( + description="The team that owns the account. Omit for an organization account. Can't be changed.", + title="Team Id", + ), + ] = None + preset_permissions: Annotated[ + ServiceAccountPresetPermissionsRequest, + Field( + description="What the service account may do. Can be changed later. Temporary; may be removed once fine-grained access control is available." + ), + ] + + +class DeletedServiceAccount(BaseModel): + id: Annotated[ + str, Field(description="ID of the deleted service account", title="Id") + ] + deleted: Annotated[bool, Field(description="Always true", title="Deleted")] + + +class Name8(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Name, unique in the organization", + max_length=255, + min_length=1, + title="Name", + ), + ] = None + + +class Description1(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Description, up to 1,024 characters; null clears it", + max_length=1024, + title="Description", + ), + ] = None + + +class UpdateServiceAccountRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name8 | None, + Field(description="Name, unique in the organization", title="Name"), + ] = None + description: Annotated[ + Description1 | None, + Field( + description="Description, up to 1,024 characters; null clears it", + title="Description", + ), + ] = None + disabled: Annotated[ + bool | None, + Field( + description="Disable the account to stop it being used, or enable it again", + title="Disabled", + ), + ] = None + preset_permissions: Annotated[ + ServiceAccountPresetPermissionsRequest | None, + Field( + description="Replaces the account's access as a whole. Temporary; may be removed once fine-grained access control is available." + ), + ] = None + + +class PredefinedIdentityProvider(BaseModel): + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Pass as `kind` when adding the provider", + title="PredefinedIdentityProviderKindV1", + ), + ] + name: Annotated[str, Field(description="Display name", title="Name")] + issuer_url: Annotated[ + str | None, + Field( + description="The `iss` claim its tokens carry. Null when each account, tenant, or cluster has its own issuer, which you pass as `issuer_url` when adding the provider.", + title="Issuer Url", + ), + ] = None + issuer_url_example: Annotated[ + str | None, + Field( + description="An example of the `issuer_url` to pass. Null when the issuer is fixed.", + title="Issuer Url Example", + ), + ] = None + + +class PredefinedIdentityProviders(BaseModel): + items: Annotated[ + list[PredefinedIdentityProvider], + Field(description="Identity providers Baseten supports", title="Items"), + ] + + +class IssuerUrl(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + max_length=1024, + title="Issuer Url", + ), + ] = None + + +class PredefinedIdentityProviderConfig(BaseModel): + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Which predefined provider. Can't be changed.", + title="PredefinedIdentityProviderKindV1", + ), + ] + issuer_url: Annotated[ + IssuerUrl | None, + Field( + description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + title="Issuer Url", + ), + ] = None + + +class CreatePredefinedIdentityProviderConfig(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Which predefined provider. Can't be changed.", + title="PredefinedIdentityProviderKindV1", + ), + ] + issuer_url: Annotated[ + IssuerUrl | None, + Field( + description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + title="Issuer Url", + ), + ] = None + + +class Name9(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", + max_length=255, + min_length=1, + title="Name", + ), + ] = None + + +class Description2(RootModel[str]): + root: Annotated[ + str | None, + Field(description="Optional description", max_length=1024, title="Description"), + ] = None + + +class CreateIdentityProviderRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name9 | None, + Field( + description="Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", + title="Name", + ), + ] = None + description: Annotated[ + Description2 | None, + Field(description="Optional description", title="Description"), + ] = None + predefined: Annotated[ + CreatePredefinedIdentityProviderConfig, + Field(description="The predefined provider to add"), + ] + + +class VerifyPredefinedIdentityProviderConfig(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str, + Field( + description="Which predefined provider", + title="PredefinedIdentityProviderKindV1", + ), + ] + issuer_url: Annotated[ + str | None, + Field( + description="The issuer to check, for AWS IAM, Amazon EKS, Azure managed identity, and Azure Kubernetes Service, in the format the predefined identity providers endpoint shows", + title="Issuer Url", + ), + ] = None + + +class VerifyIdentityProviderRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + predefined: Annotated[ + VerifyPredefinedIdentityProviderConfig, + Field( + description="The predefined provider to check, as you'd pass it when adding it" + ), + ] + + +class Verification(BaseModel): + valid: Annotated[ + bool, Field(description="Whether the input passes every check", title="Valid") + ] + error: Annotated[ + str | None, + Field( + description="Why the input fails, as creating it would report. Null when it's valid.", + title="Error", + ), + ] = None + + +class DeletedIdentityProvider(BaseModel): + id: Annotated[ + str, Field(description="ID of the deleted identity provider", title="Id") + ] + deleted: Annotated[bool, Field(description="Always true", title="Deleted")] + + +class Name10(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Name, unique in the organization", + max_length=255, + min_length=1, + title="Name", + ), + ] = None + + +class Description3(RootModel[str]): + root: Annotated[ + str | None, + Field( + description="Description; null clears it", + max_length=1024, + title="Description", + ), + ] = None + + +class UpdateIdentityProviderRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name10 | None, + Field(description="Name, unique in the organization", title="Name"), + ] = None + description: Annotated[ + Description3 | None, + Field(description="Description; null clears it", title="Description"), + ] = None + + +class AccessTrustRule(BaseModel): + id: Annotated[ + str, + Field( + description="Trust rule ID. Workloads pass it when they exchange a token.", + title="Id", + ), + ] + name: Annotated[ + str, Field(description="Name, unique in the organization", title="Name") + ] + description: Annotated[ + str | None, Field(description="Description", title="Description") + ] = None + identity_provider_id: Annotated[ + str, + Field( + description="The identity provider whose tokens it accepts", + title="Identity Provider Id", + ), + ] + identity_provider_name: Annotated[ + str, + Field( + description="Name of the identity provider", title="Identity Provider Name" + ), + ] + service_account_id: Annotated[ + str, + Field( + description="The service account its tokens act as", + title="Service Account Id", + ), + ] + service_account_name: Annotated[ + str, + Field(description="Name of the service account", title="Service Account Name"), + ] + team_id: Annotated[ + str | None, + Field( + description="The service account's team. Null for an organization service account.", + title="Team Id", + ), + ] = None + team_name: Annotated[ + str | None, + Field( + description="Name of the service account's team. Null for an organization service account.", + title="Team Name", + ), + ] = None + condition: Annotated[ + str, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + examples=[ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + title="Condition", + ), + ] + audience: Annotated[ + str, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + title="Audience", + ), + ] + max_access_token_lifetime_seconds: Annotated[ + int, + Field( + description="Longest lifetime of a token the rule issues, in seconds", + title="Max Access Token Lifetime Seconds", + ), + ] + last_used_at: Annotated[ + AwareDatetime | None, + Field( + description="Last time a request authenticated with a token the rule issued, to within an hour. Null until the first.", + title="Last Used At", + ), + ] = None + created_by: Annotated[ + str, + Field(description="ID of the user who created the rule", title="Created By"), + ] + created_at: Annotated[ + AwareDatetime, + Field(description="Time the rule was created", title="Created At"), + ] + updated_at: Annotated[ + AwareDatetime, + Field(description="Time the rule was last updated", title="Updated At"), + ] + + +class AccessTrustRules(BaseModel): + items: Annotated[ + list[AccessTrustRule], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + +class CreateAccessTrustRuleRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + str, + Field( + description="Name, unique in the organization. Can be changed later.", + max_length=255, + min_length=1, + title="Name", + ), + ] + description: Annotated[ + str | None, Field(description="Optional description", title="Description") + ] = None + identity_provider_id: Annotated[ + str, + Field( + description="Whose tokens the rule accepts. Can't be changed.", + title="Identity Provider Id", + ), + ] + service_account_id: Annotated[ + str, + Field( + description="The service account its tokens act as. Can be changed later.", + title="Service Account Id", + ), + ] + condition: Annotated[ + str, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters. Can be changed later.", + examples=[ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + title="Condition", + ), + ] + audience: Annotated[ + str, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters. Can be changed later.", + title="Audience", + ), + ] + max_access_token_lifetime_seconds: Annotated[ + int, + Field( + description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Can be changed later.", + ge=60, + le=3600, + title="Max Access Token Lifetime Seconds", + ), + ] = 3600 + + +class VerifyAccessTrustRuleRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + identity_provider_id: Annotated[ + str, + Field( + description="The identity provider the rule is for, which decides the claims it must pin", + title="Identity Provider Id", + ), + ] + condition: Annotated[ + str, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + examples=[ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + title="Condition", + ), + ] + audience: Annotated[ + str, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + title="Audience", + ), + ] + + +class DeletedAccessTrustRule(BaseModel): + id: Annotated[str, Field(description="ID of the deleted trust rule", title="Id")] + deleted: Annotated[bool, Field(description="Always true", title="Deleted")] + + +class MaxAccessTokenLifetimeSeconds(RootModel[int]): + root: Annotated[ + int | None, + Field( + description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", + ge=60, + le=3600, + title="Max Access Token Lifetime Seconds", + ), + ] = None + + +class UpdateAccessTrustRuleRequest(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[ + Name10 | None, + Field(description="Name, unique in the organization", title="Name"), + ] = None + description: Annotated[ + str | None, + Field(description="Description; null clears it", title="Description"), + ] = None + condition: Annotated[ + str | None, + Field( + description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + title="Condition", + ), + ] = None + audience: Annotated[ + str | None, + Field( + description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + title="Audience", + ), + ] = None + max_access_token_lifetime_seconds: Annotated[ + MaxAccessTokenLifetimeSeconds | None, + Field( + description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", + title="Max Access Token Lifetime Seconds", + ), + ] = None + service_account_id: Annotated[ + str | None, + Field( + description="Moves the rule to another service account. Tokens already issued keep the old account until they expire.", + title="Service Account Id", + ), + ] = None + + +class AccessTokenLifetimeSeconds(RootModel[int]): + root: Annotated[ + int | None, + Field( + description="Lifetime of the access token, in seconds. At most the rule's maximum.", + ge=1, + title="Access Token Lifetime Seconds", + ), + ] = None + + +class TokenExchangeRequest(BaseModel): + grant_type: Annotated[ + str, + Field( + description="Always `urn:ietf:params:oauth:grant-type:token-exchange`", + examples=["urn:ietf:params:oauth:grant-type:token-exchange"], + title="Grant Type", + ), + ] + subject_token: Annotated[ + str, + Field( + description="The identity provider's JWT", + examples=[""], + max_length=16384, + title="Subject Token", + ), + ] + subject_token_type: Annotated[ + str, + Field( + description="`urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`", + examples=["urn:ietf:params:oauth:token-type:jwt"], + title="Subject Token Type", + ), + ] + audience: Annotated[ + str, + Field( + description="ID of the trust rule to check the JWT against", + examples=["abcd1234"], + max_length=64, + title="Audience", + ), + ] + requested_token_type: Annotated[ + str | None, + Field( + description="Optional; only `urn:ietf:params:oauth:token-type:access_token` is issued", + title="Requested Token Type", + ), + ] = None + access_token_lifetime_seconds: Annotated[ + AccessTokenLifetimeSeconds | None, + Field( + description="Lifetime of the access token, in seconds. At most the rule's maximum.", + title="Access Token Lifetime Seconds", + ), + ] = None + + +class TokenExchangeResponse(BaseModel): + access_token: Annotated[ + str, Field(description="Send as `Authorization: Bearer`", title="Access Token") + ] + issued_token_type: Annotated[ + str, + Field( + description="Always `urn:ietf:params:oauth:token-type:access_token`", + title="Issued Token Type", + ), + ] + token_type: Annotated[str, Field(description="Always `Bearer`", title="Token Type")] + expires_in: Annotated[ + int, + Field(description="Seconds until the access token expires", title="Expires In"), + ] + + +class GatewayEventTokens(BaseModel): + inputTokens: Annotated[ + int, Field(description="Cached and uncached input tokens.", title="Inputtokens") + ] + outputTokens: Annotated[ + int, Field(description="Output tokens.", title="Outputtokens") + ] + cachedInputTokens: Annotated[ + int, Field(description="Cached input tokens.", title="Cachedinputtokens") ] @@ -8787,7 +10093,7 @@ class ExploreMetadataAPIFormats(BaseModel): ] = False -class TeamId4(RootModel[str]): +class TeamId5(RootModel[str]): root: Annotated[ str | None, Field( @@ -8801,7 +10107,7 @@ class TeamId4(RootModel[str]): class CreateGridTokenRequest(BaseModel): team_id: Annotated[ - TeamId4 | None, + TeamId5 | None, Field( description="ID of the team. When omitted, the team you belong to; required when you belong to several.", examples=["abc1234"], @@ -8843,21 +10149,19 @@ class GridToken(BaseModel): ] -class GridClassifier(BaseModel): - id: Annotated[ +class GridRouteAlias(BaseModel): + name: Annotated[ str, Field( - description="Stable classifier identifier.", - examples=["general-v1"], - title="Id", + description="Name to send in the inference request's `model` field instead of the route's `name`.", + title="Name", ), ] - name: Annotated[ - str, + kind: Annotated[ + Literal["CLAUDE_DESKTOP", "ALIAS"] | str, Field( - description="Display name of the classifier.", - examples=["General"], - title="Name", + description="Purpose of the alias. CLAUDE_DESKTOP is for Claude Code desktop, which rejects model names without a `claude` substring. ALIAS is any other name the team's clients send for the route.", + title="GridRouteAliasKindV1", ), ] @@ -8867,16 +10171,16 @@ class GridRouteClassifier(BaseModel): str, Field( description="Stable route classifier identifier.", - examples=["general-v1"], + examples=["abc1234"], title="Id", ), ] - name: Annotated[ + display_name: Annotated[ str, Field( description="Display name of the route classifier.", examples=["General"], - title="Name", + title="Display Name", ), ] supported_tradeoffs: Annotated[ @@ -8886,23 +10190,12 @@ class GridRouteClassifier(BaseModel): title="Supported Tradeoffs", ), ] - decidable_models: Annotated[ + decidable_canonical_model_ids: Annotated[ list[str], Field( - description="Model identities the route classifier picks from.", + description="Canonical model ids the route classifier picks from.", examples=[["zai-org/GLM-5.3", "anthropic/claude-opus-5-5"]], - title="Decidable Models", - ), - ] - - -class GridRouteRef(BaseModel): - id: Annotated[str, Field(description="Stable route identifier.", title="Id")] - slug: Annotated[ - str, - Field( - description="Name of the route to send in the inference request's model field.", - title="Slug", + title="Decidable Canonical Model Ids", ), ] @@ -8913,31 +10206,8 @@ class GridRouteTargetBasetenModelAPI(BaseModel): Field(description="Target kind for a Baseten Model API.", title="Type"), ] model: Annotated[ - str, - Field(description="Name of the target Model API.", min_length=1, title="Model"), - ] - - -class GridRouteTargetClassifier(BaseModel): - type: Annotated[ - Literal["CLASSIFIER"], - Field(description="Target kind for a classifier-based route.", title="Type"), - ] - classifier: Annotated[ - GridClassifier | None, - Field( - description="Classifier that picks a route for each request. Null for routers created before classifiers could be selected." - ), - ] - default_route: Annotated[ - GridRouteRef, Field(description="Route used when the classifier picks none.") - ] - allowed_routes: Annotated[ - list[GridRouteRef], - Field( - description="Routes the classifier may pick, in creation order.", - title="Allowed Routes", - ), + str, + Field(description="Name of the target Model API.", min_length=1, title="Model"), ] @@ -8998,70 +10268,64 @@ class UpsertGridRouteTargetBasetenModelAPI(BaseModel): ] -class UpsertGridRouteTargetClassifier(BaseModel): +class UpsertGridRouteTargetConnection(BaseModel): model_config = ConfigDict( extra="forbid", ) type: Annotated[ - Literal["CLASSIFIER"], - Field(description="Target kind for a classifier-based route.", title="Type"), - ] - classifier_id: Annotated[ - str, + Literal["CONNECTION"], Field( - description="ID of the classifier that picks a route for each request.", - examples=["general-v1"], - min_length=1, - title="Classifier Id", + description="Target kind for a provider reached through a team connection.", + title="Type", ), ] - allowed_route_ids: Annotated[ - list[str], + model: Annotated[ + str, Field( - description="IDs of the routes the classifier may pick. All must belong to the route's team and must not be routers themselves.", - examples=[["abc1234", "def5678"]], - title="Allowed Route Ids", + description="Model name sent to the provider.", min_length=1, title="Model" ), ] - default_route_id: Annotated[ + connection_id: Annotated[ str, Field( - description="ID of the allowed route used when the classifier picks none.", + description="Identifier of a connection owned by the route's team. Its provider serves the route.", examples=["abc1234"], - title="Default Route Id", + min_length=1, + title="Connection Id", ), ] -class UpsertGridRouteTargetConnection(BaseModel): +class UpsertGridRouteTargetIntelligent(BaseModel): model_config = ConfigDict( extra="forbid", ) type: Annotated[ - Literal["CONNECTION"], + Literal["INTELLIGENT"], Field( - description="Target kind for a provider reached through a team connection.", + description="Target kind for an intelligent route: Baseten picks the model per request.", title="Type", ), ] - model: Annotated[ + route_classifier_id: Annotated[ str, Field( - description="Model name sent to the provider.", min_length=1, title="Model" + description="Identifier of the route classifier that picks the model. List them with GET /v1/grid/route_classifiers.", + examples=["abc1234"], + min_length=1, + title="Route Classifier Id", ), ] - connection_id: Annotated[ - str, + tradeoff: Annotated[ + Literal["cost", "balanced", "intelligence"] | str, Field( - description="Identifier of a connection owned by the route's team. Its provider serves the route.", - examples=["abc1234"], - min_length=1, - title="Connection Id", + description="How the classifier weighs cost against quality. Must be one of the classifier's supported tradeoffs.", + title="GridRouteTradeoffV1", ), ] -class TeamId5(RootModel[str]): +class TeamId6(RootModel[str]): root: Annotated[ str | None, Field( @@ -9077,7 +10341,7 @@ class DisplayName(RootModel[str]): root: Annotated[ str | None, Field( - description="Display label. Omit to use the route name; null is not accepted.", + description="Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", examples=["Assistant"], max_length=255, min_length=1, @@ -9086,7 +10350,7 @@ class DisplayName(RootModel[str]): ] = None -class Description(RootModel[str]): +class Description4(RootModel[str]): root: Annotated[ str | None, Field( @@ -9103,7 +10367,7 @@ class CreateGridRouteRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId5 | None, + TeamId6 | None, Field( description="Identifier of the team that owns the route.", examples=["abc1234"], @@ -9113,7 +10377,7 @@ class CreateGridRouteRequest(BaseModel): display_name: Annotated[ DisplayName | None, Field( - description="Display label. Omit to use the route name; null is not accepted.", + description="Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", examples=["Assistant"], title="Display Name", ), @@ -9122,9 +10386,9 @@ class CreateGridRouteRequest(BaseModel): Annotated[ UpsertGridRouteTargetBasetenModelAPI | UpsertGridRouteTargetConnection - | UpsertGridRouteTargetClassifier, + | UpsertGridRouteTargetIntelligent, Field( - description="Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team.", + description="Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team. INTELLIGENT targets need at least one of the route classifier's models, and one of its fallback models, servable by the team.", discriminator="type", examples=[{"model": "zai-org/GLM-5.3", "type": "BASETEN_MODEL_API"}], title="Target", @@ -9134,7 +10398,7 @@ class CreateGridRouteRequest(BaseModel): Field(union_mode="left_to_right"), ] description: Annotated[ - Description | None, + Description4 | None, Field( description="Short description of the route. Omit for no description; null is not accepted.", examples=["Assistant for code review and debugging."], @@ -9181,6 +10445,7 @@ class GridRouteUsageResult(BaseModel): "VERTEX", "OPENAI_COMPATIBLE", "BEDROCK", + "AZURE", ] | str | None, @@ -9188,11 +10453,18 @@ class GridRouteUsageResult(BaseModel): description="Provider that served the requests. Null when not grouping by PROVIDER." ), ] = None - intelligent_route: Annotated[ + intelligent_route_id: Annotated[ + str | None, + Field( + description="ID of the intelligent route, as `id` in GET /v1/grid/routes. Null when not grouping by INTELLIGENT_ROUTE.", + title="Intelligent Route Id", + ), + ] = None + intelligent_route_display_name: Annotated[ str | None, Field( - description="Name of the intelligent route, as in `GET /v1/grid/routes`. Null when not grouping by INTELLIGENT_ROUTE.", - title="Intelligent Route", + description="Display name of the intelligent route. Null when `intelligent_route_id` is null or the route cannot be resolved.", + title="Intelligent Route Display Name", ), ] = None harness: Annotated[ @@ -9201,6 +10473,20 @@ class GridRouteUsageResult(BaseModel): description="Coding harness. Null when not grouping by HARNESS, when no harness was recorded (including usage from before harness tracking), or when the recorded harness is not recognized by this API version." ), ] = None + api_key_prefix: Annotated[ + str | None, + Field( + description="Prefix of the API key that made the requests, matching `GET /v1/api_keys`. Null when not grouping by API_KEY, for usage without an API key, and for usage recorded before API key tracking.", + title="Api Key Prefix", + ), + ] = None + api_key_name: Annotated[ + str | None, + Field( + description="Name of the API key. Null when `api_key_prefix` is null or the key has no name.", + title="Api Key Name", + ), + ] = None cost_usd: Annotated[ str, Field( @@ -9249,7 +10535,7 @@ class GridRouteTombstone(BaseModel): name: Annotated[str, Field(description="Name of the deleted route.", title="Name")] -class Description1(RootModel[str]): +class Description5(RootModel[str]): root: Annotated[ str | None, Field( @@ -9279,7 +10565,7 @@ class UpdateGridRouteRequest(BaseModel): extra="forbid", ) description: Annotated[ - Description1 | None, + Description5 | None, Field( description="New description. Omit to keep the current description; use an empty string to clear it. Null is not accepted.", examples=["Assistant for code review and debugging."], @@ -9294,16 +10580,6 @@ class UpdateGridRouteRequest(BaseModel): title="Display Name", ), ] = None - target: Annotated[ - UpsertGridRouteTargetBasetenModelAPI - | UpsertGridRouteTargetConnection - | UpsertGridRouteTargetClassifier - | None, - Field( - description="Complete new target configuration. Omit to keep the current configuration; null is not accepted. Only the CLASSIFIER configuration of a router route is mutable.", - title="Target", - ), - ] = None class GridTeamSpendLimitSetting(BaseModel): @@ -9518,6 +10794,34 @@ class GridConnectionConfigAnthropic(BaseModel): ] +class GridConnectionConfigAzure(BaseModel): + provider: Annotated[ + Literal["AZURE"], + Field(description="Provider kind for Microsoft Azure.", title="Provider"), + ] + secret_id: Annotated[ + str, + Field( + description="Identifier of the team secret holding the provider API key.", + title="Secret Id", + ), + ] + secret_name: Annotated[ + str, + Field( + description="Name of the team secret holding the provider API key.", + title="Secret Name", + ), + ] + resource_name: Annotated[ + str, + Field( + description="Name of the Azure AI Foundry or Azure OpenAI resource.", + title="Resource Name", + ), + ] + + class GridConnectionConfigBedrock(BaseModel): provider: Annotated[ Literal["BEDROCK"], @@ -9652,7 +10956,8 @@ class GridConnection(BaseModel): | GridConnectionConfigOpenAI | GridConnectionConfigXAI | GridConnectionConfigVertex - | GridConnectionConfigBedrock, + | GridConnectionConfigBedrock + | GridConnectionConfigAzure, Field( description="Provider the connection authenticates with, and the team secret holding its API key.", discriminator="provider", @@ -9725,6 +11030,37 @@ class UpsertGridConnectionConfigAnthropic(BaseModel): ] +class UpsertGridConnectionConfigAzure(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + provider: Annotated[ + Literal["AZURE"], + Field( + description="Provider kind for Microsoft Azure. Route targets name a deployment, which must be named after its Azure model. Claude models (`claude-*`) use the Anthropic Messages API, and other models use the OpenAI-compatible APIs.", + title="Provider", + ), + ] + secret_name: Annotated[ + str, + Field( + description="Name of an existing secret, owned by the same team, that holds the provider API key.", + examples=["anthropic-key"], + min_length=1, + title="Secret Name", + ), + ] + resource_name: Annotated[ + str, + Field( + description="Name of the Azure AI Foundry or Azure OpenAI resource, the subdomain of `.openai.azure.com`.", + examples=["my-foundry-resource"], + min_length=1, + title="Resource Name", + ), + ] + + class UpsertGridConnectionConfigBedrock(BaseModel): model_config = ConfigDict( extra="forbid", @@ -9843,7 +11179,7 @@ class UpsertGridConnectionConfigXAI(BaseModel): ] -class TeamId6(RootModel[str]): +class TeamId7(RootModel[str]): root: Annotated[ str | None, Field( @@ -9860,7 +11196,7 @@ class CreateGridConnectionRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId6 | None, + TeamId7 | None, Field( description="Identifier of the team that owns the connection.", examples=["abc1234"], @@ -9873,7 +11209,8 @@ class CreateGridConnectionRequest(BaseModel): | UpsertGridConnectionConfigOpenAI | UpsertGridConnectionConfigXAI | UpsertGridConnectionConfigVertex - | UpsertGridConnectionConfigBedrock, + | UpsertGridConnectionConfigBedrock + | UpsertGridConnectionConfigAzure, Field( description="Provider the connection authenticates with, and the team secret holding its API key.", discriminator="provider", @@ -9903,7 +11240,8 @@ class UpdateGridConnectionRequest(BaseModel): | UpsertGridConnectionConfigOpenAI | UpsertGridConnectionConfigXAI | UpsertGridConnectionConfigVertex - | UpsertGridConnectionConfigBedrock, + | UpsertGridConnectionConfigBedrock + | UpsertGridConnectionConfigAzure, Field( description="Complete new connection configuration, replacing the current one. The provider must match the connection and is immutable.", discriminator="provider", @@ -9916,15 +11254,6 @@ class UpdateGridConnectionRequest(BaseModel): ] -class GridClassifiersResponse(BaseModel): - items: Annotated[ - list[GridClassifier], Field(description="Items in this page.", title="Items") - ] - pagination: Annotated[ - PaginationResponse, Field(description="Pagination metadata for the page.") - ] - - class GridRouteClassifiersResponse(BaseModel): items: Annotated[ list[GridRouteClassifier], @@ -9985,7 +11314,7 @@ class GridMachineUsersResponse(BaseModel): ] -class Name5(RootModel[str]): +class Name12(RootModel[str]): root: Annotated[ str | None, Field( @@ -10003,7 +11332,7 @@ class CreateGridMachineUserAPIKeyRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name5 | None, + Name12 | None, Field( description="Name of the API key: lowercase letters, numbers, and hyphens, at most 255 characters, and unique among the machine user's active keys. Defaults to a name derived from the machine user's.", examples=["production"], @@ -10012,7 +11341,7 @@ class CreateGridMachineUserAPIKeyRequest(BaseModel): ] = None -class TeamId7(RootModel[str]): +class TeamId8(RootModel[str]): root: Annotated[ str | None, Field( @@ -10029,7 +11358,7 @@ class CreateGridMachineUserRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId7 | None, + TeamId8 | None, Field( description="Identifier of the team that owns the machine user. Defaults to your only team, if you belong to exactly one.", examples=["abc1234"], @@ -10107,7 +11436,7 @@ class GridMachineUserTombstone(BaseModel): ] -class Name6(RootModel[str]): +class Name13(RootModel[str]): root: Annotated[ str | None, Field( @@ -10124,7 +11453,7 @@ class UpdateGridMachineUserRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name6 | None, + Name13 | None, Field( description="Name of the machine user, unique within its team. At most 255 characters. Omit to keep it.", title="Name", @@ -10390,7 +11719,7 @@ class EffectiveRateLimit(BaseModel): ] -class Name7(RootModel[str]): +class Name14(RootModel[str]): root: Annotated[ str | None, Field( @@ -10404,7 +11733,7 @@ class Name7(RootModel[str]): class GroupMetadata(BaseModel): name: Annotated[ - Name7 | None, + Name14 | None, Field( description="Optional display name for the group.", examples=["Acme prod"], @@ -10508,7 +11837,7 @@ class CreateGroupHierarchy(BaseModel): class UpdateGroupMetadata(BaseModel): name: Annotated[ - Name7 | None, + Name14 | None, Field( description="Optional display name for the group.", examples=["Acme prod"], @@ -11369,6 +12698,7 @@ class GetAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY", ] | str ] @@ -11482,6 +12812,7 @@ class GetModelsAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY", ] | str ] @@ -11725,6 +13056,43 @@ class GetModelsDeploymentsStartupsParams(BaseModel): ] = None +class GetModelsDeploymentsReplicasParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + statuses: Annotated[ + list[ + Literal[ + "STARTING", + "ACTIVE", + "UNHEALTHY", + "TERMINATING", + "TERMINATED", + "UNKNOWN", + ] + | str + ] + | None, + Field( + description="Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + title="Statuses", + ), + ] = None + + class GetModelsEnvironmentsLogsParams(BaseModel): start_epoch_millis: Annotated[ int | None, @@ -11908,6 +13276,43 @@ class GetModelsEnvironmentsStartupsParams(BaseModel): ] = None +class GetModelsEnvironmentsReplicasParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + statuses: Annotated[ + list[ + Literal[ + "STARTING", + "ACTIVE", + "UNHEALTHY", + "TERMINATING", + "TERMINATED", + "UNKNOWN", + ] + | str + ] + | None, + Field( + description="Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + title="Statuses", + ), + ] = None + + class GetChainsAuditLogsParams(BaseModel): cursor: Annotated[ str | None, @@ -11961,6 +13366,7 @@ class GetChainsAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY", ] | str ] @@ -12301,6 +13707,13 @@ class GetModelApisMetricsParams(BaseModel): title="Metrics", ), ] = None + team_ids: Annotated[ + list[str] | None, + Field( + description="Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", + title="Team Ids", + ), + ] = None class GetBillingModelApisParams(BaseModel): @@ -12410,6 +13823,46 @@ class GetBillingToolCallUsageParams(BaseModel): ] = None +class GetAccessIdentityProvidersParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + name: Annotated[ + Name2 | None, + Field( + description="Only the provider with this name, ignoring case", title="Name" + ), + ] = None + predefined_kind: Annotated[ + Literal[ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS", + ] + | str + | None, + Field(description="Only this predefined provider's issuers"), + ] = None + + class GetGridRoutesUsageParams(BaseModel): cursor: Annotated[ str | None, @@ -12450,12 +13903,20 @@ class GetGridRoutesUsageParams(BaseModel): ] = None group_by: Annotated[ list[ - Literal["USER", "TEAM", "MODEL", "PROVIDER", "INTELLIGENT_ROUTE", "HARNESS"] + Literal[ + "USER", + "TEAM", + "MODEL", + "PROVIDER", + "INTELLIGENT_ROUTE", + "HARNESS", + "API_KEY", + ] | str ] | None, Field( - description="Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", + description="Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", title="Group By", ), ] = None @@ -12483,6 +13944,7 @@ class GetGridRoutesUsageParams(BaseModel): "VERTEX", "OPENAI_COMPATIBLE", "BEDROCK", + "AZURE", ] | str ] @@ -12499,6 +13961,13 @@ class GetGridRoutesUsageParams(BaseModel): title="Harnesses", ), ] = None + api_key_prefixes: Annotated[ + list[str] | None, + Field( + description="Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", + title="Api Key Prefixes", + ), + ] = None class GetSandboxMetricsParams(BaseModel): @@ -12970,6 +14439,27 @@ class AuditLogEventEnvironmentUpdated(BaseModel): previous_settings: AuditLogEventEnvironmentSettings | None +class AuditLogEventIdentityProviderCreated(BaseModel): + event_type: Annotated[ + Literal["IDENTITY_PROVIDER_CREATED"], Field(title="Event Type") + ] + identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] + name: Annotated[str, Field(title="Name")] + description: Annotated[ + str | None, + Field( + description="Null when the provider was added without one.", + title="Description", + ), + ] = None + predefined: Annotated[ + AuditLogEventPredefinedIdentityProviderConfig, + Field( + description="The provider's settings, as the identity provider resource returns them." + ), + ] + + class AuditLogEventModelDeployed(BaseModel): event_type: Annotated[Literal["MODEL_DEPLOYED"], Field(title="Event Type")] model_id: Annotated[str, Field(title="Model Id")] @@ -13062,10 +14552,31 @@ class AuditLogEventModelPromotionControlAction(BaseModel): ] | str, Field( - description="User-initiated promotion control signal recorded on a promotion-control event.", - title="AuditLogPromotionControlActionV1", + description="User-initiated promotion control signal recorded on a promotion-control event.", + title="AuditLogPromotionControlActionV1", + ), + ] + + +class AuditLogEventServiceAccountCreated(BaseModel): + event_type: Annotated[Literal["SERVICE_ACCOUNT_CREATED"], Field(title="Event Type")] + service_account_id: Annotated[str, Field(title="Service Account Id")] + name: Annotated[str, Field(title="Name")] + description: Annotated[ + str | None, + Field( + description="Null when the account was created without one.", + title="Description", + ), + ] = None + owner_team_id: Annotated[ + str | None, + Field( + description="The team that owns the account. Null for an organization account.", + title="Owner Team Id", ), - ] + ] = None + preset_permissions: AuditLogEventServiceAccountPresetPermissions class Deployment(BaseModel): @@ -13158,6 +14669,13 @@ class Deployment(BaseModel): description="Effective request backpressure settings for the deployment." ), ] + failure_reason: Annotated[ + str | None, + Field( + description="Why the deployment failed. Set only when the status is DEPLOY_FAILED; null otherwise.", + title="Failure Reason", + ), + ] = None class CreatedModelDeployment(BaseModel): @@ -13542,10 +15060,10 @@ class TrafficRoutingRuleUpsert(BaseModel): sampling_mode: Annotated[ Literal["RANDOM", "USER_SESSION"] | str, Field( - description="How requests are picked for shadowing", + description="How requests are picked for shadowing. Defaults to USER_SESSION.", title="TrafficRoutingRuleShadowSamplingModeV1", ), - ] + ] = "USER_SESSION" propagate_client_cancellation: Annotated[ bool, Field( @@ -13915,7 +15433,14 @@ class UpdateChainletEnvironmentInstanceTypeResponse(BaseModel): ] +class TrainingBDNConfigResponse(BaseModel): + mounts: Annotated[list[TrainingBDNMountResponse] | None, Field(title="Mounts")] = ( + None + ) + + class TrainingJob(BaseModel): + bdn: TrainingBDNConfigResponse | None = None id: Annotated[ str, Field(description="Unique identifier of the training job.", title="Id") ] @@ -14226,6 +15751,15 @@ class RegistrySecretDockerAuth(BaseModel): ] +class TrainingBDNConfig(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + mounts: Annotated[ + list[TrainingBDNMount] | None, Field(max_length=32, title="Mounts") + ] = None + + class CreateTrainingJobResponse(BaseModel): training_job: Annotated[TrainingJob, Field(description="The created training job.")] @@ -14266,35 +15800,63 @@ class TrainingJobMetrics(BaseModel): gpu_memory_usage_bytes: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + description="A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Memory Usage Bytes", ), ] gpu_utilization: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + description="A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Utilization", ), ] + gpu_temperature_celsius: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Temperature Celsius", + ), + ] + gpu_power_usage_watts: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Power Usage Watts", + ), + ] + gpu_tensor_core_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Tensor Core Utilization", + ), + ] + gpu_memory_bandwidth_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Memory Bandwidth Utilization", + ), + ] cpu_usage: Annotated[ list[TrainingJobMetric], Field( - description="The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + description="The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Usage", ), ] cpu_memory_usage_bytes: Annotated[ list[TrainingJobMetric], Field( - description="The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + description="The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Memory Usage Bytes", ), ] ephemeral_storage: Annotated[ StorageMetrics, Field( - description="The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + description="The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." ), ] @@ -14310,35 +15872,63 @@ class GetTrainingJobMetricsResponse(BaseModel): gpu_memory_usage_bytes: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + description="A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Memory Usage Bytes", ), ] gpu_utilization: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + description="A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Gpu Utilization", ), ] + gpu_temperature_celsius: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Temperature Celsius", + ), + ] + gpu_power_usage_watts: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Power Usage Watts", + ), + ] + gpu_tensor_core_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Tensor Core Utilization", + ), + ] + gpu_memory_bandwidth_utilization: Annotated[ + dict[str, list[TrainingJobMetric]], + Field( + description="A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + title="Gpu Memory Bandwidth Utilization", + ), + ] cpu_usage: Annotated[ list[TrainingJobMetric], Field( - description="The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + description="The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Usage", ), ] cpu_memory_usage_bytes: Annotated[ list[TrainingJobMetric], Field( - description="The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + description="The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", title="Cpu Memory Usage Bytes", ), ] ephemeral_storage: Annotated[ StorageMetrics, Field( - description="The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + description="The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." ), ] training_job: Annotated[TrainingJob, Field(description="The training job.")] @@ -14444,12 +16034,6 @@ class CreateLoopsRunResponse(BaseModel): run: LoopsRun -class GetLoopsRunResponse(BaseModel): - run: Annotated[ - LoopsRun, Field(description="The Loops run with its associated sampler.") - ] - - class LoopsCheckpoint(BaseModel): checkpoint_id: Annotated[ str, Field(description="The ID of the checkpoint.", title="Checkpoint Id") @@ -14507,6 +16091,30 @@ class LoopsCheckpoint(BaseModel): title="TrainerCheckpointTarget", ), ] + expires_at: Annotated[ + AwareDatetime | None, + Field( + description="When the checkpoint expires and is deleted, set from the TTL it was saved with. Null means it's kept until you delete it. A checkpoint that's still in use when it expires, for example deployed, is deleted once it's released.", + title="Expires At", + ), + ] + + +class DeleteLoopsRunResponse(BaseModel): + id: Annotated[str, Field(description="The deleted Loops run ID.", title="Id")] + kept_checkpoints: Annotated[ + list[LoopsCheckpoint], + Field( + description="The run's checkpoints that were not deleted because something still uses them, such as a deployment. They stay usable until that stops.", + title="Kept Checkpoints", + ), + ] + + +class GetLoopsRunResponse(BaseModel): + run: Annotated[ + LoopsRun, Field(description="The Loops run with its associated sampler.") + ] class ListLoopsCheckpointsResponse(BaseModel): @@ -15351,7 +16959,7 @@ class DedicatedUsage(BaseModel): subtotal: Annotated[ float | Subtotal5, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", title="Subtotal", ), ] @@ -15428,7 +17036,7 @@ class TrainingUsage(BaseModel): subtotal: Annotated[ float | Subtotal13, Field( - description="Subtotal cost in dollars after applying credits used", + description="Usage charges in dollars before applying credits", title="Subtotal", ), ] @@ -15437,7 +17045,7 @@ class TrainingUsage(BaseModel): Field(description="Credits applied in dollars", title="Credits Used"), ] total: Annotated[ - float | Total, Field(description="Total cost in dollars", title="Total") + float | Total3, Field(description="Total cost in dollars", title="Total") ] minutes: Annotated[int, Field(description="Total minutes used", title="Minutes")] breakdown: Annotated[ @@ -15446,6 +17054,137 @@ class TrainingUsage(BaseModel): ] = None +class ServiceAccountPresetPermissions(BaseModel): + type: Annotated[ + Literal[ + "WORKSPACE_MANAGE_ALL", + "WORKSPACE_INVOKE", + "WORKSPACE_EXPORT_METRICS", + "WORKSPACE_MANAGE_API_KEYS", + "WORKSPACE_INVOKE_MODEL_APIS", + ] + | str, + Field( + description="What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + examples=["WORKSPACE_MANAGE_ALL"], + title="ServiceAccountPresetTypeV1", + ), + ] + model_ids: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + examples=[["abcd1234"]], + title="Model Ids", + ), + ] = None + environment_names: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + examples=[["production"]], + title="Environment Names", + ), + ] = None + model_api_slugs: Annotated[ + list[str] | None, + Field( + description="WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + examples=[["my-model-api"]], + title="Model Api Slugs", + ), + ] = None + + +class ServiceAccount(BaseModel): + id: Annotated[str, Field(description="Service account ID", title="Id")] + name: Annotated[ + str, Field(description="Name, unique in the organization", title="Name") + ] + description: Annotated[ + str | None, Field(description="Description", title="Description") + ] = None + team_id: Annotated[ + str | None, + Field( + description="The team that owns the account. Null for an organization account.", + title="Team Id", + ), + ] = None + preset_permissions: Annotated[ + ServiceAccountPresetPermissions, + Field( + description="What the service account may do. Temporary; may be removed once fine-grained access control is available." + ), + ] + disabled: Annotated[ + bool, + Field( + description="Whether the account is disabled. A disabled account can't be used.", + title="Disabled", + ), + ] + last_used_at: Annotated[ + AwareDatetime | None, + Field( + description="Last time a request authenticated as this account, to within an hour. Null until the first.", + title="Last Used At", + ), + ] = None + created_at: Annotated[ + AwareDatetime, + Field(description="Time the account was created", title="Created At"), + ] + updated_at: Annotated[ + AwareDatetime, + Field(description="Time the account was last updated", title="Updated At"), + ] + + +class ServiceAccounts(BaseModel): + items: Annotated[ + list[ServiceAccount], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + +class IdentityProvider(BaseModel): + id: Annotated[str, Field(description="Identity provider ID", title="Id")] + name: Annotated[ + str, Field(description="Name, unique in the organization", title="Name") + ] + description: Annotated[ + str | None, Field(description="Description", title="Description") + ] = None + predefined: Annotated[ + PredefinedIdentityProviderConfig, + Field(description="Settings of the predefined provider"), + ] + created_by: Annotated[ + str, + Field(description="ID of the user who added the provider", title="Created By"), + ] + created_at: Annotated[ + AwareDatetime, + Field(description="Time the provider was added", title="Created At"), + ] + updated_at: Annotated[ + AwareDatetime, + Field(description="Time the provider was last updated", title="Updated At"), + ] + + +class IdentityProviders(BaseModel): + items: Annotated[ + list[IdentityProvider], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + class ExploreCost(BaseModel): input: Annotated[ float | None, @@ -15554,28 +17293,111 @@ class ExploreMetadataResponse(BaseModel): ] +class GridRouteMetadata(BaseModel): + slug: Annotated[ + str | None, + Field( + description="Metadata slug, e.g. 'anthropic/claude-opus-4'; null for rows without one.", + title="Slug", + ), + ] + display_name: Annotated[ + str | None, + Field(description="Model display name, when available.", title="Display Name"), + ] + release_date: Annotated[ + date_aliased | None, + Field( + description="Model release date. Month-only source dates use the first day of that month.", + title="Release Date", + ), + ] + provider: Annotated[ + str | None, + Field( + description="Provider key derived from the slug prefix, e.g. 'anthropic'; null for unprefixed slugs.", + title="Provider", + ), + ] + context_window: Annotated[ + int | None, + Field(description="Total context window in tokens.", title="Context Window"), + ] + max_output_tokens: Annotated[ + int | None, + Field( + description="Maximum output tokens per response.", title="Max Output Tokens" + ), + ] + input_modalities: Annotated[ + list[str], + Field(description="Accepted input modalities.", title="Input Modalities"), + ] + tools: Annotated[ + bool | None, + Field(description="Whether the model supports tool calling.", title="Tools"), + ] + reasoning_effort_levels: Annotated[ + list[str] | None, + Field( + description="Reasoning effort levels the model supports.", + title="Reasoning Effort Levels", + ), + ] + parallel_tool_calls: Annotated[ + bool | None, + Field( + description="Whether the model supports parallel tool calls.", + title="Parallel Tool Calls", + ), + ] + supported_api_formats: Annotated[ + ExploreMetadataAPIFormats | None, + Field(description="API formats the model supports."), + ] + cost: Annotated[ + ExploreCost | None, + Field(description="Provider list prices in USD per 1M tokens, when available."), + ] + api_formats: Annotated[ + list[Literal["messages", "responses", "chat_completions"] | str], + Field( + description="API formats the route supports, most preferred first: `chat_completions`, `messages`, `responses` for a BASETEN_MODEL_API target and `messages`, `responses`, `chat_completions` for any other target, keeping only the formats the route supports. Never empty.", + min_length=1, + title="Api Formats", + ), + ] + + class GridRoute(BaseModel): id: Annotated[str, Field(description="Stable route identifier.", title="Id")] name: Annotated[ str, Field( - description="Name to send in the inference request's model field.", + description="Name to send in the inference request's `model` field. Unique within the team; immutable.", title="Name", ), ] - team_id: Annotated[ - str, Field(description="Identifier of the owning team.", title="Team Id") - ] - team_name: Annotated[ - str, Field(description="Name of the owning team.", title="Team Name") - ] display_name: Annotated[ str, Field( - description="Display label, defaulting to the route name.", + description="Display label, defaulting to the route's name.", title="Display Name", ), ] + aliases: Annotated[ + list[GridRouteAlias] | None, + Field( + description="The route's other names, one per purpose. Empty for routes created before aliases existed.", + title="Aliases", + ), + ] = None + team_id: Annotated[ + str, Field(description="Identifier of the owning team.", title="Team Id") + ] + team_name: Annotated[ + str, Field(description="Name of the owning team.", title="Team Name") + ] description: Annotated[ str, Field( @@ -15587,7 +17409,6 @@ class GridRoute(BaseModel): Annotated[ GridRouteTargetBasetenModelAPI | GridRouteTargetConnection - | GridRouteTargetClassifier | GridRouteTargetIntelligent, Field( description="Configured upstream target.", @@ -15599,9 +17420,9 @@ class GridRoute(BaseModel): Field(union_mode="left_to_right"), ] metadata: Annotated[ - ExploreMetadata | None, + GridRouteMetadata | None, Field( - description="Resolved model metadata; for a router, the envelope of its allowed routes' metadata. Null when nothing is linked." + description="Resolved model metadata; for an intelligent route, the envelope of its servable models' metadata. Null when nothing is linked or the metadata has no supported API formats." ), ] invoke_url: Annotated[ @@ -16367,6 +18188,16 @@ class AuditLogEntry(BaseModel): "TELEMETRY_EXPORT_CREATED", "TELEMETRY_EXPORT_UPDATED", "TELEMETRY_EXPORT_DELETED", + "SERVICE_ACCOUNT_CREATED", + "SERVICE_ACCOUNT_UPDATED", + "SERVICE_ACCOUNT_DELETED", + "IDENTITY_PROVIDER_CREATED", + "IDENTITY_PROVIDER_UPDATED", + "IDENTITY_PROVIDER_DELETED", + "TRUST_RULE_CREATED", + "TRUST_RULE_UPDATED", + "TRUST_RULE_DELETED", + "ORGANIZATION_API_KEY_SETTINGS_UPDATED", ] | str, Field( @@ -16401,6 +18232,7 @@ class AuditLogEntry(BaseModel): | AuditLogEventApiKeyCreated | AuditLogEventApiKeyDeleted | AuditLogEventApiKeyLifetimeLimitsUpdated + | AuditLogEventOrganizationApiKeySettingsUpdated | AuditLogEventGatewayEndpointCreated | AuditLogEventGatewayEndpointUpdated | AuditLogEventGatewayEndpointDeleted @@ -16434,7 +18266,16 @@ class AuditLogEntry(BaseModel): | AuditLogEventVolumeUpdated | AuditLogEventTelemetryExportCreated | AuditLogEventTelemetryExportUpdated - | AuditLogEventTelemetryExportDeleted, + | AuditLogEventTelemetryExportDeleted + | AuditLogEventServiceAccountCreated + | AuditLogEventServiceAccountUpdated + | AuditLogEventServiceAccountDeleted + | AuditLogEventIdentityProviderCreated + | AuditLogEventIdentityProviderUpdated + | AuditLogEventIdentityProviderDeleted + | AuditLogEventTrustRuleCreated + | AuditLogEventTrustRuleUpdated + | AuditLogEventTrustRuleDeleted, Field( description="Structured details of the action, discriminated by `event_type`.", discriminator="event_type", @@ -17480,6 +19321,7 @@ class CreateTrainingJobImage(BaseModel): class CreateTrainingJob(BaseModel): + bdn: TrainingBDNConfig | None = None image: Annotated[ CreateTrainingJobImage, Field(examples=[{"base_image": "hello-world", "docker_auth": None}]), diff --git a/baseten/client/modelconfig/__init__.py b/baseten/client/modelconfig/__init__.py index 3215dcf..672e898 100644 --- a/baseten/client/modelconfig/__init__.py +++ b/baseten/client/modelconfig/__init__.py @@ -17,6 +17,8 @@ BDNConfig, BDNHotload, BDNVolumeMount, + BEIConfiguration, + BEIModelConfiguration, Build, CheckpointList, CheckpointRepository, @@ -74,6 +76,8 @@ "BDNConfig", "BDNHotload", "BDNVolumeMount", + "BEIConfiguration", + "BEIModelConfiguration", "BaseImage", "Build", "CheckpointList", diff --git a/baseten/client/modelconfig/_models.py b/baseten/client/modelconfig/_models.py index 64ca410..05b942a 100644 --- a/baseten/client/modelconfig/_models.py +++ b/baseten/client/modelconfig/_models.py @@ -71,6 +71,25 @@ class BDNVolumeMount(BaseModel): ] = None +class BEIModelConfiguration(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + checkpoint: Annotated[ + str, + Field( + description="Hugging Face repository to download through weights, or an absolute path to manually mounted weights.", + min_length=1, + title="Checkpoint", + ), + ] + revision: Annotated[str | None, Field(title="Revision")] = None + served_model_name: Annotated[str | None, Field(title="Served Model Name")] = None + quantization: Annotated[ + Literal["none", "fp8", "mxfp8", "nvfp4"] | str, Field(title="Quantization") + ] = "none" + + class DockerServer(BaseModel): model_config = ConfigDict( extra="allow", @@ -85,7 +104,7 @@ class DockerServer(BaseModel): server_port: Annotated[ int, Field( - description="The port where the server runs. Port 8080 is reserved by Baseten's internal reverse proxy and cannot be used.", + description="The port where the server runs. Port 8080 is reserved when Truss installs its internal reverse proxy; no_build deployments can use 8080.", title="Server Port", ), ] @@ -234,14 +253,14 @@ class HealthChecks(BaseModel): restart_threshold_seconds: Annotated[ int | None, Field( - description="The time in seconds after which an unhealthy instance is restarted. Defaults to platform-determined value when not set.", + description="The time in seconds after which an unhealthy instance is restarted. With trt_llm, defaults to 60 and must be <= 60. Otherwise defaults to platform-determined value when not set.", title="Restart Threshold Seconds", ), ] = None stop_traffic_threshold_seconds: Annotated[ int | None, Field( - description="The time in seconds after which traffic is stopped to an unhealthy instance. Defaults to platform-determined value when not set.", + description="The time in seconds after which traffic is stopped to an unhealthy instance. With trt_llm, defaults to 30 and must be <= 30. Otherwise defaults to platform-determined value when not set.", title="Stop Traffic Threshold Seconds", ), ] = None @@ -318,7 +337,7 @@ class Resources(BaseModel): accelerator: Annotated[ str | None, Field( - description="The GPU type for your instance. To request multiple GPUs, use the ':' operator (e.g. L4:4).", + description="The accelerator type for your instance. To request multiple accelerators, use the ':' operator (e.g. L4:4).", examples=["A100", "T4:2", "H100:8"], ), ] = None @@ -590,6 +609,17 @@ class BDNConfig(BaseModel): ] = None +class BEIConfiguration(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + backend: Annotated[Literal["nvidia", "tpu"] | str, Field(title="Backend")] + version_override: Annotated[str | None, Field(title="Version Override")] = None + configuration: Annotated[ + list[BEIModelConfiguration], Field(min_length=1, title="Configuration") + ] + + class BISLLM(BaseModel): model_config = ConfigDict( extra="allow", @@ -908,7 +938,8 @@ class WeightsAuth(BaseModel): ), ] = None auth_method: Annotated[ - Literal["CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", "AWS_ASSUME_ROLE"] | str, + Literal["CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", "HF_OIDC", "AWS_ASSUME_ROLE"] + | str, Field( description="Authentication method for downloading weights from the source.", title="WeightsAuthMethod", @@ -921,6 +952,13 @@ class WeightsAuth(BaseModel): title="Auth Secret Name", ), ] = None + hf_oidc_resource: Annotated[ + str | None, + Field( + description="Hugging Face repository (namespace/name) or username for OIDC token exchange.", + title="Hf Oidc Resource", + ), + ] = None class WeightsSource(BaseModel): @@ -1136,6 +1174,12 @@ class ModelConfig(BaseModel): TRTLLMConfigurationV1 | TRTLLMConfigurationV2 | None, Field(description="TensorRT-LLM configuration for optimized LLM inference."), ] = None + bei: Annotated[ + BEIConfiguration | None, + Field( + description="BEIv3 encoder serving without an engine-build job. Hugging Face checkpoints use runtime weights mounts. Requires explicit restart and stop-traffic health thresholds of 1–60 seconds." + ), + ] = None training_checkpoints: Annotated[ CheckpointList | None, Field(description="Configuration for deploying from training checkpoints."), diff --git a/scripts/apigen/specs/config.schema.json b/scripts/apigen/specs/config.schema.json index b9fbb1d..dc08074 100644 --- a/scripts/apigen/specs/config.schema.json +++ b/scripts/apigen/specs/config.schema.json @@ -167,6 +167,96 @@ "title": "BDNVolumeMount", "type": "object" }, + "BEIConfiguration": { + "additionalProperties": true, + "properties": { + "backend": { + "enum": [ + "nvidia", + "tpu" + ], + "title": "Backend", + "type": "string" + }, + "version_override": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Version Override" + }, + "configuration": { + "items": { + "$ref": "#/$defs/BEIModelConfiguration" + }, + "minItems": 1, + "title": "Configuration", + "type": "array" + } + }, + "required": [ + "backend", + "configuration" + ], + "title": "BEIConfiguration", + "type": "object" + }, + "BEIModelConfiguration": { + "additionalProperties": true, + "properties": { + "checkpoint": { + "description": "Hugging Face repository to download through weights, or an absolute path to manually mounted weights.", + "minLength": 1, + "title": "Checkpoint", + "type": "string" + }, + "revision": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Revision" + }, + "served_model_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Served Model Name" + }, + "quantization": { + "default": "none", + "enum": [ + "none", + "fp8", + "mxfp8", + "nvfp4" + ], + "title": "Quantization", + "type": "string" + } + }, + "required": [ + "checkpoint" + ], + "title": "BEIModelConfiguration", + "type": "object" + }, "BISLLM": { "additionalProperties": true, "description": "Configuration options for BIS LLM deployments.", @@ -519,7 +609,7 @@ "title": "Start Command" }, "server_port": { - "description": "The port where the server runs. Port 8080 is reserved by Baseten's internal reverse proxy and cannot be used.", + "description": "The port where the server runs. Port 8080 is reserved when Truss installs its internal reverse proxy; no_build deployments can use 8080.", "title": "Server Port", "type": "integer" }, @@ -783,7 +873,7 @@ } ], "default": null, - "description": "The time in seconds after which an unhealthy instance is restarted. Defaults to platform-determined value when not set.", + "description": "The time in seconds after which an unhealthy instance is restarted. With trt_llm, defaults to 60 and must be <= 60. Otherwise defaults to platform-determined value when not set.", "title": "Restart Threshold Seconds" }, "stop_traffic_threshold_seconds": { @@ -796,7 +886,7 @@ } ], "default": null, - "description": "The time in seconds after which traffic is stopped to an unhealthy instance. Defaults to platform-determined value when not set.", + "description": "The time in seconds after which traffic is stopped to an unhealthy instance. With trt_llm, defaults to 30 and must be <= 30. Otherwise defaults to platform-determined value when not set.", "title": "Stop Traffic Threshold Seconds" }, "startup_threshold_seconds": { @@ -1059,7 +1149,7 @@ }, "accelerator": { "$ref": "#/$defs/AcceleratorSpec", - "description": "The GPU type for your instance. To request multiple GPUs, use the ':' operator (e.g. L4:4).", + "description": "The accelerator type for your instance. To request multiple accelerators, use the ':' operator (e.g. L4:4).", "examples": [ "A100", "T4:2", @@ -2157,6 +2247,19 @@ "default": null, "description": "Baseten secret name containing credentials for accessing the source.", "title": "Auth Secret Name" + }, + "hf_oidc_resource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Hugging Face repository (namespace/name) or username for OIDC token exchange.", + "title": "Hf Oidc Resource" } }, "required": [ @@ -2171,6 +2274,7 @@ "CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", + "HF_OIDC", "AWS_ASSUME_ROLE" ], "title": "WeightsAuthMethod", @@ -2482,6 +2586,18 @@ "default": null, "description": "TensorRT-LLM configuration for optimized LLM inference." }, + "bei": { + "anyOf": [ + { + "$ref": "#/$defs/BEIConfiguration" + }, + { + "type": "null" + } + ], + "default": null, + "description": "BEIv3 encoder serving without an engine-build job. Hugging Face checkpoints use runtime weights mounts. Requires explicit restart and stop-traffic health thresholds of 1\u201360 seconds." + }, "training_checkpoints": { "anyOf": [ { diff --git a/scripts/apigen/specs/management.json b/scripts/apigen/specs/management.json index e859282..977a7ce 100644 --- a/scripts/apigen/specs/management.json +++ b/scripts/apigen/specs/management.json @@ -1494,7 +1494,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/audit_logs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'direction': 'DESC', 'search': None, 'start_epoch_millis': None, 'end_epoch_millis': None}\n)\n\nprint(response.text)" } ], - "description": "Returns audit-log entries across the workspace, newest first, covering models, chains, and workspace-level actions. Use the filters to narrow by event type, actor, resource, environment, source, or time window, and the cursor to page. In workspaces with multiple teams, only organization admins can read the workspace audit log.", + "description": "Returns audit-log entries across the workspace, newest first, covering models, chains, and workspace-level actions. Use the filters to narrow by event type, actor, resource, environment, source, or time window, and the cursor to page. Requires a personal API key; team API keys can't read the workspace audit log. In workspaces with multiple teams, only organization admins can read the workspace audit log.", "parameters": [ { "name": "cursor", @@ -3831,6 +3831,88 @@ } ] }, + "/v1/models/{model_id}/deployments/{deployment_id}/replicas": { + "get": { + "summary": "Lists replicas for a deployment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + } + ], + "description": "Includes terminated replicas and lifecycle information without metrics. Replicas are ordered by creation time, oldest first, with replica ID as a tie-breaker. For subsequent pages, pass pagination.cursor as cursor with unchanged filters. Cursors expire after one hour. Replica status may change between requests.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "statuses", + "in": "query", + "required": false, + "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + "schema": { + "items": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1" + }, + "title": "Statuses", + "type": "array" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicasV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/model_id" + }, + { + "$ref": "#/components/parameters/deployment_id" + } + ] + }, "/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}": { "delete": { "summary": "Terminates a replica in a deployment", @@ -3844,7 +3926,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Terminates a deployment replica and returns the termination status.", + "description": "Terminates a deployment replica and returns the termination status. Returns 404 if no replica matches the replica ID. Returns 400 without requesting termination if multiple replicas match the replica ID.", "responses": { "200": { "description": "", @@ -3868,7 +3950,33 @@ { "$ref": "#/components/parameters/replica_id" } - ] + ], + "get": { + "summary": "Gets a replica in a deployment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Returns lifecycle information without metrics, including for terminated replicas. Returns 404 if the replica does not exist in the specified deployment. Returns 400 if multiple replicas match the replica ID.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicaV1" + } + } + } + } + } + } }, "/v1/models/{model_id}/deployments/{deployment_id}/ssh/sign": { "post": { @@ -4980,6 +5088,153 @@ } ] }, + "/v1/models/{model_id}/environments/{env_name}/replicas": { + "get": { + "summary": "Lists replicas for an environment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + } + ], + "description": "Includes retained terminated replicas from deployments active in the preceding hour. Orders replicas oldest first, with replica ID breaking ties. Pass pagination.cursor with unchanged filters for subsequent pages. Cursors pin deployment membership and expire after one hour.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "statuses", + "in": "query", + "required": false, + "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + "schema": { + "items": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1" + }, + "title": "Statuses", + "type": "array" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicasV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/model_id" + }, + { + "$ref": "#/components/parameters/env_name" + } + ] + }, + "/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}": { + "delete": { + "summary": "Terminates a replica in an environment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Requests replica termination in the environment's current deployment. Returns 404 if the environment has no current deployment or no replica matches the replica ID. Returns 400 without requesting termination if multiple replicas in the current deployment match the replica ID.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TerminateReplicaResponseV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/model_id" + }, + { + "$ref": "#/components/parameters/env_name" + }, + { + "$ref": "#/components/parameters/replica_id" + } + ], + "get": { + "summary": "Gets a replica in an environment", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Searches deployments active in the environment during the preceding hour. Includes retained terminated replicas. Returns 404 if the replica is outside this scope. Returns 400 if multiple replicas match the replica ID.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeploymentReplicaV1" + } + } + } + } + } + } + }, "/v1/chains": { "get": { "summary": "Gets all chains", @@ -6116,11 +6371,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/training_projects/{training_project_id}/jobs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"training_job\": {\n \"image\": {\n \"base_image\": \"hello-world\",\n \"docker_auth\": null\n },\n \"compute\": {\n \"node_count\": 1,\n \"cpu_count\": 1,\n \"memory\": \"2Gi\",\n \"accelerator\": {\n \"accelerator\": \"H100\",\n \"count\": 2\n },\n \"availability_model\": \"spot\"\n },\n \"runtime\": {\n \"start_commands\": [\n \"python main.py\"\n ],\n \"environment_variables\": {\n \"API_KEY\": \"your_api_key_here\",\n \"PATH\": \"/usr/bin\"\n },\n \"enable_cache\": true,\n \"cache_config\": {\n \"enable_legacy_hf_mount\": true,\n \"enabled\": true,\n \"mount_base_path\": \"/root/.cache\",\n \"persistent_home\": false,\n \"require_cache_affinity\": true\n },\n \"checkpointing_config\": {\n \"enabled\": true,\n \"checkpoint_path\": \"/mnt/ckpts\",\n \"volume_size_gib\": 10\n },\n \"load_checkpoint_config\": null\n },\n \"name\": \"gpt-oss-job\",\n \"truss_user_env\": null,\n \"interactive_session\": null,\n \"weights\": [\n {\n \"allow_patterns\": null,\n \"auth\": null,\n \"auth_secret_name\": null,\n \"ignore_patterns\": null,\n \"mount_location\": \"/app/models/base\",\n \"source\": \"hf://meta-llama/Llama-3-8B@main\"\n }\n ],\n \"enable_baseten_workdir\": false,\n \"priority\": 0\n }\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/training_projects/{training_project_id}/jobs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"training_job\": {\n \"bdn\": {},\n \"image\": {\n \"base_image\": \"hello-world\",\n \"docker_auth\": null\n },\n \"compute\": {\n \"node_count\": 1,\n \"cpu_count\": 1,\n \"memory\": \"2Gi\",\n \"accelerator\": {\n \"accelerator\": \"H100\",\n \"count\": 2\n },\n \"availability_model\": \"spot\"\n },\n \"runtime\": {\n \"start_commands\": [\n \"python main.py\"\n ],\n \"environment_variables\": {\n \"API_KEY\": \"your_api_key_here\",\n \"PATH\": \"/usr/bin\"\n },\n \"enable_cache\": true,\n \"cache_config\": {\n \"enable_legacy_hf_mount\": true,\n \"enabled\": true,\n \"mount_base_path\": \"/root/.cache\",\n \"persistent_home\": false,\n \"require_cache_affinity\": true\n },\n \"checkpointing_config\": {\n \"enabled\": true,\n \"checkpoint_path\": \"/mnt/ckpts\",\n \"volume_size_gib\": 10\n },\n \"load_checkpoint_config\": null\n },\n \"name\": \"gpt-oss-job\",\n \"truss_user_env\": null,\n \"interactive_session\": null,\n \"weights\": [\n {\n \"allow_patterns\": null,\n \"auth\": null,\n \"auth_secret_name\": null,\n \"ignore_patterns\": null,\n \"mount_location\": \"/app/models/base\",\n \"source\": \"hf://meta-llama/Llama-3-8B@main\"\n }\n ],\n \"enable_baseten_workdir\": false,\n \"priority\": 0\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training_projects/{training_project_id}/jobs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'training_job': {'image': {'base_image': 'hello-world', 'docker_auth': None}, 'compute': {'node_count': 1, 'cpu_count': 1, 'memory': '2Gi', 'accelerator': {'accelerator': 'H100', 'count': 2}, 'availability_model': 'spot'}, 'runtime': {'start_commands': ['python main.py'], 'environment_variables': {'API_KEY': 'your_api_key_here', 'PATH': '/usr/bin'}, 'enable_cache': True, 'cache_config': {'enable_legacy_hf_mount': True, 'enabled': True, 'mount_base_path': '/root/.cache', 'persistent_home': False, 'require_cache_affinity': True}, 'checkpointing_config': {'enabled': True, 'checkpoint_path': '/mnt/ckpts', 'volume_size_gib': 10}, 'load_checkpoint_config': None}, 'name': 'gpt-oss-job', 'truss_user_env': None, 'interactive_session': None, 'weights': [{'allow_patterns': None, 'auth': None, 'auth_secret_name': None, 'ignore_patterns': None, 'mount_location': '/app/models/base', 'source': 'hf://meta-llama/Llama-3-8B@main'}], 'enable_baseten_workdir': False, 'priority': 0}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training_projects/{training_project_id}/jobs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'training_job': {'bdn': {}, 'image': {'base_image': 'hello-world', 'docker_auth': None}, 'compute': {'node_count': 1, 'cpu_count': 1, 'memory': '2Gi', 'accelerator': {'accelerator': 'H100', 'count': 2}, 'availability_model': 'spot'}, 'runtime': {'start_commands': ['python main.py'], 'environment_variables': {'API_KEY': 'your_api_key_here', 'PATH': '/usr/bin'}, 'enable_cache': True, 'cache_config': {'enable_legacy_hf_mount': True, 'enabled': True, 'mount_base_path': '/root/.cache', 'persistent_home': False, 'require_cache_affinity': True}, 'checkpointing_config': {'enabled': True, 'checkpoint_path': '/mnt/ckpts', 'volume_size_gib': 10}, 'load_checkpoint_config': None}, 'name': 'gpt-oss-job', 'truss_user_env': None, 'interactive_session': None, 'weights': [{'allow_patterns': None, 'auth': None, 'auth_secret_name': None, 'ignore_patterns': None, 'mount_location': '/app/models/base', 'source': 'hf://meta-llama/Llama-3-8B@main'}], 'enable_baseten_workdir': False, 'priority': 0}}\n)\n\nprint(response.text)" } ], "description": "Creates a training job with the specified configuration.", @@ -7305,11 +7560,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"sampler_num_replicas\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"sampler_num_replicas\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" } ], "description": "Creates a Loops run with an associated sampler in the given session.", @@ -7371,6 +7626,37 @@ ] }, "/v1/loops/runs/{run_id}": { + "delete": { + "summary": "Deletes a Loops run", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/loops/runs/{run_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs/{run_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes a Loops run by ID, deactivating it first if it is active, and deletes its checkpoints. Checkpoints still in use, such as deployed ones, are kept and listed in the response; they stay usable until that use stops. Deletion is permanent, and storage for some checkpoints is reclaimed later.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteLoopsRunResponseV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/run_id" + } + ], "get": { "summary": "Gets a Loops run", "x-codeSamples": [ @@ -7396,12 +7682,7 @@ } } } - }, - "parameters": [ - { - "$ref": "#/components/parameters/run_id" - } - ] + } }, "/v1/loops/trainers": { "post": { @@ -7409,11 +7690,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"scope\": \"default\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"scope\": \"default\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'scope': 'default'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'scope': 'default'}\n)\n\nprint(response.text)" } ], "description": "Creates a trainer-only Loops run in the given session, without a sampler. To sample from it, create a sampler with POST /v1/loops/samplers and pass this run's ID as run_id to pair the two. List and read the trainer through the /v1/loops/runs endpoints.", @@ -7784,6 +8065,39 @@ } } }, + "/v1/loops/checkpoints/{checkpoint_id}": { + "delete": { + "summary": "Deletes a Loops checkpoint", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes a Loops checkpoint by ID and returns its tombstone. The checkpoint disappears from listings and can't be loaded, sampled, or deployed. Deletion is permanent, and storage for some checkpoints is reclaimed later. A checkpoint that is deployed, read by an unfinished LoRA merge, served by an active sampler, or the start of an active run can't be deleted, and the error says which. Deleting an already-deleted checkpoint returns the same tombstone.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoopsCheckpointTombstoneV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/checkpoint_id" + } + ] + }, "/v1/loops/checkpoints/{checkpoint_id}/files": { "get": { "summary": "Gets Loops checkpoint files", @@ -7876,6 +8190,49 @@ } ] }, + "/v1/loops/checkpoints/{checkpoint_id}/ttl": { + "put": { + "summary": "Sets a Loops checkpoint's TTL", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PUT \\\n--url https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}/ttl \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"ttl_seconds\": null\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}/ttl\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PUT\",\n url,\n headers=headers,\n json={'ttl_seconds': None}\n)\n\nprint(response.text)" + } + ], + "description": "Sets when a Loops checkpoint expires, counted from now, or removes its TTL so it's kept until you delete it. An expired checkpoint is deleted within 24 hours. If it's in use when it expires, it's deleted within 24 hours after it stops being used.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetLoopsCheckpointTtlRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoopsCheckpointV1" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/checkpoint_id" + } + ] + }, "/v1/loops/deployments": { "get": { "summary": "Lists Loops deployments", @@ -8115,7 +8472,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/deployments/{deployment_id}/logs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_epoch_millis': None, 'end_epoch_millis': None, 'direction': None, 'limit': None, 'min_level': None}\n)\n\nprint(response.text)" } ], - "description": "Fetches logs from the trainer pods of a Loops deployment. Visible to any member of the deployment's team.", + "description": "Fetches logs from the trainer pods of a Loops deployment. Visible to anyone with training access to the deployment's team.", "parameters": [ { "name": "start_epoch_millis", @@ -8383,11 +8740,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"sampler_num_replicas\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"sampler_num_replicas\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" } ], "description": "Creates a Loops run with an associated sampler in the given session; the run's infrastructure belongs to the given team.", @@ -8421,11 +8778,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"scope\": \"default\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"scope\": \"default\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'scope': 'default'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'scope': 'default'}\n)\n\nprint(response.text)" } ], "description": "Creates a trainer-only Loops run in the given session, without a sampler. To sample from it, create a sampler with POST /v1/loops/samplers and pass this run's ID as run_id to pair the two. List and read the trainer through the /v1/loops/runs endpoints.", @@ -8584,7 +8941,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training/capacity\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Returns GPU capacity limits (baseline and peak) and current usage for the organization.", + "description": "Returns on-demand and spot GPU quotas and current usage for the teams you can view, plus organization-wide totals when you have organization-level access.", "responses": { "200": { "description": "", @@ -8599,7 +8956,7 @@ } }, "patch": { - "summary": "Sets a team's training GPU capacity", + "summary": "Sets a team's training GPU quota", "x-codeSamples": [ { "lang": "bash", @@ -8610,7 +8967,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training/capacity\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'team_id': None, 'gpu_type': None, 'max_gpus': 8}\n)\n\nprint(response.text)" } ], - "description": "Sets the max concurrent GPUs of a given type a team may use. Creates the limit if one doesn't exist for this (team, gpu_type) pair, otherwise updates it in place. Org-admin only: this is a ceiling the org imposes on the team, not something the team manages for itself.", + "description": "Sets a team's GPU quota for a given type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota, and on-demand jobs can borrow past it from the organization's shared pool when one exists. Creates the quota if one doesn't exist for this (team, gpu_type) pair, otherwise updates it in place. Org-admin only: this is a quota the org imposes on the team, not something the team manages for itself.", "requestBody": { "content": { "application/json": { @@ -9170,7 +9527,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/model_apis/{model_api_name}/metrics\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'mode': 'CURRENT', 'start_epoch_millis': None, 'end_epoch_millis': None}\n)\n\nprint(response.text)" } ], - "description": "Gets the metrics for a Model API in the given time range.", + "description": "Gets the metrics for a Model API in the given time range for the teams you can manage, with each series labeled by team_id. Organization admins receive organization-wide metrics by default. For a Model API your lab organization lists, other organizations' consumption is included regardless of team_ids.", "parameters": [ { "name": "mode", @@ -9230,6 +9587,19 @@ "title": "Metrics", "type": "array" } + }, + { + "name": "team_ids", + "in": "query", + "required": false, + "description": "Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", + "schema": { + "items": { + "type": "string" + }, + "title": "Team Ids", + "type": "array" + } } ], "responses": { @@ -9937,7 +10307,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/billing/usage_summary\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" } ], - "description": "Returns billing usage within [start_date, end_date): the start date is inclusive and the end date is exclusive. Both dates are normalized to midnight UTC. Includes dedicated model serving, training, and model APIs usage. The date range must not exceed 31 days.", + "description": "Returns billing usage within [start_date, end_date): the start date is inclusive and the end date is exclusive. Both dates are normalized to midnight UTC. Includes dedicated model serving, training, and model APIs usage. For multi-team organizations, Model APIs usage is split by team. Historical usage without a recorded team is assigned to Default Team. Usage subtotals are before credits; credits are deducted only at the product summary level. The date range must not exceed 31 days.", "parameters": [ { "name": "start_date", @@ -10232,31 +10602,68 @@ } }, "x-stability": "unstable" + }, + "patch": { + "summary": "Updates the authenticated organization", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/organizations/me \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"allow_personal_api_keys\": null,\n \"allow_service_account_api_keys\": null\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/organizations/me\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'allow_personal_api_keys': None, 'allow_service_account_api_keys': None}\n)\n\nprint(response.text)" + } + ], + "description": "Updates settings of the organization of the user making the request. Only organization admins can call it. Omitted fields are unchanged.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOrganizationRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OrganizationInfoV1" + } + } + } + } + }, + "x-stability": "unstable" } }, - "/v1/gateway/events": { + "/v1/service_accounts": { "get": { - "summary": "Lists gateway events", + "summary": "Lists service accounts", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/gateway/events \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/service_accounts \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/gateway/events\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_time': None, 'end_time': None, 'limit': None, 'cursor': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'team_id': None, 'disabled': None}\n)\n\nprint(response.text)" } ], + "description": "Lists the service accounts you administer: every account for an organization admin, and your teams' accounts for a team admin. Workload identity federation tokens act as service accounts.", "parameters": [ { - "name": "start_time", + "name": "cursor", "in": "query", "required": false, - "description": "Inclusive start (ISO 8601, UTC). Required without a cursor.", + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", "schema": { "anyOf": [ { - "format": "date-time", "type": "string" }, { @@ -10264,18 +10671,31 @@ } ], "default": null, - "title": "Start Time" + "title": "Cursor" } }, { - "name": "end_time", + "name": "limit", "in": "query", "required": false, - "description": "Exclusive end (ISO 8601, UTC). Defaults to now.", + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "name", + "in": "query", + "required": false, + "description": "Only the account with this name, ignoring case", "schema": { "anyOf": [ { - "format": "date-time", + "minLength": 1, "type": "string" }, { @@ -10283,71 +10703,43 @@ } ], "default": null, - "title": "End Time" + "title": "Name" } }, { - "name": "limit", + "name": "team_id", "in": "query", "required": false, - "description": "Max events. Default 100, max 1000.", + "description": "Only this team's accounts", "schema": { "anyOf": [ { - "maximum": 1000, - "minimum": 1, - "type": "integer" + "type": "string" }, { "type": "null" } ], "default": null, - "title": "Limit" - } - }, - { - "name": "api_keys", - "in": "query", - "required": false, - "description": "Return only events for these API key prefixes, repeated once per prefix.", - "schema": { - "items": { - "type": "string" - }, - "title": "Api Keys", - "type": "array" + "title": "Team Id" } }, { - "name": "external_entity_ids", + "name": "disabled", "in": "query", "required": false, - "description": "Return only events for these external entity IDs, repeated once per ID.", - "schema": { - "items": { - "type": "string" - }, - "title": "External Entity Ids", - "type": "array" - } - }, - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Next-page cursor. Other parameters are ignored.", + "description": "Only disabled or enabled accounts", "schema": { "anyOf": [ { - "type": "string" + "type": "boolean" }, { "type": "null" } ], "default": null, - "title": "Cursor" + "title": "Disabled" } } ], @@ -10357,28 +10749,192 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayEventsResponseV1" + "$ref": "#/components/schemas/ServiceAccountsV1" } } } } + }, + "x-stability": "unstable" + }, + "post": { + "summary": "Creates a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/service_accounts \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"ci-deployer\",\n \"description\": \"GitHub Actions deploys from acme/models\",\n \"team_id\": \"abcd1234\",\n \"preset_permissions\": {\n \"type\": \"WORKSPACE_MANAGE_ALL\"\n }\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'ci-deployer', 'description': 'GitHub Actions deploys from acme/models', 'team_id': 'abcd1234', 'preset_permissions': {'type': 'WORKSPACE_MANAGE_ALL'}}\n)\n\nprint(response.text)" + } + ], + "description": "Creates a service account that workload identity federation tokens act as. It's enabled at once. Omit `team_id` for an organization account, which only an organization admin can create. A team admin can create accounts for their own team.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateServiceAccountRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/service_accounts/{service_account_id}": { + "delete": { + "summary": "Deletes a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes a disabled service account that no trust rule uses. Disable the account and delete its trust rules first.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/service_account_id" } + ], + "get": { + "summary": "Gets a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "patch": { + "summary": "Updates a service account", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"disabled\": true\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'disabled': True}\n)\n\nprint(response.text)" + } + ], + "description": "Updates the fields you send. Set `disabled` to true to stop the account being used, and back to false to restore it. `preset_permissions` replaces the account's access as a whole. The owning team can't change.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateServiceAccountRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceAccountV1" + } + } + } + } + }, + "x-stability": "unstable" } }, - "/v1/explore/metadata": { + "/v1/access/predefined_identity_providers": { "get": { - "summary": "Lists model metadata", + "summary": "Lists predefined identity providers", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/explore/metadata \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/predefined_identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/explore/metadata\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'provider': None, 'q': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/predefined_identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Lists all live model metadata rows, e.g. for model pickers.", + "description": "Lists the identity providers Baseten supports, with the issuer format for those where each account, tenant, or cluster has its own issuer.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PredefinedIdentityProvidersV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/access/identity_providers": { + "get": { + "summary": "Lists identity providers", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'predefined_kind': None}\n)\n\nprint(response.text)" + } + ], + "description": "Lists the organization's identity providers. Organization and team admins can list them.", "parameters": [ { "name": "cursor", @@ -10412,13 +10968,14 @@ } }, { - "name": "provider", + "name": "name", "in": "query", "required": false, - "description": "Filter to a provider by slug prefix, e.g. 'anthropic'. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Only the provider with this name, ignoring case", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -10426,25 +10983,24 @@ } ], "default": null, - "title": "Provider" + "title": "Name" } }, { - "name": "q", + "name": "predefined_kind", "in": "query", "required": false, - "description": "Case-insensitive substring search over metadata slugs. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Only this predefined provider's issuers", "schema": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1" }, { "type": "null" } ], - "default": null, - "title": "Q" + "default": null } } ], @@ -10454,34 +11010,32 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ExploreMetadataResponseV1" + "$ref": "#/components/schemas/IdentityProvidersV1" } } } } }, "x-stability": "unstable" - } - }, - "/v1/grid/token": { + }, "post": { - "summary": "Creates a Grid access token", + "summary": "Adds an identity provider", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/token \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"prod-eks\",\n \"predefined\": {\n \"kind\": \"AWS_EKS\",\n \"issuer_url\": \"https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE\"\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/token\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'prod-eks', 'predefined': {'kind': 'AWS_EKS', 'issuer_url': 'https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE'}}\n)\n\nprint(response.text)" } ], - "description": "Exchanges your Baseten credentials for a short-lived token that authenticates against the Grid gateway as you, in the given team. Tokens expire after four hours and cannot be renewed; request a new one when needed. Routes keys cannot create tokens.", + "description": "Adds an identity provider to the organization. For a provider with a per-customer issuer, the issuer must match the provider's format, and its signing keys are fetched before it's saved; a failure returns 422 with the reason. Each provider with a fixed issuer can be added once. Only organization admins can call this endpoint.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridTokenRequestV1" + "$ref": "#/components/schemas/CreateIdentityProviderRequestV1" } } }, @@ -10493,7 +11047,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTokenV1" + "$ref": "#/components/schemas/IdentityProviderV1" } } } @@ -10502,98 +11056,88 @@ "x-stability": "unstable" } }, - "/v1/grid/routes": { - "get": { - "summary": "Lists routes", + "/v1/access/identity_providers/verify": { + "post": { + "summary": "Checks an identity provider before adding it", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/identity_providers/verify \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"predefined\": {\n \"kind\": \"AWS_EKS\",\n \"issuer_url\": \"https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE\"\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'name': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/verify\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'predefined': {'kind': 'AWS_EKS', 'issuer_url': 'https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE'}}\n)\n\nprint(response.text)" } ], - "description": "Lists routes you can invoke, newest first, optionally filtered by exact name. Without `team_id`, routes from every team where you can invoke routes. With `for_harnesses`, exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", - "parameters": [ - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" + "description": "Runs the checks that adding the identity provider runs, without adding it: the issuer's format, that the organization doesn't have it yet, and, for a provider with a per-customer issuer, that its signing keys can be fetched. A failed check returns 200 with `valid` false and the reason. Only organization admins can call this endpoint.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifyIdentityProviderRequestV1" + } } }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerificationV1" + } + } } + } + }, + "x-stability": "unstable" + } + }, + "/v1/access/identity_providers/{identity_provider_id}": { + "delete": { + "summary": "Deletes an identity provider", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { - "name": "team_id", - "in": "query", - "required": false, - "description": "Limit routes to this team. Without it, routes from every team where you can invoke routes.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Removes the identity provider from the organization. Returns 409 while a trust rule uses it. Only organization admins can call this endpoint.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedIdentityProviderV1" } - ], - "default": null, - "title": "Team Id" + } } - }, + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/identity_provider_id" + } + ], + "get": { + "summary": "Gets an identity provider", + "x-codeSamples": [ { - "name": "for_harnesses", - "in": "query", - "required": false, - "description": "Set by harness setup and sync. Returns routes from exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", - "schema": { - "default": false, - "title": "For Harnesses", - "type": "boolean" - } + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { - "name": "name", - "in": "query", - "required": false, - "description": "Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Name" - } + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -10602,7 +11146,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRoutesResponseV1" + "$ref": "#/components/schemas/IdentityProviderV1" } } } @@ -10610,24 +11154,24 @@ }, "x-stability": "unstable" }, - "post": { - "summary": "Creates a route", + "patch": { + "summary": "Updates an identity provider", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"display_name\": \"Assistant\",\n \"target\": {\n \"model\": \"zai-org/GLM-5.3\",\n \"type\": \"BASETEN_MODEL_API\"\n },\n \"description\": \"Assistant for code review and debugging.\"\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"prod-eks\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'display_name': 'Assistant', 'target': {'model': 'zai-org/GLM-5.3', 'type': 'BASETEN_MODEL_API'}, 'description': 'Assistant for code review and debugging.'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'name': 'prod-eks'}\n)\n\nprint(response.text)" } ], - "description": "Creates and derives a name for the provided route configuration. CONNECTION targets reference a connection owned by the route's team; create the connection first.", + "description": "Updates the fields you send. The provider and issuer can't change. Only organization admins can call this endpoint.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridRouteRequestV1" + "$ref": "#/components/schemas/UpdateIdentityProviderRequestV1" } } }, @@ -10639,7 +11183,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/IdentityProviderV1" } } } @@ -10648,20 +11192,20 @@ "x-stability": "unstable" } }, - "/v1/grid/routes/usage": { + "/v1/access/trust_rules": { "get": { - "summary": "Gets daily Grid usage and estimated costs", + "summary": "Lists trust rules", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/usage \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/trust_rules \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/usage\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'identity_provider_id': None, 'service_account_id': None, 'team_id': None}\n)\n\nprint(response.text)" } ], - "description": "Buckets are UTC days, and days with no usage are included. Organization admins see all Grid usage in the organization. Team admins see usage in teams they manage. Other members, including viewers, see only usage from Routes keys they created, including keys that have since expired, been revoked, or been deleted. Usage can be filtered and grouped by the team it was metered in. Usage is metered every 15 minutes, so the current hour can lag. Model API costs use your prices at the time of each request and include tool calls. xAI costs are the charges xAI reports. OpenAI and Anthropic costs are estimated from Baseten's reference prices and may differ from your provider's bill. Vertex and OpenAI-compatible usage is not included. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges. Usage is retained for 92 days.", + "description": "Lists the trust rules you administer: every rule for an organization admin, and rules for your teams' service accounts for a team admin.", "parameters": [ { "name": "cursor", @@ -10685,23 +11229,24 @@ "name": "limit", "in": "query", "required": false, - "description": "Number of daily buckets to return. Defaults to 7; maximum 31.", + "description": "Maximum number of items to return.", "schema": { - "default": 7, - "maximum": 31, + "default": 100, + "maximum": 1000, "minimum": 1, "title": "Limit", "type": "integer" } }, { - "name": "team_id", + "name": "name", "in": "query", "required": false, - "description": "Limit usage to a team you can access. Organization admins can view all usage in the team, team admins can view usage in teams they manage, and other members can view only their own usage. Without a team, organization admins see all organization usage, team admins see their managed teams, and other members see their own usage.", + "description": "Only the rule with this name, ignoring case", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -10709,18 +11254,17 @@ } ], "default": null, - "title": "Team Id" + "title": "Name" } }, { - "name": "start_date", + "name": "identity_provider_id", "in": "query", "required": false, - "description": "Inclusive UTC calendar day at the start of the query range. Defaults to the previous UTC date, and is ignored when you pass a cursor.", + "description": "Only this provider's rules", "schema": { "anyOf": [ { - "format": "date", "type": "string" }, { @@ -10728,18 +11272,17 @@ } ], "default": null, - "title": "Start Date" + "title": "Identity Provider Id" } }, { - "name": "end_date", + "name": "service_account_id", "in": "query", "required": false, - "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included.", + "description": "Only rules for this service account", "schema": { "anyOf": [ { - "format": "date", "type": "string" }, { @@ -10747,82 +11290,111 @@ } ], "default": null, - "title": "End Date" + "title": "Service Account Id" } }, { - "name": "group_by", + "name": "team_id", "in": "query", "required": false, - "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", + "description": "Only rules for this team's service accounts", "schema": { - "items": { - "$ref": "#/components/schemas/GridRouteUsageDimensionV1" - }, - "title": "Group By", - "type": "array" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Team Id" } - }, - { - "name": "user_ids", - "in": "query", - "required": false, - "description": "Return only usage from Routes keys created by these user IDs, repeated once per ID.", - "schema": { - "items": { - "type": "string" - }, - "title": "User Ids", - "type": "array" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AccessTrustRulesV1" + } + } } + } + }, + "x-stability": "unstable" + }, + "post": { + "summary": "Creates a trust rule", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/trust_rules \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"models-main-deploy\",\n \"identity_provider_id\": \"abcd1234\",\n \"service_account_id\": \"wxyz5678\",\n \"condition\": \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\",\n \"audience\": \"https://api.baseten.co\"\n}'" }, { - "name": "models", - "in": "query", - "required": false, - "description": "Return only usage for these exact model names, repeated once per model.", - "schema": { - "items": { - "type": "string" - }, - "title": "Models", - "type": "array" + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'models-main-deploy', 'identity_provider_id': 'abcd1234', 'service_account_id': 'wxyz5678', 'condition': \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\", 'audience': 'https://api.baseten.co'}\n)\n\nprint(response.text)" + } + ], + "description": "Creates a rule that lets tokens from an identity provider act as a service account. Organization admins can create rules for any service account, team admins for their own team's. An organization API key manager key can't target organization accounts.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateAccessTrustRuleRequestV1" + } } }, - { - "name": "providers", - "in": "query", - "required": false, - "description": "Return only usage for these providers, repeated once per provider.", - "schema": { - "items": { - "$ref": "#/components/schemas/GridProviderV1" - }, - "title": "Providers", - "type": "array" + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AccessTrustRuleV1" + } + } } + } + }, + "x-stability": "unstable" + } + }, + "/v1/access/trust_rules/verify": { + "post": { + "summary": "Checks a trust rule's condition and audience", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/trust_rules/verify \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"identity_provider_id\": \"abcd1234\",\n \"condition\": \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\",\n \"audience\": \"https://api.baseten.co\"\n}'" }, { - "name": "harnesses", - "in": "query", - "required": false, - "description": "Return only usage for these harnesses, repeated once per harness. Omit to include all usage, including usage with no recorded harness.", - "schema": { - "items": { - "$ref": "#/components/schemas/GridRouteUsageHarnessV1" - }, - "title": "Harnesses", - "type": "array" - } + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/verify\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'identity_provider_id': 'abcd1234', 'condition': \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\", 'audience': 'https://api.baseten.co'}\n)\n\nprint(response.text)" } ], + "description": "Runs the checks that creating or updating a trust rule runs on its condition and audience, without saving anything: that the condition compiles and pins the claims the identity provider requires. A failed check returns 200 with `valid` false and the reason.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifyAccessTrustRuleRequestV1" + } + } + }, + "required": true + }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteUsageResponseV1" + "$ref": "#/components/schemas/VerificationV1" } } } @@ -10831,26 +11403,27 @@ "x-stability": "unstable" } }, - "/v1/grid/routes/{route_id}": { + "/v1/access/trust_rules/{trust_rule_id}": { "delete": { - "summary": "Deletes a route", + "summary": "Deletes a trust rule", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], + "description": "New exchanges through the rule fail at once; tokens already issued keep working until they expire.", "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteTombstoneV1" + "$ref": "#/components/schemas/DeletedAccessTrustRuleV1" } } } @@ -10860,19 +11433,19 @@ }, "parameters": [ { - "$ref": "#/components/parameters/route_id" + "$ref": "#/components/parameters/trust_rule_id" } ], "get": { - "summary": "Gets a route", + "summary": "Gets a trust rule", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -10881,7 +11454,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/AccessTrustRuleV1" } } } @@ -10890,23 +11463,23 @@ "x-stability": "unstable" }, "patch": { - "summary": "Updates a route", + "summary": "Updates a trust rule", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"description\": \"Assistant for code review and debugging.\",\n \"display_name\": \"Assistant\",\n \"target\": null\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"models-release-deploy\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'description': 'Assistant for code review and debugging.', 'display_name': 'Assistant', 'target': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'name': 'models-release-deploy'}\n)\n\nprint(response.text)" } ], - "description": "The route name, target type, and owning team are immutable.", + "description": "Updates the fields you send. Changes apply to new exchanges only. The identity provider can't change.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateGridRouteRequestV1" + "$ref": "#/components/schemas/UpdateAccessTrustRuleRequestV1" } } }, @@ -10918,7 +11491,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/AccessTrustRuleV1" } } } @@ -10927,30 +11500,64 @@ "x-stability": "unstable" } }, - "/v1/grid/team_settings": { + "/v1/auth/token": { + "post": { + "summary": "Exchanges an identity provider's JWT for an access token", + "security": [], + "description": "Exchanges a JWT from your identity provider for a short-lived Baseten access token, as described in RFC 8693. Send no API key: the JWT is the credential. Name the trust rule to check the JWT against as the `audience`, and send the access token as `Authorization: Bearer` on later requests. Errors follow RFC 6749 section 5.2: a 400 response with an `error` of `invalid_request`, `unsupported_grant_type`, or `invalid_grant`. A well-formed request that is refused always returns `invalid_grant`, whatever the reason.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenExchangeRequestV1" + } + }, + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/TokenExchangeRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenExchangeResponseV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/gateway/events": { "get": { - "summary": "Gets a team's Grid settings by team ID or your only team", + "summary": "Lists gateway events", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/gateway/events \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/gateway/events\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_time': None, 'end_time': None, 'limit': None, 'cursor': None}\n)\n\nprint(response.text)" } ], - "description": "Returns the settings that apply to the team, including the default models for each coding harness and the team's spend limits. Any member who can invoke the team's routes can read them. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", "parameters": [ { - "name": "team_id", + "name": "start_time", "in": "query", "required": false, - "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", + "description": "Inclusive start (ISO 8601, UTC). Required without a cursor.", "schema": { "anyOf": [ { - "minLength": 1, + "format": "date-time", "type": "string" }, { @@ -10958,79 +11565,121 @@ } ], "default": null, - "examples": [ - "abc1234" + "title": "Start Time" + } + }, + { + "name": "end_time", + "in": "query", + "required": false, + "description": "Exclusive end (ISO 8601, UTC). Defaults to now.", + "schema": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } ], - "title": "Team Id" + "default": null, + "title": "End Time" } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridTeamSettingsV1" + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Max events. Default 100, max 1000.", + "schema": { + "anyOf": [ + { + "maximum": 1000, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" } - } + ], + "default": null, + "title": "Limit" } - } - }, - "x-stability": "unstable" - }, - "patch": { - "summary": "Updates a team's Grid settings by team ID or your only team", - "x-codeSamples": [ + }, { - "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"harness_defaults\": null,\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" + "name": "api_keys", + "in": "query", + "required": false, + "description": "Return only events for these API key prefixes, repeated once per prefix.", + "schema": { + "items": { + "type": "string" + }, + "title": "Api Keys", + "type": "array" + } }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'harness_defaults': None, 'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" - } - ], - "description": "Changes only the fields in the request, all or nothing. Requires team admin, and organization admin to change the team-wide spend limit. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateGridTeamSettingsRequestV1" - } + "name": "external_entity_ids", + "in": "query", + "required": false, + "description": "Return only events for these external entity IDs, repeated once per ID.", + "schema": { + "items": { + "type": "string" + }, + "title": "External Entity Ids", + "type": "array" } }, - "required": true - }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Next-page cursor. Other parameters are ignored.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + } + ], "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamSettingsV1" + "$ref": "#/components/schemas/GatewayEventsResponseV1" } } } } - }, - "x-stability": "unstable" + } } }, - "/v1/grid/team_settings/users": { + "/v1/explore/metadata": { "get": { - "summary": "Lists members' Grid settings", + "summary": "Lists model metadata", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/explore/metadata \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/explore/metadata\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'provider': None, 'q': None}\n)\n\nprint(response.text)" } ], - "description": "Returns each member's settings in each team, including organization admins and Grid service accounts, one row per team membership. With `team_id`, one team, which requires team admin for it or organization admin; without it, every team you administer, which is none for members.", + "description": "Lists all live model metadata rows, e.g. for model pickers.", "parameters": [ { "name": "cursor", @@ -11064,14 +11713,13 @@ } }, { - "name": "team_id", + "name": "provider", "in": "query", "required": false, - "description": "Limit the list to this team. Without it, the members of every team you administer, one row per team.", + "description": "Filter to a provider by slug prefix, e.g. 'anthropic'. Preserved by the cursor; if repeated, must match the original filter.", "schema": { "anyOf": [ { - "minLength": 1, "type": "string" }, { @@ -11079,10 +11727,25 @@ } ], "default": null, - "examples": [ - "abc1234" + "title": "Provider" + } + }, + { + "name": "q", + "in": "query", + "required": false, + "description": "Case-insensitive substring search over metadata slugs. Preserved by the cursor; if repeated, must match the original filter.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], - "title": "Team Id" + "default": null, + "title": "Q" } } ], @@ -11092,7 +11755,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsListV1" + "$ref": "#/components/schemas/ExploreMetadataResponseV1" } } } @@ -11101,30 +11764,68 @@ "x-stability": "unstable" } }, - "/v1/grid/team_settings/users/{user_id}": { - "get": { - "summary": "Gets a user's Grid settings by team ID or your only team", + "/v1/grid/token": { + "post": { + "summary": "Creates a Grid access token", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/token \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/token\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Returns the user's spend limit for Baseten Grid in the team, their spend in the team this month, and whether that spend reached the limit. Members can read their own settings; team admins can read members' settings in teams they administer, and organization admins can read anyone's. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "description": "Exchanges your Baseten credentials for a short-lived token that authenticates against the Grid gateway as you, in the given team. Tokens expire after four hours and cannot be renewed; request a new one when needed. Routes keys cannot create tokens.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateGridTokenRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridTokenV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/routes": { + "get": { + "summary": "Lists routes", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'name': None}\n)\n\nprint(response.text)" + } + ], + "description": "Lists routes you can invoke, newest first, optionally filtered by exact name. Without `team_id`, routes from every team where you can invoke routes. With `for_harnesses`, exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", "parameters": [ { - "name": "team_id", + "name": "cursor", "in": "query", "required": false, - "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", "schema": { "anyOf": [ { - "minLength": 1, "type": "string" }, { @@ -11132,11 +11833,68 @@ } ], "default": null, - "examples": [ - "abc1234" + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "team_id", + "in": "query", + "required": false, + "description": "Limit routes to this team. Without it, routes from every team where you can invoke routes.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], + "default": null, "title": "Team Id" } + }, + { + "name": "for_harnesses", + "in": "query", + "required": false, + "description": "Set by harness setup and sync. Returns routes from exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", + "schema": { + "default": false, + "title": "For Harnesses", + "type": "boolean" + } + }, + { + "name": "name", + "in": "query", + "required": false, + "description": "Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Name" + } } ], "responses": { @@ -11145,7 +11903,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsV1" + "$ref": "#/components/schemas/GridRoutesResponseV1" } } } @@ -11153,29 +11911,24 @@ }, "x-stability": "unstable" }, - "parameters": [ - { - "$ref": "#/components/parameters/user_id" - } - ], - "patch": { - "summary": "Updates a user's Grid settings by team ID or your only team", + "post": { + "summary": "Creates a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"display_name\": \"Assistant\",\n \"target\": {\n \"model\": \"zai-org/GLM-5.3\",\n \"type\": \"BASETEN_MODEL_API\"\n },\n \"description\": \"Assistant for code review and debugging.\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'display_name': 'Assistant', 'target': {'model': 'zai-org/GLM-5.3', 'type': 'BASETEN_MODEL_API'}, 'description': 'Assistant for code review and debugging.'}\n)\n\nprint(response.text)" } ], - "description": "Changes only the fields in the request. Once the user's metered spend in the team in a month reaches the spend limit, requests with Routes keys they created in the team are rejected until the limit is raised or the next month starts. Spend is metered every 15 minutes and can lag, so a user can go over the limit. Requires team admin for the specified team or organization admin. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "description": "Creates and derives a name for the provided route configuration. CONNECTION targets reference a connection owned by the route's team; create the connection first. INTELLIGENT targets reference a route classifier from GET /v1/grid/route_classifiers.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateGridUserSettingsRequestV1" + "$ref": "#/components/schemas/CreateGridRouteRequestV1" } } }, @@ -11187,7 +11940,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11196,20 +11949,20 @@ "x-stability": "unstable" } }, - "/v1/grid/connections": { + "/v1/grid/routes/usage": { "get": { - "summary": "Lists connections", + "summary": "Gets daily Grid usage and estimated costs", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/usage \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/usage\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" } ], - "description": "Lists connections, newest first: the team's with `team_id`, else those of every team where you can invoke routes.", + "description": "Buckets are UTC days, and days with no usage are included. Organization admins see all Grid usage in the organization. Team admins see usage in teams they manage. Other members, including viewers, see only usage from Routes keys they created, including keys that have since expired, been revoked, or been deleted. Usage can be filtered and grouped by the team it was metered in. Usage is metered every 15 minutes, so the current hour can lag. Model API costs use your prices at the time of each request and include tool calls. xAI costs are the charges xAI reports. OpenAI and Anthropic costs are estimated from Baseten's reference prices and may differ from your provider's bill. Vertex and OpenAI-compatible usage is not included. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges. Usage is retained for 92 days.", "parameters": [ { "name": "cursor", @@ -11233,10 +11986,10 @@ "name": "limit", "in": "query", "required": false, - "description": "Maximum number of items to return.", + "description": "Number of daily buckets to return. Defaults to 7; maximum 31.", "schema": { - "default": 100, - "maximum": 1000, + "default": 7, + "maximum": 31, "minimum": 1, "title": "Limit", "type": "integer" @@ -11246,7 +11999,7 @@ "name": "team_id", "in": "query", "required": false, - "description": "Limit connections to this team. Without it, connections from every team where you can invoke routes.", + "description": "Limit usage to a team you can access. Organization admins can view all usage in the team, team admins can view usage in teams they manage, and other members can view only their own usage. Without a team, organization admins see all organization usage, team admins see their managed teams, and other members see their own usage.", "schema": { "anyOf": [ { @@ -11259,52 +12012,131 @@ "default": null, "title": "Team Id" } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridConnectionsResponseV1" + }, + { + "name": "start_date", + "in": "query", + "required": false, + "description": "Inclusive UTC calendar day at the start of the query range. Defaults to the previous UTC date, and is ignored when you pass a cursor.", + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" } - } + ], + "default": null, + "title": "Start Date" } - } - }, - "x-stability": "unstable" - }, - "post": { - "summary": "Creates a connection", - "x-codeSamples": [ + }, { - "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" + "name": "end_date", + "in": "query", + "required": false, + "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included.", + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "End Date" + } }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" - } - ], - "description": "Creates a connection from the team to an upstream provider.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateGridConnectionRequestV1" - } + "name": "group_by", + "in": "query", + "required": false, + "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridRouteUsageDimensionV1" + }, + "title": "Group By", + "type": "array" } }, - "required": true - }, + { + "name": "user_ids", + "in": "query", + "required": false, + "description": "Return only usage from Routes keys created by these user IDs, repeated once per ID.", + "schema": { + "items": { + "type": "string" + }, + "title": "User Ids", + "type": "array" + } + }, + { + "name": "models", + "in": "query", + "required": false, + "description": "Return only usage for these exact model names, repeated once per model.", + "schema": { + "items": { + "type": "string" + }, + "title": "Models", + "type": "array" + } + }, + { + "name": "providers", + "in": "query", + "required": false, + "description": "Return only usage for these providers, repeated once per provider.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridProviderV1" + }, + "title": "Providers", + "type": "array" + } + }, + { + "name": "harnesses", + "in": "query", + "required": false, + "description": "Return only usage for these harnesses, repeated once per harness. Omit to include all usage, including usage with no recorded harness.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridRouteUsageHarnessV1" + }, + "title": "Harnesses", + "type": "array" + } + }, + { + "name": "api_key_prefixes", + "in": "query", + "required": false, + "description": "Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", + "schema": { + "items": { + "type": "string" + }, + "title": "Api Key Prefixes", + "type": "array" + } + } + ], "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionV1" + "$ref": "#/components/schemas/GridRouteUsageResponseV1" } } } @@ -11313,27 +12145,26 @@ "x-stability": "unstable" } }, - "/v1/grid/connections/{connection_id}": { + "/v1/grid/routes/{route_id}": { "delete": { - "summary": "Deletes a connection", + "summary": "Deletes a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Deletes the connection. The team secret it points at is left in place.", "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionTombstoneV1" + "$ref": "#/components/schemas/GridRouteTombstoneV1" } } } @@ -11343,19 +12174,19 @@ }, "parameters": [ { - "$ref": "#/components/parameters/connection_id" + "$ref": "#/components/parameters/route_id" } ], "get": { - "summary": "Gets a connection", + "summary": "Gets a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -11364,7 +12195,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11373,23 +12204,23 @@ "x-stability": "unstable" }, "patch": { - "summary": "Updates a connection", + "summary": "Updates a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"description\": \"Assistant for code review and debugging.\",\n \"display_name\": \"Assistant\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'description': 'Assistant for code review and debugging.', 'display_name': 'Assistant'}\n)\n\nprint(response.text)" } ], - "description": "Updates the connection's fields. The provider and owning team are immutable; point the connection at a new team secret to change its API key, or rotate the key itself by updating the secret.", + "description": "The route name, target, and owning team are immutable.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateGridConnectionRequestV1" + "$ref": "#/components/schemas/UpdateGridRouteRequestV1" } } }, @@ -11401,7 +12232,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11410,29 +12241,30 @@ "x-stability": "unstable" } }, - "/v1/grid/classifiers": { + "/v1/grid/team_settings": { "get": { - "summary": "Lists classifiers available for intelligent routes", + "summary": "Gets a team's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Returns Baseten-managed classifiers available to your organization, ordered by identifier. Classifiers cannot be created or modified through this API.", + "description": "Returns the settings that apply to the team, including the default models for each coding harness and the team's spend limits. Any member who can invoke the team's routes can read them. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", "parameters": [ { - "name": "cursor", + "name": "team_id", "in": "query", "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -11440,20 +12272,10 @@ } ], "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" + "examples": [ + "abc1234" + ], + "title": "Team Id" } } ], @@ -11463,62 +12285,66 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridClassifiersResponseV1" + "$ref": "#/components/schemas/GridTeamSettingsV1" } } } } }, "x-stability": "unstable" - } - }, - "/v1/grid/classifiers/{classifier_id}": { - "get": { - "summary": "Gets a classifier available for intelligent routes", + }, + "patch": { + "summary": "Updates a team's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/classifiers/{classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"harness_defaults\": null,\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/classifiers/{classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'harness_defaults': None, 'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], + "description": "Changes only the fields in the request, all or nothing. Requires team admin, and organization admin to change the team-wide spend limit. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateGridTeamSettingsRequestV1" + } + } + }, + "required": true + }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridClassifierV1" + "$ref": "#/components/schemas/GridTeamSettingsV1" } } } } }, "x-stability": "unstable" - }, - "parameters": [ - { - "$ref": "#/components/parameters/classifier_id" - } - ] + } }, - "/v1/grid/route_classifiers": { + "/v1/grid/team_settings/users": { "get": { - "summary": "Lists route classifiers available for intelligent routes", + "summary": "Lists members' Grid settings", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Returns Baseten-managed route classifiers available to your organization, ordered by identifier. Route classifiers cannot be created or modified through this API.", + "description": "Returns each member's settings in each team, including organization admins and Grid service accounts, one row per team membership. With `team_id`, one team, which requires team admin for it or organization admin; without it, every team you administer, which is none for members.", "parameters": [ { "name": "cursor", @@ -11550,6 +12376,28 @@ "title": "Limit", "type": "integer" } + }, + { + "name": "team_id", + "in": "query", + "required": false, + "description": "Limit the list to this team. Without it, the members of every team you administer, one row per team.", + "schema": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "examples": [ + "abc1234" + ], + "title": "Team Id" + } } ], "responses": { @@ -11558,7 +12406,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteClassifiersResponseV1" + "$ref": "#/components/schemas/GridTeamUserSettingsListV1" } } } @@ -11567,17 +12415,42 @@ "x-stability": "unstable" } }, - "/v1/grid/route_classifiers/{route_classifier_id}": { + "/v1/grid/team_settings/users/{user_id}": { "get": { - "summary": "Gets a route classifier available for intelligent routes", + "summary": "Gets a user's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + } + ], + "description": "Returns the user's spend limit for Baseten Grid in the team, their spend in the team this month, and whether that spend reached the limit. Members can read their own settings; team admins can read members' settings in teams they administer, and organization admins can read anyone's. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "parameters": [ + { + "name": "team_id", + "in": "query", + "required": false, + "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", + "schema": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "examples": [ + "abc1234" + ], + "title": "Team Id" + } } ], "responses": { @@ -11586,7 +12459,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteClassifierV1" + "$ref": "#/components/schemas/GridTeamUserSettingsV1" } } } @@ -11596,24 +12469,61 @@ }, "parameters": [ { - "$ref": "#/components/parameters/route_classifier_id" + "$ref": "#/components/parameters/user_id" } - ] + ], + "patch": { + "summary": "Updates a user's Grid settings by team ID or your only team", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + } + ], + "description": "Changes only the fields in the request. Once the user's metered spend in the team in a month reaches the spend limit, requests with Routes keys they created in the team are rejected until the limit is raised or the next month starts. Spend is metered every 15 minutes and can lag, so a user can go over the limit. Requires team admin for the specified team or organization admin. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateGridUserSettingsRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridTeamUserSettingsV1" + } + } + } + } + }, + "x-stability": "unstable" + } }, - "/v1/grid/machine_users": { + "/v1/grid/connections": { "get": { - "summary": "Lists machine users", + "summary": "Lists connections", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" } ], - "description": "Lists machine users, newest first: the team's with `team_id`, which requires team admin for it, else those of every team you administer.", + "description": "Lists connections, newest first: the team's with `team_id`, else those of every team where you can invoke routes.", "parameters": [ { "name": "cursor", @@ -11650,7 +12560,7 @@ "name": "team_id", "in": "query", "required": false, - "description": "Limit machine users to this team. Without it, every team you administer.", + "description": "Limit connections to this team. Without it, connections from every team where you can invoke routes.", "schema": { "anyOf": [ { @@ -11671,7 +12581,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridMachineUsersResponseV1" + "$ref": "#/components/schemas/GridConnectionsResponseV1" } } } @@ -11680,23 +12590,23 @@ "x-stability": "unstable" }, "post": { - "summary": "Creates a machine user", + "summary": "Creates a connection", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"name\": \"night-shift\",\n \"api_key\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'name': 'night-shift', 'api_key': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" } ], - "description": "Creates a team-owned identity for an application, with its own Grid budget. Set `api_key` to also create its first API key, which the response returns only once. Set the machine user's spend limit with the user settings endpoint, using its `id` as the user ID. Requires team admin.", + "description": "Creates a connection from the team to an upstream provider.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridMachineUserRequestV1" + "$ref": "#/components/schemas/CreateGridConnectionRequestV1" } } }, @@ -11708,7 +12618,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreatedGridMachineUserV1" + "$ref": "#/components/schemas/GridConnectionV1" } } } @@ -11717,7 +12627,316 @@ "x-stability": "unstable" } }, - "/v1/grid/machine_users/{machine_user_id}": { + "/v1/grid/connections/{connection_id}": { + "delete": { + "summary": "Deletes a connection", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "description": "Deletes the connection. The team secret it points at is left in place.", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridConnectionTombstoneV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/connection_id" + } + ], + "get": { + "summary": "Gets a connection", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridConnectionV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "patch": { + "summary": "Updates a connection", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" + } + ], + "description": "Updates the connection's fields. The provider and owning team are immutable; point the connection at a new team secret to change its API key, or rotate the key itself by updating the secret.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateGridConnectionRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridConnectionV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/route_classifiers": { + "get": { + "summary": "Lists route classifiers available for intelligent routes", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" + } + ], + "description": "Returns Baseten-managed route classifiers available to your organization, ordered by identifier. Route classifiers cannot be created or modified through this API.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridRouteClassifiersResponseV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/route_classifiers/{route_classifier_id}": { + "get": { + "summary": "Gets a route classifier available for intelligent routes", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridRouteClassifierV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "parameters": [ + { + "$ref": "#/components/parameters/route_classifier_id" + } + ] + }, + "/v1/grid/machine_users": { + "get": { + "summary": "Lists machine users", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" + } + ], + "description": "Lists machine users, newest first: the team's with `team_id`, which requires team admin for it, else those of every team you administer.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "name": "team_id", + "in": "query", + "required": false, + "description": "Limit machine users to this team. Without it, every team you administer.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Team Id" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridMachineUsersResponseV1" + } + } + } + } + }, + "x-stability": "unstable" + }, + "post": { + "summary": "Creates a machine user", + "x-codeSamples": [ + { + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"name\": \"night-shift\",\n \"api_key\": null\n}'" + }, + { + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'name': 'night-shift', 'api_key': None}\n)\n\nprint(response.text)" + } + ], + "description": "Creates a team-owned identity for an application, with its own Grid budget. Set `api_key` to also create its first API key, which the response returns only once. Set the machine user's spend limit with the user settings endpoint, using its `id` as the user ID. Requires team admin.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateGridMachineUserRequestV1" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedGridMachineUserV1" + } + } + } + } + }, + "x-stability": "unstable" + } + }, + "/v1/grid/machine_users/{machine_user_id}": { "delete": { "summary": "Deletes a machine user", "x-codeSamples": [ @@ -18102,6 +19321,25 @@ "title": "PrepareModelUploadResponseV1", "type": "object" }, + "AuditFieldChangeV1": { + "description": "A field's value before and after an update.", + "properties": { + "old": { + "description": "The value before the update.", + "title": "Old" + }, + "new": { + "description": "The value after the update.", + "title": "New" + } + }, + "required": [ + "old", + "new" + ], + "title": "AuditFieldChangeV1", + "type": "object" + }, "AuditLogActorTypeV1": { "description": "Kind of actor that performed an audited action.", "enum": [ @@ -18109,7 +19347,8 @@ "API_KEY", "BASETEN_USER", "BASETEN_SYSTEM", - "TOMBSTONE_USER" + "TOMBSTONE_USER", + "SERVICE_ACCOUNT" ], "title": "AuditLogActorTypeV1", "type": "string" @@ -18159,6 +19398,45 @@ "default": null, "description": "Display name of the acting API key, when the actor is an API key.", "title": "Api Key Name" + }, + "service_account_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the acting service account, when the actor is a service account.", + "title": "Service Account Id" + }, + "service_account_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Current name of the acting service account, when the actor is a service account.", + "title": "Service Account Name" + }, + "trust_rule_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the trust rule the acting workload identity federation token was exchanged through, when the actor is a service account.", + "title": "Trust Rule Id" } }, "required": [ @@ -18170,7 +19448,8 @@ "AuditLogApiKeyRevocationReasonV1": { "description": "Reason an API key was revoked.", "enum": [ - "INACTIVITY" + "INACTIVITY", + "CREDENTIAL_EXPOSURE" ], "title": "AuditLogApiKeyRevocationReasonV1", "type": "string" @@ -18182,6 +19461,7 @@ "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", + "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -18238,6 +19518,9 @@ "GRID_MACHINE_USER_CREATED": "#/components/schemas/AuditLogEventGridMachineUserCreatedV1", "GRID_MACHINE_USER_DELETED": "#/components/schemas/AuditLogEventGridMachineUserDeletedV1", "GRID_MACHINE_USER_UPDATED": "#/components/schemas/AuditLogEventGridMachineUserUpdatedV1", + "IDENTITY_PROVIDER_CREATED": "#/components/schemas/AuditLogEventIdentityProviderCreatedV1", + "IDENTITY_PROVIDER_DELETED": "#/components/schemas/AuditLogEventIdentityProviderDeletedV1", + "IDENTITY_PROVIDER_UPDATED": "#/components/schemas/AuditLogEventIdentityProviderUpdatedV1", "MODEL_DELETED": "#/components/schemas/AuditLogEventModelDeletedV1", "MODEL_DEPLOYED": "#/components/schemas/AuditLogEventModelDeployedV1", "MODEL_DEPLOYMENT_ACTIVATED": "#/components/schemas/AuditLogEventModelDeploymentActivatedV1", @@ -18250,6 +19533,7 @@ "MODEL_DEPLOYMENT_RETRIED": "#/components/schemas/AuditLogEventModelDeploymentRetriedV1", "MODEL_PROMOTION_CONTROL_ACTION": "#/components/schemas/AuditLogEventModelPromotionControlActionV1", "MODEL_RENAMED": "#/components/schemas/AuditLogEventModelRenamedV1", + "ORGANIZATION_API_KEY_SETTINGS_UPDATED": "#/components/schemas/AuditLogEventOrganizationApiKeySettingsUpdatedV1", "PROVIDER_CONNECTION_CREATED": "#/components/schemas/AuditLogEventProviderConnectionCreatedV1", "PROVIDER_CONNECTION_DELETED": "#/components/schemas/AuditLogEventProviderConnectionDeletedV1", "PROVIDER_CONNECTION_UPDATED": "#/components/schemas/AuditLogEventProviderConnectionUpdatedV1", @@ -18257,10 +19541,16 @@ "REQUIRE_GROUP_BASED_ADMINS_ENABLED": "#/components/schemas/AuditLogEventRequireGroupBasedAdminsEnabledV1", "SECRET_DELETED": "#/components/schemas/AuditLogEventSecretDeletedV1", "SECRET_UPDATED": "#/components/schemas/AuditLogEventSecretUpdatedV1", + "SERVICE_ACCOUNT_CREATED": "#/components/schemas/AuditLogEventServiceAccountCreatedV1", + "SERVICE_ACCOUNT_DELETED": "#/components/schemas/AuditLogEventServiceAccountDeletedV1", + "SERVICE_ACCOUNT_UPDATED": "#/components/schemas/AuditLogEventServiceAccountUpdatedV1", "SSH_CERTIFICATE_SIGNED": "#/components/schemas/AuditLogEventSshCertificateSignedV1", "TELEMETRY_EXPORT_CREATED": "#/components/schemas/AuditLogEventTelemetryExportCreatedV1", "TELEMETRY_EXPORT_DELETED": "#/components/schemas/AuditLogEventTelemetryExportDeletedV1", "TELEMETRY_EXPORT_UPDATED": "#/components/schemas/AuditLogEventTelemetryExportUpdatedV1", + "TRUST_RULE_CREATED": "#/components/schemas/AuditLogEventTrustRuleCreatedV1", + "TRUST_RULE_DELETED": "#/components/schemas/AuditLogEventTrustRuleDeletedV1", + "TRUST_RULE_UPDATED": "#/components/schemas/AuditLogEventTrustRuleUpdatedV1", "USER_INVITED": "#/components/schemas/AuditLogEventUserInvitedV1", "USER_JOINED_ORGANIZATION": "#/components/schemas/AuditLogEventUserJoinedOrganizationV1", "USER_REMOVED": "#/components/schemas/AuditLogEventUserRemovedV1", @@ -18357,6 +19647,9 @@ { "$ref": "#/components/schemas/AuditLogEventApiKeyLifetimeLimitsUpdatedV1" }, + { + "$ref": "#/components/schemas/AuditLogEventOrganizationApiKeySettingsUpdatedV1" + }, { "$ref": "#/components/schemas/AuditLogEventGatewayEndpointCreatedV1" }, @@ -18458,6 +19751,33 @@ }, { "$ref": "#/components/schemas/AuditLogEventTelemetryExportDeletedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventServiceAccountCreatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventServiceAccountUpdatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventServiceAccountDeletedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventIdentityProviderCreatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventIdentityProviderUpdatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventIdentityProviderDeletedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventTrustRuleCreatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventTrustRuleUpdatedV1" + }, + { + "$ref": "#/components/schemas/AuditLogEventTrustRuleDeletedV1" } ], "title": "Event Data" @@ -21022,6 +22342,108 @@ "title": "AuditLogEventGridMachineUserUpdatedV1", "type": "object" }, + "AuditLogEventIdentityProviderCreatedV1": { + "description": "An identity provider was added.", + "properties": { + "event_type": { + "const": "IDENTITY_PROVIDER_CREATED", + "title": "Event Type", + "type": "string" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Null when the provider was added without one.", + "title": "Description" + }, + "predefined": { + "$ref": "#/components/schemas/AuditLogEventPredefinedIdentityProviderConfigV1", + "description": "The provider's settings, as the identity provider resource returns them." + } + }, + "required": [ + "event_type", + "identity_provider_id", + "name", + "predefined" + ], + "title": "AuditLogEventIdentityProviderCreatedV1", + "type": "object" + }, + "AuditLogEventIdentityProviderDeletedV1": { + "description": "An identity provider was deleted.", + "properties": { + "event_type": { + "const": "IDENTITY_PROVIDER_DELETED", + "title": "Event Type", + "type": "string" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "event_type", + "identity_provider_id", + "name" + ], + "title": "AuditLogEventIdentityProviderDeletedV1", + "type": "object" + }, + "AuditLogEventIdentityProviderUpdatedV1": { + "description": "An identity provider was updated.", + "properties": { + "event_type": { + "const": "IDENTITY_PROVIDER_UPDATED", + "title": "Event Type", + "type": "string" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/components/schemas/AuditFieldChangeV1" + }, + "description": "The fields the update changed, keyed by field name.", + "title": "Changes", + "type": "object" + } + }, + "required": [ + "event_type", + "identity_provider_id", + "name", + "changes" + ], + "title": "AuditLogEventIdentityProviderUpdatedV1", + "type": "object" + }, "AuditLogEventModelDeletedV1": { "description": "A model was deleted.", "properties": { @@ -21789,6 +23211,67 @@ "title": "AuditLogEventModelRenamedV1", "type": "object" }, + "AuditLogEventOrganizationApiKeySettingsUpdatedV1": { + "description": "An administrator changed which classes of API key the organization allows creating.", + "properties": { + "event_type": { + "const": "ORGANIZATION_API_KEY_SETTINGS_UPDATED", + "title": "Event Type", + "type": "string" + }, + "organization_id": { + "title": "Organization Id", + "type": "string" + }, + "previous_allow_personal_api_keys": { + "title": "Previous Allow Personal Api Keys", + "type": "boolean" + }, + "new_allow_personal_api_keys": { + "title": "New Allow Personal Api Keys", + "type": "boolean" + }, + "previous_allow_service_account_api_keys": { + "title": "Previous Allow Service Account Api Keys", + "type": "boolean" + }, + "new_allow_service_account_api_keys": { + "title": "New Allow Service Account Api Keys", + "type": "boolean" + } + }, + "required": [ + "event_type", + "organization_id", + "previous_allow_personal_api_keys", + "new_allow_personal_api_keys", + "previous_allow_service_account_api_keys", + "new_allow_service_account_api_keys" + ], + "title": "AuditLogEventOrganizationApiKeySettingsUpdatedV1", + "type": "object" + }, + "AuditLogEventPredefinedIdentityProviderConfigV1": { + "description": "Settings of a predefined identity provider, as recorded on an identity provider event. Not\nitself an event payload.", + "properties": { + "kind": { + "description": "Which predefined provider, for example `AWS_EKS`.", + "title": "Kind", + "type": "string" + }, + "issuer_url": { + "description": "The `iss` claim of the provider's tokens.", + "title": "Issuer Url", + "type": "string" + } + }, + "required": [ + "kind", + "issuer_url" + ], + "title": "AuditLogEventPredefinedIdentityProviderConfigV1", + "type": "object" + }, "AuditLogEventPromotionSettingsOverrideV1": { "description": "Promotion settings overridden for one promotion. Null means the environment's value. Not\nitself a payload in the discriminated union.", "properties": { @@ -22112,6 +23595,162 @@ "title": "AuditLogEventSecretUpdatedV1", "type": "object" }, + "AuditLogEventServiceAccountCreatedV1": { + "description": "A service account was created.", + "properties": { + "event_type": { + "const": "SERVICE_ACCOUNT_CREATED", + "title": "Event Type", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Null when the account was created without one.", + "title": "Description" + }, + "owner_team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The team that owns the account. Null for an organization account.", + "title": "Owner Team Id" + }, + "preset_permissions": { + "$ref": "#/components/schemas/AuditLogEventServiceAccountPresetPermissionsV1" + } + }, + "required": [ + "event_type", + "service_account_id", + "name", + "preset_permissions" + ], + "title": "AuditLogEventServiceAccountCreatedV1", + "type": "object" + }, + "AuditLogEventServiceAccountDeletedV1": { + "description": "A service account was deleted.", + "properties": { + "event_type": { + "const": "SERVICE_ACCOUNT_DELETED", + "title": "Event Type", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "event_type", + "service_account_id", + "name" + ], + "title": "AuditLogEventServiceAccountDeletedV1", + "type": "object" + }, + "AuditLogEventServiceAccountPresetPermissionsV1": { + "description": "A service account's access, as recorded on a service account event. Not itself an event\npayload.", + "properties": { + "api_key_type": { + "description": "The API key type whose permissions the account has, as API key events record it.", + "title": "Api Key Type", + "type": "string" + }, + "model_ids": { + "description": "Models the access is limited to; empty for all.", + "items": { + "type": "string" + }, + "title": "Model Ids", + "type": "array" + }, + "environment_names": { + "description": "Environments the access is limited to, or may also manage; empty for none.", + "items": { + "type": "string" + }, + "title": "Environment Names", + "type": "array" + }, + "model_api_slugs": { + "description": "Model APIs the access is limited to; empty for all.", + "items": { + "type": "string" + }, + "title": "Model Api Slugs", + "type": "array" + } + }, + "required": [ + "api_key_type", + "model_ids", + "environment_names", + "model_api_slugs" + ], + "title": "AuditLogEventServiceAccountPresetPermissionsV1", + "type": "object" + }, + "AuditLogEventServiceAccountUpdatedV1": { + "description": "A service account was updated. Disabling or enabling it is a change to `disabled`.", + "properties": { + "event_type": { + "const": "SERVICE_ACCOUNT_UPDATED", + "title": "Event Type", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/components/schemas/AuditFieldChangeV1" + }, + "description": "The fields the update changed, keyed by field name.", + "title": "Changes", + "type": "object" + } + }, + "required": [ + "event_type", + "service_account_id", + "name", + "changes" + ], + "title": "AuditLogEventServiceAccountUpdatedV1", + "type": "object" + }, "AuditLogEventSshCertificateSignedV1": { "description": "An SSH certificate was signed for a workload.", "properties": { @@ -22234,6 +23873,131 @@ "title": "AuditLogEventTelemetryExportUpdatedV1", "type": "object" }, + "AuditLogEventTrustRuleCreatedV1": { + "description": "A trust rule was created.", + "properties": { + "event_type": { + "const": "TRUST_RULE_CREATED", + "title": "Event Type", + "type": "string" + }, + "trust_rule_id": { + "title": "Trust Rule Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Null when the rule was created without one.", + "title": "Description" + }, + "identity_provider_id": { + "title": "Identity Provider Id", + "type": "string" + }, + "service_account_id": { + "title": "Service Account Id", + "type": "string" + }, + "condition": { + "description": "The CEL expression a token's claims must satisfy.", + "title": "Condition", + "type": "string" + }, + "audience": { + "description": "The `aud` claim a token must carry.", + "title": "Audience", + "type": "string" + }, + "max_access_token_lifetime_seconds": { + "description": "The longest lifetime, in seconds, of an access token the rule issues.", + "title": "Max Access Token Lifetime Seconds", + "type": "integer" + } + }, + "required": [ + "event_type", + "trust_rule_id", + "name", + "identity_provider_id", + "service_account_id", + "condition", + "audience", + "max_access_token_lifetime_seconds" + ], + "title": "AuditLogEventTrustRuleCreatedV1", + "type": "object" + }, + "AuditLogEventTrustRuleDeletedV1": { + "description": "A trust rule was deleted.", + "properties": { + "event_type": { + "const": "TRUST_RULE_DELETED", + "title": "Event Type", + "type": "string" + }, + "trust_rule_id": { + "title": "Trust Rule Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "event_type", + "trust_rule_id", + "name" + ], + "title": "AuditLogEventTrustRuleDeletedV1", + "type": "object" + }, + "AuditLogEventTrustRuleUpdatedV1": { + "description": "A trust rule was updated.", + "properties": { + "event_type": { + "const": "TRUST_RULE_UPDATED", + "title": "Event Type", + "type": "string" + }, + "trust_rule_id": { + "title": "Trust Rule Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/components/schemas/AuditFieldChangeV1" + }, + "description": "The fields the update changed, keyed by field name.", + "title": "Changes", + "type": "object" + } + }, + "required": [ + "event_type", + "trust_rule_id", + "name", + "changes" + ], + "title": "AuditLogEventTrustRuleUpdatedV1", + "type": "object" + }, "AuditLogEventTypeV1": { "description": "Type of action recorded by an audit-log entry.", "enum": [ @@ -22296,7 +24060,17 @@ "VOLUME_UPDATED", "TELEMETRY_EXPORT_CREATED", "TELEMETRY_EXPORT_UPDATED", - "TELEMETRY_EXPORT_DELETED" + "TELEMETRY_EXPORT_DELETED", + "SERVICE_ACCOUNT_CREATED", + "SERVICE_ACCOUNT_UPDATED", + "SERVICE_ACCOUNT_DELETED", + "IDENTITY_PROVIDER_CREATED", + "IDENTITY_PROVIDER_UPDATED", + "IDENTITY_PROVIDER_DELETED", + "TRUST_RULE_CREATED", + "TRUST_RULE_UPDATED", + "TRUST_RULE_DELETED", + "ORGANIZATION_API_KEY_SETTINGS_UPDATED" ], "title": "AuditLogEventTypeV1", "type": "string" @@ -22790,7 +24564,8 @@ "USER_MANAGEMENT", "DIRECTORY_GROUP_MANAGEMENT", "SSH", - "TELEMETRY_EXPORT" + "TELEMETRY_EXPORT", + "WORKLOAD_IDENTITY" ], "title": "AuditLogEventTypeGroupV1", "type": "string" @@ -23367,6 +25142,19 @@ "request_backpressure_settings": { "$ref": "#/components/schemas/RequestBackpressureSettingsV1", "description": "Effective request backpressure settings for the deployment." + }, + "failure_reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Why the deployment failed. Set only when the status is DEPLOY_FAILED; null otherwise.", + "title": "Failure Reason" } }, "required": [ @@ -25329,6 +27117,146 @@ "title": "GetStartupSummaryRequestV1", "type": "object" }, + "DeploymentReplicaStatusV1": { + "enum": [ + "STARTING", + "ACTIVE", + "UNHEALTHY", + "TERMINATING", + "TERMINATED", + "UNKNOWN" + ], + "title": "DeploymentReplicaStatusV1", + "type": "string" + }, + "DeploymentReplicaV1": { + "properties": { + "id": { + "description": "Pod-name suffix used for replica lookup and termination, usually five characters.", + "title": "Id", + "type": "string" + }, + "deployment_id": { + "description": "ID of the replica's deployment.", + "title": "Deployment Id", + "type": "string" + }, + "deployment_name": { + "description": "Name of the replica's deployment.", + "title": "Deployment Name", + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1", + "description": "Current replica lifecycle status." + }, + "created_at": { + "description": "Replica creation time in ISO 8601 format.", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "terminated_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Observed termination completion time in ISO 8601 format, or null if unavailable.", + "title": "Terminated At" + }, + "age_seconds": { + "description": "Age in seconds since creation, frozen at termination.", + "title": "Age Seconds", + "type": "number" + }, + "restart_count": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Model container lifetime restart count, or null if unavailable.", + "title": "Restart Count" + } + }, + "required": [ + "id", + "deployment_id", + "deployment_name", + "status", + "created_at", + "terminated_at", + "age_seconds", + "restart_count" + ], + "title": "DeploymentReplicaV1", + "type": "object" + }, + "DeploymentReplicasV1": { + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/DeploymentReplicaV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "DeploymentReplicasV1", + "type": "object" + }, + "DeploymentReplicasRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "statuses": { + "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", + "items": { + "$ref": "#/components/schemas/DeploymentReplicaStatusV1" + }, + "title": "Statuses", + "type": "array" + } + }, + "title": "DeploymentReplicasRequestV1", + "type": "object" + }, "TerminateReplicaResponseV1": { "description": "The response to a request to terminate a replica in a deployment.", "properties": { @@ -26421,7 +28349,8 @@ }, "sampling_mode": { "$ref": "#/components/schemas/TrafficRoutingRuleShadowSamplingModeV1", - "description": "How requests are picked for shadowing" + "default": "USER_SESSION", + "description": "How requests are picked for shadowing. Defaults to USER_SESSION." }, "propagate_client_cancellation": { "description": "Whether a shadow request is cancelled when the original client disconnects", @@ -26434,7 +28363,6 @@ "targets", "percent_traffic", "expires_at", - "sampling_mode", "propagate_client_cancellation" ], "title": "TrafficRoutingRuleUpsertV1", @@ -27893,8 +29821,58 @@ "title": "CheckpointSyncStatus", "type": "string" }, + "TrainingBDNConfigResponseV1": { + "properties": { + "mounts": { + "items": { + "$ref": "#/components/schemas/TrainingBDNMountResponseV1" + }, + "title": "Mounts", + "type": "array" + } + }, + "title": "TrainingBDNConfigResponseV1", + "type": "object" + }, + "TrainingBDNMountResponseV1": { + "properties": { + "source": { + "title": "Source", + "type": "string" + }, + "path": { + "title": "Path", + "type": "string" + }, + "include": { + "description": "Relative glob patterns selecting files to mount; empty includes all files.", + "items": { + "type": "string" + }, + "title": "Include", + "type": "array" + }, + "exclude": { + "description": "Relative glob patterns excluding files from the mount; exclusions win.", + "items": { + "type": "string" + }, + "title": "Exclude", + "type": "array" + } + }, + "required": [ + "source", + "path" + ], + "title": "TrainingBDNMountResponseV1", + "type": "object" + }, "TrainingJobV1": { "properties": { + "bdn": { + "$ref": "#/components/schemas/TrainingBDNConfigResponseV1" + }, "id": { "description": "Unique identifier of the training job.", "title": "Id", @@ -28876,6 +30854,9 @@ "CreateTrainingJobV1": { "description": "Configuration for a training job.", "properties": { + "bdn": { + "$ref": "#/components/schemas/TrainingBDNConfigV1" + }, "image": { "$ref": "#/components/schemas/CreateTrainingJobImageV1", "examples": [ @@ -29352,6 +31333,58 @@ "title": "SecretReferenceV1", "type": "object" }, + "TrainingBDNConfigV1": { + "additionalProperties": false, + "description": "Read-only BDN mounts with the same reference semantics as inference.", + "properties": { + "mounts": { + "items": { + "$ref": "#/components/schemas/TrainingBDNMountV1" + }, + "maxItems": 32, + "title": "Mounts", + "type": "array" + } + }, + "title": "TrainingBDNConfigV1", + "type": "object" + }, + "TrainingBDNMountV1": { + "additionalProperties": false, + "description": "A requested read-only BDN dataset mount.", + "properties": { + "source": { + "title": "Source", + "type": "string" + }, + "path": { + "title": "Path", + "type": "string" + }, + "include": { + "description": "Relative glob patterns selecting files to mount; empty includes all files.", + "items": { + "type": "string" + }, + "title": "Include", + "type": "array" + }, + "exclude": { + "description": "Relative glob patterns excluding files from the mount; exclusions win.", + "items": { + "type": "string" + }, + "title": "Exclude", + "type": "array" + } + }, + "required": [ + "source", + "path" + ], + "title": "TrainingBDNMountV1", + "type": "object" + }, "TrainingWeightAuthV1": { "description": "Authentication configuration for a training weight source.", "properties": { @@ -29850,7 +31883,7 @@ }, "type": "array" }, - "description": "A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + "description": "A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Memory Usage Bytes", "type": "object" }, @@ -29861,12 +31894,56 @@ }, "type": "array" }, - "description": "A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + "description": "A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Utilization", "type": "object" }, + "gpu_temperature_celsius": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Temperature Celsius", + "type": "object" + }, + "gpu_power_usage_watts": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Power Usage Watts", + "type": "object" + }, + "gpu_tensor_core_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Tensor Core Utilization", + "type": "object" + }, + "gpu_memory_bandwidth_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Memory Bandwidth Utilization", + "type": "object" + }, "cpu_usage": { - "description": "The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + "description": "The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29874,7 +31951,7 @@ "type": "array" }, "cpu_memory_usage_bytes": { - "description": "The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + "description": "The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29883,12 +31960,16 @@ }, "ephemeral_storage": { "$ref": "#/components/schemas/StorageMetricsV1", - "description": "The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + "description": "The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." } }, "required": [ "gpu_memory_usage_bytes", "gpu_utilization", + "gpu_temperature_celsius", + "gpu_power_usage_watts", + "gpu_tensor_core_utilization", + "gpu_memory_bandwidth_utilization", "cpu_usage", "cpu_memory_usage_bytes", "ephemeral_storage" @@ -29926,7 +32007,7 @@ }, "type": "array" }, - "description": "A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", + "description": "A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Memory Usage Bytes", "type": "object" }, @@ -29937,12 +32018,56 @@ }, "type": "array" }, - "description": "A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", + "description": "A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "title": "Gpu Utilization", "type": "object" }, + "gpu_temperature_celsius": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Temperature Celsius", + "type": "object" + }, + "gpu_power_usage_watts": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Power Usage Watts", + "type": "object" + }, + "gpu_tensor_core_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Tensor Core Utilization", + "type": "object" + }, + "gpu_memory_bandwidth_utilization": { + "additionalProperties": { + "items": { + "$ref": "#/components/schemas/TrainingJobMetricV1" + }, + "type": "array" + }, + "description": "A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "title": "Gpu Memory Bandwidth Utilization", + "type": "object" + }, "cpu_usage": { - "description": "The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", + "description": "The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29950,7 +32075,7 @@ "type": "array" }, "cpu_memory_usage_bytes": { - "description": "The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", + "description": "The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -29959,7 +32084,7 @@ }, "ephemeral_storage": { "$ref": "#/components/schemas/StorageMetricsV1", - "description": "The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." + "description": "The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." }, "training_job": { "$ref": "#/components/schemas/TrainingJobV1", @@ -29988,6 +32113,10 @@ "required": [ "gpu_memory_usage_bytes", "gpu_utilization", + "gpu_temperature_celsius", + "gpu_power_usage_watts", + "gpu_tensor_core_utilization", + "gpu_memory_bandwidth_utilization", "cpu_usage", "cpu_memory_usage_bytes", "ephemeral_storage", @@ -31508,9 +33637,27 @@ } ], "default": null, - "description": "Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + "description": "Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", "title": "Base Checkpoint" }, + "base_checkpoint_auth": { + "anyOf": [ + { + "$ref": "#/components/schemas/TrainingWeightAuthV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + "examples": [ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint" + } + ] + }, "sampler_num_replicas": { "anyOf": [ { @@ -31571,6 +33718,198 @@ "title": "DeactivateLoopsRunResponseV1", "type": "object" }, + "LoopsCheckpointV1": { + "description": "A checkpoint saved by a Loops run.", + "properties": { + "checkpoint_id": { + "description": "The ID of the checkpoint.", + "title": "Checkpoint Id", + "type": "string" + }, + "created_at": { + "description": "The timestamp of the checkpoint in ISO 8601 format.", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "checkpoint_type": { + "description": "The type of checkpoint.", + "title": "Checkpoint Type", + "type": "string" + }, + "base_model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The base model of the checkpoint.", + "title": "Base Model" + }, + "lora_adapter_config": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "description": "The adapter config of the checkpoint.", + "title": "Lora Adapter Config" + }, + "size_bytes": { + "description": "The size of the checkpoint in bytes.", + "title": "Size Bytes", + "type": "integer" + }, + "sync_status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sync state of the checkpoint: SYNCING or COMPLETE.", + "title": "Sync Status" + }, + "id": { + "description": "The checkpoint ID.", + "title": "Id", + "type": "string" + }, + "lora_config": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoopsLoRAConfigV1" + }, + { + "type": "null" + } + ], + "description": "The immutable LoRA config used to save this checkpoint. Null means the checkpoint is unsupported and cannot be loaded." + }, + "run_id": { + "description": "The ID of the run that produced the checkpoint.", + "title": "Run Id", + "type": "string" + }, + "target": { + "$ref": "#/components/schemas/TrainerCheckpointTarget", + "description": "Whether this checkpoint is loadable by the sampler or by the run." + }, + "expires_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "When the checkpoint expires and is deleted, set from the TTL it was saved with. Null means it's kept until you delete it. A checkpoint that's still in use when it expires, for example deployed, is deleted once it's released.", + "title": "Expires At" + } + }, + "required": [ + "checkpoint_id", + "created_at", + "checkpoint_type", + "base_model", + "lora_adapter_config", + "size_bytes", + "id", + "lora_config", + "run_id", + "target", + "expires_at" + ], + "title": "LoopsCheckpointV1", + "type": "object" + }, + "LoopsLoRAConfigV1": { + "description": "A published LoRA config: which modules the adapter targets and how experts are laid out.", + "properties": { + "config_version": { + "description": "The config version, like v1.", + "title": "Config Version", + "type": "string" + }, + "targets": { + "description": "The module names the LoRA adapter targets.", + "items": { + "type": "string" + }, + "title": "Targets", + "type": "array" + }, + "expert_layout": { + "anyOf": [ + { + "enum": [ + "per_expert", + "shared_outer", + "shared_adapter" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "How routed-expert LoRA weights are laid out. Null when no experts are targeted.", + "title": "Expert Layout" + } + }, + "required": [ + "config_version", + "targets" + ], + "title": "LoopsLoRAConfigV1", + "type": "object" + }, + "TrainerCheckpointTarget": { + "description": "Whether a TrainerServerCheckpoint is loadable by the sampler or the trainer.\n\nSAMPLER checkpoints are consumed by the sampling server for inference;\nTRAINER checkpoints capture full trainer state for resuming training.\nMirrored in the bt:// URI as\n``bt://loops:/(sampler_weights|weights)/``.", + "enum": [ + "sampler", + "trainer" + ], + "title": "TrainerCheckpointTarget", + "type": "string" + }, + "DeleteLoopsRunResponseV1": { + "description": "A Loops run whose delete was accepted.", + "properties": { + "id": { + "description": "The deleted Loops run ID.", + "title": "Id", + "type": "string" + }, + "kept_checkpoints": { + "description": "The run's checkpoints that were not deleted because something still uses them, such as a deployment. They stay usable until that stops.", + "items": { + "$ref": "#/components/schemas/LoopsCheckpointV1" + }, + "title": "Kept Checkpoints", + "type": "array" + } + }, + "required": [ + "id", + "kept_checkpoints" + ], + "title": "DeleteLoopsRunResponseV1", + "type": "object" + }, "GetLoopsRunResponseV1": { "description": "Response for ``GET /v1/loops/runs/``.", "properties": { @@ -31730,9 +34069,27 @@ } ], "default": null, - "description": "Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + "description": "Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", "title": "Base Checkpoint" }, + "base_checkpoint_auth": { + "anyOf": [ + { + "$ref": "#/components/schemas/TrainingWeightAuthV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", + "examples": [ + { + "auth_method": "CUSTOM_SECRET", + "auth_secret_name": "hf_read_my_checkpoint" + } + ] + }, "scope": { "$ref": "#/components/schemas/LoopsPlacementScopeV1", "default": "default", @@ -31968,160 +34325,6 @@ "title": "GetLoopsSamplerResponseV1", "type": "object" }, - "LoopsCheckpointV1": { - "description": "A checkpoint saved by a Loops run.", - "properties": { - "checkpoint_id": { - "description": "The ID of the checkpoint.", - "title": "Checkpoint Id", - "type": "string" - }, - "created_at": { - "description": "The timestamp of the checkpoint in ISO 8601 format.", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "checkpoint_type": { - "description": "The type of checkpoint.", - "title": "Checkpoint Type", - "type": "string" - }, - "base_model": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The base model of the checkpoint.", - "title": "Base Model" - }, - "lora_adapter_config": { - "anyOf": [ - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "description": "The adapter config of the checkpoint.", - "title": "Lora Adapter Config" - }, - "size_bytes": { - "description": "The size of the checkpoint in bytes.", - "title": "Size Bytes", - "type": "integer" - }, - "sync_status": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Sync state of the checkpoint: SYNCING or COMPLETE.", - "title": "Sync Status" - }, - "id": { - "description": "The checkpoint ID.", - "title": "Id", - "type": "string" - }, - "lora_config": { - "anyOf": [ - { - "$ref": "#/components/schemas/LoopsLoRAConfigV1" - }, - { - "type": "null" - } - ], - "description": "The immutable LoRA config used to save this checkpoint. Null means the checkpoint is unsupported and cannot be loaded." - }, - "run_id": { - "description": "The ID of the run that produced the checkpoint.", - "title": "Run Id", - "type": "string" - }, - "target": { - "$ref": "#/components/schemas/TrainerCheckpointTarget", - "description": "Whether this checkpoint is loadable by the sampler or by the run." - } - }, - "required": [ - "checkpoint_id", - "created_at", - "checkpoint_type", - "base_model", - "lora_adapter_config", - "size_bytes", - "id", - "lora_config", - "run_id", - "target" - ], - "title": "LoopsCheckpointV1", - "type": "object" - }, - "LoopsLoRAConfigV1": { - "description": "A published LoRA config: which modules the adapter targets and how experts are laid out.", - "properties": { - "config_version": { - "description": "The config version, like v1.", - "title": "Config Version", - "type": "string" - }, - "targets": { - "description": "The module names the LoRA adapter targets.", - "items": { - "type": "string" - }, - "title": "Targets", - "type": "array" - }, - "expert_layout": { - "anyOf": [ - { - "enum": [ - "per_expert", - "shared_outer", - "shared_adapter" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "How routed-expert LoRA weights are laid out. Null when no experts are targeted.", - "title": "Expert Layout" - } - }, - "required": [ - "config_version", - "targets" - ], - "title": "LoopsLoRAConfigV1", - "type": "object" - }, - "TrainerCheckpointTarget": { - "description": "Whether a TrainerServerCheckpoint is loadable by the sampler or the trainer.\n\nSAMPLER checkpoints are consumed by the sampling server for inference;\nTRAINER checkpoints capture full trainer state for resuming training.\nMirrored in the bt:// URI as\n``bt://loops:/(sampler_weights|weights)/``.", - "enum": [ - "sampler", - "trainer" - ], - "title": "TrainerCheckpointTarget", - "type": "string" - }, "ListLoopsCheckpointsResponseV1": { "description": "Checkpoints matching the query filter.", "properties": { @@ -32293,6 +34496,44 @@ "title": "DeployLoopsCheckpointResponseV1", "type": "object" }, + "LoopsCheckpointTombstoneV1": { + "description": "A Loops checkpoint whose delete was accepted.", + "properties": { + "id": { + "description": "The deleted checkpoint ID.", + "title": "Id", + "type": "string" + }, + "run_id": { + "description": "The ID of the run that produced the checkpoint.", + "title": "Run Id", + "type": "string" + }, + "checkpoint_id": { + "description": "The name the checkpoint was saved under.", + "title": "Checkpoint Id", + "type": "string" + }, + "target": { + "$ref": "#/components/schemas/TrainerCheckpointTarget", + "description": "Whether the checkpoint was loadable by the sampler or by the run." + }, + "path": { + "description": "The checkpoint's bt:// path.", + "title": "Path", + "type": "string" + } + }, + "required": [ + "id", + "run_id", + "checkpoint_id", + "target", + "path" + ], + "title": "LoopsCheckpointTombstoneV1", + "type": "object" + }, "LoopsCheckpointFilesResponseV1": { "description": "Response with presigned URLs for files under a Loops checkpoint.", "properties": { @@ -32420,6 +34661,29 @@ "title": "LoopsCheckpointSourceResponseV1", "type": "object" }, + "SetLoopsCheckpointTtlRequestV1": { + "properties": { + "ttl_seconds": { + "anyOf": [ + { + "maximum": 315360000, + "minimum": 3600, + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", + "title": "Ttl Seconds" + } + }, + "required": [ + "ttl_seconds" + ], + "title": "SetLoopsCheckpointTtlRequestV1", + "type": "object" + }, "LoopsDeploymentStatusV1": { "description": "Latest deployment status for a Loops deployment.", "properties": { @@ -33118,12 +35382,12 @@ "type": "string" }, "baseline": { - "description": "Baseline GPU allocation for the team. 0 if not configured.", + "description": "Configured minimum GPU allocation for the team. Not enforced. 0 if not configured.", "title": "Baseline", "type": "integer" }, "limit": { - "description": "Maximum concurrent GPUs of this type for this team", + "description": "The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", "title": "Limit", "type": "integer" }, @@ -33134,7 +35398,7 @@ }, "dedicated_usage_count": { "default": 0, - "description": "Portion of usage_count from standard (non-spot) jobs.", + "description": "Portion of usage_count from on-demand (non-spot) jobs.", "title": "Dedicated Usage Count", "type": "integer" }, @@ -33165,15 +35429,33 @@ "type": "string" }, "baseline": { - "description": "Baseline GPU allocation; jobs below this threshold are expected to run immediately. 0 if not configured.", + "description": "Configured minimum GPU allocation (`min_gpus`). 0 if not configured. Use `on_demand_quota` for the quota applied to on-demand jobs.", "title": "Baseline", "type": "integer" }, "limit": { - "description": "Maximum concurrent GPUs of this type for this org", + "description": "Configured maximum GPU allocation (`max_gpus`). Use `on_demand_quota` and `spot_quota` for the quotas applied to jobs.", "title": "Limit", "type": "integer" }, + "on_demand_quota": { + "description": "GPU quota for this type for on-demand (non-spot) jobs: the most GPUs they can use at once.", + "title": "On Demand Quota", + "type": "integer" + }, + "spot_quota": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "GPU quota for this type for spot jobs. Spot shares this quota with on-demand jobs: spot can use up to the quota minus on-demand GPUs in use. Null if spot is not enabled for the organization.", + "title": "Spot Quota" + }, "usage_count": { "description": "GPUs currently in use by active training jobs", "title": "Usage Count", @@ -33181,13 +35463,13 @@ }, "dedicated_usage_count": { "default": 0, - "description": "Portion of usage_count from standard (non-spot) jobs, which run against the baseline.", + "description": "Portion of usage_count from on-demand (non-spot) jobs.", "title": "Dedicated Usage Count", "type": "integer" }, "spot_usage_count": { "default": 0, - "description": "Portion of usage_count from spot jobs, which burst into the peak and may push usage above the limit.", + "description": "Portion of usage_count from spot jobs.", "title": "Spot Usage Count", "type": "integer" } @@ -33196,6 +35478,7 @@ "gpu_type", "baseline", "limit", + "on_demand_quota", "usage_count" ], "title": "TrainingGpuCapacityItemV1", @@ -33205,7 +35488,7 @@ "description": "Response for the training GPU capacity endpoint.", "properties": { "gpu_capacities": { - "description": "Org-level GPU capacity limits and current usage per GPU type", + "description": "Organization GPU quotas and current usage per GPU type", "items": { "$ref": "#/components/schemas/TrainingGpuCapacityItemV1" }, @@ -33213,12 +35496,18 @@ "type": "array" }, "team_gpu_capacities": { - "description": "Per-team GPU capacity limits and current usage per GPU type", + "description": "Per-team GPU quotas and current usage per GPU type", "items": { "$ref": "#/components/schemas/TeamTrainingGpuCapacityItemV1" }, "title": "Team Gpu Capacities", "type": "array" + }, + "spot_enabled": { + "default": false, + "description": "Whether the organization can submit spot training jobs.", + "title": "Spot Enabled", + "type": "boolean" } }, "required": [ @@ -33228,7 +35517,7 @@ "type": "object" }, "PatchTeamTrainingGpuCapacityRequestV1": { - "description": "A request to set the GPU capacity ceiling for a (team, gpu_type) pair.\n\nCreates the limit if one doesn't already exist for this team and GPU type,\notherwise updates it in place.", + "description": "A request to set the GPU quota for a (team, gpu_type) pair.\n\nCreates the quota if one doesn't already exist for this team and GPU type,\notherwise updates it in place.", "properties": { "team_id": { "description": "Team identifier", @@ -33241,7 +35530,7 @@ "type": "string" }, "max_gpus": { - "description": "Max concurrent GPUs of this type the team may use", + "description": "The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", "examples": [ 8, 16, @@ -33260,11 +35549,11 @@ "type": "object" }, "PatchTeamTrainingGpuCapacityResponseV1": { - "description": "Response for setting a team's GPU capacity ceiling.", + "description": "Response for setting a team's GPU quota.", "properties": { "team_gpu_capacity": { "$ref": "#/components/schemas/TeamTrainingGpuCapacityItemV1", - "description": "The updated per-team GPU capacity limit" + "description": "The updated per-team GPU quota" } }, "required": [ @@ -34747,6 +37036,14 @@ }, "title": "Metrics", "type": "array" + }, + "team_ids": { + "description": "Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", + "items": { + "type": "string" + }, + "title": "Team Ids", + "type": "array" } }, "title": "GetModelAPIMetricsRequestV1", @@ -36885,7 +39182,7 @@ "type": "string" } ], - "description": "Subtotal cost in dollars after applying credits used", + "description": "Usage charges in dollars before applying credits", "title": "Subtotal" }, "credits_used": { @@ -37175,6 +39472,32 @@ "description": "Subtotal cost in dollars for this model", "title": "Subtotal" }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Team ID for multi-team organizations; otherwise null", + "title": "Team Id" + }, + "team_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Team name, including historical teams; null if unavailable", + "title": "Team Name" + }, "input_tokens": { "description": "Total input tokens for this model", "title": "Input Tokens", @@ -37221,7 +39544,7 @@ "type": "string" } ], - "description": "Subtotal cost in dollars after applying credits used", + "description": "Usage charges in dollars before applying credits", "title": "Subtotal" }, "credits_used": { @@ -37247,11 +39570,11 @@ "type": "string" } ], - "description": "Total cost in dollars", + "description": "Usage charges in dollars after applying credits, floored at zero", "title": "Total" }, "breakdown": { - "description": "Per-model usage breakdown", + "description": "Per-model usage breakdown, split by team for multi-team organizations", "items": { "$ref": "#/components/schemas/ModelApiItemV1" }, @@ -37332,7 +39655,7 @@ "type": "string" } ], - "description": "Subtotal cost in dollars after applying credits used", + "description": "Usage charges in dollars before applying credits", "title": "Subtotal" }, "credits_used": { @@ -37390,169 +39713,1730 @@ "dedicated_usage": { "anyOf": [ { - "$ref": "#/components/schemas/DedicatedUsageV1" + "$ref": "#/components/schemas/DedicatedUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dedicated model serving usage" + }, + "training_usage": { + "anyOf": [ + { + "$ref": "#/components/schemas/TrainingUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Training usage" + }, + "model_apis_usage": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelApisUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Model APIs usage" + }, + "loops_usage": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoopsUsageV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Serverless Loops usage, billed per token. Loops usage on dedicated trainers and samplers is billed by the minute and is part of training usage." + } + }, + "title": "UsageSummaryV1", + "type": "object" + }, + "UsageSummaryRequestV1": { + "properties": { + "start_date": { + "description": "Inclusive start date (ISO 8601, normalized to midnight UTC). Earliest queryable: 2026-01-01.", + "format": "date-time", + "title": "Start Date", + "type": "string" + }, + "end_date": { + "description": "Exclusive end date (ISO 8601, normalized to midnight UTC). Date range cannot exceed 31 days.", + "format": "date-time", + "title": "End Date", + "type": "string" + } + }, + "required": [ + "start_date", + "end_date" + ], + "title": "UsageSummaryRequestV1", + "type": "object" + }, + "ToolCallUsageBucketV1": { + "description": "Server-side tool call usage for one day, provider, charge unit, and model.", + "properties": { + "date": { + "description": "UTC day the usage was recorded on.", + "format": "date", + "title": "Date", + "type": "string" + }, + "provider": { + "description": "Tool provider, such as exa or parallel.", + "title": "Provider", + "type": "string" + }, + "sku": { + "description": "Charge unit, as `/`. The unit is what the provider reported, or the tool name when it reported none. Its meaning varies by provider.", + "title": "Sku", + "type": "string" + }, + "model": { + "description": "Model that made the tool calls.", + "title": "Model", + "type": "string" + }, + "calls": { + "description": "Number of tool calls.", + "title": "Calls", + "type": "integer" + }, + "quantity": { + "description": "Billable quantity in the provider's sku unit, summed over the calls.", + "title": "Quantity", + "type": "number" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Team attributed to the usage. Null when not grouping by team or when historical team attribution is unavailable.", + "title": "Team Id" + } + }, + "required": [ + "date", + "provider", + "sku", + "model", + "calls", + "quantity" + ], + "title": "ToolCallUsageBucketV1", + "type": "object" + }, + "ToolCallUsageResponseV1": { + "description": "Daily server-side tool call usage, ordered by day, provider, sku, and model.", + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/ToolCallUsageBucketV1" + }, + "title": "Items", + "type": "array" + } + }, + "title": "ToolCallUsageResponseV1", + "type": "object" + }, + "ToolCallUsageDimensionV1": { + "enum": [ + "TEAM" + ], + "title": "ToolCallUsageDimensionV1", + "type": "string" + }, + "ToolCallUsageRequestV1": { + "properties": { + "start_date": { + "description": "Inclusive UTC calendar day at the start of the query range.", + "format": "date", + "title": "Start Date", + "type": "string" + }, + "end_date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included. The date range cannot exceed 90 days.", + "title": "End Date" + }, + "team_ids": { + "description": "Return only usage for these teams, repeated once per team. Defaults to all teams you can manage. An unauthorized team ID causes a 403 response.", + "items": { + "type": "string" + }, + "title": "Team Ids", + "type": "array" + }, + "group_by": { + "description": "Pass TEAM to split daily rows by team. Defaults to aggregating across teams.", + "items": { + "$ref": "#/components/schemas/ToolCallUsageDimensionV1" + }, + "title": "Group By", + "type": "array" + } + }, + "required": [ + "start_date" + ], + "title": "ToolCallUsageRequestV1", + "type": "object" + }, + "UserInfoV1": { + "description": "A Baseten user.", + "properties": { + "user_id": { + "description": "Unique identifier for the user", + "title": "User Id", + "type": "string" + }, + "email": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Email address of the user", + "title": "Email" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the user", + "title": "Name" + }, + "workspace_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the user's workspace", + "title": "Workspace Name" + } + }, + "required": [ + "user_id" + ], + "title": "UserInfoV1", + "type": "object" + }, + "UsersResponseV1": { + "description": "A page of users in the caller's workspace.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/UserInfoV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "UsersResponseV1", + "type": "object" + }, + "UsersRequestV1": { + "description": "Request parameters for listing users.", + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "email": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "When set, returns only users with this exact email, if any.", + "title": "Email" + } + }, + "title": "UsersRequestV1", + "type": "object" + }, + "AwsAssumeRoleV1": { + "description": "AWS AssumeRole trust-policy inputs for the organization.", + "properties": { + "baseten_role_arn": { + "description": "Baseten role ARN to allow in an IAM role's trust policy", + "title": "Baseten Role Arn", + "type": "string" + }, + "external_id": { + "description": "sts:ExternalId Baseten presents when assuming the role", + "title": "External Id", + "type": "string" + } + }, + "required": [ + "baseten_role_arn", + "external_id" + ], + "title": "AwsAssumeRoleV1", + "type": "object" + }, + "OrganizationInfoV1": { + "description": "The caller's organization.", + "properties": { + "org_id": { + "description": "Unique identifier for the organization", + "title": "Org Id", + "type": "string" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the organization", + "title": "Name" + }, + "created_at": { + "description": "Time the organization was created in ISO 8601 format", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "aws_assume_role": { + "anyOf": [ + { + "$ref": "#/components/schemas/AwsAssumeRoleV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" + }, + "allow_personal_api_keys": { + "description": "Whether members can create new personal API keys. Existing keys keep working.", + "title": "Allow Personal Api Keys", + "type": "boolean" + }, + "allow_service_account_api_keys": { + "description": "Whether new team and organization API keys can be created. Existing keys keep working.", + "title": "Allow Service Account Api Keys", + "type": "boolean" + } + }, + "required": [ + "org_id", + "created_at", + "allow_personal_api_keys", + "allow_service_account_api_keys" + ], + "title": "OrganizationInfoV1", + "type": "object" + }, + "UpdateOrganizationRequestV1": { + "additionalProperties": false, + "description": "Partial update of the caller's organization settings. Omitted fields are unchanged.", + "properties": { + "allow_personal_api_keys": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether members can create new personal API keys. Null is not accepted.", + "title": "Allow Personal Api Keys" + }, + "allow_service_account_api_keys": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether new team and organization API keys can be created. Null is not accepted.", + "title": "Allow Service Account Api Keys" + } + }, + "title": "UpdateOrganizationRequestV1", + "type": "object" + }, + "ServiceAccountPresetPermissionsV1": { + "description": "A service account's access: one of the access types API keys have.\n\nTemporary: mirrors API key access until fine-grained access control is available, and may be removed.", + "properties": { + "type": { + "$ref": "#/components/schemas/ServiceAccountPresetTypeV1", + "description": "What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + "examples": [ + "WORKSPACE_MANAGE_ALL" + ] + }, + "model_ids": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + "examples": [ + [ + "abcd1234" + ] + ], + "title": "Model Ids" + }, + "environment_names": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + "examples": [ + [ + "production" + ] + ], + "title": "Environment Names" + }, + "model_api_slugs": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + "examples": [ + [ + "my-model-api" + ] + ], + "title": "Model Api Slugs" + } + }, + "required": [ + "type" + ], + "title": "ServiceAccountPresetPermissionsV1", + "type": "object" + }, + "ServiceAccountPresetTypeV1": { + "description": "What a service account may do: the workspace API key categories, plus Model APIs.\n\nTemporary: mirrors API key access until fine-grained access control is available, and may be removed.", + "enum": [ + "WORKSPACE_MANAGE_ALL", + "WORKSPACE_INVOKE", + "WORKSPACE_EXPORT_METRICS", + "WORKSPACE_MANAGE_API_KEYS", + "WORKSPACE_INVOKE_MODEL_APIS" + ], + "title": "ServiceAccountPresetTypeV1", + "type": "string" + }, + "ServiceAccountV1": { + "description": "A named service account that workload identity federation tokens act as.", + "properties": { + "id": { + "description": "Service account ID", + "title": "Id", + "type": "string" + }, + "name": { + "description": "Name, unique in the organization", + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description", + "title": "Description" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The team that owns the account. Null for an organization account.", + "title": "Team Id" + }, + "preset_permissions": { + "$ref": "#/components/schemas/ServiceAccountPresetPermissionsV1", + "description": "What the service account may do. Temporary; may be removed once fine-grained access control is available." + }, + "disabled": { + "description": "Whether the account is disabled. A disabled account can't be used.", + "title": "Disabled", + "type": "boolean" + }, + "last_used_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Last time a request authenticated as this account, to within an hour. Null until the first.", + "title": "Last Used At" + }, + "created_at": { + "description": "Time the account was created", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "updated_at": { + "description": "Time the account was last updated", + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "id", + "name", + "preset_permissions", + "disabled", + "created_at", + "updated_at" + ], + "title": "ServiceAccountV1", + "type": "object" + }, + "ServiceAccountsV1": { + "description": "A page of service accounts.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/ServiceAccountV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "ServiceAccountsV1", + "type": "object" + }, + "ServiceAccountsRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only the account with this name, ignoring case", + "title": "Name" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only this team's accounts", + "title": "Team Id" + }, + "disabled": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only disabled or enabled accounts", + "title": "Disabled" + } + }, + "title": "ServiceAccountsRequestV1", + "type": "object" + }, + "ServiceAccountPresetPermissionsRequestV1": { + "additionalProperties": false, + "description": "A service account's access, as sent. Omit a list for no restriction; never send it empty.", + "properties": { + "type": { + "$ref": "#/components/schemas/ServiceAccountPresetTypeV1", + "description": "What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", + "examples": [ + "WORKSPACE_MANAGE_ALL" + ] + }, + "model_ids": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", + "examples": [ + [ + "abcd1234" + ] + ], + "title": "Model Ids" + }, + "environment_names": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", + "examples": [ + [ + "production" + ] + ], + "title": "Environment Names" + }, + "model_api_slugs": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", + "examples": [ + [ + "my-model-api" + ] + ], + "title": "Model Api Slugs" + } + }, + "required": [ + "type" + ], + "title": "ServiceAccountPresetPermissionsRequestV1", + "type": "object" + }, + "CreateServiceAccountRequestV1": { + "additionalProperties": false, + "description": "Request to create a service account.", + "properties": { + "name": { + "description": "Name, unique in the organization. Can be changed later.", + "examples": [ + "ci-deployer" + ], + "maxLength": 255, + "minLength": 1, + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional description, up to 1,024 characters", + "title": "Description" + }, + "team_id": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The team that owns the account. Omit for an organization account. Can't be changed.", + "title": "Team Id" + }, + "preset_permissions": { + "$ref": "#/components/schemas/ServiceAccountPresetPermissionsRequestV1", + "description": "What the service account may do. Can be changed later. Temporary; may be removed once fine-grained access control is available." + } + }, + "required": [ + "name", + "preset_permissions" + ], + "title": "CreateServiceAccountRequestV1", + "type": "object" + }, + "DeletedServiceAccountV1": { + "properties": { + "id": { + "description": "ID of the deleted service account", + "title": "Id", + "type": "string" + }, + "deleted": { + "description": "Always true", + "title": "Deleted", + "type": "boolean" + } + }, + "required": [ + "id", + "deleted" + ], + "title": "DeletedServiceAccountV1", + "type": "object" + }, + "UpdateServiceAccountRequestV1": { + "additionalProperties": false, + "description": "Request to update a service account. Only the fields sent change.", + "properties": { + "name": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name, unique in the organization", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description, up to 1,024 characters; null clears it", + "title": "Description", + "x-null-distinct": true + }, + "disabled": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Disable the account to stop it being used, or enable it again", + "title": "Disabled" + }, + "preset_permissions": { + "anyOf": [ + { + "$ref": "#/components/schemas/ServiceAccountPresetPermissionsRequestV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Replaces the account's access as a whole. Temporary; may be removed once fine-grained access control is available." + } + }, + "title": "UpdateServiceAccountRequestV1", + "type": "object" + }, + "PredefinedIdentityProviderKindV1": { + "description": "An identity provider Baseten supports.", + "enum": [ + "GITHUB_ACTIONS", + "GCP", + "BASETEN", + "AWS_IAM", + "AWS_EKS", + "AZURE_MANAGED_IDENTITY_V1", + "AZURE_MANAGED_IDENTITY_V2", + "AZURE_AKS" + ], + "title": "PredefinedIdentityProviderKindV1", + "type": "string" + }, + "PredefinedIdentityProviderV1": { + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Pass as `kind` when adding the provider" + }, + "name": { + "description": "Display name", + "title": "Name", + "type": "string" + }, + "issuer_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The `iss` claim its tokens carry. Null when each account, tenant, or cluster has its own issuer, which you pass as `issuer_url` when adding the provider.", + "title": "Issuer Url" + }, + "issuer_url_example": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "An example of the `issuer_url` to pass. Null when the issuer is fixed.", + "title": "Issuer Url Example" + } + }, + "required": [ + "kind", + "name" + ], + "title": "PredefinedIdentityProviderV1", + "type": "object" + }, + "PredefinedIdentityProvidersV1": { + "properties": { + "items": { + "description": "Identity providers Baseten supports", + "items": { + "$ref": "#/components/schemas/PredefinedIdentityProviderV1" + }, + "title": "Items", + "type": "array" + } + }, + "required": [ + "items" + ], + "title": "PredefinedIdentityProvidersV1", + "type": "object" + }, + "IdentityProviderV1": { + "description": "An OIDC issuer whose tokens the organization accepts for workload identity federation.", + "properties": { + "id": { + "description": "Identity provider ID", + "title": "Id", + "type": "string" + }, + "name": { + "description": "Name, unique in the organization", + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description", + "title": "Description" + }, + "predefined": { + "$ref": "#/components/schemas/PredefinedIdentityProviderConfigV1", + "description": "Settings of the predefined provider" + }, + "created_by": { + "description": "ID of the user who added the provider", + "title": "Created By", + "type": "string" + }, + "created_at": { + "description": "Time the provider was added", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "updated_at": { + "description": "Time the provider was last updated", + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "id", + "name", + "predefined", + "created_by", + "created_at", + "updated_at" + ], + "title": "IdentityProviderV1", + "type": "object" + }, + "PredefinedIdentityProviderConfigV1": { + "description": "Settings of an identity provider that Baseten defines.", + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Which predefined provider. Can't be changed." + }, + "issuer_url": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + "title": "Issuer Url" + } + }, + "required": [ + "kind" + ], + "title": "PredefinedIdentityProviderConfigV1", + "type": "object" + }, + "IdentityProvidersV1": { + "description": "A page of identity providers.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/IdentityProviderV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "IdentityProvidersV1", + "type": "object" + }, + "IdentityProvidersRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only the provider with this name, ignoring case", + "title": "Name" + }, + "predefined_kind": { + "anyOf": [ + { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Only this predefined provider's issuers" + } + }, + "title": "IdentityProvidersRequestV1", + "type": "object" + }, + "CreatePredefinedIdentityProviderConfigV1": { + "additionalProperties": false, + "description": "Settings of the predefined identity provider to add.", + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Which predefined provider. Can't be changed." + }, + "issuer_url": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", + "title": "Issuer Url" + } + }, + "required": [ + "kind" + ], + "title": "CreatePredefinedIdentityProviderConfigV1", + "type": "object" + }, + "CreateIdentityProviderRequestV1": { + "additionalProperties": false, + "description": "Request to add an identity provider.", + "properties": { + "name": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional description", + "title": "Description" + }, + "predefined": { + "$ref": "#/components/schemas/CreatePredefinedIdentityProviderConfigV1", + "description": "The predefined provider to add" + } + }, + "required": [ + "predefined" + ], + "title": "CreateIdentityProviderRequestV1", + "type": "object" + }, + "VerifyPredefinedIdentityProviderConfigV1": { + "additionalProperties": false, + "description": "Settings of the predefined identity provider to check.", + "properties": { + "kind": { + "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", + "description": "Which predefined provider" + }, + "issuer_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The issuer to check, for AWS IAM, Amazon EKS, Azure managed identity, and Azure Kubernetes Service, in the format the predefined identity providers endpoint shows", + "title": "Issuer Url" + } + }, + "required": [ + "kind" + ], + "title": "VerifyPredefinedIdentityProviderConfigV1", + "type": "object" + }, + "VerifyIdentityProviderRequestV1": { + "additionalProperties": false, + "description": "Request to check an identity provider before adding it.", + "properties": { + "predefined": { + "$ref": "#/components/schemas/VerifyPredefinedIdentityProviderConfigV1", + "description": "The predefined provider to check, as you'd pass it when adding it" + } + }, + "required": [ + "predefined" + ], + "title": "VerifyIdentityProviderRequestV1", + "type": "object" + }, + "VerificationV1": { + "description": "Whether a create request would pass the checks the server runs on it.", + "properties": { + "valid": { + "description": "Whether the input passes every check", + "title": "Valid", + "type": "boolean" + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Why the input fails, as creating it would report. Null when it's valid.", + "title": "Error" + } + }, + "required": [ + "valid" + ], + "title": "VerificationV1", + "type": "object" + }, + "DeletedIdentityProviderV1": { + "properties": { + "id": { + "description": "ID of the deleted identity provider", + "title": "Id", + "type": "string" + }, + "deleted": { + "description": "Always true", + "title": "Deleted", + "type": "boolean" + } + }, + "required": [ + "id", + "deleted" + ], + "title": "DeletedIdentityProviderV1", + "type": "object" + }, + "UpdateIdentityProviderRequestV1": { + "additionalProperties": false, + "description": "Request to update an identity provider. Only the fields sent change.", + "properties": { + "name": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name, unique in the organization", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "maxLength": 1024, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description; null clears it", + "title": "Description", + "x-null-distinct": true + } + }, + "title": "UpdateIdentityProviderRequestV1", + "type": "object" + }, + "AccessTrustRuleV1": { + "description": "Which tokens from an identity provider may act as a service account.", + "properties": { + "id": { + "description": "Trust rule ID. Workloads pass it when they exchange a token.", + "title": "Id", + "type": "string" + }, + "name": { + "description": "Name, unique in the organization", + "title": "Name", + "type": "string" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Description", + "title": "Description" + }, + "identity_provider_id": { + "description": "The identity provider whose tokens it accepts", + "title": "Identity Provider Id", + "type": "string" + }, + "identity_provider_name": { + "description": "Name of the identity provider", + "title": "Identity Provider Name", + "type": "string" + }, + "service_account_id": { + "description": "The service account its tokens act as", + "title": "Service Account Id", + "type": "string" + }, + "service_account_name": { + "description": "Name of the service account", + "title": "Service Account Name", + "type": "string" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The service account's team. Null for an organization service account.", + "title": "Team Id" + }, + "team_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the service account's team. Null for an organization service account.", + "title": "Team Name" + }, + "condition": { + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + "examples": [ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + "title": "Condition", + "type": "string" + }, + "audience": { + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + "title": "Audience", + "type": "string" + }, + "max_access_token_lifetime_seconds": { + "description": "Longest lifetime of a token the rule issues, in seconds", + "title": "Max Access Token Lifetime Seconds", + "type": "integer" + }, + "last_used_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Last time a request authenticated with a token the rule issued, to within an hour. Null until the first.", + "title": "Last Used At" + }, + "created_by": { + "description": "ID of the user who created the rule", + "title": "Created By", + "type": "string" + }, + "created_at": { + "description": "Time the rule was created", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "updated_at": { + "description": "Time the rule was last updated", + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "id", + "name", + "identity_provider_id", + "identity_provider_name", + "service_account_id", + "service_account_name", + "condition", + "audience", + "max_access_token_lifetime_seconds", + "created_by", + "created_at", + "updated_at" + ], + "title": "AccessTrustRuleV1", + "type": "object" + }, + "AccessTrustRulesV1": { + "description": "A page of trust rules.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/AccessTrustRuleV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "AccessTrustRulesV1", + "type": "object" + }, + "AccessTrustRulesRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + }, + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Dedicated model serving usage" + "description": "Only the rule with this name, ignoring case", + "title": "Name" }, - "training_usage": { + "identity_provider_id": { "anyOf": [ { - "$ref": "#/components/schemas/TrainingUsageV1" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Training usage" + "description": "Only this provider's rules", + "title": "Identity Provider Id" }, - "model_apis_usage": { + "service_account_id": { "anyOf": [ { - "$ref": "#/components/schemas/ModelApisUsageV1" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Model APIs usage" + "description": "Only rules for this service account", + "title": "Service Account Id" }, - "loops_usage": { + "team_id": { "anyOf": [ { - "$ref": "#/components/schemas/LoopsUsageV1" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Serverless Loops usage, billed per token. Loops usage on dedicated trainers and samplers is billed by the minute and is part of training usage." + "description": "Only rules for this team's service accounts", + "title": "Team Id" } }, - "title": "UsageSummaryV1", + "title": "AccessTrustRulesRequestV1", "type": "object" }, - "UsageSummaryRequestV1": { + "CreateAccessTrustRuleRequestV1": { + "additionalProperties": false, + "description": "Request to create a trust rule.", "properties": { - "start_date": { - "description": "Inclusive start date (ISO 8601, normalized to midnight UTC). Earliest queryable: 2026-01-01.", - "format": "date-time", - "title": "Start Date", + "name": { + "description": "Name, unique in the organization. Can be changed later.", + "maxLength": 255, + "minLength": 1, + "title": "Name", "type": "string" }, - "end_date": { - "description": "Exclusive end date (ISO 8601, normalized to midnight UTC). Date range cannot exceed 31 days.", - "format": "date-time", - "title": "End Date", + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional description", + "title": "Description" + }, + "identity_provider_id": { + "description": "Whose tokens the rule accepts. Can't be changed.", + "title": "Identity Provider Id", + "type": "string" + }, + "service_account_id": { + "description": "The service account its tokens act as. Can be changed later.", + "title": "Service Account Id", + "type": "string" + }, + "condition": { + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters. Can be changed later.", + "examples": [ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + "title": "Condition", + "type": "string" + }, + "audience": { + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters. Can be changed later.", + "title": "Audience", "type": "string" + }, + "max_access_token_lifetime_seconds": { + "default": 3600, + "description": "Longest lifetime of a token the rule issues, 60 to 3600 seconds. Can be changed later.", + "maximum": 3600, + "minimum": 60, + "title": "Max Access Token Lifetime Seconds", + "type": "integer" } }, "required": [ - "start_date", - "end_date" + "name", + "identity_provider_id", + "service_account_id", + "condition", + "audience" ], - "title": "UsageSummaryRequestV1", + "title": "CreateAccessTrustRuleRequestV1", "type": "object" }, - "ToolCallUsageBucketV1": { - "description": "Server-side tool call usage for one day, provider, charge unit, and model.", + "VerifyAccessTrustRuleRequestV1": { + "additionalProperties": false, + "description": "Request to check a trust rule's condition and audience before saving them.", "properties": { - "date": { - "description": "UTC day the usage was recorded on.", - "format": "date", - "title": "Date", - "type": "string" - }, - "provider": { - "description": "Tool provider, such as exa or parallel.", - "title": "Provider", + "identity_provider_id": { + "description": "The identity provider the rule is for, which decides the claims it must pin", + "title": "Identity Provider Id", "type": "string" }, - "sku": { - "description": "Charge unit, as `/`. The unit is what the provider reported, or the tool name when it reported none. Its meaning varies by provider.", - "title": "Sku", + "condition": { + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + "examples": [ + "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" + ], + "title": "Condition", "type": "string" }, - "model": { - "description": "Model that made the tool calls.", - "title": "Model", + "audience": { + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + "title": "Audience", "type": "string" - }, - "calls": { - "description": "Number of tool calls.", - "title": "Calls", - "type": "integer" - }, - "quantity": { - "description": "Billable quantity in the provider's sku unit, summed over the calls.", - "title": "Quantity", - "type": "number" - }, - "team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Team attributed to the usage. Null when not grouping by team or when historical team attribution is unavailable.", - "title": "Team Id" } }, "required": [ - "date", - "provider", - "sku", - "model", - "calls", - "quantity" + "identity_provider_id", + "condition", + "audience" ], - "title": "ToolCallUsageBucketV1", + "title": "VerifyAccessTrustRuleRequestV1", "type": "object" }, - "ToolCallUsageResponseV1": { - "description": "Daily server-side tool call usage, ordered by day, provider, sku, and model.", + "DeletedAccessTrustRuleV1": { "properties": { - "items": { - "items": { - "$ref": "#/components/schemas/ToolCallUsageBucketV1" - }, - "title": "Items", - "type": "array" + "id": { + "description": "ID of the deleted trust rule", + "title": "Id", + "type": "string" + }, + "deleted": { + "description": "Always true", + "title": "Deleted", + "type": "boolean" } }, - "title": "ToolCallUsageResponseV1", - "type": "object" - }, - "ToolCallUsageDimensionV1": { - "enum": [ - "TEAM" + "required": [ + "id", + "deleted" ], - "title": "ToolCallUsageDimensionV1", - "type": "string" + "title": "DeletedAccessTrustRuleV1", + "type": "object" }, - "ToolCallUsageRequestV1": { + "UpdateAccessTrustRuleRequestV1": { + "additionalProperties": false, + "description": "Request to update a trust rule. Only the fields sent change.", "properties": { - "start_date": { - "description": "Inclusive UTC calendar day at the start of the query range.", - "format": "date", - "title": "Start Date", - "type": "string" - }, - "end_date": { + "name": { "anyOf": [ { - "format": "date", + "maxLength": 255, + "minLength": 1, "type": "string" }, { @@ -37560,41 +41444,10 @@ } ], "default": null, - "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included. The date range cannot exceed 90 days.", - "title": "End Date" - }, - "team_ids": { - "description": "Return only usage for these teams, repeated once per team. Defaults to all teams you can manage. An unauthorized team ID causes a 403 response.", - "items": { - "type": "string" - }, - "title": "Team Ids", - "type": "array" - }, - "group_by": { - "description": "Pass TEAM to split daily rows by team. Defaults to aggregating across teams.", - "items": { - "$ref": "#/components/schemas/ToolCallUsageDimensionV1" - }, - "title": "Group By", - "type": "array" - } - }, - "required": [ - "start_date" - ], - "title": "ToolCallUsageRequestV1", - "type": "object" - }, - "UserInfoV1": { - "description": "A Baseten user.", - "properties": { - "user_id": { - "description": "Unique identifier for the user", - "title": "User Id", - "type": "string" + "description": "Name, unique in the organization", + "title": "Name" }, - "email": { + "description": { "anyOf": [ { "type": "string" @@ -37604,10 +41457,11 @@ } ], "default": null, - "description": "Email address of the user", - "title": "Email" + "description": "Description; null clears it", + "title": "Description", + "x-null-distinct": true }, - "name": { + "condition": { "anyOf": [ { "type": "string" @@ -37617,10 +41471,10 @@ } ], "default": null, - "description": "Display name of the user", - "title": "Name" + "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", + "title": "Condition" }, - "workspace_name": { + "audience": { "anyOf": [ { "type": "string" @@ -37630,64 +41484,25 @@ } ], "default": null, - "description": "Name of the user's workspace", - "title": "Workspace Name" - } - }, - "required": [ - "user_id" - ], - "title": "UserInfoV1", - "type": "object" - }, - "UsersResponseV1": { - "description": "A page of users in the caller's workspace.", - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/UserInfoV1" - }, - "title": "Items", - "type": "array" + "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", + "title": "Audience" }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "UsersResponseV1", - "type": "object" - }, - "UsersRequestV1": { - "description": "Request parameters for listing users.", - "properties": { - "cursor": { + "max_access_token_lifetime_seconds": { "anyOf": [ { - "type": "string" + "maximum": 3600, + "minimum": 60, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" + "description": "Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", + "title": "Max Access Token Lifetime Seconds" }, - "email": { + "service_account_id": { "anyOf": [ { "type": "string" @@ -37697,43 +41512,51 @@ } ], "default": null, - "description": "When set, returns only users with this exact email, if any.", - "title": "Email" + "description": "Moves the rule to another service account. Tokens already issued keep the old account until they expire.", + "title": "Service Account Id" } }, - "title": "UsersRequestV1", + "title": "UpdateAccessTrustRuleRequestV1", "type": "object" }, - "AwsAssumeRoleV1": { - "description": "AWS AssumeRole trust-policy inputs for the organization.", + "TokenExchangeRequestV1": { + "description": "An RFC 8693 token exchange request naming the trust rule to check as its audience.", "properties": { - "baseten_role_arn": { - "description": "Baseten role ARN to allow in an IAM role's trust policy", - "title": "Baseten Role Arn", + "grant_type": { + "description": "Always `urn:ietf:params:oauth:grant-type:token-exchange`", + "examples": [ + "urn:ietf:params:oauth:grant-type:token-exchange" + ], + "title": "Grant Type", "type": "string" }, - "external_id": { - "description": "sts:ExternalId Baseten presents when assuming the role", - "title": "External Id", + "subject_token": { + "description": "The identity provider's JWT", + "examples": [ + "" + ], + "maxLength": 16384, + "title": "Subject Token", "type": "string" - } - }, - "required": [ - "baseten_role_arn", - "external_id" - ], - "title": "AwsAssumeRoleV1", - "type": "object" - }, - "OrganizationInfoV1": { - "description": "The caller's organization.", - "properties": { - "org_id": { - "description": "Unique identifier for the organization", - "title": "Org Id", + }, + "subject_token_type": { + "description": "`urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`", + "examples": [ + "urn:ietf:params:oauth:token-type:jwt" + ], + "title": "Subject Token Type", "type": "string" }, - "name": { + "audience": { + "description": "ID of the trust rule to check the JWT against", + "examples": [ + "abcd1234" + ], + "maxLength": 64, + "title": "Audience", + "type": "string" + }, + "requested_token_type": { "anyOf": [ { "type": "string" @@ -37743,33 +41566,63 @@ } ], "default": null, - "description": "Display name of the organization", - "title": "Name" - }, - "created_at": { - "description": "Time the organization was created in ISO 8601 format", - "format": "date-time", - "title": "Created At", - "type": "string" + "description": "Optional; only `urn:ietf:params:oauth:token-type:access_token` is issued", + "title": "Requested Token Type" }, - "aws_assume_role": { + "access_token_lifetime_seconds": { "anyOf": [ { - "$ref": "#/components/schemas/AwsAssumeRoleV1" + "minimum": 1, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" + "description": "Lifetime of the access token, in seconds. At most the rule's maximum.", + "title": "Access Token Lifetime Seconds" } }, "required": [ - "org_id", - "created_at" + "grant_type", + "subject_token", + "subject_token_type", + "audience" ], - "title": "OrganizationInfoV1", + "title": "TokenExchangeRequestV1", + "type": "object" + }, + "TokenExchangeResponseV1": { + "properties": { + "access_token": { + "description": "Send as `Authorization: Bearer`", + "title": "Access Token", + "type": "string" + }, + "issued_token_type": { + "description": "Always `urn:ietf:params:oauth:token-type:access_token`", + "title": "Issued Token Type", + "type": "string" + }, + "token_type": { + "description": "Always `Bearer`", + "title": "Token Type", + "type": "string" + }, + "expires_in": { + "description": "Seconds until the access token expires", + "title": "Expires In", + "type": "integer" + } + }, + "required": [ + "access_token", + "issued_token_type", + "token_type", + "expires_in" + ], + "title": "TokenExchangeResponseV1", "type": "object" }, "GatewayEventTokensV1": { @@ -38403,30 +42256,31 @@ "title": "GridTokenV1", "type": "object" }, - "GridClassifierV1": { + "GridRouteAliasKindV1": { + "enum": [ + "CLAUDE_DESKTOP", + "ALIAS" + ], + "title": "GridRouteAliasKindV1", + "type": "string" + }, + "GridRouteAliasV1": { "properties": { - "id": { - "description": "Stable classifier identifier.", - "examples": [ - "general-v1" - ], - "title": "Id", - "type": "string" - }, "name": { - "description": "Display name of the classifier.", - "examples": [ - "General" - ], + "description": "Name to send in the inference request's `model` field instead of the route's `name`.", "title": "Name", "type": "string" + }, + "kind": { + "$ref": "#/components/schemas/GridRouteAliasKindV1", + "description": "Purpose of the alias. CLAUDE_DESKTOP is for Claude Code desktop, which rejects model names without a `claude` substring. ALIAS is any other name the team's clients send for the route." } }, "required": [ - "id", - "name" + "name", + "kind" ], - "title": "GridClassifierV1", + "title": "GridRouteAliasV1", "type": "object" }, "GridRouteClassifierV1": { @@ -38434,17 +42288,17 @@ "id": { "description": "Stable route classifier identifier.", "examples": [ - "general-v1" + "abc1234" ], "title": "Id", "type": "string" }, - "name": { + "display_name": { "description": "Display name of the route classifier.", "examples": [ "General" ], - "title": "Name", + "title": "Display Name", "type": "string" }, "supported_tradeoffs": { @@ -38461,8 +42315,8 @@ "title": "Supported Tradeoffs", "type": "array" }, - "decidable_models": { - "description": "Model identities the route classifier picks from.", + "decidable_canonical_model_ids": { + "description": "Canonical model ids the route classifier picks from.", "examples": [ [ "zai-org/GLM-5.3", @@ -38472,37 +42326,195 @@ "items": { "type": "string" }, - "title": "Decidable Models", + "title": "Decidable Canonical Model Ids", "type": "array" } }, "required": [ "id", - "name", + "display_name", "supported_tradeoffs", - "decidable_models" + "decidable_canonical_model_ids" ], "title": "GridRouteClassifierV1", "type": "object" }, - "GridRouteRefV1": { + "GridRouteMetadataV1": { "properties": { - "id": { - "description": "Stable route identifier.", - "title": "Id", - "type": "string" - }, "slug": { - "description": "Name of the route to send in the inference request's model field.", - "title": "Slug", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Metadata slug, e.g. 'anthropic/claude-opus-4'; null for rows without one.", + "title": "Slug" + }, + "display_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Model display name, when available.", + "title": "Display Name" + }, + "release_date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Model release date. Month-only source dates use the first day of that month.", + "title": "Release Date" + }, + "provider": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Provider key derived from the slug prefix, e.g. 'anthropic'; null for unprefixed slugs.", + "title": "Provider" + }, + "context_window": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Total context window in tokens.", + "title": "Context Window" + }, + "max_output_tokens": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Maximum output tokens per response.", + "title": "Max Output Tokens" + }, + "input_modalities": { + "description": "Accepted input modalities.", + "items": { + "type": "string" + }, + "title": "Input Modalities", + "type": "array" + }, + "tools": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "Whether the model supports tool calling.", + "title": "Tools" + }, + "reasoning_effort_levels": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "description": "Reasoning effort levels the model supports.", + "title": "Reasoning Effort Levels" + }, + "parallel_tool_calls": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "Whether the model supports parallel tool calls.", + "title": "Parallel Tool Calls" + }, + "supported_api_formats": { + "anyOf": [ + { + "$ref": "#/components/schemas/ExploreMetadataAPIFormatsV1" + }, + { + "type": "null" + } + ], + "description": "API formats the model supports." + }, + "cost": { + "anyOf": [ + { + "$ref": "#/components/schemas/ExploreCostV1" + }, + { + "type": "null" + } + ], + "description": "Provider list prices in USD per 1M tokens, when available." + }, + "api_formats": { + "description": "API formats the route supports, most preferred first: `chat_completions`, `messages`, `responses` for a BASETEN_MODEL_API target and `messages`, `responses`, `chat_completions` for any other target, keeping only the formats the route supports. Never empty.", + "items": { + "enum": [ + "messages", + "responses", + "chat_completions" + ], + "title": "GridRouteAPIFormatV1", + "type": "string" + }, + "minItems": 1, + "title": "Api Formats", + "type": "array" } }, "required": [ - "id", - "slug" + "slug", + "display_name", + "release_date", + "provider", + "context_window", + "max_output_tokens", + "input_modalities", + "tools", + "reasoning_effort_levels", + "parallel_tool_calls", + "supported_api_formats", + "cost", + "api_formats" ], - "title": "GridRouteRefV1", + "title": "GridRouteMetadataV1", "type": "object" }, "GridRouteTargetBasetenModelAPIV1": { @@ -38527,47 +42539,6 @@ "title": "GridRouteTargetBasetenModelAPIV1", "type": "object" }, - "GridRouteTargetClassifierV1": { - "properties": { - "type": { - "const": "CLASSIFIER", - "description": "Target kind for a classifier-based route.", - "title": "Type", - "type": "string" - }, - "classifier": { - "anyOf": [ - { - "$ref": "#/components/schemas/GridClassifierV1" - }, - { - "type": "null" - } - ], - "description": "Classifier that picks a route for each request. Null for routers created before classifiers could be selected." - }, - "default_route": { - "$ref": "#/components/schemas/GridRouteRefV1", - "description": "Route used when the classifier picks none." - }, - "allowed_routes": { - "description": "Routes the classifier may pick, in creation order.", - "items": { - "$ref": "#/components/schemas/GridRouteRefV1" - }, - "title": "Allowed Routes", - "type": "array" - } - }, - "required": [ - "type", - "classifier", - "default_route", - "allowed_routes" - ], - "title": "GridRouteTargetClassifierV1", - "type": "object" - }, "GridRouteTargetConnectionV1": { "properties": { "type": { @@ -38635,10 +42606,23 @@ "type": "string" }, "name": { - "description": "Name to send in the inference request's model field.", + "description": "Name to send in the inference request's `model` field. Unique within the team; immutable.", "title": "Name", "type": "string" }, + "display_name": { + "description": "Display label, defaulting to the route's name.", + "title": "Display Name", + "type": "string" + }, + "aliases": { + "description": "The route's other names, one per purpose. Empty for routes created before aliases existed.", + "items": { + "$ref": "#/components/schemas/GridRouteAliasV1" + }, + "title": "Aliases", + "type": "array" + }, "team_id": { "description": "Identifier of the owning team.", "title": "Team Id", @@ -38649,11 +42633,6 @@ "title": "Team Name", "type": "string" }, - "display_name": { - "description": "Display label, defaulting to the route name.", - "title": "Display Name", - "type": "string" - }, "description": { "description": "Short description of the route, empty when unset.", "title": "Description", @@ -38664,7 +42643,6 @@ "discriminator": { "mapping": { "BASETEN_MODEL_API": "#/components/schemas/GridRouteTargetBasetenModelAPIV1", - "CLASSIFIER": "#/components/schemas/GridRouteTargetClassifierV1", "CONNECTION": "#/components/schemas/GridRouteTargetConnectionV1", "INTELLIGENT": "#/components/schemas/GridRouteTargetIntelligentV1" }, @@ -38677,9 +42655,6 @@ { "$ref": "#/components/schemas/GridRouteTargetConnectionV1" }, - { - "$ref": "#/components/schemas/GridRouteTargetClassifierV1" - }, { "$ref": "#/components/schemas/GridRouteTargetIntelligentV1" } @@ -38689,13 +42664,13 @@ "metadata": { "anyOf": [ { - "$ref": "#/components/schemas/ExploreMetadataV1" + "$ref": "#/components/schemas/GridRouteMetadataV1" }, { "type": "null" } ], - "description": "Resolved model metadata; for a router, the envelope of its allowed routes' metadata. Null when nothing is linked." + "description": "Resolved model metadata; for an intelligent route, the envelope of its servable models' metadata. Null when nothing is linked or the metadata has no supported API formats." }, "invoke_url": { "description": "Base URL for inference requests using this route.", @@ -38712,9 +42687,9 @@ "required": [ "id", "name", + "display_name", "team_id", "team_name", - "display_name", "description", "target", "metadata", @@ -38798,7 +42773,7 @@ } ], "default": null, - "description": "Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", "title": "Name" } }, @@ -38828,87 +42803,74 @@ "title": "UpsertGridRouteTargetBasetenModelAPIV1", "type": "object" }, - "UpsertGridRouteTargetClassifierV1": { + "UpsertGridRouteTargetConnectionV1": { "additionalProperties": false, "properties": { "type": { - "const": "CLASSIFIER", - "description": "Target kind for a classifier-based route.", + "const": "CONNECTION", + "description": "Target kind for a provider reached through a team connection.", "title": "Type", "type": "string" }, - "classifier_id": { - "description": "ID of the classifier that picks a route for each request.", - "examples": [ - "general-v1" - ], + "model": { + "description": "Model name sent to the provider.", "minLength": 1, - "title": "Classifier Id", + "title": "Model", "type": "string" }, - "allowed_route_ids": { - "description": "IDs of the routes the classifier may pick. All must belong to the route's team and must not be routers themselves.", - "examples": [ - [ - "abc1234", - "def5678" - ] - ], - "items": { - "type": "string" - }, - "title": "Allowed Route Ids", - "type": "array" - }, - "default_route_id": { - "description": "ID of the allowed route used when the classifier picks none.", + "connection_id": { + "description": "Identifier of a connection owned by the route's team. Its provider serves the route.", "examples": [ "abc1234" ], - "title": "Default Route Id", + "minLength": 1, + "title": "Connection Id", "type": "string" } }, "required": [ "type", - "classifier_id", - "allowed_route_ids", - "default_route_id" + "model", + "connection_id" ], - "title": "UpsertGridRouteTargetClassifierV1", + "title": "UpsertGridRouteTargetConnectionV1", "type": "object" }, - "UpsertGridRouteTargetConnectionV1": { + "UpsertGridRouteTargetIntelligentV1": { "additionalProperties": false, "properties": { "type": { - "const": "CONNECTION", - "description": "Target kind for a provider reached through a team connection.", + "const": "INTELLIGENT", + "description": "Target kind for an intelligent route: Baseten picks the model per request.", "title": "Type", "type": "string" }, - "model": { - "description": "Model name sent to the provider.", - "minLength": 1, - "title": "Model", - "type": "string" - }, - "connection_id": { - "description": "Identifier of a connection owned by the route's team. Its provider serves the route.", + "route_classifier_id": { + "description": "Identifier of the route classifier that picks the model. List them with GET /v1/grid/route_classifiers.", "examples": [ "abc1234" ], "minLength": 1, - "title": "Connection Id", + "title": "Route Classifier Id", + "type": "string" + }, + "tradeoff": { + "description": "How the classifier weighs cost against quality. Must be one of the classifier's supported tradeoffs.", + "enum": [ + "cost", + "balanced", + "intelligence" + ], + "title": "GridRouteTradeoffV1", "type": "string" } }, "required": [ "type", - "model", - "connection_id" + "route_classifier_id", + "tradeoff" ], - "title": "UpsertGridRouteTargetConnectionV1", + "title": "UpsertGridRouteTargetIntelligentV1", "type": "object" }, "CreateGridRouteRequestV1": { @@ -38943,19 +42905,19 @@ } ], "default": null, - "description": "Display label. Omit to use the route name; null is not accepted.", + "description": "Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", "examples": [ "Assistant" ], "title": "Display Name" }, "target": { - "description": "Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team.", + "description": "Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team. INTELLIGENT targets need at least one of the route classifier's models, and one of its fallback models, servable by the team.", "discriminator": { "mapping": { "BASETEN_MODEL_API": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1", - "CLASSIFIER": "#/components/schemas/UpsertGridRouteTargetClassifierV1", - "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1" + "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1", + "INTELLIGENT": "#/components/schemas/UpsertGridRouteTargetIntelligentV1" }, "propertyName": "type" }, @@ -38973,7 +42935,7 @@ "$ref": "#/components/schemas/UpsertGridRouteTargetConnectionV1" }, { - "$ref": "#/components/schemas/UpsertGridRouteTargetClassifierV1" + "$ref": "#/components/schemas/UpsertGridRouteTargetIntelligentV1" } ], "title": "Target" @@ -39011,7 +42973,8 @@ "XAI", "VERTEX", "OPENAI_COMPATIBLE", - "BEDROCK" + "BEDROCK", + "AZURE" ], "title": "GridProviderV1", "type": "string" @@ -39116,7 +43079,7 @@ "default": null, "description": "Provider that served the requests. Null when not grouping by PROVIDER." }, - "intelligent_route": { + "intelligent_route_id": { "anyOf": [ { "type": "string" @@ -39126,8 +43089,21 @@ } ], "default": null, - "description": "Name of the intelligent route, as in `GET /v1/grid/routes`. Null when not grouping by INTELLIGENT_ROUTE.", - "title": "Intelligent Route" + "description": "ID of the intelligent route, as `id` in GET /v1/grid/routes. Null when not grouping by INTELLIGENT_ROUTE.", + "title": "Intelligent Route Id" + }, + "intelligent_route_display_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the intelligent route. Null when `intelligent_route_id` is null or the route cannot be resolved.", + "title": "Intelligent Route Display Name" }, "harness": { "anyOf": [ @@ -39141,6 +43117,32 @@ "default": null, "description": "Coding harness. Null when not grouping by HARNESS, when no harness was recorded (including usage from before harness tracking), or when the recorded harness is not recognized by this API version." }, + "api_key_prefix": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Prefix of the API key that made the requests, matching `GET /v1/api_keys`. Null when not grouping by API_KEY, for usage without an API key, and for usage recorded before API key tracking.", + "title": "Api Key Prefix" + }, + "api_key_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the API key. Null when `api_key_prefix` is null or the key has no name.", + "title": "Api Key Name" + }, "cost_usd": { "description": "Estimated cost in USD, returned as an exact decimal string. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges.", "examples": [ @@ -39215,7 +43217,8 @@ "MODEL", "PROVIDER", "INTELLIGENT_ROUTE", - "HARNESS" + "HARNESS", + "API_KEY" ], "title": "GridRouteUsageDimensionV1", "type": "string" @@ -39285,7 +43288,7 @@ "title": "End Date" }, "group_by": { - "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", + "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", "items": { "$ref": "#/components/schemas/GridRouteUsageDimensionV1" }, @@ -39323,6 +43326,14 @@ }, "title": "Harnesses", "type": "array" + }, + "api_key_prefixes": { + "description": "Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", + "items": { + "type": "string" + }, + "title": "Api Key Prefixes", + "type": "array" } }, "title": "GridRouteUsageRequestV1", @@ -39386,37 +43397,6 @@ "Assistant" ], "title": "Display Name" - }, - "target": { - "anyOf": [ - { - "discriminator": { - "mapping": { - "BASETEN_MODEL_API": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1", - "CLASSIFIER": "#/components/schemas/UpsertGridRouteTargetClassifierV1", - "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1" - }, - "propertyName": "type" - }, - "oneOf": [ - { - "$ref": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1" - }, - { - "$ref": "#/components/schemas/UpsertGridRouteTargetConnectionV1" - }, - { - "$ref": "#/components/schemas/UpsertGridRouteTargetClassifierV1" - } - ] - }, - { - "type": "null" - } - ], - "description": "Complete new target configuration. Omit to keep the current configuration; null is not accepted. Only the CLASSIFIER configuration of a router route is mutable.", - "title": "Target", - "x-null-distinct": true } }, "title": "UpdateGridRouteRequestV1", @@ -40240,6 +44220,39 @@ "title": "GridConnectionConfigAnthropicV1", "type": "object" }, + "GridConnectionConfigAzureV1": { + "properties": { + "provider": { + "const": "AZURE", + "description": "Provider kind for Microsoft Azure.", + "title": "Provider", + "type": "string" + }, + "secret_id": { + "description": "Identifier of the team secret holding the provider API key.", + "title": "Secret Id", + "type": "string" + }, + "secret_name": { + "description": "Name of the team secret holding the provider API key.", + "title": "Secret Name", + "type": "string" + }, + "resource_name": { + "description": "Name of the Azure AI Foundry or Azure OpenAI resource.", + "title": "Resource Name", + "type": "string" + } + }, + "required": [ + "provider", + "secret_id", + "secret_name", + "resource_name" + ], + "title": "GridConnectionConfigAzureV1", + "type": "object" + }, "GridConnectionConfigBedrockV1": { "properties": { "provider": { @@ -40408,6 +44421,7 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/GridConnectionConfigAnthropicV1", + "AZURE": "#/components/schemas/GridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/GridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/GridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/GridConnectionConfigVertexV1", @@ -40430,6 +44444,9 @@ }, { "$ref": "#/components/schemas/GridConnectionConfigBedrockV1" + }, + { + "$ref": "#/components/schemas/GridConnectionConfigAzureV1" } ], "title": "Config" @@ -40578,6 +44595,42 @@ "title": "UpsertGridConnectionConfigAnthropicV1", "type": "object" }, + "UpsertGridConnectionConfigAzureV1": { + "additionalProperties": false, + "properties": { + "provider": { + "const": "AZURE", + "description": "Provider kind for Microsoft Azure. Route targets name a deployment, which must be named after its Azure model. Claude models (`claude-*`) use the Anthropic Messages API, and other models use the OpenAI-compatible APIs.", + "title": "Provider", + "type": "string" + }, + "secret_name": { + "description": "Name of an existing secret, owned by the same team, that holds the provider API key.", + "examples": [ + "anthropic-key" + ], + "minLength": 1, + "title": "Secret Name", + "type": "string" + }, + "resource_name": { + "description": "Name of the Azure AI Foundry or Azure OpenAI resource, the subdomain of `.openai.azure.com`.", + "examples": [ + "my-foundry-resource" + ], + "minLength": 1, + "title": "Resource Name", + "type": "string" + } + }, + "required": [ + "provider", + "secret_name", + "resource_name" + ], + "title": "UpsertGridConnectionConfigAzureV1", + "type": "object" + }, "UpsertGridConnectionConfigBedrockV1": { "additionalProperties": false, "properties": { @@ -40757,6 +44810,7 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/UpsertGridConnectionConfigAnthropicV1", + "AZURE": "#/components/schemas/UpsertGridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/UpsertGridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/UpsertGridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/UpsertGridConnectionConfigVertexV1", @@ -40785,6 +44839,9 @@ }, { "$ref": "#/components/schemas/UpsertGridConnectionConfigBedrockV1" + }, + { + "$ref": "#/components/schemas/UpsertGridConnectionConfigAzureV1" } ], "title": "Config" @@ -40818,6 +44875,7 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/UpsertGridConnectionConfigAnthropicV1", + "AZURE": "#/components/schemas/UpsertGridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/UpsertGridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/UpsertGridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/UpsertGridConnectionConfigVertexV1", @@ -40846,6 +44904,9 @@ }, { "$ref": "#/components/schemas/UpsertGridConnectionConfigBedrockV1" + }, + { + "$ref": "#/components/schemas/UpsertGridConnectionConfigAzureV1" } ], "title": "Config" @@ -40857,55 +44918,6 @@ "title": "UpdateGridConnectionRequestV1", "type": "object" }, - "GridClassifiersResponseV1": { - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/GridClassifierV1" - }, - "title": "Items", - "type": "array" - }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "GridClassifiersResponseV1", - "type": "object" - }, - "GridClassifiersRequestV1": { - "properties": { - "cursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - } - }, - "title": "GridClassifiersRequestV1", - "type": "object" - }, "GridRouteClassifiersResponseV1": { "properties": { "items": { @@ -44919,27 +48931,43 @@ "in": "path", "required": true }, - "route_id": { + "service_account_id": { "schema": { "type": "string" }, - "name": "route_id", + "name": "service_account_id", "in": "path", "required": true }, - "connection_id": { + "identity_provider_id": { "schema": { "type": "string" }, - "name": "connection_id", + "name": "identity_provider_id", "in": "path", "required": true }, - "classifier_id": { + "trust_rule_id": { "schema": { "type": "string" }, - "name": "classifier_id", + "name": "trust_rule_id", + "in": "path", + "required": true + }, + "route_id": { + "schema": { + "type": "string" + }, + "name": "route_id", + "in": "path", + "required": true + }, + "connection_id": { + "schema": { + "type": "string" + }, + "name": "connection_id", "in": "path", "required": true }, From 9a1d96e1aa9fdd67e265f22bd8ce21bcfc7c3ab2 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Thu, 19 Nov 2026 15:52:07 -0500 Subject: [PATCH 08/14] Revert "Regenerate the API clients from the production spec" The regeneration moves to its own PR; the exchange body switches to the generated type once that lands. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_workload_identity.py | 20 +- baseten/client/managementapi/__init__.py | 170 +- baseten/client/managementapi/_client.py | 1136 +--- baseten/client/managementapi/_models.py | 2404 +-------- baseten/client/modelconfig/__init__.py | 4 - baseten/client/modelconfig/_models.py | 54 +- scripts/apigen/specs/config.schema.json | 124 +- scripts/apigen/specs/management.json | 6276 ++++------------------ 8 files changed, 1544 insertions(+), 8644 deletions(-) diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index f8cfeee..13ab6b2 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -18,7 +18,7 @@ _utc_now, ) from baseten.client._user_agent import with_user_agent -from baseten.client.managementapi import ResponseError, TokenExchangeRequest +from baseten.client.managementapi import ResponseError # The exchange takes an RFC 8693 request naming the trust rule as its audience. _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" @@ -76,21 +76,21 @@ def read_identity_token_file(self) -> str: raise ValueError(f"identity token file {self.identity_token_file} is empty") return token - def body(self, identity_token: str) -> TokenExchangeRequest: + def body(self, identity_token: str) -> dict[str, str]: token = identity_token.strip() if token == "": raise ValueError("the identity token provider returned an empty token") - return TokenExchangeRequest( - grant_type=_TOKEN_EXCHANGE_GRANT_TYPE, - subject_token=token, - subject_token_type=_JWT_TOKEN_TYPE, - audience=self.trust_rule_id, - ) + return { + "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE, + "subject_token": token, + "subject_token_type": _JWT_TOKEN_TYPE, + "audience": self.trust_rule_id, + } - def post_kwargs(self, body: TokenExchangeRequest) -> dict[str, Any]: + def post_kwargs(self, body: dict[str, str]) -> dict[str, Any]: return { "url": self.url, - "json": body.model_dump(mode="json", exclude_unset=True), + "json": body, "headers": self.headers, "timeout": self.timeout, # The body carries the identity token, so it is never sent on to diff --git a/baseten/client/managementapi/__init__.py b/baseten/client/managementapi/__init__.py index 02d5265..bfadfa4 100644 --- a/baseten/client/managementapi/__init__.py +++ b/baseten/client/managementapi/__init__.py @@ -12,9 +12,6 @@ from ._client import ApiClient, AsyncApiClient, ResponseError from ._models import ( - AccessTokenLifetimeSeconds, - AccessTrustRule, - AccessTrustRules, ActivateResponse, ActiveJobAtSubmit, APIKey, @@ -22,7 +19,6 @@ APIKeyOwner, APIKeys, APIKeyTombstone, - AuditFieldChange, AuditLogActor, AuditLogEntry, AuditLogEventApiKeyCreated, @@ -55,9 +51,6 @@ AuditLogEventGridMachineUserCreated, AuditLogEventGridMachineUserDeleted, AuditLogEventGridMachineUserUpdated, - AuditLogEventIdentityProviderCreated, - AuditLogEventIdentityProviderDeleted, - AuditLogEventIdentityProviderUpdated, AuditLogEventModelDeleted, AuditLogEventModelDeployed, AuditLogEventModelDeploymentActivated, @@ -70,8 +63,6 @@ AuditLogEventModelDeploymentRetried, AuditLogEventModelPromotionControlAction, AuditLogEventModelRenamed, - AuditLogEventOrganizationApiKeySettingsUpdated, - AuditLogEventPredefinedIdentityProviderConfig, AuditLogEventPromotionSettingsOverride, AuditLogEventProviderConnectionCreated, AuditLogEventProviderConnectionDeleted, @@ -81,17 +72,10 @@ AuditLogEventRequireGroupBasedAdminsEnabled, AuditLogEventSecretDeleted, AuditLogEventSecretUpdated, - AuditLogEventServiceAccountCreated, - AuditLogEventServiceAccountDeleted, - AuditLogEventServiceAccountPresetPermissions, - AuditLogEventServiceAccountUpdated, AuditLogEventSshCertificateSigned, AuditLogEventTelemetryExportCreated, AuditLogEventTelemetryExportDeleted, AuditLogEventTelemetryExportUpdated, - AuditLogEventTrustRuleCreated, - AuditLogEventTrustRuleDeleted, - AuditLogEventTrustRuleUpdated, AuditLogEventUserInvited, AuditLogEventUserJoinedOrganization, AuditLogEventUserRemoved, @@ -151,7 +135,6 @@ CostPerMillionInputTokens1, CostPerMillionOutputTokens, CostPerMillionOutputTokens1, - CreateAccessTrustRuleRequest, CreateApiKeyForGroupRequest, CreateApiKeyForGroupResponse, CreateAPIKeyRequest, @@ -169,7 +152,6 @@ CreateGridTokenRequest, CreateGroupHierarchy, CreateGroupRequest, - CreateIdentityProviderRequest, CreateJobWeightConfig, CreateLibraryListingRequest, CreateLibraryListingVersionRequest, @@ -183,7 +165,6 @@ CreateLoopsTrainerRequest, CreateModelDeploymentRequest, CreateModelRequest, - CreatePredefinedIdentityProviderConfig, CreateSandboxParams, CreateSandboxPreviewParams, CreateSandboxPreviewRequest, @@ -192,7 +173,6 @@ CreateSandboxRequest, CreateSandboxVolumeParams, CreateSandboxVolumeRequest, - CreateServiceAccountRequest, CreateTokenRequest, CreateTrainingJob, CreateTrainingJobAccelerator, @@ -218,12 +198,8 @@ DeactivateResponse, DedicatedItem, DedicatedUsage, - DeletedAccessTrustRule, - DeletedIdentityProvider, - DeletedServiceAccount, DeleteImageParams, DeleteImageTagParams, - DeleteLoopsRunResponse, DeleteSandboxParams, DeleteSandboxPreviewParams, DeleteSandboxPreviewTokenParams, @@ -248,16 +224,10 @@ DeploymentPatchOpPythonRequirement, DeploymentPatchPoint, DeploymentPatchPointWithHash, - DeploymentReplica, - DeploymentReplicas, Deployments, DeploymentTombstone, Description, Description1, - Description2, - Description3, - Description4, - Description5, DisplayName, DisplayName1, DockerAuth, @@ -301,8 +271,6 @@ GatewayKeyInfo, GcpOidcDockerAuth, GcpServiceAccountJsonDockerAuth, - GetAccessIdentityProvidersParams, - GetAccessTrustRulesParams, GetApiKeysParams, GetAuditLogsParams, GetAuthCodesResponse, @@ -317,6 +285,7 @@ GetDeploymentPatchesStateResponse, GetExploreMetadataParams, GetGatewayEventsParams, + GetGridClassifiersParams, GetGridConnectionsParams, GetGridMachineUsersParams, GetGridRouteClassifiersParams, @@ -354,12 +323,10 @@ GetModelsDeploymentsLogsParams, GetModelsDeploymentsMetricsParams, GetModelsDeploymentsParams, - GetModelsDeploymentsReplicasParams, GetModelsDeploymentsStartupsParams, GetModelsDeploymentsStartupsSummaryParams, GetModelsEnvironmentsLogsParams, GetModelsEnvironmentsMetricsParams, - GetModelsEnvironmentsReplicasParams, GetModelsEnvironmentsStartupsParams, GetModelsEnvironmentsStartupsSummaryParams, GetModelsParams, @@ -369,7 +336,6 @@ GetSandboxParams, GetSandboxPreviewParams, GetSandboxVolumeParams, - GetServiceAccountsParams, GetTeamsLoopsRunsParams, GetTeamsLoopsSamplersParams, GetTeamsModelsParams, @@ -393,11 +359,12 @@ GetVolumesSyncsParams, GetVolumesVersionsParams, GitInfo, + GridClassifier, + GridClassifiersResponse, GridConnection, GridConnectionBedrockAccessKeysAuth, GridConnectionBedrockApiKeyAuth, GridConnectionConfigAnthropic, - GridConnectionConfigAzure, GridConnectionConfigBedrock, GridConnectionConfigOpenAI, GridConnectionConfigVertex, @@ -412,12 +379,12 @@ GridMachineUsersResponse, GridMachineUserTombstone, GridRoute, - GridRouteAlias, GridRouteClassifier, GridRouteClassifiersResponse, - GridRouteMetadata, + GridRouteRef, GridRoutesResponse, GridRouteTargetBasetenModelAPI, + GridRouteTargetClassifier, GridRouteTargetConnection, GridRouteTargetIntelligent, GridRouteTombstone, @@ -435,8 +402,6 @@ GroupHierarchy, GroupMetadata, GroupsResponse, - IdentityProvider, - IdentityProviders, InferenceVolumeByStatusDatapoint, InProgressPromotion, InstanceType, @@ -445,7 +410,6 @@ InstanceTypeWithPrice, InteractiveSession, InteractiveSessionConfig, - IssuerUrl, KeysForGroupResponse, LibraryListing, LibraryListingMetadata, @@ -494,7 +458,6 @@ LoopsCheckpointFilesResponse, LoopsCheckpointS3Source, LoopsCheckpointSourceResponse, - LoopsCheckpointTombstone, LoopsCheckpointVolumeSource, LoopsDebugArchiveFilesResponse, LoopsDeployment, @@ -511,7 +474,6 @@ LoopsSession, LoopsUsage, LoopsUserConfig, - MaxAccessTokenLifetimeSeconds, MaxScaleDownRate, MaxScaleDownRate1, MaxSeqLen, @@ -540,15 +502,9 @@ Name1, Name2, Name3, - Name4, Name5, Name6, - Name8, - Name9, - Name10, - Name12, - Name13, - Name14, + Name7, NumReplicas, OneTimeAutoscalingSchedule, OneTimeAutoscalingScheduleUpsert, @@ -564,9 +520,6 @@ PatchVolumeRequest, PatchVolumeResponse, PendingJobAheadAtSubmit, - PredefinedIdentityProvider, - PredefinedIdentityProviderConfig, - PredefinedIdentityProviders, PrepareModelUploadRequest, PrepareModelUploadResponse, Primary, @@ -631,11 +584,6 @@ SecretReference, Secrets, SecretTombstone, - ServiceAccount, - ServiceAccountPresetPermissions, - ServiceAccountPresetPermissionsRequest, - ServiceAccounts, - SetLoopsCheckpointTtlRequest, SetVolumeTagRequest, SetVolumeTagResponse, SignalPromotionResponse, @@ -679,26 +627,17 @@ TeamId5, TeamId6, TeamId7, - TeamId8, Teams, TeamTrainingGpuCapacityItem, TerminateReplicaResponse, Token, - TokenExchangeRequest, - TokenExchangeResponse, ToolCallUsageBucket, ToolCallUsageResponse, Total, - Total2, - Total3, TrafficRoutingRule, TrafficRoutingRuleUpsert, TrafficRoutingTarget, TrafficRoutingTargetUpsert, - TrainingBDNConfig, - TrainingBDNConfigResponse, - TrainingBDNMount, - TrainingBDNMountResponse, TrainingGpuCapacityItem, TrainingItem, TrainingJob, @@ -713,9 +652,7 @@ TrainingUsage, TrainingWeightAuth, TrussUserEnv, - TtlSeconds, TTSBenchmarkMetrics, - UpdateAccessTrustRuleRequest, UpdateAutoscalingScheduleSettings, UpdateAutoscalingSettings, UpdateAutoscalingSettingsResponse, @@ -741,12 +678,10 @@ UpdateGridUserSettingsRequest, UpdateGroupMetadata, UpdateGroupRequest, - UpdateIdentityProviderRequest, UpdateLibraryListingRequest, UpdateLibraryListingVersionRequest, UpdateModelPromotionSettings, UpdateModelRequest, - UpdateOrganizationRequest, UpdatePromotionSettings, UpdateRequestBackpressureSettings, UpdateRollingDeployConfig, @@ -756,21 +691,19 @@ UpdateSandboxRequest, UpdateSandboxVolumeParams, UpdateSandboxVolumeRequest, - UpdateServiceAccountRequest, UpdateTrafficRoutingSettings, UpdateTrainingJobRequest, UpdateTrainingJobResponse, UpsertGridConnectionBedrockAccessKeysAuth, UpsertGridConnectionBedrockApiKeyAuth, UpsertGridConnectionConfigAnthropic, - UpsertGridConnectionConfigAzure, UpsertGridConnectionConfigBedrock, UpsertGridConnectionConfigOpenAI, UpsertGridConnectionConfigVertex, UpsertGridConnectionConfigXAI, UpsertGridRouteTargetBasetenModelAPI, + UpsertGridRouteTargetClassifier, UpsertGridRouteTargetConnection, - UpsertGridRouteTargetIntelligent, UpsertSecretRequest, UpsertTrainingProject, UpsertTrainingProjectRequest, @@ -783,10 +716,6 @@ ValidateLoopsCheckpointRequest, ValidateLoopsCheckpointResponse, Value, - Verification, - VerifyAccessTrustRuleRequest, - VerifyIdentityProviderRequest, - VerifyPredefinedIdentityProviderConfig, VertexTargetConfig, Volume, VolumeSync, @@ -817,14 +746,10 @@ "APIKeyTombstone", "APIKeys", "AWSCredentials", - "AccessTokenLifetimeSeconds", - "AccessTrustRule", - "AccessTrustRules", "ActivateResponse", "ActiveJobAtSubmit", "ApiClient", "AsyncApiClient", - "AuditFieldChange", "AuditLogActor", "AuditLogEntry", "AuditLogEventApiKeyCreated", @@ -857,9 +782,6 @@ "AuditLogEventGridMachineUserCreated", "AuditLogEventGridMachineUserDeleted", "AuditLogEventGridMachineUserUpdated", - "AuditLogEventIdentityProviderCreated", - "AuditLogEventIdentityProviderDeleted", - "AuditLogEventIdentityProviderUpdated", "AuditLogEventModelDeleted", "AuditLogEventModelDeployed", "AuditLogEventModelDeploymentActivated", @@ -872,8 +794,6 @@ "AuditLogEventModelDeploymentRetried", "AuditLogEventModelPromotionControlAction", "AuditLogEventModelRenamed", - "AuditLogEventOrganizationApiKeySettingsUpdated", - "AuditLogEventPredefinedIdentityProviderConfig", "AuditLogEventPromotionSettingsOverride", "AuditLogEventProviderConnectionCreated", "AuditLogEventProviderConnectionDeleted", @@ -883,17 +803,10 @@ "AuditLogEventRequireGroupBasedAdminsEnabled", "AuditLogEventSecretDeleted", "AuditLogEventSecretUpdated", - "AuditLogEventServiceAccountCreated", - "AuditLogEventServiceAccountDeleted", - "AuditLogEventServiceAccountPresetPermissions", - "AuditLogEventServiceAccountUpdated", "AuditLogEventSshCertificateSigned", "AuditLogEventTelemetryExportCreated", "AuditLogEventTelemetryExportDeleted", "AuditLogEventTelemetryExportUpdated", - "AuditLogEventTrustRuleCreated", - "AuditLogEventTrustRuleDeleted", - "AuditLogEventTrustRuleUpdated", "AuditLogEventUserInvited", "AuditLogEventUserJoinedOrganization", "AuditLogEventUserRemoved", @@ -953,7 +866,6 @@ "CostPerMillionOutputTokens", "CostPerMillionOutputTokens1", "CreateAPIKeyRequest", - "CreateAccessTrustRuleRequest", "CreateApiKeyForGroupRequest", "CreateApiKeyForGroupResponse", "CreateChainEnvironmentRequest", @@ -968,7 +880,6 @@ "CreateGridTokenRequest", "CreateGroupHierarchy", "CreateGroupRequest", - "CreateIdentityProviderRequest", "CreateJobWeightConfig", "CreateLLMModelRequest", "CreateLLMModelVersionRequest", @@ -982,7 +893,6 @@ "CreateLoopsTrainerRequest", "CreateModelDeploymentRequest", "CreateModelRequest", - "CreatePredefinedIdentityProviderConfig", "CreateSandboxParams", "CreateSandboxPreviewParams", "CreateSandboxPreviewRequest", @@ -991,7 +901,6 @@ "CreateSandboxRequest", "CreateSandboxVolumeParams", "CreateSandboxVolumeRequest", - "CreateServiceAccountRequest", "CreateTokenRequest", "CreateTrainingJob", "CreateTrainingJobAccelerator", @@ -1021,7 +930,6 @@ "DedicatedUsage", "DeleteImageParams", "DeleteImageTagParams", - "DeleteLoopsRunResponse", "DeleteSandboxParams", "DeleteSandboxPreviewParams", "DeleteSandboxPreviewTokenParams", @@ -1032,9 +940,6 @@ "DeleteVolumeTagResponse", "DeleteVolumeVersionRequest", "DeleteVolumeVersionResponse", - "DeletedAccessTrustRule", - "DeletedIdentityProvider", - "DeletedServiceAccount", "DeployLoopsCheckpointRequest", "DeployLoopsCheckpointResponse", "Deployment", @@ -1049,16 +954,10 @@ "DeploymentPatchOpPythonRequirement", "DeploymentPatchPoint", "DeploymentPatchPointWithHash", - "DeploymentReplica", - "DeploymentReplicas", "DeploymentTombstone", "Deployments", "Description", "Description1", - "Description2", - "Description3", - "Description4", - "Description5", "DisplayName", "DisplayName1", "DockerAuth", @@ -1102,8 +1001,6 @@ "GatewayKeyInfo", "GcpOidcDockerAuth", "GcpServiceAccountJsonDockerAuth", - "GetAccessIdentityProvidersParams", - "GetAccessTrustRulesParams", "GetApiKeysParams", "GetAuditLogsParams", "GetAuthCodesResponse", @@ -1118,6 +1015,7 @@ "GetDeploymentPatchesStateResponse", "GetExploreMetadataParams", "GetGatewayEventsParams", + "GetGridClassifiersParams", "GetGridConnectionsParams", "GetGridMachineUsersParams", "GetGridRouteClassifiersParams", @@ -1155,12 +1053,10 @@ "GetModelsDeploymentsLogsParams", "GetModelsDeploymentsMetricsParams", "GetModelsDeploymentsParams", - "GetModelsDeploymentsReplicasParams", "GetModelsDeploymentsStartupsParams", "GetModelsDeploymentsStartupsSummaryParams", "GetModelsEnvironmentsLogsParams", "GetModelsEnvironmentsMetricsParams", - "GetModelsEnvironmentsReplicasParams", "GetModelsEnvironmentsStartupsParams", "GetModelsEnvironmentsStartupsSummaryParams", "GetModelsParams", @@ -1170,7 +1066,6 @@ "GetSandboxParams", "GetSandboxPreviewParams", "GetSandboxVolumeParams", - "GetServiceAccountsParams", "GetTeamsLoopsRunsParams", "GetTeamsLoopsSamplersParams", "GetTeamsModelsParams", @@ -1194,11 +1089,12 @@ "GetVolumesSyncsParams", "GetVolumesVersionsParams", "GitInfo", + "GridClassifier", + "GridClassifiersResponse", "GridConnection", "GridConnectionBedrockAccessKeysAuth", "GridConnectionBedrockApiKeyAuth", "GridConnectionConfigAnthropic", - "GridConnectionConfigAzure", "GridConnectionConfigBedrock", "GridConnectionConfigOpenAI", "GridConnectionConfigVertex", @@ -1213,11 +1109,11 @@ "GridMachineUserTombstone", "GridMachineUsersResponse", "GridRoute", - "GridRouteAlias", "GridRouteClassifier", "GridRouteClassifiersResponse", - "GridRouteMetadata", + "GridRouteRef", "GridRouteTargetBasetenModelAPI", + "GridRouteTargetClassifier", "GridRouteTargetConnection", "GridRouteTargetIntelligent", "GridRouteTombstone", @@ -1236,8 +1132,6 @@ "GroupHierarchy", "GroupMetadata", "GroupsResponse", - "IdentityProvider", - "IdentityProviders", "InProgressPromotion", "InferenceVolumeByStatusDatapoint", "InstanceType", @@ -1246,7 +1140,6 @@ "InstanceTypes", "InteractiveSession", "InteractiveSessionConfig", - "IssuerUrl", "KeysForGroupResponse", "LLMBenchmarkMetrics", "LLMModelHandle", @@ -1295,7 +1188,6 @@ "LoopsCheckpointFilesResponse", "LoopsCheckpointS3Source", "LoopsCheckpointSourceResponse", - "LoopsCheckpointTombstone", "LoopsCheckpointVolumeSource", "LoopsDebugArchiveFilesResponse", "LoopsDeployment", @@ -1312,7 +1204,6 @@ "LoopsSession", "LoopsUsage", "LoopsUserConfig", - "MaxAccessTokenLifetimeSeconds", "MaxScaleDownRate", "MaxScaleDownRate1", "MaxSeqLen", @@ -1341,15 +1232,9 @@ "Name1", "Name2", "Name3", - "Name4", "Name5", "Name6", - "Name8", - "Name9", - "Name10", - "Name12", - "Name13", - "Name14", + "Name7", "NumReplicas", "OneTimeAutoscalingSchedule", "OneTimeAutoscalingScheduleUpsert", @@ -1365,9 +1250,6 @@ "PatchVolumeRequest", "PatchVolumeResponse", "PendingJobAheadAtSubmit", - "PredefinedIdentityProvider", - "PredefinedIdentityProviderConfig", - "PredefinedIdentityProviders", "PrepareModelUploadRequest", "PrepareModelUploadResponse", "Primary", @@ -1433,11 +1315,6 @@ "SecretReference", "SecretTombstone", "Secrets", - "ServiceAccount", - "ServiceAccountPresetPermissions", - "ServiceAccountPresetPermissionsRequest", - "ServiceAccounts", - "SetLoopsCheckpointTtlRequest", "SetVolumeTagRequest", "SetVolumeTagResponse", "SignSSHCertificateRequest", @@ -1482,26 +1359,17 @@ "TeamId5", "TeamId6", "TeamId7", - "TeamId8", "TeamTrainingGpuCapacityItem", "Teams", "TerminateReplicaResponse", "Token", - "TokenExchangeRequest", - "TokenExchangeResponse", "ToolCallUsageBucket", "ToolCallUsageResponse", "Total", - "Total2", - "Total3", "TrafficRoutingRule", "TrafficRoutingRuleUpsert", "TrafficRoutingTarget", "TrafficRoutingTargetUpsert", - "TrainingBDNConfig", - "TrainingBDNConfigResponse", - "TrainingBDNMount", - "TrainingBDNMountResponse", "TrainingGpuCapacityItem", "TrainingItem", "TrainingJob", @@ -1516,8 +1384,6 @@ "TrainingUsage", "TrainingWeightAuth", "TrussUserEnv", - "TtlSeconds", - "UpdateAccessTrustRuleRequest", "UpdateAutoscalingScheduleSettings", "UpdateAutoscalingSettings", "UpdateAutoscalingSettingsResponse", @@ -1543,12 +1409,10 @@ "UpdateGridUserSettingsRequest", "UpdateGroupMetadata", "UpdateGroupRequest", - "UpdateIdentityProviderRequest", "UpdateLibraryListingRequest", "UpdateLibraryListingVersionRequest", "UpdateModelPromotionSettings", "UpdateModelRequest", - "UpdateOrganizationRequest", "UpdatePromotionSettings", "UpdateRequestBackpressureSettings", "UpdateRollingDeployConfig", @@ -1558,21 +1422,19 @@ "UpdateSandboxRequest", "UpdateSandboxVolumeParams", "UpdateSandboxVolumeRequest", - "UpdateServiceAccountRequest", "UpdateTrafficRoutingSettings", "UpdateTrainingJobRequest", "UpdateTrainingJobResponse", "UpsertGridConnectionBedrockAccessKeysAuth", "UpsertGridConnectionBedrockApiKeyAuth", "UpsertGridConnectionConfigAnthropic", - "UpsertGridConnectionConfigAzure", "UpsertGridConnectionConfigBedrock", "UpsertGridConnectionConfigOpenAI", "UpsertGridConnectionConfigVertex", "UpsertGridConnectionConfigXAI", "UpsertGridRouteTargetBasetenModelAPI", + "UpsertGridRouteTargetClassifier", "UpsertGridRouteTargetConnection", - "UpsertGridRouteTargetIntelligent", "UpsertSecretRequest", "UpsertTrainingProject", "UpsertTrainingProjectRequest", @@ -1585,10 +1447,6 @@ "ValidateLoopsCheckpointRequest", "ValidateLoopsCheckpointResponse", "Value", - "Verification", - "VerifyAccessTrustRuleRequest", - "VerifyIdentityProviderRequest", - "VerifyPredefinedIdentityProviderConfig", "VertexTargetConfig", "Volume", "VolumeSync", diff --git a/baseten/client/managementapi/_client.py b/baseten/client/managementapi/_client.py index f757c3d..145cd1e 100644 --- a/baseten/client/managementapi/_client.py +++ b/baseten/client/managementapi/_client.py @@ -11,8 +11,6 @@ from pydantic import BaseModel from ._models import ( - AccessTrustRule, - AccessTrustRules, ActivateResponse, APIKey, APIKeys, @@ -27,7 +25,6 @@ ChainTombstone, CleanupImagesParams, CleanupSandboxImagesResponse, - CreateAccessTrustRuleRequest, CreateApiKeyForGroupRequest, CreateApiKeyForGroupResponse, CreateAPIKeyRequest, @@ -44,7 +41,6 @@ CreateGridRouteRequest, CreateGridTokenRequest, CreateGroupRequest, - CreateIdentityProviderRequest, CreateLibraryListingRequest, CreateLibraryListingVersionRequest, CreateLLMModelRequest, @@ -65,7 +61,6 @@ CreateSandboxRequest, CreateSandboxVolumeParams, CreateSandboxVolumeRequest, - CreateServiceAccountRequest, CreateTokenRequest, CreateTrainingJobRequest, CreateTrainingJobResponse, @@ -76,12 +71,8 @@ DeactivateLoopsRunResponse, DeactivateLoopsSamplerResponse, DeactivateResponse, - DeletedAccessTrustRule, - DeletedIdentityProvider, - DeletedServiceAccount, DeleteImageParams, DeleteImageTagParams, - DeleteLoopsRunResponse, DeleteSandboxParams, DeleteSandboxPreviewParams, DeleteSandboxPreviewTokenParams, @@ -96,8 +87,6 @@ DeployLoopsCheckpointResponse, Deployment, DeploymentConfigResponse, - DeploymentReplica, - DeploymentReplicas, Deployments, DeploymentTombstone, DownloadDeploymentResponse, @@ -113,8 +102,6 @@ ExploreMetadataResponse, GatewayEventsResponse, GatewayKeyInfo, - GetAccessIdentityProvidersParams, - GetAccessTrustRulesParams, GetApiKeysParams, GetAuditLogsParams, GetAuthCodesResponse, @@ -129,6 +116,7 @@ GetDeploymentPatchesStateResponse, GetExploreMetadataParams, GetGatewayEventsParams, + GetGridClassifiersParams, GetGridConnectionsParams, GetGridMachineUsersParams, GetGridRouteClassifiersParams, @@ -166,12 +154,10 @@ GetModelsDeploymentsLogsParams, GetModelsDeploymentsMetricsParams, GetModelsDeploymentsParams, - GetModelsDeploymentsReplicasParams, GetModelsDeploymentsStartupsParams, GetModelsDeploymentsStartupsSummaryParams, GetModelsEnvironmentsLogsParams, GetModelsEnvironmentsMetricsParams, - GetModelsEnvironmentsReplicasParams, GetModelsEnvironmentsStartupsParams, GetModelsEnvironmentsStartupsSummaryParams, GetModelsParams, @@ -181,7 +167,6 @@ GetSandboxParams, GetSandboxPreviewParams, GetSandboxVolumeParams, - GetServiceAccountsParams, GetTeamsLoopsRunsParams, GetTeamsLoopsSamplersParams, GetTeamsModelsParams, @@ -204,6 +189,8 @@ GetVolumesParams, GetVolumesSyncsParams, GetVolumesVersionsParams, + GridClassifier, + GridClassifiersResponse, GridConnection, GridConnectionsResponse, GridConnectionTombstone, @@ -222,8 +209,6 @@ GridToken, Group, GroupsResponse, - IdentityProvider, - IdentityProviders, InstanceTypePrices, InstanceTypes, KeysForGroupResponse, @@ -257,10 +242,8 @@ ListVolumesResponse, ListVolumeVersionsResponse, LLMModelHandle, - LoopsCheckpoint, LoopsCheckpointFilesResponse, LoopsCheckpointSourceResponse, - LoopsCheckpointTombstone, LoopsDebugArchiveFilesResponse, Model, ModelAPI, @@ -278,7 +261,6 @@ PatchTeamTrainingGpuCapacityResponse, PatchVolumeRequest, PatchVolumeResponse, - PredefinedIdentityProviders, PrepareModelUploadRequest, PrepareModelUploadResponse, PromoteRequest, @@ -308,9 +290,6 @@ Secret, Secrets, SecretTombstone, - ServiceAccount, - ServiceAccounts, - SetLoopsCheckpointTtlRequest, SetVolumeTagRequest, SetVolumeTagResponse, SignalPromotionResponse, @@ -326,12 +305,9 @@ Teams, TerminateReplicaResponse, Token, - TokenExchangeRequest, - TokenExchangeResponse, ToolCallUsageResponse, TrainingJobTombstone, TrainingProjectTombstone, - UpdateAccessTrustRuleRequest, UpdateAutoscalingSettings, UpdateAutoscalingSettingsResponse, UpdateChainEnvironmentRequest, @@ -350,11 +326,9 @@ UpdateGridTeamSettingsRequest, UpdateGridUserSettingsRequest, UpdateGroupRequest, - UpdateIdentityProviderRequest, UpdateLibraryListingRequest, UpdateLibraryListingVersionRequest, UpdateModelRequest, - UpdateOrganizationRequest, UpdateRequestBackpressureSettings, UpdateSandboxParams, UpdateSandboxPreviewParams, @@ -362,7 +336,6 @@ UpdateSandboxRequest, UpdateSandboxVolumeParams, UpdateSandboxVolumeRequest, - UpdateServiceAccountRequest, UpdateTrainingJobRequest, UpdateTrainingJobResponse, UpsertSecretRequest, @@ -373,9 +346,6 @@ UsersResponse, ValidateLoopsCheckpointRequest, ValidateLoopsCheckpointResponse, - Verification, - VerifyAccessTrustRuleRequest, - VerifyIdentityProviderRequest, Volume, VolumeSync, VolumeSyncs, @@ -543,40 +513,6 @@ def create_sandbox_volume( ), ) - def delete_access_identity_providers( - self, *, identity_provider_id: str - ) -> DeletedIdentityProvider: - """Deletes an identity provider""" - return self._do_json( - DeletedIdentityProvider, - _ApiRequest( - method="DELETE", - path_fmt="/v1/access/identity_providers/{}", - path_args=[identity_provider_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def delete_access_trust_rules( - self, *, trust_rule_id: str - ) -> DeletedAccessTrustRule: - """Deletes a trust rule""" - return self._do_json( - DeletedAccessTrustRule, - _ApiRequest( - method="DELETE", - path_fmt="/v1/access/trust_rules/{}", - path_args=[trust_rule_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def delete_api_keys(self, *, api_key_prefix: str) -> APIKeyTombstone: """Deletes an API key by prefix""" return self._do_json( @@ -775,38 +711,6 @@ def delete_library_listings_versions( ), ) - def delete_loops_checkpoints( - self, *, checkpoint_id: str - ) -> LoopsCheckpointTombstone: - """Deletes a Loops checkpoint""" - return self._do_json( - LoopsCheckpointTombstone, - _ApiRequest( - method="DELETE", - path_fmt="/v1/loops/checkpoints/{}", - path_args=[checkpoint_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def delete_loops_runs(self, *, run_id: str) -> DeleteLoopsRunResponse: - """Deletes a Loops run""" - return self._do_json( - DeleteLoopsRunResponse, - _ApiRequest( - method="DELETE", - path_fmt="/v1/loops/runs/{}", - path_args=[run_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def delete_models(self, *, model_id: str) -> ModelTombstone: """Deletes a model by ID""" return self._do_json( @@ -873,23 +777,6 @@ def delete_models_environments( ), ) - def delete_models_environments_replicas( - self, *, model_id: str, env_name: str, replica_id: str - ) -> TerminateReplicaResponse: - """Terminates a replica in an environment""" - return self._do_json( - TerminateReplicaResponse, - _ApiRequest( - method="DELETE", - path_fmt="/v1/models/{}/environments/{}/replicas/{}", - path_args=[model_id, env_name, replica_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def delete_sandbox( self, *, sandbox_name: str, params: DeleteSandboxParams | None = None ) -> Sandbox: @@ -981,23 +868,6 @@ def delete_secrets(self, *, secret_name: str) -> SecretTombstone: ), ) - def delete_service_accounts( - self, *, service_account_id: str - ) -> DeletedServiceAccount: - """Deletes a service account""" - return self._do_json( - DeletedServiceAccount, - _ApiRequest( - method="DELETE", - path_fmt="/v1/service_accounts/{}", - path_args=[service_account_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def delete_teams_secrets( self, *, team_id: str, secret_name: str ) -> SecretTombstone: @@ -1110,89 +980,6 @@ def delete_volumes_versions( ), ) - def get_access_identity_providers( - self, *, params: GetAccessIdentityProvidersParams | None = None - ) -> IdentityProviders: - """Lists identity providers""" - return self._do_json( - IdentityProviders, - _ApiRequest( - method="GET", - path_fmt="/v1/access/identity_providers", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - def get_access_identity_providers_identity_provider_id( - self, *, identity_provider_id: str - ) -> IdentityProvider: - """Gets an identity provider""" - return self._do_json( - IdentityProvider, - _ApiRequest( - method="GET", - path_fmt="/v1/access/identity_providers/{}", - path_args=[identity_provider_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def get_access_predefined_identity_providers(self) -> PredefinedIdentityProviders: - """Lists predefined identity providers""" - return self._do_json( - PredefinedIdentityProviders, - _ApiRequest( - method="GET", - path_fmt="/v1/access/predefined_identity_providers", - path_args=[], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def get_access_trust_rules( - self, *, params: GetAccessTrustRulesParams | None = None - ) -> AccessTrustRules: - """Lists trust rules""" - return self._do_json( - AccessTrustRules, - _ApiRequest( - method="GET", - path_fmt="/v1/access/trust_rules", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - def get_access_trust_rules_trust_rule_id( - self, *, trust_rule_id: str - ) -> AccessTrustRule: - """Gets a trust rule""" - return self._do_json( - AccessTrustRule, - _ApiRequest( - method="GET", - path_fmt="/v1/access/trust_rules/{}", - path_args=[trust_rule_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def get_api_keys(self, *, params: GetApiKeysParams | None = None) -> APIKeys: """Lists API keys (metadata only, no plain text keys)""" return self._do_json( @@ -1595,6 +1382,40 @@ def get_gateway_groups_group_id(self, *, group_id: str) -> Group: ), ) + def get_grid_classifiers( + self, *, params: GetGridClassifiersParams | None = None + ) -> GridClassifiersResponse: + """Lists classifiers available for intelligent routes""" + return self._do_json( + GridClassifiersResponse, + _ApiRequest( + method="GET", + path_fmt="/v1/grid/classifiers", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + def get_grid_classifiers_classifier_id( + self, *, classifier_id: str + ) -> GridClassifier: + """Gets a classifier available for intelligent routes""" + return self._do_json( + GridClassifier, + _ApiRequest( + method="GET", + path_fmt="/v1/grid/classifiers/{}", + path_args=[classifier_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + def get_grid_connections( self, *, params: GetGridConnectionsParams | None = None ) -> GridConnectionsResponse: @@ -2447,44 +2268,6 @@ def get_models_deployments_production(self, *, model_id: str) -> Deployment: ), ) - def get_models_deployments_replicas( - self, - *, - model_id: str, - deployment_id: str, - params: GetModelsDeploymentsReplicasParams | None = None, - ) -> DeploymentReplicas: - """Lists replicas for a deployment""" - return self._do_json( - DeploymentReplicas, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/deployments/{}/replicas", - path_args=[model_id, deployment_id], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - def get_models_deployments_replicas_replica_id( - self, *, model_id: str, deployment_id: str, replica_id: str - ) -> DeploymentReplica: - """Gets a replica in a deployment""" - return self._do_json( - DeploymentReplica, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/deployments/{}/replicas/{}", - path_args=[model_id, deployment_id, replica_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def get_models_deployments_startups( self, *, @@ -2601,44 +2384,6 @@ def get_models_environments_metrics( ), ) - def get_models_environments_replicas( - self, - *, - model_id: str, - env_name: str, - params: GetModelsEnvironmentsReplicasParams | None = None, - ) -> DeploymentReplicas: - """Lists replicas for an environment""" - return self._do_json( - DeploymentReplicas, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/environments/{}/replicas", - path_args=[model_id, env_name], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - def get_models_environments_replicas_replica_id( - self, *, model_id: str, env_name: str, replica_id: str - ) -> DeploymentReplica: - """Gets a replica in an environment""" - return self._do_json( - DeploymentReplica, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/environments/{}/replicas/{}", - path_args=[model_id, env_name, replica_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def get_models_environments_startups( self, *, @@ -2845,40 +2590,6 @@ def get_secrets(self) -> Secrets: ), ) - def get_service_accounts( - self, *, params: GetServiceAccountsParams | None = None - ) -> ServiceAccounts: - """Lists service accounts""" - return self._do_json( - ServiceAccounts, - _ApiRequest( - method="GET", - path_fmt="/v1/service_accounts", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - def get_service_accounts_service_account_id( - self, *, service_account_id: str - ) -> ServiceAccount: - """Gets a service account""" - return self._do_json( - ServiceAccount, - _ApiRequest( - method="GET", - path_fmt="/v1/service_accounts/{}", - path_args=[service_account_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def get_teams(self, *, params: GetTeamsParams | None = None) -> Teams: """Lists all teams""" return self._do_json( @@ -3538,40 +3249,6 @@ def list_sandboxes( ), ) - def patch_access_identity_providers( - self, *, identity_provider_id: str, request: UpdateIdentityProviderRequest - ) -> IdentityProvider: - """Updates an identity provider""" - return self._do_json( - IdentityProvider, - _ApiRequest( - method="PATCH", - path_fmt="/v1/access/identity_providers/{}", - path_args=[identity_provider_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def patch_access_trust_rules( - self, *, trust_rule_id: str, request: UpdateAccessTrustRuleRequest - ) -> AccessTrustRule: - """Updates a trust rule""" - return self._do_json( - AccessTrustRule, - _ApiRequest( - method="PATCH", - path_fmt="/v1/access/trust_rules/{}", - path_args=[trust_rule_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def patch_chains_environments( self, *, chain_id: str, env_name: str, request: UpdateChainEnvironmentRequest ) -> UpdateChainEnvironmentResponse: @@ -3922,40 +3599,6 @@ def patch_models_environments( ), ) - def patch_organizations_me( - self, *, request: UpdateOrganizationRequest - ) -> OrganizationInfo: - """Updates the authenticated organization""" - return self._do_json( - OrganizationInfo, - _ApiRequest( - method="PATCH", - path_fmt="/v1/organizations/me", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def patch_service_accounts( - self, *, service_account_id: str, request: UpdateServiceAccountRequest - ) -> ServiceAccount: - """Updates a service account""" - return self._do_json( - ServiceAccount, - _ApiRequest( - method="PATCH", - path_fmt="/v1/service_accounts/{}", - path_args=[service_account_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def patch_teams_environment_groups( self, *, team_id: str, env_name: str, request: UpdateEnvironmentGroupRequest ) -> EnvironmentGroup: @@ -3976,7 +3619,7 @@ def patch_teams_environment_groups( def patch_training_capacity( self, *, request: PatchTeamTrainingGpuCapacityRequest ) -> PatchTeamTrainingGpuCapacityResponse: - """Sets a team's training GPU quota""" + """Sets a team's training GPU capacity""" return self._do_json( PatchTeamTrainingGpuCapacityResponse, _ApiRequest( @@ -4050,74 +3693,6 @@ def patch_volumes( ), ) - def post_access_identity_providers( - self, *, request: CreateIdentityProviderRequest - ) -> IdentityProvider: - """Adds an identity provider""" - return self._do_json( - IdentityProvider, - _ApiRequest( - method="POST", - path_fmt="/v1/access/identity_providers", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def post_access_identity_providers_verify( - self, *, request: VerifyIdentityProviderRequest - ) -> Verification: - """Checks an identity provider before adding it""" - return self._do_json( - Verification, - _ApiRequest( - method="POST", - path_fmt="/v1/access/identity_providers/verify", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def post_access_trust_rules( - self, *, request: CreateAccessTrustRuleRequest - ) -> AccessTrustRule: - """Creates a trust rule""" - return self._do_json( - AccessTrustRule, - _ApiRequest( - method="POST", - path_fmt="/v1/access/trust_rules", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - def post_access_trust_rules_verify( - self, *, request: VerifyAccessTrustRuleRequest - ) -> Verification: - """Checks a trust rule's condition and audience""" - return self._do_json( - Verification, - _ApiRequest( - method="POST", - path_fmt="/v1/access/trust_rules/verify", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: """Creates an API key""" return self._do_json( @@ -4133,23 +3708,6 @@ def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: ), ) - def post_auth_token( - self, *, request: TokenExchangeRequest - ) -> TokenExchangeResponse: - """Exchanges an identity provider's JWT for an access token""" - return self._do_json( - TokenExchangeResponse, - _ApiRequest( - method="POST", - path_fmt="/v1/auth/token", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def post_chains_deployments_deactivate( self, *, chain_id: str, chain_deployment_id: str ) -> DeactivateResponse: @@ -5082,23 +4640,6 @@ def post_secrets(self, *, request: UpsertSecretRequest) -> Secret: ), ) - def post_service_accounts( - self, *, request: CreateServiceAccountRequest - ) -> ServiceAccount: - """Creates a service account""" - return self._do_json( - ServiceAccount, - _ApiRequest( - method="POST", - path_fmt="/v1/service_accounts", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def post_teams_api_keys( self, *, team_id: str, request: CreateAPIKeyRequest ) -> APIKey: @@ -5520,23 +5061,6 @@ def push_image( ), ) - def put_loops_checkpoints_ttl( - self, *, checkpoint_id: str, request: SetLoopsCheckpointTtlRequest - ) -> LoopsCheckpoint: - """Sets a Loops checkpoint's TTL""" - return self._do_json( - LoopsCheckpoint, - _ApiRequest( - method="PUT", - path_fmt="/v1/loops/checkpoints/{}/ttl", - path_args=[checkpoint_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - def update_sandbox( self, *, @@ -5811,40 +5335,6 @@ async def create_sandbox_volume( ), ) - async def delete_access_identity_providers( - self, *, identity_provider_id: str - ) -> DeletedIdentityProvider: - """Deletes an identity provider""" - return await self._do_json( - DeletedIdentityProvider, - _ApiRequest( - method="DELETE", - path_fmt="/v1/access/identity_providers/{}", - path_args=[identity_provider_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def delete_access_trust_rules( - self, *, trust_rule_id: str - ) -> DeletedAccessTrustRule: - """Deletes a trust rule""" - return await self._do_json( - DeletedAccessTrustRule, - _ApiRequest( - method="DELETE", - path_fmt="/v1/access/trust_rules/{}", - path_args=[trust_rule_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def delete_api_keys(self, *, api_key_prefix: str) -> APIKeyTombstone: """Deletes an API key by prefix""" return await self._do_json( @@ -6045,38 +5535,6 @@ async def delete_library_listings_versions( ), ) - async def delete_loops_checkpoints( - self, *, checkpoint_id: str - ) -> LoopsCheckpointTombstone: - """Deletes a Loops checkpoint""" - return await self._do_json( - LoopsCheckpointTombstone, - _ApiRequest( - method="DELETE", - path_fmt="/v1/loops/checkpoints/{}", - path_args=[checkpoint_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def delete_loops_runs(self, *, run_id: str) -> DeleteLoopsRunResponse: - """Deletes a Loops run""" - return await self._do_json( - DeleteLoopsRunResponse, - _ApiRequest( - method="DELETE", - path_fmt="/v1/loops/runs/{}", - path_args=[run_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def delete_models(self, *, model_id: str) -> ModelTombstone: """Deletes a model by ID""" return await self._do_json( @@ -6143,23 +5601,6 @@ async def delete_models_environments( ), ) - async def delete_models_environments_replicas( - self, *, model_id: str, env_name: str, replica_id: str - ) -> TerminateReplicaResponse: - """Terminates a replica in an environment""" - return await self._do_json( - TerminateReplicaResponse, - _ApiRequest( - method="DELETE", - path_fmt="/v1/models/{}/environments/{}/replicas/{}", - path_args=[model_id, env_name, replica_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def delete_sandbox( self, *, sandbox_name: str, params: DeleteSandboxParams | None = None ) -> Sandbox: @@ -6251,23 +5692,6 @@ async def delete_secrets(self, *, secret_name: str) -> SecretTombstone: ), ) - async def delete_service_accounts( - self, *, service_account_id: str - ) -> DeletedServiceAccount: - """Deletes a service account""" - return await self._do_json( - DeletedServiceAccount, - _ApiRequest( - method="DELETE", - path_fmt="/v1/service_accounts/{}", - path_args=[service_account_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def delete_teams_secrets( self, *, team_id: str, secret_name: str ) -> SecretTombstone: @@ -6326,139 +5750,54 @@ async def delete_volumes( return await self._do_json( DeleteVolumeResponse, _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}", - path_args=[volume_namespace, volume_name], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def delete_volumes_tags( - self, - *, - volume_namespace: str, - volume_name: str, - volume_tag: str, - request: DeleteVolumeTagRequest, - ) -> DeleteVolumeTagResponse: - """Deletes a volume tag""" - return await self._do_json( - DeleteVolumeTagResponse, - _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}/tags/{}", - path_args=[volume_namespace, volume_name, volume_tag], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def delete_volumes_versions( - self, - *, - volume_namespace: str, - volume_name: str, - volume_version: str, - request: DeleteVolumeVersionRequest, - ) -> DeleteVolumeVersionResponse: - """Deletes one version of a volume""" - return await self._do_json( - DeleteVolumeVersionResponse, - _ApiRequest( - method="DELETE", - path_fmt="/v1/volumes/{}/{}/versions/{}", - path_args=[volume_namespace, volume_name, volume_version], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_access_identity_providers( - self, *, params: GetAccessIdentityProvidersParams | None = None - ) -> IdentityProviders: - """Lists identity providers""" - return await self._do_json( - IdentityProviders, - _ApiRequest( - method="GET", - path_fmt="/v1/access/identity_providers", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_access_identity_providers_identity_provider_id( - self, *, identity_provider_id: str - ) -> IdentityProvider: - """Gets an identity provider""" - return await self._do_json( - IdentityProvider, - _ApiRequest( - method="GET", - path_fmt="/v1/access/identity_providers/{}", - path_args=[identity_provider_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_access_predefined_identity_providers( - self, - ) -> PredefinedIdentityProviders: - """Lists predefined identity providers""" - return await self._do_json( - PredefinedIdentityProviders, - _ApiRequest( - method="GET", - path_fmt="/v1/access/predefined_identity_providers", - path_args=[], - body=None, + method="DELETE", + path_fmt="/v1/volumes/{}/{}", + path_args=[volume_namespace, volume_name], + body=request, query=None, success_codes=[200], error_codes=None, ), ) - async def get_access_trust_rules( - self, *, params: GetAccessTrustRulesParams | None = None - ) -> AccessTrustRules: - """Lists trust rules""" + async def delete_volumes_tags( + self, + *, + volume_namespace: str, + volume_name: str, + volume_tag: str, + request: DeleteVolumeTagRequest, + ) -> DeleteVolumeTagResponse: + """Deletes a volume tag""" return await self._do_json( - AccessTrustRules, + DeleteVolumeTagResponse, _ApiRequest( - method="GET", - path_fmt="/v1/access/trust_rules", - path_args=[], - body=None, - query=params, + method="DELETE", + path_fmt="/v1/volumes/{}/{}/tags/{}", + path_args=[volume_namespace, volume_name, volume_tag], + body=request, + query=None, success_codes=[200], error_codes=None, ), ) - async def get_access_trust_rules_trust_rule_id( - self, *, trust_rule_id: str - ) -> AccessTrustRule: - """Gets a trust rule""" + async def delete_volumes_versions( + self, + *, + volume_namespace: str, + volume_name: str, + volume_version: str, + request: DeleteVolumeVersionRequest, + ) -> DeleteVolumeVersionResponse: + """Deletes one version of a volume""" return await self._do_json( - AccessTrustRule, + DeleteVolumeVersionResponse, _ApiRequest( - method="GET", - path_fmt="/v1/access/trust_rules/{}", - path_args=[trust_rule_id], - body=None, + method="DELETE", + path_fmt="/v1/volumes/{}/{}/versions/{}", + path_args=[volume_namespace, volume_name, volume_version], + body=request, query=None, success_codes=[200], error_codes=None, @@ -6871,6 +6210,40 @@ async def get_gateway_groups_group_id(self, *, group_id: str) -> Group: ), ) + async def get_grid_classifiers( + self, *, params: GetGridClassifiersParams | None = None + ) -> GridClassifiersResponse: + """Lists classifiers available for intelligent routes""" + return await self._do_json( + GridClassifiersResponse, + _ApiRequest( + method="GET", + path_fmt="/v1/grid/classifiers", + path_args=[], + body=None, + query=params, + success_codes=[200], + error_codes=None, + ), + ) + + async def get_grid_classifiers_classifier_id( + self, *, classifier_id: str + ) -> GridClassifier: + """Gets a classifier available for intelligent routes""" + return await self._do_json( + GridClassifier, + _ApiRequest( + method="GET", + path_fmt="/v1/grid/classifiers/{}", + path_args=[classifier_id], + body=None, + query=None, + success_codes=[200], + error_codes=None, + ), + ) + async def get_grid_connections( self, *, params: GetGridConnectionsParams | None = None ) -> GridConnectionsResponse: @@ -7723,44 +7096,6 @@ async def get_models_deployments_production(self, *, model_id: str) -> Deploymen ), ) - async def get_models_deployments_replicas( - self, - *, - model_id: str, - deployment_id: str, - params: GetModelsDeploymentsReplicasParams | None = None, - ) -> DeploymentReplicas: - """Lists replicas for a deployment""" - return await self._do_json( - DeploymentReplicas, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/deployments/{}/replicas", - path_args=[model_id, deployment_id], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_models_deployments_replicas_replica_id( - self, *, model_id: str, deployment_id: str, replica_id: str - ) -> DeploymentReplica: - """Gets a replica in a deployment""" - return await self._do_json( - DeploymentReplica, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/deployments/{}/replicas/{}", - path_args=[model_id, deployment_id, replica_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def get_models_deployments_startups( self, *, @@ -7877,44 +7212,6 @@ async def get_models_environments_metrics( ), ) - async def get_models_environments_replicas( - self, - *, - model_id: str, - env_name: str, - params: GetModelsEnvironmentsReplicasParams | None = None, - ) -> DeploymentReplicas: - """Lists replicas for an environment""" - return await self._do_json( - DeploymentReplicas, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/environments/{}/replicas", - path_args=[model_id, env_name], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_models_environments_replicas_replica_id( - self, *, model_id: str, env_name: str, replica_id: str - ) -> DeploymentReplica: - """Gets a replica in an environment""" - return await self._do_json( - DeploymentReplica, - _ApiRequest( - method="GET", - path_fmt="/v1/models/{}/environments/{}/replicas/{}", - path_args=[model_id, env_name, replica_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def get_models_environments_startups( self, *, @@ -8121,40 +7418,6 @@ async def get_secrets(self) -> Secrets: ), ) - async def get_service_accounts( - self, *, params: GetServiceAccountsParams | None = None - ) -> ServiceAccounts: - """Lists service accounts""" - return await self._do_json( - ServiceAccounts, - _ApiRequest( - method="GET", - path_fmt="/v1/service_accounts", - path_args=[], - body=None, - query=params, - success_codes=[200], - error_codes=None, - ), - ) - - async def get_service_accounts_service_account_id( - self, *, service_account_id: str - ) -> ServiceAccount: - """Gets a service account""" - return await self._do_json( - ServiceAccount, - _ApiRequest( - method="GET", - path_fmt="/v1/service_accounts/{}", - path_args=[service_account_id], - body=None, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def get_teams(self, *, params: GetTeamsParams | None = None) -> Teams: """Lists all teams""" return await self._do_json( @@ -8816,40 +8079,6 @@ async def list_sandboxes( ), ) - async def patch_access_identity_providers( - self, *, identity_provider_id: str, request: UpdateIdentityProviderRequest - ) -> IdentityProvider: - """Updates an identity provider""" - return await self._do_json( - IdentityProvider, - _ApiRequest( - method="PATCH", - path_fmt="/v1/access/identity_providers/{}", - path_args=[identity_provider_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def patch_access_trust_rules( - self, *, trust_rule_id: str, request: UpdateAccessTrustRuleRequest - ) -> AccessTrustRule: - """Updates a trust rule""" - return await self._do_json( - AccessTrustRule, - _ApiRequest( - method="PATCH", - path_fmt="/v1/access/trust_rules/{}", - path_args=[trust_rule_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def patch_chains_environments( self, *, chain_id: str, env_name: str, request: UpdateChainEnvironmentRequest ) -> UpdateChainEnvironmentResponse: @@ -9202,40 +8431,6 @@ async def patch_models_environments( ), ) - async def patch_organizations_me( - self, *, request: UpdateOrganizationRequest - ) -> OrganizationInfo: - """Updates the authenticated organization""" - return await self._do_json( - OrganizationInfo, - _ApiRequest( - method="PATCH", - path_fmt="/v1/organizations/me", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def patch_service_accounts( - self, *, service_account_id: str, request: UpdateServiceAccountRequest - ) -> ServiceAccount: - """Updates a service account""" - return await self._do_json( - ServiceAccount, - _ApiRequest( - method="PATCH", - path_fmt="/v1/service_accounts/{}", - path_args=[service_account_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def patch_teams_environment_groups( self, *, team_id: str, env_name: str, request: UpdateEnvironmentGroupRequest ) -> EnvironmentGroup: @@ -9256,7 +8451,7 @@ async def patch_teams_environment_groups( async def patch_training_capacity( self, *, request: PatchTeamTrainingGpuCapacityRequest ) -> PatchTeamTrainingGpuCapacityResponse: - """Sets a team's training GPU quota""" + """Sets a team's training GPU capacity""" return await self._do_json( PatchTeamTrainingGpuCapacityResponse, _ApiRequest( @@ -9330,74 +8525,6 @@ async def patch_volumes( ), ) - async def post_access_identity_providers( - self, *, request: CreateIdentityProviderRequest - ) -> IdentityProvider: - """Adds an identity provider""" - return await self._do_json( - IdentityProvider, - _ApiRequest( - method="POST", - path_fmt="/v1/access/identity_providers", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def post_access_identity_providers_verify( - self, *, request: VerifyIdentityProviderRequest - ) -> Verification: - """Checks an identity provider before adding it""" - return await self._do_json( - Verification, - _ApiRequest( - method="POST", - path_fmt="/v1/access/identity_providers/verify", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def post_access_trust_rules( - self, *, request: CreateAccessTrustRuleRequest - ) -> AccessTrustRule: - """Creates a trust rule""" - return await self._do_json( - AccessTrustRule, - _ApiRequest( - method="POST", - path_fmt="/v1/access/trust_rules", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - - async def post_access_trust_rules_verify( - self, *, request: VerifyAccessTrustRuleRequest - ) -> Verification: - """Checks a trust rule's condition and audience""" - return await self._do_json( - Verification, - _ApiRequest( - method="POST", - path_fmt="/v1/access/trust_rules/verify", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: """Creates an API key""" return await self._do_json( @@ -9413,23 +8540,6 @@ async def post_api_keys(self, *, request: CreateAPIKeyRequest) -> APIKey: ), ) - async def post_auth_token( - self, *, request: TokenExchangeRequest - ) -> TokenExchangeResponse: - """Exchanges an identity provider's JWT for an access token""" - return await self._do_json( - TokenExchangeResponse, - _ApiRequest( - method="POST", - path_fmt="/v1/auth/token", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def post_chains_deployments_deactivate( self, *, chain_id: str, chain_deployment_id: str ) -> DeactivateResponse: @@ -10370,23 +9480,6 @@ async def post_secrets(self, *, request: UpsertSecretRequest) -> Secret: ), ) - async def post_service_accounts( - self, *, request: CreateServiceAccountRequest - ) -> ServiceAccount: - """Creates a service account""" - return await self._do_json( - ServiceAccount, - _ApiRequest( - method="POST", - path_fmt="/v1/service_accounts", - path_args=[], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def post_teams_api_keys( self, *, team_id: str, request: CreateAPIKeyRequest ) -> APIKey: @@ -10812,23 +9905,6 @@ async def push_image( ), ) - async def put_loops_checkpoints_ttl( - self, *, checkpoint_id: str, request: SetLoopsCheckpointTtlRequest - ) -> LoopsCheckpoint: - """Sets a Loops checkpoint's TTL""" - return await self._do_json( - LoopsCheckpoint, - _ApiRequest( - method="PUT", - path_fmt="/v1/loops/checkpoints/{}/ttl", - path_args=[checkpoint_id], - body=request, - query=None, - success_codes=[200], - error_codes=None, - ), - ) - async def update_sandbox( self, *, diff --git a/baseten/client/managementapi/_models.py b/baseten/client/managementapi/_models.py index 53b2707..b5f378f 100644 --- a/baseten/client/managementapi/_models.py +++ b/baseten/client/managementapi/_models.py @@ -828,111 +828,6 @@ class GetUsersParams(BaseModel): ] = None -class Name1(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Only the account with this name, ignoring case", - min_length=1, - title="Name", - ), - ] = None - - -class GetServiceAccountsParams(BaseModel): - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor returned by a previous page. Omit to fetch the first page.", - title="Cursor", - ), - ] = None - limit: Annotated[ - int, - Field( - description="Maximum number of items to return.", - ge=1, - le=1000, - title="Limit", - ), - ] = 100 - name: Annotated[ - Name1 | None, - Field( - description="Only the account with this name, ignoring case", title="Name" - ), - ] = None - team_id: Annotated[ - str | None, Field(description="Only this team's accounts", title="Team Id") - ] = None - disabled: Annotated[ - bool | None, - Field(description="Only disabled or enabled accounts", title="Disabled"), - ] = None - - -class Name2(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Only the provider with this name, ignoring case", - min_length=1, - title="Name", - ), - ] = None - - -class Name3(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Only the rule with this name, ignoring case", - min_length=1, - title="Name", - ), - ] = None - - -class GetAccessTrustRulesParams(BaseModel): - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor returned by a previous page. Omit to fetch the first page.", - title="Cursor", - ), - ] = None - limit: Annotated[ - int, - Field( - description="Maximum number of items to return.", - ge=1, - le=1000, - title="Limit", - ), - ] = 100 - name: Annotated[ - Name3 | None, - Field(description="Only the rule with this name, ignoring case", title="Name"), - ] = None - identity_provider_id: Annotated[ - str | None, - Field(description="Only this provider's rules", title="Identity Provider Id"), - ] = None - service_account_id: Annotated[ - str | None, - Field( - description="Only rules for this service account", - title="Service Account Id", - ), - ] = None - team_id: Annotated[ - str | None, - Field( - description="Only rules for this team's service accounts", title="Team Id" - ), - ] = None - - class Limit6(RootModel[int]): root: Annotated[ int | None, @@ -1054,7 +949,7 @@ class GetGridRoutesParams(BaseModel): name: Annotated[ str | None, Field( - description="Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", + description="Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", title="Name", ), ] = None @@ -1171,6 +1066,25 @@ class GetGridConnectionsParams(BaseModel): ] = None +class GetGridClassifiersParams(BaseModel): + cursor: Annotated[ + str | None, + Field( + description="Opaque cursor returned by a previous page. Omit to fetch the first page.", + title="Cursor", + ), + ] = None + limit: Annotated[ + int, + Field( + description="Maximum number of items to return.", + ge=1, + le=1000, + title="Limit", + ), + ] = 100 + + class GetGridRouteClassifiersParams(BaseModel): cursor: Annotated[ str | None, @@ -3415,21 +3329,9 @@ class PrepareModelUploadResponse(BaseModel): ] = None -class AuditFieldChange(BaseModel): - old: Annotated[Any, Field(description="The value before the update.", title="Old")] - new: Annotated[Any, Field(description="The value after the update.", title="New")] - - class AuditLogActor(BaseModel): type: Annotated[ - Literal[ - "USER", - "API_KEY", - "BASETEN_USER", - "BASETEN_SYSTEM", - "TOMBSTONE_USER", - "SERVICE_ACCOUNT", - ] + Literal["USER", "API_KEY", "BASETEN_USER", "BASETEN_SYSTEM", "TOMBSTONE_USER"] | str, Field( description="Kind of actor that performed the action.", @@ -3457,27 +3359,6 @@ class AuditLogActor(BaseModel): title="Api Key Name", ), ] = None - service_account_id: Annotated[ - str | None, - Field( - description="ID of the acting service account, when the actor is a service account.", - title="Service Account Id", - ), - ] = None - service_account_name: Annotated[ - str | None, - Field( - description="Current name of the acting service account, when the actor is a service account.", - title="Service Account Name", - ), - ] = None - trust_rule_id: Annotated[ - str | None, - Field( - description="ID of the trust rule the acting workload identity federation token was exchanged through, when the actor is a service account.", - title="Trust Rule Id", - ), - ] = None class AuditLogEventApiKeyCreated(BaseModel): @@ -3489,7 +3370,6 @@ class AuditLogEventApiKeyCreated(BaseModel): "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", - "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -3516,7 +3396,6 @@ class AuditLogEventApiKeyDeleted(BaseModel): "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", - "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -3532,7 +3411,7 @@ class AuditLogEventApiKeyDeleted(BaseModel): ), ] prefix: Annotated[str, Field(title="Prefix")] - revocation_reason: Literal["INACTIVITY", "CREDENTIAL_EXPOSURE"] | str | None = None + revocation_reason: Literal["INACTIVITY"] | str | None = None class AuditLogEventApiKeyLifetimeLimitsUpdated(BaseModel): @@ -3931,29 +3810,6 @@ class AuditLogEventGridMachineUserUpdated(BaseModel): team_name: Annotated[str, Field(title="Team Name")] -class AuditLogEventIdentityProviderDeleted(BaseModel): - event_type: Annotated[ - Literal["IDENTITY_PROVIDER_DELETED"], Field(title="Event Type") - ] - identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] - name: Annotated[str, Field(title="Name")] - - -class AuditLogEventIdentityProviderUpdated(BaseModel): - event_type: Annotated[ - Literal["IDENTITY_PROVIDER_UPDATED"], Field(title="Event Type") - ] - identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] - name: Annotated[str, Field(title="Name")] - changes: Annotated[ - dict[str, AuditFieldChange], - Field( - description="The fields the update changed, keyed by field name.", - title="Changes", - ), - ] - - class AuditLogEventModelDeleted(BaseModel): event_type: Annotated[Literal["MODEL_DELETED"], Field(title="Event Type")] model_id: Annotated[str, Field(title="Model Id")] @@ -4032,41 +3888,6 @@ class AuditLogEventModelRenamed(BaseModel): previous_name: Annotated[str | None, Field(title="Previous Name")] -class AuditLogEventOrganizationApiKeySettingsUpdated(BaseModel): - event_type: Annotated[ - Literal["ORGANIZATION_API_KEY_SETTINGS_UPDATED"], Field(title="Event Type") - ] - organization_id: Annotated[str, Field(title="Organization Id")] - previous_allow_personal_api_keys: Annotated[ - bool, Field(title="Previous Allow Personal Api Keys") - ] - new_allow_personal_api_keys: Annotated[ - bool, Field(title="New Allow Personal Api Keys") - ] - previous_allow_service_account_api_keys: Annotated[ - bool, Field(title="Previous Allow Service Account Api Keys") - ] - new_allow_service_account_api_keys: Annotated[ - bool, Field(title="New Allow Service Account Api Keys") - ] - - -class AuditLogEventPredefinedIdentityProviderConfig(BaseModel): - kind: Annotated[ - str, - Field( - description="Which predefined provider, for example `AWS_EKS`.", - title="Kind", - ), - ] - issuer_url: Annotated[ - str, - Field( - description="The `iss` claim of the provider's tokens.", title="Issuer Url" - ), - ] - - class AuditLogEventPromotionSettingsOverride(BaseModel): redeploy_on_promotion: Annotated[bool | None, Field(title="Redeploy On Promotion")] rolling_deploy: Annotated[bool | None, Field(title="Rolling Deploy")] @@ -4147,56 +3968,6 @@ class AuditLogEventSecretUpdated(BaseModel): secret_name: Annotated[str, Field(title="Secret Name")] -class AuditLogEventServiceAccountDeleted(BaseModel): - event_type: Annotated[Literal["SERVICE_ACCOUNT_DELETED"], Field(title="Event Type")] - service_account_id: Annotated[str, Field(title="Service Account Id")] - name: Annotated[str, Field(title="Name")] - - -class AuditLogEventServiceAccountPresetPermissions(BaseModel): - api_key_type: Annotated[ - str, - Field( - description="The API key type whose permissions the account has, as API key events record it.", - title="Api Key Type", - ), - ] - model_ids: Annotated[ - list[str], - Field( - description="Models the access is limited to; empty for all.", - title="Model Ids", - ), - ] - environment_names: Annotated[ - list[str], - Field( - description="Environments the access is limited to, or may also manage; empty for none.", - title="Environment Names", - ), - ] - model_api_slugs: Annotated[ - list[str], - Field( - description="Model APIs the access is limited to; empty for all.", - title="Model Api Slugs", - ), - ] - - -class AuditLogEventServiceAccountUpdated(BaseModel): - event_type: Annotated[Literal["SERVICE_ACCOUNT_UPDATED"], Field(title="Event Type")] - service_account_id: Annotated[str, Field(title="Service Account Id")] - name: Annotated[str, Field(title="Name")] - changes: Annotated[ - dict[str, AuditFieldChange], - Field( - description="The fields the update changed, keyed by field name.", - title="Changes", - ), - ] - - class AuditLogEventSshCertificateSigned(BaseModel): event_type: Annotated[Literal["SSH_CERTIFICATE_SIGNED"], Field(title="Event Type")] workload_type: Annotated[str, Field(title="Workload Type")] @@ -4236,57 +4007,6 @@ class AuditLogEventTelemetryExportUpdated(BaseModel): enabled: Annotated[bool | None, Field(title="Enabled")] -class AuditLogEventTrustRuleCreated(BaseModel): - event_type: Annotated[Literal["TRUST_RULE_CREATED"], Field(title="Event Type")] - trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] - name: Annotated[str, Field(title="Name")] - description: Annotated[ - str | None, - Field( - description="Null when the rule was created without one.", - title="Description", - ), - ] = None - identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] - service_account_id: Annotated[str, Field(title="Service Account Id")] - condition: Annotated[ - str, - Field( - description="The CEL expression a token's claims must satisfy.", - title="Condition", - ), - ] - audience: Annotated[ - str, Field(description="The `aud` claim a token must carry.", title="Audience") - ] - max_access_token_lifetime_seconds: Annotated[ - int, - Field( - description="The longest lifetime, in seconds, of an access token the rule issues.", - title="Max Access Token Lifetime Seconds", - ), - ] - - -class AuditLogEventTrustRuleDeleted(BaseModel): - event_type: Annotated[Literal["TRUST_RULE_DELETED"], Field(title="Event Type")] - trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] - name: Annotated[str, Field(title="Name")] - - -class AuditLogEventTrustRuleUpdated(BaseModel): - event_type: Annotated[Literal["TRUST_RULE_UPDATED"], Field(title="Event Type")] - trust_rule_id: Annotated[str, Field(title="Trust Rule Id")] - name: Annotated[str, Field(title="Name")] - changes: Annotated[ - dict[str, AuditFieldChange], - Field( - description="The fields the update changed, keyed by field name.", - title="Changes", - ), - ] - - class AuditLogEventUserInvited(BaseModel): event_type: Annotated[Literal["USER_INVITED"], Field(title="Event Type")] invited_user_email: Annotated[str, Field(title="Invited User Email")] @@ -4541,7 +4261,7 @@ class ModelTombstone(BaseModel): ] -class Name4(RootModel[str]): +class Name1(RootModel[str]): root: Annotated[ str | None, Field( @@ -4559,7 +4279,7 @@ class UpdateModelRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name4 | None, + Name1 | None, Field( description="New name for the model, unique within its team. Renaming does not change the model ID, endpoints, or deployments. Pushes that still use the old model_name create another model or target a model that now uses that name, so update config.yaml after renaming.", examples=["my-model"], @@ -4580,7 +4300,7 @@ class DeploymentTombstone(BaseModel): ] -class Name5(RootModel[str]): +class Name2(RootModel[str]): root: Annotated[ str | None, Field( @@ -4598,7 +4318,7 @@ class UpdateDeploymentRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name5 | None, + Name2 | None, Field( description="New name for the deployment, unique among the model's deployments. Only alphanumeric characters, hyphens, underscores, and periods are allowed.", examples=["my-deployment"], @@ -5165,102 +4885,39 @@ class StartupSummary(BaseModel): ] -class DeploymentReplica(BaseModel): - id: Annotated[ - str, +class TerminateReplicaResponse(BaseModel): + success: Annotated[ + bool, Field( - description="Pod-name suffix used for replica lookup and termination, usually five characters.", - title="Id", + description="Whether the replica was successfully terminated", + title="Success", ), - ] - deployment_id: Annotated[ - str, Field(description="ID of the replica's deployment.", title="Deployment Id") - ] - deployment_name: Annotated[ + ] = True + + +class SignSSHCertificateRequest(BaseModel): + public_key: Annotated[ str, - Field(description="Name of the replica's deployment.", title="Deployment Name"), - ] - status: Annotated[ - Literal[ - "STARTING", "ACTIVE", "UNHEALTHY", "TERMINATING", "TERMINATED", "UNKNOWN" - ] - | str, Field( - description="Current replica lifecycle status.", - title="DeploymentReplicaStatusV1", + description="The user's SSH public key (e.g., 'ssh-ed25519 AAAA... user@host').", + title="Public Key", ), ] - created_at: Annotated[ - AwareDatetime, + replica_id: Annotated[ + str | None, Field( - description="Replica creation time in ISO 8601 format.", title="Created At" + description="The replica to connect to. Required for training jobs (e.g. '0'). Optional for inference (server picks a running replica if omitted).", + title="Replica Id", ), - ] - terminated_at: Annotated[ - AwareDatetime | None, + ] = None + + +class SignSSHCertificateResponse(BaseModel): + ssh_certificate: Annotated[ + str, Field( - description="Observed termination completion time in ISO 8601 format, or null if unavailable.", - title="Terminated At", - ), - ] - age_seconds: Annotated[ - float, - Field( - description="Age in seconds since creation, frozen at termination.", - title="Age Seconds", - ), - ] - restart_count: Annotated[ - int | None, - Field( - description="Model container lifetime restart count, or null if unavailable.", - title="Restart Count", - ), - ] - - -class DeploymentReplicas(BaseModel): - items: Annotated[ - list[DeploymentReplica], Field(description="Items in this page.", title="Items") - ] - pagination: Annotated[ - PaginationResponse, Field(description="Pagination metadata for the page.") - ] - - -class TerminateReplicaResponse(BaseModel): - success: Annotated[ - bool, - Field( - description="Whether the replica was successfully terminated", - title="Success", - ), - ] = True - - -class SignSSHCertificateRequest(BaseModel): - public_key: Annotated[ - str, - Field( - description="The user's SSH public key (e.g., 'ssh-ed25519 AAAA... user@host').", - title="Public Key", - ), - ] - replica_id: Annotated[ - str | None, - Field( - description="The replica to connect to. Required for training jobs (e.g. '0'). Optional for inference (server picks a running replica if omitted).", - title="Replica Id", - ), - ] = None - - -class SignSSHCertificateResponse(BaseModel): - ssh_certificate: Annotated[ - str, - Field( - description="The signed SSH certificate in OpenSSH format.", - title="Ssh Certificate", + description="The signed SSH certificate in OpenSSH format.", + title="Ssh Certificate", ), ] jwt: Annotated[ @@ -6031,25 +5688,6 @@ class UpsertTrainingProjectRequest(BaseModel): ] -class TrainingBDNMountResponse(BaseModel): - source: Annotated[str, Field(title="Source")] - path: Annotated[str, Field(title="Path")] - include: Annotated[ - list[str] | None, - Field( - description="Relative glob patterns selecting files to mount; empty includes all files.", - title="Include", - ), - ] = None - exclude: Annotated[ - list[str] | None, - Field( - description="Relative glob patterns excluding files from the mount; exclusions win.", - title="Exclude", - ), - ] = None - - class TrainingProjectSummary(BaseModel): id: Annotated[ str, Field(description="Unique identifier of the training project.", title="Id") @@ -6205,28 +5843,6 @@ class SecretReference(BaseModel): ] -class TrainingBDNMount(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - source: Annotated[str, Field(title="Source")] - path: Annotated[str, Field(title="Path")] - include: Annotated[ - list[str] | None, - Field( - description="Relative glob patterns selecting files to mount; empty includes all files.", - title="Include", - ), - ] = None - exclude: Annotated[ - list[str] | None, - Field( - description="Relative glob patterns excluding files from the mount; exclusions win.", - title="Exclude", - ), - ] = None - - class TrainingWeightAuth(BaseModel): auth_method: Annotated[ Literal[ @@ -6936,7 +6552,7 @@ class LoopsSampler(BaseModel): ] = None -class Name6(RootModel[str]): +class Name3(RootModel[str]): root: Annotated[ str | None, Field( @@ -6972,7 +6588,7 @@ class CreateLoopsRunRequest(BaseModel): Field(description="Base model ID (e.g. 'Qwen/Qwen3-8B').", title="Base Model"), ] name: Annotated[ - Name6 | None, + Name3 | None, Field( description="Optional display name for the run. Defaults to the base model name when omitted.", title="Name", @@ -7041,22 +6657,10 @@ class CreateLoopsRunRequest(BaseModel): base_checkpoint: Annotated[ str | None, Field( - description="Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + description="Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", title="Base Checkpoint", ), ] = None - base_checkpoint_auth: Annotated[ - TrainingWeightAuth | None, - Field( - description="Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", - examples=[ - { - "auth_method": "CUSTOM_SECRET", - "auth_secret_name": "hf_read_my_checkpoint", - } - ], - ), - ] = None sampler_num_replicas: Annotated[ SamplerNumReplicas | None, Field( @@ -7078,25 +6682,6 @@ class DeactivateLoopsRunResponse(BaseModel): user: Annotated[User, Field(description="The user who owns the Loops run.")] -class LoopsLoRAConfig(BaseModel): - config_version: Annotated[ - str, Field(description="The config version, like v1.", title="Config Version") - ] - targets: Annotated[ - list[str], - Field( - description="The module names the LoRA adapter targets.", title="Targets" - ), - ] - expert_layout: Annotated[ - Literal["per_expert", "shared_outer", "shared_adapter"] | str | None, - Field( - description="How routed-expert LoRA weights are laid out. Null when no experts are targeted.", - title="Expert Layout", - ), - ] = None - - class CreateLoopsTrainerRequest(BaseModel): session_id: Annotated[ str, @@ -7110,7 +6695,7 @@ class CreateLoopsTrainerRequest(BaseModel): Field(description="Base model ID (e.g. 'Qwen/Qwen3-8B').", title="Base Model"), ] name: Annotated[ - Name6 | None, + Name3 | None, Field( description="Optional display name for the run. Defaults to the base model name when omitted.", title="Name", @@ -7179,22 +6764,10 @@ class CreateLoopsTrainerRequest(BaseModel): base_checkpoint: Annotated[ str | None, Field( - description="Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + description="Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", title="Base Checkpoint", ), ] = None - base_checkpoint_auth: Annotated[ - TrainingWeightAuth | None, - Field( - description="Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", - examples=[ - { - "auth_method": "CUSTOM_SECRET", - "auth_secret_name": "hf_read_my_checkpoint", - } - ], - ), - ] = None scope: Annotated[ Literal["default", "serverless", "dedicated"] | str, Field( @@ -7309,6 +6882,25 @@ class GetLoopsSamplerResponse(BaseModel): sampler: Annotated[LoopsSampler, Field(description="The Loops sampler.")] +class LoopsLoRAConfig(BaseModel): + config_version: Annotated[ + str, Field(description="The config version, like v1.", title="Config Version") + ] + targets: Annotated[ + list[str], + Field( + description="The module names the LoRA adapter targets.", title="Targets" + ), + ] + expert_layout: Annotated[ + Literal["per_expert", "shared_outer", "shared_adapter"] | str | None, + Field( + description="How routed-expert LoRA weights are laid out. Null when no experts are targeted.", + title="Expert Layout", + ), + ] = None + + class ValidateLoopsCheckpointRequest(BaseModel): checkpoint_path: Annotated[ str, @@ -7376,34 +6968,6 @@ class DeployLoopsCheckpointResponse(BaseModel): ] -class LoopsCheckpointTombstone(BaseModel): - id: Annotated[str, Field(description="The deleted checkpoint ID.", title="Id")] - run_id: Annotated[ - str, - Field( - description="The ID of the run that produced the checkpoint.", - title="Run Id", - ), - ] - checkpoint_id: Annotated[ - str, - Field( - description="The name the checkpoint was saved under.", - title="Checkpoint Id", - ), - ] - target: Annotated[ - Literal["sampler", "trainer"] | str, - Field( - description="Whether the checkpoint was loadable by the sampler or by the run.", - title="TrainerCheckpointTarget", - ), - ] - path: Annotated[ - str, Field(description="The checkpoint's bt:// path.", title="Path") - ] - - class LoopsCheckpointFilesResponse(BaseModel): presigned_urls: Annotated[ list[CheckpointFile], @@ -7465,28 +7029,6 @@ class LoopsCheckpointSourceResponse(BaseModel): ] -class TtlSeconds(RootModel[int]): - root: Annotated[ - int, - Field( - description="Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", - ge=3600, - le=315360000, - title="Ttl Seconds", - ), - ] - - -class SetLoopsCheckpointTtlRequest(BaseModel): - ttl_seconds: Annotated[ - TtlSeconds | None, - Field( - description="Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", - title="Ttl Seconds", - ), - ] - - class LoopsDeploymentStatus(BaseModel): name: Annotated[ Literal[ @@ -7679,14 +7221,14 @@ class TeamTrainingGpuCapacityItem(BaseModel): baseline: Annotated[ int, Field( - description="Configured minimum GPU allocation for the team. Not enforced. 0 if not configured.", + description="Baseline GPU allocation for the team. 0 if not configured.", title="Baseline", ), ] limit: Annotated[ int, Field( - description="The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", + description="Maximum concurrent GPUs of this type for this team", title="Limit", ), ] @@ -7700,7 +7242,7 @@ class TeamTrainingGpuCapacityItem(BaseModel): dedicated_usage_count: Annotated[ int, Field( - description="Portion of usage_count from on-demand (non-spot) jobs.", + description="Portion of usage_count from standard (non-spot) jobs.", title="Dedicated Usage Count", ), ] = 0 @@ -7723,31 +7265,17 @@ class TrainingGpuCapacityItem(BaseModel): baseline: Annotated[ int, Field( - description="Configured minimum GPU allocation (`min_gpus`). 0 if not configured. Use `on_demand_quota` for the quota applied to on-demand jobs.", + description="Baseline GPU allocation; jobs below this threshold are expected to run immediately. 0 if not configured.", title="Baseline", ), ] limit: Annotated[ int, Field( - description="Configured maximum GPU allocation (`max_gpus`). Use `on_demand_quota` and `spot_quota` for the quotas applied to jobs.", + description="Maximum concurrent GPUs of this type for this org", title="Limit", ), ] - on_demand_quota: Annotated[ - int, - Field( - description="GPU quota for this type for on-demand (non-spot) jobs: the most GPUs they can use at once.", - title="On Demand Quota", - ), - ] - spot_quota: Annotated[ - int | None, - Field( - description="GPU quota for this type for spot jobs. Spot shares this quota with on-demand jobs: spot can use up to the quota minus on-demand GPUs in use. Null if spot is not enabled for the organization.", - title="Spot Quota", - ), - ] = None usage_count: Annotated[ int, Field( @@ -7758,14 +7286,14 @@ class TrainingGpuCapacityItem(BaseModel): dedicated_usage_count: Annotated[ int, Field( - description="Portion of usage_count from on-demand (non-spot) jobs.", + description="Portion of usage_count from standard (non-spot) jobs, which run against the baseline.", title="Dedicated Usage Count", ), ] = 0 spot_usage_count: Annotated[ int, Field( - description="Portion of usage_count from spot jobs.", + description="Portion of usage_count from spot jobs, which burst into the peak and may push usage above the limit.", title="Spot Usage Count", ), ] = 0 @@ -7775,24 +7303,17 @@ class GetTrainingGpuCapacityResponse(BaseModel): gpu_capacities: Annotated[ list[TrainingGpuCapacityItem], Field( - description="Organization GPU quotas and current usage per GPU type", + description="Org-level GPU capacity limits and current usage per GPU type", title="Gpu Capacities", ), ] team_gpu_capacities: Annotated[ list[TeamTrainingGpuCapacityItem] | None, Field( - description="Per-team GPU quotas and current usage per GPU type", + description="Per-team GPU capacity limits and current usage per GPU type", title="Team Gpu Capacities", ), ] = None - spot_enabled: Annotated[ - bool, - Field( - description="Whether the organization can submit spot training jobs.", - title="Spot Enabled", - ), - ] = False class PatchTeamTrainingGpuCapacityRequest(BaseModel): @@ -7806,7 +7327,7 @@ class PatchTeamTrainingGpuCapacityRequest(BaseModel): max_gpus: Annotated[ int, Field( - description="The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", + description="Max concurrent GPUs of this type the team may use", examples=[8, 16, 32], title="Max Gpus", ), @@ -7815,7 +7336,8 @@ class PatchTeamTrainingGpuCapacityRequest(BaseModel): class PatchTeamTrainingGpuCapacityResponse(BaseModel): team_gpu_capacity: Annotated[ - TeamTrainingGpuCapacityItem, Field(description="The updated per-team GPU quota") + TeamTrainingGpuCapacityItem, + Field(description="The updated per-team GPU capacity limit"), ] @@ -8868,7 +8390,7 @@ class Subtotal5(RootModel[str]): root: Annotated[ str, Field( - description="Usage charges in dollars before applying credits", + description="Subtotal cost in dollars after applying credits used", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), @@ -8993,20 +8515,6 @@ class ModelApiItem(BaseModel): float | Subtotal10, Field(description="Subtotal cost in dollars for this model", title="Subtotal"), ] - team_id: Annotated[ - str | None, - Field( - description="Team ID for multi-team organizations; otherwise null", - title="Team Id", - ), - ] = None - team_name: Annotated[ - str | None, - Field( - description="Team name, including historical teams; null if unavailable", - title="Team Name", - ), - ] = None input_tokens: Annotated[ int, Field(description="Total input tokens for this model", title="Input Tokens"), @@ -9035,32 +8543,18 @@ class Subtotal11(RootModel[str]): root: Annotated[ str, Field( - description="Usage charges in dollars before applying credits", + description="Subtotal cost in dollars after applying credits used", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), ] -class Total2(RootModel[str]): - model_config = ConfigDict( - regex_engine="python-re", - ) - root: Annotated[ - str, - Field( - description="Usage charges in dollars after applying credits, floored at zero", - pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", - title="Total", - ), - ] - - class ModelApisUsage(BaseModel): subtotal: Annotated[ float | Subtotal11, Field( - description="Usage charges in dollars before applying credits", + description="Subtotal cost in dollars after applying credits used", title="Subtotal", ), ] @@ -9069,18 +8563,11 @@ class ModelApisUsage(BaseModel): Field(description="Credits applied in dollars", title="Credits Used"), ] total: Annotated[ - float | Total2, - Field( - description="Usage charges in dollars after applying credits, floored at zero", - title="Total", - ), + float | Total, Field(description="Total cost in dollars", title="Total") ] breakdown: Annotated[ list[ModelApiItem] | None, - Field( - description="Per-model usage breakdown, split by team for multi-team organizations", - title="Breakdown", - ), + Field(description="Per-model usage breakdown", title="Breakdown"), ] = None @@ -9105,27 +8592,13 @@ class Subtotal13(RootModel[str]): root: Annotated[ str, Field( - description="Usage charges in dollars before applying credits", + description="Subtotal cost in dollars after applying credits used", pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", title="Subtotal", ), ] -class Total3(RootModel[str]): - model_config = ConfigDict( - regex_engine="python-re", - ) - root: Annotated[ - str, - Field( - description="Total cost in dollars", - pattern="^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$", - title="Total", - ), - ] - - class ToolCallUsageBucket(BaseModel): date: Annotated[ date_aliased, @@ -9228,802 +8701,23 @@ class OrganizationInfo(BaseModel): description="AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" ), ] = None - allow_personal_api_keys: Annotated[ - bool, - Field( - description="Whether members can create new personal API keys. Existing keys keep working.", - title="Allow Personal Api Keys", - ), + + +class GatewayEventTokens(BaseModel): + inputTokens: Annotated[ + int, Field(description="Cached and uncached input tokens.", title="Inputtokens") ] - allow_service_account_api_keys: Annotated[ - bool, - Field( - description="Whether new team and organization API keys can be created. Existing keys keep working.", - title="Allow Service Account Api Keys", - ), + outputTokens: Annotated[ + int, Field(description="Output tokens.", title="Outputtokens") + ] + cachedInputTokens: Annotated[ + int, Field(description="Cached input tokens.", title="Cachedinputtokens") ] -class UpdateOrganizationRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - allow_personal_api_keys: Annotated[ - bool | None, - Field( - description="Whether members can create new personal API keys. Null is not accepted.", - title="Allow Personal Api Keys", - ), - ] = None - allow_service_account_api_keys: Annotated[ - bool | None, - Field( - description="Whether new team and organization API keys can be created. Null is not accepted.", - title="Allow Service Account Api Keys", - ), - ] = None - - -class ServiceAccountPresetPermissionsRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - type: Annotated[ - Literal[ - "WORKSPACE_MANAGE_ALL", - "WORKSPACE_INVOKE", - "WORKSPACE_EXPORT_METRICS", - "WORKSPACE_MANAGE_API_KEYS", - "WORKSPACE_INVOKE_MODEL_APIS", - ] - | str, - Field( - description="What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", - examples=["WORKSPACE_MANAGE_ALL"], - title="ServiceAccountPresetTypeV1", - ), - ] - model_ids: Annotated[ - list[str] | None, - Field( - description="WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", - examples=[["abcd1234"]], - title="Model Ids", - ), - ] = None - environment_names: Annotated[ - list[str] | None, - Field( - description="WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", - examples=[["production"]], - title="Environment Names", - ), - ] = None - model_api_slugs: Annotated[ - list[str] | None, - Field( - description="WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", - examples=[["my-model-api"]], - title="Model Api Slugs", - ), - ] = None - - -class Description(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Optional description, up to 1,024 characters", - max_length=1024, - title="Description", - ), - ] = None - - -class TeamId4(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="The team that owns the account. Omit for an organization account. Can't be changed.", - min_length=1, - title="Team Id", - ), - ] = None - - -class CreateServiceAccountRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - name: Annotated[ - str, - Field( - description="Name, unique in the organization. Can be changed later.", - examples=["ci-deployer"], - max_length=255, - min_length=1, - title="Name", - ), - ] - description: Annotated[ - Description | None, - Field( - description="Optional description, up to 1,024 characters", - title="Description", - ), - ] = None - team_id: Annotated[ - TeamId4 | None, - Field( - description="The team that owns the account. Omit for an organization account. Can't be changed.", - title="Team Id", - ), - ] = None - preset_permissions: Annotated[ - ServiceAccountPresetPermissionsRequest, - Field( - description="What the service account may do. Can be changed later. Temporary; may be removed once fine-grained access control is available." - ), - ] - - -class DeletedServiceAccount(BaseModel): - id: Annotated[ - str, Field(description="ID of the deleted service account", title="Id") - ] - deleted: Annotated[bool, Field(description="Always true", title="Deleted")] - - -class Name8(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Name, unique in the organization", - max_length=255, - min_length=1, - title="Name", - ), - ] = None - - -class Description1(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Description, up to 1,024 characters; null clears it", - max_length=1024, - title="Description", - ), - ] = None - - -class UpdateServiceAccountRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - name: Annotated[ - Name8 | None, - Field(description="Name, unique in the organization", title="Name"), - ] = None - description: Annotated[ - Description1 | None, - Field( - description="Description, up to 1,024 characters; null clears it", - title="Description", - ), - ] = None - disabled: Annotated[ - bool | None, - Field( - description="Disable the account to stop it being used, or enable it again", - title="Disabled", - ), - ] = None - preset_permissions: Annotated[ - ServiceAccountPresetPermissionsRequest | None, - Field( - description="Replaces the account's access as a whole. Temporary; may be removed once fine-grained access control is available." - ), - ] = None - - -class PredefinedIdentityProvider(BaseModel): - kind: Annotated[ - Literal[ - "GITHUB_ACTIONS", - "GCP", - "BASETEN", - "AWS_IAM", - "AWS_EKS", - "AZURE_MANAGED_IDENTITY_V1", - "AZURE_MANAGED_IDENTITY_V2", - "AZURE_AKS", - ] - | str, - Field( - description="Pass as `kind` when adding the provider", - title="PredefinedIdentityProviderKindV1", - ), - ] - name: Annotated[str, Field(description="Display name", title="Name")] - issuer_url: Annotated[ - str | None, - Field( - description="The `iss` claim its tokens carry. Null when each account, tenant, or cluster has its own issuer, which you pass as `issuer_url` when adding the provider.", - title="Issuer Url", - ), - ] = None - issuer_url_example: Annotated[ - str | None, - Field( - description="An example of the `issuer_url` to pass. Null when the issuer is fixed.", - title="Issuer Url Example", - ), - ] = None - - -class PredefinedIdentityProviders(BaseModel): - items: Annotated[ - list[PredefinedIdentityProvider], - Field(description="Identity providers Baseten supports", title="Items"), - ] - - -class IssuerUrl(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", - max_length=1024, - title="Issuer Url", - ), - ] = None - - -class PredefinedIdentityProviderConfig(BaseModel): - kind: Annotated[ - Literal[ - "GITHUB_ACTIONS", - "GCP", - "BASETEN", - "AWS_IAM", - "AWS_EKS", - "AZURE_MANAGED_IDENTITY_V1", - "AZURE_MANAGED_IDENTITY_V2", - "AZURE_AKS", - ] - | str, - Field( - description="Which predefined provider. Can't be changed.", - title="PredefinedIdentityProviderKindV1", - ), - ] - issuer_url: Annotated[ - IssuerUrl | None, - Field( - description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", - title="Issuer Url", - ), - ] = None - - -class CreatePredefinedIdentityProviderConfig(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - kind: Annotated[ - Literal[ - "GITHUB_ACTIONS", - "GCP", - "BASETEN", - "AWS_IAM", - "AWS_EKS", - "AZURE_MANAGED_IDENTITY_V1", - "AZURE_MANAGED_IDENTITY_V2", - "AZURE_AKS", - ] - | str, - Field( - description="Which predefined provider. Can't be changed.", - title="PredefinedIdentityProviderKindV1", - ), - ] - issuer_url: Annotated[ - IssuerUrl | None, - Field( - description="The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", - title="Issuer Url", - ), - ] = None - - -class Name9(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", - max_length=255, - min_length=1, - title="Name", - ), - ] = None - - -class Description2(RootModel[str]): - root: Annotated[ - str | None, - Field(description="Optional description", max_length=1024, title="Description"), - ] = None - - -class CreateIdentityProviderRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - name: Annotated[ - Name9 | None, - Field( - description="Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", - title="Name", - ), - ] = None - description: Annotated[ - Description2 | None, - Field(description="Optional description", title="Description"), - ] = None - predefined: Annotated[ - CreatePredefinedIdentityProviderConfig, - Field(description="The predefined provider to add"), - ] - - -class VerifyPredefinedIdentityProviderConfig(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - kind: Annotated[ - Literal[ - "GITHUB_ACTIONS", - "GCP", - "BASETEN", - "AWS_IAM", - "AWS_EKS", - "AZURE_MANAGED_IDENTITY_V1", - "AZURE_MANAGED_IDENTITY_V2", - "AZURE_AKS", - ] - | str, - Field( - description="Which predefined provider", - title="PredefinedIdentityProviderKindV1", - ), - ] - issuer_url: Annotated[ - str | None, - Field( - description="The issuer to check, for AWS IAM, Amazon EKS, Azure managed identity, and Azure Kubernetes Service, in the format the predefined identity providers endpoint shows", - title="Issuer Url", - ), - ] = None - - -class VerifyIdentityProviderRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - predefined: Annotated[ - VerifyPredefinedIdentityProviderConfig, - Field( - description="The predefined provider to check, as you'd pass it when adding it" - ), - ] - - -class Verification(BaseModel): - valid: Annotated[ - bool, Field(description="Whether the input passes every check", title="Valid") - ] - error: Annotated[ - str | None, - Field( - description="Why the input fails, as creating it would report. Null when it's valid.", - title="Error", - ), - ] = None - - -class DeletedIdentityProvider(BaseModel): - id: Annotated[ - str, Field(description="ID of the deleted identity provider", title="Id") - ] - deleted: Annotated[bool, Field(description="Always true", title="Deleted")] - - -class Name10(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Name, unique in the organization", - max_length=255, - min_length=1, - title="Name", - ), - ] = None - - -class Description3(RootModel[str]): - root: Annotated[ - str | None, - Field( - description="Description; null clears it", - max_length=1024, - title="Description", - ), - ] = None - - -class UpdateIdentityProviderRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - name: Annotated[ - Name10 | None, - Field(description="Name, unique in the organization", title="Name"), - ] = None - description: Annotated[ - Description3 | None, - Field(description="Description; null clears it", title="Description"), - ] = None - - -class AccessTrustRule(BaseModel): - id: Annotated[ - str, - Field( - description="Trust rule ID. Workloads pass it when they exchange a token.", - title="Id", - ), - ] - name: Annotated[ - str, Field(description="Name, unique in the organization", title="Name") - ] - description: Annotated[ - str | None, Field(description="Description", title="Description") - ] = None - identity_provider_id: Annotated[ - str, - Field( - description="The identity provider whose tokens it accepts", - title="Identity Provider Id", - ), - ] - identity_provider_name: Annotated[ - str, - Field( - description="Name of the identity provider", title="Identity Provider Name" - ), - ] - service_account_id: Annotated[ - str, - Field( - description="The service account its tokens act as", - title="Service Account Id", - ), - ] - service_account_name: Annotated[ - str, - Field(description="Name of the service account", title="Service Account Name"), - ] - team_id: Annotated[ - str | None, - Field( - description="The service account's team. Null for an organization service account.", - title="Team Id", - ), - ] = None - team_name: Annotated[ - str | None, - Field( - description="Name of the service account's team. Null for an organization service account.", - title="Team Name", - ), - ] = None - condition: Annotated[ - str, - Field( - description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", - examples=[ - "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" - ], - title="Condition", - ), - ] - audience: Annotated[ - str, - Field( - description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", - title="Audience", - ), - ] - max_access_token_lifetime_seconds: Annotated[ - int, - Field( - description="Longest lifetime of a token the rule issues, in seconds", - title="Max Access Token Lifetime Seconds", - ), - ] - last_used_at: Annotated[ - AwareDatetime | None, - Field( - description="Last time a request authenticated with a token the rule issued, to within an hour. Null until the first.", - title="Last Used At", - ), - ] = None - created_by: Annotated[ - str, - Field(description="ID of the user who created the rule", title="Created By"), - ] - created_at: Annotated[ - AwareDatetime, - Field(description="Time the rule was created", title="Created At"), - ] - updated_at: Annotated[ - AwareDatetime, - Field(description="Time the rule was last updated", title="Updated At"), - ] - - -class AccessTrustRules(BaseModel): - items: Annotated[ - list[AccessTrustRule], Field(description="Items in this page.", title="Items") - ] - pagination: Annotated[ - PaginationResponse, Field(description="Pagination metadata for the page.") - ] - - -class CreateAccessTrustRuleRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - name: Annotated[ - str, - Field( - description="Name, unique in the organization. Can be changed later.", - max_length=255, - min_length=1, - title="Name", - ), - ] - description: Annotated[ - str | None, Field(description="Optional description", title="Description") - ] = None - identity_provider_id: Annotated[ - str, - Field( - description="Whose tokens the rule accepts. Can't be changed.", - title="Identity Provider Id", - ), - ] - service_account_id: Annotated[ - str, - Field( - description="The service account its tokens act as. Can be changed later.", - title="Service Account Id", - ), - ] - condition: Annotated[ - str, - Field( - description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters. Can be changed later.", - examples=[ - "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" - ], - title="Condition", - ), - ] - audience: Annotated[ - str, - Field( - description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters. Can be changed later.", - title="Audience", - ), - ] - max_access_token_lifetime_seconds: Annotated[ - int, - Field( - description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Can be changed later.", - ge=60, - le=3600, - title="Max Access Token Lifetime Seconds", - ), - ] = 3600 - - -class VerifyAccessTrustRuleRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - identity_provider_id: Annotated[ - str, - Field( - description="The identity provider the rule is for, which decides the claims it must pin", - title="Identity Provider Id", - ), - ] - condition: Annotated[ - str, - Field( - description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", - examples=[ - "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" - ], - title="Condition", - ), - ] - audience: Annotated[ - str, - Field( - description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", - title="Audience", - ), - ] - - -class DeletedAccessTrustRule(BaseModel): - id: Annotated[str, Field(description="ID of the deleted trust rule", title="Id")] - deleted: Annotated[bool, Field(description="Always true", title="Deleted")] - - -class MaxAccessTokenLifetimeSeconds(RootModel[int]): - root: Annotated[ - int | None, - Field( - description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", - ge=60, - le=3600, - title="Max Access Token Lifetime Seconds", - ), - ] = None - - -class UpdateAccessTrustRuleRequest(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - name: Annotated[ - Name10 | None, - Field(description="Name, unique in the organization", title="Name"), - ] = None - description: Annotated[ - str | None, - Field(description="Description; null clears it", title="Description"), - ] = None - condition: Annotated[ - str | None, - Field( - description="A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", - title="Condition", - ), - ] = None - audience: Annotated[ - str | None, - Field( - description="The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", - title="Audience", - ), - ] = None - max_access_token_lifetime_seconds: Annotated[ - MaxAccessTokenLifetimeSeconds | None, - Field( - description="Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", - title="Max Access Token Lifetime Seconds", - ), - ] = None - service_account_id: Annotated[ - str | None, - Field( - description="Moves the rule to another service account. Tokens already issued keep the old account until they expire.", - title="Service Account Id", - ), - ] = None - - -class AccessTokenLifetimeSeconds(RootModel[int]): - root: Annotated[ - int | None, - Field( - description="Lifetime of the access token, in seconds. At most the rule's maximum.", - ge=1, - title="Access Token Lifetime Seconds", - ), - ] = None - - -class TokenExchangeRequest(BaseModel): - grant_type: Annotated[ - str, - Field( - description="Always `urn:ietf:params:oauth:grant-type:token-exchange`", - examples=["urn:ietf:params:oauth:grant-type:token-exchange"], - title="Grant Type", - ), - ] - subject_token: Annotated[ - str, - Field( - description="The identity provider's JWT", - examples=[""], - max_length=16384, - title="Subject Token", - ), - ] - subject_token_type: Annotated[ - str, - Field( - description="`urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`", - examples=["urn:ietf:params:oauth:token-type:jwt"], - title="Subject Token Type", - ), - ] - audience: Annotated[ - str, - Field( - description="ID of the trust rule to check the JWT against", - examples=["abcd1234"], - max_length=64, - title="Audience", - ), - ] - requested_token_type: Annotated[ - str | None, - Field( - description="Optional; only `urn:ietf:params:oauth:token-type:access_token` is issued", - title="Requested Token Type", - ), - ] = None - access_token_lifetime_seconds: Annotated[ - AccessTokenLifetimeSeconds | None, - Field( - description="Lifetime of the access token, in seconds. At most the rule's maximum.", - title="Access Token Lifetime Seconds", - ), - ] = None - - -class TokenExchangeResponse(BaseModel): - access_token: Annotated[ - str, Field(description="Send as `Authorization: Bearer`", title="Access Token") - ] - issued_token_type: Annotated[ - str, - Field( - description="Always `urn:ietf:params:oauth:token-type:access_token`", - title="Issued Token Type", - ), - ] - token_type: Annotated[str, Field(description="Always `Bearer`", title="Token Type")] - expires_in: Annotated[ - int, - Field(description="Seconds until the access token expires", title="Expires In"), - ] - - -class GatewayEventTokens(BaseModel): - inputTokens: Annotated[ - int, Field(description="Cached and uncached input tokens.", title="Inputtokens") - ] - outputTokens: Annotated[ - int, Field(description="Output tokens.", title="Outputtokens") - ] - cachedInputTokens: Annotated[ - int, Field(description="Cached input tokens.", title="Cachedinputtokens") - ] - - -class GatewayEvent(BaseModel): - type: Annotated[str, Field(description="Event type.", title="Type")] = ( - "API_BILLING_USAGE" +class GatewayEvent(BaseModel): + type: Annotated[str, Field(description="Event type.", title="Type")] = ( + "API_BILLING_USAGE" ) idempotencyKey: Annotated[ str, Field(description="Deduplication key.", title="Idempotencykey") @@ -10093,7 +8787,7 @@ class ExploreMetadataAPIFormats(BaseModel): ] = False -class TeamId5(RootModel[str]): +class TeamId4(RootModel[str]): root: Annotated[ str | None, Field( @@ -10107,7 +8801,7 @@ class TeamId5(RootModel[str]): class CreateGridTokenRequest(BaseModel): team_id: Annotated[ - TeamId5 | None, + TeamId4 | None, Field( description="ID of the team. When omitted, the team you belong to; required when you belong to several.", examples=["abc1234"], @@ -10149,19 +8843,21 @@ class GridToken(BaseModel): ] -class GridRouteAlias(BaseModel): - name: Annotated[ +class GridClassifier(BaseModel): + id: Annotated[ str, Field( - description="Name to send in the inference request's `model` field instead of the route's `name`.", - title="Name", + description="Stable classifier identifier.", + examples=["general-v1"], + title="Id", ), ] - kind: Annotated[ - Literal["CLAUDE_DESKTOP", "ALIAS"] | str, + name: Annotated[ + str, Field( - description="Purpose of the alias. CLAUDE_DESKTOP is for Claude Code desktop, which rejects model names without a `claude` substring. ALIAS is any other name the team's clients send for the route.", - title="GridRouteAliasKindV1", + description="Display name of the classifier.", + examples=["General"], + title="Name", ), ] @@ -10171,16 +8867,16 @@ class GridRouteClassifier(BaseModel): str, Field( description="Stable route classifier identifier.", - examples=["abc1234"], + examples=["general-v1"], title="Id", ), ] - display_name: Annotated[ + name: Annotated[ str, Field( description="Display name of the route classifier.", examples=["General"], - title="Display Name", + title="Name", ), ] supported_tradeoffs: Annotated[ @@ -10190,12 +8886,23 @@ class GridRouteClassifier(BaseModel): title="Supported Tradeoffs", ), ] - decidable_canonical_model_ids: Annotated[ + decidable_models: Annotated[ list[str], Field( - description="Canonical model ids the route classifier picks from.", + description="Model identities the route classifier picks from.", examples=[["zai-org/GLM-5.3", "anthropic/claude-opus-5-5"]], - title="Decidable Canonical Model Ids", + title="Decidable Models", + ), + ] + + +class GridRouteRef(BaseModel): + id: Annotated[str, Field(description="Stable route identifier.", title="Id")] + slug: Annotated[ + str, + Field( + description="Name of the route to send in the inference request's model field.", + title="Slug", ), ] @@ -10211,6 +8918,29 @@ class GridRouteTargetBasetenModelAPI(BaseModel): ] +class GridRouteTargetClassifier(BaseModel): + type: Annotated[ + Literal["CLASSIFIER"], + Field(description="Target kind for a classifier-based route.", title="Type"), + ] + classifier: Annotated[ + GridClassifier | None, + Field( + description="Classifier that picks a route for each request. Null for routers created before classifiers could be selected." + ), + ] + default_route: Annotated[ + GridRouteRef, Field(description="Route used when the classifier picks none.") + ] + allowed_routes: Annotated[ + list[GridRouteRef], + Field( + description="Routes the classifier may pick, in creation order.", + title="Allowed Routes", + ), + ] + + class GridRouteTargetConnection(BaseModel): type: Annotated[ Literal["CONNECTION"], @@ -10262,9 +8992,44 @@ class UpsertGridRouteTargetBasetenModelAPI(BaseModel): Literal["BASETEN_MODEL_API"], Field(description="Target kind for a Baseten Model API.", title="Type"), ] - model: Annotated[ + model: Annotated[ + str, + Field(description="Name of the target Model API.", min_length=1, title="Model"), + ] + + +class UpsertGridRouteTargetClassifier(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[ + Literal["CLASSIFIER"], + Field(description="Target kind for a classifier-based route.", title="Type"), + ] + classifier_id: Annotated[ + str, + Field( + description="ID of the classifier that picks a route for each request.", + examples=["general-v1"], + min_length=1, + title="Classifier Id", + ), + ] + allowed_route_ids: Annotated[ + list[str], + Field( + description="IDs of the routes the classifier may pick. All must belong to the route's team and must not be routers themselves.", + examples=[["abc1234", "def5678"]], + title="Allowed Route Ids", + ), + ] + default_route_id: Annotated[ str, - Field(description="Name of the target Model API.", min_length=1, title="Model"), + Field( + description="ID of the allowed route used when the classifier picks none.", + examples=["abc1234"], + title="Default Route Id", + ), ] @@ -10296,36 +9061,7 @@ class UpsertGridRouteTargetConnection(BaseModel): ] -class UpsertGridRouteTargetIntelligent(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - type: Annotated[ - Literal["INTELLIGENT"], - Field( - description="Target kind for an intelligent route: Baseten picks the model per request.", - title="Type", - ), - ] - route_classifier_id: Annotated[ - str, - Field( - description="Identifier of the route classifier that picks the model. List them with GET /v1/grid/route_classifiers.", - examples=["abc1234"], - min_length=1, - title="Route Classifier Id", - ), - ] - tradeoff: Annotated[ - Literal["cost", "balanced", "intelligence"] | str, - Field( - description="How the classifier weighs cost against quality. Must be one of the classifier's supported tradeoffs.", - title="GridRouteTradeoffV1", - ), - ] - - -class TeamId6(RootModel[str]): +class TeamId5(RootModel[str]): root: Annotated[ str | None, Field( @@ -10341,7 +9077,7 @@ class DisplayName(RootModel[str]): root: Annotated[ str | None, Field( - description="Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", + description="Display label. Omit to use the route name; null is not accepted.", examples=["Assistant"], max_length=255, min_length=1, @@ -10350,7 +9086,7 @@ class DisplayName(RootModel[str]): ] = None -class Description4(RootModel[str]): +class Description(RootModel[str]): root: Annotated[ str | None, Field( @@ -10367,7 +9103,7 @@ class CreateGridRouteRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId6 | None, + TeamId5 | None, Field( description="Identifier of the team that owns the route.", examples=["abc1234"], @@ -10377,7 +9113,7 @@ class CreateGridRouteRequest(BaseModel): display_name: Annotated[ DisplayName | None, Field( - description="Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", + description="Display label. Omit to use the route name; null is not accepted.", examples=["Assistant"], title="Display Name", ), @@ -10386,9 +9122,9 @@ class CreateGridRouteRequest(BaseModel): Annotated[ UpsertGridRouteTargetBasetenModelAPI | UpsertGridRouteTargetConnection - | UpsertGridRouteTargetIntelligent, + | UpsertGridRouteTargetClassifier, Field( - description="Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team. INTELLIGENT targets need at least one of the route classifier's models, and one of its fallback models, servable by the team.", + description="Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team.", discriminator="type", examples=[{"model": "zai-org/GLM-5.3", "type": "BASETEN_MODEL_API"}], title="Target", @@ -10398,7 +9134,7 @@ class CreateGridRouteRequest(BaseModel): Field(union_mode="left_to_right"), ] description: Annotated[ - Description4 | None, + Description | None, Field( description="Short description of the route. Omit for no description; null is not accepted.", examples=["Assistant for code review and debugging."], @@ -10445,7 +9181,6 @@ class GridRouteUsageResult(BaseModel): "VERTEX", "OPENAI_COMPATIBLE", "BEDROCK", - "AZURE", ] | str | None, @@ -10453,18 +9188,11 @@ class GridRouteUsageResult(BaseModel): description="Provider that served the requests. Null when not grouping by PROVIDER." ), ] = None - intelligent_route_id: Annotated[ - str | None, - Field( - description="ID of the intelligent route, as `id` in GET /v1/grid/routes. Null when not grouping by INTELLIGENT_ROUTE.", - title="Intelligent Route Id", - ), - ] = None - intelligent_route_display_name: Annotated[ + intelligent_route: Annotated[ str | None, Field( - description="Display name of the intelligent route. Null when `intelligent_route_id` is null or the route cannot be resolved.", - title="Intelligent Route Display Name", + description="Name of the intelligent route, as in `GET /v1/grid/routes`. Null when not grouping by INTELLIGENT_ROUTE.", + title="Intelligent Route", ), ] = None harness: Annotated[ @@ -10473,20 +9201,6 @@ class GridRouteUsageResult(BaseModel): description="Coding harness. Null when not grouping by HARNESS, when no harness was recorded (including usage from before harness tracking), or when the recorded harness is not recognized by this API version." ), ] = None - api_key_prefix: Annotated[ - str | None, - Field( - description="Prefix of the API key that made the requests, matching `GET /v1/api_keys`. Null when not grouping by API_KEY, for usage without an API key, and for usage recorded before API key tracking.", - title="Api Key Prefix", - ), - ] = None - api_key_name: Annotated[ - str | None, - Field( - description="Name of the API key. Null when `api_key_prefix` is null or the key has no name.", - title="Api Key Name", - ), - ] = None cost_usd: Annotated[ str, Field( @@ -10535,7 +9249,7 @@ class GridRouteTombstone(BaseModel): name: Annotated[str, Field(description="Name of the deleted route.", title="Name")] -class Description5(RootModel[str]): +class Description1(RootModel[str]): root: Annotated[ str | None, Field( @@ -10565,7 +9279,7 @@ class UpdateGridRouteRequest(BaseModel): extra="forbid", ) description: Annotated[ - Description5 | None, + Description1 | None, Field( description="New description. Omit to keep the current description; use an empty string to clear it. Null is not accepted.", examples=["Assistant for code review and debugging."], @@ -10580,6 +9294,16 @@ class UpdateGridRouteRequest(BaseModel): title="Display Name", ), ] = None + target: Annotated[ + UpsertGridRouteTargetBasetenModelAPI + | UpsertGridRouteTargetConnection + | UpsertGridRouteTargetClassifier + | None, + Field( + description="Complete new target configuration. Omit to keep the current configuration; null is not accepted. Only the CLASSIFIER configuration of a router route is mutable.", + title="Target", + ), + ] = None class GridTeamSpendLimitSetting(BaseModel): @@ -10794,34 +9518,6 @@ class GridConnectionConfigAnthropic(BaseModel): ] -class GridConnectionConfigAzure(BaseModel): - provider: Annotated[ - Literal["AZURE"], - Field(description="Provider kind for Microsoft Azure.", title="Provider"), - ] - secret_id: Annotated[ - str, - Field( - description="Identifier of the team secret holding the provider API key.", - title="Secret Id", - ), - ] - secret_name: Annotated[ - str, - Field( - description="Name of the team secret holding the provider API key.", - title="Secret Name", - ), - ] - resource_name: Annotated[ - str, - Field( - description="Name of the Azure AI Foundry or Azure OpenAI resource.", - title="Resource Name", - ), - ] - - class GridConnectionConfigBedrock(BaseModel): provider: Annotated[ Literal["BEDROCK"], @@ -10956,8 +9652,7 @@ class GridConnection(BaseModel): | GridConnectionConfigOpenAI | GridConnectionConfigXAI | GridConnectionConfigVertex - | GridConnectionConfigBedrock - | GridConnectionConfigAzure, + | GridConnectionConfigBedrock, Field( description="Provider the connection authenticates with, and the team secret holding its API key.", discriminator="provider", @@ -11030,37 +9725,6 @@ class UpsertGridConnectionConfigAnthropic(BaseModel): ] -class UpsertGridConnectionConfigAzure(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - provider: Annotated[ - Literal["AZURE"], - Field( - description="Provider kind for Microsoft Azure. Route targets name a deployment, which must be named after its Azure model. Claude models (`claude-*`) use the Anthropic Messages API, and other models use the OpenAI-compatible APIs.", - title="Provider", - ), - ] - secret_name: Annotated[ - str, - Field( - description="Name of an existing secret, owned by the same team, that holds the provider API key.", - examples=["anthropic-key"], - min_length=1, - title="Secret Name", - ), - ] - resource_name: Annotated[ - str, - Field( - description="Name of the Azure AI Foundry or Azure OpenAI resource, the subdomain of `.openai.azure.com`.", - examples=["my-foundry-resource"], - min_length=1, - title="Resource Name", - ), - ] - - class UpsertGridConnectionConfigBedrock(BaseModel): model_config = ConfigDict( extra="forbid", @@ -11179,7 +9843,7 @@ class UpsertGridConnectionConfigXAI(BaseModel): ] -class TeamId7(RootModel[str]): +class TeamId6(RootModel[str]): root: Annotated[ str | None, Field( @@ -11196,7 +9860,7 @@ class CreateGridConnectionRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId7 | None, + TeamId6 | None, Field( description="Identifier of the team that owns the connection.", examples=["abc1234"], @@ -11209,8 +9873,7 @@ class CreateGridConnectionRequest(BaseModel): | UpsertGridConnectionConfigOpenAI | UpsertGridConnectionConfigXAI | UpsertGridConnectionConfigVertex - | UpsertGridConnectionConfigBedrock - | UpsertGridConnectionConfigAzure, + | UpsertGridConnectionConfigBedrock, Field( description="Provider the connection authenticates with, and the team secret holding its API key.", discriminator="provider", @@ -11240,8 +9903,7 @@ class UpdateGridConnectionRequest(BaseModel): | UpsertGridConnectionConfigOpenAI | UpsertGridConnectionConfigXAI | UpsertGridConnectionConfigVertex - | UpsertGridConnectionConfigBedrock - | UpsertGridConnectionConfigAzure, + | UpsertGridConnectionConfigBedrock, Field( description="Complete new connection configuration, replacing the current one. The provider must match the connection and is immutable.", discriminator="provider", @@ -11254,6 +9916,15 @@ class UpdateGridConnectionRequest(BaseModel): ] +class GridClassifiersResponse(BaseModel): + items: Annotated[ + list[GridClassifier], Field(description="Items in this page.", title="Items") + ] + pagination: Annotated[ + PaginationResponse, Field(description="Pagination metadata for the page.") + ] + + class GridRouteClassifiersResponse(BaseModel): items: Annotated[ list[GridRouteClassifier], @@ -11314,7 +9985,7 @@ class GridMachineUsersResponse(BaseModel): ] -class Name12(RootModel[str]): +class Name5(RootModel[str]): root: Annotated[ str | None, Field( @@ -11332,7 +10003,7 @@ class CreateGridMachineUserAPIKeyRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name12 | None, + Name5 | None, Field( description="Name of the API key: lowercase letters, numbers, and hyphens, at most 255 characters, and unique among the machine user's active keys. Defaults to a name derived from the machine user's.", examples=["production"], @@ -11341,7 +10012,7 @@ class CreateGridMachineUserAPIKeyRequest(BaseModel): ] = None -class TeamId8(RootModel[str]): +class TeamId7(RootModel[str]): root: Annotated[ str | None, Field( @@ -11358,7 +10029,7 @@ class CreateGridMachineUserRequest(BaseModel): extra="forbid", ) team_id: Annotated[ - TeamId8 | None, + TeamId7 | None, Field( description="Identifier of the team that owns the machine user. Defaults to your only team, if you belong to exactly one.", examples=["abc1234"], @@ -11436,7 +10107,7 @@ class GridMachineUserTombstone(BaseModel): ] -class Name13(RootModel[str]): +class Name6(RootModel[str]): root: Annotated[ str | None, Field( @@ -11453,7 +10124,7 @@ class UpdateGridMachineUserRequest(BaseModel): extra="forbid", ) name: Annotated[ - Name13 | None, + Name6 | None, Field( description="Name of the machine user, unique within its team. At most 255 characters. Omit to keep it.", title="Name", @@ -11719,7 +10390,7 @@ class EffectiveRateLimit(BaseModel): ] -class Name14(RootModel[str]): +class Name7(RootModel[str]): root: Annotated[ str | None, Field( @@ -11733,7 +10404,7 @@ class Name14(RootModel[str]): class GroupMetadata(BaseModel): name: Annotated[ - Name14 | None, + Name7 | None, Field( description="Optional display name for the group.", examples=["Acme prod"], @@ -11837,7 +10508,7 @@ class CreateGroupHierarchy(BaseModel): class UpdateGroupMetadata(BaseModel): name: Annotated[ - Name14 | None, + Name7 | None, Field( description="Optional display name for the group.", examples=["Acme prod"], @@ -12698,7 +11369,6 @@ class GetAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", - "WORKLOAD_IDENTITY", ] | str ] @@ -12812,7 +11482,6 @@ class GetModelsAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", - "WORKLOAD_IDENTITY", ] | str ] @@ -13056,43 +11725,6 @@ class GetModelsDeploymentsStartupsParams(BaseModel): ] = None -class GetModelsDeploymentsReplicasParams(BaseModel): - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor returned by a previous page. Omit to fetch the first page.", - title="Cursor", - ), - ] = None - limit: Annotated[ - int, - Field( - description="Maximum number of items to return.", - ge=1, - le=1000, - title="Limit", - ), - ] = 100 - statuses: Annotated[ - list[ - Literal[ - "STARTING", - "ACTIVE", - "UNHEALTHY", - "TERMINATING", - "TERMINATED", - "UNKNOWN", - ] - | str - ] - | None, - Field( - description="Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", - title="Statuses", - ), - ] = None - - class GetModelsEnvironmentsLogsParams(BaseModel): start_epoch_millis: Annotated[ int | None, @@ -13276,43 +11908,6 @@ class GetModelsEnvironmentsStartupsParams(BaseModel): ] = None -class GetModelsEnvironmentsReplicasParams(BaseModel): - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor returned by a previous page. Omit to fetch the first page.", - title="Cursor", - ), - ] = None - limit: Annotated[ - int, - Field( - description="Maximum number of items to return.", - ge=1, - le=1000, - title="Limit", - ), - ] = 100 - statuses: Annotated[ - list[ - Literal[ - "STARTING", - "ACTIVE", - "UNHEALTHY", - "TERMINATING", - "TERMINATED", - "UNKNOWN", - ] - | str - ] - | None, - Field( - description="Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", - title="Statuses", - ), - ] = None - - class GetChainsAuditLogsParams(BaseModel): cursor: Annotated[ str | None, @@ -13366,7 +11961,6 @@ class GetChainsAuditLogsParams(BaseModel): "DIRECTORY_GROUP_MANAGEMENT", "SSH", "TELEMETRY_EXPORT", - "WORKLOAD_IDENTITY", ] | str ] @@ -13707,13 +12301,6 @@ class GetModelApisMetricsParams(BaseModel): title="Metrics", ), ] = None - team_ids: Annotated[ - list[str] | None, - Field( - description="Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", - title="Team Ids", - ), - ] = None class GetBillingModelApisParams(BaseModel): @@ -13823,46 +12410,6 @@ class GetBillingToolCallUsageParams(BaseModel): ] = None -class GetAccessIdentityProvidersParams(BaseModel): - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor returned by a previous page. Omit to fetch the first page.", - title="Cursor", - ), - ] = None - limit: Annotated[ - int, - Field( - description="Maximum number of items to return.", - ge=1, - le=1000, - title="Limit", - ), - ] = 100 - name: Annotated[ - Name2 | None, - Field( - description="Only the provider with this name, ignoring case", title="Name" - ), - ] = None - predefined_kind: Annotated[ - Literal[ - "GITHUB_ACTIONS", - "GCP", - "BASETEN", - "AWS_IAM", - "AWS_EKS", - "AZURE_MANAGED_IDENTITY_V1", - "AZURE_MANAGED_IDENTITY_V2", - "AZURE_AKS", - ] - | str - | None, - Field(description="Only this predefined provider's issuers"), - ] = None - - class GetGridRoutesUsageParams(BaseModel): cursor: Annotated[ str | None, @@ -13903,20 +12450,12 @@ class GetGridRoutesUsageParams(BaseModel): ] = None group_by: Annotated[ list[ - Literal[ - "USER", - "TEAM", - "MODEL", - "PROVIDER", - "INTELLIGENT_ROUTE", - "HARNESS", - "API_KEY", - ] + Literal["USER", "TEAM", "MODEL", "PROVIDER", "INTELLIGENT_ROUTE", "HARNESS"] | str ] | None, Field( - description="Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", + description="Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", title="Group By", ), ] = None @@ -13944,7 +12483,6 @@ class GetGridRoutesUsageParams(BaseModel): "VERTEX", "OPENAI_COMPATIBLE", "BEDROCK", - "AZURE", ] | str ] @@ -13961,13 +12499,6 @@ class GetGridRoutesUsageParams(BaseModel): title="Harnesses", ), ] = None - api_key_prefixes: Annotated[ - list[str] | None, - Field( - description="Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", - title="Api Key Prefixes", - ), - ] = None class GetSandboxMetricsParams(BaseModel): @@ -14439,27 +12970,6 @@ class AuditLogEventEnvironmentUpdated(BaseModel): previous_settings: AuditLogEventEnvironmentSettings | None -class AuditLogEventIdentityProviderCreated(BaseModel): - event_type: Annotated[ - Literal["IDENTITY_PROVIDER_CREATED"], Field(title="Event Type") - ] - identity_provider_id: Annotated[str, Field(title="Identity Provider Id")] - name: Annotated[str, Field(title="Name")] - description: Annotated[ - str | None, - Field( - description="Null when the provider was added without one.", - title="Description", - ), - ] = None - predefined: Annotated[ - AuditLogEventPredefinedIdentityProviderConfig, - Field( - description="The provider's settings, as the identity provider resource returns them." - ), - ] - - class AuditLogEventModelDeployed(BaseModel): event_type: Annotated[Literal["MODEL_DEPLOYED"], Field(title="Event Type")] model_id: Annotated[str, Field(title="Model Id")] @@ -14548,35 +13058,14 @@ class AuditLogEventModelPromotionControlAction(BaseModel): environment_id: Annotated[str | None, Field(title="Environment Id")] action: Annotated[ Literal[ - "PAUSE", "RESUME", "FORCE_CANCEL", "FORCE_ROLL_FORWARD", "GRACEFUL_CANCEL" - ] - | str, - Field( - description="User-initiated promotion control signal recorded on a promotion-control event.", - title="AuditLogPromotionControlActionV1", - ), - ] - - -class AuditLogEventServiceAccountCreated(BaseModel): - event_type: Annotated[Literal["SERVICE_ACCOUNT_CREATED"], Field(title="Event Type")] - service_account_id: Annotated[str, Field(title="Service Account Id")] - name: Annotated[str, Field(title="Name")] - description: Annotated[ - str | None, - Field( - description="Null when the account was created without one.", - title="Description", - ), - ] = None - owner_team_id: Annotated[ - str | None, + "PAUSE", "RESUME", "FORCE_CANCEL", "FORCE_ROLL_FORWARD", "GRACEFUL_CANCEL" + ] + | str, Field( - description="The team that owns the account. Null for an organization account.", - title="Owner Team Id", + description="User-initiated promotion control signal recorded on a promotion-control event.", + title="AuditLogPromotionControlActionV1", ), - ] = None - preset_permissions: AuditLogEventServiceAccountPresetPermissions + ] class Deployment(BaseModel): @@ -14669,13 +13158,6 @@ class Deployment(BaseModel): description="Effective request backpressure settings for the deployment." ), ] - failure_reason: Annotated[ - str | None, - Field( - description="Why the deployment failed. Set only when the status is DEPLOY_FAILED; null otherwise.", - title="Failure Reason", - ), - ] = None class CreatedModelDeployment(BaseModel): @@ -15060,10 +13542,10 @@ class TrafficRoutingRuleUpsert(BaseModel): sampling_mode: Annotated[ Literal["RANDOM", "USER_SESSION"] | str, Field( - description="How requests are picked for shadowing. Defaults to USER_SESSION.", + description="How requests are picked for shadowing", title="TrafficRoutingRuleShadowSamplingModeV1", ), - ] = "USER_SESSION" + ] propagate_client_cancellation: Annotated[ bool, Field( @@ -15433,14 +13915,7 @@ class UpdateChainletEnvironmentInstanceTypeResponse(BaseModel): ] -class TrainingBDNConfigResponse(BaseModel): - mounts: Annotated[list[TrainingBDNMountResponse] | None, Field(title="Mounts")] = ( - None - ) - - class TrainingJob(BaseModel): - bdn: TrainingBDNConfigResponse | None = None id: Annotated[ str, Field(description="Unique identifier of the training job.", title="Id") ] @@ -15751,15 +14226,6 @@ class RegistrySecretDockerAuth(BaseModel): ] -class TrainingBDNConfig(BaseModel): - model_config = ConfigDict( - extra="forbid", - ) - mounts: Annotated[ - list[TrainingBDNMount] | None, Field(max_length=32, title="Mounts") - ] = None - - class CreateTrainingJobResponse(BaseModel): training_job: Annotated[TrainingJob, Field(description="The created training job.")] @@ -15800,63 +14266,35 @@ class TrainingJobMetrics(BaseModel): gpu_memory_usage_bytes: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", title="Gpu Memory Usage Bytes", ), ] gpu_utilization: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", title="Gpu Utilization", ), ] - gpu_temperature_celsius: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Temperature Celsius", - ), - ] - gpu_power_usage_watts: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Power Usage Watts", - ), - ] - gpu_tensor_core_utilization: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Tensor Core Utilization", - ), - ] - gpu_memory_bandwidth_utilization: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Memory Bandwidth Utilization", - ), - ] cpu_usage: Annotated[ list[TrainingJobMetric], Field( - description="The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", title="Cpu Usage", ), ] cpu_memory_usage_bytes: Annotated[ list[TrainingJobMetric], Field( - description="The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", title="Cpu Memory Usage Bytes", ), ] ephemeral_storage: Annotated[ StorageMetrics, Field( - description="The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." + description="The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." ), ] @@ -15872,63 +14310,35 @@ class GetTrainingJobMetricsResponse(BaseModel): gpu_memory_usage_bytes: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", title="Gpu Memory Usage Bytes", ), ] gpu_utilization: Annotated[ dict[str, list[TrainingJobMetric]], Field( - description="A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", title="Gpu Utilization", ), ] - gpu_temperature_celsius: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Temperature Celsius", - ), - ] - gpu_power_usage_watts: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Power Usage Watts", - ), - ] - gpu_tensor_core_utilization: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Tensor Core Utilization", - ), - ] - gpu_memory_bandwidth_utilization: Annotated[ - dict[str, list[TrainingJobMetric]], - Field( - description="A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - title="Gpu Memory Bandwidth Utilization", - ), - ] cpu_usage: Annotated[ list[TrainingJobMetric], Field( - description="The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", title="Cpu Usage", ), ] cpu_memory_usage_bytes: Annotated[ list[TrainingJobMetric], Field( - description="The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + description="The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", title="Cpu Memory Usage Bytes", ), ] ephemeral_storage: Annotated[ StorageMetrics, Field( - description="The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." + description="The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." ), ] training_job: Annotated[TrainingJob, Field(description="The training job.")] @@ -16034,6 +14444,12 @@ class CreateLoopsRunResponse(BaseModel): run: LoopsRun +class GetLoopsRunResponse(BaseModel): + run: Annotated[ + LoopsRun, Field(description="The Loops run with its associated sampler.") + ] + + class LoopsCheckpoint(BaseModel): checkpoint_id: Annotated[ str, Field(description="The ID of the checkpoint.", title="Checkpoint Id") @@ -16091,30 +14507,6 @@ class LoopsCheckpoint(BaseModel): title="TrainerCheckpointTarget", ), ] - expires_at: Annotated[ - AwareDatetime | None, - Field( - description="When the checkpoint expires and is deleted, set from the TTL it was saved with. Null means it's kept until you delete it. A checkpoint that's still in use when it expires, for example deployed, is deleted once it's released.", - title="Expires At", - ), - ] - - -class DeleteLoopsRunResponse(BaseModel): - id: Annotated[str, Field(description="The deleted Loops run ID.", title="Id")] - kept_checkpoints: Annotated[ - list[LoopsCheckpoint], - Field( - description="The run's checkpoints that were not deleted because something still uses them, such as a deployment. They stay usable until that stops.", - title="Kept Checkpoints", - ), - ] - - -class GetLoopsRunResponse(BaseModel): - run: Annotated[ - LoopsRun, Field(description="The Loops run with its associated sampler.") - ] class ListLoopsCheckpointsResponse(BaseModel): @@ -16959,7 +15351,7 @@ class DedicatedUsage(BaseModel): subtotal: Annotated[ float | Subtotal5, Field( - description="Usage charges in dollars before applying credits", + description="Subtotal cost in dollars after applying credits used", title="Subtotal", ), ] @@ -17036,7 +15428,7 @@ class TrainingUsage(BaseModel): subtotal: Annotated[ float | Subtotal13, Field( - description="Usage charges in dollars before applying credits", + description="Subtotal cost in dollars after applying credits used", title="Subtotal", ), ] @@ -17045,7 +15437,7 @@ class TrainingUsage(BaseModel): Field(description="Credits applied in dollars", title="Credits Used"), ] total: Annotated[ - float | Total3, Field(description="Total cost in dollars", title="Total") + float | Total, Field(description="Total cost in dollars", title="Total") ] minutes: Annotated[int, Field(description="Total minutes used", title="Minutes")] breakdown: Annotated[ @@ -17054,137 +15446,6 @@ class TrainingUsage(BaseModel): ] = None -class ServiceAccountPresetPermissions(BaseModel): - type: Annotated[ - Literal[ - "WORKSPACE_MANAGE_ALL", - "WORKSPACE_INVOKE", - "WORKSPACE_EXPORT_METRICS", - "WORKSPACE_MANAGE_API_KEYS", - "WORKSPACE_INVOKE_MODEL_APIS", - ] - | str, - Field( - description="What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", - examples=["WORKSPACE_MANAGE_ALL"], - title="ServiceAccountPresetTypeV1", - ), - ] - model_ids: Annotated[ - list[str] | None, - Field( - description="WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", - examples=[["abcd1234"]], - title="Model Ids", - ), - ] = None - environment_names: Annotated[ - list[str] | None, - Field( - description="WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", - examples=[["production"]], - title="Environment Names", - ), - ] = None - model_api_slugs: Annotated[ - list[str] | None, - Field( - description="WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", - examples=[["my-model-api"]], - title="Model Api Slugs", - ), - ] = None - - -class ServiceAccount(BaseModel): - id: Annotated[str, Field(description="Service account ID", title="Id")] - name: Annotated[ - str, Field(description="Name, unique in the organization", title="Name") - ] - description: Annotated[ - str | None, Field(description="Description", title="Description") - ] = None - team_id: Annotated[ - str | None, - Field( - description="The team that owns the account. Null for an organization account.", - title="Team Id", - ), - ] = None - preset_permissions: Annotated[ - ServiceAccountPresetPermissions, - Field( - description="What the service account may do. Temporary; may be removed once fine-grained access control is available." - ), - ] - disabled: Annotated[ - bool, - Field( - description="Whether the account is disabled. A disabled account can't be used.", - title="Disabled", - ), - ] - last_used_at: Annotated[ - AwareDatetime | None, - Field( - description="Last time a request authenticated as this account, to within an hour. Null until the first.", - title="Last Used At", - ), - ] = None - created_at: Annotated[ - AwareDatetime, - Field(description="Time the account was created", title="Created At"), - ] - updated_at: Annotated[ - AwareDatetime, - Field(description="Time the account was last updated", title="Updated At"), - ] - - -class ServiceAccounts(BaseModel): - items: Annotated[ - list[ServiceAccount], Field(description="Items in this page.", title="Items") - ] - pagination: Annotated[ - PaginationResponse, Field(description="Pagination metadata for the page.") - ] - - -class IdentityProvider(BaseModel): - id: Annotated[str, Field(description="Identity provider ID", title="Id")] - name: Annotated[ - str, Field(description="Name, unique in the organization", title="Name") - ] - description: Annotated[ - str | None, Field(description="Description", title="Description") - ] = None - predefined: Annotated[ - PredefinedIdentityProviderConfig, - Field(description="Settings of the predefined provider"), - ] - created_by: Annotated[ - str, - Field(description="ID of the user who added the provider", title="Created By"), - ] - created_at: Annotated[ - AwareDatetime, - Field(description="Time the provider was added", title="Created At"), - ] - updated_at: Annotated[ - AwareDatetime, - Field(description="Time the provider was last updated", title="Updated At"), - ] - - -class IdentityProviders(BaseModel): - items: Annotated[ - list[IdentityProvider], Field(description="Items in this page.", title="Items") - ] - pagination: Annotated[ - PaginationResponse, Field(description="Pagination metadata for the page.") - ] - - class ExploreCost(BaseModel): input: Annotated[ float | None, @@ -17293,111 +15554,28 @@ class ExploreMetadataResponse(BaseModel): ] -class GridRouteMetadata(BaseModel): - slug: Annotated[ - str | None, - Field( - description="Metadata slug, e.g. 'anthropic/claude-opus-4'; null for rows without one.", - title="Slug", - ), - ] - display_name: Annotated[ - str | None, - Field(description="Model display name, when available.", title="Display Name"), - ] - release_date: Annotated[ - date_aliased | None, - Field( - description="Model release date. Month-only source dates use the first day of that month.", - title="Release Date", - ), - ] - provider: Annotated[ - str | None, - Field( - description="Provider key derived from the slug prefix, e.g. 'anthropic'; null for unprefixed slugs.", - title="Provider", - ), - ] - context_window: Annotated[ - int | None, - Field(description="Total context window in tokens.", title="Context Window"), - ] - max_output_tokens: Annotated[ - int | None, - Field( - description="Maximum output tokens per response.", title="Max Output Tokens" - ), - ] - input_modalities: Annotated[ - list[str], - Field(description="Accepted input modalities.", title="Input Modalities"), - ] - tools: Annotated[ - bool | None, - Field(description="Whether the model supports tool calling.", title="Tools"), - ] - reasoning_effort_levels: Annotated[ - list[str] | None, - Field( - description="Reasoning effort levels the model supports.", - title="Reasoning Effort Levels", - ), - ] - parallel_tool_calls: Annotated[ - bool | None, - Field( - description="Whether the model supports parallel tool calls.", - title="Parallel Tool Calls", - ), - ] - supported_api_formats: Annotated[ - ExploreMetadataAPIFormats | None, - Field(description="API formats the model supports."), - ] - cost: Annotated[ - ExploreCost | None, - Field(description="Provider list prices in USD per 1M tokens, when available."), - ] - api_formats: Annotated[ - list[Literal["messages", "responses", "chat_completions"] | str], - Field( - description="API formats the route supports, most preferred first: `chat_completions`, `messages`, `responses` for a BASETEN_MODEL_API target and `messages`, `responses`, `chat_completions` for any other target, keeping only the formats the route supports. Never empty.", - min_length=1, - title="Api Formats", - ), - ] - - class GridRoute(BaseModel): id: Annotated[str, Field(description="Stable route identifier.", title="Id")] name: Annotated[ str, Field( - description="Name to send in the inference request's `model` field. Unique within the team; immutable.", + description="Name to send in the inference request's model field.", title="Name", ), ] - display_name: Annotated[ - str, - Field( - description="Display label, defaulting to the route's name.", - title="Display Name", - ), - ] - aliases: Annotated[ - list[GridRouteAlias] | None, - Field( - description="The route's other names, one per purpose. Empty for routes created before aliases existed.", - title="Aliases", - ), - ] = None team_id: Annotated[ str, Field(description="Identifier of the owning team.", title="Team Id") ] team_name: Annotated[ str, Field(description="Name of the owning team.", title="Team Name") ] + display_name: Annotated[ + str, + Field( + description="Display label, defaulting to the route name.", + title="Display Name", + ), + ] description: Annotated[ str, Field( @@ -17409,6 +15587,7 @@ class GridRoute(BaseModel): Annotated[ GridRouteTargetBasetenModelAPI | GridRouteTargetConnection + | GridRouteTargetClassifier | GridRouteTargetIntelligent, Field( description="Configured upstream target.", @@ -17420,9 +15599,9 @@ class GridRoute(BaseModel): Field(union_mode="left_to_right"), ] metadata: Annotated[ - GridRouteMetadata | None, + ExploreMetadata | None, Field( - description="Resolved model metadata; for an intelligent route, the envelope of its servable models' metadata. Null when nothing is linked or the metadata has no supported API formats." + description="Resolved model metadata; for a router, the envelope of its allowed routes' metadata. Null when nothing is linked." ), ] invoke_url: Annotated[ @@ -18188,16 +16367,6 @@ class AuditLogEntry(BaseModel): "TELEMETRY_EXPORT_CREATED", "TELEMETRY_EXPORT_UPDATED", "TELEMETRY_EXPORT_DELETED", - "SERVICE_ACCOUNT_CREATED", - "SERVICE_ACCOUNT_UPDATED", - "SERVICE_ACCOUNT_DELETED", - "IDENTITY_PROVIDER_CREATED", - "IDENTITY_PROVIDER_UPDATED", - "IDENTITY_PROVIDER_DELETED", - "TRUST_RULE_CREATED", - "TRUST_RULE_UPDATED", - "TRUST_RULE_DELETED", - "ORGANIZATION_API_KEY_SETTINGS_UPDATED", ] | str, Field( @@ -18232,7 +16401,6 @@ class AuditLogEntry(BaseModel): | AuditLogEventApiKeyCreated | AuditLogEventApiKeyDeleted | AuditLogEventApiKeyLifetimeLimitsUpdated - | AuditLogEventOrganizationApiKeySettingsUpdated | AuditLogEventGatewayEndpointCreated | AuditLogEventGatewayEndpointUpdated | AuditLogEventGatewayEndpointDeleted @@ -18266,16 +16434,7 @@ class AuditLogEntry(BaseModel): | AuditLogEventVolumeUpdated | AuditLogEventTelemetryExportCreated | AuditLogEventTelemetryExportUpdated - | AuditLogEventTelemetryExportDeleted - | AuditLogEventServiceAccountCreated - | AuditLogEventServiceAccountUpdated - | AuditLogEventServiceAccountDeleted - | AuditLogEventIdentityProviderCreated - | AuditLogEventIdentityProviderUpdated - | AuditLogEventIdentityProviderDeleted - | AuditLogEventTrustRuleCreated - | AuditLogEventTrustRuleUpdated - | AuditLogEventTrustRuleDeleted, + | AuditLogEventTelemetryExportDeleted, Field( description="Structured details of the action, discriminated by `event_type`.", discriminator="event_type", @@ -19321,7 +17480,6 @@ class CreateTrainingJobImage(BaseModel): class CreateTrainingJob(BaseModel): - bdn: TrainingBDNConfig | None = None image: Annotated[ CreateTrainingJobImage, Field(examples=[{"base_image": "hello-world", "docker_auth": None}]), diff --git a/baseten/client/modelconfig/__init__.py b/baseten/client/modelconfig/__init__.py index 672e898..3215dcf 100644 --- a/baseten/client/modelconfig/__init__.py +++ b/baseten/client/modelconfig/__init__.py @@ -17,8 +17,6 @@ BDNConfig, BDNHotload, BDNVolumeMount, - BEIConfiguration, - BEIModelConfiguration, Build, CheckpointList, CheckpointRepository, @@ -76,8 +74,6 @@ "BDNConfig", "BDNHotload", "BDNVolumeMount", - "BEIConfiguration", - "BEIModelConfiguration", "BaseImage", "Build", "CheckpointList", diff --git a/baseten/client/modelconfig/_models.py b/baseten/client/modelconfig/_models.py index 05b942a..64ca410 100644 --- a/baseten/client/modelconfig/_models.py +++ b/baseten/client/modelconfig/_models.py @@ -71,25 +71,6 @@ class BDNVolumeMount(BaseModel): ] = None -class BEIModelConfiguration(BaseModel): - model_config = ConfigDict( - extra="allow", - ) - checkpoint: Annotated[ - str, - Field( - description="Hugging Face repository to download through weights, or an absolute path to manually mounted weights.", - min_length=1, - title="Checkpoint", - ), - ] - revision: Annotated[str | None, Field(title="Revision")] = None - served_model_name: Annotated[str | None, Field(title="Served Model Name")] = None - quantization: Annotated[ - Literal["none", "fp8", "mxfp8", "nvfp4"] | str, Field(title="Quantization") - ] = "none" - - class DockerServer(BaseModel): model_config = ConfigDict( extra="allow", @@ -104,7 +85,7 @@ class DockerServer(BaseModel): server_port: Annotated[ int, Field( - description="The port where the server runs. Port 8080 is reserved when Truss installs its internal reverse proxy; no_build deployments can use 8080.", + description="The port where the server runs. Port 8080 is reserved by Baseten's internal reverse proxy and cannot be used.", title="Server Port", ), ] @@ -253,14 +234,14 @@ class HealthChecks(BaseModel): restart_threshold_seconds: Annotated[ int | None, Field( - description="The time in seconds after which an unhealthy instance is restarted. With trt_llm, defaults to 60 and must be <= 60. Otherwise defaults to platform-determined value when not set.", + description="The time in seconds after which an unhealthy instance is restarted. Defaults to platform-determined value when not set.", title="Restart Threshold Seconds", ), ] = None stop_traffic_threshold_seconds: Annotated[ int | None, Field( - description="The time in seconds after which traffic is stopped to an unhealthy instance. With trt_llm, defaults to 30 and must be <= 30. Otherwise defaults to platform-determined value when not set.", + description="The time in seconds after which traffic is stopped to an unhealthy instance. Defaults to platform-determined value when not set.", title="Stop Traffic Threshold Seconds", ), ] = None @@ -337,7 +318,7 @@ class Resources(BaseModel): accelerator: Annotated[ str | None, Field( - description="The accelerator type for your instance. To request multiple accelerators, use the ':' operator (e.g. L4:4).", + description="The GPU type for your instance. To request multiple GPUs, use the ':' operator (e.g. L4:4).", examples=["A100", "T4:2", "H100:8"], ), ] = None @@ -609,17 +590,6 @@ class BDNConfig(BaseModel): ] = None -class BEIConfiguration(BaseModel): - model_config = ConfigDict( - extra="allow", - ) - backend: Annotated[Literal["nvidia", "tpu"] | str, Field(title="Backend")] - version_override: Annotated[str | None, Field(title="Version Override")] = None - configuration: Annotated[ - list[BEIModelConfiguration], Field(min_length=1, title="Configuration") - ] - - class BISLLM(BaseModel): model_config = ConfigDict( extra="allow", @@ -938,8 +908,7 @@ class WeightsAuth(BaseModel): ), ] = None auth_method: Annotated[ - Literal["CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", "HF_OIDC", "AWS_ASSUME_ROLE"] - | str, + Literal["CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", "AWS_ASSUME_ROLE"] | str, Field( description="Authentication method for downloading weights from the source.", title="WeightsAuthMethod", @@ -952,13 +921,6 @@ class WeightsAuth(BaseModel): title="Auth Secret Name", ), ] = None - hf_oidc_resource: Annotated[ - str | None, - Field( - description="Hugging Face repository (namespace/name) or username for OIDC token exchange.", - title="Hf Oidc Resource", - ), - ] = None class WeightsSource(BaseModel): @@ -1174,12 +1136,6 @@ class ModelConfig(BaseModel): TRTLLMConfigurationV1 | TRTLLMConfigurationV2 | None, Field(description="TensorRT-LLM configuration for optimized LLM inference."), ] = None - bei: Annotated[ - BEIConfiguration | None, - Field( - description="BEIv3 encoder serving without an engine-build job. Hugging Face checkpoints use runtime weights mounts. Requires explicit restart and stop-traffic health thresholds of 1–60 seconds." - ), - ] = None training_checkpoints: Annotated[ CheckpointList | None, Field(description="Configuration for deploying from training checkpoints."), diff --git a/scripts/apigen/specs/config.schema.json b/scripts/apigen/specs/config.schema.json index dc08074..b9fbb1d 100644 --- a/scripts/apigen/specs/config.schema.json +++ b/scripts/apigen/specs/config.schema.json @@ -167,96 +167,6 @@ "title": "BDNVolumeMount", "type": "object" }, - "BEIConfiguration": { - "additionalProperties": true, - "properties": { - "backend": { - "enum": [ - "nvidia", - "tpu" - ], - "title": "Backend", - "type": "string" - }, - "version_override": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Version Override" - }, - "configuration": { - "items": { - "$ref": "#/$defs/BEIModelConfiguration" - }, - "minItems": 1, - "title": "Configuration", - "type": "array" - } - }, - "required": [ - "backend", - "configuration" - ], - "title": "BEIConfiguration", - "type": "object" - }, - "BEIModelConfiguration": { - "additionalProperties": true, - "properties": { - "checkpoint": { - "description": "Hugging Face repository to download through weights, or an absolute path to manually mounted weights.", - "minLength": 1, - "title": "Checkpoint", - "type": "string" - }, - "revision": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Revision" - }, - "served_model_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Served Model Name" - }, - "quantization": { - "default": "none", - "enum": [ - "none", - "fp8", - "mxfp8", - "nvfp4" - ], - "title": "Quantization", - "type": "string" - } - }, - "required": [ - "checkpoint" - ], - "title": "BEIModelConfiguration", - "type": "object" - }, "BISLLM": { "additionalProperties": true, "description": "Configuration options for BIS LLM deployments.", @@ -609,7 +519,7 @@ "title": "Start Command" }, "server_port": { - "description": "The port where the server runs. Port 8080 is reserved when Truss installs its internal reverse proxy; no_build deployments can use 8080.", + "description": "The port where the server runs. Port 8080 is reserved by Baseten's internal reverse proxy and cannot be used.", "title": "Server Port", "type": "integer" }, @@ -873,7 +783,7 @@ } ], "default": null, - "description": "The time in seconds after which an unhealthy instance is restarted. With trt_llm, defaults to 60 and must be <= 60. Otherwise defaults to platform-determined value when not set.", + "description": "The time in seconds after which an unhealthy instance is restarted. Defaults to platform-determined value when not set.", "title": "Restart Threshold Seconds" }, "stop_traffic_threshold_seconds": { @@ -886,7 +796,7 @@ } ], "default": null, - "description": "The time in seconds after which traffic is stopped to an unhealthy instance. With trt_llm, defaults to 30 and must be <= 30. Otherwise defaults to platform-determined value when not set.", + "description": "The time in seconds after which traffic is stopped to an unhealthy instance. Defaults to platform-determined value when not set.", "title": "Stop Traffic Threshold Seconds" }, "startup_threshold_seconds": { @@ -1149,7 +1059,7 @@ }, "accelerator": { "$ref": "#/$defs/AcceleratorSpec", - "description": "The accelerator type for your instance. To request multiple accelerators, use the ':' operator (e.g. L4:4).", + "description": "The GPU type for your instance. To request multiple GPUs, use the ':' operator (e.g. L4:4).", "examples": [ "A100", "T4:2", @@ -2247,19 +2157,6 @@ "default": null, "description": "Baseten secret name containing credentials for accessing the source.", "title": "Auth Secret Name" - }, - "hf_oidc_resource": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Hugging Face repository (namespace/name) or username for OIDC token exchange.", - "title": "Hf Oidc Resource" } }, "required": [ @@ -2274,7 +2171,6 @@ "CUSTOM_SECRET", "AWS_OIDC", "GCP_OIDC", - "HF_OIDC", "AWS_ASSUME_ROLE" ], "title": "WeightsAuthMethod", @@ -2586,18 +2482,6 @@ "default": null, "description": "TensorRT-LLM configuration for optimized LLM inference." }, - "bei": { - "anyOf": [ - { - "$ref": "#/$defs/BEIConfiguration" - }, - { - "type": "null" - } - ], - "default": null, - "description": "BEIv3 encoder serving without an engine-build job. Hugging Face checkpoints use runtime weights mounts. Requires explicit restart and stop-traffic health thresholds of 1\u201360 seconds." - }, "training_checkpoints": { "anyOf": [ { diff --git a/scripts/apigen/specs/management.json b/scripts/apigen/specs/management.json index 977a7ce..e859282 100644 --- a/scripts/apigen/specs/management.json +++ b/scripts/apigen/specs/management.json @@ -1494,7 +1494,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/audit_logs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'direction': 'DESC', 'search': None, 'start_epoch_millis': None, 'end_epoch_millis': None}\n)\n\nprint(response.text)" } ], - "description": "Returns audit-log entries across the workspace, newest first, covering models, chains, and workspace-level actions. Use the filters to narrow by event type, actor, resource, environment, source, or time window, and the cursor to page. Requires a personal API key; team API keys can't read the workspace audit log. In workspaces with multiple teams, only organization admins can read the workspace audit log.", + "description": "Returns audit-log entries across the workspace, newest first, covering models, chains, and workspace-level actions. Use the filters to narrow by event type, actor, resource, environment, source, or time window, and the cursor to page. In workspaces with multiple teams, only organization admins can read the workspace audit log.", "parameters": [ { "name": "cursor", @@ -3831,88 +3831,6 @@ } ] }, - "/v1/models/{model_id}/deployments/{deployment_id}/replicas": { - "get": { - "summary": "Lists replicas for a deployment", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" - } - ], - "description": "Includes terminated replicas and lifecycle information without metrics. Replicas are ordered by creation time, oldest first, with replica ID as a tie-breaker. For subsequent pages, pass pagination.cursor as cursor with unchanged filters. Cursors expire after one hour. Replica status may change between requests.", - "parameters": [ - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - } - }, - { - "name": "statuses", - "in": "query", - "required": false, - "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", - "schema": { - "items": { - "$ref": "#/components/schemas/DeploymentReplicaStatusV1" - }, - "title": "Statuses", - "type": "array" - } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DeploymentReplicasV1" - } - } - } - } - } - }, - "parameters": [ - { - "$ref": "#/components/parameters/model_id" - }, - { - "$ref": "#/components/parameters/deployment_id" - } - ] - }, "/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}": { "delete": { "summary": "Terminates a replica in a deployment", @@ -3926,7 +3844,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Terminates a deployment replica and returns the termination status. Returns 404 if no replica matches the replica ID. Returns 400 without requesting termination if multiple replicas match the replica ID.", + "description": "Terminates a deployment replica and returns the termination status.", "responses": { "200": { "description": "", @@ -3950,33 +3868,7 @@ { "$ref": "#/components/parameters/replica_id" } - ], - "get": { - "summary": "Gets a replica in a deployment", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/deployments/{deployment_id}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Returns lifecycle information without metrics, including for terminated replicas. Returns 404 if the replica does not exist in the specified deployment. Returns 400 if multiple replicas match the replica ID.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DeploymentReplicaV1" - } - } - } - } - } - } + ] }, "/v1/models/{model_id}/deployments/{deployment_id}/ssh/sign": { "post": { @@ -5088,153 +4980,6 @@ } ] }, - "/v1/models/{model_id}/environments/{env_name}/replicas": { - "get": { - "summary": "Lists replicas for an environment", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" - } - ], - "description": "Includes retained terminated replicas from deployments active in the preceding hour. Orders replicas oldest first, with replica ID breaking ties. Pass pagination.cursor with unchanged filters for subsequent pages. Cursors pin deployment membership and expire after one hour.", - "parameters": [ - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - } - }, - { - "name": "statuses", - "in": "query", - "required": false, - "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", - "schema": { - "items": { - "$ref": "#/components/schemas/DeploymentReplicaStatusV1" - }, - "title": "Statuses", - "type": "array" - } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DeploymentReplicasV1" - } - } - } - } - } - }, - "parameters": [ - { - "$ref": "#/components/parameters/model_id" - }, - { - "$ref": "#/components/parameters/env_name" - } - ] - }, - "/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}": { - "delete": { - "summary": "Terminates a replica in an environment", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Requests replica termination in the environment's current deployment. Returns 404 if the environment has no current deployment or no replica matches the replica ID. Returns 400 without requesting termination if multiple replicas in the current deployment match the replica ID.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TerminateReplicaResponseV1" - } - } - } - } - } - }, - "parameters": [ - { - "$ref": "#/components/parameters/model_id" - }, - { - "$ref": "#/components/parameters/env_name" - }, - { - "$ref": "#/components/parameters/replica_id" - } - ], - "get": { - "summary": "Gets a replica in an environment", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/models/{model_id}/environments/{env_name}/replicas/{replica_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Searches deployments active in the environment during the preceding hour. Includes retained terminated replicas. Returns 404 if the replica is outside this scope. Returns 400 if multiple replicas match the replica ID.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DeploymentReplicaV1" - } - } - } - } - } - } - }, "/v1/chains": { "get": { "summary": "Gets all chains", @@ -6371,11 +6116,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/training_projects/{training_project_id}/jobs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"training_job\": {\n \"bdn\": {},\n \"image\": {\n \"base_image\": \"hello-world\",\n \"docker_auth\": null\n },\n \"compute\": {\n \"node_count\": 1,\n \"cpu_count\": 1,\n \"memory\": \"2Gi\",\n \"accelerator\": {\n \"accelerator\": \"H100\",\n \"count\": 2\n },\n \"availability_model\": \"spot\"\n },\n \"runtime\": {\n \"start_commands\": [\n \"python main.py\"\n ],\n \"environment_variables\": {\n \"API_KEY\": \"your_api_key_here\",\n \"PATH\": \"/usr/bin\"\n },\n \"enable_cache\": true,\n \"cache_config\": {\n \"enable_legacy_hf_mount\": true,\n \"enabled\": true,\n \"mount_base_path\": \"/root/.cache\",\n \"persistent_home\": false,\n \"require_cache_affinity\": true\n },\n \"checkpointing_config\": {\n \"enabled\": true,\n \"checkpoint_path\": \"/mnt/ckpts\",\n \"volume_size_gib\": 10\n },\n \"load_checkpoint_config\": null\n },\n \"name\": \"gpt-oss-job\",\n \"truss_user_env\": null,\n \"interactive_session\": null,\n \"weights\": [\n {\n \"allow_patterns\": null,\n \"auth\": null,\n \"auth_secret_name\": null,\n \"ignore_patterns\": null,\n \"mount_location\": \"/app/models/base\",\n \"source\": \"hf://meta-llama/Llama-3-8B@main\"\n }\n ],\n \"enable_baseten_workdir\": false,\n \"priority\": 0\n }\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/training_projects/{training_project_id}/jobs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"training_job\": {\n \"image\": {\n \"base_image\": \"hello-world\",\n \"docker_auth\": null\n },\n \"compute\": {\n \"node_count\": 1,\n \"cpu_count\": 1,\n \"memory\": \"2Gi\",\n \"accelerator\": {\n \"accelerator\": \"H100\",\n \"count\": 2\n },\n \"availability_model\": \"spot\"\n },\n \"runtime\": {\n \"start_commands\": [\n \"python main.py\"\n ],\n \"environment_variables\": {\n \"API_KEY\": \"your_api_key_here\",\n \"PATH\": \"/usr/bin\"\n },\n \"enable_cache\": true,\n \"cache_config\": {\n \"enable_legacy_hf_mount\": true,\n \"enabled\": true,\n \"mount_base_path\": \"/root/.cache\",\n \"persistent_home\": false,\n \"require_cache_affinity\": true\n },\n \"checkpointing_config\": {\n \"enabled\": true,\n \"checkpoint_path\": \"/mnt/ckpts\",\n \"volume_size_gib\": 10\n },\n \"load_checkpoint_config\": null\n },\n \"name\": \"gpt-oss-job\",\n \"truss_user_env\": null,\n \"interactive_session\": null,\n \"weights\": [\n {\n \"allow_patterns\": null,\n \"auth\": null,\n \"auth_secret_name\": null,\n \"ignore_patterns\": null,\n \"mount_location\": \"/app/models/base\",\n \"source\": \"hf://meta-llama/Llama-3-8B@main\"\n }\n ],\n \"enable_baseten_workdir\": false,\n \"priority\": 0\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training_projects/{training_project_id}/jobs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'training_job': {'bdn': {}, 'image': {'base_image': 'hello-world', 'docker_auth': None}, 'compute': {'node_count': 1, 'cpu_count': 1, 'memory': '2Gi', 'accelerator': {'accelerator': 'H100', 'count': 2}, 'availability_model': 'spot'}, 'runtime': {'start_commands': ['python main.py'], 'environment_variables': {'API_KEY': 'your_api_key_here', 'PATH': '/usr/bin'}, 'enable_cache': True, 'cache_config': {'enable_legacy_hf_mount': True, 'enabled': True, 'mount_base_path': '/root/.cache', 'persistent_home': False, 'require_cache_affinity': True}, 'checkpointing_config': {'enabled': True, 'checkpoint_path': '/mnt/ckpts', 'volume_size_gib': 10}, 'load_checkpoint_config': None}, 'name': 'gpt-oss-job', 'truss_user_env': None, 'interactive_session': None, 'weights': [{'allow_patterns': None, 'auth': None, 'auth_secret_name': None, 'ignore_patterns': None, 'mount_location': '/app/models/base', 'source': 'hf://meta-llama/Llama-3-8B@main'}], 'enable_baseten_workdir': False, 'priority': 0}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training_projects/{training_project_id}/jobs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'training_job': {'image': {'base_image': 'hello-world', 'docker_auth': None}, 'compute': {'node_count': 1, 'cpu_count': 1, 'memory': '2Gi', 'accelerator': {'accelerator': 'H100', 'count': 2}, 'availability_model': 'spot'}, 'runtime': {'start_commands': ['python main.py'], 'environment_variables': {'API_KEY': 'your_api_key_here', 'PATH': '/usr/bin'}, 'enable_cache': True, 'cache_config': {'enable_legacy_hf_mount': True, 'enabled': True, 'mount_base_path': '/root/.cache', 'persistent_home': False, 'require_cache_affinity': True}, 'checkpointing_config': {'enabled': True, 'checkpoint_path': '/mnt/ckpts', 'volume_size_gib': 10}, 'load_checkpoint_config': None}, 'name': 'gpt-oss-job', 'truss_user_env': None, 'interactive_session': None, 'weights': [{'allow_patterns': None, 'auth': None, 'auth_secret_name': None, 'ignore_patterns': None, 'mount_location': '/app/models/base', 'source': 'hf://meta-llama/Llama-3-8B@main'}], 'enable_baseten_workdir': False, 'priority': 0}}\n)\n\nprint(response.text)" } ], "description": "Creates a training job with the specified configuration.", @@ -7560,11 +7305,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"sampler_num_replicas\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"sampler_num_replicas\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" } ], "description": "Creates a Loops run with an associated sampler in the given session.", @@ -7626,37 +7371,6 @@ ] }, "/v1/loops/runs/{run_id}": { - "delete": { - "summary": "Deletes a Loops run", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/loops/runs/{run_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/runs/{run_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Deletes a Loops run by ID, deactivating it first if it is active, and deletes its checkpoints. Checkpoints still in use, such as deployed ones, are kept and listed in the response; they stay usable until that use stops. Deletion is permanent, and storage for some checkpoints is reclaimed later.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DeleteLoopsRunResponseV1" - } - } - } - } - } - }, - "parameters": [ - { - "$ref": "#/components/parameters/run_id" - } - ], "get": { "summary": "Gets a Loops run", "x-codeSamples": [ @@ -7682,7 +7396,12 @@ } } } - } + }, + "parameters": [ + { + "$ref": "#/components/parameters/run_id" + } + ] }, "/v1/loops/trainers": { "post": { @@ -7690,11 +7409,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"scope\": \"default\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"scope\": \"default\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'scope': 'default'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'scope': 'default'}\n)\n\nprint(response.text)" } ], "description": "Creates a trainer-only Loops run in the given session, without a sampler. To sample from it, create a sampler with POST /v1/loops/samplers and pass this run's ID as run_id to pair the two. List and read the trainer through the /v1/loops/runs endpoints.", @@ -8065,39 +7784,6 @@ } } }, - "/v1/loops/checkpoints/{checkpoint_id}": { - "delete": { - "summary": "Deletes a Loops checkpoint", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Deletes a Loops checkpoint by ID and returns its tombstone. The checkpoint disappears from listings and can't be loaded, sampled, or deployed. Deletion is permanent, and storage for some checkpoints is reclaimed later. A checkpoint that is deployed, read by an unfinished LoRA merge, served by an active sampler, or the start of an active run can't be deleted, and the error says which. Deleting an already-deleted checkpoint returns the same tombstone.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LoopsCheckpointTombstoneV1" - } - } - } - } - } - }, - "parameters": [ - { - "$ref": "#/components/parameters/checkpoint_id" - } - ] - }, "/v1/loops/checkpoints/{checkpoint_id}/files": { "get": { "summary": "Gets Loops checkpoint files", @@ -8190,49 +7876,6 @@ } ] }, - "/v1/loops/checkpoints/{checkpoint_id}/ttl": { - "put": { - "summary": "Sets a Loops checkpoint's TTL", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request PUT \\\n--url https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}/ttl \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"ttl_seconds\": null\n}'" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/checkpoints/{checkpoint_id}/ttl\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PUT\",\n url,\n headers=headers,\n json={'ttl_seconds': None}\n)\n\nprint(response.text)" - } - ], - "description": "Sets when a Loops checkpoint expires, counted from now, or removes its TTL so it's kept until you delete it. An expired checkpoint is deleted within 24 hours. If it's in use when it expires, it's deleted within 24 hours after it stops being used.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetLoopsCheckpointTtlRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LoopsCheckpointV1" - } - } - } - } - } - }, - "parameters": [ - { - "$ref": "#/components/parameters/checkpoint_id" - } - ] - }, "/v1/loops/deployments": { "get": { "summary": "Lists Loops deployments", @@ -8472,7 +8115,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/loops/deployments/{deployment_id}/logs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_epoch_millis': None, 'end_epoch_millis': None, 'direction': None, 'limit': None, 'min_level': None}\n)\n\nprint(response.text)" } ], - "description": "Fetches logs from the trainer pods of a Loops deployment. Visible to anyone with training access to the deployment's team.", + "description": "Fetches logs from the trainer pods of a Loops deployment. Visible to any member of the deployment's team.", "parameters": [ { "name": "start_epoch_millis", @@ -8740,11 +8383,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"sampler_num_replicas\": null\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/runs \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"sampler_num_replicas\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/runs\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'sampler_num_replicas': None}\n)\n\nprint(response.text)" } ], "description": "Creates a Loops run with an associated sampler in the given session; the run's infrastructure belongs to the given team.", @@ -8778,11 +8421,11 @@ "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"base_checkpoint_auth\": {\n \"auth_method\": \"CUSTOM_SECRET\",\n \"auth_secret_name\": \"hf_read_my_checkpoint\"\n },\n \"scope\": \"default\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/teams/{team_id}/loops/trainers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"session_id\": null,\n \"base_model\": null,\n \"name\": null,\n \"max_seq_len\": null,\n \"seed\": null,\n \"availability_model\": \"spot\",\n \"path\": \"bt://loops:k4q95w5/weights/step-100\",\n \"reuse_from_run_id\": null,\n \"reuse_from_session_id\": null,\n \"base_checkpoint\": null,\n \"scope\": \"default\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'base_checkpoint_auth': {'auth_method': 'CUSTOM_SECRET', 'auth_secret_name': 'hf_read_my_checkpoint'}, 'scope': 'default'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/teams/{team_id}/loops/trainers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'session_id': None, 'base_model': None, 'name': None, 'max_seq_len': None, 'seed': None, 'availability_model': 'spot', 'path': 'bt://loops:k4q95w5/weights/step-100', 'reuse_from_run_id': None, 'reuse_from_session_id': None, 'base_checkpoint': None, 'scope': 'default'}\n)\n\nprint(response.text)" } ], "description": "Creates a trainer-only Loops run in the given session, without a sampler. To sample from it, create a sampler with POST /v1/loops/samplers and pass this run's ID as run_id to pair the two. List and read the trainer through the /v1/loops/runs endpoints.", @@ -8941,7 +8584,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training/capacity\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Returns on-demand and spot GPU quotas and current usage for the teams you can view, plus organization-wide totals when you have organization-level access.", + "description": "Returns GPU capacity limits (baseline and peak) and current usage for the organization.", "responses": { "200": { "description": "", @@ -8956,7 +8599,7 @@ } }, "patch": { - "summary": "Sets a team's training GPU quota", + "summary": "Sets a team's training GPU capacity", "x-codeSamples": [ { "lang": "bash", @@ -8967,7 +8610,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/training/capacity\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'team_id': None, 'gpu_type': None, 'max_gpus': 8}\n)\n\nprint(response.text)" } ], - "description": "Sets a team's GPU quota for a given type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota, and on-demand jobs can borrow past it from the organization's shared pool when one exists. Creates the quota if one doesn't exist for this (team, gpu_type) pair, otherwise updates it in place. Org-admin only: this is a quota the org imposes on the team, not something the team manages for itself.", + "description": "Sets the max concurrent GPUs of a given type a team may use. Creates the limit if one doesn't exist for this (team, gpu_type) pair, otherwise updates it in place. Org-admin only: this is a ceiling the org imposes on the team, not something the team manages for itself.", "requestBody": { "content": { "application/json": { @@ -9527,7 +9170,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/model_apis/{model_api_name}/metrics\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'mode': 'CURRENT', 'start_epoch_millis': None, 'end_epoch_millis': None}\n)\n\nprint(response.text)" } ], - "description": "Gets the metrics for a Model API in the given time range for the teams you can manage, with each series labeled by team_id. Organization admins receive organization-wide metrics by default. For a Model API your lab organization lists, other organizations' consumption is included regardless of team_ids.", + "description": "Gets the metrics for a Model API in the given time range.", "parameters": [ { "name": "mode", @@ -9587,19 +9230,6 @@ "title": "Metrics", "type": "array" } - }, - { - "name": "team_ids", - "in": "query", - "required": false, - "description": "Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", - "schema": { - "items": { - "type": "string" - }, - "title": "Team Ids", - "type": "array" - } } ], "responses": { @@ -10307,7 +9937,7 @@ "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/billing/usage_summary\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" } ], - "description": "Returns billing usage within [start_date, end_date): the start date is inclusive and the end date is exclusive. Both dates are normalized to midnight UTC. Includes dedicated model serving, training, and model APIs usage. For multi-team organizations, Model APIs usage is split by team. Historical usage without a recorded team is assigned to Default Team. Usage subtotals are before credits; credits are deducted only at the product summary level. The date range must not exceed 31 days.", + "description": "Returns billing usage within [start_date, end_date): the start date is inclusive and the end date is exclusive. Both dates are normalized to midnight UTC. Includes dedicated model serving, training, and model APIs usage. The date range must not exceed 31 days.", "parameters": [ { "name": "start_date", @@ -10602,68 +10232,31 @@ } }, "x-stability": "unstable" - }, - "patch": { - "summary": "Updates the authenticated organization", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/organizations/me \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"allow_personal_api_keys\": null,\n \"allow_service_account_api_keys\": null\n}'" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/organizations/me\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'allow_personal_api_keys': None, 'allow_service_account_api_keys': None}\n)\n\nprint(response.text)" - } - ], - "description": "Updates settings of the organization of the user making the request. Only organization admins can call it. Omitted fields are unchanged.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateOrganizationRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/OrganizationInfoV1" - } - } - } - } - }, - "x-stability": "unstable" } }, - "/v1/service_accounts": { + "/v1/gateway/events": { "get": { - "summary": "Lists service accounts", + "summary": "Lists gateway events", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/service_accounts \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/gateway/events \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'team_id': None, 'disabled': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/gateway/events\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_time': None, 'end_time': None, 'limit': None, 'cursor': None}\n)\n\nprint(response.text)" } ], - "description": "Lists the service accounts you administer: every account for an organization admin, and your teams' accounts for a team admin. Workload identity federation tokens act as service accounts.", "parameters": [ { - "name": "cursor", + "name": "start_time", "in": "query", "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "description": "Inclusive start (ISO 8601, UTC). Required without a cursor.", "schema": { "anyOf": [ { + "format": "date-time", "type": "string" }, { @@ -10671,31 +10264,18 @@ } ], "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" + "title": "Start Time" } }, { - "name": "name", + "name": "end_time", "in": "query", "required": false, - "description": "Only the account with this name, ignoring case", + "description": "Exclusive end (ISO 8601, UTC). Defaults to now.", "schema": { "anyOf": [ { - "minLength": 1, + "format": "date-time", "type": "string" }, { @@ -10703,238 +10283,102 @@ } ], "default": null, - "title": "Name" + "title": "End Time" } }, { - "name": "team_id", + "name": "limit", "in": "query", "required": false, - "description": "Only this team's accounts", + "description": "Max events. Default 100, max 1000.", "schema": { "anyOf": [ { - "type": "string" + "maximum": 1000, + "minimum": 1, + "type": "integer" }, { "type": "null" } ], "default": null, - "title": "Team Id" + "title": "Limit" + } + }, + { + "name": "api_keys", + "in": "query", + "required": false, + "description": "Return only events for these API key prefixes, repeated once per prefix.", + "schema": { + "items": { + "type": "string" + }, + "title": "Api Keys", + "type": "array" } }, { - "name": "disabled", + "name": "external_entity_ids", "in": "query", "required": false, - "description": "Only disabled or enabled accounts", + "description": "Return only events for these external entity IDs, repeated once per ID.", + "schema": { + "items": { + "type": "string" + }, + "title": "External Entity Ids", + "type": "array" + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Next-page cursor. Other parameters are ignored.", "schema": { "anyOf": [ { - "type": "boolean" + "type": "string" }, { "type": "null" } ], "default": null, - "title": "Disabled" - } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ServiceAccountsV1" - } - } - } - } - }, - "x-stability": "unstable" - }, - "post": { - "summary": "Creates a service account", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/service_accounts \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"ci-deployer\",\n \"description\": \"GitHub Actions deploys from acme/models\",\n \"team_id\": \"abcd1234\",\n \"preset_permissions\": {\n \"type\": \"WORKSPACE_MANAGE_ALL\"\n }\n}'" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'ci-deployer', 'description': 'GitHub Actions deploys from acme/models', 'team_id': 'abcd1234', 'preset_permissions': {'type': 'WORKSPACE_MANAGE_ALL'}}\n)\n\nprint(response.text)" - } - ], - "description": "Creates a service account that workload identity federation tokens act as. It's enabled at once. Omit `team_id` for an organization account, which only an organization admin can create. A team admin can create accounts for their own team.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateServiceAccountRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ServiceAccountV1" - } - } + "title": "Cursor" } } - }, - "x-stability": "unstable" - } - }, - "/v1/service_accounts/{service_account_id}": { - "delete": { - "summary": "Deletes a service account", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } ], - "description": "Deletes a disabled service account that no trust rule uses. Disable the account and delete its trust rules first.", "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeletedServiceAccountV1" + "$ref": "#/components/schemas/GatewayEventsResponseV1" } } } } - }, - "x-stability": "unstable" - }, - "parameters": [ - { - "$ref": "#/components/parameters/service_account_id" } - ], - "get": { - "summary": "Gets a service account", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ServiceAccountV1" - } - } - } - } - }, - "x-stability": "unstable" - }, - "patch": { - "summary": "Updates a service account", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/service_accounts/{service_account_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"disabled\": true\n}'" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/service_accounts/{service_account_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'disabled': True}\n)\n\nprint(response.text)" - } - ], - "description": "Updates the fields you send. Set `disabled` to true to stop the account being used, and back to false to restore it. `preset_permissions` replaces the account's access as a whole. The owning team can't change.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateServiceAccountRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ServiceAccountV1" - } - } - } - } - }, - "x-stability": "unstable" - } - }, - "/v1/access/predefined_identity_providers": { - "get": { - "summary": "Lists predefined identity providers", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/predefined_identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/predefined_identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Lists the identity providers Baseten supports, with the issuer format for those where each account, tenant, or cluster has its own issuer.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PredefinedIdentityProvidersV1" - } - } - } - } - }, - "x-stability": "unstable" } }, - "/v1/access/identity_providers": { + "/v1/explore/metadata": { "get": { - "summary": "Lists identity providers", + "summary": "Lists model metadata", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/explore/metadata \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'predefined_kind': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/explore/metadata\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'provider': None, 'q': None}\n)\n\nprint(response.text)" } ], - "description": "Lists the organization's identity providers. Organization and team admins can list them.", + "description": "Lists all live model metadata rows, e.g. for model pickers.", "parameters": [ { "name": "cursor", @@ -10968,14 +10412,13 @@ } }, { - "name": "name", + "name": "provider", "in": "query", "required": false, - "description": "Only the provider with this name, ignoring case", + "description": "Filter to a provider by slug prefix, e.g. 'anthropic'. Preserved by the cursor; if repeated, must match the original filter.", "schema": { "anyOf": [ { - "minLength": 1, "type": "string" }, { @@ -10983,24 +10426,25 @@ } ], "default": null, - "title": "Name" + "title": "Provider" } }, { - "name": "predefined_kind", + "name": "q", "in": "query", "required": false, - "description": "Only this predefined provider's issuers", + "description": "Case-insensitive substring search over metadata slugs. Preserved by the cursor; if repeated, must match the original filter.", "schema": { "anyOf": [ { - "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1" + "type": "string" }, { "type": "null" } ], - "default": null + "default": null, + "title": "Q" } } ], @@ -11010,32 +10454,34 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IdentityProvidersV1" + "$ref": "#/components/schemas/ExploreMetadataResponseV1" } } } } }, "x-stability": "unstable" - }, + } + }, + "/v1/grid/token": { "post": { - "summary": "Adds an identity provider", + "summary": "Creates a Grid access token", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/identity_providers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"prod-eks\",\n \"predefined\": {\n \"kind\": \"AWS_EKS\",\n \"issuer_url\": \"https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE\"\n }\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/token \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'prod-eks', 'predefined': {'kind': 'AWS_EKS', 'issuer_url': 'https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE'}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/token\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Adds an identity provider to the organization. For a provider with a per-customer issuer, the issuer must match the provider's format, and its signing keys are fetched before it's saved; a failure returns 422 with the reason. Each provider with a fixed issuer can be added once. Only organization admins can call this endpoint.", + "description": "Exchanges your Baseten credentials for a short-lived token that authenticates against the Grid gateway as you, in the given team. Tokens expire after four hours and cannot be renewed; request a new one when needed. Routes keys cannot create tokens.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateIdentityProviderRequestV1" + "$ref": "#/components/schemas/CreateGridTokenRequestV1" } } }, @@ -11047,7 +10493,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IdentityProviderV1" + "$ref": "#/components/schemas/GridTokenV1" } } } @@ -11056,88 +10502,98 @@ "x-stability": "unstable" } }, - "/v1/access/identity_providers/verify": { - "post": { - "summary": "Checks an identity provider before adding it", + "/v1/grid/routes": { + "get": { + "summary": "Lists routes", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/identity_providers/verify \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"predefined\": {\n \"kind\": \"AWS_EKS\",\n \"issuer_url\": \"https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE\"\n }\n}'" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/verify\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'predefined': {'kind': 'AWS_EKS', 'issuer_url': 'https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE'}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'name': None}\n)\n\nprint(response.text)" } ], - "description": "Runs the checks that adding the identity provider runs, without adding it: the issuer's format, that the organization doesn't have it yet, and, for a provider with a per-customer issuer, that its signing keys can be fetched. A failed check returns 200 with `valid` false and the reason. Only organization admins can call this endpoint.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/VerifyIdentityProviderRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/VerificationV1" + "description": "Lists routes you can invoke, newest first, optionally filtered by exact name. Without `team_id`, routes from every team where you can invoke routes. With `for_harnesses`, exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - } + ], + "default": null, + "title": "Cursor" } - } - }, - "x-stability": "unstable" - } - }, - "/v1/access/identity_providers/{identity_provider_id}": { - "delete": { - "summary": "Deletes an identity provider", - "x-codeSamples": [ + }, { - "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Removes the identity provider from the organization. Returns 409 while a trust rule uses it. Only organization admins can call this endpoint.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DeletedIdentityProviderV1" + "name": "team_id", + "in": "query", + "required": false, + "description": "Limit routes to this team. Without it, routes from every team where you can invoke routes.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - } + ], + "default": null, + "title": "Team Id" } - } - }, - "x-stability": "unstable" - }, - "parameters": [ - { - "$ref": "#/components/parameters/identity_provider_id" - } - ], - "get": { - "summary": "Gets an identity provider", - "x-codeSamples": [ + }, { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "name": "for_harnesses", + "in": "query", + "required": false, + "description": "Set by harness setup and sync. Returns routes from exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", + "schema": { + "default": false, + "title": "For Harnesses", + "type": "boolean" + } }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "name": "name", + "in": "query", + "required": false, + "description": "Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Name" + } } ], "responses": { @@ -11146,7 +10602,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IdentityProviderV1" + "$ref": "#/components/schemas/GridRoutesResponseV1" } } } @@ -11154,24 +10610,24 @@ }, "x-stability": "unstable" }, - "patch": { - "summary": "Updates an identity provider", + "post": { + "summary": "Creates a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/access/identity_providers/{identity_provider_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"prod-eks\"\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"display_name\": \"Assistant\",\n \"target\": {\n \"model\": \"zai-org/GLM-5.3\",\n \"type\": \"BASETEN_MODEL_API\"\n },\n \"description\": \"Assistant for code review and debugging.\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/identity_providers/{identity_provider_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'name': 'prod-eks'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'display_name': 'Assistant', 'target': {'model': 'zai-org/GLM-5.3', 'type': 'BASETEN_MODEL_API'}, 'description': 'Assistant for code review and debugging.'}\n)\n\nprint(response.text)" } ], - "description": "Updates the fields you send. The provider and issuer can't change. Only organization admins can call this endpoint.", + "description": "Creates and derives a name for the provided route configuration. CONNECTION targets reference a connection owned by the route's team; create the connection first.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateIdentityProviderRequestV1" + "$ref": "#/components/schemas/CreateGridRouteRequestV1" } } }, @@ -11183,7 +10639,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IdentityProviderV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11192,20 +10648,20 @@ "x-stability": "unstable" } }, - "/v1/access/trust_rules": { + "/v1/grid/routes/usage": { "get": { - "summary": "Lists trust rules", + "summary": "Gets daily Grid usage and estimated costs", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/trust_rules \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/usage \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'name': None, 'identity_provider_id': None, 'service_account_id': None, 'team_id': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/usage\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" } ], - "description": "Lists the trust rules you administer: every rule for an organization admin, and rules for your teams' service accounts for a team admin.", + "description": "Buckets are UTC days, and days with no usage are included. Organization admins see all Grid usage in the organization. Team admins see usage in teams they manage. Other members, including viewers, see only usage from Routes keys they created, including keys that have since expired, been revoked, or been deleted. Usage can be filtered and grouped by the team it was metered in. Usage is metered every 15 minutes, so the current hour can lag. Model API costs use your prices at the time of each request and include tool calls. xAI costs are the charges xAI reports. OpenAI and Anthropic costs are estimated from Baseten's reference prices and may differ from your provider's bill. Vertex and OpenAI-compatible usage is not included. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges. Usage is retained for 92 days.", "parameters": [ { "name": "cursor", @@ -11229,24 +10685,23 @@ "name": "limit", "in": "query", "required": false, - "description": "Maximum number of items to return.", + "description": "Number of daily buckets to return. Defaults to 7; maximum 31.", "schema": { - "default": 100, - "maximum": 1000, + "default": 7, + "maximum": 31, "minimum": 1, "title": "Limit", "type": "integer" } }, { - "name": "name", + "name": "team_id", "in": "query", "required": false, - "description": "Only the rule with this name, ignoring case", + "description": "Limit usage to a team you can access. Organization admins can view all usage in the team, team admins can view usage in teams they manage, and other members can view only their own usage. Without a team, organization admins see all organization usage, team admins see their managed teams, and other members see their own usage.", "schema": { "anyOf": [ { - "minLength": 1, "type": "string" }, { @@ -11254,17 +10709,18 @@ } ], "default": null, - "title": "Name" + "title": "Team Id" } }, { - "name": "identity_provider_id", + "name": "start_date", "in": "query", "required": false, - "description": "Only this provider's rules", + "description": "Inclusive UTC calendar day at the start of the query range. Defaults to the previous UTC date, and is ignored when you pass a cursor.", "schema": { "anyOf": [ { + "format": "date", "type": "string" }, { @@ -11272,17 +10728,18 @@ } ], "default": null, - "title": "Identity Provider Id" + "title": "Start Date" } }, { - "name": "service_account_id", + "name": "end_date", "in": "query", "required": false, - "description": "Only rules for this service account", + "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included.", "schema": { "anyOf": [ { + "format": "date", "type": "string" }, { @@ -11290,111 +10747,82 @@ } ], "default": null, - "title": "Service Account Id" + "title": "End Date" } }, { - "name": "team_id", + "name": "group_by", "in": "query", "required": false, - "description": "Only rules for this team's service accounts", + "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Team Id" - } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AccessTrustRulesV1" - } - } + "items": { + "$ref": "#/components/schemas/GridRouteUsageDimensionV1" + }, + "title": "Group By", + "type": "array" } - } - }, - "x-stability": "unstable" - }, - "post": { - "summary": "Creates a trust rule", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/trust_rules \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"models-main-deploy\",\n \"identity_provider_id\": \"abcd1234\",\n \"service_account_id\": \"wxyz5678\",\n \"condition\": \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\",\n \"audience\": \"https://api.baseten.co\"\n}'" }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'name': 'models-main-deploy', 'identity_provider_id': 'abcd1234', 'service_account_id': 'wxyz5678', 'condition': \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\", 'audience': 'https://api.baseten.co'}\n)\n\nprint(response.text)" - } - ], - "description": "Creates a rule that lets tokens from an identity provider act as a service account. Organization admins can create rules for any service account, team admins for their own team's. An organization API key manager key can't target organization accounts.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateAccessTrustRuleRequestV1" - } + "name": "user_ids", + "in": "query", + "required": false, + "description": "Return only usage from Routes keys created by these user IDs, repeated once per ID.", + "schema": { + "items": { + "type": "string" + }, + "title": "User Ids", + "type": "array" } }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AccessTrustRuleV1" - } - } + { + "name": "models", + "in": "query", + "required": false, + "description": "Return only usage for these exact model names, repeated once per model.", + "schema": { + "items": { + "type": "string" + }, + "title": "Models", + "type": "array" } - } - }, - "x-stability": "unstable" - } - }, - "/v1/access/trust_rules/verify": { - "post": { - "summary": "Checks a trust rule's condition and audience", - "x-codeSamples": [ + }, { - "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/access/trust_rules/verify \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"identity_provider_id\": \"abcd1234\",\n \"condition\": \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\",\n \"audience\": \"https://api.baseten.co\"\n}'" + "name": "providers", + "in": "query", + "required": false, + "description": "Return only usage for these providers, repeated once per provider.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridProviderV1" + }, + "title": "Providers", + "type": "array" + } }, { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/verify\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'identity_provider_id': 'abcd1234', 'condition': \"claims.repository_owner_id == '12345' && claims.sub == 'repo:acme/models:ref:refs/heads/main'\", 'audience': 'https://api.baseten.co'}\n)\n\nprint(response.text)" + "name": "harnesses", + "in": "query", + "required": false, + "description": "Return only usage for these harnesses, repeated once per harness. Omit to include all usage, including usage with no recorded harness.", + "schema": { + "items": { + "$ref": "#/components/schemas/GridRouteUsageHarnessV1" + }, + "title": "Harnesses", + "type": "array" + } } ], - "description": "Runs the checks that creating or updating a trust rule runs on its condition and audience, without saving anything: that the condition compiles and pins the claims the identity provider requires. A failed check returns 200 with `valid` false and the reason.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/VerifyAccessTrustRuleRequestV1" - } - } - }, - "required": true - }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/VerificationV1" + "$ref": "#/components/schemas/GridRouteUsageResponseV1" } } } @@ -11403,27 +10831,26 @@ "x-stability": "unstable" } }, - "/v1/access/trust_rules/{trust_rule_id}": { + "/v1/grid/routes/{route_id}": { "delete": { - "summary": "Deletes a trust rule", + "summary": "Deletes a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "New exchanges through the rule fail at once; tokens already issued keep working until they expire.", "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeletedAccessTrustRuleV1" + "$ref": "#/components/schemas/GridRouteTombstoneV1" } } } @@ -11433,19 +10860,19 @@ }, "parameters": [ { - "$ref": "#/components/parameters/trust_rule_id" + "$ref": "#/components/parameters/route_id" } ], "get": { - "summary": "Gets a trust rule", + "summary": "Gets a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -11454,7 +10881,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AccessTrustRuleV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11463,58 +10890,23 @@ "x-stability": "unstable" }, "patch": { - "summary": "Updates a trust rule", + "summary": "Updates a route", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/access/trust_rules/{trust_rule_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"name\": \"models-release-deploy\"\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"description\": \"Assistant for code review and debugging.\",\n \"display_name\": \"Assistant\",\n \"target\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/access/trust_rules/{trust_rule_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'name': 'models-release-deploy'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'description': 'Assistant for code review and debugging.', 'display_name': 'Assistant', 'target': None}\n)\n\nprint(response.text)" } ], - "description": "Updates the fields you send. Changes apply to new exchanges only. The identity provider can't change.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateAccessTrustRuleRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AccessTrustRuleV1" - } - } - } - } - }, - "x-stability": "unstable" - } - }, - "/v1/auth/token": { - "post": { - "summary": "Exchanges an identity provider's JWT for an access token", - "security": [], - "description": "Exchanges a JWT from your identity provider for a short-lived Baseten access token, as described in RFC 8693. Send no API key: the JWT is the credential. Name the trust rule to check the JWT against as the `audience`, and send the access token as `Authorization: Bearer` on later requests. Errors follow RFC 6749 section 5.2: a 400 response with an `error` of `invalid_request`, `unsupported_grant_type`, or `invalid_grant`. A well-formed request that is refused always returns `invalid_grant`, whatever the reason.", + "description": "The route name, target type, and owning team are immutable.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TokenExchangeRequestV1" - } - }, - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/TokenExchangeRequestV1" + "$ref": "#/components/schemas/UpdateGridRouteRequestV1" } } }, @@ -11526,7 +10918,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TokenExchangeResponseV1" + "$ref": "#/components/schemas/GridRouteV1" } } } @@ -11535,29 +10927,30 @@ "x-stability": "unstable" } }, - "/v1/gateway/events": { + "/v1/grid/team_settings": { "get": { - "summary": "Lists gateway events", + "summary": "Gets a team's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/gateway/events \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/gateway/events\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'start_time': None, 'end_time': None, 'limit': None, 'cursor': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], + "description": "Returns the settings that apply to the team, including the default models for each coding harness and the team's spend limits. Any member who can invoke the team's routes can read them. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", "parameters": [ { - "name": "start_time", + "name": "team_id", "in": "query", "required": false, - "description": "Inclusive start (ISO 8601, UTC). Required without a cursor.", + "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", "schema": { "anyOf": [ { - "format": "date-time", + "minLength": 1, "type": "string" }, { @@ -11565,121 +10958,79 @@ } ], "default": null, - "title": "Start Time" - } - }, - { - "name": "end_time", - "in": "query", - "required": false, - "description": "Exclusive end (ISO 8601, UTC). Defaults to now.", - "schema": { - "anyOf": [ - { - "format": "date-time", - "type": "string" - }, - { - "type": "null" - } + "examples": [ + "abc1234" ], - "default": null, - "title": "End Time" + "title": "Team Id" } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Max events. Default 100, max 1000.", - "schema": { - "anyOf": [ - { - "maximum": 1000, - "minimum": 1, - "type": "integer" - }, - { - "type": "null" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridTeamSettingsV1" } - ], - "default": null, - "title": "Limit" - } - }, - { - "name": "api_keys", - "in": "query", - "required": false, - "description": "Return only events for these API key prefixes, repeated once per prefix.", - "schema": { - "items": { - "type": "string" - }, - "title": "Api Keys", - "type": "array" + } } - }, + } + }, + "x-stability": "unstable" + }, + "patch": { + "summary": "Updates a team's Grid settings by team ID or your only team", + "x-codeSamples": [ { - "name": "external_entity_ids", - "in": "query", - "required": false, - "description": "Return only events for these external entity IDs, repeated once per ID.", - "schema": { - "items": { - "type": "string" - }, - "title": "External Entity Ids", - "type": "array" - } + "lang": "bash", + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"harness_defaults\": null,\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" }, { - "name": "cursor", - "in": "query", - "required": false, - "description": "Next-page cursor. Other parameters are ignored.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" - } + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'harness_defaults': None, 'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], + "description": "Changes only the fields in the request, all or nothing. Requires team admin, and organization admin to change the team-wide spend limit. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateGridTeamSettingsRequestV1" + } + } + }, + "required": true + }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayEventsResponseV1" + "$ref": "#/components/schemas/GridTeamSettingsV1" } } } } - } + }, + "x-stability": "unstable" } }, - "/v1/explore/metadata": { + "/v1/grid/team_settings/users": { "get": { - "summary": "Lists model metadata", + "summary": "Lists members' Grid settings", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/explore/metadata \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/explore/metadata\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'provider': None, 'q': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Lists all live model metadata rows, e.g. for model pickers.", + "description": "Returns each member's settings in each team, including organization admins and Grid service accounts, one row per team membership. With `team_id`, one team, which requires team admin for it or organization admin; without it, every team you administer, which is none for members.", "parameters": [ { "name": "cursor", @@ -11713,13 +11064,14 @@ } }, { - "name": "provider", + "name": "team_id", "in": "query", "required": false, - "description": "Filter to a provider by slug prefix, e.g. 'anthropic'. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Limit the list to this team. Without it, the members of every team you administer, one row per team.", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -11727,25 +11079,10 @@ } ], "default": null, - "title": "Provider" - } - }, - { - "name": "q", - "in": "query", - "required": false, - "description": "Case-insensitive substring search over metadata slugs. Preserved by the cursor; if repeated, must match the original filter.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "examples": [ + "abc1234" ], - "default": null, - "title": "Q" + "title": "Team Id" } } ], @@ -11755,7 +11092,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ExploreMetadataResponseV1" + "$ref": "#/components/schemas/GridTeamUserSettingsListV1" } } } @@ -11764,99 +11101,30 @@ "x-stability": "unstable" } }, - "/v1/grid/token": { - "post": { - "summary": "Creates a Grid access token", + "/v1/grid/team_settings/users/{user_id}": { + "get": { + "summary": "Gets a user's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/token \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\"\n}'" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/token\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234'}\n)\n\nprint(response.text)" - } - ], - "description": "Exchanges your Baseten credentials for a short-lived token that authenticates against the Grid gateway as you, in the given team. Tokens expire after four hours and cannot be renewed; request a new one when needed. Routes keys cannot create tokens.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateGridTokenRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridTokenV1" - } - } - } - } - }, - "x-stability": "unstable" - } - }, - "/v1/grid/routes": { - "get": { - "summary": "Lists routes", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'name': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Lists routes you can invoke, newest first, optionally filtered by exact name. Without `team_id`, routes from every team where you can invoke routes. With `for_harnesses`, exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", + "description": "Returns the user's spend limit for Baseten Grid in the team, their spend in the team this month, and whether that spend reached the limit. Members can read their own settings; team admins can read members' settings in teams they administer, and organization admins can read anyone's. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", "parameters": [ - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - } - }, { "name": "team_id", "in": "query", "required": false, - "description": "Limit routes to this team. Without it, routes from every team where you can invoke routes.", + "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", "schema": { "anyOf": [ { + "minLength": 1, "type": "string" }, { @@ -11864,36 +11132,10 @@ } ], "default": null, - "title": "Team Id" - } - }, - { - "name": "for_harnesses", - "in": "query", - "required": false, - "description": "Set by harness setup and sync. Returns routes from exactly one team: `team_id`, else the team you belong to; when you belong to several and name none, the request fails with a 400.", - "schema": { - "default": false, - "title": "For Harnesses", - "type": "boolean" - } - }, - { - "name": "name", - "in": "query", - "required": false, - "description": "Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "examples": [ + "abc1234" ], - "default": null, - "title": "Name" + "title": "Team Id" } } ], @@ -11903,7 +11145,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRoutesResponseV1" + "$ref": "#/components/schemas/GridTeamUserSettingsV1" } } } @@ -11911,24 +11153,29 @@ }, "x-stability": "unstable" }, - "post": { - "summary": "Creates a route", + "parameters": [ + { + "$ref": "#/components/parameters/user_id" + } + ], + "patch": { + "summary": "Updates a user's Grid settings by team ID or your only team", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/routes \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"display_name\": \"Assistant\",\n \"target\": {\n \"model\": \"zai-org/GLM-5.3\",\n \"type\": \"BASETEN_MODEL_API\"\n },\n \"description\": \"Assistant for code review and debugging.\"\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'display_name': 'Assistant', 'target': {'model': 'zai-org/GLM-5.3', 'type': 'BASETEN_MODEL_API'}, 'description': 'Assistant for code review and debugging.'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" } ], - "description": "Creates and derives a name for the provided route configuration. CONNECTION targets reference a connection owned by the route's team; create the connection first. INTELLIGENT targets reference a route classifier from GET /v1/grid/route_classifiers.", + "description": "Changes only the fields in the request. Once the user's metered spend in the team in a month reaches the spend limit, requests with Routes keys they created in the team are rejected until the limit is raised or the next month starts. Spend is metered every 15 minutes and can lag, so a user can go over the limit. Requires team admin for the specified team or organization admin. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridRouteRequestV1" + "$ref": "#/components/schemas/UpdateGridUserSettingsRequestV1" } } }, @@ -11940,7 +11187,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/GridTeamUserSettingsV1" } } } @@ -11949,20 +11196,20 @@ "x-stability": "unstable" } }, - "/v1/grid/routes/usage": { + "/v1/grid/connections": { "get": { - "summary": "Gets daily Grid usage and estimated costs", + "summary": "Lists connections", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/usage \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/usage\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None, 'start_date': None, 'end_date': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" } ], - "description": "Buckets are UTC days, and days with no usage are included. Organization admins see all Grid usage in the organization. Team admins see usage in teams they manage. Other members, including viewers, see only usage from Routes keys they created, including keys that have since expired, been revoked, or been deleted. Usage can be filtered and grouped by the team it was metered in. Usage is metered every 15 minutes, so the current hour can lag. Model API costs use your prices at the time of each request and include tool calls. xAI costs are the charges xAI reports. OpenAI and Anthropic costs are estimated from Baseten's reference prices and may differ from your provider's bill. Vertex and OpenAI-compatible usage is not included. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges. Usage is retained for 92 days.", + "description": "Lists connections, newest first: the team's with `team_id`, else those of every team where you can invoke routes.", "parameters": [ { "name": "cursor", @@ -11986,10 +11233,10 @@ "name": "limit", "in": "query", "required": false, - "description": "Number of daily buckets to return. Defaults to 7; maximum 31.", + "description": "Maximum number of items to return.", "schema": { - "default": 7, - "maximum": 31, + "default": 100, + "maximum": 1000, "minimum": 1, "title": "Limit", "type": "integer" @@ -11999,7 +11246,7 @@ "name": "team_id", "in": "query", "required": false, - "description": "Limit usage to a team you can access. Organization admins can view all usage in the team, team admins can view usage in teams they manage, and other members can view only their own usage. Without a team, organization admins see all organization usage, team admins see their managed teams, and other members see their own usage.", + "description": "Limit connections to this team. Without it, connections from every team where you can invoke routes.", "schema": { "anyOf": [ { @@ -12012,131 +11259,52 @@ "default": null, "title": "Team Id" } - }, - { - "name": "start_date", - "in": "query", - "required": false, - "description": "Inclusive UTC calendar day at the start of the query range. Defaults to the previous UTC date, and is ignored when you pass a cursor.", - "schema": { - "anyOf": [ - { - "format": "date", - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Start Date" - } - }, - { - "name": "end_date", - "in": "query", - "required": false, - "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included.", - "schema": { - "anyOf": [ - { - "format": "date", - "type": "string" - }, - { - "type": "null" + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GridConnectionsResponseV1" } - ], - "default": null, - "title": "End Date" - } - }, - { - "name": "group_by", - "in": "query", - "required": false, - "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", - "schema": { - "items": { - "$ref": "#/components/schemas/GridRouteUsageDimensionV1" - }, - "title": "Group By", - "type": "array" - } - }, - { - "name": "user_ids", - "in": "query", - "required": false, - "description": "Return only usage from Routes keys created by these user IDs, repeated once per ID.", - "schema": { - "items": { - "type": "string" - }, - "title": "User Ids", - "type": "array" - } - }, - { - "name": "models", - "in": "query", - "required": false, - "description": "Return only usage for these exact model names, repeated once per model.", - "schema": { - "items": { - "type": "string" - }, - "title": "Models", - "type": "array" - } - }, - { - "name": "providers", - "in": "query", - "required": false, - "description": "Return only usage for these providers, repeated once per provider.", - "schema": { - "items": { - "$ref": "#/components/schemas/GridProviderV1" - }, - "title": "Providers", - "type": "array" + } } - }, + } + }, + "x-stability": "unstable" + }, + "post": { + "summary": "Creates a connection", + "x-codeSamples": [ { - "name": "harnesses", - "in": "query", - "required": false, - "description": "Return only usage for these harnesses, repeated once per harness. Omit to include all usage, including usage with no recorded harness.", - "schema": { - "items": { - "$ref": "#/components/schemas/GridRouteUsageHarnessV1" - }, - "title": "Harnesses", - "type": "array" - } + "lang": "bash", + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" }, { - "name": "api_key_prefixes", - "in": "query", - "required": false, - "description": "Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", - "schema": { - "items": { - "type": "string" - }, - "title": "Api Key Prefixes", - "type": "array" - } + "lang": "python", + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" } ], + "description": "Creates a connection from the team to an upstream provider.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateGridConnectionRequestV1" + } + } + }, + "required": true + }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteUsageResponseV1" + "$ref": "#/components/schemas/GridConnectionV1" } } } @@ -12145,26 +11313,27 @@ "x-stability": "unstable" } }, - "/v1/grid/routes/{route_id}": { + "/v1/grid/connections/{connection_id}": { "delete": { - "summary": "Deletes a route", + "summary": "Deletes a connection", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], + "description": "Deletes the connection. The team secret it points at is left in place.", "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteTombstoneV1" + "$ref": "#/components/schemas/GridConnectionTombstoneV1" } } } @@ -12174,19 +11343,19 @@ }, "parameters": [ { - "$ref": "#/components/parameters/route_id" + "$ref": "#/components/parameters/connection_id" } ], "get": { - "summary": "Gets a route", + "summary": "Gets a connection", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -12195,7 +11364,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/GridConnectionV1" } } } @@ -12204,23 +11373,23 @@ "x-stability": "unstable" }, "patch": { - "summary": "Updates a route", + "summary": "Updates a connection", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/routes/{route_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"description\": \"Assistant for code review and debugging.\",\n \"display_name\": \"Assistant\"\n}'" + "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/routes/{route_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'description': 'Assistant for code review and debugging.', 'display_name': 'Assistant'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" } ], - "description": "The route name, target, and owning team are immutable.", + "description": "Updates the connection's fields. The provider and owning team are immutable; point the connection at a new team secret to change its API key, or rotate the key itself by updating the secret.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateGridRouteRequestV1" + "$ref": "#/components/schemas/UpdateGridConnectionRequestV1" } } }, @@ -12232,7 +11401,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridRouteV1" + "$ref": "#/components/schemas/GridConnectionV1" } } } @@ -12241,30 +11410,29 @@ "x-stability": "unstable" } }, - "/v1/grid/team_settings": { + "/v1/grid/classifiers": { "get": { - "summary": "Gets a team's Grid settings by team ID or your only team", + "summary": "Lists classifiers available for intelligent routes", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" } ], - "description": "Returns the settings that apply to the team, including the default models for each coding harness and the team's spend limits. Any member who can invoke the team's routes can read them. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", + "description": "Returns Baseten-managed classifiers available to your organization, ordered by identifier. Classifiers cannot be created or modified through this API.", "parameters": [ { - "name": "team_id", + "name": "cursor", "in": "query", "required": false, - "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", "schema": { "anyOf": [ { - "minLength": 1, "type": "string" }, { @@ -12272,10 +11440,20 @@ } ], "default": null, - "examples": [ - "abc1234" - ], - "title": "Team Id" + "title": "Cursor" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum number of items to return.", + "schema": { + "default": 100, + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" } } ], @@ -12285,66 +11463,62 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamSettingsV1" + "$ref": "#/components/schemas/GridClassifiersResponseV1" } } } } }, "x-stability": "unstable" - }, - "patch": { - "summary": "Updates a team's Grid settings by team ID or your only team", + } + }, + "/v1/grid/classifiers/{classifier_id}": { + "get": { + "summary": "Gets a classifier available for intelligent routes", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"harness_defaults\": null,\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/classifiers/{classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'harness_defaults': None, 'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/classifiers/{classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], - "description": "Changes only the fields in the request, all or nothing. Requires team admin, and organization admin to change the team-wide spend limit. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateGridTeamSettingsRequestV1" - } - } - }, - "required": true - }, "responses": { "200": { "description": "", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamSettingsV1" + "$ref": "#/components/schemas/GridClassifierV1" } } } } }, "x-stability": "unstable" - } + }, + "parameters": [ + { + "$ref": "#/components/parameters/classifier_id" + } + ] }, - "/v1/grid/team_settings/users": { + "/v1/grid/route_classifiers": { "get": { - "summary": "Lists members' Grid settings", + "summary": "Lists route classifiers available for intelligent routes", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" } ], - "description": "Returns each member's settings in each team, including organization admins and Grid service accounts, one row per team membership. With `team_id`, one team, which requires team admin for it or organization admin; without it, every team you administer, which is none for members.", + "description": "Returns Baseten-managed route classifiers available to your organization, ordered by identifier. Route classifiers cannot be created or modified through this API.", "parameters": [ { "name": "cursor", @@ -12376,28 +11550,6 @@ "title": "Limit", "type": "integer" } - }, - { - "name": "team_id", - "in": "query", - "required": false, - "description": "Limit the list to this team. Without it, the members of every team you administer, one row per team.", - "schema": { - "anyOf": [ - { - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "examples": [ - "abc1234" - ], - "title": "Team Id" - } } ], "responses": { @@ -12406,7 +11558,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsListV1" + "$ref": "#/components/schemas/GridRouteClassifiersResponseV1" } } } @@ -12415,42 +11567,17 @@ "x-stability": "unstable" } }, - "/v1/grid/team_settings/users/{user_id}": { + "/v1/grid/route_classifiers/{route_classifier_id}": { "get": { - "summary": "Gets a user's Grid settings by team ID or your only team", + "summary": "Gets a route classifier available for intelligent routes", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'team_id': 'abc1234'}\n)\n\nprint(response.text)" - } - ], - "description": "Returns the user's spend limit for Baseten Grid in the team, their spend in the team this month, and whether that spend reached the limit. Members can read their own settings; team admins can read members' settings in teams they administer, and organization admins can read anyone's. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", - "parameters": [ - { - "name": "team_id", - "in": "query", - "required": false, - "description": "ID of the team. When omitted, the team you belong to; required when you belong to several.", - "schema": { - "anyOf": [ - { - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "examples": [ - "abc1234" - ], - "title": "Team Id" - } + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" } ], "responses": { @@ -12459,7 +11586,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsV1" + "$ref": "#/components/schemas/GridRouteClassifierV1" } } } @@ -12469,61 +11596,24 @@ }, "parameters": [ { - "$ref": "#/components/parameters/user_id" + "$ref": "#/components/parameters/route_classifier_id" } - ], - "patch": { - "summary": "Updates a user's Grid settings by team ID or your only team", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/team_settings/users/{user_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"spend_limit\": null,\n \"team_id\": \"abc1234\"\n}'" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/team_settings/users/{user_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'spend_limit': None, 'team_id': 'abc1234'}\n)\n\nprint(response.text)" - } - ], - "description": "Changes only the fields in the request. Once the user's metered spend in the team in a month reaches the spend limit, requests with Routes keys they created in the team are rejected until the limit is raised or the next month starts. Spend is metered every 15 minutes and can lag, so a user can go over the limit. Requires team admin for the specified team or organization admin. The team comes from `team_id` instead of the path. Omit it to use the team you belong to; when you belong to several, the request fails with a 400.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateGridUserSettingsRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridTeamUserSettingsV1" - } - } - } - } - }, - "x-stability": "unstable" - } + ] }, - "/v1/grid/connections": { + "/v1/grid/machine_users": { "get": { - "summary": "Lists connections", + "summary": "Lists machine users", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" + "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" } ], - "description": "Lists connections, newest first: the team's with `team_id`, else those of every team where you can invoke routes.", + "description": "Lists machine users, newest first: the team's with `team_id`, which requires team admin for it, else those of every team you administer.", "parameters": [ { "name": "cursor", @@ -12560,7 +11650,7 @@ "name": "team_id", "in": "query", "required": false, - "description": "Limit connections to this team. Without it, connections from every team where you can invoke routes.", + "description": "Limit machine users to this team. Without it, every team you administer.", "schema": { "anyOf": [ { @@ -12581,7 +11671,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionsResponseV1" + "$ref": "#/components/schemas/GridMachineUsersResponseV1" } } } @@ -12590,23 +11680,23 @@ "x-stability": "unstable" }, "post": { - "summary": "Creates a connection", + "summary": "Creates a machine user", "x-codeSamples": [ { "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/connections \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" + "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"name\": \"night-shift\",\n \"api_key\": null\n}'" }, { "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" + "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'name': 'night-shift', 'api_key': None}\n)\n\nprint(response.text)" } ], - "description": "Creates a connection from the team to an upstream provider.", + "description": "Creates a team-owned identity for an application, with its own Grid budget. Set `api_key` to also create its first API key, which the response returns only once. Set the machine user's spend limit with the user settings endpoint, using its `id` as the user ID. Requires team admin.", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateGridConnectionRequestV1" + "$ref": "#/components/schemas/CreateGridMachineUserRequestV1" } } }, @@ -12618,7 +11708,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GridConnectionV1" + "$ref": "#/components/schemas/CreatedGridMachineUserV1" } } } @@ -12627,316 +11717,7 @@ "x-stability": "unstable" } }, - "/v1/grid/connections/{connection_id}": { - "delete": { - "summary": "Deletes a connection", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request DELETE \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"DELETE\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "description": "Deletes the connection. The team secret it points at is left in place.", - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridConnectionTombstoneV1" - } - } - } - } - }, - "x-stability": "unstable" - }, - "parameters": [ - { - "$ref": "#/components/parameters/connection_id" - } - ], - "get": { - "summary": "Gets a connection", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridConnectionV1" - } - } - } - } - }, - "x-stability": "unstable" - }, - "patch": { - "summary": "Updates a connection", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request PATCH \\\n--url https://api.baseten.co/v1/grid/connections/{connection_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"config\": {\n \"provider\": \"ANTHROPIC\",\n \"secret_name\": \"anthropic-key\"\n }\n}'" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/connections/{connection_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"PATCH\",\n url,\n headers=headers,\n json={'config': {'provider': 'ANTHROPIC', 'secret_name': 'anthropic-key'}}\n)\n\nprint(response.text)" - } - ], - "description": "Updates the connection's fields. The provider and owning team are immutable; point the connection at a new team secret to change its API key, or rotate the key itself by updating the secret.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateGridConnectionRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridConnectionV1" - } - } - } - } - }, - "x-stability": "unstable" - } - }, - "/v1/grid/route_classifiers": { - "get": { - "summary": "Lists route classifiers available for intelligent routes", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None}\n)\n\nprint(response.text)" - } - ], - "description": "Returns Baseten-managed route classifiers available to your organization, ordered by identifier. Route classifiers cannot be created or modified through this API.", - "parameters": [ - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridRouteClassifiersResponseV1" - } - } - } - } - }, - "x-stability": "unstable" - } - }, - "/v1/grid/route_classifiers/{route_classifier_id}": { - "get": { - "summary": "Gets a route classifier available for intelligent routes", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id} \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/route_classifiers/{route_classifier_id}\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n json={}\n)\n\nprint(response.text)" - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridRouteClassifierV1" - } - } - } - } - }, - "x-stability": "unstable" - }, - "parameters": [ - { - "$ref": "#/components/parameters/route_classifier_id" - } - ] - }, - "/v1/grid/machine_users": { - "get": { - "summary": "Lists machine users", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request GET \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\"\n" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params={'cursor': None, 'team_id': None}\n)\n\nprint(response.text)" - } - ], - "description": "Lists machine users, newest first: the team's with `team_id`, which requires team admin for it, else those of every team you administer.", - "parameters": [ - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cursor" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum number of items to return.", - "schema": { - "default": 100, - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - } - }, - { - "name": "team_id", - "in": "query", - "required": false, - "description": "Limit machine users to this team. Without it, every team you administer.", - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Team Id" - } - } - ], - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GridMachineUsersResponseV1" - } - } - } - } - }, - "x-stability": "unstable" - }, - "post": { - "summary": "Creates a machine user", - "x-codeSamples": [ - { - "lang": "bash", - "source": "curl --request POST \\\n--url https://api.baseten.co/v1/grid/machine_users \\\n--header \"Authorization: Bearer $BASETEN_API_KEY\" \\\n--data '{\n \"team_id\": \"abc1234\",\n \"name\": \"night-shift\",\n \"api_key\": null\n}'" - }, - { - "lang": "python", - "source": "import requests\nimport os\nAPI_KEY = os.environ.get(\"BASETEN_API_KEY\", \"\")\nurl = \"https://api.baseten.co/v1/grid/machine_users\"\n\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\nresponse = requests.request(\n \"POST\",\n url,\n headers=headers,\n json={'team_id': 'abc1234', 'name': 'night-shift', 'api_key': None}\n)\n\nprint(response.text)" - } - ], - "description": "Creates a team-owned identity for an application, with its own Grid budget. Set `api_key` to also create its first API key, which the response returns only once. Set the machine user's spend limit with the user settings endpoint, using its `id` as the user ID. Requires team admin.", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateGridMachineUserRequestV1" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreatedGridMachineUserV1" - } - } - } - } - }, - "x-stability": "unstable" - } - }, - "/v1/grid/machine_users/{machine_user_id}": { + "/v1/grid/machine_users/{machine_user_id}": { "delete": { "summary": "Deletes a machine user", "x-codeSamples": [ @@ -19321,25 +18102,6 @@ "title": "PrepareModelUploadResponseV1", "type": "object" }, - "AuditFieldChangeV1": { - "description": "A field's value before and after an update.", - "properties": { - "old": { - "description": "The value before the update.", - "title": "Old" - }, - "new": { - "description": "The value after the update.", - "title": "New" - } - }, - "required": [ - "old", - "new" - ], - "title": "AuditFieldChangeV1", - "type": "object" - }, "AuditLogActorTypeV1": { "description": "Kind of actor that performed an audited action.", "enum": [ @@ -19347,8 +18109,7 @@ "API_KEY", "BASETEN_USER", "BASETEN_SYSTEM", - "TOMBSTONE_USER", - "SERVICE_ACCOUNT" + "TOMBSTONE_USER" ], "title": "AuditLogActorTypeV1", "type": "string" @@ -19398,45 +18159,6 @@ "default": null, "description": "Display name of the acting API key, when the actor is an API key.", "title": "Api Key Name" - }, - "service_account_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of the acting service account, when the actor is a service account.", - "title": "Service Account Id" - }, - "service_account_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Current name of the acting service account, when the actor is a service account.", - "title": "Service Account Name" - }, - "trust_rule_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of the trust rule the acting workload identity federation token was exchanged through, when the actor is a service account.", - "title": "Trust Rule Id" } }, "required": [ @@ -19448,8 +18170,7 @@ "AuditLogApiKeyRevocationReasonV1": { "description": "Reason an API key was revoked.", "enum": [ - "INACTIVITY", - "CREDENTIAL_EXPOSURE" + "INACTIVITY" ], "title": "AuditLogApiKeyRevocationReasonV1", "type": "string" @@ -19461,7 +18182,6 @@ "CREATOR_SERVICE_ACCOUNT", "MANAGE_API_KEYS_SERVICE_ACCOUNT", "INVOKE_ALL_MODELS_SERVICE_ACCOUNT", - "INVOKE_ALL_DEDICATED_MODELS_SERVICE_ACCOUNT", "INVOKE_ALLOWED_MODELS_SERVICE_ACCOUNT", "INVOKE_SCOPED_ENVS_AND_MODELS_SERVICE_ACCOUNT", "EXPORT_METRICS_ALL_MODELS_SERVICE_ACCOUNT", @@ -19518,9 +18238,6 @@ "GRID_MACHINE_USER_CREATED": "#/components/schemas/AuditLogEventGridMachineUserCreatedV1", "GRID_MACHINE_USER_DELETED": "#/components/schemas/AuditLogEventGridMachineUserDeletedV1", "GRID_MACHINE_USER_UPDATED": "#/components/schemas/AuditLogEventGridMachineUserUpdatedV1", - "IDENTITY_PROVIDER_CREATED": "#/components/schemas/AuditLogEventIdentityProviderCreatedV1", - "IDENTITY_PROVIDER_DELETED": "#/components/schemas/AuditLogEventIdentityProviderDeletedV1", - "IDENTITY_PROVIDER_UPDATED": "#/components/schemas/AuditLogEventIdentityProviderUpdatedV1", "MODEL_DELETED": "#/components/schemas/AuditLogEventModelDeletedV1", "MODEL_DEPLOYED": "#/components/schemas/AuditLogEventModelDeployedV1", "MODEL_DEPLOYMENT_ACTIVATED": "#/components/schemas/AuditLogEventModelDeploymentActivatedV1", @@ -19533,7 +18250,6 @@ "MODEL_DEPLOYMENT_RETRIED": "#/components/schemas/AuditLogEventModelDeploymentRetriedV1", "MODEL_PROMOTION_CONTROL_ACTION": "#/components/schemas/AuditLogEventModelPromotionControlActionV1", "MODEL_RENAMED": "#/components/schemas/AuditLogEventModelRenamedV1", - "ORGANIZATION_API_KEY_SETTINGS_UPDATED": "#/components/schemas/AuditLogEventOrganizationApiKeySettingsUpdatedV1", "PROVIDER_CONNECTION_CREATED": "#/components/schemas/AuditLogEventProviderConnectionCreatedV1", "PROVIDER_CONNECTION_DELETED": "#/components/schemas/AuditLogEventProviderConnectionDeletedV1", "PROVIDER_CONNECTION_UPDATED": "#/components/schemas/AuditLogEventProviderConnectionUpdatedV1", @@ -19541,16 +18257,10 @@ "REQUIRE_GROUP_BASED_ADMINS_ENABLED": "#/components/schemas/AuditLogEventRequireGroupBasedAdminsEnabledV1", "SECRET_DELETED": "#/components/schemas/AuditLogEventSecretDeletedV1", "SECRET_UPDATED": "#/components/schemas/AuditLogEventSecretUpdatedV1", - "SERVICE_ACCOUNT_CREATED": "#/components/schemas/AuditLogEventServiceAccountCreatedV1", - "SERVICE_ACCOUNT_DELETED": "#/components/schemas/AuditLogEventServiceAccountDeletedV1", - "SERVICE_ACCOUNT_UPDATED": "#/components/schemas/AuditLogEventServiceAccountUpdatedV1", "SSH_CERTIFICATE_SIGNED": "#/components/schemas/AuditLogEventSshCertificateSignedV1", "TELEMETRY_EXPORT_CREATED": "#/components/schemas/AuditLogEventTelemetryExportCreatedV1", "TELEMETRY_EXPORT_DELETED": "#/components/schemas/AuditLogEventTelemetryExportDeletedV1", "TELEMETRY_EXPORT_UPDATED": "#/components/schemas/AuditLogEventTelemetryExportUpdatedV1", - "TRUST_RULE_CREATED": "#/components/schemas/AuditLogEventTrustRuleCreatedV1", - "TRUST_RULE_DELETED": "#/components/schemas/AuditLogEventTrustRuleDeletedV1", - "TRUST_RULE_UPDATED": "#/components/schemas/AuditLogEventTrustRuleUpdatedV1", "USER_INVITED": "#/components/schemas/AuditLogEventUserInvitedV1", "USER_JOINED_ORGANIZATION": "#/components/schemas/AuditLogEventUserJoinedOrganizationV1", "USER_REMOVED": "#/components/schemas/AuditLogEventUserRemovedV1", @@ -19647,9 +18357,6 @@ { "$ref": "#/components/schemas/AuditLogEventApiKeyLifetimeLimitsUpdatedV1" }, - { - "$ref": "#/components/schemas/AuditLogEventOrganizationApiKeySettingsUpdatedV1" - }, { "$ref": "#/components/schemas/AuditLogEventGatewayEndpointCreatedV1" }, @@ -19751,33 +18458,6 @@ }, { "$ref": "#/components/schemas/AuditLogEventTelemetryExportDeletedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventServiceAccountCreatedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventServiceAccountUpdatedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventServiceAccountDeletedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventIdentityProviderCreatedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventIdentityProviderUpdatedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventIdentityProviderDeletedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventTrustRuleCreatedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventTrustRuleUpdatedV1" - }, - { - "$ref": "#/components/schemas/AuditLogEventTrustRuleDeletedV1" } ], "title": "Event Data" @@ -22342,108 +21022,6 @@ "title": "AuditLogEventGridMachineUserUpdatedV1", "type": "object" }, - "AuditLogEventIdentityProviderCreatedV1": { - "description": "An identity provider was added.", - "properties": { - "event_type": { - "const": "IDENTITY_PROVIDER_CREATED", - "title": "Event Type", - "type": "string" - }, - "identity_provider_id": { - "title": "Identity Provider Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Null when the provider was added without one.", - "title": "Description" - }, - "predefined": { - "$ref": "#/components/schemas/AuditLogEventPredefinedIdentityProviderConfigV1", - "description": "The provider's settings, as the identity provider resource returns them." - } - }, - "required": [ - "event_type", - "identity_provider_id", - "name", - "predefined" - ], - "title": "AuditLogEventIdentityProviderCreatedV1", - "type": "object" - }, - "AuditLogEventIdentityProviderDeletedV1": { - "description": "An identity provider was deleted.", - "properties": { - "event_type": { - "const": "IDENTITY_PROVIDER_DELETED", - "title": "Event Type", - "type": "string" - }, - "identity_provider_id": { - "title": "Identity Provider Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - } - }, - "required": [ - "event_type", - "identity_provider_id", - "name" - ], - "title": "AuditLogEventIdentityProviderDeletedV1", - "type": "object" - }, - "AuditLogEventIdentityProviderUpdatedV1": { - "description": "An identity provider was updated.", - "properties": { - "event_type": { - "const": "IDENTITY_PROVIDER_UPDATED", - "title": "Event Type", - "type": "string" - }, - "identity_provider_id": { - "title": "Identity Provider Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/components/schemas/AuditFieldChangeV1" - }, - "description": "The fields the update changed, keyed by field name.", - "title": "Changes", - "type": "object" - } - }, - "required": [ - "event_type", - "identity_provider_id", - "name", - "changes" - ], - "title": "AuditLogEventIdentityProviderUpdatedV1", - "type": "object" - }, "AuditLogEventModelDeletedV1": { "description": "A model was deleted.", "properties": { @@ -23211,67 +21789,6 @@ "title": "AuditLogEventModelRenamedV1", "type": "object" }, - "AuditLogEventOrganizationApiKeySettingsUpdatedV1": { - "description": "An administrator changed which classes of API key the organization allows creating.", - "properties": { - "event_type": { - "const": "ORGANIZATION_API_KEY_SETTINGS_UPDATED", - "title": "Event Type", - "type": "string" - }, - "organization_id": { - "title": "Organization Id", - "type": "string" - }, - "previous_allow_personal_api_keys": { - "title": "Previous Allow Personal Api Keys", - "type": "boolean" - }, - "new_allow_personal_api_keys": { - "title": "New Allow Personal Api Keys", - "type": "boolean" - }, - "previous_allow_service_account_api_keys": { - "title": "Previous Allow Service Account Api Keys", - "type": "boolean" - }, - "new_allow_service_account_api_keys": { - "title": "New Allow Service Account Api Keys", - "type": "boolean" - } - }, - "required": [ - "event_type", - "organization_id", - "previous_allow_personal_api_keys", - "new_allow_personal_api_keys", - "previous_allow_service_account_api_keys", - "new_allow_service_account_api_keys" - ], - "title": "AuditLogEventOrganizationApiKeySettingsUpdatedV1", - "type": "object" - }, - "AuditLogEventPredefinedIdentityProviderConfigV1": { - "description": "Settings of a predefined identity provider, as recorded on an identity provider event. Not\nitself an event payload.", - "properties": { - "kind": { - "description": "Which predefined provider, for example `AWS_EKS`.", - "title": "Kind", - "type": "string" - }, - "issuer_url": { - "description": "The `iss` claim of the provider's tokens.", - "title": "Issuer Url", - "type": "string" - } - }, - "required": [ - "kind", - "issuer_url" - ], - "title": "AuditLogEventPredefinedIdentityProviderConfigV1", - "type": "object" - }, "AuditLogEventPromotionSettingsOverrideV1": { "description": "Promotion settings overridden for one promotion. Null means the environment's value. Not\nitself a payload in the discriminated union.", "properties": { @@ -23595,162 +22112,6 @@ "title": "AuditLogEventSecretUpdatedV1", "type": "object" }, - "AuditLogEventServiceAccountCreatedV1": { - "description": "A service account was created.", - "properties": { - "event_type": { - "const": "SERVICE_ACCOUNT_CREATED", - "title": "Event Type", - "type": "string" - }, - "service_account_id": { - "title": "Service Account Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Null when the account was created without one.", - "title": "Description" - }, - "owner_team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The team that owns the account. Null for an organization account.", - "title": "Owner Team Id" - }, - "preset_permissions": { - "$ref": "#/components/schemas/AuditLogEventServiceAccountPresetPermissionsV1" - } - }, - "required": [ - "event_type", - "service_account_id", - "name", - "preset_permissions" - ], - "title": "AuditLogEventServiceAccountCreatedV1", - "type": "object" - }, - "AuditLogEventServiceAccountDeletedV1": { - "description": "A service account was deleted.", - "properties": { - "event_type": { - "const": "SERVICE_ACCOUNT_DELETED", - "title": "Event Type", - "type": "string" - }, - "service_account_id": { - "title": "Service Account Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - } - }, - "required": [ - "event_type", - "service_account_id", - "name" - ], - "title": "AuditLogEventServiceAccountDeletedV1", - "type": "object" - }, - "AuditLogEventServiceAccountPresetPermissionsV1": { - "description": "A service account's access, as recorded on a service account event. Not itself an event\npayload.", - "properties": { - "api_key_type": { - "description": "The API key type whose permissions the account has, as API key events record it.", - "title": "Api Key Type", - "type": "string" - }, - "model_ids": { - "description": "Models the access is limited to; empty for all.", - "items": { - "type": "string" - }, - "title": "Model Ids", - "type": "array" - }, - "environment_names": { - "description": "Environments the access is limited to, or may also manage; empty for none.", - "items": { - "type": "string" - }, - "title": "Environment Names", - "type": "array" - }, - "model_api_slugs": { - "description": "Model APIs the access is limited to; empty for all.", - "items": { - "type": "string" - }, - "title": "Model Api Slugs", - "type": "array" - } - }, - "required": [ - "api_key_type", - "model_ids", - "environment_names", - "model_api_slugs" - ], - "title": "AuditLogEventServiceAccountPresetPermissionsV1", - "type": "object" - }, - "AuditLogEventServiceAccountUpdatedV1": { - "description": "A service account was updated. Disabling or enabling it is a change to `disabled`.", - "properties": { - "event_type": { - "const": "SERVICE_ACCOUNT_UPDATED", - "title": "Event Type", - "type": "string" - }, - "service_account_id": { - "title": "Service Account Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/components/schemas/AuditFieldChangeV1" - }, - "description": "The fields the update changed, keyed by field name.", - "title": "Changes", - "type": "object" - } - }, - "required": [ - "event_type", - "service_account_id", - "name", - "changes" - ], - "title": "AuditLogEventServiceAccountUpdatedV1", - "type": "object" - }, "AuditLogEventSshCertificateSignedV1": { "description": "An SSH certificate was signed for a workload.", "properties": { @@ -23873,131 +22234,6 @@ "title": "AuditLogEventTelemetryExportUpdatedV1", "type": "object" }, - "AuditLogEventTrustRuleCreatedV1": { - "description": "A trust rule was created.", - "properties": { - "event_type": { - "const": "TRUST_RULE_CREATED", - "title": "Event Type", - "type": "string" - }, - "trust_rule_id": { - "title": "Trust Rule Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Null when the rule was created without one.", - "title": "Description" - }, - "identity_provider_id": { - "title": "Identity Provider Id", - "type": "string" - }, - "service_account_id": { - "title": "Service Account Id", - "type": "string" - }, - "condition": { - "description": "The CEL expression a token's claims must satisfy.", - "title": "Condition", - "type": "string" - }, - "audience": { - "description": "The `aud` claim a token must carry.", - "title": "Audience", - "type": "string" - }, - "max_access_token_lifetime_seconds": { - "description": "The longest lifetime, in seconds, of an access token the rule issues.", - "title": "Max Access Token Lifetime Seconds", - "type": "integer" - } - }, - "required": [ - "event_type", - "trust_rule_id", - "name", - "identity_provider_id", - "service_account_id", - "condition", - "audience", - "max_access_token_lifetime_seconds" - ], - "title": "AuditLogEventTrustRuleCreatedV1", - "type": "object" - }, - "AuditLogEventTrustRuleDeletedV1": { - "description": "A trust rule was deleted.", - "properties": { - "event_type": { - "const": "TRUST_RULE_DELETED", - "title": "Event Type", - "type": "string" - }, - "trust_rule_id": { - "title": "Trust Rule Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - } - }, - "required": [ - "event_type", - "trust_rule_id", - "name" - ], - "title": "AuditLogEventTrustRuleDeletedV1", - "type": "object" - }, - "AuditLogEventTrustRuleUpdatedV1": { - "description": "A trust rule was updated.", - "properties": { - "event_type": { - "const": "TRUST_RULE_UPDATED", - "title": "Event Type", - "type": "string" - }, - "trust_rule_id": { - "title": "Trust Rule Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/components/schemas/AuditFieldChangeV1" - }, - "description": "The fields the update changed, keyed by field name.", - "title": "Changes", - "type": "object" - } - }, - "required": [ - "event_type", - "trust_rule_id", - "name", - "changes" - ], - "title": "AuditLogEventTrustRuleUpdatedV1", - "type": "object" - }, "AuditLogEventTypeV1": { "description": "Type of action recorded by an audit-log entry.", "enum": [ @@ -24060,17 +22296,7 @@ "VOLUME_UPDATED", "TELEMETRY_EXPORT_CREATED", "TELEMETRY_EXPORT_UPDATED", - "TELEMETRY_EXPORT_DELETED", - "SERVICE_ACCOUNT_CREATED", - "SERVICE_ACCOUNT_UPDATED", - "SERVICE_ACCOUNT_DELETED", - "IDENTITY_PROVIDER_CREATED", - "IDENTITY_PROVIDER_UPDATED", - "IDENTITY_PROVIDER_DELETED", - "TRUST_RULE_CREATED", - "TRUST_RULE_UPDATED", - "TRUST_RULE_DELETED", - "ORGANIZATION_API_KEY_SETTINGS_UPDATED" + "TELEMETRY_EXPORT_DELETED" ], "title": "AuditLogEventTypeV1", "type": "string" @@ -24564,8 +22790,7 @@ "USER_MANAGEMENT", "DIRECTORY_GROUP_MANAGEMENT", "SSH", - "TELEMETRY_EXPORT", - "WORKLOAD_IDENTITY" + "TELEMETRY_EXPORT" ], "title": "AuditLogEventTypeGroupV1", "type": "string" @@ -25142,19 +23367,6 @@ "request_backpressure_settings": { "$ref": "#/components/schemas/RequestBackpressureSettingsV1", "description": "Effective request backpressure settings for the deployment." - }, - "failure_reason": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Why the deployment failed. Set only when the status is DEPLOY_FAILED; null otherwise.", - "title": "Failure Reason" } }, "required": [ @@ -27117,146 +25329,6 @@ "title": "GetStartupSummaryRequestV1", "type": "object" }, - "DeploymentReplicaStatusV1": { - "enum": [ - "STARTING", - "ACTIVE", - "UNHEALTHY", - "TERMINATING", - "TERMINATED", - "UNKNOWN" - ], - "title": "DeploymentReplicaStatusV1", - "type": "string" - }, - "DeploymentReplicaV1": { - "properties": { - "id": { - "description": "Pod-name suffix used for replica lookup and termination, usually five characters.", - "title": "Id", - "type": "string" - }, - "deployment_id": { - "description": "ID of the replica's deployment.", - "title": "Deployment Id", - "type": "string" - }, - "deployment_name": { - "description": "Name of the replica's deployment.", - "title": "Deployment Name", - "type": "string" - }, - "status": { - "$ref": "#/components/schemas/DeploymentReplicaStatusV1", - "description": "Current replica lifecycle status." - }, - "created_at": { - "description": "Replica creation time in ISO 8601 format.", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "terminated_at": { - "anyOf": [ - { - "format": "date-time", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Observed termination completion time in ISO 8601 format, or null if unavailable.", - "title": "Terminated At" - }, - "age_seconds": { - "description": "Age in seconds since creation, frozen at termination.", - "title": "Age Seconds", - "type": "number" - }, - "restart_count": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Model container lifetime restart count, or null if unavailable.", - "title": "Restart Count" - } - }, - "required": [ - "id", - "deployment_id", - "deployment_name", - "status", - "created_at", - "terminated_at", - "age_seconds", - "restart_count" - ], - "title": "DeploymentReplicaV1", - "type": "object" - }, - "DeploymentReplicasV1": { - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/DeploymentReplicaV1" - }, - "title": "Items", - "type": "array" - }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "DeploymentReplicasV1", - "type": "object" - }, - "DeploymentReplicasRequestV1": { - "properties": { - "cursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - }, - "statuses": { - "description": "Replica statuses to include. Repeat the statuses query parameter to filter by multiple statuses. Omit to include all statuses, including terminated replicas.", - "items": { - "$ref": "#/components/schemas/DeploymentReplicaStatusV1" - }, - "title": "Statuses", - "type": "array" - } - }, - "title": "DeploymentReplicasRequestV1", - "type": "object" - }, "TerminateReplicaResponseV1": { "description": "The response to a request to terminate a replica in a deployment.", "properties": { @@ -28349,8 +26421,7 @@ }, "sampling_mode": { "$ref": "#/components/schemas/TrafficRoutingRuleShadowSamplingModeV1", - "default": "USER_SESSION", - "description": "How requests are picked for shadowing. Defaults to USER_SESSION." + "description": "How requests are picked for shadowing" }, "propagate_client_cancellation": { "description": "Whether a shadow request is cancelled when the original client disconnects", @@ -28363,6 +26434,7 @@ "targets", "percent_traffic", "expires_at", + "sampling_mode", "propagate_client_cancellation" ], "title": "TrafficRoutingRuleUpsertV1", @@ -29821,58 +27893,8 @@ "title": "CheckpointSyncStatus", "type": "string" }, - "TrainingBDNConfigResponseV1": { - "properties": { - "mounts": { - "items": { - "$ref": "#/components/schemas/TrainingBDNMountResponseV1" - }, - "title": "Mounts", - "type": "array" - } - }, - "title": "TrainingBDNConfigResponseV1", - "type": "object" - }, - "TrainingBDNMountResponseV1": { - "properties": { - "source": { - "title": "Source", - "type": "string" - }, - "path": { - "title": "Path", - "type": "string" - }, - "include": { - "description": "Relative glob patterns selecting files to mount; empty includes all files.", - "items": { - "type": "string" - }, - "title": "Include", - "type": "array" - }, - "exclude": { - "description": "Relative glob patterns excluding files from the mount; exclusions win.", - "items": { - "type": "string" - }, - "title": "Exclude", - "type": "array" - } - }, - "required": [ - "source", - "path" - ], - "title": "TrainingBDNMountResponseV1", - "type": "object" - }, "TrainingJobV1": { "properties": { - "bdn": { - "$ref": "#/components/schemas/TrainingBDNConfigResponseV1" - }, "id": { "description": "Unique identifier of the training job.", "title": "Id", @@ -30854,9 +28876,6 @@ "CreateTrainingJobV1": { "description": "Configuration for a training job.", "properties": { - "bdn": { - "$ref": "#/components/schemas/TrainingBDNConfigV1" - }, "image": { "$ref": "#/components/schemas/CreateTrainingJobImageV1", "examples": [ @@ -31333,58 +29352,6 @@ "title": "SecretReferenceV1", "type": "object" }, - "TrainingBDNConfigV1": { - "additionalProperties": false, - "description": "Read-only BDN mounts with the same reference semantics as inference.", - "properties": { - "mounts": { - "items": { - "$ref": "#/components/schemas/TrainingBDNMountV1" - }, - "maxItems": 32, - "title": "Mounts", - "type": "array" - } - }, - "title": "TrainingBDNConfigV1", - "type": "object" - }, - "TrainingBDNMountV1": { - "additionalProperties": false, - "description": "A requested read-only BDN dataset mount.", - "properties": { - "source": { - "title": "Source", - "type": "string" - }, - "path": { - "title": "Path", - "type": "string" - }, - "include": { - "description": "Relative glob patterns selecting files to mount; empty includes all files.", - "items": { - "type": "string" - }, - "title": "Include", - "type": "array" - }, - "exclude": { - "description": "Relative glob patterns excluding files from the mount; exclusions win.", - "items": { - "type": "string" - }, - "title": "Exclude", - "type": "array" - } - }, - "required": [ - "source", - "path" - ], - "title": "TrainingBDNMountV1", - "type": "object" - }, "TrainingWeightAuthV1": { "description": "Authentication configuration for a training weight source.", "properties": { @@ -31883,7 +29850,7 @@ }, "type": "array" }, - "description": "A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", "title": "Gpu Memory Usage Bytes", "type": "object" }, @@ -31894,56 +29861,12 @@ }, "type": "array" }, - "description": "A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", "title": "Gpu Utilization", "type": "object" }, - "gpu_temperature_celsius": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Temperature Celsius", - "type": "object" - }, - "gpu_power_usage_watts": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Power Usage Watts", - "type": "object" - }, - "gpu_tensor_core_utilization": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Tensor Core Utilization", - "type": "object" - }, - "gpu_memory_bandwidth_utilization": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Memory Bandwidth Utilization", - "type": "object" - }, "cpu_usage": { - "description": "The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -31951,7 +29874,7 @@ "type": "array" }, "cpu_memory_usage_bytes": { - "description": "The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -31960,16 +29883,12 @@ }, "ephemeral_storage": { "$ref": "#/components/schemas/StorageMetricsV1", - "description": "The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." + "description": "The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." } }, "required": [ "gpu_memory_usage_bytes", "gpu_utilization", - "gpu_temperature_celsius", - "gpu_power_usage_watts", - "gpu_tensor_core_utilization", - "gpu_memory_bandwidth_utilization", "cpu_usage", "cpu_memory_usage_bytes", "ephemeral_storage" @@ -32007,7 +29926,7 @@ }, "type": "array" }, - "description": "A map of GPU rank to memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "A map of GPU rank to memory usage for the training job. For multinode jobs, this is the memory usage of the leader unless specified otherwise.", "title": "Gpu Memory Usage Bytes", "type": "object" }, @@ -32018,56 +29937,12 @@ }, "type": "array" }, - "description": "A map of GPU rank to the share of time the GPU's streaming multiprocessors have work assigned, from 0 to 1. This counts any GPU work, not only tensor core math; see gpu_tensor_core_utilization for that. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "A map of GPU rank to fractional GPU utilization. For multinode jobs, this is the GPU utilization of the leader unless specified otherwise.", "title": "Gpu Utilization", "type": "object" }, - "gpu_temperature_celsius": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to GPU temperature in degrees Celsius. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Temperature Celsius", - "type": "object" - }, - "gpu_power_usage_watts": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to GPU power draw in watts. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Power Usage Watts", - "type": "object" - }, - "gpu_tensor_core_utilization": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to the share of time the GPU tensor cores are active, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Tensor Core Utilization", - "type": "object" - }, - "gpu_memory_bandwidth_utilization": { - "additionalProperties": { - "items": { - "$ref": "#/components/schemas/TrainingJobMetricV1" - }, - "type": "array" - }, - "description": "A map of GPU rank to the share of cycles GPU memory is actively reading or writing, from 0 to 1. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", - "title": "Gpu Memory Bandwidth Utilization", - "type": "object" - }, "cpu_usage": { - "description": "The CPU usage measured in cores. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "The CPU usage measured in cores. For multinode jobs, this is the CPU usage of the leader unless specified otherwise.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -32075,7 +29950,7 @@ "type": "array" }, "cpu_memory_usage_bytes": { - "description": "The CPU memory usage for the training job. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node.", + "description": "The CPU memory usage for the training job. For multinode jobs, this is the CPU memory usage of the leader unless specified otherwise.", "items": { "$ref": "#/components/schemas/TrainingJobMetricV1" }, @@ -32084,7 +29959,7 @@ }, "ephemeral_storage": { "$ref": "#/components/schemas/StorageMetricsV1", - "description": "The storage usage for the ephemeral storage. At the top level of a multinode job this is the leader node; under per_node_metrics it is that node." + "description": "The storage usage for the ephemeral storage. For multinode jobs, this is the ephemeral storage usage of the leader unless specified otherwise." }, "training_job": { "$ref": "#/components/schemas/TrainingJobV1", @@ -32113,10 +29988,6 @@ "required": [ "gpu_memory_usage_bytes", "gpu_utilization", - "gpu_temperature_celsius", - "gpu_power_usage_watts", - "gpu_tensor_core_utilization", - "gpu_memory_bandwidth_utilization", "cpu_usage", "cpu_memory_usage_bytes", "ephemeral_storage", @@ -33637,27 +31508,9 @@ } ], "default": null, - "description": "Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + "description": "Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", "title": "Base Checkpoint" }, - "base_checkpoint_auth": { - "anyOf": [ - { - "$ref": "#/components/schemas/TrainingWeightAuthV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", - "examples": [ - { - "auth_method": "CUSTOM_SECRET", - "auth_secret_name": "hf_read_my_checkpoint" - } - ] - }, "sampler_num_replicas": { "anyOf": [ { @@ -33718,198 +31571,6 @@ "title": "DeactivateLoopsRunResponseV1", "type": "object" }, - "LoopsCheckpointV1": { - "description": "A checkpoint saved by a Loops run.", - "properties": { - "checkpoint_id": { - "description": "The ID of the checkpoint.", - "title": "Checkpoint Id", - "type": "string" - }, - "created_at": { - "description": "The timestamp of the checkpoint in ISO 8601 format.", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "checkpoint_type": { - "description": "The type of checkpoint.", - "title": "Checkpoint Type", - "type": "string" - }, - "base_model": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The base model of the checkpoint.", - "title": "Base Model" - }, - "lora_adapter_config": { - "anyOf": [ - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "description": "The adapter config of the checkpoint.", - "title": "Lora Adapter Config" - }, - "size_bytes": { - "description": "The size of the checkpoint in bytes.", - "title": "Size Bytes", - "type": "integer" - }, - "sync_status": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Sync state of the checkpoint: SYNCING or COMPLETE.", - "title": "Sync Status" - }, - "id": { - "description": "The checkpoint ID.", - "title": "Id", - "type": "string" - }, - "lora_config": { - "anyOf": [ - { - "$ref": "#/components/schemas/LoopsLoRAConfigV1" - }, - { - "type": "null" - } - ], - "description": "The immutable LoRA config used to save this checkpoint. Null means the checkpoint is unsupported and cannot be loaded." - }, - "run_id": { - "description": "The ID of the run that produced the checkpoint.", - "title": "Run Id", - "type": "string" - }, - "target": { - "$ref": "#/components/schemas/TrainerCheckpointTarget", - "description": "Whether this checkpoint is loadable by the sampler or by the run." - }, - "expires_at": { - "anyOf": [ - { - "format": "date-time", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "When the checkpoint expires and is deleted, set from the TTL it was saved with. Null means it's kept until you delete it. A checkpoint that's still in use when it expires, for example deployed, is deleted once it's released.", - "title": "Expires At" - } - }, - "required": [ - "checkpoint_id", - "created_at", - "checkpoint_type", - "base_model", - "lora_adapter_config", - "size_bytes", - "id", - "lora_config", - "run_id", - "target", - "expires_at" - ], - "title": "LoopsCheckpointV1", - "type": "object" - }, - "LoopsLoRAConfigV1": { - "description": "A published LoRA config: which modules the adapter targets and how experts are laid out.", - "properties": { - "config_version": { - "description": "The config version, like v1.", - "title": "Config Version", - "type": "string" - }, - "targets": { - "description": "The module names the LoRA adapter targets.", - "items": { - "type": "string" - }, - "title": "Targets", - "type": "array" - }, - "expert_layout": { - "anyOf": [ - { - "enum": [ - "per_expert", - "shared_outer", - "shared_adapter" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "How routed-expert LoRA weights are laid out. Null when no experts are targeted.", - "title": "Expert Layout" - } - }, - "required": [ - "config_version", - "targets" - ], - "title": "LoopsLoRAConfigV1", - "type": "object" - }, - "TrainerCheckpointTarget": { - "description": "Whether a TrainerServerCheckpoint is loadable by the sampler or the trainer.\n\nSAMPLER checkpoints are consumed by the sampling server for inference;\nTRAINER checkpoints capture full trainer state for resuming training.\nMirrored in the bt:// URI as\n``bt://loops:/(sampler_weights|weights)/``.", - "enum": [ - "sampler", - "trainer" - ], - "title": "TrainerCheckpointTarget", - "type": "string" - }, - "DeleteLoopsRunResponseV1": { - "description": "A Loops run whose delete was accepted.", - "properties": { - "id": { - "description": "The deleted Loops run ID.", - "title": "Id", - "type": "string" - }, - "kept_checkpoints": { - "description": "The run's checkpoints that were not deleted because something still uses them, such as a deployment. They stay usable until that stops.", - "items": { - "$ref": "#/components/schemas/LoopsCheckpointV1" - }, - "title": "Kept Checkpoints", - "type": "array" - } - }, - "required": [ - "id", - "kept_checkpoints" - ], - "title": "DeleteLoopsRunResponseV1", - "type": "object" - }, "GetLoopsRunResponseV1": { "description": "Response for ``GET /v1/loops/runs/``.", "properties": { @@ -34069,27 +31730,9 @@ } ], "default": null, - "description": "Optional checkpoint to start training from instead of the base model's weights: a Hugging Face repo (hf:///[@]), an object store path (s3://, gs://, r2://, cw://, or azure://), or a full Baseten Training checkpoint in the run's team (bt://@/, with the checkpoint named). It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include tokenizer files: the run's sampler loads the tokenizer and chat template from the checkpoint. A Hugging Face revision is pinned to a commit when the run is created, and its files are checked then. Any other source is read again by each sampler and resumed run, so do not change it while the run is in use. Checkpoints from a run on a source outside Hugging Face cannot be deployed yet. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", + "description": "Optional Hugging Face checkpoint to start training from instead of the base model's weights. Form: hf:///[@]. It must be a complete, merged checkpoint in safetensors format with the same architecture as base_model, which still selects the hardware and training configuration. It must include its tokenizer files: the run's sampler and the SDK load the tokenizer and chat template from the checkpoint. A private or gated repository needs a Hugging Face token in the team secret hf_access_token. The revision is pinned to a commit when the run is created. Cannot be combined with path, reuse_from_run_id, or reuse_from_session_id.", "title": "Base Checkpoint" }, - "base_checkpoint_auth": { - "anyOf": [ - { - "$ref": "#/components/schemas/TrainingWeightAuthV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Optional credentials that read base_checkpoint. Only CUSTOM_SECRET is supported: set auth_secret_name to the team secret that holds a Hugging Face token for a Hugging Face repo, or the credentials for an object store. A Baseten Training checkpoint takes no auth. The run, its samplers, resumed runs, and checkpoint deployments all use this secret. When omitted, a Hugging Face repo is read with the team secret hf_access_token if it exists. Requires base_checkpoint.", - "examples": [ - { - "auth_method": "CUSTOM_SECRET", - "auth_secret_name": "hf_read_my_checkpoint" - } - ] - }, "scope": { "$ref": "#/components/schemas/LoopsPlacementScopeV1", "default": "default", @@ -34325,6 +31968,160 @@ "title": "GetLoopsSamplerResponseV1", "type": "object" }, + "LoopsCheckpointV1": { + "description": "A checkpoint saved by a Loops run.", + "properties": { + "checkpoint_id": { + "description": "The ID of the checkpoint.", + "title": "Checkpoint Id", + "type": "string" + }, + "created_at": { + "description": "The timestamp of the checkpoint in ISO 8601 format.", + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "checkpoint_type": { + "description": "The type of checkpoint.", + "title": "Checkpoint Type", + "type": "string" + }, + "base_model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The base model of the checkpoint.", + "title": "Base Model" + }, + "lora_adapter_config": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "description": "The adapter config of the checkpoint.", + "title": "Lora Adapter Config" + }, + "size_bytes": { + "description": "The size of the checkpoint in bytes.", + "title": "Size Bytes", + "type": "integer" + }, + "sync_status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sync state of the checkpoint: SYNCING or COMPLETE.", + "title": "Sync Status" + }, + "id": { + "description": "The checkpoint ID.", + "title": "Id", + "type": "string" + }, + "lora_config": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoopsLoRAConfigV1" + }, + { + "type": "null" + } + ], + "description": "The immutable LoRA config used to save this checkpoint. Null means the checkpoint is unsupported and cannot be loaded." + }, + "run_id": { + "description": "The ID of the run that produced the checkpoint.", + "title": "Run Id", + "type": "string" + }, + "target": { + "$ref": "#/components/schemas/TrainerCheckpointTarget", + "description": "Whether this checkpoint is loadable by the sampler or by the run." + } + }, + "required": [ + "checkpoint_id", + "created_at", + "checkpoint_type", + "base_model", + "lora_adapter_config", + "size_bytes", + "id", + "lora_config", + "run_id", + "target" + ], + "title": "LoopsCheckpointV1", + "type": "object" + }, + "LoopsLoRAConfigV1": { + "description": "A published LoRA config: which modules the adapter targets and how experts are laid out.", + "properties": { + "config_version": { + "description": "The config version, like v1.", + "title": "Config Version", + "type": "string" + }, + "targets": { + "description": "The module names the LoRA adapter targets.", + "items": { + "type": "string" + }, + "title": "Targets", + "type": "array" + }, + "expert_layout": { + "anyOf": [ + { + "enum": [ + "per_expert", + "shared_outer", + "shared_adapter" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "How routed-expert LoRA weights are laid out. Null when no experts are targeted.", + "title": "Expert Layout" + } + }, + "required": [ + "config_version", + "targets" + ], + "title": "LoopsLoRAConfigV1", + "type": "object" + }, + "TrainerCheckpointTarget": { + "description": "Whether a TrainerServerCheckpoint is loadable by the sampler or the trainer.\n\nSAMPLER checkpoints are consumed by the sampling server for inference;\nTRAINER checkpoints capture full trainer state for resuming training.\nMirrored in the bt:// URI as\n``bt://loops:/(sampler_weights|weights)/``.", + "enum": [ + "sampler", + "trainer" + ], + "title": "TrainerCheckpointTarget", + "type": "string" + }, "ListLoopsCheckpointsResponseV1": { "description": "Checkpoints matching the query filter.", "properties": { @@ -34496,44 +32293,6 @@ "title": "DeployLoopsCheckpointResponseV1", "type": "object" }, - "LoopsCheckpointTombstoneV1": { - "description": "A Loops checkpoint whose delete was accepted.", - "properties": { - "id": { - "description": "The deleted checkpoint ID.", - "title": "Id", - "type": "string" - }, - "run_id": { - "description": "The ID of the run that produced the checkpoint.", - "title": "Run Id", - "type": "string" - }, - "checkpoint_id": { - "description": "The name the checkpoint was saved under.", - "title": "Checkpoint Id", - "type": "string" - }, - "target": { - "$ref": "#/components/schemas/TrainerCheckpointTarget", - "description": "Whether the checkpoint was loadable by the sampler or by the run." - }, - "path": { - "description": "The checkpoint's bt:// path.", - "title": "Path", - "type": "string" - } - }, - "required": [ - "id", - "run_id", - "checkpoint_id", - "target", - "path" - ], - "title": "LoopsCheckpointTombstoneV1", - "type": "object" - }, "LoopsCheckpointFilesResponseV1": { "description": "Response with presigned URLs for files under a Loops checkpoint.", "properties": { @@ -34661,29 +32420,6 @@ "title": "LoopsCheckpointSourceResponseV1", "type": "object" }, - "SetLoopsCheckpointTtlRequestV1": { - "properties": { - "ttl_seconds": { - "anyOf": [ - { - "maximum": 315360000, - "minimum": 3600, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Seconds from now until the checkpoint expires and is deleted, from 3600 (1 hour) to 315360000 (10 years). Null removes the TTL, so the checkpoint is kept until you delete it.", - "title": "Ttl Seconds" - } - }, - "required": [ - "ttl_seconds" - ], - "title": "SetLoopsCheckpointTtlRequestV1", - "type": "object" - }, "LoopsDeploymentStatusV1": { "description": "Latest deployment status for a Loops deployment.", "properties": { @@ -35382,12 +33118,12 @@ "type": "string" }, "baseline": { - "description": "Configured minimum GPU allocation for the team. Not enforced. 0 if not configured.", + "description": "Baseline GPU allocation for the team. 0 if not configured.", "title": "Baseline", "type": "integer" }, "limit": { - "description": "The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", + "description": "Maximum concurrent GPUs of this type for this team", "title": "Limit", "type": "integer" }, @@ -35398,7 +33134,7 @@ }, "dedicated_usage_count": { "default": 0, - "description": "Portion of usage_count from on-demand (non-spot) jobs.", + "description": "Portion of usage_count from standard (non-spot) jobs.", "title": "Dedicated Usage Count", "type": "integer" }, @@ -35429,33 +33165,15 @@ "type": "string" }, "baseline": { - "description": "Configured minimum GPU allocation (`min_gpus`). 0 if not configured. Use `on_demand_quota` for the quota applied to on-demand jobs.", + "description": "Baseline GPU allocation; jobs below this threshold are expected to run immediately. 0 if not configured.", "title": "Baseline", "type": "integer" }, "limit": { - "description": "Configured maximum GPU allocation (`max_gpus`). Use `on_demand_quota` and `spot_quota` for the quotas applied to jobs.", + "description": "Maximum concurrent GPUs of this type for this org", "title": "Limit", "type": "integer" }, - "on_demand_quota": { - "description": "GPU quota for this type for on-demand (non-spot) jobs: the most GPUs they can use at once.", - "title": "On Demand Quota", - "type": "integer" - }, - "spot_quota": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "GPU quota for this type for spot jobs. Spot shares this quota with on-demand jobs: spot can use up to the quota minus on-demand GPUs in use. Null if spot is not enabled for the organization.", - "title": "Spot Quota" - }, "usage_count": { "description": "GPUs currently in use by active training jobs", "title": "Usage Count", @@ -35463,13 +33181,13 @@ }, "dedicated_usage_count": { "default": 0, - "description": "Portion of usage_count from on-demand (non-spot) jobs.", + "description": "Portion of usage_count from standard (non-spot) jobs, which run against the baseline.", "title": "Dedicated Usage Count", "type": "integer" }, "spot_usage_count": { "default": 0, - "description": "Portion of usage_count from spot jobs.", + "description": "Portion of usage_count from spot jobs, which burst into the peak and may push usage above the limit.", "title": "Spot Usage Count", "type": "integer" } @@ -35478,7 +33196,6 @@ "gpu_type", "baseline", "limit", - "on_demand_quota", "usage_count" ], "title": "TrainingGpuCapacityItemV1", @@ -35488,7 +33205,7 @@ "description": "Response for the training GPU capacity endpoint.", "properties": { "gpu_capacities": { - "description": "Organization GPU quotas and current usage per GPU type", + "description": "Org-level GPU capacity limits and current usage per GPU type", "items": { "$ref": "#/components/schemas/TrainingGpuCapacityItemV1" }, @@ -35496,18 +33213,12 @@ "type": "array" }, "team_gpu_capacities": { - "description": "Per-team GPU quotas and current usage per GPU type", + "description": "Per-team GPU capacity limits and current usage per GPU type", "items": { "$ref": "#/components/schemas/TeamTrainingGpuCapacityItemV1" }, "title": "Team Gpu Capacities", "type": "array" - }, - "spot_enabled": { - "default": false, - "description": "Whether the organization can submit spot training jobs.", - "title": "Spot Enabled", - "type": "boolean" } }, "required": [ @@ -35517,7 +33228,7 @@ "type": "object" }, "PatchTeamTrainingGpuCapacityRequestV1": { - "description": "A request to set the GPU quota for a (team, gpu_type) pair.\n\nCreates the quota if one doesn't already exist for this team and GPU type,\notherwise updates it in place.", + "description": "A request to set the GPU capacity ceiling for a (team, gpu_type) pair.\n\nCreates the limit if one doesn't already exist for this team and GPU type,\notherwise updates it in place.", "properties": { "team_id": { "description": "Team identifier", @@ -35530,7 +33241,7 @@ "type": "string" }, "max_gpus": { - "description": "The team's GPU quota for this type. It counts the team's on-demand jobs, plus its spot jobs when the organization has no separate on-demand quota. On-demand jobs can run past it by borrowing from the organization's shared pool, when one exists.", + "description": "Max concurrent GPUs of this type the team may use", "examples": [ 8, 16, @@ -35549,11 +33260,11 @@ "type": "object" }, "PatchTeamTrainingGpuCapacityResponseV1": { - "description": "Response for setting a team's GPU quota.", + "description": "Response for setting a team's GPU capacity ceiling.", "properties": { "team_gpu_capacity": { "$ref": "#/components/schemas/TeamTrainingGpuCapacityItemV1", - "description": "The updated per-team GPU quota" + "description": "The updated per-team GPU capacity limit" } }, "required": [ @@ -37036,14 +34747,6 @@ }, "title": "Metrics", "type": "array" - }, - "team_ids": { - "description": "Return only metrics for these teams, repeated once per team. Defaults to all teams you can manage. Any unauthorized team causes a 403.", - "items": { - "type": "string" - }, - "title": "Team Ids", - "type": "array" } }, "title": "GetModelAPIMetricsRequestV1", @@ -39182,7 +36885,7 @@ "type": "string" } ], - "description": "Usage charges in dollars before applying credits", + "description": "Subtotal cost in dollars after applying credits used", "title": "Subtotal" }, "credits_used": { @@ -39472,32 +37175,6 @@ "description": "Subtotal cost in dollars for this model", "title": "Subtotal" }, - "team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Team ID for multi-team organizations; otherwise null", - "title": "Team Id" - }, - "team_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Team name, including historical teams; null if unavailable", - "title": "Team Name" - }, "input_tokens": { "description": "Total input tokens for this model", "title": "Input Tokens", @@ -39544,7 +37221,7 @@ "type": "string" } ], - "description": "Usage charges in dollars before applying credits", + "description": "Subtotal cost in dollars after applying credits used", "title": "Subtotal" }, "credits_used": { @@ -39570,11 +37247,11 @@ "type": "string" } ], - "description": "Usage charges in dollars after applying credits, floored at zero", + "description": "Total cost in dollars", "title": "Total" }, "breakdown": { - "description": "Per-model usage breakdown, split by team for multi-team organizations", + "description": "Per-model usage breakdown", "items": { "$ref": "#/components/schemas/ModelApiItemV1" }, @@ -39655,7 +37332,7 @@ "type": "string" } ], - "description": "Usage charges in dollars before applying credits", + "description": "Subtotal cost in dollars after applying credits used", "title": "Subtotal" }, "credits_used": { @@ -39705,1738 +37382,177 @@ "minutes" ], "title": "TrainingUsageV1", - "type": "object" - }, - "UsageSummaryV1": { - "description": "Billing usage summary for the requested date range.", - "properties": { - "dedicated_usage": { - "anyOf": [ - { - "$ref": "#/components/schemas/DedicatedUsageV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Dedicated model serving usage" - }, - "training_usage": { - "anyOf": [ - { - "$ref": "#/components/schemas/TrainingUsageV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Training usage" - }, - "model_apis_usage": { - "anyOf": [ - { - "$ref": "#/components/schemas/ModelApisUsageV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Model APIs usage" - }, - "loops_usage": { - "anyOf": [ - { - "$ref": "#/components/schemas/LoopsUsageV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Serverless Loops usage, billed per token. Loops usage on dedicated trainers and samplers is billed by the minute and is part of training usage." - } - }, - "title": "UsageSummaryV1", - "type": "object" - }, - "UsageSummaryRequestV1": { - "properties": { - "start_date": { - "description": "Inclusive start date (ISO 8601, normalized to midnight UTC). Earliest queryable: 2026-01-01.", - "format": "date-time", - "title": "Start Date", - "type": "string" - }, - "end_date": { - "description": "Exclusive end date (ISO 8601, normalized to midnight UTC). Date range cannot exceed 31 days.", - "format": "date-time", - "title": "End Date", - "type": "string" - } - }, - "required": [ - "start_date", - "end_date" - ], - "title": "UsageSummaryRequestV1", - "type": "object" - }, - "ToolCallUsageBucketV1": { - "description": "Server-side tool call usage for one day, provider, charge unit, and model.", - "properties": { - "date": { - "description": "UTC day the usage was recorded on.", - "format": "date", - "title": "Date", - "type": "string" - }, - "provider": { - "description": "Tool provider, such as exa or parallel.", - "title": "Provider", - "type": "string" - }, - "sku": { - "description": "Charge unit, as `/`. The unit is what the provider reported, or the tool name when it reported none. Its meaning varies by provider.", - "title": "Sku", - "type": "string" - }, - "model": { - "description": "Model that made the tool calls.", - "title": "Model", - "type": "string" - }, - "calls": { - "description": "Number of tool calls.", - "title": "Calls", - "type": "integer" - }, - "quantity": { - "description": "Billable quantity in the provider's sku unit, summed over the calls.", - "title": "Quantity", - "type": "number" - }, - "team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Team attributed to the usage. Null when not grouping by team or when historical team attribution is unavailable.", - "title": "Team Id" - } - }, - "required": [ - "date", - "provider", - "sku", - "model", - "calls", - "quantity" - ], - "title": "ToolCallUsageBucketV1", - "type": "object" - }, - "ToolCallUsageResponseV1": { - "description": "Daily server-side tool call usage, ordered by day, provider, sku, and model.", - "properties": { - "items": { - "items": { - "$ref": "#/components/schemas/ToolCallUsageBucketV1" - }, - "title": "Items", - "type": "array" - } - }, - "title": "ToolCallUsageResponseV1", - "type": "object" - }, - "ToolCallUsageDimensionV1": { - "enum": [ - "TEAM" - ], - "title": "ToolCallUsageDimensionV1", - "type": "string" - }, - "ToolCallUsageRequestV1": { - "properties": { - "start_date": { - "description": "Inclusive UTC calendar day at the start of the query range.", - "format": "date", - "title": "Start Date", - "type": "string" - }, - "end_date": { - "anyOf": [ - { - "format": "date", - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included. The date range cannot exceed 90 days.", - "title": "End Date" - }, - "team_ids": { - "description": "Return only usage for these teams, repeated once per team. Defaults to all teams you can manage. An unauthorized team ID causes a 403 response.", - "items": { - "type": "string" - }, - "title": "Team Ids", - "type": "array" - }, - "group_by": { - "description": "Pass TEAM to split daily rows by team. Defaults to aggregating across teams.", - "items": { - "$ref": "#/components/schemas/ToolCallUsageDimensionV1" - }, - "title": "Group By", - "type": "array" - } - }, - "required": [ - "start_date" - ], - "title": "ToolCallUsageRequestV1", - "type": "object" - }, - "UserInfoV1": { - "description": "A Baseten user.", - "properties": { - "user_id": { - "description": "Unique identifier for the user", - "title": "User Id", - "type": "string" - }, - "email": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Email address of the user", - "title": "Email" - }, - "name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Display name of the user", - "title": "Name" - }, - "workspace_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Name of the user's workspace", - "title": "Workspace Name" - } - }, - "required": [ - "user_id" - ], - "title": "UserInfoV1", - "type": "object" - }, - "UsersResponseV1": { - "description": "A page of users in the caller's workspace.", - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/UserInfoV1" - }, - "title": "Items", - "type": "array" - }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "UsersResponseV1", - "type": "object" - }, - "UsersRequestV1": { - "description": "Request parameters for listing users.", - "properties": { - "cursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - }, - "email": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "When set, returns only users with this exact email, if any.", - "title": "Email" - } - }, - "title": "UsersRequestV1", - "type": "object" - }, - "AwsAssumeRoleV1": { - "description": "AWS AssumeRole trust-policy inputs for the organization.", - "properties": { - "baseten_role_arn": { - "description": "Baseten role ARN to allow in an IAM role's trust policy", - "title": "Baseten Role Arn", - "type": "string" - }, - "external_id": { - "description": "sts:ExternalId Baseten presents when assuming the role", - "title": "External Id", - "type": "string" - } - }, - "required": [ - "baseten_role_arn", - "external_id" - ], - "title": "AwsAssumeRoleV1", - "type": "object" - }, - "OrganizationInfoV1": { - "description": "The caller's organization.", - "properties": { - "org_id": { - "description": "Unique identifier for the organization", - "title": "Org Id", - "type": "string" - }, - "name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Display name of the organization", - "title": "Name" - }, - "created_at": { - "description": "Time the organization was created in ISO 8601 format", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "aws_assume_role": { - "anyOf": [ - { - "$ref": "#/components/schemas/AwsAssumeRoleV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" - }, - "allow_personal_api_keys": { - "description": "Whether members can create new personal API keys. Existing keys keep working.", - "title": "Allow Personal Api Keys", - "type": "boolean" - }, - "allow_service_account_api_keys": { - "description": "Whether new team and organization API keys can be created. Existing keys keep working.", - "title": "Allow Service Account Api Keys", - "type": "boolean" - } - }, - "required": [ - "org_id", - "created_at", - "allow_personal_api_keys", - "allow_service_account_api_keys" - ], - "title": "OrganizationInfoV1", - "type": "object" - }, - "UpdateOrganizationRequestV1": { - "additionalProperties": false, - "description": "Partial update of the caller's organization settings. Omitted fields are unchanged.", - "properties": { - "allow_personal_api_keys": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Whether members can create new personal API keys. Null is not accepted.", - "title": "Allow Personal Api Keys" - }, - "allow_service_account_api_keys": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Whether new team and organization API keys can be created. Null is not accepted.", - "title": "Allow Service Account Api Keys" - } - }, - "title": "UpdateOrganizationRequestV1", - "type": "object" - }, - "ServiceAccountPresetPermissionsV1": { - "description": "A service account's access: one of the access types API keys have.\n\nTemporary: mirrors API key access until fine-grained access control is available, and may be removed.", - "properties": { - "type": { - "$ref": "#/components/schemas/ServiceAccountPresetTypeV1", - "description": "What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", - "examples": [ - "WORKSPACE_MANAGE_ALL" - ] - }, - "model_ids": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", - "examples": [ - [ - "abcd1234" - ] - ], - "title": "Model Ids" - }, - "environment_names": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", - "examples": [ - [ - "production" - ] - ], - "title": "Environment Names" - }, - "model_api_slugs": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", - "examples": [ - [ - "my-model-api" - ] - ], - "title": "Model Api Slugs" - } - }, - "required": [ - "type" - ], - "title": "ServiceAccountPresetPermissionsV1", - "type": "object" - }, - "ServiceAccountPresetTypeV1": { - "description": "What a service account may do: the workspace API key categories, plus Model APIs.\n\nTemporary: mirrors API key access until fine-grained access control is available, and may be removed.", - "enum": [ - "WORKSPACE_MANAGE_ALL", - "WORKSPACE_INVOKE", - "WORKSPACE_EXPORT_METRICS", - "WORKSPACE_MANAGE_API_KEYS", - "WORKSPACE_INVOKE_MODEL_APIS" - ], - "title": "ServiceAccountPresetTypeV1", - "type": "string" - }, - "ServiceAccountV1": { - "description": "A named service account that workload identity federation tokens act as.", - "properties": { - "id": { - "description": "Service account ID", - "title": "Id", - "type": "string" - }, - "name": { - "description": "Name, unique in the organization", - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Description", - "title": "Description" - }, - "team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The team that owns the account. Null for an organization account.", - "title": "Team Id" - }, - "preset_permissions": { - "$ref": "#/components/schemas/ServiceAccountPresetPermissionsV1", - "description": "What the service account may do. Temporary; may be removed once fine-grained access control is available." - }, - "disabled": { - "description": "Whether the account is disabled. A disabled account can't be used.", - "title": "Disabled", - "type": "boolean" - }, - "last_used_at": { - "anyOf": [ - { - "format": "date-time", - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Last time a request authenticated as this account, to within an hour. Null until the first.", - "title": "Last Used At" - }, - "created_at": { - "description": "Time the account was created", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "updated_at": { - "description": "Time the account was last updated", - "format": "date-time", - "title": "Updated At", - "type": "string" - } - }, - "required": [ - "id", - "name", - "preset_permissions", - "disabled", - "created_at", - "updated_at" - ], - "title": "ServiceAccountV1", - "type": "object" - }, - "ServiceAccountsV1": { - "description": "A page of service accounts.", - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/ServiceAccountV1" - }, - "title": "Items", - "type": "array" - }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "ServiceAccountsV1", - "type": "object" - }, - "ServiceAccountsRequestV1": { - "properties": { - "cursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - }, - "name": { - "anyOf": [ - { - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Only the account with this name, ignoring case", - "title": "Name" - }, - "team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Only this team's accounts", - "title": "Team Id" - }, - "disabled": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Only disabled or enabled accounts", - "title": "Disabled" - } - }, - "title": "ServiceAccountsRequestV1", - "type": "object" - }, - "ServiceAccountPresetPermissionsRequestV1": { - "additionalProperties": false, - "description": "A service account's access, as sent. Omit a list for no restriction; never send it empty.", - "properties": { - "type": { - "$ref": "#/components/schemas/ServiceAccountPresetTypeV1", - "description": "What the service account may do. WORKSPACE_MANAGE_API_KEYS is for organization-level accounts only; every other type needs a team.", - "examples": [ - "WORKSPACE_MANAGE_ALL" - ] - }, - "model_ids": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "WORKSPACE_INVOKE and WORKSPACE_EXPORT_METRICS only. Models the account covers. Omit for every model in the team, including models added later.", - "examples": [ - [ - "abcd1234" - ] - ], - "title": "Model Ids" - }, - "environment_names": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "WORKSPACE_INVOKE: environments the account may call; omit for all. With model_ids, each model must have each environment. WORKSPACE_MANAGE_ALL: restricted environments the account may also manage.", - "examples": [ - [ - "production" - ] - ], - "title": "Environment Names" - }, - "model_api_slugs": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "WORKSPACE_INVOKE_MODEL_APIS only. Model APIs the account may call; omit for all.", - "examples": [ - [ - "my-model-api" - ] - ], - "title": "Model Api Slugs" - } - }, - "required": [ - "type" - ], - "title": "ServiceAccountPresetPermissionsRequestV1", - "type": "object" - }, - "CreateServiceAccountRequestV1": { - "additionalProperties": false, - "description": "Request to create a service account.", - "properties": { - "name": { - "description": "Name, unique in the organization. Can be changed later.", - "examples": [ - "ci-deployer" - ], - "maxLength": 255, - "minLength": 1, - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "maxLength": 1024, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Optional description, up to 1,024 characters", - "title": "Description" - }, - "team_id": { - "anyOf": [ - { - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The team that owns the account. Omit for an organization account. Can't be changed.", - "title": "Team Id" - }, - "preset_permissions": { - "$ref": "#/components/schemas/ServiceAccountPresetPermissionsRequestV1", - "description": "What the service account may do. Can be changed later. Temporary; may be removed once fine-grained access control is available." - } - }, - "required": [ - "name", - "preset_permissions" - ], - "title": "CreateServiceAccountRequestV1", - "type": "object" - }, - "DeletedServiceAccountV1": { - "properties": { - "id": { - "description": "ID of the deleted service account", - "title": "Id", - "type": "string" - }, - "deleted": { - "description": "Always true", - "title": "Deleted", - "type": "boolean" - } - }, - "required": [ - "id", - "deleted" - ], - "title": "DeletedServiceAccountV1", - "type": "object" - }, - "UpdateServiceAccountRequestV1": { - "additionalProperties": false, - "description": "Request to update a service account. Only the fields sent change.", - "properties": { - "name": { - "anyOf": [ - { - "maxLength": 255, - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Name, unique in the organization", - "title": "Name" - }, - "description": { - "anyOf": [ - { - "maxLength": 1024, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Description, up to 1,024 characters; null clears it", - "title": "Description", - "x-null-distinct": true - }, - "disabled": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Disable the account to stop it being used, or enable it again", - "title": "Disabled" - }, - "preset_permissions": { - "anyOf": [ - { - "$ref": "#/components/schemas/ServiceAccountPresetPermissionsRequestV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Replaces the account's access as a whole. Temporary; may be removed once fine-grained access control is available." - } - }, - "title": "UpdateServiceAccountRequestV1", - "type": "object" - }, - "PredefinedIdentityProviderKindV1": { - "description": "An identity provider Baseten supports.", - "enum": [ - "GITHUB_ACTIONS", - "GCP", - "BASETEN", - "AWS_IAM", - "AWS_EKS", - "AZURE_MANAGED_IDENTITY_V1", - "AZURE_MANAGED_IDENTITY_V2", - "AZURE_AKS" - ], - "title": "PredefinedIdentityProviderKindV1", - "type": "string" - }, - "PredefinedIdentityProviderV1": { - "properties": { - "kind": { - "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", - "description": "Pass as `kind` when adding the provider" - }, - "name": { - "description": "Display name", - "title": "Name", - "type": "string" - }, - "issuer_url": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The `iss` claim its tokens carry. Null when each account, tenant, or cluster has its own issuer, which you pass as `issuer_url` when adding the provider.", - "title": "Issuer Url" - }, - "issuer_url_example": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "An example of the `issuer_url` to pass. Null when the issuer is fixed.", - "title": "Issuer Url Example" - } - }, - "required": [ - "kind", - "name" - ], - "title": "PredefinedIdentityProviderV1", - "type": "object" - }, - "PredefinedIdentityProvidersV1": { - "properties": { - "items": { - "description": "Identity providers Baseten supports", - "items": { - "$ref": "#/components/schemas/PredefinedIdentityProviderV1" - }, - "title": "Items", - "type": "array" - } - }, - "required": [ - "items" - ], - "title": "PredefinedIdentityProvidersV1", - "type": "object" - }, - "IdentityProviderV1": { - "description": "An OIDC issuer whose tokens the organization accepts for workload identity federation.", - "properties": { - "id": { - "description": "Identity provider ID", - "title": "Id", - "type": "string" - }, - "name": { - "description": "Name, unique in the organization", - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Description", - "title": "Description" - }, - "predefined": { - "$ref": "#/components/schemas/PredefinedIdentityProviderConfigV1", - "description": "Settings of the predefined provider" - }, - "created_by": { - "description": "ID of the user who added the provider", - "title": "Created By", - "type": "string" - }, - "created_at": { - "description": "Time the provider was added", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "updated_at": { - "description": "Time the provider was last updated", - "format": "date-time", - "title": "Updated At", - "type": "string" - } - }, - "required": [ - "id", - "name", - "predefined", - "created_by", - "created_at", - "updated_at" - ], - "title": "IdentityProviderV1", - "type": "object" - }, - "PredefinedIdentityProviderConfigV1": { - "description": "Settings of an identity provider that Baseten defines.", - "properties": { - "kind": { - "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", - "description": "Which predefined provider. Can't be changed." - }, - "issuer_url": { - "anyOf": [ - { - "maxLength": 1024, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", - "title": "Issuer Url" - } - }, - "required": [ - "kind" - ], - "title": "PredefinedIdentityProviderConfigV1", - "type": "object" - }, - "IdentityProvidersV1": { - "description": "A page of identity providers.", - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/IdentityProviderV1" - }, - "title": "Items", - "type": "array" - }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "IdentityProvidersV1", - "type": "object" - }, - "IdentityProvidersRequestV1": { - "properties": { - "cursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - }, - "name": { - "anyOf": [ - { - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Only the provider with this name, ignoring case", - "title": "Name" - }, - "predefined_kind": { - "anyOf": [ - { - "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Only this predefined provider's issuers" - } - }, - "title": "IdentityProvidersRequestV1", - "type": "object" - }, - "CreatePredefinedIdentityProviderConfigV1": { - "additionalProperties": false, - "description": "Settings of the predefined identity provider to add.", - "properties": { - "kind": { - "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", - "description": "Which predefined provider. Can't be changed." - }, - "issuer_url": { - "anyOf": [ - { - "maxLength": 1024, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The `iss` claim of the provider's tokens. When adding AWS IAM, Amazon EKS, Azure managed identity, or Azure Kubernetes Service, pass your issuer in the format the predefined identity providers endpoint shows; it's unique in the organization. Can't be passed for other providers, or changed. Always set in responses.", - "title": "Issuer Url" - } - }, - "required": [ - "kind" - ], - "title": "CreatePredefinedIdentityProviderConfigV1", - "type": "object" - }, - "CreateIdentityProviderRequestV1": { - "additionalProperties": false, - "description": "Request to add an identity provider.", - "properties": { - "name": { - "anyOf": [ - { - "maxLength": 255, - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Name, unique in the organization. Defaults to the provider's display name, so pass one when adding a second issuer of the same provider.", - "title": "Name" - }, - "description": { - "anyOf": [ - { - "maxLength": 1024, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Optional description", - "title": "Description" - }, - "predefined": { - "$ref": "#/components/schemas/CreatePredefinedIdentityProviderConfigV1", - "description": "The predefined provider to add" - } - }, - "required": [ - "predefined" - ], - "title": "CreateIdentityProviderRequestV1", - "type": "object" - }, - "VerifyPredefinedIdentityProviderConfigV1": { - "additionalProperties": false, - "description": "Settings of the predefined identity provider to check.", - "properties": { - "kind": { - "$ref": "#/components/schemas/PredefinedIdentityProviderKindV1", - "description": "Which predefined provider" - }, - "issuer_url": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The issuer to check, for AWS IAM, Amazon EKS, Azure managed identity, and Azure Kubernetes Service, in the format the predefined identity providers endpoint shows", - "title": "Issuer Url" - } - }, - "required": [ - "kind" - ], - "title": "VerifyPredefinedIdentityProviderConfigV1", - "type": "object" - }, - "VerifyIdentityProviderRequestV1": { - "additionalProperties": false, - "description": "Request to check an identity provider before adding it.", - "properties": { - "predefined": { - "$ref": "#/components/schemas/VerifyPredefinedIdentityProviderConfigV1", - "description": "The predefined provider to check, as you'd pass it when adding it" - } - }, - "required": [ - "predefined" - ], - "title": "VerifyIdentityProviderRequestV1", - "type": "object" - }, - "VerificationV1": { - "description": "Whether a create request would pass the checks the server runs on it.", - "properties": { - "valid": { - "description": "Whether the input passes every check", - "title": "Valid", - "type": "boolean" - }, - "error": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Why the input fails, as creating it would report. Null when it's valid.", - "title": "Error" - } - }, - "required": [ - "valid" - ], - "title": "VerificationV1", - "type": "object" - }, - "DeletedIdentityProviderV1": { - "properties": { - "id": { - "description": "ID of the deleted identity provider", - "title": "Id", - "type": "string" - }, - "deleted": { - "description": "Always true", - "title": "Deleted", - "type": "boolean" - } - }, - "required": [ - "id", - "deleted" - ], - "title": "DeletedIdentityProviderV1", - "type": "object" - }, - "UpdateIdentityProviderRequestV1": { - "additionalProperties": false, - "description": "Request to update an identity provider. Only the fields sent change.", - "properties": { - "name": { - "anyOf": [ - { - "maxLength": 255, - "minLength": 1, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Name, unique in the organization", - "title": "Name" - }, - "description": { - "anyOf": [ - { - "maxLength": 1024, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Description; null clears it", - "title": "Description", - "x-null-distinct": true - } - }, - "title": "UpdateIdentityProviderRequestV1", - "type": "object" - }, - "AccessTrustRuleV1": { - "description": "Which tokens from an identity provider may act as a service account.", - "properties": { - "id": { - "description": "Trust rule ID. Workloads pass it when they exchange a token.", - "title": "Id", - "type": "string" - }, - "name": { - "description": "Name, unique in the organization", - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Description", - "title": "Description" - }, - "identity_provider_id": { - "description": "The identity provider whose tokens it accepts", - "title": "Identity Provider Id", - "type": "string" - }, - "identity_provider_name": { - "description": "Name of the identity provider", - "title": "Identity Provider Name", - "type": "string" - }, - "service_account_id": { - "description": "The service account its tokens act as", - "title": "Service Account Id", - "type": "string" - }, - "service_account_name": { - "description": "Name of the service account", - "title": "Service Account Name", - "type": "string" - }, - "team_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "The service account's team. Null for an organization service account.", - "title": "Team Id" - }, - "team_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Name of the service account's team. Null for an organization service account.", - "title": "Team Name" - }, - "condition": { - "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", - "examples": [ - "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" - ], - "title": "Condition", - "type": "string" - }, - "audience": { - "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", - "title": "Audience", - "type": "string" - }, - "max_access_token_lifetime_seconds": { - "description": "Longest lifetime of a token the rule issues, in seconds", - "title": "Max Access Token Lifetime Seconds", - "type": "integer" - }, - "last_used_at": { - "anyOf": [ - { - "format": "date-time", - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Last time a request authenticated with a token the rule issued, to within an hour. Null until the first.", - "title": "Last Used At" - }, - "created_by": { - "description": "ID of the user who created the rule", - "title": "Created By", - "type": "string" - }, - "created_at": { - "description": "Time the rule was created", - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "updated_at": { - "description": "Time the rule was last updated", - "format": "date-time", - "title": "Updated At", - "type": "string" - } - }, - "required": [ - "id", - "name", - "identity_provider_id", - "identity_provider_name", - "service_account_id", - "service_account_name", - "condition", - "audience", - "max_access_token_lifetime_seconds", - "created_by", - "created_at", - "updated_at" - ], - "title": "AccessTrustRuleV1", - "type": "object" - }, - "AccessTrustRulesV1": { - "description": "A page of trust rules.", - "properties": { - "items": { - "description": "Items in this page.", - "items": { - "$ref": "#/components/schemas/AccessTrustRuleV1" - }, - "title": "Items", - "type": "array" - }, - "pagination": { - "$ref": "#/components/schemas/PaginationResponseV1", - "description": "Pagination metadata for the page." - } - }, - "required": [ - "items", - "pagination" - ], - "title": "AccessTrustRulesV1", - "type": "object" - }, - "AccessTrustRulesRequestV1": { - "properties": { - "cursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", - "title": "Cursor" - }, - "limit": { - "default": 100, - "description": "Maximum number of items to return.", - "maximum": 1000, - "minimum": 1, - "title": "Limit", - "type": "integer" - }, - "name": { + "type": "object" + }, + "UsageSummaryV1": { + "description": "Billing usage summary for the requested date range.", + "properties": { + "dedicated_usage": { "anyOf": [ { - "minLength": 1, - "type": "string" + "$ref": "#/components/schemas/DedicatedUsageV1" }, { "type": "null" } ], "default": null, - "description": "Only the rule with this name, ignoring case", - "title": "Name" + "description": "Dedicated model serving usage" }, - "identity_provider_id": { + "training_usage": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/TrainingUsageV1" }, { "type": "null" } ], "default": null, - "description": "Only this provider's rules", - "title": "Identity Provider Id" + "description": "Training usage" }, - "service_account_id": { + "model_apis_usage": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/ModelApisUsageV1" }, { "type": "null" } ], "default": null, - "description": "Only rules for this service account", - "title": "Service Account Id" + "description": "Model APIs usage" }, - "team_id": { + "loops_usage": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/LoopsUsageV1" }, { "type": "null" } ], "default": null, - "description": "Only rules for this team's service accounts", - "title": "Team Id" + "description": "Serverless Loops usage, billed per token. Loops usage on dedicated trainers and samplers is billed by the minute and is part of training usage." } }, - "title": "AccessTrustRulesRequestV1", + "title": "UsageSummaryV1", "type": "object" }, - "CreateAccessTrustRuleRequestV1": { - "additionalProperties": false, - "description": "Request to create a trust rule.", + "UsageSummaryRequestV1": { "properties": { - "name": { - "description": "Name, unique in the organization. Can be changed later.", - "maxLength": 255, - "minLength": 1, - "title": "Name", - "type": "string" - }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Optional description", - "title": "Description" - }, - "identity_provider_id": { - "description": "Whose tokens the rule accepts. Can't be changed.", - "title": "Identity Provider Id", - "type": "string" - }, - "service_account_id": { - "description": "The service account its tokens act as. Can be changed later.", - "title": "Service Account Id", - "type": "string" - }, - "condition": { - "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters. Can be changed later.", - "examples": [ - "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" - ], - "title": "Condition", + "start_date": { + "description": "Inclusive start date (ISO 8601, normalized to midnight UTC). Earliest queryable: 2026-01-01.", + "format": "date-time", + "title": "Start Date", "type": "string" }, - "audience": { - "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters. Can be changed later.", - "title": "Audience", + "end_date": { + "description": "Exclusive end date (ISO 8601, normalized to midnight UTC). Date range cannot exceed 31 days.", + "format": "date-time", + "title": "End Date", "type": "string" - }, - "max_access_token_lifetime_seconds": { - "default": 3600, - "description": "Longest lifetime of a token the rule issues, 60 to 3600 seconds. Can be changed later.", - "maximum": 3600, - "minimum": 60, - "title": "Max Access Token Lifetime Seconds", - "type": "integer" } }, "required": [ - "name", - "identity_provider_id", - "service_account_id", - "condition", - "audience" + "start_date", + "end_date" ], - "title": "CreateAccessTrustRuleRequestV1", + "title": "UsageSummaryRequestV1", "type": "object" }, - "VerifyAccessTrustRuleRequestV1": { - "additionalProperties": false, - "description": "Request to check a trust rule's condition and audience before saving them.", + "ToolCallUsageBucketV1": { + "description": "Server-side tool call usage for one day, provider, charge unit, and model.", "properties": { - "identity_provider_id": { - "description": "The identity provider the rule is for, which decides the claims it must pin", - "title": "Identity Provider Id", + "date": { + "description": "UTC day the usage was recorded on.", + "format": "date", + "title": "Date", "type": "string" }, - "condition": { - "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", - "examples": [ - "claims.repository_owner_id == '12345' && claims.sub.startsWith('repo:acme/models:') && claims.ref == 'refs/heads/main'" - ], - "title": "Condition", + "provider": { + "description": "Tool provider, such as exa or parallel.", + "title": "Provider", + "type": "string" + }, + "sku": { + "description": "Charge unit, as `/`. The unit is what the provider reported, or the tool name when it reported none. Its meaning varies by provider.", + "title": "Sku", "type": "string" }, - "audience": { - "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", - "title": "Audience", + "model": { + "description": "Model that made the tool calls.", + "title": "Model", "type": "string" + }, + "calls": { + "description": "Number of tool calls.", + "title": "Calls", + "type": "integer" + }, + "quantity": { + "description": "Billable quantity in the provider's sku unit, summed over the calls.", + "title": "Quantity", + "type": "number" + }, + "team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Team attributed to the usage. Null when not grouping by team or when historical team attribution is unavailable.", + "title": "Team Id" } }, "required": [ - "identity_provider_id", - "condition", - "audience" + "date", + "provider", + "sku", + "model", + "calls", + "quantity" ], - "title": "VerifyAccessTrustRuleRequestV1", + "title": "ToolCallUsageBucketV1", "type": "object" }, - "DeletedAccessTrustRuleV1": { + "ToolCallUsageResponseV1": { + "description": "Daily server-side tool call usage, ordered by day, provider, sku, and model.", "properties": { - "id": { - "description": "ID of the deleted trust rule", - "title": "Id", - "type": "string" - }, - "deleted": { - "description": "Always true", - "title": "Deleted", - "type": "boolean" + "items": { + "items": { + "$ref": "#/components/schemas/ToolCallUsageBucketV1" + }, + "title": "Items", + "type": "array" } }, - "required": [ - "id", - "deleted" - ], - "title": "DeletedAccessTrustRuleV1", + "title": "ToolCallUsageResponseV1", "type": "object" }, - "UpdateAccessTrustRuleRequestV1": { - "additionalProperties": false, - "description": "Request to update a trust rule. Only the fields sent change.", + "ToolCallUsageDimensionV1": { + "enum": [ + "TEAM" + ], + "title": "ToolCallUsageDimensionV1", + "type": "string" + }, + "ToolCallUsageRequestV1": { "properties": { - "name": { + "start_date": { + "description": "Inclusive UTC calendar day at the start of the query range.", + "format": "date", + "title": "Start Date", + "type": "string" + }, + "end_date": { "anyOf": [ { - "maxLength": 255, - "minLength": 1, + "format": "date", "type": "string" }, { @@ -41444,10 +37560,41 @@ } ], "default": null, - "description": "Name, unique in the organization", - "title": "Name" + "description": "Exclusive UTC calendar day at the end of the query range. Defaults to the day after the current UTC date so current-day usage is included. The date range cannot exceed 90 days.", + "title": "End Date" }, - "description": { + "team_ids": { + "description": "Return only usage for these teams, repeated once per team. Defaults to all teams you can manage. An unauthorized team ID causes a 403 response.", + "items": { + "type": "string" + }, + "title": "Team Ids", + "type": "array" + }, + "group_by": { + "description": "Pass TEAM to split daily rows by team. Defaults to aggregating across teams.", + "items": { + "$ref": "#/components/schemas/ToolCallUsageDimensionV1" + }, + "title": "Group By", + "type": "array" + } + }, + "required": [ + "start_date" + ], + "title": "ToolCallUsageRequestV1", + "type": "object" + }, + "UserInfoV1": { + "description": "A Baseten user.", + "properties": { + "user_id": { + "description": "Unique identifier for the user", + "title": "User Id", + "type": "string" + }, + "email": { "anyOf": [ { "type": "string" @@ -41457,11 +37604,10 @@ } ], "default": null, - "description": "Description; null clears it", - "title": "Description", - "x-null-distinct": true + "description": "Email address of the user", + "title": "Email" }, - "condition": { + "name": { "anyOf": [ { "type": "string" @@ -41471,10 +37617,10 @@ } ], "default": null, - "description": "A CEL expression over the token's `claims` that must evaluate to true. It must pin a specific `claims.sub` in a top-level `&&` clause, plus any provider-required checks. Up to 4,096 characters.", - "title": "Condition" + "description": "Display name of the user", + "title": "Name" }, - "audience": { + "workspace_name": { "anyOf": [ { "type": "string" @@ -41484,25 +37630,64 @@ } ], "default": null, - "description": "The token's `aud` must equal this, or contain it when `aud` is a list. Up to 1,024 characters.", - "title": "Audience" + "description": "Name of the user's workspace", + "title": "Workspace Name" + } + }, + "required": [ + "user_id" + ], + "title": "UserInfoV1", + "type": "object" + }, + "UsersResponseV1": { + "description": "A page of users in the caller's workspace.", + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/UserInfoV1" + }, + "title": "Items", + "type": "array" }, - "max_access_token_lifetime_seconds": { + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "UsersResponseV1", + "type": "object" + }, + "UsersRequestV1": { + "description": "Request parameters for listing users.", + "properties": { + "cursor": { "anyOf": [ { - "maximum": 3600, - "minimum": 60, - "type": "integer" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Longest lifetime of a token the rule issues, 60 to 3600 seconds. Tokens already issued keep their lifetime.", - "title": "Max Access Token Lifetime Seconds" + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" }, - "service_account_id": { + "email": { "anyOf": [ { "type": "string" @@ -41512,51 +37697,43 @@ } ], "default": null, - "description": "Moves the rule to another service account. Tokens already issued keep the old account until they expire.", - "title": "Service Account Id" + "description": "When set, returns only users with this exact email, if any.", + "title": "Email" } }, - "title": "UpdateAccessTrustRuleRequestV1", + "title": "UsersRequestV1", "type": "object" }, - "TokenExchangeRequestV1": { - "description": "An RFC 8693 token exchange request naming the trust rule to check as its audience.", + "AwsAssumeRoleV1": { + "description": "AWS AssumeRole trust-policy inputs for the organization.", "properties": { - "grant_type": { - "description": "Always `urn:ietf:params:oauth:grant-type:token-exchange`", - "examples": [ - "urn:ietf:params:oauth:grant-type:token-exchange" - ], - "title": "Grant Type", - "type": "string" - }, - "subject_token": { - "description": "The identity provider's JWT", - "examples": [ - "" - ], - "maxLength": 16384, - "title": "Subject Token", + "baseten_role_arn": { + "description": "Baseten role ARN to allow in an IAM role's trust policy", + "title": "Baseten Role Arn", "type": "string" }, - "subject_token_type": { - "description": "`urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`", - "examples": [ - "urn:ietf:params:oauth:token-type:jwt" - ], - "title": "Subject Token Type", + "external_id": { + "description": "sts:ExternalId Baseten presents when assuming the role", + "title": "External Id", "type": "string" - }, - "audience": { - "description": "ID of the trust rule to check the JWT against", - "examples": [ - "abcd1234" - ], - "maxLength": 64, - "title": "Audience", + } + }, + "required": [ + "baseten_role_arn", + "external_id" + ], + "title": "AwsAssumeRoleV1", + "type": "object" + }, + "OrganizationInfoV1": { + "description": "The caller's organization.", + "properties": { + "org_id": { + "description": "Unique identifier for the organization", + "title": "Org Id", "type": "string" }, - "requested_token_type": { + "name": { "anyOf": [ { "type": "string" @@ -41566,63 +37743,33 @@ } ], "default": null, - "description": "Optional; only `urn:ietf:params:oauth:token-type:access_token` is issued", - "title": "Requested Token Type" + "description": "Display name of the organization", + "title": "Name" + }, + "created_at": { + "description": "Time the organization was created in ISO 8601 format", + "format": "date-time", + "title": "Created At", + "type": "string" }, - "access_token_lifetime_seconds": { + "aws_assume_role": { "anyOf": [ { - "minimum": 1, - "type": "integer" + "$ref": "#/components/schemas/AwsAssumeRoleV1" }, { "type": "null" } ], "default": null, - "description": "Lifetime of the access token, in seconds. At most the rule's maximum.", - "title": "Access Token Lifetime Seconds" - } - }, - "required": [ - "grant_type", - "subject_token", - "subject_token_type", - "audience" - ], - "title": "TokenExchangeRequestV1", - "type": "object" - }, - "TokenExchangeResponseV1": { - "properties": { - "access_token": { - "description": "Send as `Authorization: Bearer`", - "title": "Access Token", - "type": "string" - }, - "issued_token_type": { - "description": "Always `urn:ietf:params:oauth:token-type:access_token`", - "title": "Issued Token Type", - "type": "string" - }, - "token_type": { - "description": "Always `Bearer`", - "title": "Token Type", - "type": "string" - }, - "expires_in": { - "description": "Seconds until the access token expires", - "title": "Expires In", - "type": "integer" + "description": "AWS AssumeRole trust-policy inputs; null while the method is not enabled for the organization" } }, "required": [ - "access_token", - "issued_token_type", - "token_type", - "expires_in" + "org_id", + "created_at" ], - "title": "TokenExchangeResponseV1", + "title": "OrganizationInfoV1", "type": "object" }, "GatewayEventTokensV1": { @@ -42256,31 +38403,30 @@ "title": "GridTokenV1", "type": "object" }, - "GridRouteAliasKindV1": { - "enum": [ - "CLAUDE_DESKTOP", - "ALIAS" - ], - "title": "GridRouteAliasKindV1", - "type": "string" - }, - "GridRouteAliasV1": { + "GridClassifierV1": { "properties": { + "id": { + "description": "Stable classifier identifier.", + "examples": [ + "general-v1" + ], + "title": "Id", + "type": "string" + }, "name": { - "description": "Name to send in the inference request's `model` field instead of the route's `name`.", + "description": "Display name of the classifier.", + "examples": [ + "General" + ], "title": "Name", "type": "string" - }, - "kind": { - "$ref": "#/components/schemas/GridRouteAliasKindV1", - "description": "Purpose of the alias. CLAUDE_DESKTOP is for Claude Code desktop, which rejects model names without a `claude` substring. ALIAS is any other name the team's clients send for the route." } }, "required": [ - "name", - "kind" + "id", + "name" ], - "title": "GridRouteAliasV1", + "title": "GridClassifierV1", "type": "object" }, "GridRouteClassifierV1": { @@ -42288,17 +38434,17 @@ "id": { "description": "Stable route classifier identifier.", "examples": [ - "abc1234" + "general-v1" ], "title": "Id", "type": "string" }, - "display_name": { + "name": { "description": "Display name of the route classifier.", "examples": [ "General" ], - "title": "Display Name", + "title": "Name", "type": "string" }, "supported_tradeoffs": { @@ -42315,8 +38461,8 @@ "title": "Supported Tradeoffs", "type": "array" }, - "decidable_canonical_model_ids": { - "description": "Canonical model ids the route classifier picks from.", + "decidable_models": { + "description": "Model identities the route classifier picks from.", "examples": [ [ "zai-org/GLM-5.3", @@ -42326,195 +38472,37 @@ "items": { "type": "string" }, - "title": "Decidable Canonical Model Ids", + "title": "Decidable Models", "type": "array" } }, "required": [ "id", - "display_name", + "name", "supported_tradeoffs", - "decidable_canonical_model_ids" + "decidable_models" ], "title": "GridRouteClassifierV1", "type": "object" }, - "GridRouteMetadataV1": { + "GridRouteRefV1": { "properties": { - "slug": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Metadata slug, e.g. 'anthropic/claude-opus-4'; null for rows without one.", - "title": "Slug" - }, - "display_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Model display name, when available.", - "title": "Display Name" - }, - "release_date": { - "anyOf": [ - { - "format": "date", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Model release date. Month-only source dates use the first day of that month.", - "title": "Release Date" - }, - "provider": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Provider key derived from the slug prefix, e.g. 'anthropic'; null for unprefixed slugs.", - "title": "Provider" - }, - "context_window": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Total context window in tokens.", - "title": "Context Window" - }, - "max_output_tokens": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Maximum output tokens per response.", - "title": "Max Output Tokens" - }, - "input_modalities": { - "description": "Accepted input modalities.", - "items": { - "type": "string" - }, - "title": "Input Modalities", - "type": "array" - }, - "tools": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "description": "Whether the model supports tool calling.", - "title": "Tools" - }, - "reasoning_effort_levels": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "Reasoning effort levels the model supports.", - "title": "Reasoning Effort Levels" - }, - "parallel_tool_calls": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "description": "Whether the model supports parallel tool calls.", - "title": "Parallel Tool Calls" - }, - "supported_api_formats": { - "anyOf": [ - { - "$ref": "#/components/schemas/ExploreMetadataAPIFormatsV1" - }, - { - "type": "null" - } - ], - "description": "API formats the model supports." - }, - "cost": { - "anyOf": [ - { - "$ref": "#/components/schemas/ExploreCostV1" - }, - { - "type": "null" - } - ], - "description": "Provider list prices in USD per 1M tokens, when available." + "id": { + "description": "Stable route identifier.", + "title": "Id", + "type": "string" }, - "api_formats": { - "description": "API formats the route supports, most preferred first: `chat_completions`, `messages`, `responses` for a BASETEN_MODEL_API target and `messages`, `responses`, `chat_completions` for any other target, keeping only the formats the route supports. Never empty.", - "items": { - "enum": [ - "messages", - "responses", - "chat_completions" - ], - "title": "GridRouteAPIFormatV1", - "type": "string" - }, - "minItems": 1, - "title": "Api Formats", - "type": "array" + "slug": { + "description": "Name of the route to send in the inference request's model field.", + "title": "Slug", + "type": "string" } }, "required": [ - "slug", - "display_name", - "release_date", - "provider", - "context_window", - "max_output_tokens", - "input_modalities", - "tools", - "reasoning_effort_levels", - "parallel_tool_calls", - "supported_api_formats", - "cost", - "api_formats" + "id", + "slug" ], - "title": "GridRouteMetadataV1", + "title": "GridRouteRefV1", "type": "object" }, "GridRouteTargetBasetenModelAPIV1": { @@ -42539,6 +38527,47 @@ "title": "GridRouteTargetBasetenModelAPIV1", "type": "object" }, + "GridRouteTargetClassifierV1": { + "properties": { + "type": { + "const": "CLASSIFIER", + "description": "Target kind for a classifier-based route.", + "title": "Type", + "type": "string" + }, + "classifier": { + "anyOf": [ + { + "$ref": "#/components/schemas/GridClassifierV1" + }, + { + "type": "null" + } + ], + "description": "Classifier that picks a route for each request. Null for routers created before classifiers could be selected." + }, + "default_route": { + "$ref": "#/components/schemas/GridRouteRefV1", + "description": "Route used when the classifier picks none." + }, + "allowed_routes": { + "description": "Routes the classifier may pick, in creation order.", + "items": { + "$ref": "#/components/schemas/GridRouteRefV1" + }, + "title": "Allowed Routes", + "type": "array" + } + }, + "required": [ + "type", + "classifier", + "default_route", + "allowed_routes" + ], + "title": "GridRouteTargetClassifierV1", + "type": "object" + }, "GridRouteTargetConnectionV1": { "properties": { "type": { @@ -42606,23 +38635,10 @@ "type": "string" }, "name": { - "description": "Name to send in the inference request's `model` field. Unique within the team; immutable.", + "description": "Name to send in the inference request's model field.", "title": "Name", "type": "string" }, - "display_name": { - "description": "Display label, defaulting to the route's name.", - "title": "Display Name", - "type": "string" - }, - "aliases": { - "description": "The route's other names, one per purpose. Empty for routes created before aliases existed.", - "items": { - "$ref": "#/components/schemas/GridRouteAliasV1" - }, - "title": "Aliases", - "type": "array" - }, "team_id": { "description": "Identifier of the owning team.", "title": "Team Id", @@ -42633,6 +38649,11 @@ "title": "Team Name", "type": "string" }, + "display_name": { + "description": "Display label, defaulting to the route name.", + "title": "Display Name", + "type": "string" + }, "description": { "description": "Short description of the route, empty when unset.", "title": "Description", @@ -42643,6 +38664,7 @@ "discriminator": { "mapping": { "BASETEN_MODEL_API": "#/components/schemas/GridRouteTargetBasetenModelAPIV1", + "CLASSIFIER": "#/components/schemas/GridRouteTargetClassifierV1", "CONNECTION": "#/components/schemas/GridRouteTargetConnectionV1", "INTELLIGENT": "#/components/schemas/GridRouteTargetIntelligentV1" }, @@ -42655,6 +38677,9 @@ { "$ref": "#/components/schemas/GridRouteTargetConnectionV1" }, + { + "$ref": "#/components/schemas/GridRouteTargetClassifierV1" + }, { "$ref": "#/components/schemas/GridRouteTargetIntelligentV1" } @@ -42664,13 +38689,13 @@ "metadata": { "anyOf": [ { - "$ref": "#/components/schemas/GridRouteMetadataV1" + "$ref": "#/components/schemas/ExploreMetadataV1" }, { "type": "null" } ], - "description": "Resolved model metadata; for an intelligent route, the envelope of its servable models' metadata. Null when nothing is linked or the metadata has no supported API formats." + "description": "Resolved model metadata; for a router, the envelope of its allowed routes' metadata. Null when nothing is linked." }, "invoke_url": { "description": "Base URL for inference requests using this route.", @@ -42687,9 +38712,9 @@ "required": [ "id", "name", - "display_name", "team_id", "team_name", + "display_name", "description", "target", "metadata", @@ -42773,7 +38798,7 @@ } ], "default": null, - "description": "Filter by exact route name, the value to send in the inference request's `model` field. Matches a route's name or any of its aliases. Preserved by the cursor; if repeated, must match the original filter.", + "description": "Filter by exact route name. Preserved by the cursor; if repeated, must match the original filter.", "title": "Name" } }, @@ -42803,74 +38828,87 @@ "title": "UpsertGridRouteTargetBasetenModelAPIV1", "type": "object" }, - "UpsertGridRouteTargetConnectionV1": { + "UpsertGridRouteTargetClassifierV1": { "additionalProperties": false, "properties": { "type": { - "const": "CONNECTION", - "description": "Target kind for a provider reached through a team connection.", + "const": "CLASSIFIER", + "description": "Target kind for a classifier-based route.", "title": "Type", "type": "string" }, - "model": { - "description": "Model name sent to the provider.", + "classifier_id": { + "description": "ID of the classifier that picks a route for each request.", + "examples": [ + "general-v1" + ], "minLength": 1, - "title": "Model", + "title": "Classifier Id", "type": "string" }, - "connection_id": { - "description": "Identifier of a connection owned by the route's team. Its provider serves the route.", + "allowed_route_ids": { + "description": "IDs of the routes the classifier may pick. All must belong to the route's team and must not be routers themselves.", + "examples": [ + [ + "abc1234", + "def5678" + ] + ], + "items": { + "type": "string" + }, + "title": "Allowed Route Ids", + "type": "array" + }, + "default_route_id": { + "description": "ID of the allowed route used when the classifier picks none.", "examples": [ "abc1234" ], - "minLength": 1, - "title": "Connection Id", + "title": "Default Route Id", "type": "string" } }, "required": [ "type", - "model", - "connection_id" + "classifier_id", + "allowed_route_ids", + "default_route_id" ], - "title": "UpsertGridRouteTargetConnectionV1", + "title": "UpsertGridRouteTargetClassifierV1", "type": "object" }, - "UpsertGridRouteTargetIntelligentV1": { + "UpsertGridRouteTargetConnectionV1": { "additionalProperties": false, "properties": { "type": { - "const": "INTELLIGENT", - "description": "Target kind for an intelligent route: Baseten picks the model per request.", + "const": "CONNECTION", + "description": "Target kind for a provider reached through a team connection.", "title": "Type", "type": "string" }, - "route_classifier_id": { - "description": "Identifier of the route classifier that picks the model. List them with GET /v1/grid/route_classifiers.", - "examples": [ - "abc1234" - ], + "model": { + "description": "Model name sent to the provider.", "minLength": 1, - "title": "Route Classifier Id", + "title": "Model", "type": "string" }, - "tradeoff": { - "description": "How the classifier weighs cost against quality. Must be one of the classifier's supported tradeoffs.", - "enum": [ - "cost", - "balanced", - "intelligence" + "connection_id": { + "description": "Identifier of a connection owned by the route's team. Its provider serves the route.", + "examples": [ + "abc1234" ], - "title": "GridRouteTradeoffV1", + "minLength": 1, + "title": "Connection Id", "type": "string" } }, "required": [ "type", - "route_classifier_id", - "tradeoff" + "model", + "connection_id" ], - "title": "UpsertGridRouteTargetIntelligentV1", + "title": "UpsertGridRouteTargetConnectionV1", "type": "object" }, "CreateGridRouteRequestV1": { @@ -42905,19 +38943,19 @@ } ], "default": null, - "description": "Display label. Omit to use the route's name; required for INTELLIGENT targets. Null is not accepted.", + "description": "Display label. Omit to use the route name; null is not accepted.", "examples": [ "Assistant" ], "title": "Display Name" }, "target": { - "description": "Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team. INTELLIGENT targets need at least one of the route classifier's models, and one of its fallback models, servable by the team.", + "description": "Upstream target for the route. CONNECTION targets use the provider and credentials of a connection owned by the route's team.", "discriminator": { "mapping": { "BASETEN_MODEL_API": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1", - "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1", - "INTELLIGENT": "#/components/schemas/UpsertGridRouteTargetIntelligentV1" + "CLASSIFIER": "#/components/schemas/UpsertGridRouteTargetClassifierV1", + "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1" }, "propertyName": "type" }, @@ -42935,7 +38973,7 @@ "$ref": "#/components/schemas/UpsertGridRouteTargetConnectionV1" }, { - "$ref": "#/components/schemas/UpsertGridRouteTargetIntelligentV1" + "$ref": "#/components/schemas/UpsertGridRouteTargetClassifierV1" } ], "title": "Target" @@ -42973,8 +39011,7 @@ "XAI", "VERTEX", "OPENAI_COMPATIBLE", - "BEDROCK", - "AZURE" + "BEDROCK" ], "title": "GridProviderV1", "type": "string" @@ -43079,7 +39116,7 @@ "default": null, "description": "Provider that served the requests. Null when not grouping by PROVIDER." }, - "intelligent_route_id": { + "intelligent_route": { "anyOf": [ { "type": "string" @@ -43089,21 +39126,8 @@ } ], "default": null, - "description": "ID of the intelligent route, as `id` in GET /v1/grid/routes. Null when not grouping by INTELLIGENT_ROUTE.", - "title": "Intelligent Route Id" - }, - "intelligent_route_display_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Display name of the intelligent route. Null when `intelligent_route_id` is null or the route cannot be resolved.", - "title": "Intelligent Route Display Name" + "description": "Name of the intelligent route, as in `GET /v1/grid/routes`. Null when not grouping by INTELLIGENT_ROUTE.", + "title": "Intelligent Route" }, "harness": { "anyOf": [ @@ -43117,32 +39141,6 @@ "default": null, "description": "Coding harness. Null when not grouping by HARNESS, when no harness was recorded (including usage from before harness tracking), or when the recorded harness is not recognized by this API version." }, - "api_key_prefix": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Prefix of the API key that made the requests, matching `GET /v1/api_keys`. Null when not grouping by API_KEY, for usage without an API key, and for usage recorded before API key tracking.", - "title": "Api Key Prefix" - }, - "api_key_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Name of the API key. Null when `api_key_prefix` is null or the key has no name.", - "title": "Api Key Name" - }, "cost_usd": { "description": "Estimated cost in USD, returned as an exact decimal string. Costs for OpenAI, Anthropic, and xAI estimate what you pay those providers; they are not Baseten charges.", "examples": [ @@ -43217,8 +39215,7 @@ "MODEL", "PROVIDER", "INTELLIGENT_ROUTE", - "HARNESS", - "API_KEY" + "HARNESS" ], "title": "GridRouteUsageDimensionV1", "type": "string" @@ -43288,7 +39285,7 @@ "title": "End Date" }, "group_by": { - "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, HARNESS, or API_KEY. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. API_KEY includes usage without an API key, such as requests authenticated by a signed-in session, as a null group. Defaults to MODEL.", + "description": "Dimensions to break usage down by, repeated once per dimension: USER, TEAM, MODEL, PROVIDER, INTELLIGENT_ROUTE, or HARNESS. Each result represents one observed combination of the requested dimensions within that day, and results are sorted by those values. Combinations without usage are omitted, so result counts can differ between days. INTELLIGENT_ROUTE returns only usage sent through an intelligent route, one row per intelligent route, or per intelligent route and model with MODEL. These rows repeat usage already counted in other groupings, so don't add them to model totals. HARNESS includes usage with no recorded harness as a null group. Defaults to MODEL.", "items": { "$ref": "#/components/schemas/GridRouteUsageDimensionV1" }, @@ -43326,14 +39323,6 @@ }, "title": "Harnesses", "type": "array" - }, - "api_key_prefixes": { - "description": "Return only usage made with these API keys, repeated once per key prefix. Omit to include all usage, including usage without an API key.", - "items": { - "type": "string" - }, - "title": "Api Key Prefixes", - "type": "array" } }, "title": "GridRouteUsageRequestV1", @@ -43397,6 +39386,37 @@ "Assistant" ], "title": "Display Name" + }, + "target": { + "anyOf": [ + { + "discriminator": { + "mapping": { + "BASETEN_MODEL_API": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1", + "CLASSIFIER": "#/components/schemas/UpsertGridRouteTargetClassifierV1", + "CONNECTION": "#/components/schemas/UpsertGridRouteTargetConnectionV1" + }, + "propertyName": "type" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/UpsertGridRouteTargetBasetenModelAPIV1" + }, + { + "$ref": "#/components/schemas/UpsertGridRouteTargetConnectionV1" + }, + { + "$ref": "#/components/schemas/UpsertGridRouteTargetClassifierV1" + } + ] + }, + { + "type": "null" + } + ], + "description": "Complete new target configuration. Omit to keep the current configuration; null is not accepted. Only the CLASSIFIER configuration of a router route is mutable.", + "title": "Target", + "x-null-distinct": true } }, "title": "UpdateGridRouteRequestV1", @@ -44220,39 +40240,6 @@ "title": "GridConnectionConfigAnthropicV1", "type": "object" }, - "GridConnectionConfigAzureV1": { - "properties": { - "provider": { - "const": "AZURE", - "description": "Provider kind for Microsoft Azure.", - "title": "Provider", - "type": "string" - }, - "secret_id": { - "description": "Identifier of the team secret holding the provider API key.", - "title": "Secret Id", - "type": "string" - }, - "secret_name": { - "description": "Name of the team secret holding the provider API key.", - "title": "Secret Name", - "type": "string" - }, - "resource_name": { - "description": "Name of the Azure AI Foundry or Azure OpenAI resource.", - "title": "Resource Name", - "type": "string" - } - }, - "required": [ - "provider", - "secret_id", - "secret_name", - "resource_name" - ], - "title": "GridConnectionConfigAzureV1", - "type": "object" - }, "GridConnectionConfigBedrockV1": { "properties": { "provider": { @@ -44421,7 +40408,6 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/GridConnectionConfigAnthropicV1", - "AZURE": "#/components/schemas/GridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/GridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/GridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/GridConnectionConfigVertexV1", @@ -44444,9 +40430,6 @@ }, { "$ref": "#/components/schemas/GridConnectionConfigBedrockV1" - }, - { - "$ref": "#/components/schemas/GridConnectionConfigAzureV1" } ], "title": "Config" @@ -44595,42 +40578,6 @@ "title": "UpsertGridConnectionConfigAnthropicV1", "type": "object" }, - "UpsertGridConnectionConfigAzureV1": { - "additionalProperties": false, - "properties": { - "provider": { - "const": "AZURE", - "description": "Provider kind for Microsoft Azure. Route targets name a deployment, which must be named after its Azure model. Claude models (`claude-*`) use the Anthropic Messages API, and other models use the OpenAI-compatible APIs.", - "title": "Provider", - "type": "string" - }, - "secret_name": { - "description": "Name of an existing secret, owned by the same team, that holds the provider API key.", - "examples": [ - "anthropic-key" - ], - "minLength": 1, - "title": "Secret Name", - "type": "string" - }, - "resource_name": { - "description": "Name of the Azure AI Foundry or Azure OpenAI resource, the subdomain of `.openai.azure.com`.", - "examples": [ - "my-foundry-resource" - ], - "minLength": 1, - "title": "Resource Name", - "type": "string" - } - }, - "required": [ - "provider", - "secret_name", - "resource_name" - ], - "title": "UpsertGridConnectionConfigAzureV1", - "type": "object" - }, "UpsertGridConnectionConfigBedrockV1": { "additionalProperties": false, "properties": { @@ -44810,7 +40757,6 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/UpsertGridConnectionConfigAnthropicV1", - "AZURE": "#/components/schemas/UpsertGridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/UpsertGridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/UpsertGridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/UpsertGridConnectionConfigVertexV1", @@ -44839,9 +40785,6 @@ }, { "$ref": "#/components/schemas/UpsertGridConnectionConfigBedrockV1" - }, - { - "$ref": "#/components/schemas/UpsertGridConnectionConfigAzureV1" } ], "title": "Config" @@ -44875,7 +40818,6 @@ "discriminator": { "mapping": { "ANTHROPIC": "#/components/schemas/UpsertGridConnectionConfigAnthropicV1", - "AZURE": "#/components/schemas/UpsertGridConnectionConfigAzureV1", "BEDROCK": "#/components/schemas/UpsertGridConnectionConfigBedrockV1", "OPENAI": "#/components/schemas/UpsertGridConnectionConfigOpenAIV1", "VERTEX": "#/components/schemas/UpsertGridConnectionConfigVertexV1", @@ -44904,9 +40846,6 @@ }, { "$ref": "#/components/schemas/UpsertGridConnectionConfigBedrockV1" - }, - { - "$ref": "#/components/schemas/UpsertGridConnectionConfigAzureV1" } ], "title": "Config" @@ -44918,6 +40857,55 @@ "title": "UpdateGridConnectionRequestV1", "type": "object" }, + "GridClassifiersResponseV1": { + "properties": { + "items": { + "description": "Items in this page.", + "items": { + "$ref": "#/components/schemas/GridClassifierV1" + }, + "title": "Items", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponseV1", + "description": "Pagination metadata for the page." + } + }, + "required": [ + "items", + "pagination" + ], + "title": "GridClassifiersResponseV1", + "type": "object" + }, + "GridClassifiersRequestV1": { + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Opaque cursor returned by a previous page. Omit to fetch the first page.", + "title": "Cursor" + }, + "limit": { + "default": 100, + "description": "Maximum number of items to return.", + "maximum": 1000, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + "title": "GridClassifiersRequestV1", + "type": "object" + }, "GridRouteClassifiersResponseV1": { "properties": { "items": { @@ -48931,43 +44919,27 @@ "in": "path", "required": true }, - "service_account_id": { - "schema": { - "type": "string" - }, - "name": "service_account_id", - "in": "path", - "required": true - }, - "identity_provider_id": { - "schema": { - "type": "string" - }, - "name": "identity_provider_id", - "in": "path", - "required": true - }, - "trust_rule_id": { + "route_id": { "schema": { "type": "string" }, - "name": "trust_rule_id", + "name": "route_id", "in": "path", "required": true }, - "route_id": { + "connection_id": { "schema": { "type": "string" }, - "name": "route_id", + "name": "connection_id", "in": "path", "required": true }, - "connection_id": { + "classifier_id": { "schema": { "type": "string" }, - "name": "connection_id", + "name": "classifier_id", "in": "path", "required": true }, From 7fbcf7b683857109fade250c98cc224e32a7386a Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Thu, 19 Nov 2026 16:21:06 -0500 Subject: [PATCH 09/14] Exchange identity tokens through the generated management client Matches baseten-go: the exchange goes through the generated post_auth_token, and redirects are left to the HTTP client, which does not follow them by default. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_workload_identity.py | 137 +++++++++++++------------ tests/client/test_workload_identity.py | 33 ++++-- 2 files changed, 95 insertions(+), 75 deletions(-) diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 13ab6b2..ab06a67 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import json import os from collections.abc import Awaitable, Callable from datetime import datetime, timedelta @@ -18,7 +19,13 @@ _utc_now, ) from baseten.client._user_agent import with_user_agent -from baseten.client.managementapi import ResponseError +from baseten.client.managementapi import ( + ApiClient, + AsyncApiClient, + ResponseError, + TokenExchangeRequest, + TokenExchangeResponse, +) # The exchange takes an RFC 8693 request naming the trust rule as its audience. _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" @@ -63,10 +70,10 @@ def __init__( base_url = (base_url_override or ManagementClient.default_base_url()).rstrip( "/" ) - self.url = f"{base_url}/v1/auth/token" + self.base_url = base_url self.timeout_sec = exchange_timeout.total_seconds() self.timeout = httpx.Timeout(self.timeout_sec) - self.headers = with_user_agent({"Accept": "application/json"}) + self.headers = with_user_agent({}) def read_identity_token_file(self) -> str: assert self.identity_token_file is not None @@ -76,80 +83,64 @@ def read_identity_token_file(self) -> str: raise ValueError(f"identity token file {self.identity_token_file} is empty") return token - def body(self, identity_token: str) -> dict[str, str]: + def request(self, identity_token: str) -> TokenExchangeRequest: token = identity_token.strip() if token == "": raise ValueError("the identity token provider returned an empty token") - return { - "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE, - "subject_token": token, - "subject_token_type": _JWT_TOKEN_TYPE, - "audience": self.trust_rule_id, - } + return TokenExchangeRequest( + grant_type=_TOKEN_EXCHANGE_GRANT_TYPE, + subject_token=token, + subject_token_type=_JWT_TOKEN_TYPE, + audience=self.trust_rule_id, + ) - def post_kwargs(self, body: dict[str, str]) -> dict[str, Any]: + def api_kwargs(self) -> dict[str, Any]: + # No auth: the identity token in the body is what authenticates. return { - "url": self.url, - "json": body, + "base_url": self.base_url, "headers": self.headers, "timeout": self.timeout, - # The body carries the identity token, so it is never sent on to - # wherever a redirect points, even with a client that follows them. - "follow_redirects": False, } - def parse(self, response: httpx.Response, *, issued_at: datetime) -> AccessToken: - if response.status_code != 200: - error = ResponseError(status_code=response.status_code, body=response.text) - if _oauth_error(response) == "invalid_grant": - # The server sends every refusal as the same invalid_grant, so - # the note covers each possible cause. - error.add_note( - "workload identity token exchange refused for trust rule " - f"{self.trust_rule_id} (the trust rule may not exist or may " - "not match the identity token's issuer, audience, or claims, " - "or the identity token may have expired)" - ) - raise error - try: - body = response.json() - except ValueError: - raise ValueError( - "workload identity token exchange: the response is not JSON" - ) from None - if not isinstance(body, dict): - body = {} - access_token = body.get("access_token") - if not isinstance(access_token, str) or access_token == "": + def add_refusal_note(self, error: ResponseError) -> None: + if _oauth_error(error.body) == "invalid_grant": + # The server sends every refusal as the same invalid_grant, so the + # note covers each possible cause. + error.add_note( + "workload identity token exchange refused for trust rule " + f"{self.trust_rule_id} (the trust rule may not exist or may " + "not match the identity token's issuer, audience, or claims, " + "or the identity token may have expired)" + ) + + def parse( + self, response: TokenExchangeResponse, *, issued_at: datetime + ) -> AccessToken: + if response.access_token == "": raise ValueError( "workload identity token exchange: the response carried no access_token" ) - token_type = body.get("token_type") - if not isinstance(token_type, str) or token_type.lower() != "bearer": + if response.token_type.lower() != "bearer": raise ValueError( "workload identity token exchange: unsupported token_type " - f"{token_type!r}" + f"{response.token_type!r}" ) - expires_in = body.get("expires_in") - if ( - not isinstance(expires_in, int) - or isinstance(expires_in, bool) - or expires_in <= 0 - ): + if response.expires_in <= 0: raise ValueError( - f"workload identity token exchange: invalid expires_in {expires_in!r}" + f"workload identity token exchange: invalid expires_in {response.expires_in!r}" ) return AccessToken( - token=access_token, expires_at=issued_at + timedelta(seconds=expires_in) + token=response.access_token, + expires_at=issued_at + timedelta(seconds=response.expires_in), ) -def _oauth_error(response: httpx.Response) -> object: +def _oauth_error(body: str) -> object: try: - body = response.json() + decoded = json.loads(body) except ValueError: return None - return body.get("error") if isinstance(body, dict) else None + return decoded.get("error") if isinstance(decoded, dict) else None class WorkloadIdentityCredentials: @@ -241,14 +232,22 @@ def _exchange_token(self) -> AccessToken: identity_token = self._identity_token() else: identity_token = self._exchange.read_identity_token_file() - post_kwargs = self._exchange.post_kwargs(self._exchange.body(identity_token)) + request = self._exchange.request(identity_token) # Taken before sending, so the computed expiry errs early. issued_at = self._now() - if self._http_client is not None: - response = self._http_client.post(**post_kwargs) - else: - with httpx.Client() as http_client: - response = http_client.post(**post_kwargs) + try: + if self._http_client is not None: + response = ApiClient( + self._http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + else: + with httpx.Client() as http_client: + response = ApiClient( + http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + except ResponseError as e: + self._exchange.add_refusal_note(e) + raise return self._exchange.parse(response, issued_at=issued_at) @@ -317,12 +316,20 @@ async def _exchange_once(self) -> AccessToken: identity_token = await asyncio.to_thread( self._exchange.read_identity_token_file ) - post_kwargs = self._exchange.post_kwargs(self._exchange.body(identity_token)) + request = self._exchange.request(identity_token) # Taken before sending, so the computed expiry errs early. issued_at = self._now() - if self._http_client is not None: - response = await self._http_client.post(**post_kwargs) - else: - async with httpx.AsyncClient() as http_client: - response = await http_client.post(**post_kwargs) + try: + if self._http_client is not None: + response = await AsyncApiClient( + self._http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + else: + async with httpx.AsyncClient() as http_client: + response = await AsyncApiClient( + http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + except ResponseError as e: + self._exchange.add_refusal_note(e) + raise return self._exchange.parse(response, issued_at=issued_at) diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index 1f7ddf6..86fc13b 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -22,6 +22,7 @@ ) from baseten.client.managementapi import ResponseError +_ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" _BASE_URL = "https://api.test" _ORG = { "org_id": "o", @@ -73,6 +74,7 @@ def handle(self, request: httpx.Request) -> httpx.Response: "access_token": f"access-{len(self.assertions)}", "token_type": "Bearer", "expires_in": self.expires_in, + "issued_token_type": _ACCESS_TOKEN_TYPE, }, ) @@ -230,7 +232,7 @@ def test_does_not_follow_redirects(self) -> None: identity_token=lambda: "idp-jwt", base_url_override=_BASE_URL, http_client_override=httpx.Client( - transport=httpx.MockTransport(server.handle), follow_redirects=True + transport=httpx.MockTransport(server.handle) ), ) with pytest.raises(ResponseError, match="HTTP 307"): @@ -253,17 +255,28 @@ def test_exchange_timeout(self) -> None: credentials.access_token(_OPTIONS) @pytest.mark.parametrize( - "body", + ("body", "match"), [ - {"token_type": "Bearer", "expires_in": 60}, - {"access_token": "a", "token_type": "MAC", "expires_in": 60}, - {"access_token": "a", "token_type": "Bearer"}, + ( + {"access_token": "", "token_type": "Bearer", "expires_in": 60}, + "no access_token", + ), + ( + {"access_token": "a", "token_type": "MAC", "expires_in": 60}, + "unsupported token_type", + ), + ( + {"access_token": "a", "token_type": "Bearer", "expires_in": 0}, + "invalid expires_in", + ), ], ) - def test_malformed_success(self, body: dict[str, object]) -> None: + def test_malformed_success(self, body: dict[str, object], match: str) -> None: server = _Server() - server.exchange_response = lambda: httpx.Response(200, json=body) - with pytest.raises(ValueError): + server.exchange_response = lambda: httpx.Response( + 200, json={**body, "issued_token_type": _ACCESS_TOKEN_TYPE} + ) + with pytest.raises(ValueError, match=match): server.credentials().access_token(_OPTIONS) @pytest.mark.parametrize( @@ -366,8 +379,8 @@ async def test_invalid_grant_is_explained(self) -> None: @pytest.mark.parametrize( ("response", "match"), [ - (httpx.Response(200, text=""), "not JSON"), - (httpx.Response(200, json=["a"]), "no access_token"), + (httpx.Response(200, text=""), "unexpected content type"), + (httpx.Response(200, json=["a"]), "validation error"), ( httpx.Response(200, json={"access_token": "a", "token_type": "Bearer"}), "expires_in", From ddf3592143464d933e2ff4971761b346725b5921 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Fri, 20 Nov 2026 11:24:10 -0500 Subject: [PATCH 10/14] Bound the whole sync exchange and keep it free of client auth - exchange_timeout now bounds a whole sync exchange, including the identity token provider, as in Go; httpx alone bounds each phase. - The exchange no longer inherits an http_client_override's own auth. - Every exchange failure notes the trust rule it was for. - The async exchange no longer relabels a provider's own TimeoutError. - Taking the refused token is atomic across threads. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_token_auth.py | 8 ++- baseten/client/_workload_identity.py | 76 +++++++++++++++++++++----- tests/client/test_workload_identity.py | 75 +++++++++++++++++++++---- 3 files changed, 134 insertions(+), 25 deletions(-) diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py index 729366a..52df75b 100644 --- a/baseten/client/_token_auth.py +++ b/baseten/client/_token_auth.py @@ -318,6 +318,9 @@ def __init__(self, credentials: Credentials, *, origin: str) -> None: # The last token Baseten refused, passed to the next access_token call # so the credentials replace it. self._refused: str | None = None + # Taken and cleared together, since requests on several threads share + # this auth. + self._refused_lock = threading.Lock() def sync_auth_flow( self, request: httpx.Request @@ -326,8 +329,9 @@ def sync_auth_flow( if not _applies_to(request, self._origin): yield request return - options = AccessTokenOptions(refused_token=self._refused) - self._refused = None + with self._refused_lock: + refused, self._refused = self._refused, None + options = AccessTokenOptions(refused_token=refused) token = _non_empty(self._credentials.access_token(options)) _set_authorization(request, token) response = yield request diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index ab06a67..fb636ea 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -1,8 +1,10 @@ from __future__ import annotations import asyncio +import contextvars import json import os +import threading from collections.abc import Awaitable, Callable from datetime import datetime, timedelta from pathlib import Path @@ -27,6 +29,10 @@ TokenExchangeResponse, ) +# Sends a request as is, so the exchange never picks up an HTTP client's own +# auth, such as another client's credentials. +_NO_AUTH = httpx.Auth() + # The exchange takes an RFC 8693 request naming the trust rule as its audience. _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" _JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" @@ -95,15 +101,22 @@ def request(self, identity_token: str) -> TokenExchangeRequest: ) def api_kwargs(self) -> dict[str, Any]: - # No auth: the identity token in the body is what authenticates. + # The identity token in the body is what authenticates. return { "base_url": self.base_url, "headers": self.headers, "timeout": self.timeout, + "auth": _NO_AUTH, } - def add_refusal_note(self, error: ResponseError) -> None: - if _oauth_error(error.body) == "invalid_grant": + def add_context(self, error: Exception) -> None: + error.add_note( + f"while exchanging an identity token under trust rule {self.trust_rule_id}" + ) + if ( + isinstance(error, ResponseError) + and _oauth_error(error.body) == "invalid_grant" + ): # The server sends every refusal as the same invalid_grant, so the # note covers each possible cause. error.add_note( @@ -198,10 +211,13 @@ def __init__( refresh_leeway: How long before expiry the access token is replaced, capped at half the token's lifetime so a short-lived token is still reused. - exchange_timeout: Bounds each phase of one exchange, which - every caller waiting for a token shares. + exchange_timeout: Bounds one whole exchange, including + *identity_token* and reading *identity_token_file*, which + every caller waiting for a token shares. An exchange that + overruns is abandoned on its own thread. http_client_override: HTTP client to send the exchange with. - ``None`` uses a new one per exchange. + ``None`` uses a new one per exchange. It should not follow + redirects, since the request body carries the identity token. """ self._exchange = _Exchange( trust_rule_id=trust_rule_id, @@ -228,6 +244,37 @@ def access_token(self, options: AccessTokenOptions) -> AccessToken: return self._cache.token() def _exchange_token(self) -> AccessToken: + # httpx bounds each phase of a request rather than the whole of it, and + # nothing bounds the identity token provider, so the exchange runs on + # its own thread and is abandoned when it overruns. + done = threading.Event() + outcome: list[AccessToken | BaseException] = [] + + def run() -> None: + try: + outcome.append(self._exchange_once()) + except BaseException as e: # noqa: BLE001 - re-raised on the caller's thread + outcome.append(e) + finally: + done.set() + + threading.Thread( + target=contextvars.copy_context().run, + args=(run,), + name="baseten-workload-identity-exchange", + daemon=True, + ).start() + if not done.wait(self._exchange.timeout_sec): + raise TimeoutError( + "workload identity token exchange timed out after " + f"{self._exchange.timeout_sec}s" + ) + result = outcome[0] + if isinstance(result, BaseException): + raise result + return result + + def _exchange_once(self) -> AccessToken: if self._identity_token is not None: identity_token = self._identity_token() else: @@ -245,10 +292,10 @@ def _exchange_token(self) -> AccessToken: response = ApiClient( http_client, **self._exchange.api_kwargs() ).post_auth_token(request=request) - except ResponseError as e: - self._exchange.add_refusal_note(e) + return self._exchange.parse(response, issued_at=issued_at) + except Exception as e: + self._exchange.add_context(e) raise - return self._exchange.parse(response, issued_at=issued_at) class AsyncWorkloadIdentityCredentials: @@ -300,9 +347,12 @@ async def access_token(self, options: AccessTokenOptions) -> AccessToken: async def _exchange_token(self) -> AccessToken: try: - async with asyncio.timeout(self._exchange.timeout_sec): + async with asyncio.timeout(self._exchange.timeout_sec) as deadline: return await self._exchange_once() except TimeoutError as e: + # A TimeoutError of the provider's own is not the exchange's. + if not deadline.expired(): + raise raise TimeoutError( "workload identity token exchange timed out after " f"{self._exchange.timeout_sec}s" @@ -329,7 +379,7 @@ async def _exchange_once(self) -> AccessToken: response = await AsyncApiClient( http_client, **self._exchange.api_kwargs() ).post_auth_token(request=request) - except ResponseError as e: - self._exchange.add_refusal_note(e) + return self._exchange.parse(response, issued_at=issued_at) + except Exception as e: + self._exchange.add_context(e) raise - return self._exchange.parse(response, issued_at=issued_at) diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index 86fc13b..befe3a1 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -3,6 +3,7 @@ import asyncio import json import socket +import threading from collections.abc import Callable from datetime import UTC, datetime, timedelta from pathlib import Path @@ -31,6 +32,7 @@ "allow_service_account_api_keys": True, } _OPTIONS = AccessTokenOptions() +_CONTEXT = "while exchanging an identity token under trust rule rule-1" class _Server: @@ -199,9 +201,10 @@ def test_invalid_grant_is_explained_and_not_cached(self) -> None: credentials.access_token(_OPTIONS) assert exc_info.value.status_code == 400 assert exc_info.value.body == '{"error":"invalid_grant"}' - (note,) = exc_info.value.__notes__ - assert "trust rule rule-1" in note - assert "may have expired" in note + context, hint = exc_info.value.__notes__ + assert context == _CONTEXT + assert "trust rule rule-1" in hint + assert "may have expired" in hint with pytest.raises(ResponseError): credentials.access_token(_OPTIONS) assert len(server.assertions) == 2 @@ -213,14 +216,31 @@ def test_non_json_error_keeps_whole_body(self) -> None: with pytest.raises(ResponseError) as exc_info: server.credentials().access_token(_OPTIONS) assert (exc_info.value.status_code, exc_info.value.body) == (502, body) - assert not hasattr(exc_info.value, "__notes__") + assert exc_info.value.__notes__ == [_CONTEXT] def test_other_error_status(self) -> None: server = _Server() server.exchange_response = _error_response(429, '{"error":"rate_limited"}') with pytest.raises(ResponseError, match="HTTP 429") as exc_info: server.credentials().access_token(_OPTIONS) - assert not hasattr(exc_info.value, "__notes__") + assert exc_info.value.__notes__ == [_CONTEXT] + + def test_ignores_the_http_clients_own_auth(self) -> None: + class Leaky(httpx.Auth): + def auth_flow(self, request): + request.headers["Authorization"] = "Bearer other-client" + yield request + + server = _Server() + credentials = WorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=lambda: "idp-jwt", + base_url_override=_BASE_URL, + http_client_override=httpx.Client( + auth=Leaky(), transport=httpx.MockTransport(server.handle) + ), + ) + assert credentials.access_token(_OPTIONS).token == "access-1" def test_does_not_follow_redirects(self) -> None: server = _Server() @@ -251,9 +271,26 @@ def test_exchange_timeout(self) -> None: base_url_override=f"http://{host}:{port}", exchange_timeout=timedelta(milliseconds=100), ) - with pytest.raises(httpx.TimeoutException): + with pytest.raises((TimeoutError, httpx.TimeoutException)): credentials.access_token(_OPTIONS) + def test_exchange_timeout_bounds_the_provider(self) -> None: + release = threading.Event() + + def identity_token() -> str: + release.wait() + return "late" + + credentials = _Server().credentials( + identity_token=identity_token, + exchange_timeout=timedelta(milliseconds=50), + ) + try: + with pytest.raises(TimeoutError, match="timed out after"): + credentials.access_token(_OPTIONS) + finally: + release.set() + @pytest.mark.parametrize( ("body", "match"), [ @@ -363,6 +400,15 @@ async def identity_token() -> str: with pytest.raises(TimeoutError, match="timed out"): await credentials.access_token(_OPTIONS) + @pytest.mark.asyncio + async def test_providers_own_timeout_is_not_relabeled(self) -> None: + async def identity_token() -> str: + raise TimeoutError("idp unreachable") + + credentials = _Server().async_credentials(identity_token=identity_token) + with pytest.raises(TimeoutError, match="idp unreachable"): + await credentials.access_token(_OPTIONS) + @pytest.mark.asyncio async def test_invalid_grant_is_explained(self) -> None: server = _Server() @@ -372,8 +418,9 @@ async def test_invalid_grant_is_explained(self) -> None: with pytest.raises(ResponseError) as exc_info: await server.async_credentials().access_token(_OPTIONS) assert exc_info.value.status_code == 400 - (note,) = exc_info.value.__notes__ - assert "trust rule rule-1" in note + context, hint = exc_info.value.__notes__ + assert context == _CONTEXT + assert "trust rule rule-1" in hint @pytest.mark.asyncio @pytest.mark.parametrize( @@ -382,8 +429,16 @@ async def test_invalid_grant_is_explained(self) -> None: (httpx.Response(200, text=""), "unexpected content type"), (httpx.Response(200, json=["a"]), "validation error"), ( - httpx.Response(200, json={"access_token": "a", "token_type": "Bearer"}), - "expires_in", + httpx.Response( + 200, + json={ + "access_token": "a", + "token_type": "Bearer", + "expires_in": 0, + "issued_token_type": _ACCESS_TOKEN_TYPE, + }, + ), + "invalid expires_in", ), ], ) From f1056db59abb7a4297dab40fe9649255b91bdba2 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Fri, 20 Nov 2026 11:27:36 -0500 Subject: [PATCH 11/14] Match Go on empty api_key and identity token error context - An empty api_key next to credentials counts as unset, as in Go. - Identity token provider and file errors get the same trust rule note as other exchange failures. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_token_auth.py | 3 ++- baseten/client/_workload_identity.py | 34 +++++++++++++------------- tests/client/test_workload_identity.py | 12 +++++++-- 3 files changed, 29 insertions(+), 20 deletions(-) diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py index 52df75b..e7c03b0 100644 --- a/baseten/client/_token_auth.py +++ b/baseten/client/_token_auth.py @@ -430,7 +430,8 @@ def check_client_auth( headers: Mapping[str, str] | None, ) -> None: """Check that a client is given exactly one way to authenticate.""" - if api_key is not None and credentials is not None: + # An empty api_key next to credentials counts as unset, as in Go. + if api_key and credentials is not None: raise ValueError("api_key and credentials are mutually exclusive") if api_key is None and credentials is None: raise ValueError("one of api_key or credentials is required") diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index fb636ea..10a99ca 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -275,14 +275,14 @@ def run() -> None: return result def _exchange_once(self) -> AccessToken: - if self._identity_token is not None: - identity_token = self._identity_token() - else: - identity_token = self._exchange.read_identity_token_file() - request = self._exchange.request(identity_token) - # Taken before sending, so the computed expiry errs early. - issued_at = self._now() try: + if self._identity_token is not None: + identity_token = self._identity_token() + else: + identity_token = self._exchange.read_identity_token_file() + request = self._exchange.request(identity_token) + # Taken before sending, so the computed expiry errs early. + issued_at = self._now() if self._http_client is not None: response = ApiClient( self._http_client, **self._exchange.api_kwargs() @@ -359,17 +359,17 @@ async def _exchange_token(self) -> AccessToken: ) from e async def _exchange_once(self) -> AccessToken: - if self._identity_token is not None: - identity_token = await self._identity_token() - else: - # Off the event loop, since the file system can be slow. - identity_token = await asyncio.to_thread( - self._exchange.read_identity_token_file - ) - request = self._exchange.request(identity_token) - # Taken before sending, so the computed expiry errs early. - issued_at = self._now() try: + if self._identity_token is not None: + identity_token = await self._identity_token() + else: + # Off the event loop, since the file system can be slow. + identity_token = await asyncio.to_thread( + self._exchange.read_identity_token_file + ) + request = self._exchange.request(identity_token) + # Taken before sending, so the computed expiry errs early. + issued_at = self._now() if self._http_client is not None: response = await AsyncApiClient( self._http_client, **self._exchange.api_kwargs() diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index befe3a1..bb0c87b 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -225,6 +225,14 @@ def test_other_error_status(self) -> None: server.credentials().access_token(_OPTIONS) assert exc_info.value.__notes__ == [_CONTEXT] + def test_identity_token_errors_note_the_trust_rule(self) -> None: + def identity_token() -> str: + raise OSError("idp unreachable") + + with pytest.raises(OSError, match="idp unreachable") as exc_info: + _Server().credentials(identity_token=identity_token).access_token(_OPTIONS) + assert exc_info.value.__notes__ == [_CONTEXT] + def test_ignores_the_http_clients_own_auth(self) -> None: class Leaky(httpx.Auth): def auth_flow(self, request): @@ -614,8 +622,8 @@ def test_validates_auth_options(self) -> None: credentials = _Server().credentials() with pytest.raises(ValueError, match="mutually exclusive"): ManagementClient(api_key="k", credentials=credentials) - with pytest.raises(ValueError, match="mutually exclusive"): - ManagementClient(api_key="", credentials=credentials) + # An empty api_key counts as unset, as in Go. + ManagementClient(api_key="", credentials=credentials).close() with pytest.raises(ValueError, match="required"): ManagementClient() for name in ["Authorization", "authorization"]: From ee8b5a62fdcabe52fdc7e19f5d054df5b0ce644e Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Fri, 20 Nov 2026 17:36:43 -0500 Subject: [PATCH 12/14] Address review: keyword-only token dataclasses, record a refused token under the lock, plain trust rule check Co-Authored-By: Claude Opus 5.5 --- baseten/client/_token_auth.py | 7 ++++--- baseten/client/_workload_identity.py | 2 +- tests/client/test_workload_identity.py | 1 - 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py index e7c03b0..450ebf7 100644 --- a/baseten/client/_token_auth.py +++ b/baseten/client/_token_auth.py @@ -17,7 +17,7 @@ import httpx -@dataclass(frozen=True) +@dataclass(frozen=True, kw_only=True) class AccessToken: """A short-lived Baseten access token, sent as ``Authorization: Bearer``.""" @@ -28,7 +28,7 @@ class AccessToken: """When the token expires.""" -@dataclass(frozen=True) +@dataclass(frozen=True, kw_only=True) class AccessTokenOptions: """What :class:`Credentials` are told about the token they are asked for.""" @@ -338,7 +338,8 @@ def sync_auth_flow( # The request is not sent again, since it may have side effects; only # the next request gets a new token. if refused_by_baseten(response): - self._refused = token + with self._refused_lock: + self._refused = token class AsyncCredentialsAuth(httpx.Auth): diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 10a99ca..93bce3d 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -63,7 +63,7 @@ def __init__( ) if identity_token_file is not None and os.fspath(identity_token_file) == "": raise ValueError("identity_token_file must not be empty") - if trust_rule_id.strip() == "": + if not trust_rule_id: raise ValueError("trust_rule_id is required") if refresh_leeway < timedelta(0): raise ValueError("refresh_leeway must not be negative") diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index bb0c87b..a10dac2 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -330,7 +330,6 @@ def test_malformed_success(self, body: dict[str, object], match: str) -> None: {"trust_rule_id": "r"}, {"trust_rule_id": "r", "identity_token_file": "/f", "identity_token": str}, {"trust_rule_id": "", "identity_token": str}, - {"trust_rule_id": " ", "identity_token": str}, {"trust_rule_id": "r", "identity_token_file": ""}, { "trust_rule_id": "r", From 62be2e1e68e879e039e831a9b9a24bf13aa14f17 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Fri, 20 Nov 2026 17:54:05 -0500 Subject: [PATCH 13/14] Drop the exchange timeout option and the exchange thread The exchange's HTTP request times out after a fixed 10 seconds, as in Go. Co-Authored-By: Claude Opus 5.5 --- baseten/client/_workload_identity.py | 74 +++----------------------- tests/client/test_workload_identity.py | 52 ++---------------- 2 files changed, 12 insertions(+), 114 deletions(-) diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 93bce3d..98531cd 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -1,10 +1,8 @@ from __future__ import annotations import asyncio -import contextvars import json import os -import threading from collections.abc import Awaitable, Callable from datetime import datetime, timedelta from pathlib import Path @@ -36,6 +34,8 @@ # The exchange takes an RFC 8693 request naming the trust rule as its audience. _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" _JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" +# As in the Go SDK. httpx applies it to each phase of the request. +_EXCHANGE_TIMEOUT = httpx.Timeout(10) IdentityTokenProvider: TypeAlias = Callable[[], str] """Returns the identity provider's JWT. Called on every exchange.""" @@ -55,7 +55,6 @@ def __init__( has_identity_token: bool, base_url_override: str | None, refresh_leeway: timedelta, - exchange_timeout: timedelta, ) -> None: if (identity_token_file is None) == (not has_identity_token): raise ValueError( @@ -67,8 +66,6 @@ def __init__( raise ValueError("trust_rule_id is required") if refresh_leeway < timedelta(0): raise ValueError("refresh_leeway must not be negative") - if exchange_timeout <= timedelta(0): - raise ValueError("exchange_timeout must be positive") self.trust_rule_id = trust_rule_id self.identity_token_file = ( None if identity_token_file is None else Path(identity_token_file) @@ -77,8 +74,6 @@ def __init__( "/" ) self.base_url = base_url - self.timeout_sec = exchange_timeout.total_seconds() - self.timeout = httpx.Timeout(self.timeout_sec) self.headers = with_user_agent({}) def read_identity_token_file(self) -> str: @@ -105,7 +100,7 @@ def api_kwargs(self) -> dict[str, Any]: return { "base_url": self.base_url, "headers": self.headers, - "timeout": self.timeout, + "timeout": _EXCHANGE_TIMEOUT, "auth": _NO_AUTH, } @@ -177,7 +172,10 @@ class WorkloadIdentityCredentials: and replaced shortly before it expires. Safe for use from several threads; concurrent callers share one exchange. Everything is passed explicitly; no environment variables are read. A refused exchange raises - :class:`baseten.client.managementapi.ResponseError`. + :class:`baseten.client.managementapi.ResponseError`. Only the exchange's + HTTP request has a timeout, of 10 seconds; *identity_token* and reading + *identity_token_file* have none, so a caller that needs the whole call + bounded sets its own deadline. """ def __init__( @@ -188,7 +186,6 @@ def __init__( identity_token: IdentityTokenProvider | None = None, base_url_override: str | None = None, refresh_leeway: timedelta = timedelta(minutes=5), - exchange_timeout: timedelta = timedelta(seconds=10), http_client_override: httpx.Client | None = None, ) -> None: """Validate the options. Baseten is not contacted until first use. @@ -211,10 +208,6 @@ def __init__( refresh_leeway: How long before expiry the access token is replaced, capped at half the token's lifetime so a short-lived token is still reused. - exchange_timeout: Bounds one whole exchange, including - *identity_token* and reading *identity_token_file*, which - every caller waiting for a token shares. An exchange that - overruns is abandoned on its own thread. http_client_override: HTTP client to send the exchange with. ``None`` uses a new one per exchange. It should not follow redirects, since the request body carries the identity token. @@ -225,7 +218,6 @@ def __init__( has_identity_token=identity_token is not None, base_url_override=base_url_override, refresh_leeway=refresh_leeway, - exchange_timeout=exchange_timeout, ) self._identity_token = identity_token self._http_client = http_client_override @@ -244,37 +236,6 @@ def access_token(self, options: AccessTokenOptions) -> AccessToken: return self._cache.token() def _exchange_token(self) -> AccessToken: - # httpx bounds each phase of a request rather than the whole of it, and - # nothing bounds the identity token provider, so the exchange runs on - # its own thread and is abandoned when it overruns. - done = threading.Event() - outcome: list[AccessToken | BaseException] = [] - - def run() -> None: - try: - outcome.append(self._exchange_once()) - except BaseException as e: # noqa: BLE001 - re-raised on the caller's thread - outcome.append(e) - finally: - done.set() - - threading.Thread( - target=contextvars.copy_context().run, - args=(run,), - name="baseten-workload-identity-exchange", - daemon=True, - ).start() - if not done.wait(self._exchange.timeout_sec): - raise TimeoutError( - "workload identity token exchange timed out after " - f"{self._exchange.timeout_sec}s" - ) - result = outcome[0] - if isinstance(result, BaseException): - raise result - return result - - def _exchange_once(self) -> AccessToken: try: if self._identity_token is not None: identity_token = self._identity_token() @@ -313,21 +274,15 @@ def __init__( identity_token: AsyncIdentityTokenProvider | None = None, base_url_override: str | None = None, refresh_leeway: timedelta = timedelta(minutes=5), - exchange_timeout: timedelta = timedelta(seconds=10), http_client_override: httpx.AsyncClient | None = None, ) -> None: - """Validate the options, as :class:`WorkloadIdentityCredentials` does. - - Here *exchange_timeout* bounds the whole exchange, including - *identity_token* and reading *identity_token_file*. - """ + """Validate the options, as :class:`WorkloadIdentityCredentials` does.""" self._exchange = _Exchange( trust_rule_id=trust_rule_id, identity_token_file=identity_token_file, has_identity_token=identity_token is not None, base_url_override=base_url_override, refresh_leeway=refresh_leeway, - exchange_timeout=exchange_timeout, ) self._identity_token = identity_token self._http_client = http_client_override @@ -346,19 +301,6 @@ async def access_token(self, options: AccessTokenOptions) -> AccessToken: return await self._cache.token() async def _exchange_token(self) -> AccessToken: - try: - async with asyncio.timeout(self._exchange.timeout_sec) as deadline: - return await self._exchange_once() - except TimeoutError as e: - # A TimeoutError of the provider's own is not the exchange's. - if not deadline.expired(): - raise - raise TimeoutError( - "workload identity token exchange timed out after " - f"{self._exchange.timeout_sec}s" - ) from e - - async def _exchange_once(self) -> AccessToken: try: if self._identity_token is not None: identity_token = await self._identity_token() diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index a10dac2..5a86b73 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -3,7 +3,6 @@ import asyncio import json import socket -import threading from collections.abc import Callable from datetime import UTC, datetime, timedelta from pathlib import Path @@ -20,6 +19,7 @@ InferenceClient, ManagementClient, WorkloadIdentityCredentials, + _workload_identity, ) from baseten.client.managementapi import ResponseError @@ -267,7 +267,8 @@ def test_does_not_follow_redirects(self) -> None: credentials.access_token(_OPTIONS) assert server.assertions == ["idp-jwt"] - def test_exchange_timeout(self) -> None: + def test_exchange_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(_workload_identity, "_EXCHANGE_TIMEOUT", httpx.Timeout(0.1)) # Accepts the connection but never answers it. with socket.socket() as listener: listener.bind(("127.0.0.1", 0)) @@ -277,28 +278,10 @@ def test_exchange_timeout(self) -> None: trust_rule_id="rule-1", identity_token=lambda: "idp-jwt", base_url_override=f"http://{host}:{port}", - exchange_timeout=timedelta(milliseconds=100), ) - with pytest.raises((TimeoutError, httpx.TimeoutException)): + with pytest.raises(httpx.TimeoutException): credentials.access_token(_OPTIONS) - def test_exchange_timeout_bounds_the_provider(self) -> None: - release = threading.Event() - - def identity_token() -> str: - release.wait() - return "late" - - credentials = _Server().credentials( - identity_token=identity_token, - exchange_timeout=timedelta(milliseconds=50), - ) - try: - with pytest.raises(TimeoutError, match="timed out after"): - credentials.access_token(_OPTIONS) - finally: - release.set() - @pytest.mark.parametrize( ("body", "match"), [ @@ -331,11 +314,6 @@ def test_malformed_success(self, body: dict[str, object], match: str) -> None: {"trust_rule_id": "r", "identity_token_file": "/f", "identity_token": str}, {"trust_rule_id": "", "identity_token": str}, {"trust_rule_id": "r", "identity_token_file": ""}, - { - "trust_rule_id": "r", - "identity_token": str, - "exchange_timeout": timedelta(0), - }, { "trust_rule_id": "r", "identity_token": str, @@ -394,28 +372,6 @@ async def identity_token() -> str: with pytest.raises(asyncio.CancelledError): await cancelled - @pytest.mark.asyncio - async def test_exchange_timeout(self) -> None: - async def identity_token() -> str: - await asyncio.Event().wait() - return "never" - - credentials = _Server().async_credentials( - identity_token=identity_token, - exchange_timeout=timedelta(milliseconds=10), - ) - with pytest.raises(TimeoutError, match="timed out"): - await credentials.access_token(_OPTIONS) - - @pytest.mark.asyncio - async def test_providers_own_timeout_is_not_relabeled(self) -> None: - async def identity_token() -> str: - raise TimeoutError("idp unreachable") - - credentials = _Server().async_credentials(identity_token=identity_token) - with pytest.raises(TimeoutError, match="idp unreachable"): - await credentials.access_token(_OPTIONS) - @pytest.mark.asyncio async def test_invalid_grant_is_explained(self) -> None: server = _Server() From 2ff83bb0fece9d2e2ea2fa714d58ab990be73963 Mon Sep 17 00:00:00 2001 From: Mingming Lang Date: Fri, 20 Nov 2026 19:10:48 -0500 Subject: [PATCH 14/14] Pass the identity token provider a context object So fields can be added later without breaking providers. Co-Authored-By: Claude Opus 5.5 --- baseten/client/__init__.py | 2 ++ baseten/client/_workload_identity.py | 24 +++++++++++++++++++----- tests/client/test_workload_identity.py | 25 ++++++++++++++++++------- 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/baseten/client/__init__.py b/baseten/client/__init__.py index cd7135d..9e3f193 100644 --- a/baseten/client/__init__.py +++ b/baseten/client/__init__.py @@ -35,6 +35,7 @@ AsyncIdentityTokenProvider, AsyncWorkloadIdentityCredentials, IdentityTokenProvider, + IdentityTokenProviderContext, WorkloadIdentityCredentials, ) @@ -49,6 +50,7 @@ "AsyncWorkloadIdentityCredentials", "Credentials", "IdentityTokenProvider", + "IdentityTokenProviderContext", "InferenceClient", "InferenceClientOptions", "ManagementClient", diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py index 98531cd..e082b96 100644 --- a/baseten/client/_workload_identity.py +++ b/baseten/client/_workload_identity.py @@ -4,6 +4,7 @@ import json import os from collections.abc import Awaitable, Callable +from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path from typing import Any, TypeAlias @@ -37,10 +38,21 @@ # As in the Go SDK. httpx applies it to each phase of the request. _EXCHANGE_TIMEOUT = httpx.Timeout(10) -IdentityTokenProvider: TypeAlias = Callable[[], str] + +@dataclass(frozen=True, kw_only=True) +class IdentityTokenProviderContext: + """Passed to an :data:`IdentityTokenProvider`. + + Empty for now; fields may be added in later versions. + """ + + +IdentityTokenProvider: TypeAlias = Callable[[IdentityTokenProviderContext], str] """Returns the identity provider's JWT. Called on every exchange.""" -AsyncIdentityTokenProvider: TypeAlias = Callable[[], Awaitable[str]] +AsyncIdentityTokenProvider: TypeAlias = Callable[ + [IdentityTokenProviderContext], Awaitable[str] +] """Async form of :data:`IdentityTokenProvider`.""" @@ -199,7 +211,7 @@ def __init__( Exactly one of *identity_token_file* and *identity_token* is required. identity_token: Returns the identity provider's JWT. Called on - every exchange. + every exchange with an :class:`IdentityTokenProviderContext`. base_url_override: Management API base URL the exchange is sent to. ``None`` uses :meth:`ManagementClient.default_base_url`. Must point at the same Baseten environment as the clients @@ -238,7 +250,7 @@ def access_token(self, options: AccessTokenOptions) -> AccessToken: def _exchange_token(self) -> AccessToken: try: if self._identity_token is not None: - identity_token = self._identity_token() + identity_token = self._identity_token(IdentityTokenProviderContext()) else: identity_token = self._exchange.read_identity_token_file() request = self._exchange.request(identity_token) @@ -303,7 +315,9 @@ async def access_token(self, options: AccessTokenOptions) -> AccessToken: async def _exchange_token(self) -> AccessToken: try: if self._identity_token is not None: - identity_token = await self._identity_token() + identity_token = await self._identity_token( + IdentityTokenProviderContext() + ) else: # Off the event loop, since the file system can be slow. identity_token = await asyncio.to_thread( diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py index 5a86b73..aaf9cd8 100644 --- a/tests/client/test_workload_identity.py +++ b/tests/client/test_workload_identity.py @@ -16,6 +16,7 @@ AsyncInferenceClient, AsyncManagementClient, AsyncWorkloadIdentityCredentials, + IdentityTokenProviderContext, InferenceClient, ManagementClient, WorkloadIdentityCredentials, @@ -86,7 +87,7 @@ async def handle_async(self, request: httpx.Request) -> httpx.Response: def credentials(self, **kwargs) -> WorkloadIdentityCredentials: kwargs.setdefault("trust_rule_id", "rule-1") if "identity_token_file" not in kwargs: - kwargs.setdefault("identity_token", lambda: "idp-jwt") + kwargs.setdefault("identity_token", lambda _: "idp-jwt") return WorkloadIdentityCredentials( base_url_override=_BASE_URL, http_client_override=httpx.Client( @@ -98,7 +99,7 @@ def credentials(self, **kwargs) -> WorkloadIdentityCredentials: def async_credentials(self, **kwargs) -> AsyncWorkloadIdentityCredentials: kwargs.setdefault("trust_rule_id", "rule-1") - async def identity_token() -> str: + async def identity_token(_: IdentityTokenProviderContext) -> str: return "idp-jwt" if "identity_token_file" not in kwargs: @@ -225,8 +226,18 @@ def test_other_error_status(self) -> None: server.credentials().access_token(_OPTIONS) assert exc_info.value.__notes__ == [_CONTEXT] + def test_identity_token_is_given_a_context(self) -> None: + received: list[object] = [] + + def identity_token(context: IdentityTokenProviderContext) -> str: + received.append(context) + return "idp-jwt" + + _Server().credentials(identity_token=identity_token).access_token(_OPTIONS) + assert received == [IdentityTokenProviderContext()] + def test_identity_token_errors_note_the_trust_rule(self) -> None: - def identity_token() -> str: + def identity_token(_: IdentityTokenProviderContext) -> str: raise OSError("idp unreachable") with pytest.raises(OSError, match="idp unreachable") as exc_info: @@ -242,7 +253,7 @@ def auth_flow(self, request): server = _Server() credentials = WorkloadIdentityCredentials( trust_rule_id="rule-1", - identity_token=lambda: "idp-jwt", + identity_token=lambda _: "idp-jwt", base_url_override=_BASE_URL, http_client_override=httpx.Client( auth=Leaky(), transport=httpx.MockTransport(server.handle) @@ -257,7 +268,7 @@ def test_does_not_follow_redirects(self) -> None: ) credentials = WorkloadIdentityCredentials( trust_rule_id="rule-1", - identity_token=lambda: "idp-jwt", + identity_token=lambda _: "idp-jwt", base_url_override=_BASE_URL, http_client_override=httpx.Client( transport=httpx.MockTransport(server.handle) @@ -276,7 +287,7 @@ def test_exchange_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None: host, port = listener.getsockname() credentials = WorkloadIdentityCredentials( trust_rule_id="rule-1", - identity_token=lambda: "idp-jwt", + identity_token=lambda _: "idp-jwt", base_url_override=f"http://{host}:{port}", ) with pytest.raises(httpx.TimeoutException): @@ -358,7 +369,7 @@ async def test_cancelled_waiter_does_not_cancel_exchange(self) -> None: server = _Server() release = asyncio.Event() - async def identity_token() -> str: + async def identity_token(_: IdentityTokenProviderContext) -> str: await release.wait() return "idp-jwt"