platform_credentials.py
1"""Model credential lookups for Platform."""23from __future__ import annotations4from typing import (5 TYPE_CHECKING,6 Optional,7 Union,8)9from .api_types import (10 CredentialPersistence,11)12from sim_platform.domain.models import ContractError1314if TYPE_CHECKING:15 from sim_platform.market.playback import MarketPlayback16 from sim_platform.market.prepared.session import PreparedSession17 from sim_platform.models.contracts import ModelProfile, ModelProvider18 from sim_platform.models.credentials import CredentialStore19 from sim_platform.research.agent_controller import AgentResearchController2021 MarketInput = Union[MarketPlayback, PreparedSession]2223from .platform_base import PlatformBase, PathInput242526class PlatformCredentials(PlatformBase):27 """Model credential lookups for Platform."""2829 def _credential_store(self) -> CredentialStore:30 """Get the local store used to look up model API keys by reference name.3132 The first call creates it and selects macOS Keychain when available. This does not33 read a key yet. Platform keeps the store for later credential calls.3435 Returns:36 CredentialStore: Existing or newly allocated local store; no key lookup occurs here.3738 Raises:39 ContractError: If an identity, configuration or lifecycle precondition is invalid.40 """41 self._resources.check_open()42 if self._credentials is None:43 from sim_platform.models.credentials import CredentialStore44 import sys4546 backend = None47 if sys.platform == 'darwin':48 from sim_platform.models.keychain import MacOSKeychain4950 backend = MacOSKeychain()51 self._credentials = CredentialStore(backend)52 return self._credentials5354 def set_model_credential(55 self, reference: str, secret: str, *, persistence: CredentialPersistence = 'session'56 ) -> None:57 """Give the platform an API key that an agent can use to call a model.5859 Choose a reference name, such as 'my-model-key'. Model settings use that name rather60 than including the key itself. With persistence='session', the key stays in this61 Platform's memory until deletion or close. With 'os', it is saved in the supported62 system credential store, currently macOS Keychain.6364 The key is not written into run settings, SQLite, logs or exports. Accessing the65 system credential store can take time and may fail with a system-specific error.6667 Args:68 reference: Local credential reference; the reference itself is safe to save in model69 configuration.70 secret: Nonempty API key material supplied by the user; not a reference or file71 path.72 persistence: session for Platform-owned memory; os for an available OS credential73 backend.7475 Returns:76 None. A later model setup resolves reference to the selected key.7778 Raises:79 ContractError: If an identity, configuration or lifecycle precondition is invalid.8081 Example:82 app.set_model_credential('personal', secret_from_user, persistence='session')83 """84 self._credential_store().put(reference, secret, persistence=persistence)8586 def load_model_credential(87 self,88 reference: str,89 path: PathInput,90 *,91 variable: str = 'OPENAI_API_KEY',92 persistence: CredentialPersistence = 'session',93 ) -> None:94 """Load one API key from a file into the platform's credential store.9596 Use this for a local .env-style workflow. Choose the file, the variable containing97 the key, and the reference name that model settings will use. Only that variable is98 read. The file is not executed or changed, and other variables are not imported.99100 After loading, the key is handled just like set_model_credential(): keep it in101 memory for this session or save it in the supported system credential store.102103 Args:104 reference: Local credential reference; the reference itself is safe to save in model105 configuration.106 path: Explicit credential file path; only variable is extracted.107 variable: Exact variable name to extract from the selected credential file.108 persistence: session for Platform-owned memory; os for an available OS credential109 backend.110111 Returns:112 None. The extracted key is stored under reference using the chosen persistence.113114 Raises:115 ContractError: If the variable/file syntax or key is invalid, or storage is unavailable.116 OSError: If the selected file cannot be read.117118 Example:119 app.load_model_credential('personal', env_path, variable='OPENAI_API_KEY')120 """121 from sim_platform.models.credential_file import read_credential122123 self.set_model_credential(124 reference, read_credential(path, variable), persistence=persistence125 )126127 def check_model_credential(self, reference: str) -> None:128 """Confirm that an API key is available under this reference name.129130 Use this before starting an Agent that relies on a key saved earlier, for example131 one kept in the system credential store by a previous session. Nothing is stored or132 changed, and the key is not returned. A key set for this session is found first;133 otherwise the supported system credential store is asked for it, which may make the134 operating system ask the user for permission.135136 Args:137 reference: Local credential reference; the reference itself is safe to save in model138 configuration.139140 Returns:141 None. Returning means a usable key exists under reference.142143 Raises:144 ContractError: If no key is stored under reference, the stored value is unusable,145 or the system credential store cannot be read.146147 Example:148 app.check_model_credential('personal')149 """150 self._credential_store().get(reference)151152 def delete_model_credential(self, reference: str) -> None:153 """Remove a stored API key using its reference name.154155 Use this when the user removes a model credential from the app. It removes the local156 stored value, not the key at the model provider. A running agent may already have a157 copy; stop and close that experiment to release its process.158159 System-store deletion follows the backend's missing-entry and error behavior. Asking160 for system storage when no supported backend exists raises ContractError.161162 Args:163 reference: Local credential reference; the reference itself is safe to save in model164 configuration.165166 Returns:167 None. Session material is removed, or deletion is delegated to the OS store.168169 Raises:170 ContractError: If an identity, configuration or lifecycle precondition is invalid.171172 Example:173 app.delete_model_credential('personal')174 """175 self._credential_store().delete(reference)176177 def configure_experiment_model(178 self,179 experiment: AgentResearchController,180 profile: ModelProfile,181 *,182 provider: Optional[ModelProvider] = None,183 ) -> ModelProfile:184 """Set up the model and API key that a prepared agent experiment can use.185186 Call this once after creating the agent experiment and before Play. experiment must187 be a ready agent controller from this Platform. profile is a ModelProfile describing188 the model; it is not the user profile ID used by account methods. Its credential_ref189 selects a key previously stored on this Platform.190191 The provider setup and selected key are passed to the Agent process, where model192 requests run. The default provider follows ``profile.provider``: OpenAIResponses for193 'openai-responses', or OpenAICompatibleChat for a local 'openai-compatible' server194 (vLLM, Ollama, llama.cpp) at ``profile.base_url``, which must be on this machine or195 a private network so no data leaves the premises. A custom provider must offer196 async request(); request_received() can additionally report when the raw reply arrives.197 For integration='configured', the built-in template uses this model to run its198 prompt/tool loop after Play. Grant model.request and control.finish in the199 experiment settings; grant control.wait if waiting should be available. Custom200 trusted programs still control their own loop.201202 Args:203 experiment: Ready AgentResearchController created by this Platform; bind before204 Play.205 profile: ModelProfile containing provider/model/credential_ref and network/output206 bounds; not a user profile ID.207 provider: Optional trusted async provider adapter; None selects the built-in208 adapter for ``profile.provider``.209210 Returns:211 ModelProfile: The same supplied profile object. The experiment remains ready; no212 model request is sent.213214 Raises:215 ContractError: If an identity, configuration or lifecycle precondition is invalid.216217 Example:218 from sim_platform.models.contracts import ModelProfile219 model = ModelProfile('openai-responses', model_name, 'personal')220 app.configure_experiment_model(experiment, model)221 experiment.play()222 # Or a local server, with no key and nothing sent off this machine:223 # ModelProfile('openai-compatible', 'qwen2.5:7b',224 # base_url='http://127.0.0.1:11434/v1')225 """226 from sim_platform.models.contracts import ModelProfile227 from sim_platform.models.providers.local import default_provider228 from sim_platform.decisions.agent.runner import AgentDecisionRunner229230 if (231 experiment.app is not self._operations232 or not isinstance(profile, ModelProfile)233 or not isinstance(experiment.runner, AgentDecisionRunner)234 or experiment.runner.pipeline.snapshot()['state'] != 'ready'235 ):236 raise ContractError('configure a ready Agent experiment owned by this Platform')237 if provider is None and profile.provider == 'openai-responses':238 from sim_platform.network import require_network239240 require_network('the hosted OpenAI provider')241 runner = experiment.runner242 if runner.model_configured:243 raise ContractError('model requires live mode and one model binding')244 # A local server without a key has no credential to look up.245 secret = (246 self._credential_store().get(profile.credential_ref) if profile.credential_ref else ''247 )248 runner.bind_local_model(profile, secret, provider or default_provider(profile))249 return profile