Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ ROUTING_STRATEGY=round-robin
# fill-first 依次使用的账户 ID,逗号分隔,未列出的账户排在后面并按 ID 排序,保存后立即生效
ACCOUNT_ORDER=

# 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,0 为不换号;登录失效与额度用尽不计入
# 上游返回 403、500 等非额度错误时一个请求最多换几次账户重试,0 为不换号;登录失效与额度用尽不计入
MAX_ACCOUNT_SWITCHES=3

# 同一请求内账户失败后切往下一个账户(含冷备账户启动 Worker)前的最短等待秒数;off 为不等待,正整数为秒数
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,7 @@ cp .env.example .env
| `PER_ACCOUNT_CONCURRENCY` | `2` | 单账号同时执行的请求数 |
| `ROUTING_STRATEGY` | `round-robin` | `round-robin` 轮询;`fill-first` 账号粘性优先 |
| `ACCOUNT_ORDER` | 空 | `fill-first` 依次使用的账户,逗号分隔,未列出的账户排在后面并按 ID 排序;也可在设置页调整,保存后立即生效 |
| `MAX_ACCOUNT_SWITCHES` | `3` | 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,`0` 为不换号 |
| `MAX_ACCOUNT_SWITCHES` | `3` | 上游返回 403、500 等非额度错误时一个请求最多换几次账户重试,`0` 为不换号 |
| `ACCOUNT_SWITCH_INTERVAL` | `off` | 同一请求内前一个账户失败后,下一个账户向 Google 发出请求(或启动冷备 Worker)前从上次失败起等待的最短秒数;`off` 为不等待,正整数为秒数 |
| `MAX_QUOTA_SWITCHES` | `off` | 同一请求内因额度用尽(429)切换账户的次数上限;`off` 为不限制,依次尝试全部账户,`0` 为不换号,正整数为最多换号次数,超出后返回最后一次 429 |
| `UPSTREAM_CHANNELS` | `playground` | 生成请求使用的上游通道,`playground`、`build` 逗号分隔;`build` 为旧通道,上游已停用其生成 |
Expand Down Expand Up @@ -719,7 +719,7 @@ cp .env.example .env

- `PREVIEW_LISTEN_ADDR`:无法监听时改用同一主机上的空闲端口;页面以当前访问的主机名加实际端口打开预览
- `AUTO_START`:网络等原因启动失败时按 5 秒起、翻倍至 5 分钟的间隔重试,手动启动或停止后不再重试
- `MAX_ACCOUNT_SWITCHES`:登录失效与额度用尽不计入;额度用尽的换号次数由 `MAX_QUOTA_SWITCHES` 单独控制(默认不限)
- `MAX_ACCOUNT_SWITCHES`:上游返回 503 时直接结束请求;登录失效与额度用尽不计入;额度用尽的换号次数由 `MAX_QUOTA_SWITCHES` 单独控制(默认不限)
- `ACCOUNT_SWITCH_INTERVAL`:切往冷备账户时先等满间隔再启动 Worker,就绪后直接发送,不重复等待;等待期间客户端断开即结束
- `NONSTREAM_KEEPALIVE`:返回 200 后每 10 秒写出一个换行直到写出 JSON 正文,经 Cloudflare 等反向代理时连接不会因长时间无数据断开;此后才出现的错误以协议错误正文返回
- `STRIP_THOUGHT_SIGNATURES`:函数调用带 `skip_thought_signature_validator`;之前各轮的思考内容不随签名发给模型,长对话的输入 token 较少
Expand Down
4 changes: 2 additions & 2 deletions README_en.md
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,7 @@ Process environment variables override the same keys in `.env`, and those settin
| `PER_ACCOUNT_CONCURRENCY` | `2` | Concurrent requests allowed per account |
| `ROUTING_STRATEGY` | `round-robin` | `round-robin` rotates accounts; `fill-first` reuses the first available account |
| `ACCOUNT_ORDER` | empty | Accounts `fill-first` uses in order, comma-separated; unlisted accounts follow in ID order. Also adjustable on the Settings page, applied on save |
| `MAX_ACCOUNT_SWITCHES` | `3` | How many times a request moves to another account after a non-quota upstream error such as 403 or 5xx; `0` disables switching |
| `MAX_ACCOUNT_SWITCHES` | `3` | How many times a request moves to another account after a non-quota upstream error such as 403 or 500; `0` disables switching |
| `ACCOUNT_SWITCH_INTERVAL` | `off` | Minimum wait in seconds from a failed account attempt before the next account sends any request to Google (or cold-starts a standby worker); `off` disables waiting |
| `MAX_QUOTA_SWITCHES` | `off` | Maximum account switches for quota exhaustion (429) within one request; `off` tries all remaining accounts, `0` disables quota switching, and a positive integer returns the last 429 once exceeded |
| `UPSTREAM_CHANNELS` | `playground` | Upstream channels for generation requests, `playground` and `build` comma separated; `build` is the legacy channel whose generation upstream has disabled |
Expand Down Expand Up @@ -719,7 +719,7 @@ Notes:

- `PREVIEW_LISTEN_ADDR`: when it cannot be bound, a free port on the same host is used; the page opens previews at the current host name with the port in use
- `AUTO_START`: if startup fails for reasons such as the network, it retries at intervals starting at 5 seconds and doubling up to 5 minutes, until the service is started or stopped manually
- `MAX_ACCOUNT_SWITCHES`: expired sessions and quota errors do not count; quota-exhaustion switches are controlled separately by `MAX_QUOTA_SWITCHES` (unlimited by default)
- `MAX_ACCOUNT_SWITCHES`: an upstream 503 ends the request immediately; expired sessions and quota errors do not count; quota-exhaustion switches are controlled separately by `MAX_QUOTA_SWITCHES` (unlimited by default)
- `ACCOUNT_SWITCH_INTERVAL`: when moving to a standby account, waits for the interval before starting the worker and sends immediately once ready without waiting again; stops immediately if the client disconnects
- `NONSTREAM_KEEPALIVE`: after returning 200, a newline is written every 10 seconds until the JSON body, so reverse proxies such as Cloudflare keep the connection open; errors after that point come back as the protocol error body
- `STRIP_THOUGHT_SIGNATURES`: function calls are sent with `skip_thought_signature_validator`; earlier turns' thinking is not passed to the model with the signatures, so long conversations use fewer input tokens
Expand Down
5 changes: 3 additions & 2 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等
- `WARM_STARTUP_CONCURRENCY`:限制按需扩容时的冷启动数,预热逐个启动;`WAA_BACKEND=spidermonkey` 时不限制
- `ROUTING_STRATEGY`:账户轮询 `round-robin` 或粘性优先 `fill-first`
- `ACCOUNT_ORDER`:逗号分隔的账户 ID,`fill-first` 依次使用并按此顺序预热,未列出的账户排在后面并按 ID 排序;保存后立即生效
- `MAX_ACCOUNT_SWITCHES`:一个请求因上游 403、404、5xx、连接断开、首字超时等非额度失败换号的次数上限,`0` 为不换号,登录失效与额度失败不计入;保存后立即生效
- `MAX_ACCOUNT_SWITCHES`:一个请求因上游 403、404、500、连接断开、首字超时等非额度失败换号的次数上限,`0` 为不换号,登录失效与额度失败不计入;保存后立即生效
- `UPSTREAM_CHANNELS`:`playground`、`build`(旧通道,上游已停用其生成),逗号分隔
- `MODEL_MAPPING`:逗号分隔,每项以最后一个 `:` 分成别名与模型 ID;保存后立即生效
- `MODEL_CHANNELS`:逗号分隔,每项以最后一个 `:` 分成模型 ID 与通道 `playground` 或 `build`;保存后立即生效
Expand Down Expand Up @@ -603,7 +603,8 @@ POST /api/control/start

换号与重放:

- 未固定账户的请求遇到可重试的 401、403、404、429、5xx、收到响应前的连接断开或单账户初始化超时时,可以在首个上游语义事件前继续切换尚未尝试的同能力账户;额度以外的失败最多换 `MAX_ACCOUNT_SWITCHES` 次,额度失败不计入
- 未固定账户的请求遇到可重试的 401、403、404、429、503 以外的 5xx、收到响应前的连接断开或单账户初始化超时时,可以在首个上游语义事件前继续切换尚未尝试的同能力账户;额度以外的失败最多换 `MAX_ACCOUNT_SWITCHES` 次,额度失败不计入
- 首轮生成收到上游 503 时直接结束请求;上游给出重试时长时错误响应带 `Retry-After`,没有给出时带 `X-Should-Retry: false`
- 上游以 403、协议错误码 7 拒绝账户(官网不跳转拒绝页的情形)时,自上次成功后第一次被拒只换号;没有其他账户可换时在该账户上重试一次;连续第二次被拒起,该账户在该模型上冷却 1、5、15、30、60 分钟,成功一次后重新计数
- Drive 引用随需要临时复制到生成账户,显式账户和视频任务保持账户绑定
- Chrome 导入状态保留续签材料,HTTP `401` 时在同一固定出口续签一次、重建该账户 WAA runtime 并重放请求
Expand Down
1 change: 1 addition & 0 deletions docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -4072,6 +4072,7 @@ Gemini 列中注明状态码的行以该状态码返回;Interactions 路由与
| 文件超过 512 MiB | 413 | `file_too_large` | `request_too_large` | `INTERNAL` |
| 上游配额或限流(上游给出重试时长时带 `Retry-After`,Gemini 错误体带 `RetryInfo`) | 429 | `rate_limit_exceeded` | `rate_limit_error` | `RESOURCE_EXHAUSTED` |
| 候选账户均在冷却且在本请求累计排队 1 分钟内不恢复,或已试账户都因额度失败而其余账户在冷却(套餐限额与每日限额冷却中的账户逐个发送一次,其中 5 到 60 分钟内拒绝过同样大或更小请求的账户、收到其他额度失败且该失败的冷却没有结束的账户跳过,全部拒绝时返回最后一次拒绝,全部跳过时立即返回;带 `Retry-After`,Gemini 错误体带 `RetryInfo`) | 429 | `rate_limit_exceeded` | `rate_limit_error` | `RESOURCE_EXHAUSTED` |
| 上游暂时不可用(上游给出重试时长时带 `Retry-After`,Gemini 错误体带 `RetryInfo`;没有给出时带 `X-Should-Retry: false`) | 503 | `upstream_error` | `api_error` | `UNAVAILABLE` |
| 上游过载 | 529 | `upstream_error` | `overloaded_error` | `INTERNAL` |
| 当前客户端请求被管理端取消 | 503 | `request_canceled` | `api_error` | `UNAVAILABLE` |
| 生成服务已停止,包括停止时进行中的请求 | 503 | `service_stopped` | `api_error` | `UNAVAILABLE` |
Expand Down
16 changes: 10 additions & 6 deletions internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ func writeOpenAIRequestError(w http.ResponseWriter, err error) {

// writeOpenAIFailure 以给定状态与错误码写出请求失败的公开原因,可重试时带 Retry-After,请求记录保留完整原因
func writeOpenAIFailure(w http.ResponseWriter, status int, code string, err error) {
seconds := setRetryAfter(w, err)
seconds := setRetryHeaders(w, err)
writeOpenAIError(w, status, code, retryMessage(publicReason(err), seconds))
setAccessLogResponseError(w, err.Error())
}
Expand All @@ -540,7 +540,7 @@ func writeOpenAISSEError(w http.ResponseWriter, err error) {

// writeAnthropicRequestError 以 Anthropic 错误体写出请求失败,可重试时带 Retry-After 并在消息末尾写明重试时间
func writeAnthropicRequestError(w http.ResponseWriter, err error) {
seconds := setRetryAfter(w, err)
seconds := setRetryHeaders(w, err)
writeAnthropicError(w, statusFromError(err), anthropicErrorType(err), retryMessage(anthropicErrorMessage(err), seconds))
setAccessLogResponseError(w, err.Error())
}
Expand Down Expand Up @@ -572,7 +572,7 @@ func anthropicErrorMessage(err error) string {

// writeGeminiRequestError 以 Gemini 错误体写出请求失败,可重试时带 Retry-After 与 RetryInfo
func writeGeminiRequestError(w http.ResponseWriter, err error) {
payload := geminiErrorPayload(err, setRetryAfter(w, err))
payload := geminiErrorPayload(err, setRetryHeaders(w, err))
setAccessLogResponseError(w, err.Error())
writeJSON(w, statusFromError(err), officialOrder("gemini", map[string]any{"error": payload}))
}
Expand All @@ -586,11 +586,15 @@ func geminiErrorPayload(err error, seconds int64) map[string]any {
return payload
}

// setRetryAfter 在错误给出可重试时刻时写入 Retry-After 秒数并返回它,否则返回 0
func setRetryAfter(w http.ResponseWriter, err error) int64 {
// setRetryHeaders 在错误给出可重试时刻时写入 Retry-After 秒数并返回它,否则返回 0,此时上游 503 写入 X-Should-Retry: false
func setRetryHeaders(w http.ResponseWriter, err error) int64 {
seconds := retryAfterSeconds(err)
if seconds > 0 {
var rpc *aistudio.RPCError
switch {
case seconds > 0:
w.Header().Set("Retry-After", strconv.FormatInt(seconds, 10))
case errors.As(err, &rpc) && rpc.StatusCode == http.StatusServiceUnavailable:
w.Header().Set("X-Should-Retry", "false")
}
return seconds
}
Expand Down
52 changes: 52 additions & 0 deletions internal/api/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,55 @@ func TestPublicErrorReason(t *testing.T) {
})
}
}

// TestUpstreamUnavailableRetryHeaders 验证三种协议的上游 503 带 X-Should-Retry: false,上游给出重试时长时带 Retry-After,其他错误两者都不带
func TestUpstreamUnavailableRetryHeaders(t *testing.T) {
writers := map[string]func(http.ResponseWriter, error){
"openai": writeOpenAIRequestError, "anthropic": writeAnthropicRequestError, "gemini": writeGeminiRequestError,
}
cases := []struct {
name string
err error
status int
shouldRetry string
retryAfter string
}{
{
name: "上游 503",
err: &aistudio.RPCError{Method: "GenerateContent", StatusCode: http.StatusServiceUnavailable, Code: 14, Message: "high demand"},
status: http.StatusServiceUnavailable, shouldRetry: "false",
},
{
name: "上游 503 带重试时长",
err: &aistudio.RPCError{Method: "GenerateContent", StatusCode: http.StatusServiceUnavailable, Code: 14, Message: "high demand", RetryDelay: time.Hour},
status: http.StatusServiceUnavailable, retryAfter: "3600",
},
{
name: "上游 500",
err: &aistudio.RPCError{Method: "GenerateContent", StatusCode: http.StatusInternalServerError, Code: 13, Message: "internal"},
status: http.StatusInternalServerError,
},
{
name: "账户都不可调度",
err: &aistudio.AccountsNotReadyError{Reasons: []string{"[email protected] 需要重新登录"}, States: []aistudio.AccountState{aistudio.AccountAuthRequired}},
status: http.StatusServiceUnavailable,
},
}
for protocol, write := range writers {
for _, test := range cases {
t.Run(protocol+"/"+test.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
write(recorder, fmt.Errorf("发送 AI Studio GenerateContent: %w", test.err))
if recorder.Code != test.status {
t.Fatalf("状态码 %d,应为 %d", recorder.Code, test.status)
}
if got := recorder.Header().Get("X-Should-Retry"); got != test.shouldRetry {
t.Fatalf("X-Should-Retry %q,应为 %q", got, test.shouldRetry)
}
if got := recorder.Header().Get("Retry-After"); got != test.retryAfter {
t.Fatalf("Retry-After %q,应为 %q", got, test.retryAfter)
}
})
}
}
}
30 changes: 30 additions & 0 deletions internal/app/generate_retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package app

import (
"fmt"
"net/http"
"testing"

"github.com/Mag1cFall/AIStudio2API/internal/aistudio"
)

// TestRetryableGenerateAccountError 验证上游 503 结束请求,其余暂时失败可以换号
func TestRetryableGenerateAccountError(t *testing.T) {
cases := map[int]bool{
http.StatusBadRequest: false,
http.StatusUnauthorized: true,
http.StatusForbidden: true,
http.StatusNotFound: true,
http.StatusTooManyRequests: true,
http.StatusInternalServerError: true,
http.StatusBadGateway: true,
http.StatusServiceUnavailable: false,
http.StatusGatewayTimeout: true,
}
for status, want := range cases {
err := fmt.Errorf("发送 AI Studio GenerateContent: %w", &aistudio.RPCError{Method: "GenerateContent", StatusCode: status})
if got := retryableGenerateAccountError(t.Context(), err); got != want {
t.Errorf("HTTP %d 可换号 %v,应为 %v", status, got, want)
}
}
}
4 changes: 3 additions & 1 deletion internal/app/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -3407,6 +3407,7 @@ func collectGenerateEvents(ctx context.Context, source <-chan aistudio.Event, on
}
}

// retryableGenerateAccountError 判断生成请求的失败能否换号重试,上游 503 直接结束请求
func retryableGenerateAccountError(ctx context.Context, err error) bool {
if errors.Is(err, errStreamClosedBeforeFirstEvent) || errors.Is(err, aistudio.ErrAccountCoolingDown) {
return true
Expand Down Expand Up @@ -3435,7 +3436,8 @@ func retryableGenerateAccountError(ctx context.Context, err error) bool {
return false
}
return rpcError.StatusCode == http.StatusUnauthorized || rpcError.StatusCode == http.StatusForbidden || rpcError.StatusCode == http.StatusNotFound ||
rpcError.StatusCode == http.StatusTooManyRequests || rpcError.StatusCode >= http.StatusInternalServerError
rpcError.StatusCode == http.StatusTooManyRequests ||
rpcError.StatusCode >= http.StatusInternalServerError && rpcError.StatusCode != http.StatusServiceUnavailable
}

func (service *trackedService) lifecycleRequestContext(ctx context.Context) (context.Context, context.CancelFunc) {
Expand Down
2 changes: 1 addition & 1 deletion web/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ export const messages: Record<TranslationKey, string> = {
'settings.accountOrderRest': 'Die übrigen {count} Konten folgen in ID-Reihenfolge',
'settings.maxAccountSwitches': 'Maximale Kontowechsel',
'settings.maxAccountSwitchesHelp':
'Wie oft eine Anfrage nach einem Upstream-Fehler ohne Kontingentbezug wie 403 oder 5xx zu einem anderen Konto wechselt; 0 deaktiviert den Wechsel, Kontingentfehler zählen nicht',
'Wie oft eine Anfrage nach einem Upstream-Fehler ohne Kontingentbezug wie 403 oder 500 zu einem anderen Konto wechselt; 0 deaktiviert den Wechsel, Kontingentfehler zählen nicht',
'settings.maxQuotaSwitches': 'Maximale Wechsel bei Kontingentfehlern',
'settings.maxQuotaSwitchesHelp':
'Wie oft eine Anfrage zu einem anderen Konto wechselt, wenn ein Konto sein Kontingent aufgebraucht hat, bevor sie den Kontingentfehler zurückgibt; 0 deaktiviert den Wechsel',
Expand Down
2 changes: 1 addition & 1 deletion web/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ export const messages: Record<TranslationKey, string> = {
'settings.accountOrderRest': 'The other {count} accounts follow in ID order',
'settings.maxAccountSwitches': 'Max account switches',
'settings.maxAccountSwitchesHelp':
'How many times a request moves to another account after a non-quota upstream error such as 403 or 5xx; 0 disables switching, and quota errors do not count',
'How many times a request moves to another account after a non-quota upstream error such as 403 or 500; 0 disables switching, and quota errors do not count',
'settings.maxQuotaSwitches': 'Max switches on quota errors',
'settings.maxQuotaSwitchesHelp':
'How many times a request moves to another account when an account runs out of quota before it returns the quota error; 0 disables switching',
Expand Down
2 changes: 1 addition & 1 deletion web/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ export const messages: Record<TranslationKey, string> = {
'settings.accountOrderRest': "Les {count} autres comptes suivent dans l'ordre des ID",
'settings.maxAccountSwitches': 'Changements de compte max.',
'settings.maxAccountSwitchesHelp':
"Nombre de fois qu'une requête passe à un autre compte après une erreur amont hors quota, comme 403 ou 5xx ; 0 désactive le changement et les erreurs de quota ne comptent pas",
"Nombre de fois qu'une requête passe à un autre compte après une erreur amont hors quota, comme 403 ou 500 ; 0 désactive le changement et les erreurs de quota ne comptent pas",
'settings.maxQuotaSwitches': 'Changements max. sur quota épuisé',
'settings.maxQuotaSwitchesHelp':
'Nombre de fois qu’une requête passe à un autre compte quand un compte a épuisé son quota, avant de renvoyer l’erreur de quota ; 0 désactive le changement',
Expand Down
Loading