|
|
@@ -1623,5 +1623,37 @@ export const stringUtils = {
|
|
1623
|
1623
|
}
|
|
1624
|
1624
|
|
|
1625
|
1625
|
return false;
|
|
|
1626
|
+ },
|
|
|
1627
|
+
|
|
|
1628
|
+ /**
|
|
|
1629
|
+ * 按照权重概率分配返回字符串
|
|
|
1630
|
+ * @param {Object} options - 包含字符串和对应权重的对象
|
|
|
1631
|
+ * @example
|
|
|
1632
|
+ * // 返回 'ali-Moonshot-Kimi-K2-Instruct' 的概率为 40%,返回 'doubao-kimi-k2-250711' 的概率为 60%
|
|
|
1633
|
+ * stringUtils.weightedRandom({
|
|
|
1634
|
+ * 'ali-Moonshot-Kimi-K2-Instruct': 40,
|
|
|
1635
|
+ * 'doubao-kimi-k2-250711': 60
|
|
|
1636
|
+ * });
|
|
|
1637
|
+ * @returns {string} - 根据权重随机选择的字符串
|
|
|
1638
|
+ */
|
|
|
1639
|
+ weightedRandom(options) {
|
|
|
1640
|
+ // 计算权重总和
|
|
|
1641
|
+ const weights = Object.values(options);
|
|
|
1642
|
+ const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
|
|
|
1643
|
+
|
|
|
1644
|
+ // 生成一个随机数,范围是 [0, totalWeight)
|
|
|
1645
|
+ const random = Math.random() * totalWeight;
|
|
|
1646
|
+
|
|
|
1647
|
+ // 根据随机数和权重分布选择结果
|
|
|
1648
|
+ let cumulativeWeight = 0;
|
|
|
1649
|
+ for (const [item, weight] of Object.entries(options)) {
|
|
|
1650
|
+ cumulativeWeight += weight;
|
|
|
1651
|
+ if (random < cumulativeWeight) {
|
|
|
1652
|
+ return item;
|
|
|
1653
|
+ }
|
|
|
1654
|
+ }
|
|
|
1655
|
+
|
|
|
1656
|
+ // 如果出现意外情况,返回第一个选项
|
|
|
1657
|
+ return Object.keys(options)[0];
|
|
1626
|
1658
|
}
|
|
1627
|
1659
|
}
|