Skip to content

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

:art: Improve rerank API compatibility https://github.com/siyuan-note/siyuan/issues/18752

Danieldd1b3f9ad5bb
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index b09b3d22e1..befa0681ba 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "تنسيق طلب إعادة الترتيب",
+ "rerankRequestFormatTip": "اختر تنسيق الطلب الذي تتطلبه خدمة إعادة الترتيب",
+ "rerankRequestFormatCohere": "متوافق مع Cohere/Jina",
+ "rerankRequestFormatDashScope": "متوافق مع DashScope/ZenMux",
"listItemActionTip": "انقر بزر الماوس الأيمن <span class='ft__on-surface'>فتح قائمة عنصر القائمة هذا</span><br>انقر مع الضغط على Shift <span class='ft__on-surface'>فتح سماته</span>",
"bazaarRemoveRating": "إزالة التقييم",
"bazaarRatingRemoved": "تمت إزالة التقييم",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 873fde5781..40d009273b 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Rerank-Anfrageformat",
+ "rerankRequestFormatTip": "Das vom Rerank-Dienst benötigte Anfrageformat auswählen",
+ "rerankRequestFormatCohere": "Cohere/Jina-kompatibel",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux-kompatibel",
"listItemActionTip": "Mit der rechten Maustaste klicken <span class='ft__on-surface'>Menü dieses Listeneintrags öffnen</span><br>Shift+Klick <span class='ft__on-surface'>Attribute öffnen</span>",
"bazaarRemoveRating": "Bewertung entfernen",
"bazaarRatingRemoved": "Bewertung entfernt",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 5c3a3d4771..c0b75e161d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Rerank request format",
+ "rerankRequestFormatTip": "Select the request format required by the rerank service",
+ "rerankRequestFormatCohere": "Cohere/Jina compatible",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux compatible",
"listItemActionTip": "Right-click <span class='ft__on-surface'>Open this list item's menu</span><br>Shift+click <span class='ft__on-surface'>Open its attributes</span>",
"bazaarRemoveRating": "Remove rating",
"bazaarRatingRemoved": "Rating removed",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 02450f604b..3be3bcf86a 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Formato de solicitud de reordenación",
+ "rerankRequestFormatTip": "Selecciona el formato de solicitud requerido por el servicio de reordenación",
+ "rerankRequestFormatCohere": "Compatible con Cohere/Jina",
+ "rerankRequestFormatDashScope": "Compatible con DashScope/ZenMux",
"listItemActionTip": "Clic derecho <span class='ft__on-surface'>Abrir el menú de este elemento de lista</span><br>Shift+clic <span class='ft__on-surface'>Abrir sus atributos</span>",
"bazaarRemoveRating": "Eliminar puntuación",
"bazaarRatingRemoved": "Puntuación eliminada",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 1e3ddf225c..8b35e00e4b 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Format de requête de rerangement",
+ "rerankRequestFormatTip": "Sélectionnez le format de requête requis par le service de rerangement",
+ "rerankRequestFormatCohere": "Compatible avec Cohere/Jina",
+ "rerankRequestFormatDashScope": "Compatible avec DashScope/ZenMux",
"listItemActionTip": "Clic droit <span class='ft__on-surface'>Ouvrir le menu de cet élément de liste</span><br>Shift+clic <span class='ft__on-surface'>Ouvrir ses attributs</span>",
"bazaarRemoveRating": "Supprimer la note",
"bazaarRatingRemoved": "Note supprimée",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 9112cc53d4..360704cf44 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "פורמט בקשת סידור מחדש",
+ "rerankRequestFormatTip": "בחרו את פורמט הבקשה הנדרש על ידי שירות הסידור מחדש",
+ "rerankRequestFormatCohere": "תואם Cohere/Jina",
+ "rerankRequestFormatDashScope": "תואם DashScope/ZenMux",
"listItemActionTip": "לחיצה ימנית <span class='ft__on-surface'>פתיחת התפריט של פריט רשימה זה</span><br>Shift+לחיצה <span class='ft__on-surface'>פתיחת המאפיינים שלו</span>",
"bazaarRemoveRating": "הסרת הדירוג",
"bazaarRatingRemoved": "הדירוג הוסר",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 1b7f0c8cb8..484945531a 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "पुनः क्रम अनुरोध प्रारूप",
+ "rerankRequestFormatTip": "पुनः क्रम सेवा के लिए आवश्यक अनुरोध प्रारूप चुनें",
+ "rerankRequestFormatCohere": "Cohere/Jina संगत",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux संगत",
"listItemActionTip": "राइट-क्लिक <span class='ft__on-surface'>इस सूची आइटम का मेनू खोलें</span><br>Shift+क्लिक <span class='ft__on-surface'>इसकी विशेषताएँ खोलें</span>",
"bazaarRemoveRating": "रेटिंग हटाएँ",
"bazaarRatingRemoved": "रेटिंग हटा दी गई",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 519b849361..e4bff696e9 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Format permintaan rerank",
+ "rerankRequestFormatTip": "Pilih format permintaan yang diperlukan oleh layanan rerank",
+ "rerankRequestFormatCohere": "Kompatibel dengan Cohere/Jina",
+ "rerankRequestFormatDashScope": "Kompatibel dengan DashScope/ZenMux",
"listItemActionTip": "Klik kanan <span class='ft__on-surface'>Buka menu item daftar ini</span><br>Shift+klik <span class='ft__on-surface'>Buka atributnya</span>",
"bazaarRemoveRating": "Hapus penilaian",
"bazaarRatingRemoved": "Penilaian dihapus",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 825ded287a..07e930b04c 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Formato della richiesta di reranking",
+ "rerankRequestFormatTip": "Seleziona il formato di richiesta richiesto dal servizio di reranking",
+ "rerankRequestFormatCohere": "Compatibile con Cohere/Jina",
+ "rerankRequestFormatDashScope": "Compatibile con DashScope/ZenMux",
"listItemActionTip": "Clic destro <span class='ft__on-surface'>Apri il menu di questo elemento dell'elenco</span><br>Shift+clic <span class='ft__on-surface'>Apri i suoi attributi</span>",
"bazaarRemoveRating": "Rimuovi valutazione",
"bazaarRatingRemoved": "Valutazione rimossa",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 95f19efbc8..58e060f558 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "リランキングリクエスト形式",
+ "rerankRequestFormatTip": "リランキングサービスが要求するリクエスト形式を選択します",
+ "rerankRequestFormatCohere": "Cohere/Jina 互換",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux 互換",
"listItemActionTip": "右クリック <span class='ft__on-surface'>このリスト項目のメニューを開く</span><br>Shift+クリック <span class='ft__on-surface'>属性を開く</span>",
"bazaarRemoveRating": "評価を取り消す",
"bazaarRatingRemoved": "評価を取り消しました",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 2efa4a4b7d..e73e191efe 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "재순위 요청 형식",
+ "rerankRequestFormatTip": "재순위 서비스에 필요한 요청 형식을 선택합니다",
+ "rerankRequestFormatCohere": "Cohere/Jina 호환",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux 호환",
"listItemActionTip": "마우스 오른쪽 버튼 클릭 <span class='ft__on-surface'>이 목록 항목 메뉴 열기</span><br>Shift+클릭 <span class='ft__on-surface'>속성 열기</span>",
"bazaarRemoveRating": "평점 삭제",
"bazaarRatingRemoved": "평점이 삭제되었습니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 61a5bade41..18ed532097 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Rerank-aanvraagindeling",
+ "rerankRequestFormatTip": "Selecteer de aanvraagindeling die de rerank-service vereist",
+ "rerankRequestFormatCohere": "Compatibel met Cohere/Jina",
+ "rerankRequestFormatDashScope": "Compatibel met DashScope/ZenMux",
"listItemActionTip": "Klik met de rechtermuisknop <span class='ft__on-surface'>Menu van dit lijstitem openen</span><br>Shift+klik <span class='ft__on-surface'>Kenmerken openen</span>",
"bazaarRemoveRating": "Beoordeling verwijderen",
"bazaarRatingRemoved": "Beoordeling verwijderd",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 0120706dcd..df3852f54a 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Format żądania ponownego rankingu",
+ "rerankRequestFormatTip": "Wybierz format żądania wymagany przez usługę ponownego rankingu",
+ "rerankRequestFormatCohere": "Zgodny z Cohere/Jina",
+ "rerankRequestFormatDashScope": "Zgodny z DashScope/ZenMux",
"listItemActionTip": "Kliknij prawym przyciskiem myszy <span class='ft__on-surface'>Otwórz menu tego elementu listy</span><br>Shift+kliknięcie <span class='ft__on-surface'>Otwórz jego atrybuty</span>",
"bazaarRemoveRating": "Usuń ocenę",
"bazaarRatingRemoved": "Ocena została usunięta",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 12abb0d982..5301f189f9 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Formato da solicitação de reordenação",
+ "rerankRequestFormatTip": "Selecione o formato de solicitação exigido pelo serviço de reordenação",
+ "rerankRequestFormatCohere": "Compatível com Cohere/Jina",
+ "rerankRequestFormatDashScope": "Compatível com DashScope/ZenMux",
"listItemActionTip": "Clique com o botão direito <span class='ft__on-surface'>Abrir o menu deste item da lista</span><br>Shift+clique <span class='ft__on-surface'>Abrir seus atributos</span>",
"bazaarRemoveRating": "Remover avaliação",
"bazaarRatingRemoved": "Avaliação removida",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index f375ce987e..b75b0196ca 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Формат запроса переранжирования",
+ "rerankRequestFormatTip": "Выберите формат запроса, необходимый сервису переранжирования",
+ "rerankRequestFormatCohere": "Совместимый с Cohere/Jina",
+ "rerankRequestFormatDashScope": "Совместимый с DashScope/ZenMux",
"listItemActionTip": "Щелчок правой кнопкой мыши <span class='ft__on-surface'>Открыть меню этого элемента списка</span><br>Shift+щелчок <span class='ft__on-surface'>Открыть его атрибуты</span>",
"bazaarRemoveRating": "Удалить оценку",
"bazaarRatingRemoved": "Оценка удалена",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 7ef08e3636..69bf321abb 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Formát požiadavky na pretriedenie",
+ "rerankRequestFormatTip": "Vyberte formát požiadavky vyžadovaný službou pretriedenia",
+ "rerankRequestFormatCohere": "Kompatibilný s Cohere/Jina",
+ "rerankRequestFormatDashScope": "Kompatibilný s DashScope/ZenMux",
"listItemActionTip": "Kliknutie pravým tlačidlom <span class='ft__on-surface'>Otvoriť ponuku tejto položky zoznamu</span><br>Shift+kliknutie <span class='ft__on-surface'>Otvoriť jej atribúty</span>",
"bazaarRemoveRating": "Odstrániť hodnotenie",
"bazaarRatingRemoved": "Hodnotenie bolo odstránené",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index f0ac5a9adc..eea515ac6e 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "รูปแบบคำขอจัดอันดับใหม่",
+ "rerankRequestFormatTip": "เลือกรูปแบบคำขอที่บริการจัดอันดับใหม่ต้องการ",
+ "rerankRequestFormatCohere": "เข้ากันได้กับ Cohere/Jina",
+ "rerankRequestFormatDashScope": "เข้ากันได้กับ DashScope/ZenMux",
"listItemActionTip": "คลิกขวา <span class='ft__on-surface'>เปิดเมนูของรายการนี้</span><br>Shift+คลิก <span class='ft__on-surface'>เปิดแอตทริบิวต์</span>",
"bazaarRemoveRating": "ลบคะแนน",
"bazaarRatingRemoved": "ลบคะแนนแล้ว",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index ee4463e144..9a0a85dda4 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Yeniden sıralama istek biçimi",
+ "rerankRequestFormatTip": "Yeniden sıralama hizmetinin gerektirdiği istek biçimini seçin",
+ "rerankRequestFormatCohere": "Cohere/Jina ile uyumlu",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux ile uyumlu",
"listItemActionTip": "Sağ tıklayın <span class='ft__on-surface'>Bu liste öğesinin menüsünü açın</span><br>Shift+tıklayın <span class='ft__on-surface'>Özniteliklerini açın</span>",
"bazaarRemoveRating": "Puanı kaldır",
"bazaarRatingRemoved": "Puan kaldırıldı",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index a69da44547..4577b1cf97 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "Формат запиту переранжування",
+ "rerankRequestFormatTip": "Виберіть формат запиту, потрібний сервісу переранжування",
+ "rerankRequestFormatCohere": "Сумісний із Cohere/Jina",
+ "rerankRequestFormatDashScope": "Сумісний із DashScope/ZenMux",
"listItemActionTip": "Клацання правою кнопкою миші <span class='ft__on-surface'>Відкрити меню цього елемента списку</span><br>Shift+клацання <span class='ft__on-surface'>Відкрити його атрибути</span>",
"bazaarRemoveRating": "Видалити оцінку",
"bazaarRatingRemoved": "Оцінку видалено",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index c6a99bc172..2f04c55f6d 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "重排 API 格式",
+ "rerankRequestFormatTip": "选择重排服务所需的请求格式",
+ "rerankRequestFormatCohere": "Cohere/Jina 兼容",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux 兼容",
"listItemActionTip": "右键 <span class='ft__on-surface'>打开该列表项菜单</span><br>Shift+点击 <span class='ft__on-surface'>打开属性</span>",
"bazaarRemoveRating": "取消评分",
"bazaarRatingRemoved": "已取消评分",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 26b0f6d393..c6ef897c85 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,8 @@
{
+ "rerankRequestFormat": "重排 API 格式",
+ "rerankRequestFormatTip": "選擇重排服務所需的請求格式",
+ "rerankRequestFormatCohere": "Cohere/Jina 相容",
+ "rerankRequestFormatDashScope": "DashScope/ZenMux 相容",
"listItemActionTip": "右鍵 <span class='ft__on-surface'>開啟此清單項目的功能表</span><br>Shift+點擊 <span class='ft__on-surface'>開啟屬性</span>",
"bazaarRemoveRating": "取消評分",
"bazaarRatingRemoved": "已取消評分",
diff --git a/app/src/config/tabs/ai/aiTab.ts b/app/src/config/tabs/ai/aiTab.ts
index abbff5efa7..af393694b3 100644
--- a/app/src/config/tabs/ai/aiTab.ts
+++ b/app/src/config/tabs/ai/aiTab.ts
@@ -236,6 +236,14 @@ const registerAiRerankGroup = (tab: SettingTabBuilder) => {
title: window.siyuan.languages.rerankModel,
desc: window.siyuan.languages.rerankTip,
});
+ group.select("ai.rerank.requestFormat", {
+ title: window.siyuan.languages.rerankRequestFormat,
+ desc: window.siyuan.languages.rerankRequestFormatTip,
+ options: [
+ {value: "cohere", label: window.siyuan.languages.rerankRequestFormatCohere},
+ {value: "dashscope", label: window.siyuan.languages.rerankRequestFormatDashScope},
+ ],
+ });
group.textBlock("ai.rerank.endpoint", {
title: window.siyuan.languages.apiEndpoint,
desc: window.siyuan.languages.apiEndpointRerankTip,
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index f5a433da81..7fb1ded999 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -227,6 +227,7 @@ declare namespace Config {
endpoint: string;
apiKey: string;
name: string;
+ requestFormat: "cohere" | "dashscope";
timeout: number;
candidateCount: number;
}
diff --git a/kernel/api/ai.go b/kernel/api/ai.go
index 3162d0eff4..e7819218ef 100644
--- a/kernel/api/ai.go
+++ b/kernel/api/ai.go
@@ -345,7 +345,13 @@ func testRerankModel(c *gin.Context) {
return
}
- matched, err := util.TestRerankModel(rerank.APIKey, rerank.Endpoint, rerank.Name, rerank.Timeout)
+ matched, err := util.TestRerankModel(util.RerankOptions{
+ APIKey: rerank.APIKey,
+ Endpoint: rerank.Endpoint,
+ Model: rerank.Name,
+ RequestFormat: rerank.RequestFormat,
+ Timeout: rerank.Timeout,
+ })
// 测试结果统一以 code=0 返回,具体成败信息放在 data 中由前端控制展示
result := map[string]any{
"matched": matched,
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index 74557ea7df..f3960245c5 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -106,13 +106,14 @@ type Embedding struct {
// 采用主流重排服务的 /rerank 协议(OpenAI 官方暂无 rerank API)。
// 各服务商端点路径不一(Jina /v1/rerank、阿里云 /v1/reranks 等),故 Endpoint 为完整端点地址。
type Rerank struct {
- ID string `json:"id"`
- Enabled bool `json:"enabled"`
- APIKey string `json:"apiKey"`
- Endpoint string `json:"endpoint"` // 完整重排端点 URL,按目标模型文档填写
- Name string `json:"name"`
- Timeout int `json:"timeout"`
- CandidateCount int `json:"candidateCount"` // 向量召回后送入重排的候选文档数,默认 30;越大越准但越慢
+ ID string `json:"id"`
+ Enabled bool `json:"enabled"`
+ APIKey string `json:"apiKey"`
+ Endpoint string `json:"endpoint"` // 完整重排端点 URL,按目标模型文档填写
+ Name string `json:"name"`
+ RequestFormat util.RerankRequestFormat `json:"requestFormat"`
+ Timeout int `json:"timeout"`
+ CandidateCount int `json:"candidateCount"` // 向量召回后送入重排的候选文档数,默认 30;越大越准但越慢
}
type Provider struct {
@@ -162,7 +163,11 @@ func defaultEmbedding() *Embedding {
}
func defaultRerank() *Rerank {
- return &Rerank{Timeout: 30, CandidateCount: 30}
+ return &Rerank{
+ RequestFormat: util.RerankRequestFormatCohere,
+ Timeout: 30,
+ CandidateCount: 30,
+ }
}
func defaultAgent() *Agent {
@@ -618,6 +623,10 @@ func (ai *AI) Normalize() {
if ai.Rerank.Timeout < 1 {
ai.Rerank.Timeout = 30
}
+ if util.RerankRequestFormatCohere != ai.Rerank.RequestFormat &&
+ util.RerankRequestFormatDashScope != ai.Rerank.RequestFormat {
+ ai.Rerank.RequestFormat = util.RerankRequestFormatCohere
+ }
if ai.Rerank.CandidateCount < 5 {
ai.Rerank.CandidateCount = 5
} else if ai.Rerank.CandidateCount > 100 {
diff --git a/kernel/model/embedding.go b/kernel/model/embedding.go
index 5d1220fa1b..0b5f91f346 100644
--- a/kernel/model/embedding.go
+++ b/kernel/model/embedding.go
@@ -602,7 +602,13 @@ func rerankSqlBlocks(query string, sqlBlocks []*sql.Block) []*sql.Block {
}
// topN=0 表示不传 top_n,要求服务端返回全部文档评分,避免被服务端 top_n 上限截断
- indices, _, err := util.Rerank(query, documents, rerankKey(), rerankEndpoint(), rerankModel(), 0, rerankTimeout())
+ indices, _, err := util.Rerank(query, documents, util.RerankOptions{
+ APIKey: rerankKey(),
+ Endpoint: rerankEndpoint(),
+ Model: rerankModel(),
+ RequestFormat: rerankRequestFormat(),
+ Timeout: rerankTimeout(),
+ })
if nil != err {
logging.LogErrorf("rerank failed, fallback to vector similarity order: %s", err)
return sqlBlocks
diff --git a/kernel/model/rerank.go b/kernel/model/rerank.go
index ca0ee34385..d29d92d30f 100644
--- a/kernel/model/rerank.go
+++ b/kernel/model/rerank.go
@@ -16,6 +16,8 @@
package model
+import "github.com/siyuan-note/siyuan/kernel/util"
+
// defaultRerankCandidateCount 向量召回后默认送入重排的候选文档数,与 conf.defaultRerank 保持一致。
const defaultRerankCandidateCount = 30
@@ -45,6 +47,13 @@ func rerankModel() string {
return ""
}
+func rerankRequestFormat() util.RerankRequestFormat {
+ if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled {
+ return Conf.AI.Rerank.RequestFormat
+ }
+ return util.RerankRequestFormatCohere
+}
+
func rerankTimeout() int {
if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled && 0 < Conf.AI.Rerank.Timeout {
return Conf.AI.Rerank.Timeout
diff --git a/kernel/util/openai.go b/kernel/util/openai.go
index bc66c356c6..8660532009 100644
--- a/kernel/util/openai.go
+++ b/kernel/util/openai.go
@@ -509,14 +509,46 @@ func closeOpenAIIdleConnections() {
}
}
-// rerankRequest 对应主流重排服务的 /rerank 请求体(Jina/Cohere/阿里云 compatible-api 等)。
-type rerankRequest struct {
+type RerankRequestFormat string
+
+const (
+ RerankRequestFormatCohere RerankRequestFormat = "cohere"
+ RerankRequestFormatDashScope RerankRequestFormat = "dashscope"
+)
+
+type RerankOptions struct {
+ APIKey string
+ Endpoint string
+ Model string
+ RequestFormat RerankRequestFormat
+ TopN int
+ Timeout int
+}
+
+// rerankCohereRequest 对应 Jina、Cohere 和阿里云 compatible-api 等服务的扁平请求体。
+type rerankCohereRequest struct {
Model string `json:"model"`
Query string `json:"query"`
Documents []string `json:"documents"`
TopN int `json:"top_n,omitempty"`
}
+type rerankDashScopeInput struct {
+ Query string `json:"query"`
+ Documents []string `json:"documents"`
+}
+
+type rerankDashScopeParameters struct {
+ TopN int `json:"top_n"`
+}
+
+// rerankDashScopeRequest 对应 DashScope 和 ZenMux 等服务的嵌套请求体。
+type rerankDashScopeRequest struct {
+ Model string `json:"model"`
+ Input rerankDashScopeInput `json:"input"`
+ Parameters *rerankDashScopeParameters `json:"parameters,omitempty"`
+}
+
// rerankResult 为响应 results 数组中的单项,index 指向 documents 下标。
type rerankResult struct {
Index int `json:"index"`
@@ -526,6 +558,9 @@ type rerankResult struct {
// rerankResponse 对应 /v1/rerank 响应体。
type rerankResponse struct {
Results []rerankResult `json:"results"`
+ Output *struct {
+ Results []rerankResult `json:"results"`
+ } `json:"output"`
}
// Rerank 调用重排服务对 query 与候选文档逐对精排。endpoint 为完整重排端点地址,不同服务商路径无统一标准
@@ -534,15 +569,15 @@ type rerankResponse struct {
// 对每条 document 文本按 rerankDocTextMaxRunes 截断,防超服务端 token 限制并保证 UTF-8 完整。
// topN 语义:topN <= 0 时不传 top_n(服务端默认返回全部文档评分,搜索场景用此避免被服务端 top_n 上限截断);
// topN > 0 时透传给服务端,仅用于测试连通性等只需少量结果的场景。
-func Rerank(query string, documents []string, apiKey, endpoint, model string, topN, timeout int) (indices []int, scores []float64, err error) {
- if 1 > timeout {
- timeout = 30
+func Rerank(query string, documents []string, options RerankOptions) (indices []int, scores []float64, err error) {
+ if 1 > options.Timeout {
+ options.Timeout = 30
}
if 1 > len(documents) {
return
}
- if 0 < topN && topN > len(documents) {
- topN = len(documents)
+ if 0 < options.TopN && options.TopN > len(documents) {
+ options.TopN = len(documents)
}
trimmed := make([]string, len(documents))
@@ -550,25 +585,20 @@ func Rerank(query string, documents []string, apiKey, endpoint, model string, to
trimmed[i] = truncateRerankDocument(doc)
}
- body, err := json.Marshal(rerankRequest{
- Model: model,
- Query: query,
- Documents: trimmed,
- TopN: topN,
- })
+ body, err := marshalRerankRequest(query, trimmed, options)
if nil != err {
return
}
// endpoint 为完整重排端点地址,不做路径追加——不同服务商端点路径无统一标准,用户照文档填写。
- req, err := http.NewRequest(http.MethodPost, strings.TrimRight(endpoint, "/"), bytes.NewReader(body))
+ req, err := http.NewRequest(http.MethodPost, strings.TrimRight(options.Endpoint, "/"), bytes.NewReader(body))
if nil != err {
return
}
req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", "Bearer "+apiKey)
+ req.Header.Set("Authorization", "Bearer "+options.APIKey)
- ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Duration(options.Timeout)*time.Second)
defer cancel()
req = req.WithContext(ctx)
@@ -594,7 +624,16 @@ func Rerank(query string, documents []string, apiKey, endpoint, model string, to
return
}
- for _, r := range rr.Results {
+ results := rr.Results
+ if nil == results && nil != rr.Output {
+ results = rr.Output.Results
+ }
+ if nil == results {
+ err = errors.New("rerank response missing results")
+ return
+ }
+
+ for _, r := range results {
if r.Index < 0 || r.Index >= len(documents) {
continue
}
@@ -604,6 +643,29 @@ func Rerank(query string, documents []string, apiKey, endpoint, model string, to
return
}
+func marshalRerankRequest(query string, documents []string, options RerankOptions) ([]byte, error) {
+ if RerankRequestFormatDashScope == options.RequestFormat {
+ request := rerankDashScopeRequest{
+ Model: options.Model,
+ Input: rerankDashScopeInput{
+ Query: query,
+ Documents: documents,
+ },
+ }
+ if 0 < options.TopN {
+ request.Parameters = &rerankDashScopeParameters{TopN: options.TopN}
+ }
+ return json.Marshal(request)
+ }
+
+ return json.Marshal(rerankCohereRequest{
+ Model: options.Model,
+ Query: query,
+ Documents: documents,
+ TopN: options.TopN,
+ })
+}
+
func truncateRerankDocument(document string) string {
runes := []rune(document)
if len(runes) > rerankDocTextMaxRunes {
@@ -614,9 +676,10 @@ func truncateRerankDocument(document string) string {
// TestRerankModel 测试重排模型可用性,用极简 query+documents 发一次重排请求验证连通性与鉴权。
// 返回值:matched 表示是否连通成功,err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。
-func TestRerankModel(apiKey, apiBaseURL, model string, timeout int) (matched bool, err error) {
+func TestRerankModel(options RerankOptions) (matched bool, err error) {
documents := []string{"a", "b"}
- indices, _, err := Rerank("1", documents, apiKey, apiBaseURL, model, len(documents), timeout)
+ options.TopN = len(documents)
+ indices, _, err := Rerank("1", documents, options)
if nil != err {
return
}
diff --git a/kernel/util/rerank_test.go b/kernel/util/rerank_test.go
index 400eac8ee0..d66876ec76 100644
--- a/kernel/util/rerank_test.go
+++ b/kernel/util/rerank_test.go
@@ -18,6 +18,7 @@ package util
import (
"encoding/json"
+ "io"
"net/http"
"net/http/httptest"
"strings"
@@ -33,7 +34,8 @@ func TestTestRerankModelValidatesResults(t *testing.T) {
}{
{name: "valid", body: `{"results":[{"index":1,"relevance_score":0.9},{"index":0,"relevance_score":0.8}]}`, matched: true},
{name: "empty", body: `{"results":[]}`},
- {name: "nested", body: `{"output":{"results":[{"index":1,"relevance_score":0.9},{"index":0,"relevance_score":0.8}]}}`},
+ {name: "nested", body: `{"output":{"results":[{"index":1,"relevance_score":0.9},{"index":0,"relevance_score":0.8}]}}`, matched: true},
+ {name: "missing", body: `{"output":{}}`},
{name: "duplicate", body: `{"results":[{"index":0,"relevance_score":0.9},{"index":0,"relevance_score":0.8}]}`},
}
@@ -45,7 +47,12 @@ func TestTestRerankModelValidatesResults(t *testing.T) {
}))
defer server.Close()
- matched, err := TestRerankModel("key", server.URL, "model", 5)
+ matched, err := TestRerankModel(RerankOptions{
+ APIKey: "key",
+ Endpoint: server.URL,
+ Model: "model",
+ Timeout: 5,
+ })
if matched != test.matched {
t.Fatalf("matched = %v, want %v", matched, test.matched)
}
@@ -59,8 +66,71 @@ func TestTestRerankModelValidatesResults(t *testing.T) {
}
}
+func TestRerankRequestFormats(t *testing.T) {
+ tests := []struct {
+ name string
+ requestFormat RerankRequestFormat
+ topN int
+ expected string
+ }{
+ {
+ name: "default cohere",
+ topN: 1,
+ expected: `{"model":"model","query":"query","documents":["document"],"top_n":1}`,
+ },
+ {
+ name: "cohere without top n",
+ requestFormat: RerankRequestFormatCohere,
+ expected: `{"model":"model","query":"query","documents":["document"]}`,
+ },
+ {
+ name: "dashscope",
+ requestFormat: RerankRequestFormatDashScope,
+ topN: 1,
+ expected: `{"model":"model","input":{"query":"query","documents":["document"]},"parameters":{"top_n":1}}`,
+ },
+ {
+ name: "dashscope without top n",
+ requestFormat: RerankRequestFormatDashScope,
+ expected: `{"model":"model","input":{"query":"query","documents":["document"]}}`,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if nil != err {
+ t.Fatalf("read request failed: %v", err)
+ }
+ if string(body) != test.expected {
+ t.Fatalf("request body = %s, want %s", body, test.expected)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"results":[{"index":0,"relevance_score":1}]}`))
+ }))
+ defer server.Close()
+
+ indices, _, err := Rerank("query", []string{"document"}, RerankOptions{
+ APIKey: "key",
+ Endpoint: server.URL,
+ Model: "model",
+ RequestFormat: test.requestFormat,
+ TopN: test.topN,
+ Timeout: 5,
+ })
+ if nil != err {
+ t.Fatalf("Rerank failed: %v", err)
+ }
+ if len(indices) != 1 || 0 != indices[0] {
+ t.Fatalf("unexpected indices: %v", indices)
+ }
+ })
+ }
+}
+
func TestRerankTruncatesDocumentsByRunes(t *testing.T) {
- var received rerankRequest
+ var received rerankCohereRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(&received); nil != err {
t.Fatalf("decode request failed: %v", err)
@@ -71,7 +141,13 @@ func TestRerankTruncatesDocumentsByRunes(t *testing.T) {
defer server.Close()
document := strings.Repeat("中", rerankDocTextMaxRunes+1)
- indices, _, err := Rerank("query", []string{document}, "key", server.URL, "model", 1, 5)
+ indices, _, err := Rerank("query", []string{document}, RerankOptions{
+ APIKey: "key",
+ Endpoint: server.URL,
+ Model: "model",
+ TopN: 1,
+ Timeout: 5,
+ })
if nil != err {
t.Fatalf("Rerank failed: %v", err)
}