@@ -76,6 +76,8 @@ type Bridge struct {
7676 client * BearerClient
7777 region account.Region
7878 templateBase map [string ]interface {}
79+ // pool 非空时启用多账号轮询 + 失败换号;为空则退化为单账号(sess/client/region)。
80+ pool * Pool
7981 // chatStreamURL 测试注入用:非空时覆盖 region 对应的上游 chat 流地址
8082 chatStreamURL string
8183}
@@ -174,8 +176,12 @@ func NewBridge(pat string, region account.Region, templateBase map[string]interf
174176// ListAvailableModels 通过 cosy 签名调用 /algo/api/v2/model/list 拉取上游模型清单。
175177// 返回顶层 assistant 数组中 enable=true 的模型,按 is_default desc + display_name asc 排序。
176178func (b * Bridge ) ListAvailableModels () ([]QoderModel , error ) {
177- modelListURL := qoderModelListURL (b .region )
178- resp , err := b .client .callGet (modelListURL )
179+ slot , ok := b .pickSlot (nil )
180+ if ! ok {
181+ return nil , ErrNoAccount
182+ }
183+ modelListURL := qoderModelListURL (slot .Region )
184+ resp , err := slot .client .callGet (modelListURL )
179185 if err != nil {
180186 return nil , err
181187 }
@@ -184,7 +190,7 @@ func (b *Bridge) ListAvailableModels() ([]QoderModel, error) {
184190 for k := range resp {
185191 keys = append (keys , k )
186192 }
187- logger .Info ("model list response keys: %v (region=%s)" , keys , b . region )
193+ logger .Info ("model list response keys: %v (region=%s)" , keys , slot . Region )
188194 models := parseQoderModels (resp )
189195 if len (models ) == 0 {
190196 return nil , fmt .Errorf ("%s -> empty model list, keys=%v" , modelListURL , keys )
@@ -322,13 +328,7 @@ func (b *Bridge) CallQoderWithOpts(ctx context.Context, agent string, messages [
322328 }
323329 body := DeepCopyMap (b .templateBase )
324330
325- nid := cosy .NewUUID ()
326- body ["request_id" ] = nid
327- body ["chat_record_id" ] = nid
328- body ["request_set_id" ] = cosy .NewUUID ()
329- body ["session_id" ] = cosy .NewUUID ()
330331 body ["stream" ] = true
331- body ["aliyun_user_type" ] = b .sess .Identity .UserType
332332
333333 if mc , ok := body ["model_config" ].(map [string ]interface {}); ok {
334334 mc ["key" ] = model
@@ -397,38 +397,77 @@ func (b *Bridge) CallQoderWithOpts(ctx context.Context, agent string, messages [
397397 }
398398 }
399399
400- qurl := qoderChatStreamURL (b .region )
401- if b .chatStreamURL != "" {
402- qurl = b .chatStreamURL
403- }
404400 extra := map [string ]string {
405401 "x-model-key" : model ,
406402 "x-model-source" : mcSource ,
407403 }
408404
409405 preview := prompt
410- if len (preview ) > 80 {
406+ if len (prompt ) > 80 {
411407 preview = preview [:80 ] + "..."
412408 }
413409 logger .Info ("callQoder model=%s prompt=%s" , model , preview )
414- logger .Debug ("callQoder request body: %s" , func () string { d , _ := json .Marshal (body ); return string (d ) }())
415-
416- // ---- SSE 信封重试闸门(第 3 步,参照 hub should_retry_envelope /
417- // aggregate_with_envelope_retry)------------------------------------------
418- // 关键形态:上游 HTTP200 建流后才在信封里投 418/5xx,连接层重试覆盖不到。
419- // 闸门规则:只要「尚未向 onDelta 发出任何非空 delta」且错误属瞬时类
420- // (信封 418/5xx/provider_error、传输层 TLS EOF 等),就重开上游重试,
421- // 对调用方无感;已发出内容则直接上抛,避免客户端收到重复内容。
422- // 客户端参数错 / 内容审核 / 401/429 经 IsTransientUpstream 判定为
423- // 不可重试,快速失败。闸门做在此处,chat/claude/codex 三协议的
424- // 流式与非流式路径全部自动覆盖。
425- // 说明:连接阶段错误已在 openStreamLines 内部重试过;此处重开是
426- // 第二层防护(有界:最多 TransientMaxRetries 次),主要覆盖流内信封错误。
410+
411+ // ---- 账号池选号 + 失败换号 -------------------------------------------
412+ // 逐个尝试池内账号:某账号失败且「尚未向客户端发出任何内容」、且错误属于
413+ // 可换号类(额度/频控/瞬时),就冷却该账号并换下一个;已发出内容或
414+ // 客户端参数错/内容审核则立即上抛——避免重复内容、避免无意义换号。
415+ tried := make (map [string ]struct {})
427416 var lastErr error
417+ for {
418+ slot , ok := b .pickSlot (tried )
419+ if ! ok {
420+ break
421+ }
422+ // 每个账号用全新的请求 id / session,避免跨账号复用同一标识
423+ nid := cosy .NewUUID ()
424+ body ["request_id" ] = nid
425+ body ["chat_record_id" ] = nid
426+ body ["request_set_id" ] = cosy .NewUUID ()
427+ body ["session_id" ] = cosy .NewUUID ()
428+ body ["aliyun_user_type" ] = slot .sess .Identity .UserType
429+ if biz , ok := body ["business" ].(map [string ]interface {}); ok {
430+ biz ["id" ] = cosy .NewUUID ()
431+ biz ["begin_at" ] = cosy .UnixMs ()
432+ }
433+
434+ qurl := b .chatStreamURL
435+ if qurl == "" {
436+ qurl = qoderChatStreamURL (slot .Region )
437+ }
438+ logger .Debug ("callQoder request body: %s" , func () string { d , _ := json .Marshal (body ); return string (d ) }())
439+
440+ emitted , err := b .streamWithSlot (ctx , slot , qurl , body , extra , onDelta )
441+ if err == nil {
442+ b .noteSlotSuccess (slot .ID )
443+ return nil
444+ }
445+ lastErr = err
446+ if emitted || ! ShouldFailover (err ) {
447+ return err
448+ }
449+ b .coolSlot (slot .ID , CooldownFor (err ), err .Error ())
450+ tried [slot .ID ] = struct {}{}
451+ logger .Info ("callQoder: account %s failed, failing over to next account: %v" , slot .ID , err )
452+ }
453+ if lastErr == nil {
454+ lastErr = ErrNoAccount
455+ }
456+ return lastErr
457+ }
458+
459+ // streamWithSlot 在单个账号上执行「SSE 信封重试闸门」。
460+ // 连接阶段错误已由 openStreamLines 内部重试;此处是第二层防护(有界:
461+ // 最多 TransientMaxRetries 次),主要覆盖上游 HTTP200 建流后才在信封里
462+ // 投递 418/5xx 的形态。返回是否已向 onDelta 发出过内容——上层据此决定
463+ // 能否换号(已发出内容则不能,否则客户端会收到重复内容)。
464+ func (b * Bridge ) streamWithSlot (ctx context.Context , slot * Slot , qurl string , body map [string ]interface {}, extra map [string ]string , onDelta func (Delta )) (bool , error ) {
465+ var lastErr error
466+ emittedAny := false
428467 for attempt := 0 ; attempt <= TransientMaxRetries ; attempt ++ {
429468 if attempt > 0 {
430469 if serr := sleepCtx (ctx , RetryBackoff (attempt )); serr != nil {
431- return lastErr
470+ return emittedAny , lastErr
432471 }
433472 logger .Info ("reopen upstream after in-stream error (try %d/%d): %v" ,
434473 attempt + 1 , TransientMaxRetries + 1 , lastErr )
@@ -438,30 +477,30 @@ func (b *Bridge) CallQoderWithOpts(ctx context.Context, agent string, messages [
438477 onDeltaWrapped := func (d Delta ) {
439478 if ! d .isEmpty () {
440479 emitted = true
480+ emittedAny = true
441481 }
442482 onDelta (d )
443483 }
444- streamErr := b .client .openStreamLines (ctx , qurl , body , extra ,
484+ streamErr := slot .client .openStreamLines (ctx , qurl , body , extra ,
445485 deltaDispatcher (onDeltaWrapped , & upstreamErr ))
446486 if upstreamErr == nil && streamErr == nil {
447487 // 上游正常关流但未发出任何有效 delta/usage 帧:对齐 hub
448- // "empty upstream stream" 显式报错(不纳入重开闸门——
449- // isRetryableStreamError 对哨兵错误自然返回 false,不重试)
488+ // "empty upstream stream" 显式报错(不纳入重开闸门)。
450489 if ! emitted {
451- return ErrEmptyStream
490+ return emittedAny , ErrEmptyStream
452491 }
453- return nil
492+ return emittedAny , nil
454493 }
455494 if upstreamErr != nil {
456495 lastErr = upstreamErr
457496 } else {
458497 lastErr = streamErr
459498 }
460499 if emitted || attempt >= TransientMaxRetries || ! isRetryableStreamError (lastErr ) {
461- return lastErr
500+ return emittedAny , lastErr
462501 }
463502 }
464- return lastErr
503+ return emittedAny , lastErr
465504}
466505
467506// isRetryableStreamError 判定流内/连接错误是否值得重开上游:
0 commit comments