Skip to content

Function: resolveApiKey()

@providerprotocol/ai


@providerprotocol/ai / http / resolveApiKey

resolveApiKey(config, envVar?, provider?, modality?): Promise<string>

Defined in: src/http/keys.ts:221

Resolves an API key from provider configuration with multiple fallback options.

This function handles various key specification methods in priority order:

  1. Direct string key in config.apiKey
  2. Function returning a key (sync or async) in config.apiKey
  3. KeyStrategy instance in config.apiKey (roundRobinKeys, weightedKeys, dynamicKey)
  4. Environment variable fallback (if envVar parameter is provided)

ProviderConfig

Provider configuration containing the apiKey option

string

Optional environment variable name to check as fallback

string = 'unknown'

Provider identifier for error context (default: ‘unknown’)

Modality = 'llm'

Request modality for error context (default: ‘llm’)

Promise<string>

The resolved API key string

AUTHENTICATION_FAILED - When no valid key is found

// Direct key in config
const key1 = await resolveApiKey({ apiKey: 'sk-...' }, 'OPENAI_API_KEY', 'openai');
// Function-based key
const key2 = await resolveApiKey({ apiKey: () => getKeyFromVault() }, undefined, 'anthropic');
// KeyStrategy instance
const key3 = await resolveApiKey({
apiKey: roundRobinKeys(['sk-1', 'sk-2', 'sk-3'])
}, 'OPENAI_API_KEY', 'openai');
// Environment variable fallback
const key4 = await resolveApiKey({}, 'ANTHROPIC_API_KEY', 'anthropic');