Skip to content

Function: weightedKeys()

@providerprotocol/ai


@providerprotocol/ai / @providerprotocol/ai / weightedKeys

weightedKeys(keys): KeyStrategy

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

Creates a key strategy that selects API keys using weighted random probability.

Each key is assigned a weight that determines its probability of being selected. Higher weights mean higher selection probability. This is useful for:

  • Preferring higher-tier API keys with better rate limits
  • Gradually migrating traffic between old and new keys
  • A/B testing different API accounts
  • Directing more traffic to keys with higher quotas

The selection probability for each key is: weight / totalWeight

object[]

Array of key-weight pairs defining selection probabilities

KeyStrategy

A KeyStrategy that selects keys by weighted probability

When the keys array is empty

const keys = weightedKeys([
{ key: 'sk-premium', weight: 70 }, // 70% of requests
{ key: 'sk-standard', weight: 20 }, // 20% of requests
{ key: 'sk-backup', weight: 10 } // 10% of requests
]);
// Configure provider with weighted key selection
const provider = createOpenAI({
apiKey: keys
});