@@ -307,22 +307,31 @@ async function getMessageById(id: string): Promise<ChatMessage | undefined> {
307307 else { return undefined }
308308}
309309
310- const _lockedKeys : string [ ] = [ ]
311- async function randomKeyConfig ( keys : KeyConfig [ ] ) : Promise < KeyConfig | null > {
310+ const _lockedKeys : { key : string ; count : number } [ ] = [ ]
311+ const _oneTimeCount = 3 // api
312+ async function randomKeyConfig ( keys : KeyConfig [ ] ) : Promise < KeyConfig | null > {
312313 if ( keys . length <= 0 )
313314 return null
314- let unsedKeys = keys . filter ( d => ! _lockedKeys . includes ( d . key ) )
315+ let unsedKeys = keys . filter ( d => _lockedKeys . filter ( l => d . key === l . key ) . length <= 0
316+ || _lockedKeys . filter ( l => d . key === l . key ) [ 0 ] . count < _oneTimeCount )
315317 const start = Date . now ( )
316318 while ( unsedKeys . length <= 0 ) {
317319 if ( Date . now ( ) - start > 3000 )
318320 break
319321 await new Promise ( resolve => setTimeout ( resolve , 1000 ) )
320- unsedKeys = keys . filter ( d => ! _lockedKeys . includes ( d . key ) )
322+ unsedKeys = keys . filter ( d => _lockedKeys . filter ( l => d . key === l . key ) . length <= 0
323+ || _lockedKeys . filter ( l => d . key === l . key ) [ 0 ] . count < _oneTimeCount )
321324 }
322325 if ( unsedKeys . length <= 0 )
323326 return null
324327 const thisKey = unsedKeys [ Math . floor ( Math . random ( ) * unsedKeys . length ) ]
325- _lockedKeys . push ( thisKey . key )
328+ const thisLockedKey = _lockedKeys . filter ( d => d . key === thisKey . key )
329+ if ( thisLockedKey . length <= 0 )
330+ _lockedKeys . push ( { key : thisKey . key , count : 1 } )
331+
332+ else
333+ thisLockedKey [ 0 ] . count ++
334+
326335 return thisKey
327336}
328337
@@ -335,9 +344,17 @@ async function releaseApiKey(key: KeyConfig) {
335344 if ( key == null || key === undefined )
336345 return
337346
338- const index = _lockedKeys . indexOf ( key . key )
339- if ( index >= 0 )
340- _lockedKeys . splice ( index , 1 )
347+ const lockedKeys = _lockedKeys . filter ( d => d . key === key . key )
348+ if ( lockedKeys . length > 0 ) {
349+ if ( lockedKeys [ 0 ] . count <= 1 ) {
350+ const index = _lockedKeys . findIndex ( item => item . key === key . key )
351+ if ( index !== - 1 )
352+ _lockedKeys . splice ( index , 1 )
353+ }
354+ else {
355+ lockedKeys [ 0 ] . count --
356+ }
357+ }
341358}
342359
343360export type { ChatContext , ChatMessage }
0 commit comments