Skip to content

Function: dynamicKey()

@providerprotocol/ai


@providerprotocol/ai / @providerprotocol/ai / 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.

() => string | Promise<string>

Function that returns an API key (sync or async)

KeyStrategy

A KeyStrategy that delegates to the selector function

// Fetch key from environment based on current mode
const envKey = dynamicKey(() => {
return process.env.NODE_ENV === 'production'
? process.env.PROD_API_KEY!
: process.env.DEV_API_KEY!;
});
// Async key fetching from a secrets manager
const vaultKey = dynamicKey(async () => {
const secret = await vault.read('secret/openai');
return secret.data.apiKey;
});
// Time-based key rotation
const timedKey = dynamicKey(() => {
const hour = new Date().getHours();
return hour < 12 ? morningKey : afternoonKey;
});