|
| 1 | +"""Keycard-minted OpenAI credential for temporalio's OpenAI Agents plugin. |
| 2 | +
|
| 3 | +``OpenAIAgentsPlugin`` runs every model call as a Temporal activity of its |
| 4 | +own, and that activity asks its ``ModelProvider`` for a model on each call. |
| 5 | +Neither ``@grant`` nor :class:`keycardai.temporal.KeycardInterceptor` can |
| 6 | +reach that activity: the plugin registers it and builds its OpenAI client |
| 7 | +before any consumer activity exists. :class:`KeycardOpenAIProvider` closes |
| 8 | +the gap from the provider side. It hands the OpenAI client an async key |
| 9 | +callback instead of a key string, and the client awaits that callback before |
| 10 | +every request it sends. The callback mints the OpenAI key from a vaulted |
| 11 | +Keycard resource with a client-credentials grant and caches it for a short |
| 12 | +``refresh`` window, so a key rotated in Keycard is picked up by the next |
| 13 | +model call after the window closes, with no worker restart. |
| 14 | +
|
| 15 | +Optional dependencies (``openai``, ``agents``) are imported only here, and |
| 16 | +only when a provider is built, so ``import keycardai.temporal`` stays clean |
| 17 | +without the ``openai-agents`` extra. |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import asyncio |
| 23 | +import time |
| 24 | +from datetime import timedelta |
| 25 | +from typing import TYPE_CHECKING, Any |
| 26 | + |
| 27 | +from temporalio import workflow |
| 28 | + |
| 29 | +with workflow.unsafe.imports_passed_through(): |
| 30 | + from keycardai.oauth import AsyncClient |
| 31 | + from keycardai.oauth.server import ApplicationCredential, ClientSecret |
| 32 | + |
| 33 | +from keycardai.temporal import ( |
| 34 | + GrantConfigurationError, |
| 35 | + _raise_for_grant_failure, |
| 36 | + _worker_credential, |
| 37 | +) |
| 38 | + |
| 39 | +if TYPE_CHECKING: |
| 40 | + from agents import Model, ModelProvider |
| 41 | + |
| 42 | + _ProviderBase = ModelProvider |
| 43 | +else: |
| 44 | + # Duck-typed at runtime so this module imports without ``agents``; the |
| 45 | + # plugin only ever calls get_model() and aclose(). |
| 46 | + _ProviderBase = object |
| 47 | + |
| 48 | +__all__ = ["KeycardOpenAIKey", "KeycardOpenAIProvider"] |
| 49 | + |
| 50 | +_MISSING_EXTRA = ( |
| 51 | + "keycardai.temporal.openai_agents needs the OpenAI Agents SDK and the openai " |
| 52 | + "client: install keycardai-temporal[openai-agents] next to " |
| 53 | + "temporalio[openai-agents]." |
| 54 | +) |
| 55 | + |
| 56 | + |
| 57 | +def _openai_deps() -> tuple[Any, Any]: |
| 58 | + """Import the optional dependencies on first use: (OpenAIProvider, AsyncOpenAI).""" |
| 59 | + try: |
| 60 | + from agents.models.openai_provider import OpenAIProvider |
| 61 | + from openai import AsyncOpenAI |
| 62 | + except ImportError as e: |
| 63 | + raise ImportError(_MISSING_EXTRA) from e |
| 64 | + return OpenAIProvider, AsyncOpenAI |
| 65 | + |
| 66 | + |
| 67 | +class KeycardOpenAIKey: |
| 68 | + """Async callable returning the OpenAI key vaulted behind a Keycard resource. |
| 69 | +
|
| 70 | + Shaped for ``openai.AsyncOpenAI(api_key=...)``, which awaits it before |
| 71 | + each request. The key is minted with a client-credentials grant and |
| 72 | + cached for ``refresh`` (bounded by the grant's ``expires_in`` when the |
| 73 | + zone reports a shorter one); concurrent callers on a cold or expired |
| 74 | + cache share one mint. A permanent grant failure raises the same |
| 75 | + non-retryable ``KeycardAccessDenied`` ``ApplicationError`` the |
| 76 | + interceptor raises, so the plugin's model activity fails the same way a |
| 77 | + ``@grant`` activity would; a transient failure propagates as-is and the |
| 78 | + model activity's retry policy governs it. |
| 79 | +
|
| 80 | + Args: |
| 81 | + zone_url: Keycard zone issuer URL. |
| 82 | + resource: Identifier of the vaulted OpenAI key resource in the zone. |
| 83 | + credential: How this application authenticates to the zone; when |
| 84 | + omitted, discovered from the environment exactly as |
| 85 | + :class:`keycardai.temporal.KeycardInterceptor` does. Must be a |
| 86 | + ``ClientSecret`` (the client-credentials path has no bridge for |
| 87 | + assertion credentials yet). |
| 88 | + refresh: How long a minted key is reused before the next call mints |
| 89 | + again. Default five minutes. |
| 90 | +
|
| 91 | + Raises: |
| 92 | + GrantConfigurationError: the credential could not be discovered, or |
| 93 | + is not a ``ClientSecret``. |
| 94 | + """ |
| 95 | + |
| 96 | + def __init__( |
| 97 | + self, |
| 98 | + zone_url: str, |
| 99 | + resource: str, |
| 100 | + credential: ApplicationCredential | None = None, |
| 101 | + *, |
| 102 | + refresh: timedelta = timedelta(minutes=5), |
| 103 | + ) -> None: |
| 104 | + credential = _worker_credential(credential) |
| 105 | + if not isinstance(credential, ClientSecret): |
| 106 | + raise GrantConfigurationError( |
| 107 | + f"{type(self).__name__} for {resource} mints with client " |
| 108 | + "credentials, which requires a ClientSecret credential; the " |
| 109 | + f"worker has {type(credential).__name__}." |
| 110 | + ) |
| 111 | + if refresh <= timedelta(0): |
| 112 | + raise GrantConfigurationError( |
| 113 | + f"{type(self).__name__}: refresh must be positive, got {refresh}." |
| 114 | + ) |
| 115 | + self.resource = resource |
| 116 | + self.refresh = refresh |
| 117 | + self._client = AsyncClient(zone_url, auth=credential.get_http_client_auth()) |
| 118 | + self._key: str | None = None |
| 119 | + self._fresh_until = 0.0 |
| 120 | + self._lock = asyncio.Lock() |
| 121 | + |
| 122 | + def _cached(self) -> str | None: |
| 123 | + if self._key is not None and time.monotonic() < self._fresh_until: |
| 124 | + return self._key |
| 125 | + return None |
| 126 | + |
| 127 | + async def __call__(self) -> str: |
| 128 | + key = self._cached() |
| 129 | + if key is not None: |
| 130 | + return key |
| 131 | + async with self._lock: |
| 132 | + key = self._cached() |
| 133 | + if key is not None: |
| 134 | + return key |
| 135 | + try: |
| 136 | + resp = await self._client.client_credentials_grant( |
| 137 | + resource=self.resource |
| 138 | + ) |
| 139 | + except Exception as e: |
| 140 | + _raise_for_grant_failure(self.resource, e) |
| 141 | + window = self.refresh.total_seconds() |
| 142 | + if resp.expires_in is not None: |
| 143 | + window = min(window, float(resp.expires_in)) |
| 144 | + self._key = resp.access_token |
| 145 | + self._fresh_until = time.monotonic() + window |
| 146 | + return self._key |
| 147 | + |
| 148 | + async def aclose(self) -> None: |
| 149 | + """Close the Keycard client; the next call opens a fresh one.""" |
| 150 | + self._key = None |
| 151 | + self._fresh_until = 0.0 |
| 152 | + await self._client.aclose() |
| 153 | + |
| 154 | + |
| 155 | +class KeycardOpenAIProvider(_ProviderBase): |
| 156 | + """``agents.ModelProvider`` whose OpenAI key comes from Keycard per call. |
| 157 | +
|
| 158 | + Pass it as ``OpenAIAgentsPlugin(model_provider=...)``. Models come from |
| 159 | + the SDK's own ``OpenAIProvider`` over one ``AsyncOpenAI`` client that |
| 160 | + carries a :class:`KeycardOpenAIKey` in place of a key string, so every |
| 161 | + request the plugin's model activity sends first resolves (and, past the |
| 162 | + ``refresh`` window, re-mints) the key. ``max_retries`` on that client |
| 163 | + is 0, as in the plugin's default provider, so the model activity's |
| 164 | + retry policy is the only retry loop. |
| 165 | +
|
| 166 | + The plugin requires an explicit ``start_to_close_timeout`` or |
| 167 | + ``schedule_to_close_timeout`` in ``ModelActivityParameters`` whenever a |
| 168 | + custom provider is set; it only defaults the timeout for its own. |
| 169 | +
|
| 170 | + Args: |
| 171 | + zone_url, resource, credential, refresh: as :class:`KeycardOpenAIKey`. |
| 172 | + base_url: OpenAI-compatible base URL, when not api.openai.com. |
| 173 | + use_responses: Forwarded to ``OpenAIProvider`` (Responses API vs |
| 174 | + Chat Completions); ``None`` keeps the SDK default. |
| 175 | +
|
| 176 | + Raises: |
| 177 | + GrantConfigurationError: as :class:`KeycardOpenAIKey`. |
| 178 | + ImportError: the ``openai-agents`` extra is not installed. |
| 179 | + """ |
| 180 | + |
| 181 | + def __init__( |
| 182 | + self, |
| 183 | + zone_url: str, |
| 184 | + resource: str, |
| 185 | + credential: ApplicationCredential | None = None, |
| 186 | + *, |
| 187 | + refresh: timedelta = timedelta(minutes=5), |
| 188 | + base_url: str | None = None, |
| 189 | + use_responses: bool | None = None, |
| 190 | + ) -> None: |
| 191 | + OpenAIProvider, AsyncOpenAI = _openai_deps() |
| 192 | + self.api_key = KeycardOpenAIKey(zone_url, resource, credential, refresh=refresh) |
| 193 | + self._openai = AsyncOpenAI( |
| 194 | + api_key=self.api_key, base_url=base_url, max_retries=0 |
| 195 | + ) |
| 196 | + self._provider = OpenAIProvider( |
| 197 | + openai_client=self._openai, use_responses=use_responses |
| 198 | + ) |
| 199 | + |
| 200 | + def get_model(self, model_name: str | None) -> Model: |
| 201 | + return self._provider.get_model(model_name) |
| 202 | + |
| 203 | + async def aclose(self) -> None: |
| 204 | + """Release the inner provider, the OpenAI client, and the Keycard client.""" |
| 205 | + await self._provider.aclose() |
| 206 | + await self._openai.close() |
| 207 | + await self.api_key.aclose() |
0 commit comments