An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve reasoning content compatibility for OpenAI-compatible providers https://github.com/siyuan-note/siyuan/issues/19550
fengwind200645141dfeb75b
diff --git a/kernel/util/openai.go b/kernel/util/openai.goindex 823c9002ad..f4819308f2 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -217,13 +217,10 @@ func (t *extraBodyTransport) Do(req *http.Request) (*http.Response, error) {}// NewOpenAIClientWithModel 创建 OpenAI client,并按模型与端点启用兼容适配。-// 绝大多数模型走 NewOpenAIClient 路径;命中清单的模型会注入额外参数,官方 Gemini 端点会保留工具调用签名。+// 模型请求统一启用思考字段适配,命中清单的模型会注入额外参数,官方 Gemini 端点会保留工具调用签名。func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string, headers ...map[string]string) *openai.Client {extra := ExtraBodyForModel(model)geminiThoughtSignatures := isGoogleGeminiOpenAICompatibleEndpoint(apiBaseURL, model)- if len(extra) == 0 && !geminiThoughtSignatures {- return NewOpenAIClient(apiKey, apiBaseURL, headers...)- }config := openai.DefaultConfig(apiKey)config.BaseURL = apiBaseURLvar transport openai.HTTPDoer = newAIProviderHTTPClient(apiBaseURL, headers...)@@ -233,6 +230,7 @@ func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string, headers ...map[sif geminiThoughtSignatures {transport = WrapGeminiThoughtSignatureTransport(transport)}+ transport = &reasoningResponseTransport{base: transport}config.HTTPClient = transportreturn openai.NewClientWithConfig(config)}diff --git a/kernel/util/openai_reasoning.go b/kernel/util/openai_reasoning.gonew file mode 100644index 0000000000..2362bb3b69--- /dev/null+++ b/kernel/util/openai_reasoning.go@@ -0,0 +1,178 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "bufio"+ "bytes"+ "encoding/json"+ "io"+ "net/http"+ "strings"++ "github.com/sashabaranov/go-openai"+)++// reasoningResponseTransport 将不同 OpenAI 兼容服务商的思考字段统一为 SDK 支持的字段。+// 该适配器按 SSE 行处理响应,不会等待整个流结束后才把内容交给上层。+type reasoningResponseTransport struct {+ base openai.HTTPDoer+}++func (t *reasoningResponseTransport) Do(req *http.Request) (*http.Response, error) {+ resp, err := t.base.Do(req)+ if err != nil || resp == nil || resp.Body == nil || req.Method != http.MethodPost ||+ !strings.Contains(req.URL.Path, "chat/completions") {+ return resp, err+ }+ if strings.Contains(strings.ToLower(req.Header.Get("Accept")), "text/event-stream") ||+ strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {+ resp.Body = newReasoningResponseBody(resp.Body, true)+ } else {+ resp.Body = newReasoningResponseBody(resp.Body, false)+ }+ resp.ContentLength = -1+ resp.Header.Del("Content-Length")+ return resp, nil+}++type reasoningResponseBody struct {+ source io.ReadCloser+ reader *bufio.Reader+ sse bool+ output []byte+ terminalErr error+ done bool+}++func newReasoningResponseBody(source io.ReadCloser, sse bool) *reasoningResponseBody {+ return &reasoningResponseBody{source: source, reader: bufio.NewReader(source), sse: sse}+}++func (r *reasoningResponseBody) Read(p []byte) (int, error) {+ for len(r.output) == 0 && !r.done {+ var data []byte+ var err error+ if r.sse {+ data, err = r.reader.ReadBytes('\n')+ } else {+ data, err = io.ReadAll(r.reader)+ r.done = true+ }+ if len(data) > 0 {+ if r.sse {+ r.output = normalizeReasoningResponseLine(data)+ } else if normalized, changed := normalizeReasoningJSON(data); changed {+ r.output = normalized+ } else {+ r.output = data+ }+ }+ if err != nil {+ r.terminalErr = err+ r.done = true+ }+ }+ if len(r.output) > 0 {+ n := copy(p, r.output)+ r.output = r.output[n:]+ return n, nil+ }+ if r.terminalErr != nil {+ return 0, r.terminalErr+ }+ return 0, io.EOF+}++func (r *reasoningResponseBody) Close() error {+ return r.source.Close()+}++func normalizeReasoningResponseLine(line []byte) []byte {+ trimmed := bytes.TrimLeft(line, " \t")+ if !bytes.HasPrefix(trimmed, []byte("data:")) {+ return line+ }+ dataStart := len(line) - len(trimmed) + len("data:")+ data := line[dataStart:]+ var lineEnding []byte+ if bytes.HasSuffix(data, []byte("\n")) {+ data = data[:len(data)-1]+ lineEnding = []byte("\n")+ }+ if bytes.HasSuffix(data, []byte("\r")) {+ data = data[:len(data)-1]+ lineEnding = []byte("\r\n")+ }+ data = bytes.TrimSpace(data)+ if len(data) == 0 || bytes.Equal(data, []byte("[DONE]")) {+ return line+ }+ normalized, changed := normalizeReasoningJSON(data)+ if !changed {+ return line+ }+ result := append([]byte{}, line[:dataStart-len("data:")]...)+ result = append(result, []byte("data: ")...)+ result = append(result, normalized...)+ return append(result, lineEnding...)+}++func normalizeReasoningJSON(data []byte) ([]byte, bool) {+ var payload map[string]any+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.UseNumber()+ if err := decoder.Decode(&payload); err != nil {+ return nil, false+ }+ if err := decoder.Decode(&struct{}{}); err != io.EOF {+ return nil, false+ }+ changed := false+ choices, _ := payload["choices"].([]any)+ for _, rawChoice := range choices {+ choice, _ := rawChoice.(map[string]any)+ if choice == nil {+ continue+ }+ for _, field := range []string{"delta", "message"} {+ value, _ := choice[field].(map[string]any)+ if value != nil && normalizeReasoningFields(value) {+ changed = true+ }+ }+ }+ if !changed {+ return data, false+ }+ normalized, err := json.Marshal(payload)+ if err != nil {+ return data, false+ }+ return normalized, true+}++func normalizeReasoningFields(message map[string]any) bool {+ if reasoningContent, ok := message["reasoning_content"]; ok && reasoningContent != nil {+ return false+ }+ if text, ok := message["reasoning"].(string); ok && text != "" {+ message["reasoning_content"] = text+ return true+ }+ return false+}diff --git a/kernel/util/openai_reasoning_test.go b/kernel/util/openai_reasoning_test.gonew file mode 100644index 0000000000..22e52fe319--- /dev/null+++ b/kernel/util/openai_reasoning_test.go@@ -0,0 +1,201 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "bytes"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/sashabaranov/go-openai"+)++func TestOpenAIReasoningResponseNormalizesAliases(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = fmt.Fprint(w, `{"choices":[{"message":{"role":"assistant","content":"answer","reasoning":"thought"}}]}`)+ }))+ defer server.Close()++ client := newReasoningTestClient(server)+ response, err := client.CreateChatCompletion(t.Context(), openai.ChatCompletionRequest{Model: "test-model"})+ if err != nil {+ t.Fatal(err)+ }+ if len(response.Choices) != 1 || response.Choices[0].Message.ReasoningContent != "thought" {+ t.Fatalf("reasoning alias was not normalized: %#v", response)+ }+}++func TestOpenAIReasoningStreamNormalizesAlias(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "text/event-stream")+ _, _ = fmt.Fprint(w,+ "data: {\"choices\":[{\"delta\":{\"reasoning\":\"thought\"}}]}\n\n"++ "data: {\"choices\":[{\"delta\":{\"content\":\"answer\"}}]}\n\n"++ "data: [DONE]\n\n")+ }))+ defer server.Close()++ client := newReasoningTestClient(server)+ stream, err := client.CreateChatCompletionStream(t.Context(), openai.ChatCompletionRequest{Model: "test-model"})+ if err != nil {+ t.Fatal(err)+ }+ defer stream.Close()++ var reasoning, content string+ for {+ response, receiveErr := stream.Recv()+ if receiveErr != nil {+ if receiveErr == io.EOF {+ break+ }+ t.Fatal(receiveErr)+ }+ for _, choice := range response.Choices {+ reasoning += choice.Delta.ReasoningContent+ content += choice.Delta.Content+ }+ }+ if reasoning != "thought" || content != "answer" {+ t.Fatalf("normalized stream = reasoning %q, content %q", reasoning, content)+ }+}++func TestNormalizeReasoningFieldsPreservesCanonicalValueAndDetails(t *testing.T) {+ data := []byte(`{"choices":[{"message":{"reasoning":"alias","reasoning_content":"canonical","reasoning_details":[{"type":"summary"}]}}]}`)+ normalized, changed := normalizeReasoningJSON(data)+ if changed {+ t.Fatal("canonical reasoning_content should not be rewritten")+ }+ if !bytes.Equal(normalized, data) {+ t.Fatalf("normalization changed the response: %s", normalized)+ }++ data = []byte(`{"choices":[{"message":{"reasoning":"alias","reasoning_content":""}}]}`)+ normalized, changed = normalizeReasoningJSON(data)+ if changed || !bytes.Equal(normalized, data) {+ t.Fatalf("empty canonical reasoning_content was overwritten: %s", normalized)+ }++ data = []byte(`{"created":9007199254740993,"choices":[{"message":{"reasoning":"alias","reasoning_details":[{"type":"summary"}]}}]}`)+ normalized, changed = normalizeReasoningJSON(data)+ if !changed || !strings.Contains(string(normalized), `"reasoning_details":[{"type":"summary"}]`) ||+ !strings.Contains(string(normalized), `"reasoning_content":"alias"`) ||+ !strings.Contains(string(normalized), `"created":9007199254740993`) {+ t.Fatalf("reasoning alias was not normalized without losing details: %s", normalized)+ }+}++func TestNormalizeReasoningJSONRejectsTrailingData(t *testing.T) {+ data := []byte(`{"choices":[{"message":{"reasoning":"alias"}}]} trailing`)+ normalized, changed := normalizeReasoningJSON(data)+ if changed || normalized != nil {+ t.Fatalf("invalid response was normalized: %s", normalized)+ }+}++func TestReasoningSSEBodyHandlesReadBoundaries(t *testing.T) {+ source := &chunkedReadCloser{data: []byte(+ "data: {\"choices\":[{\"delta\":{\"reasoning\":\"thought\"}}]}\r\n\r\n" ++ "data: [DONE]\r\n\r\n"), chunkSize: 1}+ body := newReasoningResponseBody(source, true)+ data, err := io.ReadAll(body)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(data), `"reasoning_content":"thought"`) {+ t.Fatalf("SSE normalization failed across reads: %s", data)+ }+}++func TestReasoningSSEBodyNormalizesFinalLineWithoutNewline(t *testing.T) {+ body := newReasoningResponseBody(io.NopCloser(strings.NewReader(+ `data: {"choices":[{"delta":{"reasoning":"thought"}}]}`)), true)+ data, err := io.ReadAll(body)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(data), `"reasoning_content":"thought"`) || strings.HasSuffix(string(data), "\n") {+ t.Fatalf("final SSE line was not preserved and normalized: %q", data)+ }+}++func TestReasoningResponseTransportPassesNonChatRequestsThrough(t *testing.T) {+ const body = `{"reasoning":"keep"}`+ transport := &reasoningResponseTransport{base: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: make(http.Header),+ Body: io.NopCloser(strings.NewReader(body)),+ Request: req,+ }, nil+ })}+ req, err := http.NewRequest(http.MethodPost, "https://example.com/v1/embeddings", nil)+ if err != nil {+ t.Fatal(err)+ }+ response, err := transport.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer response.Body.Close()+ data, err := io.ReadAll(response.Body)+ if err != nil {+ t.Fatal(err)+ }+ if string(data) != body {+ t.Fatalf("non-chat response was changed: %s", data)+ }+}++type chunkedReadCloser struct {+ data []byte+ chunkSize int+}++func (r *chunkedReadCloser) Read(p []byte) (int, error) {+ if len(r.data) == 0 {+ return 0, io.EOF+ }+ n := min(len(p), r.chunkSize, len(r.data))+ copy(p, r.data[:n])+ r.data = r.data[n:]+ return n, nil+}++func (r *chunkedReadCloser) Close() error {+ return nil+}++type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) Do(req *http.Request) (*http.Response, error) {+ return f(req)+}++func newReasoningTestClient(server *httptest.Server) *openai.Client {+ config := openai.DefaultConfig("test")+ config.BaseURL = server.URL + "/v1"+ config.HTTPClient = &reasoningResponseTransport{base: server.Client()}+ return openai.NewClientWithConfig(config)+}