From 5493a812f9e25c7f214e57d766ca2d46fca69856 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Sat, 21 Nov 2026 15:02:07 +0800 Subject: [PATCH] =?UTF-8?q?=E5=82=99=E7=94=A8=E6=A8=A1=E5=9E=8B=EF=BC=88?= =?UTF-8?q?=E8=A8=88=E7=95=AB=20D1=EF=BC=9ABot=20=E4=B8=8D=E5=B1=AC?= =?UTF-8?q?=E6=96=BC=E4=BB=BB=E4=BD=95=E4=B8=80=E5=AE=B6=E4=BE=9B=E6=87=89?= =?UTF-8?q?=E5=95=86=EF=BC=89=EF=BC=9A=E6=AF=8F=E5=80=8B=20Bot=20=E6=9C=80?= =?UTF-8?q?=E5=A4=9A=208=20=E5=80=8B=EF=BC=8C=E7=85=A7=E9=A0=86=E5=BA=8F?= =?UTF-8?q?=E3=80=82Bot=20=E8=87=AA=E5=B7=B1=E7=9A=84=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E4=B8=8D=E8=83=BD=E5=9B=9E=E7=AD=94=E2=80=94=E2=80=94=E9=A1=8D?= =?UTF-8?q?=E5=BA=A6=E7=94=A8=E5=AE=8C=EF=BC=88402=E3=80=81=E3=80=8C?= =?UTF-8?q?=E5=B7=B2=E9=81=94=E7=94=A8=E9=87=8F=E4=B8=8A=E9=99=90=E3=80=8D?= =?UTF-8?q?=EF=BC=89=E3=80=81=E5=A4=AA=E5=BF=99=E6=88=96=E7=94=A8=E9=87=8F?= =?UTF-8?q?=E5=88=B0=E4=B8=8A=E9=99=90=EF=BC=88429=EF=BC=8C=E4=BE=9B?= =?UTF-8?q?=E6=87=89=E5=95=86=E8=87=AA=E5=B7=B1=E9=87=8D=E8=A9=A6=E5=AE=8C?= =?UTF-8?q?=E4=B9=8B=E5=BE=8C=EF=BC=89=E3=80=81=E9=87=91=E9=91=B0=E6=88=96?= =?UTF-8?q?=E7=99=BB=E5=85=A5=E4=B8=8D=E8=83=BD=E7=94=A8=EF=BC=88401?= =?UTF-8?q?=E3=80=81403=EF=BC=89=E3=80=81=E6=9C=8D=E5=8B=99=E5=87=BA?= =?UTF-8?q?=E9=8C=AF=EF=BC=885xx=E3=80=81408=E3=80=81529=EF=BC=89=E3=80=81?= =?UTF-8?q?=E9=80=A3=E4=B8=8D=E4=B8=8A=E2=80=94=E2=80=94=E5=B0=B1=E6=8F=9B?= =?UTF-8?q?=E4=B8=8B=E4=B8=80=E5=80=8B=E9=82=84=E6=B2=92=E4=BC=91=E6=81=AF?= =?UTF-8?q?=E7=9A=84=EF=BC=8C=E5=BE=9E=E5=90=8C=E4=B8=80=E6=AD=A5=E6=8E=A5?= =?UTF-8?q?=E8=91=97=E5=81=9A=EF=BC=88=E5=A4=B1=E6=95=97=E7=9A=84=E9=82=A3?= =?UTF-8?q?=E4=B8=80=E6=AD=A5=E6=B2=92=E6=9C=89=E5=81=9A=E4=BB=BB=E4=BD=95?= =?UTF-8?q?=E4=BA=8B=EF=BC=89=EF=BC=8C=E8=81=8A=E5=A4=A9=E8=A3=A1=E9=82=A3?= =?UTF-8?q?=E4=B8=80=E6=AD=A5=E5=89=8D=E9=9D=A2=E4=B8=80=E8=A1=8C=E3=80=8C?= =?UTF-8?q?=E6=94=B9=E7=94=A8=20=E2=97=8B=E2=97=8B=20=E7=B9=BC=E7=BA=8C?= =?UTF-8?q?=EF=BC=88=E2=97=8B=E2=97=8B=EF=BC=9A=E9=80=A3=E4=B8=8D=E4=B8=8A?= =?UTF-8?q?=EF=BC=8C10=20=E5=88=86=E9=90=98=E5=85=A7=E5=85=88=E4=B8=8D?= =?UTF-8?q?=E7=94=A8=E5=AE=83=EF=BC=89=E3=80=8D=EF=BC=8C=E4=B9=8B=E5=BE=8C?= =?UTF-8?q?=E7=9A=84=E5=9B=9E=E7=AD=94=E6=A8=99=E6=96=B0=E7=9A=84=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E3=80=82=E4=B8=8D=E8=83=BD=E7=94=A8=E7=9A=84=E9=82=A3?= =?UTF-8?q?=E5=80=8B=E4=BC=91=E6=81=AF=2010=20=E5=88=86=E9=90=98=EF=BC=88p?= =?UTF-8?q?roviders::rest=EF=BC=8Fis=5Fresting=EF=BC=89=EF=BC=9A=E9=80=99?= =?UTF-8?q?=E6=AE=B5=E6=99=82=E9=96=93=E7=9A=84=E6=96=B0=E4=B8=80=E8=BC=AA?= =?UTF-8?q?=E4=B8=80=E9=96=8B=E5=A7=8B=E5=B0=B1=E7=94=A8=E5=82=99=E7=94=A8?= =?UTF-8?q?=E7=9A=84=EF=BC=88=E3=80=8C=E6=94=B9=E7=94=A8=20=E2=97=8B?= =?UTF-8?q?=E2=97=8B=20=E5=9B=9E=E7=AD=94=EF=BC=88=E2=97=8B=E2=97=8B=20?= =?UTF-8?q?=E5=89=9B=E5=89=9B=E4=B8=8D=E8=83=BD=E7=94=A8=EF=BC=8C10=20?= =?UTF-8?q?=E5=88=86=E9=90=98=E5=85=A7=E5=85=88=E4=B8=8D=E7=94=A8=E5=AE=83?= =?UTF-8?q?=EF=BC=89=E3=80=8D=EF=BC=89=EF=BC=8C=E4=B9=8B=E5=BE=8C=E5=8F=88?= =?UTF-8?q?=E5=85=88=E7=94=A8=20Bot=20=E8=87=AA=E5=B7=B1=E7=9A=84=E3=80=82?= =?UTF-8?q?=E5=B0=8D=E8=A9=B1=E5=A4=AA=E9=95=B7=E3=80=81=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E4=B8=8D=E6=94=AF=E6=8F=B4=E5=B7=A5=E5=85=B7=E3=80=81=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E5=90=8D=E7=A8=B1=E6=89=93=E9=8C=AF=E4=B8=8D=E6=8F=9B?= =?UTF-8?q?=EF=BC=88=E6=8F=9B=E4=BA=86=E4=B9=9F=E4=B8=80=E6=A8=A3=EF=BC=8C?= =?UTF-8?q?=E6=88=96=E6=98=AF=E6=88=91=E5=80=91=E9=80=99=E9=82=8A=E7=9A=84?= =?UTF-8?q?=E4=BA=8B=EF=BC=89=E3=80=82=E9=82=84=E6=B2=92=E8=A8=AD=E5=AE=9A?= =?UTF-8?q?=E9=87=91=E9=91=B0=E7=9A=84=E4=BE=9B=E6=87=89=E5=95=86=E8=B7=B3?= =?UTF-8?q?=E9=81=8E=EF=BC=8C=E8=B7=9F=E8=87=AA=E5=B7=B1=E4=B8=80=E6=A8=A3?= =?UTF-8?q?=E7=9A=84=E4=B8=8D=E7=AE=97=EF=BC=9B=E6=8F=9B=E9=81=8E=E5=8E=BB?= =?UTF-8?q?=E4=B8=8D=E5=B8=B6=E6=80=9D=E8=80=83=E6=A8=A1=E5=BC=8F=E3=80=81?= =?UTF-8?q?=E4=B8=8D=E7=94=A8=E5=BF=AB=E9=80=9F=E6=A8=A1=E5=9E=8B=EF=BC=88?= =?UTF-8?q?=E9=82=A3=E6=98=AF=E5=8E=9F=E6=9C=AC=E9=82=A3=E5=AE=B6=E7=9A=84?= =?UTF-8?q?=EF=BC=89=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - model.rs:Bot.fallbacks(Fallback { provider, model }、MAX_FALLBACKS 8)。 - providers.rs:why_another_model(哪些錯誤換別的模型有用,和短的原因)、REST_SECS、rest、is_resting;StreamEvent::Switched(那一行, via)。 - agent.rs:Job.backups(Backup:可以直接送的位址、金鑰、模型、via、名字);主迴圈在一般的錯誤之前多一支:換 job.req、job.via,關掉快速模型,送 Switched,同一步再問一次。 - app.rs:一輪開始時把 Bot 的備用模型(準備好的)變成 Backup;自己的在休息就從第一個沒休息的開始並寫那一行(不再另外寫「上一個回答是」那行);Switched 在那一步前面插一行註記、正在寫的那則改標新模型。Bot 設定「思考模式」下面「備用模型」:每列供應商、模型名稱、「選擇」、×,「+ 加一個備用模型」先挑還沒用過、已經設定好的供應商;沒金鑰的那列寫「…還沒設定金鑰或登入:會跳過」。 - 手機:「改用 ○○ 回答/繼續」都用模型的星星圖示(以前只認「上一個回答是」那種)。 - 換模型本來就排在這一輪做完之後(一輪開始時 Job.req 就拿好了),文件寫明。 已驗證: cargo test 838 過(新:a_backup_model_carries_on_when_the_bots_own_cannot——兩個假模型服務,自己的回 401、備用的回答:Switched 那行、回答標備用的、自己的在休息;沒備用照舊報錯;備用跟自己一樣不換。only_failures_another_model_could_get_past_switch_models——429/402/401/503/連不上/已達用量上限會換,400 太長/404/不支援工具不換;含 featuremap::、layout_audit::);clippy 維持 12;scratch 照 models.md 那一步重跑(新的 scratch、zsh):Bot 1 改用連不上的 Ollama(127.0.0.1:9)、備用是假模型,第一輪「改用 自訂(OpenAI 相容) · fake-model 繼續(Ollama · llama3.2:連不上,10 分鐘內先不用它)」、回答標 fake-model,第二輪一開始就是「改用 … 回答(Ollama · llama3.2 剛剛不能用,10 分鐘內先不用它)」,手機兩行是星星圖示(重新整理後;舊頁面還是 ◎);桌面 Bot 設定「備用模型」按「+」多一列 Ollama · llama3.2、還沒金鑰的主模型提示在它上面。 未驗證: 真的供應商額度用完或 5xx(要付費帳號、真的出錯;用假服務的 401 和連不上代替);429 時供應商自己的重試要等完才換(可能幾十秒,沒有縮短);螢幕電腦上改備用模型同步到大腦(scratch 沒有第二台);Bot 自己改備用模型(要動 update_my_profile 的工具定義,鎖檔要簽名,沒做);手機的 Bot 設定還沒有這一欄;字數預算重建上下文沒做。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm --- FEATURES.md | 7 +++ docs/feature-map/models.md | 10 +-- docs/plan-2026-11-openbot.md | 2 +- mobile/index.html | 5 +- src/agent.rs | 86 ++++++++++++++++++++++++++ src/app.rs | 116 ++++++++++++++++++++++++++++++++--- src/appctl.rs | 1 + src/model.rs | 16 +++++ src/providers.rs | 74 ++++++++++++++++++++++ src/setup.rs | 1 + 10 files changed, 302 insertions(+), 16 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 3524c86..ce314f3 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1588,6 +1588,13 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 檔案不在原處(刪掉或搬走):灰字、紅字「不見了」,點不開。其他點一下用 AnyBot 的檢視器打開(Markdown、表格、圖片、PDF、影音、程式碼;用其他 App 打開、下載)。 - 螢幕電腦看的是從大腦抓過來的副本。手機還沒有(只有每個對話的「資料庫」)。功能地圖新的一區 library.md。 +### 備用模型(Bot 設定 › AI 供應商與模型) + +- 每個 Bot 最多 8 個備用模型,照順序(計畫 D1:Bot 不屬於任何一家供應商)。Bot 自己的模型不能回答——額度用完(402、「已達用量上限」)、太忙或用量到上限(429,供應商重試完之後)、金鑰或登入不能用(401、403)、服務出錯(5xx、408、529)、連不上——就換下一個還沒休息的,從同一步接著做(失敗的那一步沒有做任何事),聊天裡寫一行「改用 ○○ 繼續(○○:連不上,10 分鐘內先不用它)」,那之後的回答標新的模型。 +- 不能用的那個休息 10 分鐘:這段時間的新一輪一開始就用備用的(「改用 ○○ 回答(○○ 剛剛不能用,10 分鐘內先不用它)」),之後又先用 Bot 自己的。對話太長、模型不支援工具、模型名稱打錯不換。還沒設定金鑰的供應商跳過;換過去不用思考模式和執行步驟用的快速模型(那是原本那家的)。 +- 換模型本來就排在這一輪做完之後:一輪開始時就拿好了用哪個模型(Job.req),中途在設定裡換,正在跑的這一輪照舊。 +- Bot 設定「思考模式」下面「備用模型」:每列供應商、模型名稱、「選擇」、×,「+ 加一個備用模型」先挑還沒用過、已經設定好的供應商;沒設定金鑰的那列下面寫「…還沒設定金鑰或登入:會跳過」。手機的這兩行是星星圖示。Bot 自己還不能改備用模型(要動工具定義,等簽名);手機的 Bot 設定也還沒有這一欄。 + ### 市集(側邊欄左下角的格子圖示) - 一個視窗看能加給 Bot 的東西(計畫 C1,照 OpenBot 市集的排版):左欄「搜尋市集」、三個分頁「連接器」(8)「技能」(內建 8+Anthropic 開源 8)「Bot 範本」(5),下面「已安裝」列加入的連接器(綠點、關掉灰點、有問題紅點)和技能(最多 8 個,多的寫「還有 N」),點一列打開設定裡它自己的頁。 diff --git a/docs/feature-map/models.md b/docs/feature-map/models.md index d576321..a7556d2 100644 --- a/docs/feature-map/models.md +++ b/docs/feature-map/models.md @@ -6,8 +6,9 @@ - `models-providers` 供應商:xAI Grok、OpenAI、ChatGPT 方案、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama、自訂(OpenAI 相容),每個 Bot 各選各的。 - `models-where` 在哪裡跑:每家依服務網址標「本機」(localhost)、「區網」(私有位址、tailnet、.local、沒有點的名字)或「雲端」(其他;分不出來也算雲端),本機、區網是綠字。標在:設定 › 模型 每列右邊、標題下一句(在哪台跑、對話和檔案內容會不會送出去);Bot 設定「AI 供應商與模型」;聊天頂端名字後面;空聊天的模型那行;+ 的模型選單每家後面;手機 Bot 設定 › 模型 右邊、選模型時每家的標題、設定 › 模型。螢幕電腦和手機上,「本機」是大腦那台。只看網址、不查名字。 -- `models-switch` 換模型:資料、記憶、聊天都不用動;換過之後的第一個回答前面,聊天裡留一行「改用 ○○ 回答(上一個回答是 ○○)」(從哪裡換的都一樣;不送給模型;群組聊天不寫)。換過去的第一個請求先把舊步驟的結果收起(要用再讀),不一次送一大包;另一個模型的思考內容不會送過去(它會拒絕);模型說過的可讀長度各記各的,不會把別的模型的聊天壓得太短。 -- `models-bot` 「AI 供應商與模型」(Bot 設定裡):供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」——欄位名稱在上,說明在名稱旁的「?」。 +- `models-switch` 換模型:資料、記憶、聊天都不用動;換過之後的第一個回答前面,聊天裡留一行「改用 ○○ 回答(上一個回答是 ○○)」(從哪裡換的都一樣;不送給模型;群組聊天不寫)。正在跑的那一輪照舊。換過去的第一個請求先把舊步驟的結果收起(要用再讀);另一個模型的思考內容不會送過去(它會拒絕);模型說過的可讀長度各記各的。 +- `models-fallback` 備用模型(Bot 設定,最多 8 個,依序):Bot 自己的模型額度用完(402、「已達用量上限」)、太忙(429)、金鑰或登入不能用(401、403)、服務出錯(5xx)或連不上,換下一個還沒休息的,從同一步接著做,聊天裡一行「改用 ○○ 繼續(○○:原因,10 分鐘內先不用它)」。不能用的休息 10 分鐘,這段時間新的一輪直接用備用(「改用 ○○ 回答(○○ 剛剛不能用…)」)。對話太長、不支援工具、模型名稱錯不換;沒金鑰的跳過;換過去不用思考模式、快速模型。手機這兩行是星星圖示。 +- `models-bot` 「AI 供應商與模型」(Bot 設定裡):供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」、「備用模型」——欄位名稱在上,說明在名稱旁的「?」。 - `models-thinking` 思考模式:「自動(模型自己決定)」「快速(想得少,回得快)」「平衡」「深入(想得久,較慢)」。執行步驟用的模型:「自動」、「不分開(每一步都用上面的模型)」或指定一個;上面的模型負責想計畫、遇到問題和最後確認,中間的步驟交給快的模型。 - `models-chatgpt` 「ChatGPT 方案」:用 ChatGPT 帳號登入(OpenAI 的 Sign in with ChatGPT),用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰。第一次登入時 AnyBot 向 OpenAI 註冊自己,之後重用;登入後 設定 › 模型 寫「已用 ChatGPT 登入(信箱)」,第一次回答會說一次「你正在使用你的 ChatGPT 方案」。 @@ -34,12 +35,13 @@ - **ChatGPT 登出要先問**(covers `models-chatgpt`):請 Bot 登出,按拒絕;再看狀態。指令:`$CTL phone send '登出 [[call chatgpt_login {"action":"logout"}]]' && $CTL phone wait-text '登出 ChatGPT' --in '#ask' && $CTL phone wait-text '驗證小幫手 想要登出 ChatGPT 方案' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL phone send '狀態 [[call chatgpt_login {"action":"status"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "chatgpt_login" and .status == "done")] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "chatgpt_login") | {status, result}]'`。看到:登出先跳卡片「驗證小幫手 想要登出 ChatGPT 方案」(「登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答…」),拒絕後 denied;status 不用問,「還沒有用 ChatGPT 登入。」 - **用 ChatGPT 登入**(covers `models-chatgpt`):指令:走不到——登入會向 OpenAI 註冊、要真的 ChatGPT 帳號和方案(貼回網址、螢幕電腦的「完成登入」、額度用完都一樣)。看到:最接近的真路是上一步的 status 和 `cargo test chatgpt::`(註冊一次後重用、貼回網址、沒勾同意、額度用完)。 - **桌面**(covers `models-bot`、`models-providers`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot models ANYBOT_SHOT_TAB=providers`。看到:設定 › 模型 每家的金鑰欄和「使用 ChatGPT 繼續」;輸入框 + 的模型子選單(「(未設定金鑰)」)、Bot 設定的紅字「前往設定」靠自動測試。 -- 自動測試:`cargo test chatgpt::`、`cargo test providers::`(含 `calls_of_set_aside_steps_go_shortened`、`each_model_says_where_it_runs`)、`a_changed_model_leaves_a_line_in_the_chat`、`cargo test a_switched_model_starts_from_a_lean_request`、`cargo test profile::`、`cargo test remote::tests::only_the_owner_signs_the_brain_in_to_chatgpt`。 +- **備用模型接手**(covers `models-fallback`):Bot 1 改用連不上的 Ollama、備用假模型(只改沒秘密的欄位),問兩輪。指令:`$CTL stop && F="$(sed -n 's/^SCR=//p' target/verify-anybot/current/run.env)/data/state.json" && jq '.bots[0].provider = "Ollama" | .bots[0].model = "llama3.2" | .bots[0].fallbacks = [{"provider":"Custom","model":"fake-model"}] | .providers.ollama = {"base_url":"http://127.0.0.1:9"}' "$F" > "$F.new" && mv "$F.new" "$F" && $CTL serve && for n in 一 二; do $CTL api POST /api/bots/1/send "{\"text\":\"第${n}輪\"}" && $CTL wait-api /api/bots/1 "[.messages[]?.text] | any(test(\"回答:第${n}輪\"))" 90 || break; done && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.note) | .text]' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone shot models-fallback`;桌面:`ABV_ALLOW_WINDOW=1 $CTL desktop-shot fb ANYBOT_SHOT_VIEW=editor ANYBOT_SHOT_SIZE=1000x820 'ANYBOT_SHOT_SCROLL=500,400,-12@10' 'ANYBOT_SHOT_CLICK=335,375@125' ANYBOT_SHOT_FRAMES=140`。看到:第一輪前一行「改用 自訂(OpenAI 相容) · fake-model 繼續(Ollama · llama3.2:連不上…)」,回答標 fake-model;第二輪「改用 … 回答(… 剛剛不能用…)」;手機星星;「+」多一列。 +- 自動測試:`cargo test a_backup_model_carries_on_when_the_bots_own_cannot`、`cargo test only_failures_another_model_could_get_past_switch_models`、`cargo test chatgpt::`、`cargo test providers::`(含 `calls_of_set_aside_steps_go_shortened`、`each_model_says_where_it_runs`)、`a_changed_model_leaves_a_line_in_the_chat`、`cargo test a_switched_model_starts_from_a_lean_request`、`cargo test profile::`、`cargo test remote::tests::only_the_owner_signs_the_brain_in_to_chatgpt`。 ## 陷阱 - 只換供應商不給模型,模型會換成那家的建議模型;在 Bot 設定裡換供應商也會換模型。 -- ChatGPT 方案:額度用完會停下來說「已達用量上限(ChatGPT 方案)」並給「管理用量」連結,不會自動改用 API 金鑰付費,也不會一直重試;之後沒人在看的(例行任務、訊息管道、檢查)先不送,等你自己問的那一次成功才恢復。回答沒有正常結束(例如太長)算失敗,那一步的工具不執行;沒勾同意使用方案,算登入了但不能用;在 ChatGPT 設定裡中斷連線,下一次要求才會發現,要重新登入。 +- ChatGPT 方案:額度用完會停下來說「已達用量上限(ChatGPT 方案)」並給「管理用量」連結,不會自動改用 API 金鑰付費(Bot 加了備用模型才換),也不會一直重試;之後沒人在看的(例行任務、訊息管道、檢查)先不送,等你自己問的那一次成功才恢復。回答沒有正常結束(例如太長)算失敗,那一步的工具不執行;沒勾同意使用方案,算登入了但不能用;在 ChatGPT 設定裡中斷連線,下一次要求才會發現,要重新登入。 - 訊息管道和團隊成員傳來的對話拿不到 `chatgpt_login`。 - 語音轉文字、朗讀不能用方案,還是要 OpenAI 的 API 金鑰([appearance](appearance.md))。 - 登入的 token 存在大腦,不會傳到螢幕電腦和手機。連到大腦的螢幕電腦:設定 › 模型 › ChatGPT 方案 按鈕一樣,登入頁開在這台;登入後那頁打不開,把網址貼進下面的欄位按「完成登入」。手機同樣貼回網址。`chatgpt_login` 的 logout、switch_account 會先跳確認卡片。 diff --git a/docs/plan-2026-11-openbot.md b/docs/plan-2026-11-openbot.md index d3e6dd1..55bc31f 100644 --- a/docs/plan-2026-11-openbot.md +++ b/docs/plan-2026-11-openbot.md @@ -154,7 +154,7 @@ ## D. 後端(最重要的學習方向) -**D1. Bot 和模型供應商分開**——11/21 做了「聊天裡留一行『改用 ○○ 回答』」。換的動作排到這一輪做完、字數預算重建上下文、備用模型自動接手還沒做。 +**D1. Bot 和模型供應商分開**——11/21 做了「聊天裡留一行『改用 ○○ 回答』」和「備用模型」(最多 8 個,額度用完、金鑰不能用、服務出錯、連不上就從同一步換下一個,失敗的休息 10 分鐘)。換的動作本來就排到這一輪做完(一輪開始時就拿好模型)。字數預算重建上下文、Bot 自己改備用模型(工具定義,等簽名)、手機的欄位還沒做。 - 現況:聊天、記憶、工作區、任務、目標、例行任務都掛在 Bot 上,換模型不會掉(`models-switch`,提交 ec8fe4b 把舊的工具結果收起來、不送別家模型的思考)。缺:換的那一刻正在跑的那一輪怎麼辦、沒有備用模型自動接手、聊天裡沒有「換了模型」的記號、介面上沒把「Bot」和「用哪家模型」當兩件事。 - 原則:Bot 的身分、工作區、聊天、記憶、任務都不屬於任何供應商;供應商那邊的會話只是可以丟掉的快取。 - 做什麼:換模型/供應商時——進行中的那一輪先跑完(換的動作排著);下一輪用大腦自己的聊天紀錄重建上下文, diff --git a/mobile/index.html b/mobile/index.html index bad7d5b..365d79d 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -2005,8 +2005,9 @@ function renderMsgs() { if (m.branch && m.role === "user") { h += `
${ic("activity", 13)}支線的結果已交給正在做事的主線
`; return; } // 目標: AnyBot's own line about the goal (met, paused…), not the bot's words. if (m.note) { - // (A goal's lines wear the target; 「改用 ○○ 回答」 the model's sparkle.) - h += `
${ic(/^改用 .+ 回答(上一個回答是 /.test(m.text) ? "sparkles" : "target", 13)}${esc(m.text)}
`; + // (A goal's lines wear the target; 「改用 ○○ 回答/繼續」 — another model, chosen or a + // backup taking over — the model's sparkle.) + h += `
${ic(/^改用 .+ (回答|繼續)(/.test(m.text) ? "sparkles" : "target", 13)}${esc(m.text)}
`; return; } if (m.role === "user") { diff --git a/src/agent.rs b/src/agent.rs index d78e5de..c3b2625 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -40,8 +40,23 @@ pub const KEEP_RECENT_MESSAGES: usize = 6; /// Characters of each old message given to the summarizer (estimated). const SUMMARY_SNIPPET_CHARS: usize = 2_000; +/// 備用模型 (D1): a model to go on with when the bot's own can't answer, ready to send to. +#[derive(Clone, Debug)] +pub struct Backup { + pub kind: crate::providers::ProviderKind, + pub base_url: String, + pub api_key: String, + pub model: String, + /// What its answers are marked with (as `Job::via`). + pub via: String, + /// How the chat names it: 「OpenRouter · kimi-k3」. + pub label: String, +} + pub struct Job { pub req: ChatRequest, + /// 備用模型, in the bot's order, the one it started on taken out (see Backup). + pub backups: Vec, /// The quick model that carries out planned steps (same provider), or None: every step uses /// `req.model`. See `step_plan`. pub step_model: Option, @@ -104,6 +119,12 @@ pub struct Job { pub unattended: bool, } +/// 備用模型: where in the job's backups the next one to try is — not resting, not the model it is +/// on now. +fn next_backup(job: &Job) -> Option { + job.backups.iter().position(|b| !(b.base_url == job.req.base_url && b.model == job.req.model) && !providers::is_resting(&b.base_url, &b.model)) +} + /// What a turn in plan mode switches to once the plan is approved. pub struct Drafting { pub plan: crate::plan::Plan, @@ -2443,6 +2464,24 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } } } + // 備用模型 (D1): this model can't answer in a way another could get past (credit + // used up, key refused, service failing or out of reach): the next of the bot's + // backups that isn't resting asks this same step again — nothing of the failed + // one was done — and this one rests REST_SECS. The chat gets a line saying so. + Err(e) if !cancel.load(Ordering::Relaxed) && providers::why_another_model(&e).is_some() && next_backup(&job).is_some() => { + let why = providers::why_another_model(&e).unwrap_or_default(); + providers::rest(&job.req.base_url, &job.req.model); + let Some(i) = next_backup(&job) else { continue }; + let b = job.backups.remove(i); + let was = format!("{} · {}", job.req.kind.label(), job.req.model); + log::warn!("AnyBot:{was} 不能用({e}),改用備用模型 {}", b.label); + let line = format!("改用 {} 繼續({was}:{why},{} 分鐘內先不用它)", b.label, providers::REST_SECS / 60); + job.req = ChatRequest { kind: b.kind, base_url: b.base_url, api_key: b.api_key, model: b.model, effort: String::new(), ..job.req.clone() }; + job.via = b.via.clone(); + // (The quick model was the other one's.) + plan.quick_failed(); + send(StreamEvent::Switched(line, b.via)); + } Err(e) => { closing.close(crate::oplog::Outcome::Failed); send(StreamEvent::Error(e)); @@ -2702,6 +2741,7 @@ mod tests { fn test_job() -> Job { Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: String::new(), api_key: String::new(), model: String::new(), system: String::new(), history: vec![], tools: vec![], session: String::new(), effort: String::new() }, + backups: vec![], step_model: None, computers: vec![], default_computer: String::new(), @@ -2733,6 +2773,48 @@ mod tests { } } + /// 備用模型 (D1): the bot's model refuses (its key, here) — the backup answers the same step, + /// the chat gets the line saying so, the answer is marked as the backup's, and the model that + /// failed rests (the next turn starts on the backup). A refusal another model can't get past + /// (the chat too long, a wrong name) fails as before; with no backup left, too. + #[test] + fn a_backup_model_carries_on_when_the_bots_own_cannot() { + use crate::testkit::{Fake, Format, Reply}; + let refused = || Reply::Fail { status: 401, body: r#"{"error":{"message":"invalid api key"}}"#.into(), retry_after: None }; + let own = Fake::start(Format::OpenAi, vec![], Some(refused())); + let backup = Fake::start(Format::OpenAi, vec![], Some(Reply::text("備用的回答"))); + let run = |job: Job| { + let (tx, rx) = channel(); + spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); + let mut got = vec![]; + loop { + match rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled") { + (_, StreamEvent::Done) => break got, + (_, StreamEvent::Error(e)) => { + got.push(format!("錯誤:{e}")); + break got; + } + (_, StreamEvent::Switched(line, via)) => got.push(format!("換:{line}|{via}")), + (_, StreamEvent::StepDone(m)) => got.push(format!("答:{}|{}", m.text, m.via)), + _ => {} + } + } + }; + let own_req = ChatRequest { kind: ProviderKind::Custom, base_url: own.base(), api_key: "k".into(), model: "own-model".into(), system: String::new(), history: vec![Message::user("你好")], tools: vec![], session: String::new(), effort: String::new() }; + let to_backup = || Backup { kind: ProviderKind::Custom, base_url: backup.base(), api_key: "k".into(), model: "backup-model".into(), via: "自訂 · backup-model".into(), label: "自訂 · backup-model".into() }; + let got = run(Job { req: own_req.clone(), backups: vec![to_backup()], via: "自訂 · own-model".into(), ..test_job() }); + assert_eq!(got.len(), 2, "{got:?}"); + assert!(got[0].starts_with("換:改用 自訂 · backup-model 繼續(") && got[0].contains("own-model:金鑰或登入不能用") && got[0].ends_with("|自訂 · backup-model"), "{got:?}"); + assert_eq!(got[1], "答:備用的回答|自訂 · backup-model"); + assert!(providers::is_resting(&own.base(), "own-model") && !providers::is_resting(&backup.base(), "backup-model")); + // No backup: the refusal is the answer, as before. + let got = run(Job { req: ChatRequest { model: "own-model-2".into(), ..own_req.clone() }, via: "自訂 · own-model-2".into(), ..test_job() }); + assert!(got.len() == 1 && got[0].starts_with("錯誤:錯誤 401") && got[0].contains("金鑰無效"), "{got:?}"); + // The backup is the same model as the one failing: nothing to switch to. + let got = run(Job { req: ChatRequest { model: "own-model-3".into(), ..own_req.clone() }, backups: vec![Backup { base_url: own.base(), model: "own-model-3".into(), ..to_backup() }], ..test_job() }); + assert!(got.len() == 1 && got[0].starts_with("錯誤:"), "{got:?}"); + } + #[test] fn computer_words_need_word_boundaries() { // "mac" as its own word names this computer; inside longer words (macOS, a device @@ -4277,6 +4359,7 @@ echo 'done送出了' > done.html; (setsid pyt std::fs::write(w.join("a.txt"), "hi").unwrap(); let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("有什麼檔案?")], tools: tools::specs(), session: String::new(), effort: String::new() }, + backups: vec![], step_model: None, computers: vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w } }], default_computer: crate::model::THIS_COMPUTER_NAME.into(), @@ -4367,6 +4450,7 @@ echo 'done送出了' > done.html; (setsid pyt let steer = Arc::new(Mutex::new(vec![Queued::with_files("順便用英文", vec![att])])); let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("打招呼")], tools: vec![], session: String::new(), effort: String::new() }, + backups: vec![], step_model: None, computers: vec![], default_computer: crate::model::BOT_COMPUTER_NAME.into(), @@ -4460,6 +4544,7 @@ echo 'done送出了' > done.html; (setsid pyt std::fs::write(w.join("note.txt"), "hi").unwrap(); let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("看看我的電腦")], tools: tools::specs(), session: String::new(), effort: String::new() }, + backups: vec![], step_model: None, computers: vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w } }], default_computer: crate::model::THIS_COMPUTER_NAME.into(), @@ -4689,6 +4774,7 @@ echo 'done送出了' > done.html; (setsid pyt std::fs::create_dir_all(&w).unwrap(); let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("做一個檔案")], tools: tools::specs(), session: String::new(), effort: String::new() }, + backups: vec![], step_model: None, computers: vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }], default_computer: crate::model::THIS_COMPUTER_NAME.into(), diff --git a/src/app.rs b/src/app.rs index 7ad38f5..254cbc6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1984,11 +1984,41 @@ impl App { session: format!("anybot-bot-{bot_id}"), effort: b.thinking.clone(), }; - let via = if speaker.is_some() { format!("{} · {} · {}", b.name, b.provider.label(), b.model) } else { format!("{} · {}", b.provider.label(), b.model) }; + let via_of = |kind: ProviderKind, model: &str| if speaker.is_some() { format!("{} · {} · {}", b.name, kind.label(), model) } else { format!("{} · {}", kind.label(), model) }; + // 備用模型 (D1): the bot's backups that are ready (a key, or a sign-in), each ready to + // send to. The bot's own model resting (it failed in the last 10 minutes): this turn + // starts on the first backup that isn't, and the chat says so. + let mut backups: Vec = b + .fallbacks + .iter() + .filter(|f| !(f.provider == b.provider && f.model == b.model) && !f.model.trim().is_empty()) + .filter_map(|f| { + let fps = self.state.provider(f.provider); + providers::ready(f.provider, &fps.api_key).then(|| agent::Backup { + kind: f.provider, + base_url: providers::resolve_base(f.provider, &fps.base_url), + api_key: providers::resolve_key_for(f.provider, &fps.api_key, &fps.base_url), + model: f.model.trim().to_string(), + via: via_of(f.provider, f.model.trim()), + label: format!("{} · {}", f.provider.label(), f.model.trim()), + }) + }) + .collect(); + let mut req = req; + let mut on_backup = None; + if providers::is_resting(&req.base_url, &req.model) { + if let Some(i) = backups.iter().position(|x| !providers::is_resting(&x.base_url, &x.model)) { + let x = backups.remove(i); + on_backup = Some(format!("改用 {} 回答({} · {} 剛剛不能用,{} 分鐘內先不用它)", x.label, b.provider.label(), b.model, providers::REST_SECS / 60)); + req = ChatRequest { kind: x.kind, base_url: x.base_url, api_key: x.api_key, model: x.model, effort: String::new(), ..req }; + } + } + let via = via_of(req.kind, &req.model); // 換了模型 (D1): a line where the model changed, however it was changed (the + menu, Bot - // 設定, the phone, the bot itself). The bot, its chat, memory and work are the same; only - // who writes the answers is not. (A group's members each have their own: not there.) - let changed = speaker.is_none().then(|| model_changed_line(&conv.messages, &via)).flatten(); + // 設定, the phone, the bot itself, a backup taking over). The bot, its chat, memory and + // work are the same; only who writes the answers is not. (A group's members each have + // their own: not there.) + let changed = on_backup.clone().or_else(|| speaker.is_none().then(|| model_changed_line(&conv.messages, &via)).flatten()); if let Some(c) = self.state.bot_mut(bot_id) { if let Some(line) = changed { c.messages.push(Message { note: true, ..Message::assistant(&line, "") }); @@ -2035,11 +2065,17 @@ impl App { // 完成條件: a routine's run counts its sends against the routine's number. let target_sends = conv.messages.iter().rev().find(|m| m.role == Role::User && !m.steer).map(|m| m.routine).filter(|&id| id != 0).and_then(|id| self.state.bots.iter().flat_map(|x| x.routines.iter()).find(|r| r.id == id)).map(|r| r.target_sends).unwrap_or(0); let job = agent::Job { - step_model: match b.step_model.trim() { - "off" => None, - "" => b.provider.quick_model(&b.model).map(String::from), - m if m == b.model => None, - m => Some(m.to_string()), + backups, + // (On a backup: the bot's quick model is its own provider's, not this one's.) + step_model: if on_backup.is_some() { + None + } else { + match b.step_model.trim() { + "off" => None, + "" => b.provider.quick_model(&b.model).map(String::from), + m if m == b.model => None, + m => Some(m.to_string()), + } }, req, computers, @@ -3317,6 +3353,24 @@ impl App { self.delivered.push((id, qid)); self.save_now = true; } + // 備用模型 (D1): the bot's model couldn't answer and another carries on: a line + // where it happened; the step under way is the new model's. + StreamEvent::Switched(line, via) => { + let note = Message { note: true, ..Message::assistant(&line, "") }; + match b.messages.last_mut() { + Some(m) if m.role == Role::Assistant && m.text.is_empty() && m.tool_calls.is_empty() => { + m.via = via; + let at = b.messages.len() - 1; + b.messages.insert(at, note); + } + _ => { + let author = b.messages.iter().rev().find(|m| m.role == Role::Assistant).map(|m| m.author).unwrap_or(0); + b.messages.push(note); + b.messages.push(Message { author, ..Message::assistant("", &via) }); + } + } + self.save_now = true; + } // (In a group chat, the member speaking: who said it stays on every step.) StreamEvent::NextStep(via) => { let author = b.messages.iter().rev().find(|m| m.role == Role::Assistant).map(|m| m.author).unwrap_or(0); @@ -3721,6 +3775,7 @@ impl App { provider, model, step_model: String::new(), + fallbacks: vec![], thinking: String::new(), pinned: false, messages: Default::default(), @@ -5679,6 +5734,49 @@ impl App { } }); } + // 備用模型 (D1): tried in order when the model above can't answer. + form_row_help(ui, "備用模型", "上面的模型不能回答時(額度用完、金鑰不能用、服務出錯或連不上),照順序改用這裡的模型,從同一步接著做;不能用的那個 10 分鐘內先不用,之後又先用上面的。聊天裡會寫一行「改用 ○○ 繼續」。還沒設定金鑰的供應商會跳過。", p, |ui| { + ui.vertical(|ui| { + let mut remove = None; + for (i, f) in b.fallbacks.iter_mut().enumerate() { + ui.horizontal(|ui| { + let before = f.provider; + egui::ComboBox::from_id_salt(("bot_fallback_provider", i)).selected_text(f.provider.label()).width(150.0).show_ui(ui, |ui| { + for k in ALL_PROVIDERS { + ui.selectable_value(&mut f.provider, k, k.label()); + } + }); + if f.provider != before { + f.model = self.default_model(f.provider); + } + let w = (ui.available_width() - 110.0).max(80.0); + ui.add(egui::TextEdit::singleline(&mut f.model).hint_text(t("模型名稱")).desired_width(w)); + egui::ComboBox::from_id_salt(("bot_fallback_model", i)).selected_text(t("選擇")).width(60.0).show_ui(ui, |ui| { + for m in self.models_for(f.provider) { + if ui.selectable_label(m == f.model, &m).clicked() { + f.model = m; + } + } + }); + if crate::icons::button(ui, crate::icons::Icon::Close, 22.0, p.text3, p.hover).on_hover_text(t("移除這個備用模型")).clicked() { + remove = Some(i); + } + }); + if !providers::ready(f.provider, &self.state.provider(f.provider).api_key) { + ui.label(RichText::new(format!("{}{}", f.provider.label(), t("還沒設定金鑰或登入:會跳過"))).size(FONT_XS).color(p.text3)); + } + } + if let Some(i) = remove { + b.fallbacks.remove(i); + } + if b.fallbacks.len() < crate::model::MAX_FALLBACKS && ui.add(secondary_button("+ 加一個備用模型")).clicked() { + // The first ready provider not used yet (else any other ready one, else the same). + let ready = |k: &ProviderKind| *k != b.provider && providers::ready(*k, &self.state.provider(*k).api_key); + let k = ALL_PROVIDERS.into_iter().find(|k| ready(k) && !b.fallbacks.iter().any(|f| f.provider == *k)).or_else(|| ALL_PROVIDERS.into_iter().find(ready)).unwrap_or(b.provider); + b.fallbacks.push(crate::model::Fallback { provider: k, model: self.default_model(k) }); + } + }); + }); }); setting_card(ui, p, |ui| { let summary = if b.tools_enabled { t("可以查看、修改檔案和執行指令") } else { t("關閉") }; diff --git a/src/appctl.rs b/src/appctl.rs index 12cc0c0..cc30bc5 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -891,6 +891,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome provider, model: model.clone(), step_model: String::new(), + fallbacks: vec![], thinking: String::new(), pinned: false, messages: Default::default(), diff --git a/src/model.rs b/src/model.rs index 6eff2ee..dd7f98f 100644 --- a/src/model.rs +++ b/src/model.rs @@ -398,6 +398,16 @@ impl Message { } } +/// One 備用模型: a provider and a model of it. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct Fallback { + pub provider: ProviderKind, + pub model: String, +} + +/// How many 備用模型 a bot may have. +pub const MAX_FALLBACKS: usize = 8; + #[derive(Clone, Serialize, Deserialize, Debug)] pub struct Bot { pub id: u64, @@ -416,6 +426,11 @@ pub struct Bot { /// and gets the hard steps; the quick one carries out the planned steps in between. #[serde(default, skip_serializing_if = "String::is_empty")] pub step_model: String, + /// 備用模型 (D1): tried in order when this bot's own model can't answer (its credit is used + /// up, its key refused, the service down or out of reach); at most MAX_FALLBACKS. The one + /// that failed rests 10 minutes (providers::rest), then the bot's own is tried first again. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub fallbacks: Vec, /// 思考模式: "" leaves it to the model; "low" | "medium" | "high" is how long this bot's own /// model thinks before it answers (providers::EFFORTS). The quick step model never gets it. #[serde(default, skip_serializing_if = "String::is_empty")] @@ -1334,6 +1349,7 @@ impl State { provider, model: provider.suggested_model().into(), step_model: String::new(), + fallbacks: vec![], thinking: String::new(), pinned, messages: Default::default(), diff --git a/src/providers.rs b/src/providers.rs index 5f8503e..0c7d589 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -231,6 +231,9 @@ pub enum StreamEvent { /// (no bubble until it shows something). The status line, and the first-response deadline /// again — unlike Retrying, which also comes while a summary is written mid-turn. Nudged(String), + /// 備用模型 (D1): the bot's model couldn't answer and another carries on from this step — + /// the line for the chat, and what the new model's answers are marked with (`via`). + Switched(String, String), /// The model asked for a tool; shown at once, run after the step ends. ToolCall(ToolCall), /// A tool's state changed (waiting for approval, running, done…). @@ -759,6 +762,52 @@ pub fn is_context_overflow(msg: &str) -> bool { msg.starts_with(CONTEXT_OVERFLOW) } +/// 備用模型 (D1): a failure another model could get past — this one's credit or limit is used +/// up, its key refused, its service failing or out of reach. (Not the chat being too long, a +/// model that has no tools, a wrong model name: another model meets those too, or they are ours.) +/// The words why, short, for the chat; None when another model wouldn't help. +pub fn why_another_model(err: &str) -> Option<&'static str> { + let e = err.trim_start(); + if e.starts_with("已達用量上限") || e.starts_with("錯誤 402") { + return Some("額度用完了"); + } + if e.starts_with("錯誤 429") { + return Some("太忙或用量到上限"); + } + if e.starts_with("錯誤 401") || e.starts_with("錯誤 403") || e.starts_with("ChatGPT 的登入不能用了") { + return Some("金鑰或登入不能用"); + } + let server_error = e.strip_prefix("錯誤 5").is_some_and(|r| r.chars().take(2).filter(char::is_ascii_digit).count() == 2); + if e.starts_with("錯誤 408") || e.starts_with("錯誤 529") || server_error || e.starts_with("ChatGPT 方案暫時沒辦法用") { + return Some("服務出錯"); + } + if e.starts_with("連不上 ") { + return Some("連不上"); + } + None +} + +/// How long a model that failed is passed over for its bot's 備用模型 (seconds). +pub const REST_SECS: u64 = 600; + +fn resting() -> &'static std::sync::Mutex> { + static R: std::sync::OnceLock>> = std::sync::OnceLock::new(); + R.get_or_init(Default::default) +} + +/// This model (at this address) failed in a way another could get past: passed over for +/// REST_SECS. +pub fn rest(base_url: &str, model: &str) { + resting().lock().unwrap().insert((base_url.to_string(), model.to_string()), std::time::Instant::now()); +} + +/// Still resting since it failed. +pub fn is_resting(base_url: &str, model: &str) -> bool { + let mut r = resting().lock().unwrap(); + r.retain(|_, at| at.elapsed().as_secs() < REST_SECS); + r.contains_key(&(base_url.to_string(), model.to_string())) +} + fn http_error(status: u16, body: &str, retry_after: Option) -> Failure { let detail = serde_json::from_str::(body) .ok() @@ -2259,6 +2308,31 @@ pub fn list_models(kind: ProviderKind, base_url: &str, api_key: &str) -> Result< Ok(ids) } +#[cfg(test)] +mod backup_tests { + use super::*; + + /// 備用模型: what another model could get past, and what it couldn't. + #[test] + fn only_failures_another_model_could_get_past_switch_models() { + let why = |e: &str| why_another_model(e); + assert_eq!(why(&http_error(429, r#"{"error":{"message":"rate"}}"#, None).msg), Some("太忙或用量到上限")); + assert_eq!(why(&http_error(402, r#"{"error":{"message":"Insufficient credits"}}"#, None).msg), Some("額度用完了")); + assert_eq!(why(&http_error(401, "{}", None).msg), Some("金鑰或登入不能用")); + assert_eq!(why(&http_error(503, "{}", None).msg), Some("服務出錯")); + assert_eq!(why("連不上 OpenRouter:timed out"), Some("連不上")); + assert_eq!(why("已達用量上限(ChatGPT 方案):…"), Some("額度用完了")); + // Another model would meet these too, or they are ours to fix. + assert_eq!(why(&http_error(400, r#"{"error":{"message":"maximum context length exceeded"}}"#, None).msg), None); + assert_eq!(why(&http_error(404, "{}", None).msg), None); + assert_eq!(why(&http_error(400, r#"{"error":{"message":"tools not supported"}}"#, None).msg), None); + assert_eq!(why("錯誤 50x 不是數字"), None); + // Resting: only that model at that address, for REST_SECS. + rest("http://a/v1", "m1"); + assert!(is_resting("http://a/v1", "m1") && !is_resting("http://a/v1", "m2") && !is_resting("http://b/v1", "m1")); + } +} + #[cfg(test)] mod tests { /// Each model says where it runs — this computer, the person's own network, a company's diff --git a/src/setup.rs b/src/setup.rs index 4905882..e172310 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1146,6 +1146,7 @@ fn seed_first() -> i32 { provider: kind, model, step_model: String::new(), + fallbacks: vec![], thinking: String::new(), pinned: false, folder: String::new(),