Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve ai settings https://github.com/siyuan-note/siyuan/issues/17914

Daniel33af4c0a5ec1
diff --git a/app/appearance/icons/index.html b/app/appearance/icons/index.html
index d1c89ef783..2992e776dd 100644
--- a/app/appearance/icons/index.html
+++ b/app/appearance/icons/index.html
@@ -28,6 +28,12 @@
<body>
<h2>SiYuan</h2>
<div class="fn__clear">
+ <div>
+ <svg>
+ <use xlink:href="#iconPlugZap"></use>
+ </svg>
+ iconPlugZap
+ </div>
<div>
<svg>
<use xlink:href="#iconSquareAsterisk"></use>
diff --git a/app/appearance/icons/litheness/icon.js b/app/appearance/icons/litheness/icon.js
index 15380bde7b..8cdeabc40a 100644
--- a/app/appearance/icons/litheness/icon.js
+++ b/app/appearance/icons/litheness/icon.js
@@ -1,5 +1,8 @@
document.body.insertAdjacentHTML('afterbegin', `<svg id="iconsLitheness" style="position: absolute; width: 0; height: 0; overflow: hidden;">
<defs>
+ <symbol id="iconPlugZap" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z"/><path d="m2 22 3-3"/><path d="M7.5 13.5 10 11"/><path d="M10.5 16.5 13 14"/><path d="m18 3-4 4h6l-4 4"/>
+ </symbol>
<symbol id="iconSquareAsterisk" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M12 8v8"/><path d="m8.5 14 7-4"/><path d="m8.5 10 7 4"/>
</symbol>
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 4824f67e66..3f7d5ca075 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "اختبار الاتصال",
+ "testConnectionTesting": "جارٍ الاختبار...",
+ "testConnectionSuccess": "تم الاتصال بنجاح",
+ "testConnectionFail": "فشل الاتصال",
+ "testConnectionFailModelRequired": "يرجى إدخال اسم النموذج",
+ "testConnectionFailModelNotFound": "هذا النموذج غير موجود في قائمة النماذج المتاحة",
"secretsVariables": "الأسرار والمتغيرات",
"secrets": "الأسرار",
"variables": "المتغيرات",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index c4c14753e4..2481f57bec 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Verbindung testen",
+ "testConnectionTesting": "Wird getestet …",
+ "testConnectionSuccess": "Verbindung erfolgreich",
+ "testConnectionFail": "Verbindung fehlgeschlagen",
+ "testConnectionFailModelRequired": "Bitte den Modellnamen eingeben",
+ "testConnectionFailModelNotFound": "Dieses Modell ist nicht in der Liste der verfügbaren Modelle",
"secretsVariables": "Secrets und Variablen",
"secrets": "Secrets",
"variables": "Variablen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 1398709cc0..dcef245590 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Test connection",
+ "testConnectionTesting": "Testing...",
+ "testConnectionSuccess": "Connection successful",
+ "testConnectionFail": "Connection failed",
+ "testConnectionFailModelRequired": "Please enter the model name",
+ "testConnectionFailModelNotFound": "This model is not in the available model list",
"secretsVariables": "Secrets and Variables",
"secrets": "Secrets",
"variables": "Variables",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index aa0c088664..5d1c3932e2 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Probar conexión",
+ "testConnectionTesting": "Probando...",
+ "testConnectionSuccess": "Conexión correcta",
+ "testConnectionFail": "Conexión fallida",
+ "testConnectionFailModelRequired": "Introduzca el nombre del modelo",
+ "testConnectionFailModelNotFound": "Este modelo no está en la lista de modelos disponibles",
"secretsVariables": "Secretos y variables",
"secrets": "Secretos",
"variables": "Variables",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 1bf042ee08..a3b33d12bb 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Tester la connexion",
+ "testConnectionTesting": "Test en cours...",
+ "testConnectionSuccess": "Connexion réussie",
+ "testConnectionFail": "Échec de la connexion",
+ "testConnectionFailModelRequired": "Veuillez saisir le nom du modèle",
+ "testConnectionFailModelNotFound": "Ce modèle ne figure pas dans la liste des modèles disponibles",
"secretsVariables": "Secrets et variables",
"secrets": "Secrets",
"variables": "Variables",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 5d3b35b7fa..035e422425 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "בדיקת חיבור",
+ "testConnectionTesting": "בודק...",
+ "testConnectionSuccess": "החיבור הצליח",
+ "testConnectionFail": "החיבור נכשל",
+ "testConnectionFailModelRequired": "נא להזין את שם המודל",
+ "testConnectionFailModelNotFound": "מודל זה אינו ברשימת המודלים הזמינים",
"secretsVariables": "סודות ומשתנים",
"secrets": "סודות",
"variables": "משתנים",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index da1aa2fa38..0f602f9529 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "कनेक्शन परीक्षण",
+ "testConnectionTesting": "परीक्षण कर रहा है...",
+ "testConnectionSuccess": "कनेक्शन सफल",
+ "testConnectionFail": "कनेक्शन विफल",
+ "testConnectionFailModelRequired": "कृपया मॉडल नाम दर्ज करें",
+ "testConnectionFailModelNotFound": "यह मॉडल उपलब्ध मॉडल सूची में नहीं है",
"secretsVariables": "रहस्य और चर",
"secrets": "रहस्य",
"variables": "चर",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 912b9d9c9d..d79992eab8 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Uji koneksi",
+ "testConnectionTesting": "Menguji...",
+ "testConnectionSuccess": "Koneksi berhasil",
+ "testConnectionFail": "Koneksi gagal",
+ "testConnectionFailModelRequired": "Silakan masukkan nama model",
+ "testConnectionFailModelNotFound": "Model ini tidak ada dalam daftar model yang tersedia",
"secretsVariables": "Rahasia dan Variabel",
"secrets": "Rahasia",
"variables": "Variabel",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 0963626765..cbc832676b 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Testa connessione",
+ "testConnectionTesting": "Test in corso...",
+ "testConnectionSuccess": "Connessione riuscita",
+ "testConnectionFail": "Connessione non riuscita",
+ "testConnectionFailModelRequired": "Inserisci il nome del modello",
+ "testConnectionFailModelNotFound": "Questo modello non è presente nell'elenco dei modelli disponibili",
"secretsVariables": "Secret e variabili",
"secrets": "Secret",
"variables": "Variabili",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index b163392e10..f92a3b9d5d 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "接続テスト",
+ "testConnectionTesting": "テスト中...",
+ "testConnectionSuccess": "接続成功",
+ "testConnectionFail": "接続失敗",
+ "testConnectionFailModelRequired": "モデル名を入力してください",
+ "testConnectionFailModelNotFound": "このモデルは利用可能なモデル一覧にありません",
"secretsVariables": "シークレットと変数",
"secrets": "シークレット",
"variables": "変数",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 1bb25e1d22..e8391f2f93 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "연결 테스트",
+ "testConnectionTesting": "테스트 중...",
+ "testConnectionSuccess": "연결 성공",
+ "testConnectionFail": "연결 실패",
+ "testConnectionFailModelRequired": "모델 이름을 입력하세요",
+ "testConnectionFailModelNotFound": "이 모델은 사용 가능한 모델 목록에 없습니다",
"secretsVariables": "시크릿 및 변수",
"secrets": "시크릿",
"variables": "변수",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 050049c7b2..4995dc5dfd 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Verbinding testen",
+ "testConnectionTesting": "Bezig met testen...",
+ "testConnectionSuccess": "Verbinding geslaagd",
+ "testConnectionFail": "Verbinding mislukt",
+ "testConnectionFailModelRequired": "Voer de modelnaam in",
+ "testConnectionFailModelNotFound": "Dit model staat niet in de lijst met beschikbare modellen",
"secretsVariables": "Secrets en variabelen",
"secrets": "Secrets",
"variables": "Variabelen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 050b844605..b9c09d11f9 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Testuj połączenie",
+ "testConnectionTesting": "Testowanie...",
+ "testConnectionSuccess": "Połączenie nawiązane",
+ "testConnectionFail": "Połączenie nie powiodło się",
+ "testConnectionFailModelRequired": "Wprowadź nazwę modelu",
+ "testConnectionFailModelNotFound": "Ten model nie znajduje się na liście dostępnych modeli",
"secretsVariables": "Tajemnice i zmienne",
"secrets": "Tajemnice",
"variables": "Zmienne",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 9b67a710c8..fad3b255f7 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Testar conexão",
+ "testConnectionTesting": "Testando...",
+ "testConnectionSuccess": "Conexão bem-sucedida",
+ "testConnectionFail": "Falha na conexão",
+ "testConnectionFailModelRequired": "Informe o nome do modelo",
+ "testConnectionFailModelNotFound": "Este modelo não está na lista de modelos disponíveis",
"secretsVariables": "Segredos e variáveis",
"secrets": "Segredos",
"variables": "Variáveis",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 69f96817b8..b55920d697 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Проверить подключение",
+ "testConnectionTesting": "Проверка...",
+ "testConnectionSuccess": "Подключение успешно",
+ "testConnectionFail": "Ошибка подключения",
+ "testConnectionFailModelRequired": "Введите имя модели",
+ "testConnectionFailModelNotFound": "Этой модели нет в списке доступных моделей",
"secretsVariables": "Секреты и переменные",
"secrets": "Секреты",
"variables": "Переменные",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index c2989ad5ca..927324284e 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Otestovať pripojenie",
+ "testConnectionTesting": "Testuje sa...",
+ "testConnectionSuccess": "Pripojenie úspešné",
+ "testConnectionFail": "Pripojenie zlyhalo",
+ "testConnectionFailModelRequired": "Zadajte názov modelu",
+ "testConnectionFailModelNotFound": "Tento model nie je v zozname dostupných modelov",
"secretsVariables": "Tajomstvá a premenné",
"secrets": "Tajomstvá",
"variables": "Premenné",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 7a2591768f..dab720c17d 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "ทดสอบการเชื่อมต่อ",
+ "testConnectionTesting": "กำลังทดสอบ...",
+ "testConnectionSuccess": "เชื่อมต่อสำเร็จ",
+ "testConnectionFail": "การเชื่อมต่อล้มเหลว",
+ "testConnectionFailModelRequired": "กรุณากรอกชื่อโมเดล",
+ "testConnectionFailModelNotFound": "โมเดลนี้ไม่อยู่ในรายการโมเดลที่ใช้ได้",
"secretsVariables": "ความลับและตัวแปร",
"secrets": "ความลับ",
"variables": "ตัวแปร",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index ac74e7006d..dc1dea5327 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Bağlantıyı test et",
+ "testConnectionTesting": "Test ediliyor...",
+ "testConnectionSuccess": "Bağlantı başarılı",
+ "testConnectionFail": "Bağlantı başarısız",
+ "testConnectionFailModelRequired": "Lütfen model adını girin",
+ "testConnectionFailModelNotFound": "Bu model kullanılabilir modeller listesinde değil",
"secretsVariables": "Gizli Anahtarlar ve Değişkenler",
"secrets": "Gizli Anahtarlar",
"variables": "Değişkenler",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 921a347e96..8605d9a602 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "Перевірити з'єднання",
+ "testConnectionTesting": "Перевірка...",
+ "testConnectionSuccess": "З'єднання успішне",
+ "testConnectionFail": "Помилка з'єднання",
+ "testConnectionFailModelRequired": "Введіть назву моделі",
+ "testConnectionFailModelNotFound": "Цієї моделі немає в списку доступних моделей",
"secretsVariables": "Секрети та змінні",
"secrets": "Секрети",
"variables": "Змінні",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index d577d0d384..d13f776275 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "测试连接",
+ "testConnectionTesting": "测试中...",
+ "testConnectionSuccess": "连接成功",
+ "testConnectionFail": "连接失败",
+ "testConnectionFailModelRequired": "请填写模型名称",
+ "testConnectionFailModelNotFound": "该模型不在可用模型列表中",
"secretsVariables": "密钥和变量",
"secrets": "密钥",
"variables": "变量",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 508e5d7790..d401aa772f 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,10 @@
{
+ "testConnection": "測試連線",
+ "testConnectionTesting": "測試中...",
+ "testConnectionSuccess": "連線成功",
+ "testConnectionFail": "連線失敗",
+ "testConnectionFailModelRequired": "請填寫模型名稱",
+ "testConnectionFailModelNotFound": "此模型不在可用模型清單中",
"secretsVariables": "金鑰和變數",
"secrets": "金鑰",
"variables": "變數",
diff --git a/app/src/config/tabs/aiUi.ts b/app/src/config/tabs/aiUi.ts
index c14f7c56c9..fe14785aaa 100644
--- a/app/src/config/tabs/aiUi.ts
+++ b/app/src/config/tabs/aiUi.ts
@@ -4,6 +4,7 @@ import {confirmDialog} from "../../dialog/confirmDialog";
import {showMessage} from "../../dialog/message";
import {Constants} from "../../constants";
import {isMobile} from "../../util/functions";
+import {fetchPost} from "../../util/fetch";
import {aiConfigApi} from "./aiRuntime";
export const getProvidersBlockKeywords = (): string[] => [
@@ -26,6 +27,9 @@ export const getProvidersBlockKeywords = (): string[] => [
window.siyuan.languages.apiModelTip,
window.siyuan.languages.noProviderConfigured,
window.siyuan.languages.noModelConfigured,
+ window.siyuan.languages.testConnection,
+ window.siyuan.languages.testConnectionFailModelRequired,
+ window.siyuan.languages.testConnectionFailModelNotFound,
];
export const genProvidersBlockHtml = (): string => `<div class="b3-label config-item" id="aiProvidersBlock">
@@ -508,6 +512,7 @@ const openModelDialog = (root: HTMLElement, providerId: string, modelId: string
</div>
<div class="b3-dialog__action">
<button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>
+ <button class="b3-button b3-button--outline" id="aiModelTestBtn"><svg class="b3-button__icon"><use xlink:href="#iconPlugZap"></use></svg><span>${window.siyuan.languages.testConnection}</span></button><div class="fn__space"></div>
<button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>
</div>`,
});
@@ -515,7 +520,48 @@ const openModelDialog = (root: HTMLElement, providerId: string, modelId: string
dialog.element.querySelector<HTMLInputElement>("#aiModelName")?.select();
const btns = dialog.element.querySelectorAll(".b3-dialog__action .b3-button");
btns[0].addEventListener("click", () => dialog.destroy());
- btns[1].addEventListener("click", () => {
+ dialog.element.querySelector<HTMLElement>("#aiModelTestBtn")?.addEventListener("click", () => {
+ const modelName = dialog.element.querySelector<HTMLInputElement>("#aiModelName").value.trim();
+ if (!modelName) {
+ showMessage(window.siyuan.languages.testConnectionFailModelRequired);
+ return;
+ }
+ const testBtn = dialog.element.querySelector<HTMLButtonElement>("#aiModelTestBtn");
+ const iconUse = testBtn.querySelector("use");
+ const svgEl = testBtn.querySelector("svg");
+ const labelSpan = testBtn.querySelector("span");
+ const originalHref = iconUse.getAttribute("xlink:href");
+ testBtn.disabled = true;
+ iconUse.setAttribute("xlink:href", "#iconRefresh");
+ svgEl.style.animation = "agent-mirror-spin 0.8s linear infinite";
+ labelSpan.textContent = window.siyuan.languages.testConnectionTesting;
+ const restoreBtn = () => {
+ testBtn.disabled = false;
+ iconUse.setAttribute("xlink:href", originalHref);
+ svgEl.style.animation = "";
+ labelSpan.textContent = window.siyuan.languages.testConnection;
+ };
+ fetchPost("/api/ai/testModel", {provider: providerId, model: modelName}, (response) => {
+ restoreBtn();
+ const data = response.data || {};
+ if (data.matched) {
+ showMessage(window.siyuan.languages.testConnectionSuccess, undefined, "info");
+ return;
+ }
+ const available = data.available;
+ if (Array.isArray(available) && available.length > 0) {
+ showMessage(`${window.siyuan.languages.testConnectionFailModelNotFound}(${available.slice(0, 10).join(", ")})`, undefined, "error");
+ return;
+ }
+ showMessage(`${window.siyuan.languages.testConnectionFail}${data.msg ? ":" + data.msg : ""}`, undefined, "error");
+ });
+ });
+ btns[2].addEventListener("click", () => {
+ const modelName = dialog.element.querySelector<HTMLInputElement>("#aiModelName").value.trim();
+ if (!modelName) {
+ showMessage(window.siyuan.languages.testConnectionFailModelRequired);
+ return;
+ }
const nextModel: Config.IModel = {
...initialModel,
name: dialog.element.querySelector<HTMLInputElement>("#aiModelName").value,
diff --git a/kernel/api/ai.go b/kernel/api/ai.go
index dcce49b594..63bdae58d9 100644
--- a/kernel/api/ai.go
+++ b/kernel/api/ai.go
@@ -21,6 +21,8 @@ import (
"github.com/88250/gulu"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -58,3 +60,57 @@ func chatGPTWithAction(c *gin.Context) {
action := arg["action"].(string)
ret.Data = model.ChatGPTWithAction(ids, action)
}
+
+// testModel 测试 AI 模型可用性。用该 Provider 已保存的 baseURL/APIKey/超时,
+// 校验指定模型是否可用。优先通过 ListModels 拉取可用模型清单精确匹配,
+// 若该端点不可用则回退到极简 Chat Completion 验证连通性。
+func testModel(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var providerID, modelName string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("provider", &providerID, true, true),
+ util.BindJsonArg("model", &modelName, true, true),
+ ) {
+ return
+ }
+
+ // 按 ID 查找 Provider(不限制启用状态,便于测试尚未启用的配置)
+ var provider *conf.Provider
+ for _, p := range model.Conf.AI.Providers {
+ if p != nil && p.ID == providerID {
+ provider = p
+ break
+ }
+ }
+ if nil == provider {
+ ret.Code = -1
+ ret.Msg = "provider not found"
+ return
+ }
+
+ available, matched, err := util.TestModel(provider.APIKey, provider.BaseURL, modelName, provider.RequestTimeout)
+ // 可用模型清单裁剪到前 50 条,避免响应体过大
+ if 50 < len(available) {
+ available = available[:50]
+ }
+ // 测试结果统一以 code=0 返回,具体成败信息放在 data 中由前端控制展示,
+ // 避免触发统一的错误消息提示导致按钮状态无法恢复
+ result := map[string]any{
+ "available": available,
+ "matched": matched,
+ }
+ if nil != err {
+ result["msg"] = err.Error()
+ logging.LogErrorf("test model [%s] failed: %s", modelName, err)
+ } else if !matched {
+ result["msg"] = "model not in available list"
+ }
+ ret.Data = result
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index ecce0c84f3..e1f6b4cc91 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -535,6 +535,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/ai/chatGPT", model.CheckAuth, model.CheckAdminRole, chatGPT)
ginServer.Handle("POST", "/api/ai/chatGPTWithAction", model.CheckAuth, model.CheckAdminRole, chatGPTWithAction)
+ ginServer.Handle("POST", "/api/ai/testModel", model.CheckAuth, model.CheckAdminRole, testModel)
ginServer.Handle("POST", "/api/ai/agent/chat", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChat)
ginServer.Handle("POST", "/api/ai/agent/confirm", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatConfirm)
ginServer.Handle("POST", "/api/ai/agent/question", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatQuestion)
diff --git a/kernel/util/openai.go b/kernel/util/openai.go
index 749eaac3da..98f96b4746 100644
--- a/kernel/util/openai.go
+++ b/kernel/util/openai.go
@@ -93,6 +93,51 @@ func NewOpenAIClient(apiKey, apiBaseURL string) *openai.Client {
return openai.NewClientWithConfig(config)
}
+// TestModel 测试模型可用性。优先调用 ListModels(GET /v1/models)拉取可用模型清单,
+// 校验 model 是否在其中;若该端点不可用(部分 OpenAI 兼容服务未实现),则回退到极简 Chat Completion。
+// 返回值:available 为可用模型清单(仅 ListModels 成功时填充),matched 表示 model 是否可用,
+// err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。
+func TestModel(apiKey, apiBaseURL, model string, timeout int) (available []string, matched bool, err error) {
+ if 1 > timeout {
+ timeout = 30
+ }
+ client := NewOpenAIClient(apiKey, apiBaseURL)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
+ defer cancel()
+
+ // 优先校验模型是否在可用清单中
+ list, listErr := client.ListModels(ctx)
+ if nil == listErr {
+ model = strings.TrimSpace(model)
+ target := strings.ToLower(model)
+ for _, m := range list.Models {
+ available = append(available, m.ID)
+ if strings.ToLower(m.ID) == target {
+ matched = true
+ }
+ }
+ return
+ }
+
+ // ListModels 不可用时回退到极简 Chat Completion 验证连通性与鉴权
+ logging.LogInfof("list models failed [%s], fallback to chat completion: %s", apiBaseURL, listErr)
+ _, err = client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
+ Model: model,
+ Messages: []openai.ChatCompletionMessage{{
+ Role: "user",
+ Content: "1",
+ }},
+ MaxCompletionTokens: 1,
+ })
+ if nil != err {
+ logging.LogErrorf("test model [%s] failed: %s", model, err)
+ return
+ }
+ matched = true
+ available = nil
+ return
+}
+
func IsNetworkError(err error) bool {
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "actively refused") ||