MCPcopy Create free account
hub / github.com/astercloud/aster / Complete

Method Complete

pkg/agent/model_fallback.go:104–162  ·  view source on GitHub ↗

Complete 执行非流式请求,支持自动降级

(
	ctx context.Context,
	messages []types.Message,
	opts *provider.StreamOptions,
)

Source from the content-addressed store, hash-verified

102
103// Complete 执行非流式请求,支持自动降级
104func (m *ModelFallbackManager) Complete(
105 ctx context.Context,
106 messages []types.Message,
107 opts *provider.StreamOptions,
108) (*provider.CompleteResponse, error) {
109 m.stats.TotalRequests++
110
111 var lastErr error
112
113 // 遍历所有启用的模型
114 for i, fb := range m.fallbacks {
115 if !fb.Enabled {
116 continue
117 }
118
119 modelKey := fmt.Sprintf("%s/%s", fb.Config.Provider, fb.Config.Model)
120
121 // 尝试执行,支持重试
122 for retry := 0; retry <= fb.MaxRetries; retry++ {
123 if retry > 0 {
124 fallbackLog.Debug(ctx, "retrying model", map[string]any{"retry": retry, "max_retries": fb.MaxRetries, "model": modelKey})
125
126 // 重试前等待一小段时间(指数退避)
127 backoff := time.Duration(retry) * 500 * time.Millisecond
128 select {
129 case <-ctx.Done():
130 return nil, ctx.Err()
131 case <-time.After(backoff):
132 }
133 }
134
135 // 执行请求
136 resp, err := fb.provider.Complete(ctx, messages, opts)
137 if err == nil {
138 // 成功
139 m.stats.SuccessRequests++
140 m.stats.ModelUsageCount[modelKey]++
141 m.currentIndex = i
142
143 fallbackLog.Debug(ctx, "success with model", map[string]any{"model": modelKey, "retry": retry})
144 return resp, nil
145 }
146
147 lastErr = err
148 fallbackLog.Warn(ctx, "error with model", map[string]any{"model": modelKey, "retry": retry, "max_retries": fb.MaxRetries, "error": err})
149 }
150
151 // 所有重试都失败,尝试下一个模型
152 if i < len(m.fallbacks)-1 {
153 m.stats.FallbackCount++
154 m.stats.LastFallbackTime = time.Now()
155 fallbackLog.Info(ctx, "falling back to next model", map[string]any{"from_model": modelKey})
156 }
157 }
158
159 // 所有模型都失败
160 m.stats.FailedRequests++
161 return nil, fmt.Errorf("all models failed, last error: %w", lastErr)

Calls 5

DebugMethod · 0.65
CompleteMethod · 0.65
WarnMethod · 0.65
InfoMethod · 0.65
DurationMethod · 0.45