Function: dynamicKey()
@providerprotocol/ai / @providerprotocol/ai / dynamicKey
Function: dynamicKey()
Section titled “Function: dynamicKey()”dynamicKey(
selector):KeyStrategy
Defined in: src/http/keys.ts:144
Creates a key strategy that delegates key selection to a user-provided function, enabling advanced scenarios such as:
- Fetching keys from a secrets manager (AWS Secrets Manager, HashiCorp Vault)
- Rotating keys based on external state or configuration
- Selecting keys based on request context or time of day
- Implementing custom load balancing algorithms
The selector function can be synchronous or asynchronous.
Parameters
Section titled “Parameters”selector
Section titled “selector”() => string | Promise<string>
Function that returns an API key (sync or async)
Returns
Section titled “Returns”A KeyStrategy that delegates to the selector function
Example
Section titled “Example”// Fetch key from environment based on current modeconst envKey = dynamicKey(() => { return process.env.NODE_ENV === 'production' ? process.env.PROD_API_KEY! : process.env.DEV_API_KEY!;});
// Async key fetching from a secrets managerconst vaultKey = dynamicKey(async () => { const secret = await vault.read('secret/openai'); return secret.data.apiKey;});
// Time-based key rotationconst timedKey = dynamicKey(() => { const hour = new Date().getHours(); return hour < 12 ? morningKey : afternoonKey;});