Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import type { SuperAgentsTarget } from '@shared/types/api/request/headers';
/**
* Selects a provider based on their assigned weights.
* The weight is used to determine the probability of each provider being chosen.
* If all providers have a weight of 0, an error will be thrown.
*/
export function selectProviderByWeight(
targetConfigs: SuperAgentsTarget[],
): SuperAgentsTarget {
// Assign a default weight of 1 to providers with undefined weight
targetConfigs = targetConfigs.map((targetConfig) => ({
...targetConfig,
weight: targetConfig.weight ?? 1,
}));
// Compute the total weight
const totalWeight = targetConfigs.reduce(
(sum: number, targetConfig: SuperAgentsTarget) =>
sum + targetConfig.weight!,
0,
);
// Select a random weight between 0 and totalWeight
let randomWeight = Math.random() * totalWeight;
// Find the provider that corresponds to the selected weight
for (let index = 0; index < targetConfigs.length; index++) {
const targetConfig = targetConfigs[index];
if (randomWeight < targetConfig.weight) {
return { ...targetConfig, index };
}
randomWeight -= targetConfig.weight;
}
throw new Error('No provider selected, please check the weights');
}
|