Skip to content

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

:sparkles: Support OpenAI Decisions provider with isolated profiles https://github.com/siyuan-note/siyuan/issues/19986

Danielae387ed6dee8
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index d4eadd70be..7e56182e19 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "تعذّر حفظ إعدادات خدمة القرار؛ لا تزال مسودتك متاحة",
+ "decisionProvidersTip": "تُحفظ إعدادات المزوّدين بشكل منفصل؛ يسري التبديل على الطلبات الجديدة",
+ "decisionCurrentProvider": "قيد الاستخدام حاليًا",
+ "decisionSaveAndUse": "حفظ واستخدام",
+ "decisionTestDraftTip": "يرسل الاختبار عينة ثابتة إلى الخدمة وقد تترتب عليه رسوم؛ لا تُحفظ الإعدادات",
+ "decisionOpenAIEndpointTip": "عنوان URL الكامل لواجهة Decisions API؛ قد لا تدعم الخدمات المتوافقة مع الدردشة Decisions",
"chatGPTTransfer": "نقل الحساب",
"chatGPTSignedOut": "لم يتم تسجيل الدخول؛ تُحفظ معلومات الحساب لتسجيل الدخول مجددًا",
"chatGPTAddAccount": "إضافة حساب",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "اسحب لضبط المسار؛ انقر نقرًا مزدوجًا على مقبض السحب لاستعادة الحساب التلقائي",
"listMindmapRouteFallback": "المسار المعدّل غير متاح في هذا التخطيط؛ يتم عرض المسار التلقائي",
"decisionModel": "نموذج اتخاذ القرار",
- "decisionModelTip": "تفضيل TypeSafe System One (Jev) للتصنيف والتصفية والتقييم؛ يُرسل المحتوى ذي الصلة إلى خدمة اتخاذ القرار وقد تُفرض رسوم",
- "decisionEndpointTip": "عنوان API الكامل لخدمة TypeSafe System One، الافتراضي: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "استخدم خدمة القرار المحددة للتصنيف والتصفية والتقييم؛ يُرسل المحتوى المعني إلى الخدمة وقد تُفرض رسوم",
+ "decisionEndpointTip": "عنوان نقطة نهاية API الكامل لمزوّد القرارات هذا",
"listView": "قائمة",
"databaseListView": "عرض قائمة قاعدة البيانات",
"copyRuntimeInfo": "نسخ معلومات التشغيل",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 9b090c3634..eebbf8b5f7 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Die Einstellungen des Entscheidungsdienstes konnten nicht gespeichert werden; Ihr Entwurf bleibt erhalten",
+ "decisionProvidersTip": "Anbietereinstellungen werden getrennt gespeichert; ein Wechsel gilt für neue Anfragen",
+ "decisionCurrentProvider": "Aktuell verwendet",
+ "decisionSaveAndUse": "Speichern und verwenden",
+ "decisionTestDraftTip": "Der Test sendet ein festes Beispiel an den Dienst und kann Kosten verursachen; Einstellungen werden nicht gespeichert",
+ "decisionOpenAIEndpointTip": "Vollständige Decisions-API-URL; chatkompatible Dienste unterstützen Decisions möglicherweise nicht",
"chatGPTTransfer": "Konto übertragen",
"chatGPTSignedOut": "Nicht angemeldet; die Kontoinformationen bleiben für eine erneute Anmeldung gespeichert",
"chatGPTAddAccount": "Konto hinzufügen",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Ziehen, um den Verlauf anzupassen; Doppelklick auf den Ziehpunkt stellt die automatische Berechnung wieder her",
"listMindmapRouteFallback": "Der angepasste Verlauf ist in diesem Layout nicht verfügbar; der automatische Verlauf wird angezeigt",
"decisionModel": "Entscheidungsmodell",
- "decisionModelTip": "TypeSafe System One (Jev) bevorzugt zum Klassifizieren, Filtern und Bewerten verwenden; relevante Inhalte werden an den Entscheidungsdienst gesendet, dabei können Kosten entstehen",
- "decisionEndpointTip": "Vollständiger API-Endpunkt von TypeSafe System One, Standard: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Den gewählten Entscheidungsdienst zum Klassifizieren, Filtern und Bewerten verwenden; relevante Inhalte werden an den Dienst gesendet und es können Kosten entstehen",
+ "decisionEndpointTip": "Vollständiger API-Endpunkt dieses Entscheidungsanbieters",
"listView": "Liste",
"databaseListView": "Datenbank-Listenansicht",
"copyRuntimeInfo": "Laufzeitinformationen kopieren",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 2e5626b128..c4086a5e07 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Unable to save the decision service settings; your draft is still available",
+ "decisionProvidersTip": "Provider settings are saved separately; switching applies to new requests",
+ "decisionCurrentProvider": "Currently in use",
+ "decisionSaveAndUse": "Save and use",
+ "decisionTestDraftTip": "Testing sends a fixed sample to the service and may incur charges; settings are not saved",
+ "decisionOpenAIEndpointTip": "Full Decisions API URL; chat-compatible services may not support Decisions",
"chatGPTTransfer": "Transfer account",
"chatGPTSignedOut": "Not signed in; account info is kept for signing in again",
"chatGPTAddAccount": "Add account",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Drag to adjust the path; double-click the handle to reset",
"listMindmapRouteFallback": "The adjusted path is unavailable in this layout; showing the automatic path",
"decisionModel": "Decision model",
- "decisionModelTip": "Prefer TypeSafe System One (Jev) for classification, filtering and scoring; relevant content is sent to the decision service and charges may apply",
- "decisionEndpointTip": "Full TypeSafe System One API endpoint, default: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Use the selected decision service for classification, filtering and scoring; relevant content is sent to the service and charges may apply",
+ "decisionEndpointTip": "Full API endpoint for this decision provider",
"listView": "List",
"databaseListView": "Database list view",
"copyRuntimeInfo": "Copy runtime information",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index aacc88c876..371963ac20 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "No se pudo guardar la configuración del servicio de decisión; el borrador se conserva",
+ "decisionProvidersTip": "La configuración de cada proveedor se guarda por separado; el cambio se aplica a las nuevas solicitudes",
+ "decisionCurrentProvider": "En uso",
+ "decisionSaveAndUse": "Guardar y usar",
+ "decisionTestDraftTip": "La prueba envía un ejemplo fijo al servicio y puede generar cargos; no guarda la configuración",
+ "decisionOpenAIEndpointTip": "URL completa de Decisions API; los servicios compatibles con chat pueden no admitir Decisions",
"chatGPTTransfer": "Transferir cuenta",
"chatGPTSignedOut": "No has iniciado sesión; se conserva la información de la cuenta para volver a iniciar sesión",
"chatGPTAddAccount": "Añadir cuenta",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Arrastra para ajustar el trazado; haz doble clic en el controlador para restablecerlo",
"listMindmapRouteFallback": "El trazado ajustado no está disponible en esta disposición; se muestra el trazado automático",
"decisionModel": "Modelo de decisión",
- "decisionModelTip": "Priorizar TypeSafe System One (Jev) para clasificar, filtrar y puntuar; el contenido pertinente se envía al servicio de decisión y puede generar cargos",
- "decisionEndpointTip": "Dirección completa de la API de TypeSafe System One, predeterminada: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Usar el servicio de decisión seleccionado para clasificar, filtrar y puntuar; se envía el contenido pertinente al servicio y pueden aplicarse cargos",
+ "decisionEndpointTip": "Dirección completa de la API de este proveedor de decisiones",
"listView": "Lista",
"databaseListView": "Vista de lista de base de datos",
"copyRuntimeInfo": "Copiar información de ejecución",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index c3e47b7456..975ccf4f7d 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Impossible d’enregistrer les paramètres du service de décision ; votre brouillon est conservé",
+ "decisionProvidersTip": "Les paramètres des fournisseurs sont enregistrés séparément ; le changement s’applique aux nouvelles requêtes",
+ "decisionCurrentProvider": "Actuellement utilisé",
+ "decisionSaveAndUse": "Enregistrer et utiliser",
+ "decisionTestDraftTip": "Le test envoie un exemple fixe au service et peut entraîner des frais ; les paramètres ne sont pas enregistrés",
+ "decisionOpenAIEndpointTip": "URL complète de l’API Decisions ; les services compatibles avec le chat ne prennent pas forcément en charge Decisions",
"chatGPTTransfer": "Transférer le compte",
"chatGPTSignedOut": "Non connecté ; les informations du compte sont conservées pour vous reconnecter",
"chatGPTAddAccount": "Ajouter un compte",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Faites glisser pour ajuster le tracé ; double-cliquez sur la poignée pour rétablir le calcul automatique",
"listMindmapRouteFallback": "Le tracé ajusté est indisponible dans cette disposition ; le tracé automatique est affiché",
"decisionModel": "Modèle de décision",
- "decisionModelTip": "Privilégier TypeSafe System One (Jev) pour classer, filtrer et noter ; le contenu pertinent est envoyé au service de décision et des frais peuvent s’appliquer",
- "decisionEndpointTip": "Adresse complète de l’API TypeSafe System One, par défaut : https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Utiliser le service de décision sélectionné pour classer, filtrer et noter ; le contenu pertinent est envoyé au service et des frais peuvent s’appliquer",
+ "decisionEndpointTip": "Adresse complète de l’API de ce fournisseur de décisions",
"listView": "Liste",
"databaseListView": "Vue liste de base de données",
"copyRuntimeInfo": "Copier les informations d’exécution",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 7d9b0532c3..575d3092ce 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "לא ניתן לשמור את הגדרות שירות ההחלטות; הטיוטה שלך נשמרה",
+ "decisionProvidersTip": "הגדרות הספקים נשמרות בנפרד; ההחלפה חלה על בקשות חדשות",
+ "decisionCurrentProvider": "בשימוש כעת",
+ "decisionSaveAndUse": "שמירה ושימוש",
+ "decisionTestDraftTip": "הבדיקה שולחת דוגמה קבועה לשירות ועשויה להיות כרוכה בתשלום; ההגדרות אינן נשמרות",
+ "decisionOpenAIEndpointTip": "כתובת URL מלאה של Decisions API; שירותים תואמי צ׳אט עשויים שלא לתמוך ב-Decisions",
"chatGPTTransfer": "העברת חשבון",
"chatGPTSignedOut": "לא מחובר; פרטי החשבון נשמרים לצורך התחברות מחדש",
"chatGPTAddAccount": "הוסף חשבון",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "גררו כדי להתאים את הנתיב; לחצו פעמיים על ידית הגרירה כדי לשחזר חישוב אוטומטי",
"listMindmapRouteFallback": "הנתיב המותאם אינו זמין בפריסה זו; מוצג הנתיב האוטומטי",
"decisionModel": "מודל החלטות",
- "decisionModelTip": "העדפת TypeSafe System One (Jev) לסיווג, סינון וניקוד; תוכן רלוונטי נשלח לשירות ההחלטות וייתכנו חיובים",
- "decisionEndpointTip": "כתובת API מלאה של TypeSafe System One, ברירת מחדל: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "שימוש בשירות ההחלטות שנבחר לסיווג, סינון וניקוד; התוכן הרלוונטי נשלח לשירות וייתכן חיוב",
+ "decisionEndpointTip": "כתובת נקודת הקצה המלאה של ה-API עבור ספק החלטות זה",
"listView": "רשימה",
"databaseListView": "תצוגת רשימה של מסד נתונים",
"copyRuntimeInfo": "העתקת מידע על סביבת הריצה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 3b854373f5..5d62be26e7 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "निर्णय सेवा की सेटिंग सहेजी नहीं जा सकीं; आपका मसौदा सुरक्षित है",
+ "decisionProvidersTip": "प्रदाताओं की सेटिंग अलग-अलग सहेजी जाती हैं; बदलाव नए अनुरोधों पर लागू होता है",
+ "decisionCurrentProvider": "अभी उपयोग में",
+ "decisionSaveAndUse": "सहेजें और उपयोग करें",
+ "decisionTestDraftTip": "परीक्षण सेवा को एक तय नमूना भेजता है और शुल्क लग सकता है; सेटिंग सहेजी नहीं जाती",
+ "decisionOpenAIEndpointTip": "Decisions API का पूरा URL; चैट-संगत सेवाएँ Decisions का समर्थन करें, यह ज़रूरी नहीं",
"chatGPTTransfer": "खाता स्थानांतरित करें",
"chatGPTSignedOut": "साइन इन नहीं है; दोबारा साइन इन करने के लिए खाते की जानकारी रखी गई है",
"chatGPTAddAccount": "खाता जोड़ें",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "पथ समायोजित करने के लिए खींचें; स्वचालित गणना बहाल करने के लिए ड्रैग हैंडल पर दो बार क्लिक करें",
"listMindmapRouteFallback": "इस लेआउट में समायोजित पथ उपलब्ध नहीं है; स्वचालित पथ दिखाया जा रहा है",
"decisionModel": "निर्णय मॉडल",
- "decisionModelTip": "वर्गीकरण, छँटाई और अंक देने के लिए TypeSafe System One (Jev) को प्राथमिकता दें; संबंधित सामग्री निर्णय सेवा को भेजी जाती है और शुल्क लग सकता है",
- "decisionEndpointTip": "TypeSafe System One API का पूरा पता, डिफ़ॉल्ट: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "वर्गीकरण, फ़िल्टरिंग और स्कोरिंग के लिए चुनी गई निर्णय सेवा का उपयोग करें; संबंधित सामग्री सेवा को भेजी जाती है और शुल्क लग सकता है",
+ "decisionEndpointTip": "इस निर्णय प्रदाता का पूरा API एंडपॉइंट",
"listView": "सूची",
"databaseListView": "डेटाबेस सूची दृश्य",
"copyRuntimeInfo": "रनटाइम की जानकारी कॉपी करें",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 40bca9f3e1..d1ee3051ff 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Tidak dapat menyimpan pengaturan layanan keputusan; draf Anda tetap tersedia",
+ "decisionProvidersTip": "Pengaturan penyedia disimpan terpisah; pergantian berlaku untuk permintaan baru",
+ "decisionCurrentProvider": "Sedang digunakan",
+ "decisionSaveAndUse": "Simpan dan gunakan",
+ "decisionTestDraftTip": "Pengujian mengirim contoh tetap ke layanan dan dapat dikenai biaya; pengaturan tidak disimpan",
+ "decisionOpenAIEndpointTip": "URL Decisions API lengkap; layanan yang kompatibel dengan obrolan belum tentu mendukung Decisions",
"chatGPTTransfer": "Transfer akun",
"chatGPTSignedOut": "Belum masuk; informasi akun disimpan agar dapat masuk kembali",
"chatGPTAddAccount": "Tambahkan akun",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Seret untuk menyesuaikan jalur; klik dua kali pada pegangan seret untuk mengembalikan perhitungan otomatis",
"listMindmapRouteFallback": "Jalur yang disesuaikan tidak tersedia dalam tata letak ini; jalur otomatis ditampilkan",
"decisionModel": "Model keputusan",
- "decisionModelTip": "Utamakan TypeSafe System One (Jev) untuk klasifikasi, penyaringan, dan penilaian; konten terkait dikirim ke layanan keputusan dan dapat dikenai biaya",
- "decisionEndpointTip": "Alamat lengkap API TypeSafe System One, bawaan: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Gunakan layanan keputusan yang dipilih untuk klasifikasi, penyaringan, dan penilaian; konten terkait dikirim ke layanan dan biaya mungkin berlaku",
+ "decisionEndpointTip": "Titik akhir API lengkap untuk penyedia keputusan ini",
"listView": "Daftar",
"databaseListView": "Tampilan daftar database",
"copyRuntimeInfo": "Salin informasi runtime",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 3fc3f4c32d..4ef957d459 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Impossibile salvare le impostazioni del servizio decisionale; la bozza è stata conservata",
+ "decisionProvidersTip": "Le impostazioni dei fornitori vengono salvate separatamente; il cambio si applica alle nuove richieste",
+ "decisionCurrentProvider": "Attualmente in uso",
+ "decisionSaveAndUse": "Salva e usa",
+ "decisionTestDraftTip": "Il test invia un esempio fisso al servizio e può comportare costi; le impostazioni non vengono salvate",
+ "decisionOpenAIEndpointTip": "URL completo di Decisions API; i servizi compatibili con la chat potrebbero non supportare Decisions",
"chatGPTTransfer": "Trasferisci account",
"chatGPTSignedOut": "Accesso non effettuato; le informazioni dell'account sono conservate per accedere nuovamente",
"chatGPTAddAccount": "Aggiungi account",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Trascina per regolare il percorso; fai doppio clic sulla maniglia per ripristinare il calcolo automatico",
"listMindmapRouteFallback": "Il percorso modificato non è disponibile in questa disposizione; viene mostrato il percorso automatico",
"decisionModel": "Modello decisionale",
- "decisionModelTip": "Preferire TypeSafe System One (Jev) per classificare, filtrare e valutare; i contenuti pertinenti vengono inviati al servizio decisionale e possono comportare costi",
- "decisionEndpointTip": "Indirizzo completo dell’API TypeSafe System One, predefinito: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Usa il servizio decisionale selezionato per classificare, filtrare e valutare; i contenuti pertinenti vengono inviati al servizio e potrebbero esserci costi",
+ "decisionEndpointTip": "Endpoint API completo di questo fornitore di decisioni",
"listView": "Elenco",
"databaseListView": "Vista elenco del database",
"copyRuntimeInfo": "Copia informazioni di esecuzione",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 5745a44955..3fba6cc37f 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "判定サービスの設定を保存できませんでした。編集中の内容は保持されています",
+ "decisionProvidersTip": "プロバイダーごとに設定を保存します。切り替えは新しいリクエストに適用されます",
+ "decisionCurrentProvider": "使用中",
+ "decisionSaveAndUse": "保存して使用",
+ "decisionTestDraftTip": "テストは固定サンプルをサービスに送信し、料金が発生する場合があります。設定は保存されません",
+ "decisionOpenAIEndpointTip": "Decisions API の完全な URL。チャット互換サービスが Decisions に対応しているとは限りません",
"chatGPTTransfer": "アカウントの移行",
"chatGPTSignedOut": "未ログインです。再ログイン用にアカウント情報を保持しています",
"chatGPTAddAccount": "アカウントを追加",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "ドラッグして経路を調整、ハンドルをダブルクリックして自動計算に戻す",
"listMindmapRouteFallback": "現在のレイアウトでは手動の経路を使用できないため、自動の経路を表示しています",
"decisionModel": "判定モデル",
- "decisionModelTip": "分類、絞り込み、評価に TypeSafe System One(Jev)を優先して使用します。関連する内容は判定サービスに送信され、料金が発生する場合があります",
- "decisionEndpointTip": "TypeSafe System One API の完全なエンドポイント。既定値:https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "選択した判定サービスで分類、絞り込み、評価を行います。関連する内容がサービスに送信され、料金が発生する場合があります",
+ "decisionEndpointTip": "この判定プロバイダーの完全な API エンドポイント",
"listView": "リスト",
"databaseListView": "データベース リストビュー",
"copyRuntimeInfo": "実行環境情報をコピー",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 06450f540f..8bde1b0ea2 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "의사결정 서비스 설정을 저장할 수 없습니다. 작성 중인 내용은 유지됩니다",
+ "decisionProvidersTip": "공급자 설정은 개별 저장되며 전환은 새 요청에 적용됩니다",
+ "decisionCurrentProvider": "현재 사용 중",
+ "decisionSaveAndUse": "저장 후 사용",
+ "decisionTestDraftTip": "테스트는 고정 샘플을 서비스에 전송하며 요금이 발생할 수 있습니다. 설정은 저장되지 않습니다",
+ "decisionOpenAIEndpointTip": "전체 Decisions API URL을 입력하세요. 채팅 호환 서비스가 Decisions를 지원하지 않을 수 있습니다",
"chatGPTTransfer": "계정 이전",
"chatGPTSignedOut": "로그인되지 않음. 다시 로그인할 수 있도록 계정 정보를 유지합니다",
"chatGPTAddAccount": "계정 추가",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "드래그하여 경로 조정, 드래그 핸들을 두 번 클릭하여 자동 계산으로 복원",
"listMindmapRouteFallback": "현재 레이아웃에서는 수동 경로를 사용할 수 없어 자동 경로를 표시합니다",
"decisionModel": "판단 모델",
- "decisionModelTip": "분류, 필터링 및 평가에 TypeSafe System One(Jev)을 우선 사용합니다. 관련 내용은 판단 서비스로 전송되며 요금이 발생할 수 있습니다",
- "decisionEndpointTip": "TypeSafe System One API의 전체 주소, 기본값: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "선택한 의사결정 서비스를 분류, 필터링 및 평가에 사용합니다. 관련 내용이 서비스로 전송되며 요금이 발생할 수 있습니다",
+ "decisionEndpointTip": "이 의사결정 공급자의 전체 API 엔드포인트",
"listView": "목록",
"databaseListView": "데이터베이스 목록 보기",
"copyRuntimeInfo": "실행 환경 정보 복사",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 67cbfc6401..0194e142cc 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "De instellingen van de beslissingsdienst konden niet worden opgeslagen; uw concept is bewaard",
+ "decisionProvidersTip": "Providerinstellingen worden afzonderlijk opgeslagen; wisselen geldt voor nieuwe verzoeken",
+ "decisionCurrentProvider": "Momenteel in gebruik",
+ "decisionSaveAndUse": "Opslaan en gebruiken",
+ "decisionTestDraftTip": "De test stuurt een vast voorbeeld naar de dienst en kan kosten veroorzaken; instellingen worden niet opgeslagen",
+ "decisionOpenAIEndpointTip": "Volledige Decisions API-URL; chatcompatibele diensten ondersteunen Decisions mogelijk niet",
"chatGPTTransfer": "Account overdragen",
"chatGPTSignedOut": "Niet aangemeld; de accountgegevens worden bewaard om opnieuw aan te melden",
"chatGPTAddAccount": "Account toevoegen",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Sleep om het pad aan te passen; dubbelklik op de sleepgreep om de automatische berekening te herstellen",
"listMindmapRouteFallback": "Het aangepaste pad is niet beschikbaar in deze indeling; het automatische pad wordt getoond",
"decisionModel": "Beslismodel",
- "decisionModelTip": "Geef TypeSafe System One (Jev) voorrang bij classificeren, filteren en beoordelen; relevante inhoud wordt naar de beslisservice verzonden en er kunnen kosten ontstaan",
- "decisionEndpointTip": "Volledig API-eindpunt van TypeSafe System One, standaard: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Gebruik de geselecteerde beslissingsdienst voor classificatie, filtering en beoordeling; relevante inhoud wordt naar de dienst verstuurd en er kunnen kosten gelden",
+ "decisionEndpointTip": "Volledig API-eindpunt voor deze beslissingsprovider",
"listView": "Lijst",
"databaseListView": "Lijstweergave van database",
"copyRuntimeInfo": "Runtime-informatie kopiëren",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index d6aefe22c7..cade6ef926 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Nie można zapisać ustawień usługi decyzyjnej; wersja robocza została zachowana",
+ "decisionProvidersTip": "Ustawienia dostawców są zapisywane oddzielnie; zmiana dotyczy nowych żądań",
+ "decisionCurrentProvider": "Obecnie używany",
+ "decisionSaveAndUse": "Zapisz i użyj",
+ "decisionTestDraftTip": "Test wysyła stały przykład do usługi i może generować opłaty; ustawienia nie są zapisywane",
+ "decisionOpenAIEndpointTip": "Pełny adres URL interfejsu Decisions API; usługi zgodne z czatem mogą nie obsługiwać Decisions",
"chatGPTTransfer": "Przenieś konto",
"chatGPTSignedOut": "Nie zalogowano; informacje o koncie są zachowane, aby umożliwić ponowne logowanie",
"chatGPTAddAccount": "Dodaj konto",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Przeciągnij, aby dostosować przebieg; kliknij dwukrotnie uchwyt, aby przywrócić automatyczne wyznaczanie",
"listMindmapRouteFallback": "Dostosowany przebieg jest niedostępny w tym układzie; wyświetlany jest przebieg automatyczny",
"decisionModel": "Model decyzyjny",
- "decisionModelTip": "Preferuj TypeSafe System One (Jev) do klasyfikowania, filtrowania i oceniania; odpowiednia treść jest wysyłana do usługi decyzyjnej, co może wiązać się z opłatami",
- "decisionEndpointTip": "Pełny adres API TypeSafe System One, domyślnie: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Używaj wybranej usługi decyzyjnej do klasyfikowania, filtrowania i oceniania; odpowiednia treść jest wysyłana do usługi i mogą być naliczane opłaty",
+ "decisionEndpointTip": "Pełny adres punktu końcowego API tego dostawcy decyzji",
"listView": "Lista",
"databaseListView": "Widok listy bazy danych",
"copyRuntimeInfo": "Kopiuj informacje o środowisku uruchomieniowym",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 7b1753f289..acbd24cfeb 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Não foi possível salvar as configurações do serviço de decisão; seu rascunho foi mantido",
+ "decisionProvidersTip": "As configurações dos provedores são salvas separadamente; a troca se aplica às novas solicitações",
+ "decisionCurrentProvider": "Em uso",
+ "decisionSaveAndUse": "Salvar e usar",
+ "decisionTestDraftTip": "O teste envia um exemplo fixo ao serviço e pode gerar cobranças; as configurações não são salvas",
+ "decisionOpenAIEndpointTip": "URL completa da API Decisions; serviços compatíveis com chat podem não oferecer suporte ao Decisions",
"chatGPTTransfer": "Transferir conta",
"chatGPTSignedOut": "Sessão não iniciada; as informações da conta são mantidas para entrar novamente",
"chatGPTAddAccount": "Adicionar conta",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Arraste para ajustar o trajeto; clique duas vezes na alça para restaurar o cálculo automático",
"listMindmapRouteFallback": "O trajeto ajustado não está disponível neste leiaute; exibindo o trajeto automático",
"decisionModel": "Modelo de decisão",
- "decisionModelTip": "Priorizar o TypeSafe System One (Jev) para classificar, filtrar e pontuar; o conteúdo relevante é enviado ao serviço de decisão e pode gerar cobranças",
- "decisionEndpointTip": "Endereço completo da API do TypeSafe System One, padrão: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Use o serviço de decisão selecionado para classificar, filtrar e pontuar; o conteúdo relevante é enviado ao serviço e pode haver cobranças",
+ "decisionEndpointTip": "Endpoint completo da API deste provedor de decisões",
"listView": "Lista",
"databaseListView": "Visualização de lista do banco de dados",
"copyRuntimeInfo": "Copiar informações de execução",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 7f54d98ce3..725cbdb853 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Не удалось сохранить настройки службы принятия решений; черновик сохранён",
+ "decisionProvidersTip": "Настройки провайдеров сохраняются отдельно; переключение применяется к новым запросам",
+ "decisionCurrentProvider": "Используется сейчас",
+ "decisionSaveAndUse": "Сохранить и использовать",
+ "decisionTestDraftTip": "Тест отправляет службе фиксированный пример и может быть платным; настройки не сохраняются",
+ "decisionOpenAIEndpointTip": "Полный URL Decisions API; совместимые с чатом службы могут не поддерживать Decisions",
"chatGPTTransfer": "Перенести аккаунт",
"chatGPTSignedOut": "Вход не выполнен; данные аккаунта сохранены для повторного входа",
"chatGPTAddAccount": "Добавить аккаунт",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Перетащите, чтобы изменить путь; дважды щёлкните маркер перетаскивания, чтобы восстановить автоматический расчёт",
"listMindmapRouteFallback": "Изменённый путь недоступен в этой компоновке; показан автоматический путь",
"decisionModel": "Модель принятия решений",
- "decisionModelTip": "Предпочитать TypeSafe System One (Jev) для классификации, фильтрации и оценки; соответствующее содержимое отправляется сервису принятия решений, возможна плата",
- "decisionEndpointTip": "Полный адрес API TypeSafe System One, по умолчанию: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Использовать выбранную службу принятия решений для классификации, фильтрации и оценки; соответствующее содержимое отправляется службе, возможны расходы",
+ "decisionEndpointTip": "Полный адрес API этого провайдера решений",
"listView": "Список",
"databaseListView": "Представление базы данных в виде списка",
"copyRuntimeInfo": "Копировать информацию о среде выполнения",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 265db93a38..f50a3ba5cf 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Nastavenia rozhodovacej služby sa nepodarilo uložiť; koncept zostal zachovaný",
+ "decisionProvidersTip": "Nastavenia poskytovateľov sa ukladajú oddelene; prepnutie sa vzťahuje na nové požiadavky",
+ "decisionCurrentProvider": "Aktuálne sa používa",
+ "decisionSaveAndUse": "Uložiť a použiť",
+ "decisionTestDraftTip": "Test odošle pevnú vzorku službe a môže byť spoplatnený; nastavenia sa neuložia",
+ "decisionOpenAIEndpointTip": "Úplná URL rozhrania Decisions API; služby kompatibilné s chatom nemusia podporovať Decisions",
"chatGPTTransfer": "Preniesť účet",
"chatGPTSignedOut": "Nie ste prihlásení; údaje účtu sa uchovávajú na opätovné prihlásenie",
"chatGPTAddAccount": "Pridať účet",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Potiahnutím upravíte trasu; dvojitým kliknutím na úchyt obnovíte automatický výpočet",
"listMindmapRouteFallback": "Upravená trasa nie je v tomto rozložení dostupná; zobrazuje sa automatická trasa",
"decisionModel": "Rozhodovací model",
- "decisionModelTip": "Uprednostniť TypeSafe System One (Jev) pri klasifikácii, filtrovaní a hodnotení; príslušný obsah sa odosiela rozhodovacej službe a môžu vzniknúť poplatky",
- "decisionEndpointTip": "Úplná adresa API TypeSafe System One, predvolená: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Použiť vybranú rozhodovaciu službu na klasifikáciu, filtrovanie a hodnotenie; príslušný obsah sa odošle službe a môžu sa účtovať poplatky",
+ "decisionEndpointTip": "Úplná adresa koncového bodu API tohto poskytovateľa rozhodnutí",
"listView": "Zoznam",
"databaseListView": "Zoznamové zobrazenie databázy",
"copyRuntimeInfo": "Kopírovať informácie o prostredí behu",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 431ccd51b3..d0927d2e78 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Није могуће сачувати подешавања услуге одлучивања; нацрт је задржан",
+ "decisionProvidersTip": "Подешавања добављача се чувају одвојено; промена важи за нове захтеве",
+ "decisionCurrentProvider": "Тренутно се користи",
+ "decisionSaveAndUse": "Сачувај и користи",
+ "decisionTestDraftTip": "Тест шаље фиксни пример услузи и може изазвати трошкове; подешавања се не чувају",
+ "decisionOpenAIEndpointTip": "Потпуни URL за Decisions API; услуге компатибилне са ћаскањем можда не подржавају Decisions",
"chatGPTTransfer": "Пренос налога",
"chatGPTSignedOut": "Нисте пријављени; подаци налога су сачувани за поновно пријављивање",
"chatGPTAddAccount": "Додај налог",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Превуците да подесите путању; двапут кликните на ручицу за превлачење да вратите аутоматско израчунавање",
"listMindmapRouteFallback": "Подешена путања није доступна у овом распореду; приказује се аутоматска путања",
"decisionModel": "Модел за одлучивање",
- "decisionModelTip": "Дајте предност моделу TypeSafe System One (Jev) за класификацију, филтрирање и оцењивање; одговарајући садржај се шаље сервису за одлучивање и може бити наплаћен",
- "decisionEndpointTip": "Пуна адреса API-ја TypeSafe System One, подразумевано: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Користите изабрану услугу одлучивања за класификацију, филтрирање и оцењивање; релевантан садржај се шаље услузи и могући су трошкови",
+ "decisionEndpointTip": "Потпуна API адреса овог добављача одлука",
"listView": "Lista",
"databaseListView": "Prikaz baze - lista",
"copyRuntimeInfo": "Копирај информације о извршавању",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 1a06c2fa92..1135a84a3e 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "ไม่สามารถบันทึกการตั้งค่าบริการตัดสินใจได้ ฉบับร่างของคุณยังคงอยู่",
+ "decisionProvidersTip": "บันทึกการตั้งค่าของผู้ให้บริการแยกกัน การสลับมีผลกับคำขอใหม่",
+ "decisionCurrentProvider": "กำลังใช้งาน",
+ "decisionSaveAndUse": "บันทึกและใช้งาน",
+ "decisionTestDraftTip": "การทดสอบจะส่งตัวอย่างคงที่ไปยังบริการและอาจมีค่าใช้จ่าย โดยไม่บันทึกการตั้งค่า",
+ "decisionOpenAIEndpointTip": "URL ของ Decisions API แบบเต็ม บริการที่รองรับแชตอาจไม่รองรับ Decisions",
"chatGPTTransfer": "โอนย้ายบัญชี",
"chatGPTSignedOut": "ยังไม่ได้เข้าสู่ระบบ โดยเก็บข้อมูลบัญชีไว้เพื่อเข้าสู่ระบบอีกครั้ง",
"chatGPTAddAccount": "เพิ่มบัญชี",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "ลากเพื่อปรับเส้นทาง ดับเบิลคลิกที่จุดควบคุมเพื่อกลับไปคำนวณอัตโนมัติ",
"listMindmapRouteFallback": "ไม่สามารถใช้เส้นทางที่ปรับไว้ในเค้าโครงนี้ได้ จึงแสดงเส้นทางอัตโนมัติชั่วคราว",
"decisionModel": "โมเดลการตัดสินใจ",
- "decisionModelTip": "ให้ความสำคัญกับ TypeSafe System One (Jev) สำหรับการจัดประเภท การกรอง และการให้คะแนน โดยส่งเนื้อหาที่เกี่ยวข้องไปยังบริการตัดสินใจและอาจมีค่าใช้จ่าย",
- "decisionEndpointTip": "ที่อยู่ API แบบเต็มของ TypeSafe System One ค่าเริ่มต้น: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "ใช้บริการตัดสินใจที่เลือกเพื่อจำแนก กรอง และให้คะแนน เนื้อหาที่เกี่ยวข้องจะถูกส่งไปยังบริการและอาจมีค่าใช้จ่าย",
+ "decisionEndpointTip": "ปลายทาง API แบบเต็มของผู้ให้บริการตัดสินใจนี้",
"listView": "รายการ",
"databaseListView": "มุมมองรายการฐานข้อมูล",
"copyRuntimeInfo": "คัดลอกข้อมูลสภาพแวดล้อมการทำงาน",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 54b1f69eb0..0766019a7c 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Karar hizmeti ayarları kaydedilemedi; taslağınız korunuyor",
+ "decisionProvidersTip": "Sağlayıcı ayarları ayrı kaydedilir; değişiklik yeni isteklere uygulanır",
+ "decisionCurrentProvider": "Şu anda kullanılıyor",
+ "decisionSaveAndUse": "Kaydet ve kullan",
+ "decisionTestDraftTip": "Test, hizmete sabit bir örnek gönderir ve ücret doğurabilir; ayarlar kaydedilmez",
+ "decisionOpenAIEndpointTip": "Tam Decisions API URL’si; sohbet uyumlu hizmetler Decisions desteği sunmayabilir",
"chatGPTTransfer": "Hesabı aktar",
"chatGPTSignedOut": "Oturum açılmadı; yeniden oturum açmak için hesap bilgileri korunur",
"chatGPTAddAccount": "Hesap ekle",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Yolu ayarlamak için sürükleyin; otomatik hesaplamayı geri yüklemek için sürükleme tutamacına çift tıklayın",
"listMindmapRouteFallback": "Ayarlanan yol bu düzende kullanılamıyor; otomatik yol gösteriliyor",
"decisionModel": "Karar modeli",
- "decisionModelTip": "Sınıflandırma, filtreleme ve puanlama için TypeSafe System One (Jev) tercih edilir; ilgili içerik karar hizmetine gönderilir ve ücret uygulanabilir",
- "decisionEndpointTip": "TypeSafe System One API tam adresi, varsayılan: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Sınıflandırma, filtreleme ve puanlama için seçilen karar hizmetini kullanın; ilgili içerik hizmete gönderilir ve ücret uygulanabilir",
+ "decisionEndpointTip": "Bu karar sağlayıcısının tam API uç noktası",
"listView": "Liste",
"databaseListView": "Veritabanı liste görünümü",
"copyRuntimeInfo": "Çalışma zamanı bilgilerini kopyala",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index e13b3b1046..2132514094 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "Не вдалося зберегти налаштування служби ухвалення рішень; чернетку збережено",
+ "decisionProvidersTip": "Налаштування постачальників зберігаються окремо; перемикання застосовується до нових запитів",
+ "decisionCurrentProvider": "Зараз використовується",
+ "decisionSaveAndUse": "Зберегти й використовувати",
+ "decisionTestDraftTip": "Тест надсилає службі фіксований приклад і може бути платним; налаштування не зберігаються",
+ "decisionOpenAIEndpointTip": "Повна URL-адреса Decisions API; сумісні з чатом служби можуть не підтримувати Decisions",
"chatGPTTransfer": "Перенести обліковий запис",
"chatGPTSignedOut": "Вхід не виконано; дані облікового запису збережено для повторного входу",
"chatGPTAddAccount": "Додати обліковий запис",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "Перетягніть, щоб змінити шлях; двічі клацніть маркер перетягування, щоб відновити автоматичний розрахунок",
"listMindmapRouteFallback": "Змінений шлях недоступний у цьому компонуванні; показано автоматичний шлях",
"decisionModel": "Модель ухвалення рішень",
- "decisionModelTip": "Надавати перевагу TypeSafe System One (Jev) для класифікації, фільтрування й оцінювання; відповідний вміст надсилається сервісу ухвалення рішень, можлива оплата",
- "decisionEndpointTip": "Повна адреса API TypeSafe System One, типово: https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "Використовувати вибрану службу ухвалення рішень для класифікації, фільтрування й оцінювання; відповідний вміст надсилається службі, можливі витрати",
+ "decisionEndpointTip": "Повна адреса API цього постачальника рішень",
"listView": "Список",
"databaseListView": "Подання бази даних у вигляді списку",
"copyRuntimeInfo": "Копіювати інформацію про середовище виконання",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 7ef16a15d0..2a9d10f7b5 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "保存决策服务配置失败,草稿已保留",
+ "decisionProvidersTip": "各提供商的配置独立保存,切换仅对新请求生效",
+ "decisionCurrentProvider": "当前使用",
+ "decisionSaveAndUse": "保存并使用",
+ "decisionTestDraftTip": "测试会向服务发送固定样例,可能产生费用,不保存配置",
+ "decisionOpenAIEndpointTip": "填写完整的 Decisions API 地址,兼容聊天接口的服务不一定支持 Decisions",
"chatGPTTransfer": "账户转移",
"chatGPTSignedOut": "未登录,保留账户信息以便重新登录",
"chatGPTAddAccount": "添加账户",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "拖动调整路径,双击拖拽手柄恢复自动计算",
"listMindmapRouteFallback": "当前布局无法使用手动路径,暂时显示自动路径",
"decisionModel": "决策模型",
- "decisionModelTip": "优先使用 TypeSafe System One(Jev)处理分类、筛选和评分;相关内容会发送到决策服务,可能产生费用",
- "decisionEndpointTip": "TypeSafe System One 完整接口地址,默认 https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "使用选定的决策服务进行分类、筛选和评分,相关内容会发送到该服务,可能产生费用",
+ "decisionEndpointTip": "填写此决策提供商的完整 API 接口地址",
"listView": "列表",
"databaseListView": "数据库 列表视图",
"copyRuntimeInfo": "复制运行信息",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 0d2d6348e1..d38e82ca3a 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,10 @@
{
+ "decisionSaveFailed": "儲存決策服務設定失敗,草稿已保留",
+ "decisionProvidersTip": "各提供商的設定獨立儲存,切換僅對新請求生效",
+ "decisionCurrentProvider": "目前使用",
+ "decisionSaveAndUse": "儲存並使用",
+ "decisionTestDraftTip": "測試會向服務傳送固定範例,可能產生費用,不儲存設定",
+ "decisionOpenAIEndpointTip": "填寫完整的 Decisions API 位址,相容聊天介面的服務不一定支援 Decisions",
"chatGPTTransfer": "帳戶轉移",
"chatGPTSignedOut": "未登入,保留帳戶資訊以便重新登入",
"chatGPTAddAccount": "新增帳戶",
@@ -201,8 +207,8 @@
"listMindmapRouteHandle": "拖曳調整路徑,按兩下拖曳控制點恢復自動計算",
"listMindmapRouteFallback": "目前配置無法使用手動路徑,暫時顯示自動路徑",
"decisionModel": "決策模型",
- "decisionModelTip": "優先使用 TypeSafe System One(Jev)處理分類、篩選和評分;相關內容會傳送至決策服務,可能產生費用",
- "decisionEndpointTip": "TypeSafe System One 完整介面位址,預設為 https://api.typesafe.ai/v1/systemone",
+ "decisionModelTip": "使用選定的決策服務進行分類、篩選和評分,相關內容會傳送至該服務,可能產生費用",
+ "decisionEndpointTip": "填寫此決策提供商的完整 API 介面位址",
"listView": "列表",
"databaseListView": "資料庫 列表檢視",
"copyRuntimeInfo": "複製執行資訊",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy
index 26923b45d7..5947ba0622 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy
@@ -6,7 +6,7 @@
"id": "20230304000547-ibldj1z",
"title": "Artificial Intelligence",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -328,7 +328,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-bayhe2r",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -343,12 +343,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920123707-dn6uk2y",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "The agent can use TypeSafe System One (Jev) for classification, filtering and scoring. See "
+ "Data": "The agent can use TypeSafe System One (Jev) or OpenAI Decisions API (Beta) for classification, filtering and scoring. See "
},
{
"Type": "NodeTextMark",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.sy
index cdca5db0c8..24fff6ef0a 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.sy
@@ -6,7 +6,7 @@
"id": "20260920123707-taf3ttd",
"title": "Decision model",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260920122941-wpyglnt",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -29,12 +29,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-y6ady6p",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "The agent prefers TypeSafe System One (Jev) for repetitive classification, filtering and scoring with explicit criteria. For example, ask it to rate selected documents against a research question using a defined rubric. It can pass block IDs for the kernel to read the full content, reducing repeated text generation by the main model. Embedding and reranking models are not required."
+ "Data": "The agent uses the selected decision service for repetitive classification, filtering and scoring with explicit criteria. Choose TypeSafe System One (Jev) or OpenAI Decisions API (Beta). For example, ask it to rate selected documents against a research question using a defined rubric. It can pass block IDs for the kernel to read the full content, reducing repeated text generation by the main model. Embedding and reranking models are not required. Inputs remain text or blocks; this feature does not replace chat or process images."
}
]
},
@@ -43,7 +43,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-gv610zn",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -58,7 +58,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-omz7px3",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -90,7 +90,7 @@
},
{
"Type": "NodeText",
- "Data": ", configure the API endpoint, API key, model name and request timeout, test the connection, then enable the model. It is disabled by default; the default endpoint is https://api.typesafe.ai/v1/systemone, model jev-latest, and timeout 30 seconds. Disabling it keeps the configuration."
+ "Data": ", open a provider card to edit its API endpoint, API key, model name and request timeout. Opening a card does not change the active provider. Save keeps that provider’s settings; Save and use also selects it for new requests. Each provider retains its own settings and key when you switch. The global switch is off by default; disabling it retains both configurations. TypeSafe defaults to https://api.typesafe.ai/v1/systemone with jev-latest; OpenAI defaults to https://api.openai.com/v1/decisions with gpt-6-luna. Both default to a 30-second timeout. A chat-compatible endpoint does not necessarily support Decisions. Existing TypeSafe settings are retained after upgrading."
}
]
},
@@ -99,7 +99,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-nuj8zg2",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -114,12 +114,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-falzyb0",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "The main model still understands the request, handles complex reasoning and tool selection, and prepares the final answer. Scores may fall between rubric levels, and probabilities or confidence do not guarantee correctness. Failed and unprocessed items are reported separately; completed items are retained and requests are not automatically retried."
+ "Data": "The main model still understands the request, handles complex reasoning and tool selection, and prepares the final answer. Scores may fall between rubric levels, and probabilities or confidence do not guarantee correctness. Failed and unprocessed items are reported separately; completed items are retained and requests are not automatically retried. Switching providers affects new requests; a batch already in progress keeps its original provider settings. Errors or refusals are not treated as zero scores or negative answers, and failures never silently switch to another provider."
}
]
},
@@ -128,7 +128,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-5yw9ara",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -143,12 +143,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-fvzl2j1",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Relevant content is sent to the configured decision service and charges may apply. Tool calls follow the existing capability confirmation policy. Encrypted notebooks must be unlocked; encrypted sources also require their notebook ID. The connection test uses a fixed sample and does not read your notes."
+ "Data": "Relevant text is sent to the selected decision service and charges may apply. Tool calls follow the existing capability confirmation policy. Encrypted notebooks must be unlocked; encrypted sources also require their notebook ID, and their selected content is sent in readable form. The connection test uses the complete draft settings and a fixed sample, does not read notes, and may incur charges. Testing does not save settings, change the active provider or enable the service. A successful test checks the connection and basic protocol, not answer quality."
}
]
},
@@ -157,7 +157,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-p6korqp",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -179,6 +179,16 @@
"TextMarkType": "a",
"TextMarkAHref": "https://docs.typesafe.ai/",
"TextMarkTextContent": "System One API"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " / "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "a",
+ "TextMarkAHref": "https://developers.openai.com/api/docs/guides/decisions",
+ "TextMarkTextContent": "OpenAI Decisions API"
}
]
}
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy
index 6f9292d0f7..1e2013a454 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy
@@ -6,7 +6,7 @@
"id": "20230303235619-ex5l63e",
"title": "人工智能",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -336,7 +336,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-u8b0czt",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -351,12 +351,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920123707-h982ktj",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "智能体可以使用 TypeSafe System One(Jev)完成分类、筛选和评分。配置和使用方式请参阅 "
+ "Data": "智能体可以使用 TypeSafe System One(Jev)或 OpenAI Decisions API(Beta)完成分类、筛选和评分。配置和使用方式请参阅 "
},
{
"Type": "NodeTextMark",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.sy
index aa28dc44e0..23902e40cf 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.sy
@@ -6,7 +6,7 @@
"id": "20260920123707-1cgsb12",
"title": "决策模型",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260920122941-6z1dygp",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -29,12 +29,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-iwjp5y3",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "智能体会优先将标准明确、重复的分类、筛选和评分任务交给 TypeSafe System One(Jev)。例如,要求智能体按给定标准评价选中文档与研究问题的相关程度。智能体可以直接传递区块 ID,由内核读取完整正文,减少主模型重复输出正文的负担。无需启用嵌入或重排模型。"
+ "Data": "智能体会将标准明确、重复的分类、筛选和评分任务交给选定的决策服务,可选择 TypeSafe System One(Jev)或 OpenAI Decisions API(Beta)。例如,要求智能体按给定标准评价选中文档与研究问题的相关程度。智能体可以直接传递区块 ID,由内核读取完整正文,减少主模型重复输出正文的负担。无需启用嵌入或重排模型。输入仍为文本或区块,此功能不替代聊天,也不处理图片。"
}
]
},
@@ -43,7 +43,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-dk1tbi0",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -58,7 +58,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-e5xvhrd",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -90,7 +90,7 @@
},
{
"Type": "NodeText",
- "Data": " 中填写接口地址、API 密钥、模型名称和请求超时,测试连接后启用。默认关闭,接口地址为 https://api.typesafe.ai/v1/systemone,模型为 jev-latest,超时为 30 秒。关闭后保留配置。"
+ "Data": " 中点击提供商卡片,进入详情编辑接口地址、API 密钥、模型名称和请求超时。打开卡片不会切换当前提供商。“保存”仅保存该提供商的配置,“保存并使用”还会将其设为新请求使用的提供商。切换时各自的配置和密钥均保留。全局开关默认关闭,关闭后仍保留两套配置。TypeSafe 默认接口为 https://api.typesafe.ai/v1/systemone,模型为 jev-latest;OpenAI 默认接口为 https://api.openai.com/v1/decisions,模型为 gpt-6-luna;两者默认超时均为 30 秒。兼容聊天接口的服务不一定支持 Decisions。升级后保留原有 TypeSafe 配置。"
}
]
},
@@ -99,7 +99,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-b3dug8y",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -114,12 +114,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-qpkgek0",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "主模型仍负责理解需求、复杂推理、工具选择和最终回答。评分可能介于两个等级之间,概率和置信度不代表结果一定正确。失败和未处理的项目会单独标记,已完成的结果会保留,请求不会自动重试。"
+ "Data": "主模型仍负责理解需求、复杂推理、工具选择和最终回答。评分可能介于两个等级之间,概率和置信度不代表结果一定正确。失败和未处理的项目会单独标记,已完成的结果会保留,请求不会自动重试。 切换提供商仅影响新请求,执行中的批次继续使用原有提供商配置。错误或拒答不会被当作零分或否定答案,失败时不会静默切换到其他提供商。"
}
]
},
@@ -128,7 +128,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-te89kkt",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -143,12 +143,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-au1tcls",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "相关内容会发送到配置的决策服务,可能产生费用。工具调用沿用现有的能力确认策略。加密笔记本必须先解锁,引用其中的区块还需要提供笔记本 ID。连接测试使用固定样例,不读取笔记内容。"
+ "Data": "相关文本会发送到选定的决策服务,可能产生费用。工具调用沿用现有的能力确认策略。加密笔记本必须先解锁,引用其中的区块还需要提供笔记本 ID,选中的内容会以可读形式发送。连接测试使用完整的配置草稿和固定样例,不读取笔记,可能产生费用。测试不会保存配置、切换当前提供商或启用服务。测试成功仅代表连接和基本协议可用,不代表答案质量已通过验证。"
}
]
},
@@ -157,7 +157,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-yh1yy94",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -179,6 +179,16 @@
"TextMarkType": "a",
"TextMarkAHref": "https://docs.typesafe.ai/",
"TextMarkTextContent": "System One API"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " / "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "a",
+ "TextMarkAHref": "https://developers.openai.com/api/docs/guides/decisions",
+ "TextMarkTextContent": "OpenAI Decisions API"
}
]
}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy
index 9c30861e63..eb9981741d 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy
@@ -6,7 +6,7 @@
"id": "20230304000829-9jwu3po",
"title": "人工智能",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -336,7 +336,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-t2pi3vb",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -351,12 +351,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920123707-8n0gvk2",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "智能體可以使用 TypeSafe System One(Jev)完成分類、篩選和評分。設定和使用方式請參閱 "
+ "Data": "智能體可以使用 TypeSafe System One(Jev)或 OpenAI Decisions API(Beta)完成分類、篩選和評分。設定和使用方式請參閱 "
},
{
"Type": "NodeTextMark",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.sy
index 07a6d6e99b..1eb7b2307c 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.sy
@@ -6,7 +6,7 @@
"id": "20260920123707-f5ggb0o",
"title": "決策模型",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260920122941-41jh42y",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -29,12 +29,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-ihm3tk3",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "智能體會優先將標準明確、重複的分類、篩選和評分任務交給 TypeSafe System One(Jev)。例如,要求智能體依指定標準評估選取文件與研究問題的相關程度。智能體可以直接傳遞區塊 ID,由核心讀取完整內文,減少主模型重複輸出內文的負擔。無須啟用嵌入或重排模型。"
+ "Data": "智能體會將標準明確、重複的分類、篩選和評分任務交給選定的決策服務,可選擇 TypeSafe System One(Jev)或 OpenAI Decisions API(Beta)。例如,要求智能體依指定標準評估選取文件與研究問題的相關程度。智能體可以直接傳遞區塊 ID,由核心讀取完整內文,減少主模型重複輸出內文的負擔。無須啟用嵌入或重排模型。輸入仍為文字或區塊,此功能不取代聊天,也不處理圖片。"
}
]
},
@@ -43,7 +43,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-z1tozow",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -58,7 +58,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-2h90hjs",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -90,7 +90,7 @@
},
{
"Type": "NodeText",
- "Data": " 中填寫介面位址、API 金鑰、模型名稱和請求逾時,測試連線後啟用。預設關閉,介面位址為 https://api.typesafe.ai/v1/systemone,模型為 jev-latest,逾時為 30 秒。關閉後保留設定。"
+ "Data": " 中點擊提供商卡片,進入詳細資料編輯介面位址、API 金鑰、模型名稱和請求逾時。開啟卡片不會切換目前的提供商。「儲存」僅儲存該提供商的設定,「儲存並使用」還會將其設為新請求使用的提供商。切換時各自的設定和金鑰均保留。全域開關預設關閉,關閉後仍保留兩套設定。TypeSafe 預設介面為 https://api.typesafe.ai/v1/systemone,模型為 jev-latest;OpenAI 預設介面為 https://api.openai.com/v1/decisions,模型為 gpt-6-luna;兩者預設逾時均為 30 秒。相容聊天介面的服務不一定支援 Decisions。升級後保留原有 TypeSafe 設定。"
}
]
},
@@ -99,7 +99,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-nnwx8ao",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -114,12 +114,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-fl4ev86",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "主模型仍負責理解需求、複雜推理、工具選擇和最終回答。評分可能介於兩個等級之間,機率和信心度不代表結果一定正確。失敗和未處理的項目會個別標示,已完成的結果會保留,請求不會自動重試。"
+ "Data": "主模型仍負責理解需求、複雜推理、工具選擇和最終回答。評分可能介於兩個等級之間,機率和信心度不代表結果一定正確。失敗和未處理的項目會個別標示,已完成的結果會保留,請求不會自動重試。 切換提供商僅影響新請求,執行中的批次繼續使用原有提供商設定。錯誤或拒答不會被當作零分或否定答案,失敗時不會無提示地切換至其他提供商。"
}
]
},
@@ -128,7 +128,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-sgt2wba",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -143,12 +143,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-hyptw2z",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "相關內容會傳送至設定的決策服務,可能產生費用。工具呼叫沿用既有的能力確認策略。加密筆記本必須先解鎖,引用其中的區塊還需要提供筆記本 ID。連線測試使用固定範例,不讀取筆記內容。"
+ "Data": "相關文字會傳送至選定的決策服務,可能產生費用。工具呼叫沿用既有的能力確認策略。加密筆記本必須先解鎖,引用其中的區塊還需要提供筆記本 ID,選取的內容會以可讀形式傳送。連線測試使用完整的設定草稿和固定範例,不讀取筆記,可能產生費用。測試不會儲存設定、切換目前的提供商或啟用服務。測試成功僅代表連線和基本協定可用,不代表答案品質已通過驗證。"
}
]
},
@@ -157,7 +157,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-5j2mjsr",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -179,6 +179,16 @@
"TextMarkType": "a",
"TextMarkAHref": "https://docs.typesafe.ai/",
"TextMarkTextContent": "System One API"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " / "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "a",
+ "TextMarkAHref": "https://developers.openai.com/api/docs/guides/decisions",
+ "TextMarkTextContent": "OpenAI Decisions API"
}
]
}
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy
index abbd5e99ff..2fccc3f26c 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy
@@ -6,7 +6,7 @@
"id": "20240530101000-ei5t6tt",
"title": "人工知能",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -324,7 +324,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-ejudvzu",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -339,12 +339,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920123707-x2ixv5y",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "エージェントは TypeSafe System One(Jev)を使って分類、絞り込み、評価を行えます。設定と使い方は "
+ "Data": "エージェントは TypeSafe System One(Jev)または OpenAI Decisions API(Beta)を使って分類、絞り込み、評価を行えます。設定と使い方は "
},
{
"Type": "NodeTextMark",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.sy
index 6c47d3097c..90c727df2e 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.sy
@@ -6,7 +6,7 @@
"id": "20260920123707-im3t4o6",
"title": "判定モデル",
"type": "doc",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260920122941-2jaz8xt",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -29,12 +29,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-q3bk39x",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "エージェントは、基準が明確な分類、絞り込み、評価を繰り返す作業に TypeSafe System One(Jev)を優先して使用します。例えば、指定した基準に従い、選択した文書と研究課題との関連度を評価できます。ブロック ID を渡すとカーネルが全文を読み取るため、メインモデルが本文を繰り返し出力する負担を減らせます。埋め込みモデルやリランキングモデルの有効化は不要です。"
+ "Data": "エージェントは、基準が明確な分類、絞り込み、評価を繰り返す作業に、選択した判定サービスを使用します。TypeSafe System One(Jev)または OpenAI Decisions API(Beta)を選択できます。例えば、指定した基準に従い、選択した文書と研究課題との関連度を評価できます。ブロック ID を渡すとカーネルが全文を読み取るため、メインモデルが本文を繰り返し出力する負担を減らせます。埋め込みモデルやリランキングモデルの有効化は不要です。入力はテキストまたはブロックであり、チャットの代わりにはならず、画像も処理しません。"
}
]
},
@@ -43,7 +43,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-4696u20",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -58,7 +58,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-wp7a1fq",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -86,7 +86,7 @@
},
{
"Type": "NodeText",
- "Data": " で API エンドポイント、API キー、モデル名、リクエストのタイムアウトを設定し、接続をテストしてから有効にします。既定では無効です。エンドポイントは https://api.typesafe.ai/v1/systemone、モデルは jev-latest、タイムアウトは30秒です。無効にしても設定は保持されます。"
+ "Data": " でプロバイダーのカードを開き、詳細画面で API エンドポイント、API キー、モデル名、リクエストのタイムアウトを編集します。カードを開くだけでは使用中のプロバイダーは変わりません。「保存」はそのプロバイダーの設定だけを保存し、「保存して使用」は新しいリクエストで使用するプロバイダーも変更します。切り替えても各プロバイダーの設定とキーは保持されます。全体のスイッチは既定で無効で、無効にしても両方の設定は保持されます。TypeSafe の既定値は https://api.typesafe.ai/v1/systemone と jev-latest、OpenAI は https://api.openai.com/v1/decisions と gpt-6-luna です。タイムアウトの既定値はいずれも30秒です。チャット互換サービスが Decisions に対応しているとは限りません。アップグレード後も既存の TypeSafe 設定は保持されます。"
}
]
},
@@ -95,7 +95,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-3kw55cx",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -110,12 +110,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-eu59o60",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "要求の理解、複雑な推論、ツールの選択、最終回答はメインモデルが担当します。評価値は基準の段階の間になることがあり、確率や信頼度は正しさを保証しません。失敗した項目と未処理の項目は区別され、完了した結果は保持されます。リクエストは自動で再試行されません。"
+ "Data": "要求の理解、複雑な推論、ツールの選択、最終回答はメインモデルが担当します。評価値は基準の段階の間になることがあり、確率や信頼度は正しさを保証しません。失敗した項目と未処理の項目は区別され、完了した結果は保持されます。リクエストは自動で再試行されません。 プロバイダーの切り替えは新しいリクエストに適用され、実行中のバッチは元のプロバイダー設定を使用し続けます。エラーや回答拒否をゼロの評価や否定的な回答として扱いません。失敗しても別のプロバイダーへ自動で切り替えません。"
}
]
},
@@ -124,7 +124,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260920123707-z2he5ii",
- "updated": "20260920123707"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -139,12 +139,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-f8kxvml",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
"Type": "NodeText",
- "Data": "関連する内容は設定した判定サービスに送信され、料金が発生する場合があります。ツールの呼び出しには既存の機能確認ポリシーが適用されます。暗号化されたノートブックはロックを解除し、ブロックと共にノートブック ID を指定する必要があります。接続テストは固定サンプルを使用し、ノートの内容を読み取りません。"
+ "Data": "関連するテキストは選択した判定サービスに送信され、料金が発生する場合があります。ツールの呼び出しには既存の機能確認ポリシーが適用されます。暗号化されたノートブックはロックを解除し、ブロックと共にノートブック ID を指定する必要があります。選択した内容は読み取り可能な形で送信されます。接続テストは編集中の設定一式と固定サンプルを使用し、ノートを読み取りませんが、料金が発生する場合があります。テストは設定の保存、使用中のプロバイダーの変更、サービスの有効化を行いません。成功は接続と基本的なプロトコルの確認を示すもので、回答品質の検証ではありません。"
}
]
},
@@ -153,7 +153,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260920122941-7ymos0b",
- "updated": "20260920122941"
+ "updated": "20261007020517"
},
"Children": [
{
@@ -175,6 +175,16 @@
"TextMarkType": "a",
"TextMarkAHref": "https://docs.typesafe.ai/",
"TextMarkTextContent": "System One API"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " / "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "a",
+ "TextMarkAHref": "https://developers.openai.com/api/docs/guides/decisions",
+ "TextMarkTextContent": "OpenAI Decisions API"
}
]
}
diff --git a/app/src/config/setting/mount.test.ts b/app/src/config/setting/mount.test.ts
index 320f67023e..506352a1c8 100644
--- a/app/src/config/setting/mount.test.ts
+++ b/app/src/config/setting/mount.test.ts
@@ -163,3 +163,57 @@ test("deferred refresh preserves a pressed label until its click completes or is
await Promise.resolve();
assert.equal(mounted, 1);
});
+
+test("AI remount preserves an unfocused decision draft through discard confirmation and closing animation", async () => {
+ const code = transpileModule(readFileSync("src/config/setting/mount.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const draft = {apiKey: "unsaved-openai-key"};
+ const card = {};
+ let view: object = draft;
+ let mounted = 0;
+ const listeners = new Map<string, () => void>();
+ const timers: Array<() => void> = [];
+ const root = {innerHTML: "decision settings", scrollTop: 25, scrollLeft: 0,
+ contains: (element: unknown) => element === card,
+ querySelector: (selector: string) => selector.includes("[data-decision-profile-view]") ? view : null};
+ const document = {activeElement: {}, addEventListener: (name: string, callback: () => void) => listeners.set(name, callback)};
+ const exports = {} as {remountOpenSettingTab: (tab: string) => Promise<void>};
+ runInNewContext(code, {exports, document,
+ setTimeout: (callback: () => void) => timers.push(callback),
+ require: () => ({Constants: {DIALOG_SETTING: "settings"}, getSearchKeywordsLower: () => "",
+ getSettingsOwnerApp: () => ({}), getSettingTab: () => ({mount: async () => {
+ mounted++;
+ root.innerHTML = "refreshed";
+ }})}),
+ window: {siyuan: {dialogs: [{element: {getAttribute: () => "settings", querySelector: () => root}}]}}});
+ const flush = async () => {
+ timers.splice(0).forEach(callback => callback());
+ await Promise.resolve();
+ };
+ // 外部 AI 更新到达时,焦点在空白区域,仍需保留详情中的未保存密钥。
+ await exports.remountOpenSettingTab("ai");
+ assert.equal(mounted, 0);
+ document.activeElement = {modal: "discard confirmation"};
+ listeners.get("focusout")();
+ await flush();
+ await exports.remountOpenSettingTab("ai");
+ assert.equal(mounted, 0);
+ assert.equal((view as typeof draft).apiKey, "unsaved-openai-key");
+ // 动画未结束时详情仍在 DOM,关闭通知也不能提前重建。
+ listeners.get("siyuan-decision-profile-closed")();
+ await flush();
+ assert.equal(mounted, 0);
+ view = undefined;
+ document.activeElement = card;
+ listeners.get("siyuan-decision-profile-closed")();
+ await flush();
+ assert.equal(mounted, 0);
+ // 返回后的卡片焦点不得被刷新替换,真正离开设置面板后再恢复待执行刷新。
+ document.activeElement = {};
+ listeners.get("focusout")();
+ await flush();
+ assert.equal(mounted, 1);
+ assert.equal(root.innerHTML, "refreshed");
+ assert.equal(root.scrollTop, 25);
+});
diff --git a/app/src/config/setting/mount.ts b/app/src/config/setting/mount.ts
index 1d7634dc75..616503d324 100644
--- a/app/src/config/setting/mount.ts
+++ b/app/src/config/setting/mount.ts
@@ -53,13 +53,14 @@ export const remountOpenSettingTab = async (tabId: TSettingTab) => {
return;
}
if (root.contains(document.activeElement) || pressedTarget && root.contains(pressedTarget as Node) ||
- root.querySelector(".config-entry-visibility__view")) {
+ root.querySelector(".config-entry-visibility__view, [data-decision-profile-view]")) {
deferredTabs.add(tabId);
if (!watchingFocus) {
watchingFocus = true;
- // 离开输入控件或关闭入口方案编辑器后再刷新,保留尚未提交的输入与草稿。
+ // 离开输入控件或关闭配置详情后再刷新,保留尚未提交的输入与草稿。
document.addEventListener("focusout", refreshDeferredTabs);
document.addEventListener("siyuan-entry-profile-closed", refreshDeferredTabs);
+ document.addEventListener("siyuan-decision-profile-closed", refreshDeferredTabs);
}
return;
}
diff --git a/app/src/config/tabs/ai/aiDecisionUi.test.ts b/app/src/config/tabs/ai/aiDecisionUi.test.ts
new file mode 100644
index 0000000000..e5acf49410
--- /dev/null
+++ b/app/src/config/tabs/ai/aiDecisionUi.test.ts
@@ -0,0 +1,242 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, transpileModule} from "typescript";
+
+class ElementStub {
+ innerHTML = "";
+ textContent = "";
+ disabled = false;
+ isConnected = true;
+ dataset: Record<string, string> = {};
+ events: Record<string, (event: any) => any> = {};
+ elements: Record<string, ElementStub> = {};
+ attributes: Record<string, string> = {};
+ emitted: string[] = [];
+ focused = false;
+ setAttribute(name: string, value: string) { this.attributes[name] = value; }
+ dispatchEvent(event: {type: string}) { this.emitted.push(event.type); }
+ addEventListener(name: string, callback: (event: any) => any) { this.events[name] = callback; }
+ querySelector(selector: string) { return this.elements[selector]; }
+ querySelectorAll(): ElementStub[] { return []; }
+ closest() { return this; }
+ focus() { this.focused = true; }
+}
+
+const loadUI = () => {
+ const source = readFileSync(resolve(process.cwd(), "src/config/tabs/ai/aiDecisionUi.ts"), "utf8");
+ const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;
+ const profile = {endpoint: "https://type.example", apiKey: "type-key", name: "jev-latest", timeout: 30};
+ const decision = {enabled: true, provider: "typesafe", profiles: {typesafe: profile,
+ openai: {...profile, endpoint: "https://open.example", apiKey: "open-key", name: "gpt-6-luna"}}};
+ const root = new ElementStub();
+ const cards = new ElementStub();
+ root.elements["#aiDecisionCards"] = cards;
+ const view = new ElementStub();
+ for (const selector of [".b3-dialog__body", "[data-type='testResult']", "[data-action='test']"]) {
+ view.elements[selector] = new ElementStub();
+ }
+ const patches: any[] = [];
+ const requests: Array<{body: any; complete: (response: any) => void; fail: () => void; done: () => void}> = [];
+ let confirms = 0;
+ let removed = false;
+ let applySave = true;
+ let finishRemoval: () => void;
+ const exports: any = {};
+ runInNewContext(code, {
+ exports,
+ CustomEvent: class { constructor(public type: string) {} },
+ window: {siyuan: {config: {ai: {decision}}, languages: new Proxy({}, {get: (_target, key) => String(key)})},
+ addEventListener() {}, removeEventListener() {}},
+ require: (name: string) => {
+ if (name.endsWith("/escape")) { return {escapeHtmlTextAndAttr: (value: string) => value}; }
+ if (name.endsWith("/fragments")) { return {genConfigItemMainHtml: () => "", bindPasswordIconaToggle() {}}; }
+ if (name.endsWith("/confirmDialog")) { return {confirmDialog: () => confirms++}; }
+ if (name.endsWith("/fetch")) {
+ return {fetchPost: (_url: string, body: any, complete: (response: any) => void, _headers: unknown, fail: () => void) =>
+ new Promise<void>(done => requests.push({body, complete, fail, done}))};
+ }
+ if (name === "./aiRuntime") {
+ return {aiConfigApi: {patch: async (path: string, value: any, applied: () => void) => {
+ patches.push({path, value});
+ if (applySave) { applied(); }
+ }}};
+ }
+ if (name === "./aiProviderUi") {
+ return {createProviderView: () => view, removeProviderView: (_root: unknown, _view: unknown, callback: () => void) => {
+ removed = true;
+ finishRemoval = callback;
+ }};
+ }
+ throw new Error(name);
+ },
+ });
+ exports.mountDecisionCards(root);
+ const target = new ElementStub();
+ target.dataset.decisionProvider = "openai";
+ cards.events.click({target});
+ const click = (action: string) => {
+ const target = new ElementStub();
+ target.dataset.action = action;
+ return view.events.click({target});
+ };
+ const edit = (key: string, value: string) => view.events.input({target: {dataset: {decisionField: key}, value}});
+ return {exports, decision, patches, requests, view, root, click, edit, finishRemoval: () => finishRemoval(),
+ confirms: () => confirms, removed: () => removed, failSave: () => applySave = false};
+};
+
+test("opening and cancelling a decision card never selects or saves it", async () => {
+ const ui = loadUI();
+ assert.equal(ui.decision.provider, "typesafe");
+ assert.equal(ui.patches.length, 0);
+ await ui.click("cancel");
+ assert.equal(ui.removed(), true);
+ assert.equal(ui.patches.length, 0);
+});
+
+test("profile drafts isolate keys and save only the edited provider atomically", async () => {
+ const ui = loadUI();
+ ui.edit("apiKey", "new-open-key");
+ assert.equal(ui.decision.profiles.openai.apiKey, "open-key");
+ await ui.click("use");
+ assert.equal(ui.patches.length, 1);
+ const patch = ui.patches[0];
+ assert.equal(patch.path, "decision");
+ assert.equal(patch.value.provider, "openai");
+ assert.equal(patch.value.profiles.openai.apiKey, "new-open-key");
+ assert.equal(patch.value.profiles.typesafe, undefined);
+ assert.equal(patch.value.enabled, undefined);
+ assert.equal(ui.decision.profiles.typesafe.apiKey, "type-key");
+});
+
+test("save alone preserves active selection; failure retains the unsaved draft", async () => {
+ const ui = loadUI();
+ ui.failSave();
+ ui.edit("name", "draft-model");
+ await ui.click("save");
+ assert.equal(ui.patches[0].value.provider, undefined);
+ assert.equal(ui.removed(), false);
+ assert.equal(ui.view.elements["[data-type='testResult']"].textContent, "decisionSaveFailed");
+ await ui.click("back");
+ assert.equal(ui.confirms(), 1);
+ assert.equal(ui.removed(), false);
+});
+
+test("draft tests send isolated credentials without saving; edits invalidate pending results", async () => {
+ const ui = loadUI();
+ const testing = ui.click("test");
+ await ui.click("test");
+ assert.equal(ui.requests.length, 1);
+ assert.equal(ui.requests[0].body.provider, "openai");
+ assert.equal(ui.requests[0].body.profile.apiKey, "open-key");
+ ui.edit("apiKey", "edited-key");
+ assert.equal(ui.requests[0].body.profile.apiKey, "open-key");
+ ui.requests[0].complete({data: {matched: true}});
+ ui.requests[0].done();
+ await testing;
+ assert.equal(ui.view.elements["[data-type='testResult']"].textContent, "");
+ assert.equal(ui.patches.length, 0);
+ assert.equal(ui.decision.provider, "typesafe");
+ assert.equal(ui.view.elements["[data-action='test']"].disabled, false);
+});
+
+test("closing a detail hides late test results", async () => {
+ const ui = loadUI();
+ const testing = ui.click("test");
+ await ui.click("cancel");
+ ui.requests[0].complete({data: {matched: true}});
+ ui.requests[0].done();
+ await testing;
+ assert.equal(ui.view.elements["[data-type='testResult']"].textContent, "");
+});
+
+test("decision close notification waits until the marked detail is removed", async () => {
+ const ui = loadUI();
+ assert.equal(ui.view.attributes["data-decision-profile-view"], "openai");
+ await ui.click("cancel");
+ assert.deepEqual(ui.root.emitted, []);
+ ui.finishRemoval();
+ assert.deepEqual(ui.root.emitted, ["siyuan-decision-profile-closed"]);
+});
+
+test("closing animation never steals focus from a newly opened provider detail", async () => {
+ const ui = loadUI();
+ const card = new ElementStub();
+ ui.root.elements["[data-decision-provider='openai']"] = card;
+ await ui.click("cancel");
+ ui.root.elements[".config-ai-provider__view.config__view--show"] = new ElementStub();
+ ui.finishRemoval();
+ assert.equal(card.focused, false);
+ assert.deepEqual(ui.root.emitted, ["siyuan-decision-profile-closed"]);
+});
+
+test("closing restores card focus only when the settings root is still connected", async () => {
+ for (const connected of [true, false]) {
+ const ui = loadUI();
+ const card = new ElementStub();
+ ui.root.elements["[data-decision-provider='openai']"] = card;
+ await ui.click("cancel");
+ ui.root.isConnected = connected;
+ ui.finishRemoval();
+ assert.equal(card.focused, connected);
+ assert.deepEqual(ui.root.emitted, ["siyuan-decision-profile-closed"]);
+ }
+});
+
+test("provider view removal invokes its completion once after animation or timeout", () => {
+ const source = readFileSync("src/config/tabs/ai/aiProviderUi.ts", "utf8");
+ const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;
+ const timers: Array<() => void> = [];
+ let transition: (event: {propertyName: string}) => void;
+ let connected = true;
+ let completed = 0;
+ const view = {classList: {remove() {}}, remove: () => connected = false,
+ addEventListener: (_name: string, callback: typeof transition) => transition = callback};
+ const exports: {removeProviderView?: (root: unknown, view: unknown, callback: () => void) => void} = {};
+ runInNewContext(code, {exports, require: () => ({}), window: {setTimeout: (callback: () => void) => timers.push(callback)}});
+ exports.removeProviderView({}, view, () => {
+ assert.equal(connected, false);
+ completed++;
+ });
+ assert.equal(completed, 0);
+ transition({propertyName: "transform"});
+ assert.equal(completed, 0);
+ transition({propertyName: "opacity"});
+ assert.equal(completed, 1);
+ timers.splice(0).forEach(callback => callback());
+ assert.equal(completed, 1);
+ connected = true;
+ exports.removeProviderView({}, view, () => { assert.equal(connected, false); completed++; });
+ timers.splice(0).forEach(callback => callback());
+ transition({propertyName: "opacity"});
+ assert.equal(completed, 2);
+});
+
+test("current test results clear on edits and failures restore the test button", async () => {
+ const ui = loadUI();
+ const testing = ui.click("test");
+ ui.requests[0].complete({data: {matched: true}});
+ ui.requests[0].done();
+ await testing;
+ const result = ui.view.elements["[data-type='testResult']"];
+ assert.equal(result.textContent, "testConnectionSuccess");
+ ui.edit("endpoint", "https://changed.example");
+ assert.equal(result.textContent, "");
+ const retry = ui.click("test");
+ ui.requests[1].fail();
+ ui.requests[1].done();
+ await retry;
+ assert.equal(result.textContent, "testConnectionFail");
+ assert.equal(ui.view.elements["[data-action='test']"].disabled, false);
+ assert.equal(ui.patches.length, 0);
+});
+
+test("legacy flat configuration supplies only the TypeSafe draft", () => {
+ const ui = loadUI();
+ const legacy = {endpoint: "https://legacy.example", apiKey: "legacy-key", name: "legacy-model", timeout: 60};
+ assert.equal(ui.exports.getDecisionProfileDraft(legacy, "typesafe").apiKey, "legacy-key");
+ assert.equal(ui.exports.getDecisionProfileDraft(legacy, "openai").apiKey, "");
+ assert.equal(ui.exports.getDecisionProfileDraft(legacy, "openai").name, "gpt-6-luna");
+});
diff --git a/app/src/config/tabs/ai/aiDecisionUi.ts b/app/src/config/tabs/ai/aiDecisionUi.ts
new file mode 100644
index 0000000000..483866b10c
--- /dev/null
+++ b/app/src/config/tabs/ai/aiDecisionUi.ts
@@ -0,0 +1,220 @@
+import {escapeHtmlTextAndAttr} from "../../../util/escape";
+import {bindPasswordIconaToggle, genConfigItemMainHtml} from "../../render/fragments";
+import {confirmDialog} from "../../../dialog/confirmDialog";
+import {fetchPost} from "../../../util/fetch";
+import {aiConfigApi, AI_CONFIG_CHANGED_EVENT} from "./aiRuntime";
+import {createProviderView, removeProviderView} from "./aiProviderUi";
+
+type DecisionProvider = "typesafe" | "openai";
+const PROVIDERS: DecisionProvider[] = ["typesafe", "openai"];
+interface IDecisionField {
+ key: keyof Config.IDecisionProfile;
+ title: string;
+ desc: string;
+ type: string;
+}
+// 各供应商分别声明字段和默认值,共用控件只负责渲染,不限定其他供应商的参数。
+const PROVIDER_DETAILS: Record<DecisionProvider, {title: string; defaults: Config.IDecisionProfile; fields: IDecisionField[]}> = {
+ typesafe: {
+ title: "TypeSafe System One",
+ defaults: {endpoint: "https://api.typesafe.ai/v1/systemone", apiKey: "", name: "jev-latest", timeout: 30},
+ fields: [
+ {key: "endpoint", title: "apiEndpoint", type: "url", desc: "decisionEndpointTip"},
+ {key: "apiKey", title: "apiKey", type: "password", desc: "apiKeyTip"},
+ {key: "name", title: "apiModel", type: "text", desc: "apiModelTip"},
+ {key: "timeout", title: "apiTimeout", type: "number", desc: "apiTimeoutTip"},
+ ],
+ },
+ openai: {
+ title: "OpenAI Decisions API (Beta)",
+ defaults: {endpoint: "https://api.openai.com/v1/decisions", apiKey: "", name: "gpt-6-luna", timeout: 30},
+ fields: [
+ {key: "endpoint", title: "apiEndpoint", type: "url", desc: "decisionOpenAIEndpointTip"},
+ {key: "apiKey", title: "apiKey", type: "password", desc: "apiKeyTip"},
+ {key: "name", title: "apiModel", type: "text", desc: "apiModelTip"},
+ {key: "timeout", title: "apiTimeout", type: "number", desc: "apiTimeoutTip"},
+ ],
+ },
+};
+const title = (provider: DecisionProvider) => PROVIDER_DETAILS[provider].title;
+const escapeHTML = (value: string) => escapeHtmlTextAndAttr(value ?? "");
+
+export const getDecisionProfileDraft = (decision: Config.IDecision, provider: DecisionProvider): Config.IDecisionProfile => {
+ const profile = decision.profiles?.[provider];
+ if (profile) {
+ return {...profile};
+ }
+ const defaults = PROVIDER_DETAILS[provider].defaults;
+ if (provider === "typesafe" && !decision.profiles) {
+ return {endpoint: decision.endpoint || defaults.endpoint, apiKey: decision.apiKey || "",
+ name: decision.name || defaults.name, timeout: decision.timeout || defaults.timeout};
+ }
+ return {...defaults};
+};
+
+// 只提交编辑的供应商配置,由设置补丁接口原子合并,保留其他供应商及其他窗口的修改。
+export const getDecisionProfilePatch = (provider: DecisionProvider, profile: Config.IDecisionProfile, use: boolean) => ({
+ profiles: {[provider]: {...profile}},
+ ...(use ? {provider} : {}),
+});
+
+export const genDecisionCardsHtml = () => `<div class="b3-label config-item">
+ ${genConfigItemMainHtml(window.siyuan.languages.apiProvider, window.siyuan.languages.decisionProvidersTip)}
+ <div class="fn__hr"></div><div id="aiDecisionCards"></div>
+</div>`;
+
+const renderDecisionCards = (root: HTMLElement) => {
+ const container = root.querySelector<HTMLElement>("#aiDecisionCards");
+ if (!container) { return; }
+ const decision = window.siyuan.config.ai.decision;
+ container.innerHTML = `<div class="b3-cards b3-cards--nowrap">${PROVIDERS.map(provider => {
+ const active = (decision.provider || "typesafe") === provider;
+ return `<div class="b3-card${active ? " b3-card--current" : ""}" role="button" tabindex="0" data-decision-provider="${provider}" aria-label="${escapeHTML(title(provider))}${active ? `: ${escapeHTML(window.siyuan.languages.decisionCurrentProvider)}` : ""}">
+ <div class="b3-card__img"><span><svg class="b3-card__icon"><use xlink:href="#iconBrain"></use></svg></span></div>
+ <div class="fn__flex-1 fn__flex-column"><div class="b3-card__info b3-card__info--left fn__flex-1">
+ <div class="fn__ellipsis config-name">${title(provider)}</div>
+ <div class="b3-card__desc">${active ? window.siyuan.languages.decisionCurrentProvider : window.siyuan.languages.config}</div>
+ </div></div>
+</div>`;
+ }).join("")}</div>`;
+};
+
+const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {
+ const draft = getDecisionProfileDraft(window.siyuan.config.ai.decision, provider);
+ const initial = JSON.stringify(draft);
+ const view = createProviderView(root, title(provider));
+ view.setAttribute("data-decision-profile-view", provider);
+ const fields = PROVIDER_DETAILS[provider].fields;
+ view.querySelector(".b3-dialog__body").innerHTML = `<div class="b3-dialog__content" style="padding: 0">
+ <div class="config-items">${fields.map(field => {
+ const input = `<input id="aiDecisionDetail-${field.key}" class="b3-text-field${field.type === "password" ? " b3-form__icona-input" : " fn__flex-center fn__size200"}" data-decision-field="${field.key}" type="${field.type}" spellcheck="false" autocomplete="off"${field.type === "number" ? ' min="1" max="600" step="1" required' : ""} value="${escapeHTML(String(draft[field.key]))}">`;
+ return `<label class="fn__flex b3-label config-item">${genConfigItemMainHtml(window.siyuan.languages[field.title], window.siyuan.languages[field.desc])}
+ <span class="fn__space"></span>${field.type === "password" ? `<div class="b3-form__icona fn__size200">${input}<svg class="b3-form__icona-icon" data-action="togglePassword"><use xlink:href="#iconEye"></use></svg></div>` : input}</label>`;
+ }).join("")}</div>
+ <div class="b3-label"><div class="b3-label__text">${window.siyuan.languages.decisionTestDraftTip}</div>
+ <div class="fn__hr"></div><button class="b3-button b3-button--outline" data-action="test">${window.siyuan.languages.testConnection}</button>
+ <div class="fn__hr"></div><div data-type="testResult" role="status" aria-live="polite"></div>
+ </div>
+</div><div class="b3-dialog__action">
+ <button class="b3-button b3-button--cancel" data-action="cancel">${window.siyuan.languages.cancel}</button><span class="fn__space"></span>
+ <button class="b3-button b3-button--outline" data-action="save">${window.siyuan.languages.save}</button><span class="fn__space"></span>
+ <button class="b3-button b3-button--text" data-action="use">${window.siyuan.languages.decisionSaveAndUse}</button>
+</div>`;
+ bindPasswordIconaToggle(view, "aiDecisionDetail-apiKey");
+ const result = view.querySelector<HTMLElement>("[data-type='testResult']");
+ const testButton = view.querySelector<HTMLButtonElement>("[data-action='test']");
+ let revision = 0;
+ let closed = false;
+ let saving = false;
+ let testing = false;
+ const leave = () => {
+ closed = true;
+ removeProviderView(root, view, () => {
+ const host = root.closest<HTMLElement>(".config__tab-container") || root;
+ if (root.isConnected && !host.querySelector(".config-ai-provider__view.config__view--show")) {
+ root.querySelector<HTMLElement>(`[data-decision-provider='${provider}']`)?.focus();
+ }
+ root.dispatchEvent(new CustomEvent("siyuan-decision-profile-closed", {bubbles: true}));
+ });
+ };
+ const close = () => {
+ if (saving) { return; }
+ if (JSON.stringify(draft) !== initial) {
+ confirmDialog(window.siyuan.languages.confirm, window.siyuan.languages.discardUnsavedChanges, leave);
+ } else { leave(); }
+ };
+ const back = view.querySelector<HTMLElement>("[data-action='back']");
+ back?.setAttribute("role", "button");
+ back?.setAttribute("tabindex", "0");
+ back?.addEventListener("keydown", event => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ close();
+ }
+ });
+ view.querySelector<HTMLInputElement>("[data-decision-field='endpoint']")?.focus();
+ const validate = (required: boolean) => {
+ for (const input of Array.from(view.querySelectorAll<HTMLInputElement>("[data-decision-field]"))) {
+ input.required = required || input.type === "number";
+ if (!input.reportValidity()) { return false; }
+ }
+ return true;
+ };
+ view.addEventListener("input", event => {
+ const input = event.target as HTMLInputElement;
+ const field = input.dataset.decisionField as keyof Config.IDecisionProfile;
+ if (!field) { return; }
+ if (field === "timeout") { draft.timeout = input.valueAsNumber; } else { draft[field] = input.value; }
+ revision++;
+ result.textContent = "";
+ });
+ view.addEventListener("click", async event => {
+ const action = (event.target as Element).closest<HTMLElement>("[data-action]")?.dataset.action;
+ if (action === "back" || action === "cancel") { close(); return; }
+ if (saving || closed) { return; }
+ if (action === "save" || action === "use") {
+ if (!validate(action === "use")) { return; }
+ saving = true;
+ revision++;
+ result.textContent = "";
+ view.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button").forEach(element => element.disabled = true);
+ let applied = false;
+ try {
+ await aiConfigApi.patch("decision", getDecisionProfilePatch(provider, draft, action === "use"), () => {
+ applied = true;
+ renderDecisionCards(root);
+ leave();
+ });
+ } finally {
+ if (!applied) { result.textContent = window.siyuan.languages.decisionSaveFailed; }
+ saving = false;
+ view.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button").forEach(element => element.disabled = false);
+ testButton.disabled = testing;
+ }
+ } else if (action === "test" && !testing && validate(true)) {
+ testing = true;
+ testButton.disabled = true;
+ testButton.textContent = window.siyuan.languages.testConnectionTesting;
+ result.textContent = "";
+ const testedRevision = revision;
+ const current = () => !closed && view.isConnected && testedRevision === revision;
+ try {
+ await fetchPost("/api/ai/testDecisionModel", {provider, profile: {...draft}}, response => {
+ if (!current()) { return; }
+ result.textContent = response.data?.matched ? window.siyuan.languages.testConnectionSuccess
+ : response.data?.msg ? window.siyuan.languages.testConnectionFailMsg.replace("${msg}", String(response.data.msg))
+ : window.siyuan.languages.testConnectionFail;
+ }, undefined, () => {
+ if (current()) { result.textContent = window.siyuan.languages.testConnectionFail; }
+ });
+ } catch (_error) {
+ if (current()) { result.textContent = window.siyuan.languages.testConnectionFail; }
+ } finally {
+ testing = false;
+ testButton.disabled = saving;
+ testButton.textContent = window.siyuan.languages.testConnection;
+ }
+ }
+ });
+};
+
+export const mountDecisionCards = (root: HTMLElement) => {
+ const container = root.querySelector<HTMLElement>("#aiDecisionCards");
+ if (!container) { return; }
+ renderDecisionCards(root);
+ container.addEventListener("click", event => {
+ const provider = (event.target as Element).closest<HTMLElement>("[data-decision-provider]")?.dataset.decisionProvider as DecisionProvider;
+ if (PROVIDERS.includes(provider)) { openDecisionProfile(root, provider); }
+ });
+ container.addEventListener("keydown", event => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ (event.target as HTMLElement).click();
+ }
+ });
+ const update = () => {
+ if (!container.isConnected) { window.removeEventListener(AI_CONFIG_CHANGED_EVENT, update); return; }
+ renderDecisionCards(root);
+ };
+ window.addEventListener(AI_CONFIG_CHANGED_EVENT, update);
+};
diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.ts
index a7f944c351..d62ba882ad 100644
--- a/app/src/config/tabs/ai/aiProviderUi.ts
+++ b/app/src/config/tabs/ai/aiProviderUi.ts
@@ -98,20 +98,27 @@ const getProviderViews = (root: HTMLElement) => {
element instanceof HTMLElement && element.classList.contains("config-ai-provider__view"));
};
-const removeProviderView = (root: HTMLElement, view?: HTMLElement) => {
+export const removeProviderView = (root: HTMLElement, view?: HTMLElement, onRemoved?: () => void) => {
const views = view ? [view] : getProviderViews(root);
views.forEach((item) => {
+ let removed = false;
+ const remove = () => {
+ if (removed) { return; }
+ removed = true;
+ item.remove();
+ onRemoved?.();
+ };
item.classList.remove("config__view--show");
item.addEventListener("transitionend", (event) => {
if (event.propertyName === "opacity") {
- item.remove();
+ remove();
}
});
- window.setTimeout(() => item.remove(), 300);
+ window.setTimeout(remove, 300);
});
};
-const createProviderView = (root: HTMLElement, backLabel: string, stacked = false) => {
+export const createProviderView = (root: HTMLElement, backLabel: string, stacked = false) => {
if (!stacked) {
removeProviderView(root);
}
diff --git a/app/src/config/tabs/ai/aiTab.ts b/app/src/config/tabs/ai/aiTab.ts
index bcd243307c..463a5cc26c 100644
--- a/app/src/config/tabs/ai/aiTab.ts
+++ b/app/src/config/tabs/ai/aiTab.ts
@@ -13,7 +13,6 @@ import {
mountEmbeddingStatsBlock,
mountEmbeddingTestBtn,
mountRerankTestBtn,
- mountDecisionTestBtn,
} from "./aiUi";
import {
genProviderCardsHtml,
@@ -32,6 +31,7 @@ import {
import {isAgentStreamingMarkdownEnabled, setAgentStreamingMarkdownEnabled} from "./agentStreamingMarkdown";
import {openSkillManager} from "../../../ai/skills/manager";
import {openAgentInstructions} from "./aiInstructions";
+import {genDecisionCardsHtml, mountDecisionCards} from "./aiDecisionUi";
import {genMcpOAuthHtml, mountMcpOAuth} from "./mcpOAuthUi";
const registerAiProvidersGroup = (tab: SettingTabBuilder) => {
@@ -165,31 +165,13 @@ const registerAiDecisionGroup = (tab: SettingTabBuilder) => {
title: window.siyuan.languages.decisionModel,
desc: window.siyuan.languages.decisionModelTip,
});
- group.textBlock("ai.decision.endpoint", {
- spellcheck: false,
- title: window.siyuan.languages.apiEndpoint,
- desc: window.siyuan.languages.decisionEndpointTip,
- mode: "input-text",
- });
- group.textBlock("ai.decision.apiKey", {
- spellcheck: false,
- title: window.siyuan.languages.apiKey,
- desc: window.siyuan.languages.apiKeyTip,
- mode: "input-password",
- });
- group.textBlock("ai.decision.name", {
- spellcheck: false,
- title: window.siyuan.languages.apiModel,
- desc: window.siyuan.languages.apiModelTip,
- mode: "input-text",
- afterMount: mountDecisionTestBtn,
- });
- group.number("ai.decision.timeout", {
- title: window.siyuan.languages.apiTimeout,
- desc: window.siyuan.languages.apiTimeoutTip,
- min: 1,
- max: 600,
- unit: "s",
+ group.slot({
+ key: "decisionProviders",
+ keywords: ["TypeSafe", "OpenAI", "Decisions", window.siyuan.languages.apiKey,
+ window.siyuan.languages.apiEndpoint, window.siyuan.languages.apiModel,
+ window.siyuan.languages.apiTimeout, window.siyuan.languages.testConnection],
+ html: genDecisionCardsHtml,
+ afterMount: mountDecisionCards,
});
};
diff --git a/app/src/config/tabs/ai/aiUi.ts b/app/src/config/tabs/ai/aiUi.ts
index 4fae236bcd..6175ca0689 100644
--- a/app/src/config/tabs/ai/aiUi.ts
+++ b/app/src/config/tabs/ai/aiUi.ts
@@ -306,38 +306,6 @@ export const mountRerankTestBtn = (root: HTMLElement) => {
});
};
-// mountDecisionTestBtn 将测试按钮放在模型名称输入框右侧,并在网络或内核错误后恢复按钮。
-export const mountDecisionTestBtn = (root: HTMLElement) => {
- const button = mountModelTestButton(root, "ai.decision.name", "aiDecisionTestBtn", "input");
- if (!button) {
- return;
- }
- const label = button.querySelector("span");
- button.addEventListener("click", async () => {
- button.disabled = true;
- label.textContent = window.siyuan.languages.testConnectionTesting;
- try {
- if (!await aiConfigApi.waitForSave()) {
- showMessage(window.siyuan.languages.testConnectionFail, undefined, "error");
- return;
- }
- await fetchPost("/api/ai/testDecisionModel", {}, response => {
- const data = response.data;
- if (data.matched) {
- showMessage(window.siyuan.languages.testConnectionSuccess, undefined, "info");
- return;
- }
- showMessage(data.msg
- ? window.siyuan.languages.testConnectionFailMsg.replace("${msg}", escapeHtml(data.msg))
- : window.siyuan.languages.testConnectionFail, undefined, "error");
- }, undefined, () => showMessage(window.siyuan.languages.testConnectionFail, undefined, "error"));
- } finally {
- button.disabled = false;
- label.textContent = window.siyuan.languages.testConnection;
- }
- });
-};
-
export const getModelPickerKeywords = (group: ModelPickerGroup): string[] => {
const keywords = [
window.siyuan.languages.defaultModel,
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 0e9a15b366..1ab0f5fd32 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -38,6 +38,8 @@ export type AIConfirmRequestInput = { "always"?: boolean | null; "approved"?: bo
export type AIDecisionTestData = { "matched": boolean; "msg"?: string; };
+export type AIDecisionTestRequestInput = { "profile"?: SettingDecisionProfileInput | null; "provider"?: string; };
+
export type AIEditorAction = { "action": string; "id": string; "name": string; };
export type AIEditorActionIDRequestInput = { "id": string; };
@@ -1946,9 +1948,13 @@ export type SettingCapabilityPolicyInput = { "default"?: string | null; "overrid
export type SettingCloudUserRequestInput = { "cached"?: boolean; "token"?: string | null; };
-export type SettingDecision = { "apiKey": string; "enabled": boolean; "endpoint": string; "name": string; "timeout": number; };
+export type SettingDecision = { "apiKey": string; "enabled": boolean; "endpoint": string; "name": string; "profiles": Record<string, SettingDecisionProfile | null> | null; "provider": string; "timeout": number; };
+
+export type SettingDecisionInput = { "apiKey"?: string | null; "enabled"?: boolean | null; "endpoint"?: string | null; "name"?: string | null; "profiles"?: Record<string, SettingDecisionProfileInput | null> | null; "provider"?: string | null; "timeout"?: number | null; };
+
+export type SettingDecisionProfile = { "apiKey": string; "endpoint": string; "name": string; "timeout": number; };
-export type SettingDecisionInput = { "apiKey"?: string | null; "enabled"?: boolean | null; "endpoint"?: string | null; "name"?: string | null; "timeout"?: number | null; };
+export type SettingDecisionProfileInput = { "apiKey": string; "endpoint": string; "name": string; "timeout": number; };
export type SettingEditing = { "maxCompletionTokens": number; "maxHistoryMessages": number; "modelId": string; "temperature": number; };
@@ -2866,9 +2872,9 @@ export interface APIPOSTRoutes {
body: "none";
};
"/api/ai/testDecisionModel": {
- request: EmptyRequestInput;
+ request: AIDecisionTestRequestInput;
response: { "code": 0; "data": AIDecisionTestData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
- body: "none";
+ body: "json";
};
"/api/ai/testEmbeddingModel": {
request: EmptyRequestInput;
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 91cfc2d96a..34864f70fc 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -201,17 +201,21 @@ declare namespace Config {
outputFormat: string;
}
- /**
- * 智能体决策模型配置,使用 TypeSafe System One 协议。
- */
- export interface IDecision {
- enabled: boolean;
+ /** 独立保存的决策服务凭证和参数。 */
+ export interface IDecisionProfile {
endpoint: string;
apiKey: string;
name: string;
timeout: number;
}
+ /** 当前决策服务及各供应商独立配置;平铺字段仅兼容 TypeSafe 客户端。 */
+ export interface IDecision extends IDecisionProfile {
+ enabled: boolean;
+ provider: string;
+ profiles: Record<string, IDecisionProfile>;
+ }
+
/**
* Embedding model configuration
*/
diff --git a/kernel/agent/decision_test.go b/kernel/agent/decision_test.go
index 73d7ef4bfd..f9e3c80359 100644
--- a/kernel/agent/decision_test.go
+++ b/kernel/agent/decision_test.go
@@ -31,7 +31,7 @@ func TestDecisionCapabilityAvailabilityAndApproval(t *testing.T) {
check(false)
kernelModel.Conf.AI.Decision.Enabled = true
check(false)
- kernelModel.Conf.AI.Decision.APIKey = "key"
+ kernelModel.Conf.AI.Decision.Profiles["typesafe"].APIKey = "key"
set := check(true)
registration := set.registration("decision")
if !tools.DecisionTool.AgentOnly || !needsCapabilityConfirm(registration, "evaluate", nil, false, nil) {
diff --git a/kernel/api/ai_decision.go b/kernel/api/ai_decision.go
index bb59921d39..c9a7a8a834 100644
--- a/kernel/api/ai_decision.go
+++ b/kernel/api/ai_decision.go
@@ -1,26 +1,41 @@
package api
import (
+ "encoding/json"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
var testDecisionModel = contractHandler(apicontract.AITestDecisionModel, testDecisionModelContract)
-// testDecisionModelContract 使用固定样例测试已保存配置,允许在启用前测试,不读取笔记内容。
-func testDecisionModelContract(c *gin.Context, _ apicontract.EmptyRequest) apicontract.Response[apicontract.AIDecisionTestData] {
- decision := model.Conf.AI.Decision
- if !decision.Configured() {
- message := "decision model not configured"
- return apicontract.Success(apicontract.AIDecisionTestData{Msg: &message})
+// testDecisionModelContract 使用固定样例测试,不读取笔记或保存草稿。
+func testDecisionModelContract(c *gin.Context, request apicontract.AIDecisionTestRequest) apicontract.Response[apicontract.AIDecisionTestData] {
+ var decision *conf.Decision
+ if request.HasDraft() {
+ if request.Provider == "" || request.Profile == nil {
+ message := "decision draft requires provider and complete profile"
+ return apicontract.Success(apicontract.AIDecisionTestData{Msg: &message})
+ }
+ profile := request.Profile
+ decision = &conf.Decision{Provider: request.Provider, Profiles: map[string]*conf.DecisionProfile{request.Provider: {Endpoint: profile.Endpoint, APIKey: profile.APIKey, Name: profile.Name, Timeout: profile.Timeout}}}
+ } else {
+ settingMutationMu.Lock()
+ if model.Conf.AI != nil {
+ decision = model.Conf.AI.Decision.Clone()
+ }
+ settingMutationMu.Unlock()
+ }
+ options, err := decision.ActiveOptions()
+ if err == nil {
+ _, err = util.EvaluateDecision(c.Request.Context(), options, util.DecisionState{Text: "The sky is blue."}, map[string]util.DecisionQuestion{
+ "sample": {Type: "noul", Instructions: "Does the text mention a color?"},
+ "category": {Type: "choice", Instructions: "What does the text describe?", Criteria: json.RawMessage(`{"sky":"The sky","sea":"The sea"}`)},
+ "rating": {Type: "score", Instructions: "How clearly does the text describe a color?", Criteria: json.RawMessage(`["No color mentioned","A color is explicitly mentioned"]`)},
+ })
}
- _, err := util.EvaluateDecision(c.Request.Context(), util.DecisionOptions{
- Endpoint: decision.Endpoint, APIKey: decision.APIKey, Model: decision.Name, Timeout: decision.Timeout,
- }, util.DecisionState{Text: "The sky is blue."}, map[string]util.DecisionQuestion{
- "sample": {Type: "noul", Instructions: "Does the text mention a color?"},
- })
result := apicontract.AIDecisionTestData{Matched: err == nil}
if err != nil {
message := err.Error()
diff --git a/kernel/api/ai_decision_test.go b/kernel/api/ai_decision_test.go
index 778977379f..8daabebd5d 100644
--- a/kernel/api/ai_decision_test.go
+++ b/kernel/api/ai_decision_test.go
@@ -11,7 +11,9 @@ import (
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestAPIContractAIDecisionConnection(t *testing.T) {
@@ -23,14 +25,14 @@ func TestAPIContractAIDecisionConnection(t *testing.T) {
t.Error("connection test did not use a fixed sample")
}
if calls.Add(1) == 1 {
- io.WriteString(w, `{"model":"jev-test","answers":{"sample":{"type":"noul","noul":0.99}}}`)
+ io.WriteString(w, `{"model":"jev-test","answers":{"sample":{"type":"noul","noul":0.99},"category":{"type":"choice","choice":"sky","probabilities":{"sky":0.99,"sea":0.01},"confidence":0.99},"rating":{"type":"score","score":0.99,"probabilities":{"0":0.01,"1":0.99},"confidence":0.99,"legend":{"0":"No color mentioned","1":"A color is explicitly mentioned"}}}}`)
} else {
io.WriteString(w, `{"answers":{}}`)
}
}))
defer server.Close()
- model.Conf.AI.Decision.Endpoint = server.URL
- model.Conf.AI.Decision.APIKey = "test-key"
+ model.Conf.AI.Decision.Profiles["typesafe"].Endpoint = server.URL
+ model.Conf.AI.Decision.Profiles["typesafe"].APIKey = "test-key"
engine := gin.New()
engine.POST("/api/ai/testDecisionModel", testDecisionModel)
bundle, err := apicontract.BuildBundle()
@@ -58,3 +60,111 @@ func TestAPIContractAIDecisionConnection(t *testing.T) {
t.Fatal("test requires enabled model or retries requests")
}
}
+
+func TestAPIContractAIDecisionDraftIsolation(t *testing.T) {
+ aiContractConfiguration(t)
+ var calls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if r.Header.Get("Authorization") != "Bearer draft-key" {
+ t.Error("draft borrowed saved credentials")
+ }
+ io.WriteString(w, `{"answers":{}}`)
+ }))
+ defer server.Close()
+ saved := model.Conf.AI.Decision
+ saved.Profiles["typesafe"].APIKey = "saved-secret"
+ before, _ := json.Marshal(saved)
+ engine := gin.New()
+ engine.POST("/api/ai/testDecisionModel", testDecisionModel)
+ for _, key := range []string{"", "draft-key"} {
+ payload, _ := json.Marshal(apicontract.AIDecisionTestRequest{Provider: "typesafe", Profile: &apicontract.SettingDecisionProfile{Endpoint: server.URL, APIKey: key, Name: "jev-test", Timeout: 1}})
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/ai/testDecisionModel", strings.NewReader(string(payload))))
+ if strings.Contains(recorder.Body.String(), "saved-secret") || strings.Contains(recorder.Body.String(), "draft-key") {
+ t.Fatal("test leaked credentials")
+ }
+ }
+ for _, body := range []string{`{"provider":"","profile":null}`, `{"profile":null}`, `{"provider":""}`} {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/ai/testDecisionModel", strings.NewReader(body)))
+ if !strings.Contains(recorder.Body.String(), "complete profile") {
+ t.Fatalf("incomplete draft fell back to saved configuration: %s", recorder.Body.String())
+ }
+ }
+ after, _ := json.Marshal(model.Conf.AI.Decision)
+ if string(before) != string(after) || calls.Load() != 1 {
+ t.Fatal("draft saved state or missing draft key borrowed saved key")
+ }
+}
+
+func TestAPIContractSettingDecisionLegacyProjection(t *testing.T) {
+ decision := &conf.Decision{Provider: "openai", Profiles: map[string]*conf.DecisionProfile{
+ "typesafe": {Endpoint: "https://typesafe.example", APIKey: "typesafe-key", Name: "typesafe", Timeout: 30},
+ "openai": {Endpoint: "https://openai.example", APIKey: "openai-key", Name: "openai", Timeout: 60},
+ }}
+ payload := settingDecisionPayload(decision)
+ system, err := systemConfPayload(&model.AppConf{AI: &conf.AI{Decision: decision}})
+ if err != nil || system.AI.Decision.APIKey != "typesafe-key" || system.AI.Decision.Provider != "openai" {
+ t.Fatal("initial configuration lost legacy projection")
+ }
+ if payload.APIKey != "typesafe-key" || payload.Endpoint != "https://typesafe.example" || payload.Provider != "openai" || payload.Profiles["openai"].APIKey != "openai-key" {
+ t.Fatal("legacy projection leaked active profile")
+ }
+}
+
+func TestAPIContractSettingDecisionPartialSave(t *testing.T) {
+ aiContractConfiguration(t)
+ previousReadOnly := util.ReadOnly
+ util.ReadOnly = true
+ t.Cleanup(func() { util.ReadOnly = previousReadOnly })
+ decision := model.Conf.AI.Decision
+ decision.Provider = "openai"
+ decision.Profiles["openai"].APIKey = "openai-key"
+ decision.Profiles["typesafe"].APIKey = "typesafe-key"
+ for _, body := range []string{
+ `{}`,
+ `{"decision":{"enabled":true,"endpoint":"https://legacy.example","apiKey":"legacy-key","name":"legacy","timeout":30}}`,
+ `{"decision":{"enabled":true,"profiles":{"typesafe":{"endpoint":"https://new.example","apiKey":"new-key","name":"new","timeout":40}}}}`,
+ } {
+ code, message, _ := settingContractRequest(t, "setAI", setAI, body)
+ if code != 0 {
+ t.Fatalf("save failed: %s", message)
+ }
+ current := model.Conf.AI.Decision
+ if current.Provider != "openai" || current.Profiles["openai"].APIKey != "openai-key" {
+ t.Fatal("partial save lost provider or unrelated credentials")
+ }
+ }
+ if model.Conf.AI.Decision.Profiles["typesafe"].APIKey != "new-key" {
+ t.Fatal("partial profile was not saved")
+ }
+}
+
+func TestAPIContractSettingDecisionLegacyPatch(t *testing.T) {
+ aiContractConfiguration(t)
+ previousReadOnly := util.ReadOnly
+ util.ReadOnly = true
+ t.Cleanup(func() { util.ReadOnly = previousReadOnly })
+ decision := model.Conf.AI.Decision
+ decision.Provider = "openai"
+ decision.Profiles["openai"].APIKey = "openai-key"
+ for _, body := range []string{
+ `{"ai":{"decision":{"apiKey":"changed-typesafe-key"}}}`,
+ `{"ai":{"decision":{"endpoint":"https://typesafe.example/decision","name":"changed-model","timeout":45}}}`,
+ } {
+ code, message, _ := settingContractRequest(t, "patch", patchSetting, body)
+ if code != 0 {
+ t.Fatalf("legacy patch failed: %s", message)
+ }
+ }
+ decision = model.Conf.AI.Decision
+ profile := decision.Profiles["typesafe"]
+ if decision.Provider != "openai" || decision.Profiles["openai"].APIKey != "openai-key" || profile.APIKey != "changed-typesafe-key" || profile.Endpoint != "https://typesafe.example/decision" || profile.Name != "changed-model" || profile.Timeout != 45 {
+ t.Fatal("legacy patch was lost or changed the active provider")
+ }
+ code, message, _ := settingContractRequest(t, "patch", patchSetting, `{"ai":{"decision":{"apiKey":"stale-projection","profiles":{"typesafe":{"apiKey":"modern-key"}}}}}`)
+ if code != 0 || model.Conf.AI.Decision.Profiles["typesafe"].APIKey != "modern-key" {
+ t.Fatalf("legacy projection overwrote modern patch: %s", message)
+ }
+}
diff --git a/kernel/api/contract_ai_test.go b/kernel/api/contract_ai_test.go
index 3ac5bcfa92..ce15be39cc 100644
--- a/kernel/api/contract_ai_test.go
+++ b/kernel/api/contract_ai_test.go
@@ -137,7 +137,9 @@ func TestAPIContractAIResponses(t *testing.T) {
}{
{"/api/ai/testEmbeddingModel", "ignored", 200, "embedding model not configured"},
{"/api/ai/testRerankModel", "ignored", 200, "rerank model not configured"},
- {"/api/ai/testDecisionModel", "ignored", 200, "decision model not configured"},
+ {"/api/ai/testDecisionModel", "", 200, "decision model not configured"},
+ {"/api/ai/testDecisionModel", `{}`, 200, "decision model not configured"},
+ {"/api/ai/testDecisionModel", "ignored", 200, "invalid character"},
{"/api/ai/agent/confirm", `{"confirmID":"expired"}`, 409, "agent confirmation expired"},
{"/api/ai/agent/question", `{"questionID":"expired"}`, 409, "agent question expired"},
{"/api/ai/agent/browserCapabilityResult", `{"callID":"expired","structuredContent":{"nested":[1,true,null]}}`, 409, "agent browser capability call expired"},
diff --git a/kernel/api/contract_setting_test.go b/kernel/api/contract_setting_test.go
index 5384ecfb1e..9041654542 100644
--- a/kernel/api/contract_setting_test.go
+++ b/kernel/api/contract_setting_test.go
@@ -266,11 +266,33 @@ func compareSettingPayload[Source, Data any](t *testing.T, route string, convert
if err != nil {
t.Fatal(err)
}
+ // Decision 的旧字段只在响应中投影,持久化配置不重复存储凭证。
+ if ai, ok := any(source).(*conf.AI); ok && ai.Decision != nil {
+ var expected map[string]json.RawMessage
+ if err = json.Unmarshal(before, &expected); err != nil {
+ t.Fatal(err)
+ }
+ expected["decision"], err = json.Marshal(settingDecisionPayload(ai.Decision))
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, err = json.Marshal(expected)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
after, err := json.Marshal(convert(source))
if err != nil {
t.Fatal(err)
}
- if string(before) != string(after) {
+ var beforeValue, afterValue any
+ if err = json.Unmarshal(before, &beforeValue); err != nil {
+ t.Fatal(err)
+ }
+ if err = json.Unmarshal(after, &afterValue); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(beforeValue, afterValue) {
t.Fatalf("%s response mapping changed:\n%s\n%s", route, before, after)
}
if route == "" {
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index c9bc239d95..3b01759f9d 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -185,6 +185,13 @@ func applyAISetting(c *gin.Context, request apicontract.SetAIRequest) (ret apico
ret = apicontract.Failure[*apicontract.SettingAI](-1, err.Error())
return
}
+ if model.Conf.AI != nil {
+ if ai.Decision == nil {
+ ai.Decision = model.Conf.AI.Decision.Clone()
+ } else {
+ ai.Decision.MergePrevious(model.Conf.AI.Decision)
+ }
+ }
if ai.MCP != nil {
for _, server := range ai.MCP.Servers {
if err = mcpclient.ValidateMCPServerEnvironment(server); err != nil {
diff --git a/kernel/api/setting_contract.go b/kernel/api/setting_contract.go
index a68017ad0e..400e4847d8 100644
--- a/kernel/api/setting_contract.go
+++ b/kernel/api/setting_contract.go
@@ -129,8 +129,22 @@ func settingDecisionPayload(value *conf.Decision) *apicontract.SettingDecision {
if value == nil {
return nil
}
- return &apicontract.SettingDecision{Enabled: value.Enabled, Endpoint: value.Endpoint,
- APIKey: value.APIKey, Name: value.Name, Timeout: value.Timeout}
+ result := &apicontract.SettingDecision{Enabled: value.Enabled, Provider: value.Provider, Endpoint: value.Endpoint, APIKey: value.APIKey, Name: value.Name, Timeout: value.Timeout}
+ if value.Profiles != nil {
+ result.Profiles = map[string]*apicontract.SettingDecisionProfile{}
+ }
+ for provider, profile := range value.Profiles {
+ if profile == nil {
+ result.Profiles[provider] = nil
+ } else {
+ result.Profiles[provider] = &apicontract.SettingDecisionProfile{Endpoint: profile.Endpoint, APIKey: profile.APIKey, Name: profile.Name, Timeout: profile.Timeout}
+ }
+ }
+ // 旧客户端兼容字段固定投影 TypeSafe,不能投影当前供应商的凭证。
+ if profile := value.Profiles["typesafe"]; profile != nil {
+ result.Endpoint, result.APIKey, result.Name, result.Timeout = profile.Endpoint, profile.APIKey, profile.Name, profile.Timeout
+ }
+ return result
}
func settingAgentPayload(value *conf.Agent) *apicontract.SettingAgent {
diff --git a/kernel/api/setting_patch.go b/kernel/api/setting_patch.go
index 22a681a91f..8164f160f0 100644
--- a/kernel/api/setting_patch.go
+++ b/kernel/api/setting_patch.go
@@ -129,6 +129,48 @@ func mergeSettingJSON(base, patch []byte) ([]byte, error) {
return json.Marshal(current)
}
+// migrateDecisionSettingPatch 在合并前识别旧客户端的平铺字段,避免被现有 profiles 遮蔽。
+func migrateDecisionSettingPatch(patch []byte) ([]byte, error) {
+ var ai map[string]json.RawMessage
+ if err := json.Unmarshal(patch, &ai); err != nil {
+ return nil, err
+ }
+ var decision map[string]json.RawMessage
+ if json.Unmarshal(ai["decision"], &decision) != nil || decision == nil {
+ return patch, nil
+ }
+ if _, modern := decision["profiles"]; modern {
+ return patch, nil
+ }
+ profile := map[string]json.RawMessage{}
+ for _, field := range []string{"endpoint", "apiKey", "name", "timeout"} {
+ if value, exists := decision[field]; exists {
+ // 旧设置字段允许 null,保持清空密钥和恢复默认参数的既有语义。
+ if bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
+ value = json.RawMessage(`""`)
+ if field == "timeout" {
+ value = json.RawMessage(`0`)
+ }
+ }
+ profile[field] = value
+ delete(decision, field)
+ }
+ }
+ if len(profile) == 0 {
+ return patch, nil
+ }
+ profiles, err := json.Marshal(map[string]map[string]json.RawMessage{"typesafe": profile})
+ if err != nil {
+ return nil, err
+ }
+ decision["profiles"] = profiles
+ ai["decision"], err = json.Marshal(decision)
+ if err != nil {
+ return nil, err
+ }
+ return json.Marshal(ai)
+}
+
func applySettingPatch[Request, Data, Config any](c *gin.Context, patch []byte, config Config,
endpoint apicontract.Endpoint[Request, Data], apply func(*gin.Context, Request) apicontract.Response[Data]) apicontract.Response[apicontract.Null] {
base, err := json.Marshal(config)
@@ -181,6 +223,11 @@ var patchSetting = contractHandler(apicontract.PatchSetting, func(c *gin.Context
if util.IsDisabledFeature("ai") {
return apicontract.Failure[apicontract.Null](-1, util.I18nTerm(model.Conf.Lang, "agentCapabilitiesUnavailable"))
}
+ var err error
+ patch, err = migrateDecisionSettingPatch(patch)
+ if err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
response = applySettingPatch(c, patch, model.Conf.AI, apicontract.SetAI, applyAISetting)
default:
return apicontract.Failure[apicontract.Null](-1, fmt.Sprintf("unsupported settings namespace: %s", request.Namespace()))
diff --git a/kernel/api/system.go b/kernel/api/system.go
index fcbed0f10b..4487adebae 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -542,6 +542,11 @@ var exportConf = contractHandler(apicontract.SystemExportConf, func(c *gin.Conte
}
if nil != clonedConf.AI.Decision {
clonedConf.AI.Decision.APIKey = ""
+ for _, profile := range clonedConf.AI.Decision.Profiles {
+ if profile != nil {
+ profile.APIKey = ""
+ }
+ }
}
clonedConf.AI.MCP = nil
}
diff --git a/kernel/api/system_contract.go b/kernel/api/system_contract.go
index e5bc3b9993..90d264121f 100644
--- a/kernel/api/system_contract.go
+++ b/kernel/api/system_contract.go
@@ -17,6 +17,9 @@ func systemConfPayload(value *model.AppConf) (result *apicontract.SystemAppConf,
if err == nil {
err = json.Unmarshal(encoded, &result)
}
+ if err == nil && result != nil && value.AI != nil && result.AI != nil {
+ result.AI.Decision = settingDecisionPayload(value.AI.Decision)
+ }
return
}
diff --git a/kernel/api/system_export_secrets_test.go b/kernel/api/system_export_secrets_test.go
index e7b07c4187..2aa2c37540 100644
--- a/kernel/api/system_export_secrets_test.go
+++ b/kernel/api/system_export_secrets_test.go
@@ -23,7 +23,8 @@ func TestAPIContractSystemExportSecrets(t *testing.T) {
model.Conf = model.NewAppConf()
if populated {
model.Conf.AI = conf.NewAI()
- model.Conf.AI.Decision.APIKey = "export-test-decision-secret"
+ model.Conf.AI.Decision.Profiles["typesafe"].APIKey = "export-test-decision-secret"
+ model.Conf.AI.Decision.Profiles["openai"].APIKey = "export-test-openai-secret"
model.Conf.OIDC = conf.NewOIDC()
model.Conf.OIDC.ClientID = "test-client"
model.Conf.OIDC.ClientSecret = "export-test-oidc-secret"
@@ -65,11 +66,11 @@ func TestAPIContractSystemExportSecrets(t *testing.T) {
t.Fatal(err)
}
if populated {
- if exported.AI.Decision.APIKey != "" || exported.OIDC.ClientSecret != "" ||
+ if exported.AI.Decision.APIKey != "" || exported.AI.Decision.Profiles["typesafe"].APIKey != "" || exported.AI.Decision.Profiles["openai"].APIKey != "" || exported.OIDC.ClientSecret != "" ||
bytes.Contains(data, []byte("export-test-")) {
t.Fatal("export retained secrets")
}
- if exported.AI.Decision.Name != model.Conf.AI.Decision.Name || exported.OIDC.ClientID != "test-client" {
+ if exported.AI.Decision.Profiles["typesafe"].Name != model.Conf.AI.Decision.Profiles["typesafe"].Name || exported.OIDC.ClientID != "test-client" {
t.Fatal("export lost non-secret settings")
}
}
diff --git a/kernel/apicontract/ai.go b/kernel/apicontract/ai.go
index caf006fb78..1c61e308fa 100644
--- a/kernel/apicontract/ai.go
+++ b/kernel/apicontract/ai.go
@@ -218,3 +218,16 @@ type AISkillData struct {
Name string `json:"name"`
Content string `json:"content"`
}
+
+// AIDecisionTestRequest 使用固定三类问题测试完整草稿,不保存、不读笔记,也不借用已保存的凭证。
+// 空请求或未提供草稿字段的对象测试已保存配置;提供任一草稿字段即要求完整配置。
+// 损坏的 JSON 和尾随内容返回错误,不回退到已保存配置,测试可能产生供应商费用。
+type AIDecisionTestRequest struct {
+ Provider string `json:"provider" api:"optional"`
+ Profile *SettingDecisionProfile `json:"profile" api:"optional"`
+ draft bool
+}
+
+func (request AIDecisionTestRequest) HasDraft() bool {
+ return request.draft || request.Provider != "" || request.Profile != nil
+}
diff --git a/kernel/apicontract/ai_decision_test.go b/kernel/apicontract/ai_decision_test.go
new file mode 100644
index 0000000000..5d830b4a3e
--- /dev/null
+++ b/kernel/apicontract/ai_decision_test.go
@@ -0,0 +1,24 @@
+package apicontract
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestAIDecisionDraftDecode(t *testing.T) {
+ for _, body := range []string{"", " ", `{}`, `{"text":"ignored-note"}`} {
+ request, err := AITestDecisionModel.Decode(strings.NewReader(body))
+ if err != nil || request.Provider != "" || request.Profile != nil {
+ t.Fatalf("legacy saved-configuration test rejected: %q %v", body, err)
+ }
+ }
+ for _, body := range []string{`{`, `{}garbage`, `{} {"provider":"openai"}`, `{"provider":42}`, `{"provider":"openai","profile":{"endpoint":"https://example.com"}}`} {
+ if _, err := AITestDecisionModel.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("invalid draft accepted: %q", body)
+ }
+ }
+ request, err := AITestDecisionModel.Decode(strings.NewReader(`{"provider":"openai","profile":{"endpoint":"https://example.com","apiKey":"key","name":"model","timeout":30}}`))
+ if err != nil || request.Profile == nil || request.Profile.APIKey != "key" || request.Provider != "openai" {
+ t.Fatalf("complete draft rejected: %+v %v", request, err)
+ }
+}
diff --git a/kernel/apicontract/ai_input.go b/kernel/apicontract/ai_input.go
index 4921185d1f..daa9d5b502 100644
--- a/kernel/apicontract/ai_input.go
+++ b/kernel/apicontract/ai_input.go
@@ -3,6 +3,7 @@ package apicontract
import (
"bytes"
"encoding/json"
+ "errors"
"fmt"
"io"
"reflect"
@@ -61,6 +62,26 @@ func aiProviderFields(fields fileTreeFields) AIProviderRequest {
}
func init() {
+ // 空请求兼容已保存配置测试;草稿仍使用契约字段校验,不能吞掉损坏的 JSON。
+ AITestDecisionModel.decodeRequest = func(reader io.Reader) (request AIDecisionTestRequest, err error) {
+ var fields map[string]json.RawMessage
+ decoder := json.NewDecoder(reader)
+ if err = decoder.Decode(&fields); err != nil {
+ if errors.Is(err, io.EOF) {
+ return request, nil
+ }
+ return request, err
+ }
+ var trailing json.RawMessage
+ if err = decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
+ return request, errors.New("decision test requires a single JSON object")
+ }
+ _, providerPresent := fields["provider"]
+ _, profilePresent := fields["profile"]
+ request.draft = providerPresent || profilePresent
+ err = decodeRequestFields(reflect.ValueOf(&request).Elem(), fields)
+ return
+ }
aiStructDecoder(&AIEditorChat, "aiEditorChatReq")
aiStructDecoder(&AIAgentChat, "agentChatReq")
aiStructDecoder(&AIGetSession, "agentSessionGetReq")
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 103dae0e31..ce752e8e5d 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1005,7 +1005,7 @@ var AIRemoveEditorAction = define[AIEditorActionIDRequest, Null]("removeAIEditor
var AITestModel = define[AIModelRequest, AIModelTestData]("testModel", "/api/ai/testModel", JSONBody, ResponseOptions{}, "POST")
var AITestEmbeddingModel = define[EmptyRequest, AIEmbeddingTestData]("testEmbeddingModel", "/api/ai/testEmbeddingModel", NoBody, ResponseOptions{}, "POST")
var AITestRerankModel = define[EmptyRequest, AIRerankTestData]("testRerankModel", "/api/ai/testRerankModel", NoBody, ResponseOptions{}, "POST")
-var AITestDecisionModel = define[EmptyRequest, AIDecisionTestData]("testDecisionModel", "/api/ai/testDecisionModel", NoBody, ResponseOptions{}, "POST")
+var AITestDecisionModel = define[AIDecisionTestRequest, AIDecisionTestData]("testDecisionModel", "/api/ai/testDecisionModel", JSONBody, ResponseOptions{}, "POST")
var AIListModels = define[AIProviderRequest, AIModelsData]("listModels", "/api/ai/listModels", JSONBody, ResponseOptions{}, "POST")
// 套餐授权接口仅供已鉴权管理员使用,遵守 AI 禁用开关及只读限制。
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index afa6fffffb..2c131937dc 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -833,6 +833,25 @@
],
"additionalProperties": false
},
+ "AIDecisionTestRequestInput": {
+ "type": "object",
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SettingDecisionProfileInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "provider": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ },
"AIEditorAction": {
"type": "object",
"properties": {
@@ -42972,6 +42991,29 @@
"name": {
"type": "string"
},
+ "profiles": {
+ "anyOf": [
+ {
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SettingDecisionProfile"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "provider": {
+ "type": "string"
+ },
"timeout": {
"type": "integer"
}
@@ -42981,6 +43023,8 @@
"enabled",
"endpoint",
"name",
+ "profiles",
+ "provider",
"timeout"
],
"additionalProperties": false
@@ -43028,6 +43072,36 @@
}
]
},
+ "profiles": {
+ "anyOf": [
+ {
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SettingDecisionProfileInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "provider": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"timeout": {
"anyOf": [
{
@@ -43041,6 +43115,54 @@
},
"additionalProperties": false
},
+ "SettingDecisionProfile": {
+ "type": "object",
+ "properties": {
+ "apiKey": {
+ "type": "string"
+ },
+ "endpoint": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "timeout": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "apiKey",
+ "endpoint",
+ "name",
+ "timeout"
+ ],
+ "additionalProperties": false
+ },
+ "SettingDecisionProfileInput": {
+ "type": "object",
+ "properties": {
+ "apiKey": {
+ "type": "string"
+ },
+ "endpoint": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "timeout": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "apiKey",
+ "endpoint",
+ "name",
+ "timeout"
+ ],
+ "additionalProperties": false
+ },
"SettingEditing": {
"type": "object",
"properties": {
@@ -120995,9 +121117,9 @@
"method": "POST",
"path": "/api/ai/testDecisionModel",
"handler": "testDecisionModel",
- "body": "none",
+ "body": "json",
"request": {
- "$ref": "#/$defs/EmptyRequestInput"
+ "$ref": "#/$defs/AIDecisionTestRequestInput"
},
"response": {
"anyOf": [
diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.go
index c043120866..d0e8524597 100644
--- a/kernel/apicontract/setting.go
+++ b/kernel/apicontract/setting.go
@@ -69,11 +69,20 @@ type SettingRerank struct {
}
type SettingDecision struct {
- Enabled bool `json:"enabled" api:"optional,nullable"`
- Endpoint string `json:"endpoint" api:"optional,nullable"`
- APIKey string `json:"apiKey" api:"optional,nullable"`
- Name string `json:"name" api:"optional,nullable"`
- Timeout int `json:"timeout" api:"optional,nullable"`
+ Enabled bool `json:"enabled" api:"optional,nullable"`
+ Provider string `json:"provider" api:"optional,nullable"`
+ Profiles map[string]*SettingDecisionProfile `json:"profiles" api:"optional,nullable"`
+ Endpoint string `json:"endpoint" api:"optional,nullable"`
+ APIKey string `json:"apiKey" api:"optional,nullable"`
+ Name string `json:"name" api:"optional,nullable"`
+ Timeout int `json:"timeout" api:"optional,nullable"`
+}
+
+type SettingDecisionProfile struct {
+ Endpoint string `json:"endpoint"`
+ APIKey string `json:"apiKey"`
+ Name string `json:"name"`
+ Timeout int `json:"timeout"`
}
type SettingAgent struct {
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index 35759ff1db..3da1e7f0fd 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -19,6 +19,7 @@ package conf
import (
"encoding/hex"
"encoding/json"
+ "fmt"
"net/url"
"os"
"strconv"
@@ -117,21 +118,136 @@ type Embedding struct {
Dimensions int `json:"dimensions"` // 输出向量维度,仅 text-embedding-3 及以上模型支持;0 表示用模型默认值(不传该参数)
}
-// Decision 配置智能体使用的 TypeSafe System One 决策模型。
+// Decision 按供应商隔离凭证,平铺字段仅用于兼容旧配置输入。
type Decision struct {
- Enabled bool `json:"enabled"`
+ Enabled bool `json:"enabled"`
+ Provider string `json:"provider"`
+ Profiles map[string]*DecisionProfile `json:"profiles"`
+ Endpoint string `json:"endpoint,omitempty"`
+ APIKey string `json:"apiKey,omitempty"`
+ Name string `json:"name,omitempty"`
+ Timeout int `json:"timeout,omitempty"`
+}
+
+type DecisionProfile struct {
Endpoint string `json:"endpoint"`
APIKey string `json:"apiKey"`
Name string `json:"name"`
Timeout int `json:"timeout"`
}
-func (decision *Decision) Configured() bool {
- return decision != nil && decision.Endpoint != "" && decision.APIKey != "" && decision.Name != ""
+func (decision *Decision) ActiveOptions() (util.DecisionOptions, error) {
+ if decision == nil {
+ return util.DecisionOptions{}, fmt.Errorf("decision model not configured")
+ }
+ provider := strings.TrimSpace(decision.Provider)
+ if provider == "" {
+ provider = "typesafe"
+ }
+ if provider != "typesafe" && provider != "openai" {
+ return util.DecisionOptions{}, fmt.Errorf("unknown decision provider")
+ }
+ profile := decision.Profiles[provider]
+ if decision.Profiles == nil && provider == "typesafe" {
+ profile = &DecisionProfile{decision.Endpoint, decision.APIKey, decision.Name, decision.Timeout}
+ }
+ if profile == nil || profile.Endpoint == "" || profile.APIKey == "" || profile.Name == "" {
+ return util.DecisionOptions{}, fmt.Errorf("decision model not configured")
+ }
+ return util.DecisionOptions{Provider: provider, Endpoint: profile.Endpoint, APIKey: profile.APIKey, Model: profile.Name, Timeout: profile.Timeout}, nil
+}
+
+func (decision *Decision) Configured() bool { _, err := decision.ActiveOptions(); return err == nil }
+
+func defaultDecisionProfile(provider string) *DecisionProfile {
+ if provider == "openai" {
+ return &DecisionProfile{Endpoint: "https://api.openai.com/v1/decisions", Name: "gpt-6-luna", Timeout: 30}
+ }
+ return &DecisionProfile{Endpoint: "https://api.typesafe.ai/v1/systemone", Name: "jev-latest", Timeout: 30}
}
func defaultDecision() *Decision {
- return &Decision{Endpoint: "https://api.typesafe.ai/v1/systemone", Name: "jev-latest", Timeout: 30}
+ return &Decision{Provider: "typesafe", Profiles: map[string]*DecisionProfile{"typesafe": defaultDecisionProfile("typesafe"), "openai": defaultDecisionProfile("openai")}}
+}
+
+func (decision *Decision) Normalize() {
+ decision.Provider = strings.TrimSpace(decision.Provider)
+ if decision.Provider == "" {
+ decision.Provider = "typesafe"
+ }
+ if decision.Profiles == nil {
+ decision.Profiles = map[string]*DecisionProfile{"typesafe": {Endpoint: decision.Endpoint, APIKey: decision.APIKey, Name: decision.Name, Timeout: decision.Timeout}}
+ }
+ for _, provider := range []string{"typesafe", "openai"} {
+ profile := decision.Profiles[provider]
+ defaults := defaultDecisionProfile(provider)
+ if profile == nil {
+ profile = defaults
+ decision.Profiles[provider] = profile
+ }
+ profile.Endpoint = strings.TrimSpace(profile.Endpoint)
+ profile.APIKey = strings.TrimSpace(profile.APIKey)
+ profile.Name = strings.TrimSpace(profile.Name)
+ if profile.Endpoint == "" {
+ profile.Endpoint = defaults.Endpoint
+ }
+ if profile.Name == "" {
+ profile.Name = defaults.Name
+ }
+ if profile.Timeout < 1 {
+ profile.Timeout = 30
+ } else if profile.Timeout > 600 {
+ profile.Timeout = 600
+ }
+ }
+ decision.Endpoint, decision.APIKey, decision.Name, decision.Timeout = "", "", "", 0
+}
+
+// MergePrevious 合并旧客户端输入或单个供应商更新,保留其他配置和活动供应商。
+func (decision *Decision) MergePrevious(previous *Decision) {
+ if previous == nil {
+ return
+ }
+ old := previous.Clone()
+ old.Normalize()
+ if decision.Profiles == nil {
+ old.Enabled = decision.Enabled
+ if decision.Provider != "" {
+ old.Provider = decision.Provider
+ }
+ if decision.Endpoint != "" || decision.APIKey != "" || decision.Name != "" || decision.Timeout != 0 {
+ old.Profiles["typesafe"] = &DecisionProfile{decision.Endpoint, decision.APIKey, decision.Name, decision.Timeout}
+ }
+ *decision = *old
+ return
+ }
+ if strings.TrimSpace(decision.Provider) == "" {
+ decision.Provider = old.Provider
+ }
+ for provider, profile := range old.Profiles {
+ if _, exists := decision.Profiles[provider]; !exists {
+ decision.Profiles[provider] = profile
+ }
+ }
+}
+
+func (decision *Decision) Clone() *Decision {
+ if decision == nil {
+ return nil
+ }
+ result := *decision
+ if decision.Profiles != nil {
+ result.Profiles = make(map[string]*DecisionProfile, len(decision.Profiles))
+ for id, profile := range decision.Profiles {
+ if profile != nil {
+ copy := *profile
+ result.Profiles[id] = &copy
+ } else {
+ result.Profiles[id] = nil
+ }
+ }
+ }
+ return &result
}
// Rerank 配置语义搜索结果的重排模型。重排在向量召回后对 query 与候选文档逐对精排,
@@ -693,20 +809,7 @@ func (ai *AI) Normalize() {
if ai.Decision == nil {
ai.Decision = defaultDecision()
}
- ai.Decision.Endpoint = strings.TrimSpace(ai.Decision.Endpoint)
- ai.Decision.APIKey = strings.TrimSpace(ai.Decision.APIKey)
- ai.Decision.Name = strings.TrimSpace(ai.Decision.Name)
- if ai.Decision.Endpoint == "" {
- ai.Decision.Endpoint = defaultDecision().Endpoint
- }
- if ai.Decision.Name == "" {
- ai.Decision.Name = defaultDecision().Name
- }
- if ai.Decision.Timeout < 1 {
- ai.Decision.Timeout = 30
- } else if ai.Decision.Timeout > 600 {
- ai.Decision.Timeout = 600
- }
+ ai.Decision.Normalize()
if ai.Rerank.Timeout < 1 {
ai.Rerank.Timeout = 30
}
@@ -784,13 +887,24 @@ func normalizeApprovalPolicy(policy *ApprovalPolicy) {
}
func (ai *AI) DecryptAPIKeys() {
- if ai.Decision != nil && ai.Decision.APIKey != "" {
- if dec := util.AESDecrypt(ai.Decision.APIKey); dec != nil {
- if plain, err := hex.DecodeString(string(dec)); err == nil {
- ai.Decision.APIKey = string(plain)
+ if ai.Decision != nil {
+ decrypt := func(key *string) {
+ if *key != "" {
+ if dec := util.AESDecrypt(*key); dec != nil {
+ if plain, err := hex.DecodeString(string(dec)); err == nil {
+ *key = string(plain)
+ }
+ }
+ }
+ }
+ decrypt(&ai.Decision.APIKey)
+ for _, profile := range ai.Decision.Profiles {
+ if profile != nil {
+ decrypt(&profile.APIKey)
}
}
}
+
for _, p := range ai.Providers {
if p == nil || p.APIKey == "" {
continue
@@ -824,9 +938,15 @@ func (ai *AI) DecryptAPIKeys() {
}
func (ai *AI) EncryptAPIKeys() {
- if ai.Decision != nil && ai.Decision.APIKey != "" {
- ai.Decision.APIKey = util.AESEncrypt(ai.Decision.APIKey)
+ if ai.Decision != nil {
+ ai.Decision.Normalize()
+ for _, profile := range ai.Decision.Profiles {
+ if profile != nil && profile.APIKey != "" {
+ profile.APIKey = util.AESEncrypt(profile.APIKey)
+ }
+ }
}
+
for _, p := range ai.Providers {
if p == nil || p.APIKey == "" {
continue
diff --git a/kernel/conf/ai_decision_test.go b/kernel/conf/ai_decision_test.go
index fb6b87b25d..72f4436f1c 100644
--- a/kernel/conf/ai_decision_test.go
+++ b/kernel/conf/ai_decision_test.go
@@ -1,25 +1,62 @@
package conf
-import "testing"
+import (
+ "encoding/json"
+ "testing"
+)
func TestAIDecisionConfiguration(t *testing.T) {
- ai := &AI{}
+ ai := &AI{Decision: &Decision{Enabled: true, Endpoint: " https://example.com/decision ", APIKey: "legacy-key", Name: "legacy-model", Timeout: 900}}
ai.Normalize()
- if ai.Decision.Enabled || ai.Decision.Timeout != 30 || ai.Decision.Name != "jev-latest" || ai.Decision.Endpoint != "https://api.typesafe.ai/v1/systemone" {
- t.Fatalf("incorrect defaults: %+v", ai.Decision)
+ if ai.Decision.Provider != "typesafe" || !ai.Decision.Configured() || ai.Decision.Profiles["typesafe"].Timeout != 600 || !ai.Decision.Enabled {
+ t.Fatal("legacy migration failed")
}
- ai.Decision.APIKey = "test-decision-key"
- ai.Decision.Timeout = 900
- ai.Normalize()
- if !ai.Decision.Configured() || ai.Decision.Timeout != 600 {
- t.Fatal("decision normalization failed")
+ if ai.Decision.APIKey != "" || ai.Decision.Profiles["openai"].APIKey != "" {
+ t.Fatal("legacy credentials duplicated or leaked")
}
+ ai.Decision.Profiles["openai"].APIKey = "openai-key"
+ ai.Decision.Provider = "openai"
+ ai.Normalize()
ai.EncryptAPIKeys()
- if ai.Decision.APIKey == "test-decision-key" || ai.Decision.APIKey == "" {
- t.Fatal("decision key not encrypted")
+ if ai.Decision.Profiles["typesafe"].APIKey == "legacy-key" || ai.Decision.Profiles["openai"].APIKey == "openai-key" {
+ t.Fatal("both profiles must be encrypted")
+ }
+ data, err := json.Marshal(ai)
+ if err != nil {
+ t.Fatal(err)
+ }
+ restored := &AI{}
+ if err = json.Unmarshal(data, restored); err != nil {
+ t.Fatal(err)
+ }
+ restored.DecryptAPIKeys()
+ restored.Normalize()
+ if restored.Decision.Profiles["typesafe"].APIKey != "legacy-key" || restored.Decision.Profiles["openai"].APIKey != "openai-key" || restored.Decision.Provider != "openai" {
+ t.Fatal("profile round trip failed")
+ }
+ restored.Decision.Provider = "unknown"
+ if restored.Decision.Configured() {
+ t.Fatal("unknown provider silently accepted")
+ }
+}
+
+func TestAIDecisionMergeLegacy(t *testing.T) {
+ previous := defaultDecision()
+ previous.Provider = "openai"
+ previous.Profiles["openai"].APIKey = "openai-key"
+ legacy := &Decision{Enabled: true, Endpoint: "https://legacy.example", APIKey: "typesafe-key", Name: "legacy", Timeout: 45}
+ legacy.MergePrevious(previous)
+ legacy.Normalize()
+ if legacy.Provider != "openai" || legacy.Profiles["openai"].APIKey != "openai-key" || legacy.Profiles["typesafe"].APIKey != "typesafe-key" {
+ t.Fatal("legacy save lost active provider or credentials")
+ }
+ legacy.Profiles["openai"].APIKey = ""
+ if previous.Profiles["openai"].APIKey != "openai-key" {
+ t.Fatal("merge aliases previous config")
}
- ai.DecryptAPIKeys()
- if ai.Decision.APIKey != "test-decision-key" || ai.Decision.Enabled {
- t.Fatal("disabled decision configuration was not preserved")
+ legacy.APIKey = "stale-flat-key"
+ legacy.Normalize()
+ if legacy.Profiles["typesafe"].APIKey != "typesafe-key" {
+ t.Fatal("stale flat config replaced profile")
}
}
diff --git a/kernel/mcp/tools/decision.go b/kernel/mcp/tools/decision.go
index a0f8f7ab3c..ba1d7e001c 100644
--- a/kernel/mcp/tools/decision.go
+++ b/kernel/mcp/tools/decision.go
@@ -42,7 +42,7 @@ type decisionItemResult struct {
var DecisionTool = &Tool{
Name: "decision",
- Description: "Classify, filter, choose or score content using the configured TypeSafe System One decision model. Submit 1-32 independent items evaluated sequentially with shared questions. Use blockIDs (full Markdown, no truncation), optionally notebook for encrypted blocks, or text. For comparative choices put all related blocks in one item. Maximum 255 choices or 2-10 score levels. Noul returns P(yes), not a boolean. Stops on first failure; returns completed, error and not_run items. Sends content externally and may incur charges.",
+ Description: "Classify, filter, choose or score content using the configured decision provider. Submit 1-32 independent items evaluated sequentially with shared questions. Use blockIDs (full Markdown, no truncation), optionally notebook for encrypted blocks, or text. For comparative choices put all related blocks in one item. Maximum 255 choices or 2-10 score levels. Noul returns P(yes), not a boolean. Stops on first failure; returns completed, error and not_run items. Sends content externally and may incur charges.",
AgentOnly: true,
Available: decisionAvailable,
ReadOnlyHint: true,
@@ -86,8 +86,14 @@ func init() {
}
func decisionAvailable() bool {
+ return decisionEnabled() && model.Conf.AI.Decision.Configured()
+}
+
+// decisionEnabled 不读取活动供应商配置,已开始的批次使用独立的配置快照。
+func decisionEnabled() bool {
return !util.IsDisabledFeature("ai") && model.Conf != nil && model.Conf.AI != nil &&
- model.Conf.AI.Decision.Configured() && model.Conf.AI.Decision.Enabled
+ model.Conf.AI.Decision != nil && model.Conf.AI.Decision.Enabled &&
+ (model.Conf.AI.Agent == nil || model.Conf.AI.Agent.CapabilityPolicy.Allows("native/backend/decision"))
}
func decisionBoxLeases(args map[string]any) []string {
@@ -126,16 +132,18 @@ func decisionHandler(ctx context.Context, args map[string]any) (CallToolResult,
return blockToolError("encrypted notebook is locked, please unlock it first")
}
defer release()
- config := *model.Conf.AI.Decision
- options := util.DecisionOptions{Endpoint: config.Endpoint, APIKey: config.APIKey, Model: config.Name, Timeout: config.Timeout}
+ options, err := model.Conf.AI.Decision.ActiveOptions()
+ if err != nil {
+ return blockToolError(err.Error())
+ }
results := make([]decisionItemResult, 0, len(input.Items))
failed := false
for _, item := range input.Items {
entry := decisionItemResult{ID: item.ID, Status: "not_run"}
if !failed {
state, stateErr := decisionItemState(ctx, item, input.Context)
- if stateErr == nil && !decisionAvailable() {
- stateErr = errors.New("decision model is disabled or not configured")
+ if stateErr == nil && !decisionEnabled() {
+ stateErr = errors.New("decision model is disabled or not permitted")
}
if stateErr == nil {
entry.Result, stateErr = util.EvaluateDecision(ctx, options, state, questions)
diff --git a/kernel/mcp/tools/decision_test.go b/kernel/mcp/tools/decision_test.go
index fb5892e11e..4f052eebdf 100644
--- a/kernel/mcp/tools/decision_test.go
+++ b/kernel/mcp/tools/decision_test.go
@@ -103,6 +103,80 @@ func TestDecisionRejectsInvalidBatchBeforeRequest(t *testing.T) {
}
}
+func TestDecisionBatchProviderSnapshotAndDisable(t *testing.T) {
+ for _, change := range []string{"switch", "edit", "disable", "deny"} {
+ t.Run(change, func(t *testing.T) {
+ var calls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer test-key" {
+ t.Error("batch mixed provider credentials")
+ }
+ if calls.Add(1) == 1 {
+ switch change {
+ case "switch":
+ model.Conf.AI.Decision.Provider = "openai"
+ case "edit":
+ model.Conf.AI.Decision.Profiles["typesafe"].APIKey = "changed-key"
+ model.Conf.AI.Decision.Profiles["typesafe"].Endpoint = "http://unused.invalid"
+ case "disable":
+ model.Conf.AI.Decision.Enabled = false
+ case "deny":
+ model.Conf.AI.Agent.CapabilityPolicy.Overrides["native/backend/decision"] = "deny"
+ }
+ }
+ io.WriteString(w, `{"model":"jev-test","answers":{"q":{"type":"noul","noul":0.1}}}`)
+ }))
+ defer server.Close()
+ configureDecisionTest(t, server.URL)
+ model.Conf.AI.Decision.Normalize()
+ result, err := decisionHandler(context.Background(), decisionArgs(t, `{"action":"evaluate","items":[{"id":"a","text":"first"},{"id":"b","text":"second"},{"id":"c","text":"third"}],"questions":[{"id":"q","type":"noul","instructions":"Relevant?"}]}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var batch struct {
+ Items []decisionItemResult `json:"items"`
+ }
+ if err = json.Unmarshal([]byte(result.Content[0].Text), &batch); err != nil {
+ t.Fatal(err)
+ }
+ if change == "disable" || change == "deny" {
+ if calls.Load() != 1 || !result.IsError || batch.Items[0].Status != "completed" || batch.Items[1].Status != "error" || batch.Items[2].Status != "not_run" {
+ t.Fatalf("disabled batch continued: %+v calls=%d", batch, calls.Load())
+ }
+ } else if calls.Load() != 3 || result.IsError || batch.Items[2].Status != "completed" {
+ t.Fatalf("batch abandoned snapshot after profile change: %+v calls=%d", batch, calls.Load())
+ }
+ })
+ }
+}
+
+func TestDecisionOpenAIRefusalStopsBatch(t *testing.T) {
+ var calls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if calls.Add(1) == 1 {
+ io.WriteString(w, `{"model":"gpt-6-luna","answers":[{"name":"q","type":"predicate","probability":0.2}],"usage":{"input_tokens":12,"output_tokens":0}}`)
+ } else {
+ io.WriteString(w, `{"model":"gpt-6-luna","answers":[{"name":"q","type":"refusal"}],"usage":{"input_tokens":12,"output_tokens":0}}`)
+ }
+ }))
+ defer server.Close()
+ configureDecisionTest(t, server.URL)
+ model.Conf.AI.Decision = &conf.Decision{Enabled: true, Provider: "openai", Profiles: map[string]*conf.DecisionProfile{"openai": {Endpoint: server.URL, APIKey: "key", Name: "gpt-6-luna", Timeout: 1}}}
+ result, err := decisionHandler(context.Background(), decisionArgs(t, `{"action":"evaluate","items":[{"id":"a","text":"first"},{"id":"b","text":"second"},{"id":"c","text":"third"}],"questions":[{"id":"q","type":"noul","instructions":"Relevant?"}]}`))
+ if err != nil || !result.IsError || calls.Load() != 2 {
+ t.Fatalf("refusal was retried or ignored: %+v %v", result, err)
+ }
+ var batch struct {
+ Items []decisionItemResult `json:"items"`
+ }
+ if err = json.Unmarshal([]byte(result.Content[0].Text), &batch); err != nil {
+ t.Fatal(err)
+ }
+ if batch.Items[0].Status != "completed" || batch.Items[1].Status != "error" || batch.Items[1].Result != nil || batch.Items[2].Status != "not_run" {
+ t.Fatalf("refusal changed partial result semantics: %+v", batch)
+ }
+}
+
func TestDecisionBlockSources(t *testing.T) {
originalData, originalDB := util.DataDir, util.BlockTreeDBPath
util.DataDir = t.TempDir()
diff --git a/kernel/util/decision.go b/kernel/util/decision.go
index cba7426834..dafb3cef54 100644
--- a/kernel/util/decision.go
+++ b/kernel/util/decision.go
@@ -21,8 +21,8 @@ import (
const DecisionMaxBytes = 1024 * 1024
type DecisionOptions struct {
- Endpoint, APIKey, Model string
- Timeout int
+ Provider, Endpoint, APIKey, Model string
+ Timeout int
}
type DecisionState struct {
@@ -69,6 +69,11 @@ var decisionHTTPClient = func() *http.Client {
}()
func ValidateDecisionQuestions(questions map[string]DecisionQuestion) error {
+ _, err := normalizeDecisionQuestions(questions)
+ return err
+}
+
+func validateDecisionQuestions(questions map[string]DecisionQuestion) error {
if len(questions) == 0 || len(questions) > 32 {
return errors.New("decision requires 1 to 32 questions")
}
@@ -110,7 +115,12 @@ func ValidateDecisionQuestions(questions map[string]DecisionQuestion) error {
// EvaluateDecision 发送一次判断请求,不重试、不截断原文,也不将缺失或无效答案转换为分数。
func EvaluateDecision(ctx context.Context, options DecisionOptions, state DecisionState, questions map[string]DecisionQuestion) (*DecisionResult, error) {
- if err := ValidateDecisionQuestions(questions); err != nil {
+ plan, err := normalizeDecisionQuestions(questions)
+ if err != nil {
+ return nil, err
+ }
+ provider, err := decisionProviderFor(options.Provider)
+ if err != nil {
return nil, err
}
endpoint, err := url.Parse(options.Endpoint)
@@ -121,11 +131,7 @@ func EvaluateDecision(ctx context.Context, options DecisionOptions, state Decisi
if strings.TrimSpace(options.APIKey) == "" || strings.TrimSpace(options.Model) == "" {
return nil, errors.New("decision model not configured")
}
- payload, err := json.Marshal(struct {
- Model string `json:"model"`
- State DecisionState `json:"state"`
- Questions map[string]DecisionQuestion `json:"questions"`
- }{options.Model, state, questions})
+ payload, err := provider.encode(options.Model, state, plan)
if err != nil || len(payload) > DecisionMaxBytes {
return nil, errors.New("decision request exceeds 1 MiB; reduce the input without silently truncating it")
}
@@ -165,15 +171,19 @@ func EvaluateDecision(ctx context.Context, options DecisionOptions, state Decisi
if len(data) > DecisionMaxBytes {
return nil, errors.New("decision response exceeds 1 MiB")
}
- var result DecisionResult
- if err = json.Unmarshal(data, &result); err != nil || !validDecisionResult(result, questions) {
+ result, err := provider.decode(data, plan)
+ if err != nil {
+ return nil, err
+ }
+ if result == nil || !validDecisionResult(*result, questions) {
return nil, errors.New("decision API returned incomplete or invalid answers")
}
- return &result, nil
+ return result, nil
}
func validDecisionResult(result DecisionResult, questions map[string]DecisionQuestion) bool {
- if result.Model == "" || len(result.Answers) != len(questions) {
+ if strings.TrimSpace(result.Model) == "" || len(result.Answers) != len(questions) ||
+ result.Usage.InputTokens < 0 || result.Usage.OutputTokens < 0 {
return false
}
for id, question := range questions {
diff --git a/kernel/util/decision_openai_test.go b/kernel/util/decision_openai_test.go
new file mode 100644
index 0000000000..7bae592b2c
--- /dev/null
+++ b/kernel/util/decision_openai_test.go
@@ -0,0 +1,111 @@
+package util
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+const openAIDecisionFixture = `{"model":"gpt-6-luna-resolved","answers":[{"type":"score","name":"rating","score":0.75,"probabilities":[{"value":0,"label":"0","probability":0.25},{"value":1,"label":"1","probability":0.75}],"confidence":0.5},{"type":"predicate","name":"condition","probability":0.2},{"type":"choice","name":"category","choice":"a","probabilities":[{"value":"a","probability":0.8},{"value":"b","probability":0.2}],"confidence":0.6}],"usage":{"input_tokens":12,"output_tokens":3,"total_tokens":15,"input_tokens_details":{"cached_tokens":0}}}`
+
+func TestDecisionOpenAIProtocol(t *testing.T) {
+ state := DecisionState{Context: "shared context", Text: "complete text", Blocks: []DecisionBlock{{ID: "block-id", Markdown: "full **Markdown** END"}}}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.Header.Get("Authorization") != "Bearer openai-key" || r.Header.Get("Content-Type") != "application/json" {
+ t.Error("incorrect request headers")
+ }
+ var payload struct {
+ Model string `json:"model"`
+ Input string `json:"input"`
+ Questions []openAIDecisionQuestion `json:"questions"`
+ State json.RawMessage `json:"state"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatal(err)
+ }
+ var decoded DecisionState
+ if err := json.Unmarshal([]byte(payload.Input), &decoded); err != nil || !reflect.DeepEqual(decoded, state) {
+ t.Errorf("lost input evidence: %+v", decoded)
+ }
+ if payload.Model != "gpt-6-luna" || len(payload.State) != 0 || len(payload.Questions) != 3 {
+ t.Errorf("wrong protocol: %+v", payload)
+ }
+ if payload.Questions[0].Name != "category" || payload.Questions[0].Choices[0].Value != "a" || payload.Questions[1].Type != "predicate" || payload.Questions[2].Levels[1].Label != "1" || payload.Questions[2].Levels[1].Description != "High" {
+ t.Errorf("incorrect stable question mapping: %+v", payload.Questions)
+ }
+ io.WriteString(w, openAIDecisionFixture)
+ }))
+ defer server.Close()
+ result, err := EvaluateDecision(context.Background(), DecisionOptions{Provider: "openai", Endpoint: server.URL, APIKey: "openai-key", Model: "gpt-6-luna"}, state, decisionTestQuestions())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.Model != "gpt-6-luna-resolved" || result.Usage.InputTokens != 12 || result.Usage.OutputTokens != 3 || *result.Answers["condition"].Noul != .2 || *result.Answers["rating"].Score != .75 || result.Answers["rating"].Legend["1"] != "High" || *result.Answers["category"].Choice != "a" {
+ t.Fatalf("mapped values changed: %+v", result)
+ }
+}
+
+func TestDecisionOpenAIRejectsInvalidAnswers(t *testing.T) {
+ cases := map[string]string{
+ "duplicate answer": strings.Replace(openAIDecisionFixture, `"name":"condition"`, `"name":"category"`, 1),
+ "unknown answer": strings.Replace(openAIDecisionFixture, `"name":"condition"`, `"name":"other"`, 1),
+ "null answer name": strings.Replace(openAIDecisionFixture, `"name":"condition"`, `"name":null`, 1),
+ "wrong answer type": strings.Replace(openAIDecisionFixture, `"type":"predicate"`, `"type":"noul"`, 1),
+ "missing probability": strings.Replace(openAIDecisionFixture, `,"probability":0.2}`, `}`, 1),
+ "null probability": strings.Replace(openAIDecisionFixture, `"probability":0.2}`, `"probability":null}`, 1),
+ "probability out of range": strings.Replace(openAIDecisionFixture, `"probability":0.2}`, `"probability":1.2}`, 1),
+ "duplicate choice": strings.Replace(openAIDecisionFixture, `"value":"b"`, `"value":"a"`, 1),
+ "unknown choice": strings.Replace(openAIDecisionFixture, `"choice":"a"`, `"choice":"c"`, 1),
+ "boolean choice": strings.Replace(openAIDecisionFixture, `"choice":"a"`, `"choice":true`, 1),
+ "boolean option": strings.Replace(openAIDecisionFixture, `"value":"a"`, `"value":true`, 1),
+ "null option": strings.Replace(openAIDecisionFixture, `"value":"a"`, `"value":null`, 1),
+ "duplicate score index": strings.Replace(openAIDecisionFixture, `"value":1,"label":"1"`, `"value":0,"label":"0"`, 1),
+ "wrong label": strings.Replace(openAIDecisionFixture, `"label":"1"`, `"label":"High"`, 1),
+ "null score index": strings.Replace(openAIDecisionFixture, `"value":0`, `"value":null`, 1),
+ "fractional score index": strings.Replace(openAIDecisionFixture, `"value":0`, `"value":0.5`, 1),
+ "out of range score index": strings.Replace(openAIDecisionFixture, `"value":0`, `"value":2`, 1),
+ "out of range score": strings.Replace(openAIDecisionFixture, `"score":0.75`, `"score":2`, 1),
+ "bad sum": strings.Replace(openAIDecisionFixture, `"probability":0.25`, `"probability":0.5`, 1),
+ "missing confidence": strings.Replace(openAIDecisionFixture, `,"confidence":0.5`, ``, 1),
+ "missing model": strings.Replace(openAIDecisionFixture, `"model":"gpt-6-luna-resolved",`, ``, 1),
+ "missing usage": strings.Replace(openAIDecisionFixture, `"usage":`, `"other":`, 1),
+ "null tokens": strings.Replace(openAIDecisionFixture, `"input_tokens":12`, `"input_tokens":null`, 1),
+ "negative tokens": strings.Replace(openAIDecisionFixture, `"input_tokens":12`, `"input_tokens":-1`, 1),
+ "invalid json": `{`,
+ }
+ for name, response := range cases {
+ t.Run(name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, response) }))
+ defer server.Close()
+ result, err := EvaluateDecision(context.Background(), DecisionOptions{Provider: "openai", Endpoint: server.URL, APIKey: "key", Model: "gpt-6-luna"}, DecisionState{Text: "text"}, decisionTestQuestions())
+ if err == nil || result != nil {
+ t.Fatalf("invalid response accepted: %+v %v", result, err)
+ }
+ })
+ }
+}
+
+func TestDecisionOpenAIRefusalAndUnknownProvider(t *testing.T) {
+ var calls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ io.WriteString(w, strings.Replace(openAIDecisionFixture, `{"type":"predicate","name":"condition","probability":0.2}`, `{"type":"refusal","name":"condition"}`, 1))
+ }))
+ defer server.Close()
+ options := DecisionOptions{Provider: "openai", Endpoint: server.URL, APIKey: "key", Model: "gpt-6-luna"}
+ result, err := EvaluateDecision(context.Background(), options, DecisionState{Text: "text"}, decisionTestQuestions())
+ if !errors.Is(err, ErrDecisionRefused) || result != nil || calls.Load() != 1 {
+ t.Fatalf("refusal was coerced or retried: %+v %v", result, err)
+ }
+ options.Provider = "unknown"
+ if _, err = EvaluateDecision(context.Background(), options, DecisionState{Text: "text"}, decisionTestQuestions()); err == nil || calls.Load() != 1 {
+ t.Fatal("unknown provider sent request or fell back")
+ }
+}
diff --git a/kernel/util/decision_provider.go b/kernel/util/decision_provider.go
new file mode 100644
index 0000000000..e30dbe6499
--- /dev/null
+++ b/kernel/util/decision_provider.go
@@ -0,0 +1,249 @@
+package util
+
+import (
+ "encoding/json"
+ "errors"
+ "sort"
+ "strconv"
+)
+
+const (
+ DecisionProviderTypeSafe = "typesafe"
+ DecisionProviderOpenAI = "openai"
+)
+
+// ErrDecisionRefused 区分供应商拒答和格式错误,不携带原始响应或笔记正文。
+var ErrDecisionRefused = errors.New("decision provider refused to answer a question")
+
+// decisionQuestionSpec 是供应商无关的问题定义,候选和等级在协议转换前完成校验。
+type decisionQuestionSpec struct {
+ ID, Kind, Instructions string
+ Choices []decisionChoice
+ Levels []string
+}
+
+type decisionChoice struct {
+ Value string `json:"value"`
+ Description string `json:"description"`
+}
+
+func normalizeDecisionQuestions(questions map[string]DecisionQuestion) ([]decisionQuestionSpec, error) {
+ if err := validateDecisionQuestions(questions); err != nil {
+ return nil, err
+ }
+ ids := make([]string, 0, len(questions))
+ for id := range questions {
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+ ret := make([]decisionQuestionSpec, 0, len(ids))
+ for _, id := range ids {
+ question := questions[id]
+ spec := decisionQuestionSpec{ID: id, Kind: question.Type, Instructions: question.Instructions}
+ switch question.Type {
+ case "choice":
+ var options map[string]string
+ _ = json.Unmarshal(question.Criteria, &options)
+ keys := make([]string, 0, len(options))
+ for key := range options {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ spec.Choices = append(spec.Choices, decisionChoice{Value: key, Description: options[key]})
+ }
+ case "score":
+ _ = json.Unmarshal(question.Criteria, &spec.Levels)
+ }
+ ret = append(ret, spec)
+ }
+ return ret, nil
+}
+
+type decisionProvider interface {
+ encode(string, DecisionState, []decisionQuestionSpec) ([]byte, error)
+ decode([]byte, []decisionQuestionSpec) (*DecisionResult, error)
+}
+
+func decisionProviderFor(provider string) (decisionProvider, error) {
+ switch provider {
+ case "", DecisionProviderTypeSafe:
+ return typeSafeDecisionProvider{}, nil
+ case DecisionProviderOpenAI:
+ return openAIDecisionProvider{}, nil
+ default:
+ return nil, errors.New("unsupported decision provider")
+ }
+}
+
+type typeSafeDecisionProvider struct{}
+
+func (typeSafeDecisionProvider) encode(model string, state DecisionState, specs []decisionQuestionSpec) ([]byte, error) {
+ questions := make(map[string]DecisionQuestion, len(specs))
+ for _, spec := range specs {
+ question := DecisionQuestion{Type: spec.Kind, Instructions: spec.Instructions}
+ switch spec.Kind {
+ case "choice":
+ options := make(map[string]string, len(spec.Choices))
+ for _, choice := range spec.Choices {
+ options[choice.Value] = choice.Description
+ }
+ question.Criteria, _ = json.Marshal(options)
+ case "score":
+ question.Criteria, _ = json.Marshal(spec.Levels)
+ }
+ questions[spec.ID] = question
+ }
+ return json.Marshal(struct {
+ Model string `json:"model"`
+ State DecisionState `json:"state"`
+ Questions map[string]DecisionQuestion `json:"questions"`
+ }{model, state, questions})
+}
+
+func (typeSafeDecisionProvider) decode(data []byte, _ []decisionQuestionSpec) (*DecisionResult, error) {
+ var result DecisionResult
+ if err := json.Unmarshal(data, &result); err != nil {
+ return nil, errors.New("decision API returned incomplete or invalid answers")
+ }
+ return &result, nil
+}
+
+type openAIDecisionProvider struct{}
+
+type openAIDecisionLevel struct {
+ Label string `json:"label"`
+ Description string `json:"description"`
+}
+
+type openAIDecisionQuestion struct {
+ Type string `json:"type"`
+ Name string `json:"name"`
+ Instructions string `json:"instructions"`
+ Choices []decisionChoice `json:"choices,omitempty"`
+ Levels []openAIDecisionLevel `json:"levels,omitempty"`
+}
+
+func (openAIDecisionProvider) encode(model string, state DecisionState, specs []decisionQuestionSpec) ([]byte, error) {
+ // 将完整状态作为结构化文本证据传递,问题指令只放在 questions 中。
+ input, err := json.Marshal(state)
+ if err != nil {
+ return nil, err
+ }
+ questions := make([]openAIDecisionQuestion, 0, len(specs))
+ for _, spec := range specs {
+ question := openAIDecisionQuestion{Type: spec.Kind, Name: spec.ID, Instructions: spec.Instructions}
+ switch spec.Kind {
+ case "noul":
+ question.Type = "predicate"
+ case "choice":
+ question.Choices = spec.Choices
+ case "score":
+ for index, description := range spec.Levels {
+ question.Levels = append(question.Levels, openAIDecisionLevel{Label: strconv.Itoa(index), Description: description})
+ }
+ }
+ questions = append(questions, question)
+ }
+ return json.Marshal(struct {
+ Model string `json:"model"`
+ Input string `json:"input"`
+ Questions []openAIDecisionQuestion `json:"questions"`
+ }{model, string(input), questions})
+}
+
+func (openAIDecisionProvider) decode(data []byte, specs []decisionQuestionSpec) (*DecisionResult, error) {
+ invalid := errors.New("decision API returned incomplete or invalid answers")
+ var response struct {
+ Model string `json:"model"`
+ Answers []struct {
+ Name *string `json:"name"`
+ Type string `json:"type"`
+ Choice *string `json:"choice"`
+ Score *float64 `json:"score"`
+ Probability *float64 `json:"probability"`
+ Confidence *float64 `json:"confidence"`
+ Probabilities []struct {
+ Value json.RawMessage `json:"value"`
+ Label *string `json:"label"`
+ Probability *float64 `json:"probability"`
+ } `json:"probabilities"`
+ } `json:"answers"`
+ Usage *struct {
+ InputTokens *int `json:"input_tokens"`
+ OutputTokens *int `json:"output_tokens"`
+ } `json:"usage"`
+ }
+ if json.Unmarshal(data, &response) != nil || len(response.Answers) != len(specs) {
+ return nil, invalid
+ }
+ questions := make(map[string]decisionQuestionSpec, len(specs))
+ for _, spec := range specs {
+ questions[spec.ID] = spec
+ }
+ result := &DecisionResult{Model: response.Model, Answers: make(map[string]DecisionAnswer, len(specs))}
+ refused := false
+ seen := make(map[string]bool, len(specs))
+ for _, answer := range response.Answers {
+ if answer.Name == nil || seen[*answer.Name] {
+ return nil, invalid
+ }
+ spec, exists := questions[*answer.Name]
+ if !exists {
+ return nil, invalid
+ }
+ seen[*answer.Name] = true
+ if answer.Type == "refusal" {
+ refused = true
+ continue
+ }
+ expectedType := spec.Kind
+ if expectedType == "noul" {
+ expectedType = "predicate"
+ }
+ if answer.Type != expectedType {
+ return nil, invalid
+ }
+ converted := DecisionAnswer{Type: spec.Kind, Choice: answer.Choice, Score: answer.Score,
+ Noul: answer.Probability, Confidence: answer.Confidence}
+ if spec.Kind != "noul" {
+ converted.Probabilities = make(map[string]*float64, len(answer.Probabilities))
+ if spec.Kind == "score" {
+ converted.Legend = make(map[string]string, len(spec.Levels))
+ }
+ for _, probability := range answer.Probabilities {
+ var key string
+ if spec.Kind == "choice" {
+ var value *string
+ if json.Unmarshal(probability.Value, &value) != nil || value == nil {
+ return nil, invalid
+ }
+ key = *value
+ } else {
+ var index *int
+ if json.Unmarshal(probability.Value, &index) != nil || index == nil || *index < 0 || *index >= len(spec.Levels) {
+ return nil, invalid
+ }
+ key = strconv.Itoa(*index)
+ if probability.Label == nil || *probability.Label != key {
+ return nil, invalid
+ }
+ converted.Legend[key] = spec.Levels[*index]
+ }
+ if _, duplicate := converted.Probabilities[key]; duplicate {
+ return nil, invalid
+ }
+ converted.Probabilities[key] = probability.Probability
+ }
+ }
+ result.Answers[*answer.Name] = converted
+ }
+ if refused {
+ return nil, ErrDecisionRefused
+ }
+ if response.Usage == nil || response.Usage.InputTokens == nil || response.Usage.OutputTokens == nil {
+ return nil, invalid
+ }
+ result.Usage.InputTokens, result.Usage.OutputTokens = *response.Usage.InputTokens, *response.Usage.OutputTokens
+ return result, nil
+}