-
Notifications
You must be signed in to change notification settings - Fork 666
[feat] Seed starter credits at signup via budget-capped proxy keys (EE) #6138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import re | ||
| from typing import Any, Optional | ||
|
|
||
| import httpx | ||
|
|
||
| from ee.src.core.starter_credits_bridge.types import ( | ||
| KeyAliasExistsError, | ||
| MintedKey, | ||
| ProxyRequestError, | ||
| ) | ||
|
|
||
| _REQUEST_TIMEOUT_SECONDS = 10.0 | ||
|
|
||
| _KEY_PATTERN = re.compile(r"sk-[A-Za-z0-9_\-]+") | ||
|
|
||
|
|
||
| class StarterCreditsProxyClient: | ||
| """Admin client for the starter-credits proxy (mint / block keys, team info). | ||
|
|
||
| Authenticates with the master key, which must never leave the backend. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| base_url: str, | ||
| master_key: str, | ||
| transport: Optional[httpx.AsyncBaseTransport] = None, | ||
| ): | ||
| self._base_url = base_url.rstrip("/") | ||
| self._master_key = master_key | ||
| self._transport = transport | ||
|
|
||
| def _http_client(self) -> httpx.AsyncClient: | ||
| return httpx.AsyncClient( | ||
| headers={"Authorization": f"Bearer {self._master_key}"}, | ||
| timeout=_REQUEST_TIMEOUT_SECONDS, | ||
| transport=self._transport, | ||
| ) | ||
|
|
||
| async def generate_key( | ||
| self, | ||
| *, | ||
| key_alias: str, | ||
| max_budget: float, | ||
| models: list[str], | ||
| metadata: dict[str, Any], | ||
| team_id: str, | ||
| max_parallel_requests: Optional[int] = None, | ||
| rpm_limit: Optional[int] = None, | ||
| tpm_limit: Optional[int] = None, | ||
| ) -> MintedKey: | ||
| body: dict[str, Any] = { | ||
| "key_alias": key_alias, | ||
| "max_budget": max_budget, | ||
| # An explicit list always; an omitted list would mean "any model". | ||
| "models": models, | ||
| "metadata": metadata, | ||
| # Always under the program team so its ceiling bounds total exposure. | ||
| "team_id": team_id, | ||
| } | ||
| if max_parallel_requests is not None: | ||
| body["max_parallel_requests"] = max_parallel_requests | ||
| if rpm_limit is not None: | ||
| body["rpm_limit"] = rpm_limit | ||
| if tpm_limit is not None: | ||
| body["tpm_limit"] = tpm_limit | ||
|
|
||
| payload = await self._request("POST", "/key/generate", json=body) | ||
|
|
||
| key = payload.get("key") if isinstance(payload, dict) else None | ||
| if not isinstance(key, str) or not key: | ||
| raise ProxyRequestError( | ||
| status_code=200, | ||
| detail="key generation response carried no key", | ||
| ) | ||
|
|
||
| return MintedKey(key=key, key_alias=key_alias) | ||
|
|
||
| async def get_team_info(self, *, team_id: str) -> dict[str, Any]: | ||
| payload = await self._request("GET", "/team/info", params={"team_id": team_id}) | ||
| return payload if isinstance(payload, dict) else {} | ||
|
|
||
| async def block_key(self, *, key: str) -> None: | ||
| await self._request("POST", "/key/block", json={"key": key}) | ||
|
|
||
| async def _request( | ||
| self, | ||
| method: str, | ||
| path: str, | ||
| *, | ||
| json: Optional[dict[str, Any]] = None, | ||
| params: Optional[dict[str, Any]] = None, | ||
| ) -> Any: | ||
| try: | ||
| async with self._http_client() as client: | ||
| response = await client.request( | ||
| method, | ||
| f"{self._base_url}{path}", | ||
| json=json, | ||
| params=params, | ||
| ) | ||
| except httpx.HTTPError as exc: | ||
| raise ProxyRequestError( | ||
| status_code=None, | ||
| detail=f"request to {path} failed: {type(exc).__name__}", | ||
| ) from exc | ||
|
|
||
| if response.status_code >= 400: | ||
| # Redact key material before the body can reach logs (a proxy error | ||
| # may echo the failing request, which can carry a virtual key). | ||
| detail = _KEY_PATTERN.sub("sk-[redacted]", response.text)[:300] | ||
| # Only the measured conflict wording may read as "this organization | ||
| # already holds its key"; a validation 400 that merely mentions the | ||
| # alias field must not. | ||
| if ( | ||
| response.status_code == 400 | ||
| and "alias" in detail.lower() | ||
| and "already exists" in detail.lower() | ||
| ): | ||
| raise KeyAliasExistsError( | ||
| status_code=response.status_code, | ||
| detail=detail, | ||
| ) | ||
| raise ProxyRequestError( | ||
| status_code=response.status_code, | ||
| detail=detail, | ||
| ) | ||
|
mmabrouk marked this conversation as resolved.
|
||
|
|
||
| try: | ||
| return response.json() | ||
| except ValueError as exc: | ||
| raise ProxyRequestError( | ||
| status_code=response.status_code, | ||
| detail=f"non-JSON response from {path}", | ||
| ) from exc | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.